Skip to content
Permalink
Browse files
Added a Command Error Handler to filter errors and easily manage
tracebacks
  • Loading branch information
stavilam committed Nov 28, 2018
1 parent 98ae4a1 commit f818b2dea3cec57c6121e92e0c4e080dd8fadd11
Showing 1 changed file with 48 additions and 0 deletions.
@@ -0,0 +1,48 @@
import traceback
import sys
from discord.ext import commands

""" http://discordpy.readthedocs.io/en/rewrite/ext/commands/api.html#errors for a list of exceptions"""


class CommandErrorHandler:
def __init__(self, client):
self.client = client

async def on_command_error(self, ctx, error):
"""Triggers when an error is raised while calling/invoking any command."""

# Tuple of ignored errors
ignored = (commands.CommandNotFound, commands.CommandOnCooldown, commands.UserInputError)

# Check for original exceptions raised and sent to CommandInvokeError.
# Otherwise, keep the exception passed to on_command_error.
error = getattr(error, 'original', error)

# If the error is ignored, return and nothing happens.
if isinstance(error, ignored):
return

# If a disabled command has been called by a user.
elif isinstance(error, commands.DisabledCommand):
return await ctx.send(f'{ctx.command} has been disabled.')

# If the command can only be used in server channels (and not Direct Messages)
elif isinstance(error, commands.NoPrivateMessage):
try:
return await ctx.author.send(f'{ctx.command} can not be used in Private Messages.')
except:
pass

# If user mentioned does not exist (for the >user command)
elif isinstance(error, commands.BadArgument):
if ctx.command.qualified_name == 'user':
return await ctx.send('I could not find that member. Please try again.')

# If the error hasn't been returned yet, print the traceback
print('Ignoring exception in command {}:'.format(ctx.command), file=sys.stderr)
traceback.print_exception(type(error), error, error.__traceback__, file=sys.stderr)


def setup(client):
client.add_cog(CommandErrorHandler(client))

0 comments on commit f818b2d

Please sign in to comment.