Ignoring Exception in_onmessage - python

I am new to making Discord Bots using Discord API and python, and apparently my code is acting a bit strange since i added Databases, i have used replit for the coding.
My code is:
import discord
import os
import requests
import json
client = discord.Client()
def get_quote():
response = requests.get("http://zenquotes.io/api/random")
json_data = json.loads(response.text)
quote = json_data[0]['q'] + " -" + json_data[0]['a']
return quote
#client.event
async def on_ready():
print('{0.user}'.format(client) + ' has successfully logged in.')
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('.ltt help'):
await message.channel.send('hello')
if input.content.startswith('.ltt inspire'):
quote = get_quote()
await message.channel.send(quote)
client.run(os.getenv('TOKEN'))
And when i try to execute it, it gives me the following error after sucessfully executing:
The error causes the bot to be unresponsive, even after mutliple triez of executing .ltt inspire and .ltt help, it seems their is a bug, or error. Even after rechecking the code the error persists.
Note: The following code is from a tutorial, if you want to refer to that here is the link: https://www.youtube.com/watch?v=SPTfmiYiuok
Note: I had not merged .ltt inspire and .ltt help before. When I did .ltt inspire was the only code that worked. .ltt help is not responding.

if message.content.startswith('.ltt inspire'):
quote = get_quote()
await message.channel.send(quote)
just make sure whenever you start a new line in on_message() you always stat that it is a message and not an input

Related

Discord Python bot commands not responding

basically i have no idea why this code is not working, ive tried using on_message and that works so long as i dont include and if statement to filter for the messages with the prefix at the start. so i scrapped that, this code worked a few months ago with a different bot i made and ive ended up scrapping all the other stuff i was doing and bringing it down to the bare basics because i cant figure out why the bot doesnt recognise messages starting with the prefix.
import discord
import os
from discord.ext import commands
bot = commands.Bot(command_prefix='!')
TOKEN = "Token_here"
#bot.command(name='tst')
async def test(ctx):
await ctx.send('testt')
#bot.event
async def on_ready():
print ('Successful login as {0.user}'.format(bot))
bot.run(TOKEN)
ive tried print('Test') debugging aswell see below
#bot.command(name='tst')
async def test(ctx):
print('Test")
then in discord typing the !test command still does nothing and the terminal also remains empty other than the on_ready result of
Successful login as botname#0001
i have no idea whats going on honestly
There are a couple of things that could be causing your problems. I fixed the issue by enabling intents for the bot. This also must be done on the developer portal. https://discord.com/developers/applications
intents = discord.Intents().all()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
you also don't need the name parameter in the command decorator. It can just be written as :
#bot.command()
async def test(ctx):
await ctx.send('testt')
Try these changes:
bot= commands.Bot(command_prefix='!!', intents=discord.Intents.all())
#bot.command()
async def test():
await ctx.channel.send("Test successful")

Python Discord Bot problems

this is a long one.
so basically im trying to code a Python bot based on Harry Potter, and on my pc im using repl.it
and on my laptop im using PyCharm CE.
my laptop doesnt detect any type of discord (as in import discord) and my pc comes up with the error "AttributeError: 'NoneType' object has no attribute 'strip'". plus repl.it wont allow me to create a .env file and i cant figure out how to use Secrets (Environment Variables). my laptop also will not let me reinstall/uninstall discord and comes up with a LOT of errors (OSErro when i try to force reinstall, permission denied etc. i dont know how to change permissions)
The following is the troublesome code. Note they are the exact same on both platforms
import os
client = discord.Client()
#client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('$hello'):
await message.channel.send('Hello!')
client.run(os.getenv('TOKEN'))'''
Short answer:
In the last line, simply change client.run(os.getenv('TOKEN')) to client.run('<bot-token>') where '<bot-token>' is supposed to be your actual bot token in string format. (In case you aren't sure where to find the bot token of your bot, this link may help)
Long answer:
The client.run() function needs your bot token as the argument in string format. From the error message that you mentioned, it seems that os.getenv('TOKEN') is returning None value, and it seems internally it is trying to strip the given token and failing to strip it because None value doesn't have strip attribute unlike string values. Have you stored your bot token in the key 'TOKEN' of os.environ in string format? Unless you are doing that, I don't think you should use os.getenv('TOKEN') at all. Just enter the bot token as a string, directly as the argument in client.run(). (In case you aren't sure where to find the bot token of your bot, this link may help)
Btw, I am assuming that the ''' in the end is a typo and if not then please remove it!
So, the new code would look like:
import os
import discord
client = discord.Client()
#client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('$hello'):
await message.channel.send('Hello!')
client.run('<your bot token>')

Discord bot isn't responding to commands

I've been using the
import os
import discord
from discord.ext import commands
client = commands.Bot(command_prefix = "!")
#client.event
async def on_ready():
await client.change_presence(status=discord.Status.idle,
activity=discord.Game(''))
print('Successfully logged in as {0.user}'.format(client))
#client.command()
async def hello(ctx):
await ctx.send("Hello! It's great to see you!")
client.run(os.getenv('TOKEN'))
code for commands. I expected to have it respond "Hello! It's great to see you!" when I said !hello (! = prefix). But it returned nothing. Not even an error. Does anyone know why? Also, please don't show discord bot not responding to commands or Discord command bot doesn't responde (python) because I tried both, and neither worked.
I cant chat here because of lack of reputation so I answer it here instead. you should post the full code to make the job easier.
.
Cause 1:
You didn't add a prefix. You need a prefix to use the command
look onto your client. Did you tell the prefix already? like:
client = commands.Bot(command_prefix = "-")
if so, add this and it should work!
.
Cause 2:
You didn't import from discord.ext import commands
this is important if you want to use commands, import that and it should work!
.
Cause 3:
You mixing up client and bot
this might not happen but here it goes, You might mix up client or bot on the decorator, which is #client.command
if you use client (like client = commands.Bot(command_prefix = "-")), use #client.command on the decorator, while if you use Bot (bot = commmands.Bot(command_prefix = "-")) then you should use #bot.command on the decorator.
Hope these will help :D

How to solve a "429: Too Many Requests" when running discord.py bot on repl.it?

My code (see below) was running fine, but then this error popped up and doesn't go away:
"http.py", line 293, in static_login
data = await self.request(Route('GET', '/users/#me')
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/http.py", line 209, in request
raise HTTPException(r, data)
discord.errors.HTTPException: 429 Too Many Requests (error code: 0): "
I searched up the error, and I saw that people got it from running powerful programs on multiple servers, or people running the same code tons of times on a single one. But, I only run it on one server and it's very simple code.
Here's the code for reference (it's running in repl.it) (the os.getenv is to hide the bot's token):
import discord
import os
client = discord.Client()
#client.event
async def on_ready():
print ('We have logged in as {0.user}'.format(client))
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('$hello'):
await message.channel.send('Hello!')
client.run(os.getenv('TOKEN'))
Other than avoiding the error, there's a way to get around it. If discord.errors.HTTPException: 429 appears in the console on replit, just use the command kill 1 in the shell. This command completely exits the script, and when you click run again it will run from a different IP Address, bypassing the Discord rate limit.
If the error happens regularly, this can be a hassle. An automatic solution is to have another file called 'restarter.py' with this code:
from time import sleep
from os import system
sleep(7)
system("python main.py")
Then in your main script:
import discord
import os
client = discord.Client()
#client.event
async def on_ready():
print ('We have logged in as {0.user}'.format(client))
#client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('$hello'):
await message.channel.send('Hello!')
try:
client.run(os.getenv('TOKEN'))
except discord.errors.HTTPException:
print("\n\n\nBLOCKED BY RATE LIMITS\nRESTARTING NOW\n\n\n")
system("python restarter.py")
system('kill 1')
Cohen's solution worked pretty decently for me. However, sometimes the bot got stuck in a loop of trying to start the bot over and over again and constantly crashing. This got solved only after the Cloudflare ban expired (1 hour). I really could not figure out why or what happens, but I found a solution.
I have a main.py file, that imports my bot.py file, where all my bot code is located. The runbot function is just bot.run(token).
import bot.bot as bot
from bot.keep_alive import keep_alive
import os
import discord
while __name__ == '__main__':
try:
keep_alive()
bot.runbot(os.environ['token'])
except discord.errors.HTTPException as e:
print(e)
print("\n\n\nBLOCKED BY RATE LIMITS\nRESTARTING NOW\n\n\n")
os.system('kill 1')
Instead of using the restarter.py file, I'm just using a while loop. This makes sure that everything is executed in the correct order.
I hope this helps.
This worked perfect. If it keeps spamming that you're being rate limited then just run kill 1 again and it should be fine

Why is my discord bot spamming?

I have previously posted on this same bot and got it working thanks to the people who responded. But, while it finally came to life and turned on, it started spamming messages for no apparent reason. I've looked over the code for typos and can't find any.
Here's the code:
import discord
from discord.ext.commands import bot
from discord.ext import commands
import asyncio
import time
Client = discord.Client()
client = commands.Bot (command_prefix = discord)
#client.event
async def on_ready() :
print("Bepis machine fixed")
#client.event
async def on_message(message) :
if message.content == "bepis" :
await client.send_message (message.channel, "bepis")
client.run("Censored Bot Token")
after #client.event is where i need help. also the bottom line if fine this time! turns out i had hit the space bar before the parenthesis and it didn't like that. Help is very appreciated so i can continue adding on to this awesome bot.
It looks like you are sending a message "bepis" in response to the first, then every, message "bepis" - presumably your first response will appear as an entry on the incoming feed which will trigger a second, etc.
Turns out I was not using proper formatting for my bot.
Whenever you say "bepis" in the discord server, the bot will see it and then say "bepis" back, as its intended to do, but, because of my improper formatting, the bot saw itself say "bepis" and responded as if someone else was saying "bepis".
Old lines:
if message.content == "bepis" :
await client.send_message(message.channel, "bepis")
New lines:
if message.content.startswith('bepis'):
await client.send_message(message.channel, "bepis")
So make sure you're using the right format if you're making a bot!
You seemed to already know what the problem is, from this answer you posted. But your solution is far from being able to solve the problem.
on_message is called whenever a new message is sent to anywhere accessible by the bot; therefore, when you type in "bepis" in discord, the bot replies with "bepis", then the message sent by the bot goes into on_message, which the bot re-replies "bepis", and so on...
The simple solution is to check if the message's author is any bot account, or if you want, if the message's author is your bot.
from discord.ext import commands
client = commands.Bot(command_prefix=None)
#client.event
async def on_ready():
print("Bepis machine fixed")
#client.event
async def on_message(message):
# or `if message.author.bot:` # which checks for any bot account
if message.author == client.user:
return
if message.content == "bepis":
await client.send_message(message.channel, "bepis")
client.run("Token")
Note: I also fixed many of your other problems, such as multiple unused imports, another Client, and indentation.
And FYI, command_prefix is only used when command is being processed by a functional command. When you use on_message it has no use, which means you can set it to None.

Categories