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类DisabledCommand()的实例源码
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(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 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, error, ctx):
if isinstance(error, commands.NoPrivateMessage):
await self.send_message(ctx.message.author, "\N{WARNING SIGN} Sorry, you can't use this command in a private message!")
elif isinstance(error, commands.DisabledCommand):
await self.send_message(ctx.message.author, "\N{WARNING SIGN} Sorry, this command is disabled!")
elif isinstance(error, commands.CommandOnCooldown):
await self.send_message(ctx.message.channel, f"{ctx.message.author.mention} slow down! Try again in {error.retry_after:.1f} seconds.")
elif isinstance(error, commands.MissingRequiredArgument) or isinstance(error, commands.BadArgument):
await self.send_message(ctx.message.channel, f"\N{WARNING SIGN} {error}")
elif isinstance(error, commands.CommandInvokeError):
original_name = error.original.__class__.__name__
print(f"In {paint(ctx.command.qualified_name, 'b_red')}:")
traceback.print_tb(error.original.__traceback__)
print(f"{paint(original_name, 'red')}: {error.original}")
else:
print(f"{paint(type(error).__name__, 'b_red')}: {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(error, ctx):
if isinstance(error, commands.NoPrivateMessage):
await ctx.author.send('This command cannot be used in private messages.')
elif isinstance(error, commands.DisabledCommand):
await ctx.channel.send(':x: Dieser Command wurde deaktiviert')
elif isinstance(error, commands.CommandInvokeError):
if bot.dev:
raise error
else:
embed = discord.Embed(title=':x: Command Error', colour=0x992d22) #Dark Red
embed.add_field(name='Error', value=error)
embed.add_field(name='Guild', value=ctx.guild)
embed.add_field(name='Channel', value=ctx.channel)
embed.add_field(name='User', value=ctx.author)
embed.add_field(name='Message', value=ctx.message.clean_content)
embed.timestamp = datetime.datetime.utcnow()
try:
await bot.owner.send(embed=embed)
except:
pass
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, error, ctx):
if isinstance(error, commands.NoPrivateMessage):
await self.send_message(ctx.message.author, 'This command cannot be used in private messages.')
elif isinstance(error, commands.DisabledCommand):
await self.send_message(ctx.message.author, 'Sorry. This command is disabled and cannot 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)
def define_error(self, ctx, err):
if isinstance(err, commands.DisabledCommand) or isinstance(err, commands.CheckFailure):
return
await ctx.send('An error has occurred.')
def on_command_error(error, ctx):
if isinstance(error, commands.NoPrivateMessage):
await bot.send_message(ctx.message.author, 'Cette commande ne peut pas être utilisée en message privée.')
elif isinstance(error, commands.DisabledCommand):
await bot.send_message(ctx.message.author, 'Désoler mais cette commande est désactivé, elle ne peut donc pas être utilisée.')
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)
def on_command_error(self, ctx, error):
if isinstance(error, commands.NoPrivateMessage):
await ctx.author.send('Cette commande ne peut pas être utilisée en message privée.')
elif isinstance(error, commands.DisabledCommand):
await ctx.author.send('Désoler mais cette commande est désactivé, elle ne peut donc pas être utilisée.')
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)
## LOAD ##
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(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.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)
#event on_ready(), so, when the bot starts this is shown in the console, still trying to get author name and id to work
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.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)
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.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)
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.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)
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(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(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):
"""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)