def __error(self, ctx, error):
if isinstance(error, commands.BadArgument):
await ctx.send(error)
elif isinstance(error, commands.CommandInvokeError):
original = error.original
if isinstance(original, discord.Forbidden):
await ctx.send('I do not have permission to execute this action.')
elif isinstance(original, discord.NotFound):
await ctx.send(f'This entity does not exist: {original.text}')
elif isinstance(original, discord.HTTPException):
await ctx.send('Somehow, an unexpected error occurred. Try again later?')
python类CommandInvokeError()的实例源码
def on_command_error(self, ctx, error):
if isinstance(error, commands.NoPrivateMessage):
await ctx.author.send('This command cannot be used in private messages.')
elif isinstance(error, commands.DisabledCommand):
await ctx.author.send('Sorry. This command is disabled and cannot be used.')
elif isinstance(error, commands.CommandInvokeError):
print(f'In {ctx.command.qualified_name}:', file=sys.stderr)
traceback.print_tb(error.original.__traceback__)
print(f'{error.original.__class__.__name__}: {error.original}', file=sys.stderr)
def on_command_error(error, ctx):
if isinstance(error, commands.NoPrivateMessage):
await fox.send_message(ctx.message.author, "Sorry, you can't use this command in private messages.")
elif isinstance(error, commands.DisabledCommand):
await fox.send_message(ctx.message.author, 'Sorry, it looks like that command is disabled.')
elif isinstance(error, commands.CommandInvokeError):
print('In {0.command.qualified_name}:'.format(ctx))
traceback.print_tb(error.original.__traceback__)
print('{0.__class__.__name__}: {0}'.format(error.original))
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(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(error, ctx):
language = prefs.getPref(ctx.message.server, "language")
if isinstance(error, commands.NoPrivateMessage):
await bot.send_message(ctx.message.author, _(':x: This command cannot be used in private messages.', language))
elif isinstance(error, commands.DisabledCommand):
await bot.send_message(ctx.message.author, _(':x: Sorry. This command is disabled and cannot be used.', language))
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)
myperms = ctx.message.channel.permissions_for(ctx.message.server.me)
can_send = myperms.add_reactions and myperms.create_instant_invite
if can_send:
error_report = _("Send an error report?", language)
else:
error_report = _("Sadly, I need the `add_reactions` and `create_instant_invite` permissions to be able to send an error report.", language)
msg = await comm.message_user(ctx.message, _(":x: An error (`{error}`) happened while executing `{command}`, here is the traceback: ```\n{tb}\n```\n{error_report}", language).format(**{
"command" : ctx.command.qualified_name,
"error" : error.original.__class__.__name__,
"tb" : "\n".join(traceback.format_tb(error.original.__traceback__, 4)),
"error_report": error_report
}))
if can_send:
yes = "\N{THUMBS UP SIGN}"
no = "\N{THUMBS DOWN SIGN}"
await bot.add_reaction(msg, yes)
await bot.add_reaction(msg, no)
res = await bot.wait_for_reaction(emoji=[yes, no], user=ctx.message.author, message=msg, timeout=120)
if res:
reaction, user = res
emoji = reaction.emoji
if emoji == yes:
msg = await comm.message_user(ctx.message, _(":anger_right: Creating an invite for the error report...", language))
support_channel = discord.utils.find(lambda c: str(c.id) == '273930986314792960', discord.utils.find(lambda s: str(s.id) == '195260081036591104', bot.servers).channels)
invite = await bot.create_invite(ctx.message.channel, max_uses=5)
invite = invite.url
await bot.edit_message(msg, _(":anger_right: Sending error report...", language))
await bot.send_message(support_channel, _(":hammer: {date} :hammer:").format(date=int(time.time())))
await bot.send_message(support_channel, await comm.paste(_("{cause}\n\n{tb}").format(cause=error.original.__class__.__name__,
tb="\n".join(traceback.format_tb(error.original.__traceback__))), "py"))
await bot.send_message(support_channel, invite)
await bot.edit_message(msg, _(":ok: Error report sent, thanks. :)", language))
return
await comm.message_user(ctx.message, _("OK, I won't send an error report.", language))
elif isinstance(error, commands.MissingRequiredArgument):
await comm.message_user(ctx.message, _(":x: Missing a required argument. ", language) + (("Help: \n```\n" + ctx.command.help + "\n```") if ctx.command.help else ""))
elif isinstance(error, commands.BadArgument):
await comm.message_user(ctx.message, _(":x: Bad argument provided. ", language) + (("Help: \n```\n" + ctx.command.help + "\n```") if ctx.command.help else ""))
# elif isinstance(error, commands.CheckFailure):
# await comm.message_user(ctx.message, _(":x: You are not an admin/owner, you don't have enough exp to use this command, or you are banned from the channel, so you can't use this command. ", language) + (("Help: \n```\n" + ctx.command.help + "\n```") if ctx.command.help else ""))
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