Skip to content

Instantly share code, notes, and snippets.

@AileenLumina
Last active May 2, 2022 17:40
Show Gist options
  • Save AileenLumina/510438b241c16a2960e9b0b014d9ed06 to your computer and use it in GitHub Desktop.
Save AileenLumina/510438b241c16a2960e9b0b014d9ed06 to your computer and use it in GitHub Desktop.
discord.py command error handler
async def on_command_error(self, ctx, error):
# if command has local error handler, return
if hasattr(ctx.command, 'on_error'):
return
# get the original exception
error = getattr(error, 'original', error)
if isinstance(error, commands.CommandNotFound):
return
if isinstance(error, commands.BotMissingPermissions):
missing = [perm.replace('_', ' ').replace('guild', 'server').title() for perm in error.missing_perms]
if len(missing) > 2:
fmt = '{}, and {}'.format("**, **".join(missing[:-1]), missing[-1])
else:
fmt = ' and '.join(missing)
_message = 'I need the **{}** permission(s) to run this command.'.format(fmt)
await ctx.send(_message)
return
if isinstance(error, commands.DisabledCommand):
await ctx.send('This command has been disabled.')
return
if isinstance(error, commands.CommandOnCooldown):
await ctx.send("This command is on cooldown, please retry in {}s.".format(math.ceil(error.retry_after)))
return
if isinstance(error, commands.MissingPermissions):
missing = [perm.replace('_', ' ').replace('guild', 'server').title() for perm in error.missing_perms]
if len(missing) > 2:
fmt = '{}, and {}'.format("**, **".join(missing[:-1]), missing[-1])
else:
fmt = ' and '.join(missing)
_message = 'You need the **{}** permission(s) to use this command.'.format(fmt)
await ctx.send(_message)
return
if isinstance(error, commands.UserInputError):
await ctx.send("Invalid input.")
await self.send_command_help(ctx)
return
if isinstance(error, commands.NoPrivateMessage):
try:
await ctx.author.send('This command cannot be used in direct messages.')
except discord.Forbidden:
pass
return
if isinstance(error, commands.CheckFailure):
await ctx.send("You do not have permission to use this command.")
return
# ignore all other exception types, but print them to stderr
print('Ignoring exception in command {}:'.format(ctx.command), file=sys.stderr)
traceback.print_exception(type(error), error, error.__traceback__, file=sys.stderr)
@RGBCube
Copy link

RGBCube commented Dec 11, 2021

ffs use codeblocks @barryii

@erew70
Copy link

erew70 commented Mar 30, 2022

it doesn't work

@Hunter87ff
Copy link

Hunter87ff commented Apr 27, 2022

How do i detect the error of the @commands.has_role() check?

@bot.event
async def on_command_error(ctx, error):
    elif isinstance(error, (commands.MissingRole, commands.MissingAnyRole)):
      await ctx.send("You dont have the exact role to use this command")

More Detail

@iSimpp
Copy link

iSimpp commented May 2, 2022

Thanks!

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