def on_command_error(self, error, ctx):
ignored = (commands.NoPrivateMessage, commands.DisabledCommand, commands.CheckFailure,
commands.CommandNotFound, commands.UserInputError, discord.HTTPException)
error = getattr(error, 'original', error)
if isinstance(error, ignored):
return
if ctx.message.server:
fmt = 'Channel: {0} (ID: {0.id})\nGuild: {1} (ID: {1.id})'
else:
fmt = 'Channel: {0} (ID: {0.id})'
exc = traceback.format_exception(type(error), error, error.__traceback__, chain=False)
description = '```py\n%s\n```' % ''.join(exc)
time = datetime.datetime.utcnow()
name = ctx.command.qualified_name
author = '{0} (ID: {0.id})'.format(ctx.message.author)
location = fmt.format(ctx.message.channel, ctx.message.server)
message = '{0} at {1}: Called by: {2} in {3}. More info: {4}'.format(name, time, author, location, description)
self.bot.logs['discord'].critical(message)
python类CommandNotFound()的实例源码
def on_command_error(ctx, error):
if isinstance(error, commands.CommandNotFound):
return
# if isinstance(error, commands.CommandInvokeError):
# return print(error)
errors = {
commands.DisabledCommand: 'Command has been disabled.',
commands.MissingPermissions: 'Invoker is missing permissions to run this command.',
commands.BotMissingPermissions: 'Bot is missing permissions to run this command.',
commands.CheckFailure: 'You are not allowed to run this command.'
}
for type, text in errors.items():
if isinstance(error, type):
return await ctx.send(errors[type])
# argument error
if isinstance(error, commands.UserInputError):
bot.formatter.context = ctx
bot.formatter.command = ctx.command
return await ctx.send(f'Invalid argument(s) provided.\n```{bot.formatter.get_command_signature()}```')
await ctx.send(f'An error occured in `{ctx.command.name}` invoked by {ctx.message.author}:\n```{error}```')
#traceback.print_exception(type(exception), exception, exception.__traceback__, file=sys.stderr)
# blacklist check
# check is user is blacklister, or if it's a bot
def on_command_error(ctx, error):
console = bot.get_channel(358776134243975169)
errid = id_generator()
if isinstance(error, commands.CommandNotFound):
return
global totalErrors
totalErrors += 1
await ctx.send(":x: I ran into an error! Please report this on the support guild with the error ID, which is **{1}**. ```py\n{0}```".format(str(error)[29:], errid))
webhook.send(content="[`"+str(datetime.datetime.now(pytz.timezone('America/New_York')).strftime("%H:%M:%S"))+"`][`Godavaru`][:x:]\n"
+"[`CommandHandler`][`Error`]\n"
+"[`ErrorInformation`][`{}`]: {}\n".format(errid, str(error)[29:])
+"[`GuildInformation`]: {}\n".format(ctx.message.guild.name+" ("+str(ctx.message.guild.id)+") owned by "+str(ctx.message.guild.owner)+" ("+str(ctx.message.author.id)+")")
+"[`AuthorInformation`]: {} ({})\n".format(str(ctx.message.author), str(ctx.message.author.id))
+"[`MessageInformation`]: {} ({})\n".format(ctx.message.clean_content, str(ctx.message.id)))
print("["+str(datetime.datetime.now(pytz.timezone('America/New_York')).strftime("%H:%M:%S"))+"][Godavaru]\n"
+"[CommandHandler][Error]\n"
+"[ErrorInformation]: {}\n".format(str(error)[29:])
+"[GuildInformation]: {}\n".format(ctx.message.guild.name+" ("+str(ctx.message.guild.id)+") owned by "+str(ctx.message.guild.owner)+" ("+str(ctx.message.author.id)+")")
+"[AuthorInformation]: {} ({})\n".format(str(ctx.message.author), str(ctx.message.author.id))
+"[MessageInformation]: {} ({})\n".format(ctx.message.clean_content, str(ctx.message.id)))
# help command
def on_command_error(error, ctx):
if isinstance(error, commands.NoPrivateMessage):
await bot.send_typing(ctx.message.author)
await asyncio.sleep(1)
await bot.send_message(ctx.message.author, "Um... this command can't be used in private messages.")
elif isinstance(error, commands.DisabledCommand):
await bot.send_typing(ctx.message.author)
await asyncio.sleep(1)
await bot.send_message(ctx.message.author, "I'm Sorry. This command is disabled and it can't be used.")
elif isinstance(error, commands.CommandInvokeError):
print('In {0.command.qualified_name}:'.format(ctx), file=sys.stderr)
traceback.print_tb(error.original.__traceback__)
print('{0.__class__.__name__}: {0}'.format(error.original), file=sys.stderr)
elif isinstance(error, commands.CommandNotFound):
log.info("'{0.message.author}' in {0.message.server} used a command thats not in Inkxbot, the content is resent here: '{0.message.content}'".format(ctx))
elif isinstance(error, commands.MissingRequiredArgument):
log.info("'{0.message.author}' in {0.message.server} was missing some arguments in a command, message is resent here: '{0.message.content}'".format(ctx))
await bot.send_typing(ctx.message.channel)
await asyncio.sleep(1)
await bot.send_message(ctx.message.channel, "It seems you are missing required argument(s). Try again if you have all the arguments needed.")
def setup(bot):
"""Set up the cog."""
@bot.check
def is_human(ctx):
"""Prevent the bot from responding to other bots."""
if ctx.author.bot:
raise IsNotHuman("User is not human")
return True
@bot.listen("on_command_error")
async def handle_error(ctx, exc):
"""Simple error handler."""
if isinstance(exc, commands.MissingRequiredArgument):
param = exc.param.replace("_", " ")
await ctx.send(f"Please specify a {param} for this command to work.")
elif not isinstance(exc, (commands.CommandNotFound, IsNotHuman)):
await ctx.send(exc)
def on_command_error(ctx, error):
if isinstance(error, commands.NoPrivateMessage):
await ctx.send(content='This command cannot be used in private messages.')
elif isinstance(error, commands.DisabledCommand):
await ctx.send(content='This command is disabled and cannot be used.')
elif isinstance(error, commands.MissingRequiredArgument):
await bot.formatter.format_help_for(ctx, ctx.command, "You are missing required arguments.")
elif isinstance(error, commands.CommandNotFound):
# await ctx.send('Command not found. (I\'m working on fixing cmd_not_found forf help module')
await bot.formatter.format_help_for(ctx, [c for c in bot.commands if 'help' == c.name][0],
"Command not found.")
elif isinstance(error, commands.CommandInvokeError):
print('In {0.command.qualified_name}:'.format(ctx), file=sys.stderr)
print('{0.__class__.__name__}: {0}'.format(error.original), file=sys.stderr)
traceback.print_tb(error.__traceback__, file=sys.stderr)
log.error('In {0.command.qualified_name}:'.format(ctx))
log.error('{0.__class__.__name__}: {0}'.format(error.original))
else:
traceback.print_tb(error.__traceback__, file=sys.stderr)
def on_command_error(self, ctx, error):
"""Error handling"""
error_msg = None
if isinstance(error, commands.MissingRequiredArgument):
await ctx.send(error)
elif isinstance(error, commands.CommandNotFound):
pass
elif isinstance(error, commands.CommandInvokeError):
original = error.original
if isinstance(original, discord.Forbidden):
await ctx.send("I need to have the 'embed links' permission to send messages!")
return
elif isinstance(original, exceptions.Halt):
return
print('{0.created_at}: {0.author}: {0.content}'.format(ctx.message))
print(error)
embed = discord.Embed(title="An unexpected error occured :I", colour=0xCA0147,
description="If you feel like this shouldn't be happening [click here to join my support server](https://discord.gg/UP4TwFX).")
await ctx.send("", embed=embed)
else:
print('{0.created_at}: {0.author}: {0.content}'.format(ctx.message))
print(str(error))
def on_command_error(error, ctx):
channel = ctx.message.channel
if isinstance(error, commands.MissingRequiredArgument):
await bot.send_cmd_help(ctx)
elif isinstance(error, commands.BadArgument):
await bot.send_message(channel, "Truly, your wish is my command, but I cannot make head nor tail of the argument you provide.")
elif isinstance(error, commands.CommandNotFound):
# This is almost as ugly as Manta on Medusa
await bot.send_message(channel, "I fear I know not of this \"%s\". Is it perchance a new Hero?" % ctx.message.content[len(bot.settings["prefix"]):].partition(' ')[0])
elif isinstance(error, commands.CommandOnCooldown):
await bot.send_message(channel, random.choice(CDMESSAGES) + " (%ss remaining)" % int(error.retry_after))
elif isinstance(error, commands.NoPrivateMessage):
await bot.send_message(channel, "Truly, your wish is my command, but that order is not to be issued in secret. It must be invoked in a server.")
else:
try:
await bot.send_message(channel, "I fear some unprecedented disaster has occurred which I cannot myself resolve. Methinks you would do well to consult %s on this matter." % (await bot.get_owner()).mention)
except discord.NotFound:
await bot.send_message(channel, "I fear some unprecedented disaster has occurred which I cannot myself resolve.")
if isinstance(error, commands.CommandInvokeError):
print(repr(error.original))
else:
print(repr(error))
def on_command_error(self, ctx, error):
ignored = (commands.NoPrivateMessage, commands.DisabledCommand, commands.CheckFailure,
commands.CommandNotFound, commands.UserInputError, discord.Forbidden)
error = getattr(error, 'original', error)
if isinstance(error, ignored):
return
e = discord.Embed(title='Command Error', colour=0xcc3366)
e.add_field(name='Name', value=ctx.command.qualified_name)
e.add_field(name='Author', value=f'{ctx.author} (ID: {ctx.author.id})')
fmt = f'Channel: {ctx.channel} (ID: {ctx.channel.id})'
if ctx.guild:
fmt = f'{fmt}\nGuild: {ctx.guild} (ID: {ctx.guild.id})'
e.add_field(name='Location', value=fmt, inline=False)
exc = ''.join(traceback.format_exception(type(error), error, error.__traceback__, chain=False))
e.description = f'```py\n{exc}\n```'
e.timestamp = datetime.datetime.utcnow()
ch = self.bot.get_channel(LOGGING_CHANNEL)
await ch.send(embed=e)
def on_command_error(self, ctx, error):
"""Command error handler"""
manager = MessageManager(self.bot, ctx.author, ctx.channel, ctx.prefix, [ctx.message])
if isinstance(error, commands.CommandNotFound):
pass
elif isinstance(error, commands.MissingRequiredArgument):
pass
elif isinstance(error, commands.NotOwner):
pass
elif isinstance(error, commands.NoPrivateMessage):
await manager.say("You can't use that command in a private message", mention=False)
elif isinstance(error, commands.CheckFailure):
await manager.say("You don't have the required permissions to do that")
elif isinstance(error, commands.CommandOnCooldown):
await manager.say(error)
elif isinstance(error, commands.CommandInvokeError):
if isinstance(error.original, discord.errors.Forbidden):
pass
else:
raise error
else:
raise error
await manager.clear()
def on_command_error(self, ctx, error):
if not await self.__local_check(ctx):
return
# command not found? docs search it. only if message string is not *only* dots though
if isinstance(error, commands.CommandNotFound) and not re.search('^\.{2}', ctx.message.content):
await ctx.invoke(self.docs, search=ctx.message.content[1:])
def on_command_error(self, ctx, err):
if isinstance(err, errors.PermissionDenied):
await ctx.send('BAKA! You do not have my permission!')
elif isinstance(err, errors.MissingPermissions):
await ctx.send('BAKA! I require these permissions: %s' % ', '.join(err.args))
elif isinstance(err, commands.NoPrivateMessage):
await ctx.send('BAKA! This command does not work in private messages!')
elif isinstance(err, commands.BadArgument):
str_err = str(err)
if not str_err.endswith(('.', '!')):
str_err += '.'
await ctx.send('BAKA! %s' % str_err)
elif isinstance(err, commands.MissingRequiredArgument):
await ctx.send('BAKA! Missing required argument: `%s`' % err.args[0].partition(' ')[0])
elif isinstance(err, commands.TooManyArguments):
await ctx.send('BAKA! Too many arguments!')
elif isinstance(err, commands.CommandNotFound):
pass
else:
await ctx.send('```\n%s\n```' % ''.join(traceback.format_exception_only(type(err), err)).strip())
if isinstance(ctx.channel, discord.TextChannel):
log.error('Error in command <{0}> ({1.name!r}({1.id}) {2}({2.id}) {3}({3.id}) {4!r})'.format(ctx.command, ctx.guild, ctx.channel, ctx.author, ctx.message.content))
else:
log.error('Error in command <{0}> (DM {1}({1.id}) {2!r})'.format(ctx.command, ctx.channel.recipient, ctx.message.content))
log.error(''.join(traceback.format_exception(type(err), err, err.__traceback__)))
def on_command_error(error, ctx):
if isinstance(error, commands.NoPrivateMessage):
await bot.send_message(ctx.message.author, 'This command cannot be used in private messages.')
elif isinstance(error, commands.DisabledCommand):
await bot.send_message(ctx.message.author, 'Sorry. This command is disabled and cannot be used.')
elif isinstance(error, commands.MissingRequiredArgument):
command = ctx.message.content.split()[1]
await bot.send_message(ctx.message.channel, "Missing an argument: try gsbot help or gsbot help " + command)
elif isinstance(error, commands.CommandNotFound):
await bot.send_message(ctx.message.channel, codify("I don't know that command: try gsbot help"))
def on_command_error(self, exception, context):
"""
Custom command error handling
:param exception: the expection raised
:param context: the context of the command
"""
if isinstance(exception, Forbidden):
# Ignore this case
return
if isinstance(exception, CommandNotFound):
# Ignore this case
return
channel = context.message.channel
try:
res = command_error_handler(exception)
except Exception as e:
tb = format_exc()
msg, triggered = format_command_error(e, context)
self.logger.log(logging.WARN, f'\n{msg}\n\n{tb}')
warn = (f':warning: I ran into an error while executing this '
f'command. It has been reported to my developers.\n{msg}')
await self.__try_send_msg(channel, context.message.author, warn)
await self.send_traceback(
tb, f'**WARNING** Triggered message:\n{triggered}')
else:
await self.__try_send_msg(channel, context.message.author, res)
def on_command_error(self, ctx, error):
if isinstance(error, commands.NoPrivateMessage):
return await ctx.send('This command cannot be used in private messages.')
if isinstance(error, commands.DisabledCommand):
return await ctx.send('Sorry. This command is disabled and cannot be used.')
if isinstance(error, commands.CommandNotFound):
return await ctx.send('Type `snb?help` for help on valid commands.')
if isinstance(error, errors.StreamNotificationBotError):
return log.error('StreamNotificationBotError: %s', error)
if isinstance(error, commands.CommandInvokeError):
return log.error('CommandInvokeError: %s', error)
tb = ''.join(traceback.format_exception(type(error), error, error.__traceback__))
log.error(f'Command error in %s:\n%s', ctx.command.qualified_name, tb)
def on_command_error(self, ctx, error):
if isinstance(error, commands.CheckFailure) and await self.is_owner(ctx.author):
# There is actually a race here. When this command is invoked the
# first time, it's wrapped in a context manager that automatically
# starts and closes a DB session.
#
# The issue is that this event is dispatched, which means during the
# first invoke, it creates a task for this and goes on with its day.
# The problem is that it doesn't wait for this event, meaning it might
# accidentally close the session before or during this command's
# reinvoke.
#
# This solution is dirty but since I'm only doing it once here
# it's fine. Besides it works anyway.
while ctx.session:
await asyncio.sleep(0)
try:
async with ctx.acquire():
await ctx.reinvoke()
except Exception as exc:
await ctx.command.dispatch_error(ctx, exc)
return
# command_counter['failed'] += 0 sets the 'failed' key. We don't want that.
if not isinstance(error, commands.CommandNotFound):
self.command_counter['failed'] += 1
cause = error.__cause__
if isinstance(error, errors.ChiakiException):
await ctx.send(str(error))
elif type(error) is commands.BadArgument:
await ctx.send(str(cause or error))
elif isinstance(error, commands.NoPrivateMessage):
await ctx.send('This command cannot be used in private messages.')
elif isinstance(error, commands.MissingRequiredArgument):
await ctx.send(f'This command ({ctx.command}) needs another parameter ({error.param})')
elif isinstance(error, commands.CommandInvokeError):
print(f'In {ctx.command.qualified_name}:', file=sys.stderr)
traceback.print_tb(error.original.__traceback__)
print(f'{error.__class__.__name__}: {error}'.format(error), file=sys.stderr)
def on_command_error(self, exception, ctx):
if isinstance(exception, CommandNotFound):
if await self.database.has(ctx.invoked_with):
return
else:
print(exception.args[0])
def on_command_error(self, exception, ctx):
if isinstance(exception, CheckFailure):
print("{0} does not have permission to run `{1}`".format(ctx.message.author, ctx.command.name))
elif isinstance(exception, CommandNotFound):
# This is handled in CustomCommands
pass
else:
pprint(exception)
await self.on_error("on_command_error", exception, ctx)
def _on_command_error(self, exception, ctx):
# non-existing commands won't trigger check thus are not deleted
if isinstance(exception, dec.CommandNotFound) and not isinstance(ctx.message.channel, discord.PrivateChannel):
await self._bot.client.delete_message(ctx.message)
# get a cause if the exception was thrown inside the command routine
if isinstance(exception, dec.CommandInvokeError):
exception = exception.__cause__
# now inform the author of the command on the failure using PMs
await self._bot.client.send_message(ctx.message.author, str(exception))
# log the error for debugging purposes
log.debug('Command \'{}\' invoked by {} raised an exception\n{}'
.format(ctx.command, ctx.message.author, ctx.message.content), exc_info=exception)
def on_command_error(exception, context):
if type(exception) == commands.CommandOnCooldown:
await bot.send_message(context.message.channel,
"!{} is on cooldown for {:0.2f} seconds.".format(
context.command, exception.retry_after))
elif type(exception) == commands.CommandNotFound:
cmd = context.message.content.split()[0][1:]
try:
closest = get_close_matches(cmd.lower(), list(bot.commands))[0]
except IndexError:
await bot.send_message(context.message.channel,
"!{} is not a known command."
.format(cmd))
else:
await bot.send_message(context.message.channel,
"!{} is not a command, did you mean !{}?"
.format(cmd, closest))
elif type(exception) == commands.CheckFailure:
await bot.send_message(context.message.channel,
"You failed to meet a requirement for that "
"command.")
elif type(exception) == commands.MissingRequiredArgument:
await bot.send_message(context.message.channel,
"You are missing a required argument for that "
"command.")
else:
await bot.send_message(context.message.channel,
"Unhandled command error ({})"
.format(exception))
print('Ignoring exception in command {}'.format(context.command),
file=sys.stderr)
traceback.print_exception(type(exception), exception,
exception.__traceback__, file=sys.stderr)
def on_command_error(self, error, ctx: commands.Context):
log = lib.get_author_name(ctx)
send = None
if isinstance(error, commands.CheckFailure):
if str(error) == "timer not found":
send = "No timer found for this channel."
log += " tried to interact with a nonexistent timer."
elif str(error) == "timer locked":
send = "You are not allowed to modify this timer."
log += " tried to modify a locked timer without permissions."
elif str(error) == "no permissions" or str(error) == "not admin":
send = "You do not have permission to do this!"
log += (" tried to execute a command and failed, " +
"lacked permissions.")
else:
send = "Timers are not allowed in this channel."
log += " tried to start a timer in a non-whitelisted channel."
elif isinstance(error, commands.CommandNotFound):
send = "Command not found: `" + ctx.invoked_with + "`."
log += " tried to execute a nonexistent command: `{}`."\
.format(ctx.invoked_with)
alt = None
for name, command in self.bot.commands.items():
if ctx.invoked_with == name:
alt = name
elif isinstance(command, commands.GroupMixin):
for sub_name, sub_command in command.commands.items():
if ctx.invoked_with == sub_name:
alt = name + " " + sub_name
if alt is not None:
send += " Did you mean `" + alt + "`?"
elif isinstance(error, commands.CommandInvokeError):
lib.log_cmd_stacktrace(error)
return
else:
log = str(error)
lib.log(log, channel_id=lib.get_channel_id(ctx), level=logging.WARN)
await self.bot.safe_send(lib.get_channel(ctx), send,
delete_after=self.bot.ans_lifespan)
def on_command_error(error, ctx):
if isinstance(error, commands.CommandNotFound):
return
if isinstance(error, commands.DisabledCommand):
return
try:
if isinstance(error.original, discord.Forbidden):
return
elif isinstance(error.original, discord.HTTPException) and 'empty message' in str(error.original):
return
elif isinstance(error.original, aiohttp.ClientOSError):
return
except AttributeError:
pass
if isinstance(error, commands.BadArgument):
fmt = "Please provide a valid argument to pass to the command: {}".format(error)
await bot.send_message(ctx.message.channel, fmt)
elif isinstance(error, commands.CheckFailure):
fmt = "You can't tell me what to do!"
await bot.send_message(ctx.message.channel, fmt)
elif isinstance(error, commands.CommandOnCooldown):
m, s = divmod(error.retry_after, 60)
fmt = "This command is on cooldown! Hold your horses! >:c\nTry again in {} minutes and {} seconds" \
.format(round(m), round(s))
await bot.send_message(ctx.message.channel, fmt)
elif isinstance(error, commands.NoPrivateMessage):
fmt = "This command cannot be used in a private message"
await bot.send_message(ctx.message.channel, fmt)
elif isinstance(error, commands.MissingRequiredArgument):
await bot.send_message(ctx.message.channel, error)
else:
now = datetime.datetime.now()
with open("error_log", 'a') as f:
print("In server '{0.message.server}' at {1}\nFull command: `{0.message.content}`".format(ctx, str(now)),
file=f)
try:
traceback.print_tb(error.original.__traceback__, file=f)
print('{0.__class__.__name__}: {0}'.format(error.original), file=f)
except:
traceback.print_tb(error.__traceback__, file=f)
print('{0.__class__.__name__}: {0}'.format(error), file=f)
def on_command_error(ctx, error):
if ctx.message in thinker.messages:
await thinker.stop_thinking(ctx.message)
try:
if isinstance(error, commands.CommandNotFound):
cmd = ctx.message.content[1:].split(" ")[0]
if cmd in deprecated_commands:
await ctx.send(f"You shouldn't use `?{cmd}` anymore. It's *deprecated*. Try `?{deprecated_commands[cmd]}` instead.")
return
elif cmd == "" or cmd.startswith("?") or cmd.startswith("!"):
return # These were probably not meant to be commands
if cmd.lower() in bot.commands:
new_message = ctx.message
new_message.content = "?" + cmd.lower() + ctx.message.content[len(cmd) + 1:]
await bot.process_commands(new_message)
elif await invalid_command_reporting(ctx):
await ctx.send(f"?? Ya I dunno what a '{cmd}' is, but it ain't a command. Try `?help` fer a list of things that ARE commands.")
elif isinstance(error, commands.CheckFailure):
print("(suppressed)")
return # The user does not have permissions
elif isinstance(error, commands.MissingRequiredArgument):
await ctx.send(embed=await bot.formatter.format_as_embed(ctx, ctx.command))
elif isinstance(error, commands.BadArgument):
signature = await get_cmd_signature(ctx)
await ctx.send((
"Thats the wrong type of argument for that command.\n\n"
f"Ya gotta do it like this:\n`{signature}`\n\n"
f"Try `?help {ctx.command}` for a more detailed description of the command"))
elif isinstance(error, commands.CommandInvokeError) and isinstance(error.original, discord.errors.Forbidden):
await print_missing_perms(ctx, error)
elif isinstance(error, commands.CommandInvokeError) and isinstance(error.original, discord.errors.HTTPException):
await ctx.send("Looks like there was a problem with discord just then. Try again in a bit.")
elif isinstance(error, commands.CommandInvokeError) and isinstance(error.original, UserError):
await ctx.send(error.original.message)
else:
await ctx.send("Uh-oh, sumthin dun gone wrong ??")
trace_string = report_error(ctx.message, error, skip_lines=4)
if settings.debug:
await ctx.send(f"```{trace_string}```")
except discord.errors.Forbidden:
await ctx.author.send("Looks like I don't have permission to talk in that channel, sorry")
def on_command_error(ctx, error):
"""The event triggered when an error is raised while invoking a command.
ctx : Context
error : Exception"""
if hasattr(ctx.command, 'on_error'):
return
cog = ctx.cog
if cog:
attr = f'_{cog.__class__.__name__}__error'
if hasattr(cog, attr):
return
error = getattr(error, 'original', error)
ignored = (commands.CommandNotFound, commands.UserInputError)
if isinstance(error, ignored):
return
handler = {
discord.Forbidden: '**I do not have the required permissions to run this command.**',
commands.DisabledCommand: f'{ctx.command} has been disabled.',
commands.NoPrivateMessage: f'{ctx.command} can not be used in Private Messages.',
commands.CheckFailure: '**You aren\'t allowed to use this command!**',
ExplicitCheckFailure: f'This command can only be used in a **NSFW** channel.',
InvalidChannelCheck: f'{ctx.command} can only be used in a server',
BotPermissionsCheck: 'For **any** of the moderation commands, the bot must be given\n'
'Manage Messages, Manage Nicknames, Kick Members and Ban Members'
}
try:
message = handler[type(error)]
except KeyError:
pass
else:
return await ctx.send(message)
embed = discord.Embed(title=f'Command Exception', color=discord.Color.red())
embed.set_footer(text='Occured on')
embed.timestamp = datetime.datetime.utcnow()
exc = ''.join(traceback.format_exception(type(error), error, error.__traceback__, chain=False))
exc = exc.replace('`', '\u200b`')
embed.description = f'```py\n{exc}\n```'
embed.add_field(name='Command', value=ctx.command.qualified_name)
embed.add_field(name='Invoker', value=ctx.author)
embed.add_field(name='Location', value=f'Guild: {ctx.guild}\nChannel: {ctx.channel}')
embed.add_field(name='Message', value=ctx.message.content)
await ctx.bot.get_channel(368477860387880960).send(embed=embed)
def on_command_error(ctx, error): # pylint: disable=arguments-differ
"""Handles all errors returned from Commands."""
async def send_error(description):
"""A small helper function which sends an Embed with red colour."""
await ctx.send(embed=discord.Embed(
description=description,
colour=discord.Colour.red()
))
if isinstance(error, commands.MissingRequiredArgument):
await send_error(
f'You are missing the parameter {error.param} for the Command.'
)
elif isinstance(error, commands.NoPrivateMessage):
await send_error(
'This Command cannot be used in Private Messages.'
)
elif isinstance(error, commands.BadArgument):
await send_error(
'You invoked the Command with the wrong type of arguments. Use'
'`.help <command>` to get information about its usage.'
)
elif isinstance(error, commands.CommandInvokeError):
await ctx.send(embed=discord.Embed(
title='Exception in command occurred, traceback printed.',
colour=discord.Colour.red()
))
print(
'In {0.command.qualified_name}:'.format(ctx),
file=sys.stderr
)
traceback.print_tb(error.original.__traceback__)
print(
'{0.__class__.__name__}: {0}'.format(error.original),
file=sys.stderr
)
elif isinstance(error, commands.CommandOnCooldown):
await ctx.send(embed=discord.Embed(
title='This Command is currently on cooldown.',
colour=discord.Colour.red()
))
elif isinstance(error, commands.CommandNotFound):
pass