Python discord.ext.commands 模块,CommandInvokeError() 实例源码

我们从Python开源项目中,提取了以下37个代码示例,用于说明如何使用discord.ext.commands.CommandInvokeError()

项目:AceBot    作者:Run1e    | 项目源码 | 文件源码
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
项目:Inkxbot    作者:InkxtheSquid    | 项目源码 | 文件源码
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.")
项目:SESTREN    作者:SirThane    | 项目源码 | 文件源码
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)
项目:snake    作者:AnonymousDapper    | 项目源码 | 文件源码
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}")
项目:BlitzcrankBotV2    作者:SuperFrosty    | 项目源码 | 文件源码
def on_command_error(self, ctx, error):
        """Error handling"""
        error_msg = None
        if isinstance(error, commands.MissingRequiredArgument):
            await ctx.send(error)
        elif isinstance(error, commands.CommandNotFound):
            pass
        elif isinstance(error, commands.CommandInvokeError):
            original = error.original
            if isinstance(original, discord.Forbidden):
                await ctx.send("I need to have the 'embed links' permission to send messages!")
                return
            elif isinstance(original, exceptions.Halt):
                return

            print('{0.created_at}: {0.author}: {0.content}'.format(ctx.message))
            print(error)
            embed = discord.Embed(title="An unexpected error occured :I", colour=0xCA0147,
                                  description="If you feel like this shouldn't be happening [click here to join my support server](https://discord.gg/UP4TwFX).")
            await ctx.send("", embed=embed)
        else:
            print('{0.created_at}: {0.author}: {0.content}'.format(ctx.message))
            print(str(error))
项目:Dota2HelperBot    作者:enoch-ng    | 项目源码 | 文件源码
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))
项目:discord_bot    作者:Der-Eddy    | 项目源码 | 文件源码
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
项目:Nurevam    作者:Maverun    | 项目源码 | 文件源码
def on_command_error(self,ctx,error):
        if self.bot.user.id == 181503794532581376 or self.error_log:
            print(error)
        if isinstance(error, commands.MissingRequiredArgument):
            await self.send_cmd_help(ctx)
        elif isinstance(error,commands.BadArgument):
            await self.send_cmd_help(ctx)
        elif isinstance(error, commands.CommandInvokeError):
            if isinstance(error.original,discord_error.Forbidden):
                await ctx.send("I am sorry, I need a certain permission to run it...")
                traceback.print_exception(type(error), error, error.__traceback__)
                return utils.prRed(type(error.original))
            errors = traceback.format_exception(type(error), error, error.__traceback__)
            Current_Time = datetime.datetime.utcnow().strftime("%b/%d/%Y %H:%M:%S UTC")
            utils.prRed(Current_Time)
            utils.prRed("Error!")
            traceback.print_exception(type(error), error, error.__traceback__)
            cog_error =  '```fix\nCogs:{0.command.cog_name}\tCommand:{0.command}\tAuthor:{0.message.author}-{0.message.author.id}\n' \
                         'Server:{0.message.guild.id}\n{0.message.clean_content}\nError:\n{1}```'.format(ctx,error)
            msg ="```py\n{}```\n{}\n```py\n{}\n```".format(Current_Time + "\n"+ "ERROR!",cog_error,"".join(errors).replace("`",""))
            if len(msg) >= 1900:
                msg = await utils.send_hastebin(msg)
            await self.bot.owner.send(msg)
            await ctx.send("You either used the command incorrectly or an unexpected error occurred. A report has been sent to the creator so you can hope for a fix soon.")
项目:spirit    作者:jgayfer    | 项目源码 | 文件源码
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()
项目:lagbot    作者:mikevb1    | 项目源码 | 文件源码
def __error(self, ctx, exc):
        if isinstance(exc, commands.BadArgument):
            exc.handled = True
            await ctx.send(exc)
            return
        elif not isinstance(exc, commands.CommandInvokeError):
            return
        if isinstance(exc.original, (NotFound, ServerError, NotInDB, NotPlayed, InvalidBTag)):
            exc.handled = True
            await ctx.send(exc.original)
            return
项目:lagbot    作者:mikevb1    | 项目源码 | 文件源码
def on_command_error(self, ctx, exc):
        """Emulate default on_command_error and add guild + channel info."""
        if hasattr(ctx.command, 'on_error') or getattr(exc, 'handled', False) or \
                not isinstance(exc, commands.CommandInvokeError) or isinstance(exc.original, discord.Forbidden):
            return
        msg = f'{ctx.message.content}\nin {"guild" if ctx.guild else "DM"}'
        tb = ''.join(traceback.format_exception(*tb_args(exc.original))).replace(UPPER_PATH, '...')
        logging.error('\n'.join((msg, tb)))
项目:PomodoroBot    作者:VicenteRD    | 项目源码 | 文件源码
def log_cmd_stacktrace(err: commands.CommandInvokeError):
    """ Logs the stacktrace of a failed command execution.

    :param err:
    """

    if not _logger.ready:
        init_logger()

    _logger.logger.exception(" ", exc_info=err.original)
项目:discordbot.py    作者:rauenzi    | 项目源码 | 文件源码
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)
项目:dogbot    作者:slice    | 项目源码 | 文件源码
def poll_error(self, ctx, error):
        if isinstance(error, commands.CommandInvokeError) and isinstance(error.original, discord.NotFound):
            error.should_suppress = True
项目:dogbot    作者:slice    | 项目源码 | 文件源码
def __error(self, ctx, error):
        if isinstance(error, commands.CommandInvokeError):
            logger.exception('Image processing error:')
            await ctx.send('Something went wrong processing your image. Sorry about that!')
            error.should_suppress = True
        elif isinstance(error, asyncio.TimeoutError):
            await ctx.send('Your image took too long to process...')
            error.should_suppress = True
项目:dogbot    作者:slice    | 项目源码 | 文件源码
def archive_error(self, ctx, err):
        original = None if not isinstance(err, commands.CommandInvokeError) else err.original
        if isinstance(original, ValueError):
            await ctx.send('Invalid flag value provided.')
            err.should_suppress = True
项目:tuxbot-bot    作者:outout14    | 项目源码 | 文件源码
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)
项目:tuxbot-bot    作者:outout14    | 项目源码 | 文件源码
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 ##
项目:StreamNotificationBot    作者:ivandardi    | 项目源码 | 文件源码
def _cog__error(self, ctx, error):
        if isinstance(error, commands.CommandInvokeError):
            original = error.original
            if isinstance(original, errors.InvalidUsernameError):
                await ctx.send(f'Invalid username: {str(original)}')
            if isinstance(original, errors.StreamerNotFoundError):
                await ctx.send(f'Streamer not found: {str(original)}')
            if isinstance(original, errors.NotSubscribedError):
                await ctx.send(f"You're not subscriber to the streamer {str(original)}")
            if isinstance(original, errors.StreamerAlreadyExists):
                await ctx.send("You're already subscribed to this streamer!")
            if isinstance(original, errors.InvalidChannelError):
                await ctx.send(str(original))
        if isinstance(error, commands.BadArgument):
            await ctx.send(str(error))
项目:StreamNotificationBot    作者:ivandardi    | 项目源码 | 文件源码
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)
项目:Chiaki-Nanami    作者:Ikusaba-san    | 项目源码 | 文件源码
def role_error(self, ctx, error):
        if not isinstance(error, commands.CommandInvokeError):
            return

        verb = ctx.command.callback.__name__.partition('_')[0]
        role = ctx.kwargs['name'] if verb == 'create' else ctx.kwargs['role']

        print(type(error.original))
        if isinstance(error.original, discord.Forbidden):
            if not ctx.guild.me.permissions_in(ctx.channel).manage_roles:
                await ctx.send('{ctx.author.mention}, I need the Manage roles permission pls...')

            # We can't modify an add, remove, or delete an integration role, obviously.
            elif getattr(role, 'managed', False):       # ->createrole uses a string for the role.
                await ctx.send(f"{role} is an intergration role, I can't do anything with that!")

            # Assume the role was too high otherwise.
            else:
                await ctx.send('The role was higher than my highest role. '
                               'Check the hierachy please! \U0001f605')

        elif isinstance(error.original, discord.HTTPException):      # Something strange happened.
            # will probably refactor this out into another function later.
            if verb.endswith('e'):
                verb = verb[:-1]

            message = (f'{verb.title()}ing {role} failed for some reason... '
                        'Send this error to the dev if you can:\n'
                       f'{type(error).__name__}: {error}')

            await ctx.send(message)
项目:Chiaki-Nanami    作者:Ikusaba-san    | 项目源码 | 文件源码
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)
项目:Discord-ASM-Bot    作者:Emzi0767    | 项目源码 | 文件源码
def on_command_error(self, context, exception):
        extype = type(exception)
        value = exception
        tback = exception.__traceback__
        exinfo = (extype, value, tback)

        exfmts = [s.replace("\\n", "") for s in traceback.format_exception(*exinfo)]
        exfmt = [""]

        for exf in exfmts:
            ci = len(exfmt) - 1
            if len(exfmt[ci]) + len(exf) + 1 > 1024:
                exfmt.append(exf)
            else:
                exfmt[ci] = exfmt[ci] + "\n" + exf

        if context.command is None:
            return
        cmd = context.command.qualified_name

        iex = exception.original if isinstance(exception, commands.CommandInvokeError) else None
        if iex and isinstance(iex, asmbot.AssemblerException):
            embed = self._embed(context, "Error assembling code", "An error occured when assembling code", "error")
            embed.add_field(name="Details", value=f"```\n{iex.clang_data}\n```", inline=False)
        else:
            embed = self._embed(context, "Error executing command", "An error occured when executing command `{}`".format(cmd), "error")

        asmbot.log(*exfmts, tag="CMD ERR")
        await context.message.channel.send(embed=embed)

    # Bot preparation
项目:ddmbot    作者:Budovi    | 项目源码 | 文件源码
def _on_command_error(self, exception, ctx):
        # non-existing commands won't trigger check thus are not deleted
        if isinstance(exception, dec.CommandNotFound) and not isinstance(ctx.message.channel, discord.PrivateChannel):
            await self._bot.client.delete_message(ctx.message)

        # get a cause if the exception was thrown inside the command routine
        if isinstance(exception, dec.CommandInvokeError):
            exception = exception.__cause__

        # now inform the author of the command on the failure using PMs
        await self._bot.client.send_message(ctx.message.author, str(exception))

        # log the error for debugging purposes
        log.debug('Command \'{}\' invoked by {} raised an exception\n{}'
                  .format(ctx.command, ctx.message.author, ctx.message.content), exc_info=exception)
项目:LunaBot    作者:miraai    | 项目源码 | 文件源码
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
项目:discord_selfbot    作者:silentreaper    | 项目源码 | 文件源码
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)
项目:Tobo-Cogs    作者:Tobotimus    | 项目源码 | 文件源码
def _on_command_error(self, error, ctx: commands.Context):
        """Fires when a command error occurs."""
        if not self.log_channels or not isinstance(error, commands.CommandInvokeError):
            return
        destinations = [c for c in self.bot.get_all_channels() if c.id in self.log_channels]
        destinations += [c for c in self.bot.private_channels if c.id in self.log_channels]
        error_title = "Exception in command `{}` ¯\_(?)_/¯".format(ctx.command.qualified_name)
        log = "".join(traceback.format_exception(type(error), error,
                                                    error.__traceback__))
        channel = ctx.message.channel
        embed = discord.Embed(title=error_title, colour=discord.Colour.red(), timestamp=ctx.message.timestamp)
        embed.add_field(name="Invoker", value="{}\n({})".format(ctx.message.author.mention, str(ctx.message.author)))
        embed.add_field(name="Content", value=ctx.message.content)
        _channel_disp = "Private channel" if channel.is_private else "{}\n({})".format(channel.mention, channel.name)
        embed.add_field(name="Channel", value=_channel_disp)
        if not channel.is_private:
            embed.add_field(name="Server", value=ctx.message.server.name)
        for channel in destinations:
            try:
                await self.bot.send_message(channel, embed=embed)
            except discord.errors.Forbidden: # If bot can't embed
                msg = ("Invoker: {}\n"
                       "Content: {}\n"
                       "Channel: {}".format(str(ctx.message.author), ctx.message.content, _channel_disp))
                if not channel.is_private:
                    msg += "\nServer : {}".format(ctx.message.server.name)
                await self.bot.send_message(channel, box(msg))
            for page in pagify(log):
                await self.bot.send_message(channel, box(page, lang="py"))
项目:Discord-SelfBot    作者:IgneelDxD    | 项目源码 | 文件源码
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
项目:PyMiki    作者:TheGrammarJew    | 项目源码 | 文件源码
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)
项目:PyMiki    作者:TheGrammarJew    | 项目源码 | 文件源码
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)
项目:PyMiki    作者:TheGrammarJew    | 项目源码 | 文件源码
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?')
项目:PyMiki    作者:TheGrammarJew    | 项目源码 | 文件源码
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)
项目:foxpy    作者:plusreed    | 项目源码 | 文件源码
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))
项目:PomodoroBot    作者:VicenteRD    | 项目源码 | 文件源码
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)
项目:MangoByte    作者:mdiller    | 项目源码 | 文件源码
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")
项目:DHV2    作者:DuckHunt-discord    | 项目源码 | 文件源码
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 ""))
项目:docflow    作者:strinking    | 项目源码 | 文件源码
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