Command not found error in Discord Python code - python

Whenever I run my discord python code, and test it in the discord chat, it says the ping command is not found even though I defined it in the code.
I've tried to use both Bot and Client and both gave the same error.
import discord
from discord.ext import commands
bot_prefix= "]"
bot = commands.Bot(command_prefix=bot_prefix)
bot.run("*")
#bot.event
async def on_ready():
print("ok")
#bot.event
async def on_message(message):
print(message.content)
#bot.command()
async def ping(ctx):
latency = bot.latency
await ctx.send(latency)
Personal information replaced with "*"
The bot should send a message in the user's channel saying the latency of the bot, but instead I just get an error that says:
"Ignoring exception in command None:
discord.ext.commands.errors.CommandNotFound: Command "ping" is not found" even though I defined the ping command in the code.
Also, it should be noted that the on_ready event never runs; I never get the print statement in the console log.
Any help is appreciated thanks :)

bot.run must be the last line in your code. Python executes sequentially, so all of the stuff below bot.run isn't called until after the bot is finished running.

Okay I got it fixed!!
Apparently there's an issue with the on_message function, I guess I just skipped over it in the FAQ. Anyone confused about this, just add the line:
await bot.process_commands(message)
into your on_message function. When you define your own on_message function it overrides the original one that passes the message into the commands handler.
Also make sure to use bot.run() at the end of your code, after your function declarations. Simple mistakes, but they're all fixed now :)

Related

Can an event execute a command? If so, how can I make my one do so?

So I am trying to have an event where, once the user types a specific word (not a command, literally a word/string), the event will trigger an existing command. Yeah you may wonder "Why not have the user type the command itself?" well, the reason why this isn't the case it's kinda hard to explain. Check this out:
My event will work only if the person types "nothing" (literally the word nothing). Eventually, the person won't expect the bot to actually take this as a command, and so he/she won't type it as command (with the prefix and all that) This is my code:
#client.command()
async def menu(ctx)
#here, well, goes what I want the command to do but it's not the issue
#client.event
async def on_message(message):
if message.content.startswith("nothing"):
#here idk how to execute the command up there. That's my question
I hope I am being clear with my issue. Don't worry about what the command exectues, or why the message for the event is "nothing". I just really want to know how to make this work.
Some friends suggested me to invoke the command, but I didn't really know how to do that, and everytime I would try it wouldn't work. Others suggested to call the function, but I also tried that and it wouldn't work. I don't know if I typed it correctly or if it simply won't work. I hope someone helps me out here.
Thanks in advance.
get_context, this takes a message object. Then invoke. Keep in mind, there are 3 downsides to using this method.
The converters (the type hints) won't be triggered. You need to pass the correct types into the arguments.
Checks will be bypassed. You could invoke an owner only command with a non-owner and it would still work.
If you still want to run all the checks, see can_run, which will run all the checks and raise an error if any checks fail.
If ctx.invoke was invoked outside of a command (eg eval), the error handler won't fire.
#client.command()
async def menu(ctx):
await ctx.send("Hello")
#client.event
async def on_message(message):
if message.content.startswith("nothing"):
ctx = await client.get_context(message)
await ctx.invoke(menu)
await client.process_commands(message)
If your client is a Bot instance you can use Bot.get_context() to create your own context and invoke the command from there:
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix='!')
#bot.command()
async def menu(ctx):
await ctx.send('bar')
#bot.event
async def on_message(message):
if message.content.startswith('foo'):
ctx = await bot.get_context(message, cls=commands.Context)
ctx.command = bot.get_command('menu')
await bot.invoke(ctx)
await bot.process_commands(message)

Discord Python bot that deletes messages in a certain channel which are not commands

So I have a #support channel in which the members of my discord can type =support and the bot will message them to assist them, after that the bot will delete the =support command that the user typed in the channel to keep the channel clean, however in this channel they can also type any message that is not a command and the bot will not delete this, is there a way for the bot to delete a message if it isn't a command?
This can be done using on_message
#bot.event
async def on_message(m):
if m.channel.id == ChannelIDOfSupport Channel:
if m.content.replace(bot.prefix, "") not in [i.name for i in bot.commands]:
await m.delete()
So basically what I did is replace the actual command for a message listener and if it starts with support to do the command, then I restored the commands function. It looks like this:
async def on_message(m):
if m.channel.id == 735866701069025301:
if m.content.startswith('=ticket'):
await m.author.send('Your ticket will be created according to what you choose, use the = before choosing a number and then put the number next to it (Example: =2) \n \n **1. General Support** \n \n **2. Staff Application**')
await m.channel.purge()
else: {
await m.delete()
}
await client.process_commands(m)
The code below was somewhat functional however, all my #client.command or #bot.command if you want, were not functioning properly, not your fault #Poojan, I didn't paste code so you couldn't know if I was using commands instead of events.
The code above works perfectly, thank you for your help, thank you for your help too #Xetera, I followed the code and looked a bit into it and came to that conclusion :)
vvvvvvvvvvvv That answer helped me lots.

on_server_join doesn't respond. discord.py

I am trying to get an output when the bot is invited to a server, but for some reason when I try to test my code it doesn't output anything. It doesn't give any errors as well. First I tried to do it from a Cog file:
#commands.Cog.listener()
async def on_server_join(self,server):
print("hello")
print(server.id)
then in the main file:
#client.event
async def on_server_join(server):
print("hello world")
print(server.id)
both doesn't result in any errors and they doesn't output anything when I'm kicking the bot from a server and then adding him back.
Other events, like on_ready and on_member_join are working OK.
Creating a new server and adding the bot there also doesn't trigger the event.
on_server_join was changed to on_guild_join when discord.py migrated to v1.0

I made a command that automatically responds to a specific message. The command works but it makes all my other commands not work (discord.py rewrite)

This is the code that I use for command to respond when I say hello. This will work but if I try to use a command after none of them work, and if I take this out of my code then it works again. There are no error codes when I use a command. I'm really lost on how to fix this would anyone know why this is happening and if so how I could fix it?
#client.event
async def on_message(message):
channel = client.get_channel(CHANNEL)
hello = "hello"
if message.content.count(hello) > 0:
message = "Whats up!"
await channel.send(message)
When using an on_message event, you need to process_commands() to allow your commands to work:
#client.event
async def on_message(message):
# checking against lower case string will be more consistent with finding more "hello"s
if message.content.lower().count("hello") > 0:
await message.channel.send("What's up!")
await client.process_commands(message)
References:
Bot.process_commands() - "If you choose to override the on_message() event, then you should invoke this coroutine as well."

Discord.py - How can I have a command invoked in an event?

So I am trying to create an event in discord.py where, whenever a user mentions/pings the bot, it will say something. The code below runs without errors, however the only way this will work is if my command prefix is in the message.
For my bot, the prefix is "/", so whenever I mention the bot with a "/" in the message it will say something. And if I decide to just mention the bot, the bot does not respond. I am pretty sure it's got something to do with the last line of code but I don't know how to fix this issue.
#client.event
async def on_message(message):
if client.user.mention in message.content.split():
await message.channel.send('You mentioned me!')
else:
await client.process_commands(message)
The code is written in Python 3.7.4.
All help would be appreciated!
When someone mentions a user the bot reads <#userid>. So if you want to use an on_message function you would want to include an
if '<#bot/user id>' in message.content:
await message.channel.send('hi')
You can also do something like...
if bot.user in message.mentions:
await message.channel.send('hi')

Categories

Resources