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}")
python类CommandOnCooldown()的实例源码
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):
"""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 command_error_handler(exception: Exception):
"""
A function that handles command errors
:param exception: the exception raised
:return: the message to be sent based on the exception type
"""
ex_str = str(exception)
if isinstance(exception, (CommandOnCooldown, NoMongo)):
return ex_str
if isinstance(exception, HTTPStatusError):
return f'Something went wrong with the HTTP request.\n{ex_str}'
raise exception
def star_update_error(self, error, ctx):
if isinstance(error, commands.CommandOnCooldown):
if checks.is_owner_check(ctx.message):
await ctx.invoke(self.star_update)
else:
await self.bot.say(error)
def star_show_error(self, error, ctx):
if isinstance(error, commands.CommandOnCooldown):
if checks.is_owner_check(ctx.message):
await ctx.invoke(self.star_show)
else:
await self.bot.say(error)
elif isinstance(error, commands.BadArgument):
await self.bot.say('That is not a valid message ID. Use Developer Mode to get the Copy ID option.')
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(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): # 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