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类NoPrivateMessage()的实例源码
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 convert(self, ctx, arg):
if not ctx.guild:
raise commands.NoPrivateMessage
self_roles = await _get_self_roles(ctx)
if not self_roles:
message = ("This server has no self-assignable roles. "
f"Use `{ctx.prefix}asar` to add one.")
raise commands.BadArgument(message)
temp_guild = copy.copy(ctx.guild)
temp_guild.roles = self_roles
with temp_attr(ctx, 'guild', temp_guild):
try:
return await super().convert(ctx, arg)
except commands.BadArgument:
raise commands.BadArgument(f'{arg} is not a self-assignable role...')
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(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(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(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, 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, 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 member_check(self, ctx, member):
try:
return await commands.converter.MemberConverter().convert(ctx, member)
except (commands.BadArgument, commands.NoPrivateMessage):
return None
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 convert(self, ctx, arg):
if not ctx.guild:
raise commands.NoPrivateMessage
role = await super().convert(ctx, arg)
await _check_role(ctx, role, thing='an auto-assign')
return role
def convert(self, ctx, argument):
guild = ctx.guild
if not guild:
raise commands.NoPrivateMessage()
# Let ID's and mentions take priority
match = self._get_id_match(argument) or re.match(r'<@&([0-9]+)>$', argument)
if match:
predicate = lambda r, id=int(match.group(1)): r.id == id
elif self.case_sensitive:
predicate = lambda r: r.name == argument
else:
predicate = lambda r, arg=argument.lower(): r.name.lower() == arg
return await ctx.disambiguate(list(filter(predicate, guild.roles)))
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(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 convert(self, ctx, argument):
guild = ctx.message.guild
if not guild:
raise commands.NoPrivateMessage()
match = self._get_id_match(argument) or re.match(r'<@&([0-9]+)>$', argument)
params = dict(id=int(match.group(1))) if match else dict(name=argument)
result = discord.utils.get(guild.roles, **params)
if result is None:
return argument
return result
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(ctx, error):
if isinstance(error, commands.NoPrivateMessage):
await edit(ctx, content='\N{HEAVY EXCLAMATION MARK SYMBOL} Only usable on Servers', ttl=5)
elif isinstance(error, commands.CheckFailure):
await edit(ctx, content='\N{HEAVY EXCLAMATION MARK SYMBOL} No Permissions to use this command', ttl=5)
elif isinstance(error, commands.CommandInvokeError):
log.error('In {0.command.qualified_name}:\n{1}'.format(ctx, ''.join(traceback.format_list(traceback.extract_tb(error.original.__traceback__)))))
log.error('{0.__class__.__name__}: {0}'.format(error.original))
# Increase use count and log to logger
def no_pm():
def predicate(ctx):
if ctx.command.name == "help":
return True
if ctx.guild is None:
raise commands.NoPrivateMessage('This command cannot be used in private messages.')
return True
return commands.check(predicate)
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 role_or_permissions(ctx, check, **perms):
if not isinstance(ctx.channel, discord.abc.GuildChannel):
raise commands.NoPrivateMessage
role = discord.utils.find(check, ctx.author.roles)
if role:
return True
if await check_permissions(ctx, perms):
return True
return False
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, ctx, ex):
if getattr(ex, 'should_suppress', False):
logger.debug('Suppressing exception: %s', ex)
return
see_help = await ctx._('err.see_help', prefix=ctx.prefix, cmd=ctx.command.qualified_name) if ctx.command else\
'See my help for more information.'
if isinstance(ex, commands.errors.BadArgument):
message = str(ex)
if not message.endswith('.'):
message = message + '.'
await ctx.send(await ctx._('err.bad_arg', msg=message, see_help=see_help))
elif isinstance(ex, commands.errors.MissingRequiredArgument):
await ctx.send(await ctx._('err.uh_oh', ex=ex, see_help=see_help))
elif isinstance(ex, commands.NoPrivateMessage):
await ctx.send(await ctx._('err.not_in_dm'))
elif isinstance(ex, errors.InsufficientPermissions):
await ctx.send(ex)
elif isinstance(ex, commands.errors.DisabledCommand):
await ctx.send(await ctx._('err.globally_disabled'))
elif isinstance(ex, asyncio.TimeoutError):
await ctx.send(await ctx._('err.timeout'))
elif isinstance(ex, commands.errors.CommandInvokeError):
if isinstance(ex.original, discord.Forbidden):
if ctx.command.name == 'help':
# can't dm that person :(
try:
await ctx.send(await ctx._('err.dms_disabled', mention=ctx.author.mention))
except discord.Forbidden:
pass
return
return await self.handle_forbidden(ctx)
# get the traceback
tb = ''.join(traceback.format_exception(type(ex.original), ex.original, ex.original.__traceback__))
# form a good human-readable message
header = f'Command error: {type(ex.original).__name__}: {ex.original}'
message = header + '\n' + str(tb)
self.dispatch('uncaught_command_invoke_error', ex.original, (message, tb, ctx))
logger.error(message)