Darcy Power
Darcy Power

Reputation: 313

Handling discord.py specific errors in on_command_error() event

My discord bot uses the same command prefix as another bot in the server, this causes the console to spam a CommandNotFound error every time someone uses the other bot. I saw another question where someone answered that you can handle the error like this:

@client.event
async def on_command_error(ctx, error):
    #print(error) -- returns error description
    if (error == CommandNotFound):
        return
    raise error

But this solution just throws a NameError saying that CommandNotFound was not found. I also tried this after seeing that the console output said discord.ext.commands.errors.CommandNotFound instead of CommandNotFound like other python specific errors.

@client.event
async def on_command_error(ctx, error):
    if (error == (discord.ext.commands.errors.CommandNotFound)):
         return
    raise error

How could I accomplish this?

Upvotes: 1

Views: 2077

Answers (1)

ZeroKnight
ZeroKnight

Reputation: 528

If you're getting a NameError, it means that what you're referencing doesn't exist (i.e. isn't defined) in the scope where you refer to it. You need to import CommandNotFound:

from discord.ext.commands import CommandNotFound

Then check for it:

@client.event
async def on_command_error(ctx, error):
    # Or, if you've already imported `commands`, you could write
    # commands.CommandNotFound here instead of explicitly importing it.
    if isinstance(error, CommandNotFound):  # Using `==` is incorrect
        return
    raise error

Upvotes: 4

Related Questions