Permalink
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Browse files
Added a Command Error Handler to filter errors and easily manage
tracebacks
- Loading branch information
Showing
1 changed file
with
48 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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)) |