diff --git a/commandErrorHandlerFile.py b/commandErrorHandlerFile.py new file mode 100644 index 0000000..dbe656a --- /dev/null +++ b/commandErrorHandlerFile.py @@ -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))