def unload_error(ctx, error):
"""Handle load's errors"""
if isinstance(error, commands.MissingRequiredArgument):
await ctx.send(f"Usage: {prefix}unload(<extension name>).")
if isinstance(error, commands.errors.NotOwner):
await ctx.send("You're not my daddy, only daddy can use this function.")
python类MissingRequiredArgument()的实例源码
def on_command_error(self, ctx, exception):
self.stats.increment("RPGBot.errors", tags=["RPGBot:errors"], host="scw-8112e8")
logging.info(f"Exception in {ctx.command} {ctx.guild}:{ctx.channel} {exception}")
if isinstance(exception, commands.MissingRequiredArgument):
await ctx.send(f"`{exception}`")
else:
await ctx.send(f"`{exception}`")
def poll_error(self, ctx, error):
if isinstance(error, commands.MissingRequiredArgument):
return await ctx.send('Missing the question.')
def coliru_error(self, ctx, error):
if isinstance(error, commands.BadArgument):
await ctx.send(error)
if isinstance(error, commands.MissingRequiredArgument):
await ctx.send(CodeBlock.missing_error)
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 admin_spoof(self, ctx: commands.Context, spoofed_id=None):
""" Enables spoof-mode on a channel.
Spoof mode allows users with permissions to modify another specified
channel's timer from the one in which this command
was executed.
For example, if channel #session_1 has ID '249719010319532064'
and someone executes '!spoof 249719010319532064' from #admin_area,
all timer-related commands (except for setup) executed from
#admin_area by members with permissions will either affect or give
information of the timer in #session_1 instead.
:param spoofed_id: The ID of the channel that instructions will be
sent to.
:type spoofed_id: str
"""
channel = lib.get_channel(ctx)
if channel.id == spoofed_id:
await self.bot.say("How about no. " + spoofed_id,
delete_after=self.bot.ans_lifespan)
return
spoofed_channel = lib.get_server(ctx).get_channel(spoofed_id)
if spoofed_id is not None:
self.bot.get_interface(channel).spoofed = spoofed_channel
send = "Now acting in channel " + spoofed_channel.name
log = "Now acting as if in " + spoofed_channel.name
elif self.bot.get_interface(channel).spoofed is not None:
self.bot.get_interface(channel).spoofed = None
send = "Now acting in current channel"
log = "Spoofing now off"
else:
raise commands.MissingRequiredArgument
await self.bot.say(send, delete_after=self.bot.ans_lifespan)
lib.log(log, channel_id=channel.id)
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(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