Skip to content

Instantly share code, notes, and snippets.

@greendoescode
Created January 26, 2021 23:25
Show Gist options
  • Save greendoescode/a09d59e9c451f55757b6c5149e4b7b5b to your computer and use it in GitHub Desktop.
Save greendoescode/a09d59e9c451f55757b6c5149e4b7b5b to your computer and use it in GitHub Desktop.
Non-complex error handler for discord.py

Before Starting

Before I start please read through this fully, Thanks!

So, If you reading this, You have already setup up bot/client, So let's go!

Creating Decorator

First we need to create our bot event, we do this by using bot/client like

@bot.event

So we have added our decorator to our code!

Defining async def

Now we have to added this one line of code, basically every thing in discord.py uses, which is "async def" Seeing as we are looking for command errors we need to use "on_command_error"

@bot.event
async def on_command_error(ctx, error):

Defining isinstance

Now we need too look for if the error is the error we want to catch, we do this by using "if isinstance():"

@bot.event
async def on_command_error(ctx, error):
    if isinstance():

Defining What Error

We have now defined the above, now we are going to choose what error we are going to use from "commands" We do this by doing as shown below

@bot.event
async def on_command_error(ctx, error):
    if isinstance(error, commands.CommandNotFound):

We are trying to see if the command error is, Command not found, There is many more errors made into the discord library, maybe take a look!

Sending Stuff

Now we need to send something to alert the user of what has happened! We do that by doing "await ctx.send()" Today we are going to send a mention to the user, saying what has happened, you can say anything you want!

@bot.event
async def on_command_error(ctx, error):
    if isinstance(error, commands.CommandNotFound):
        await ctx.send(f"{ctx.author.mention}, That command is not found!")
        # Remember to use the f string!
        # You also mention by doing ctx.author.mention, looking at the docs does help!

Adding else

So your think it's done? Well if you had not thought, what if there's another error? It will be suppressed.

How we would deal with this is raising the error, this is pretty simple!

@bot.event
async def on_command_error(ctx, error):
    if isinstance(error, commands.CommandNotFound):
        await ctx.send(f"{ctx.author.mention}, That command is not found!")
        # Remember to use the f string!
        # You also mention by doing ctx.author.mention, looking at the docs does help!
    else:
        raise error

It's that simple! Hope you made sense out of this, happy coding!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment