當前位置: 首頁>>代碼示例>>Python>>正文


Python commands.CommandNotFound方法代碼示例

本文整理匯總了Python中discord.ext.commands.CommandNotFound方法的典型用法代碼示例。如果您正苦於以下問題:Python commands.CommandNotFound方法的具體用法?Python commands.CommandNotFound怎麽用?Python commands.CommandNotFound使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在discord.ext.commands的用法示例。


在下文中一共展示了commands.CommandNotFound方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: on_command_error

# 需要導入模塊: from discord.ext import commands [as 別名]
# 或者: from discord.ext.commands import CommandNotFound [as 別名]
def on_command_error(ctx, error):

    send_help = (commands.MissingRequiredArgument, commands.BadArgument, commands.TooManyArguments, commands.UserInputError)

    if isinstance(error, commands.CommandNotFound):  # fails silently
        pass

    elif isinstance(error, send_help):
        _help = await send_cmd_help(ctx)
        await ctx.send(embed=_help)

    elif isinstance(error, commands.CommandOnCooldown):
        await ctx.send(f'This command is on cooldown. Please wait {error.retry_after:.2f}s')

    elif isinstance(error, commands.MissingPermissions):
        await ctx.send('You do not have the permissions to use this command.')
    # If any other error occurs, prints to console.
    else:
        print(''.join(traceback.format_exception(type(error), error, error.__traceback__))) 
開發者ID:cree-py,項目名稱:RemixBot,代碼行數:21,代碼來源:bot.py

示例2: on_command_error

# 需要導入模塊: from discord.ext import commands [as 別名]
# 或者: from discord.ext.commands import CommandNotFound [as 別名]
def on_command_error(self, ctx, exception):
        exc_class = exception.__class__
        if exc_class in (commands.CommandNotFound, commands.NotOwner):
            return

        exc_table = {
            commands.MissingRequiredArgument: f"{WARNING} The required arguments are missing for this command!",
            commands.NoPrivateMessage: f"{WARNING} This command cannot be used in PM's!",
            commands.BadArgument: f"{WARNING} A bad argument was passed, please check if your arguments are correct!",
            IllegalAction: f"{WARNING} A node error has occurred: `{getattr(exception, 'msg', None)}`",
            CustomCheckFailure: getattr(exception, "msg", None) or "None"
        }

        if exc_class in exc_table.keys():
            await ctx.send(exc_table[exc_class])
        else:
            await super().on_command_error(ctx, exception) 
開發者ID:initzx,項目名稱:rewrite,代碼行數:19,代碼來源:bot.py

示例3: on_command_error

# 需要導入模塊: from discord.ext import commands [as 別名]
# 或者: from discord.ext.commands import CommandNotFound [as 別名]
def on_command_error(self, ctx, error):
        """ Send help message when a mis-entered command is received. """
        if type(error) is commands.CommandNotFound:
            # Get Levenshtein distance from commands
            in_cmd = ctx.invoked_with
            bot_cmds = list(self.bot.commands)
            lev_dists = [lev.distance(in_cmd, str(cmd)) / max(len(in_cmd), len(str(cmd))) for cmd in bot_cmds]
            lev_min = min(lev_dists)

            # Prep help message title
            embed_title = f'**```{ctx.message.content}```** is not valid!'
            prefix = self.bot.command_prefix
            prefix = prefix[0] if prefix is not str else prefix

            # Make suggestion if lowest Levenshtein distance is under threshold
            if lev_min <= 0.5:
                embed_title += f' Did you mean `{prefix}{bot_cmds[lev_dists.index(lev_min)]}`?'
            else:
                embed_title += f' Use `{prefix}help` for a list of commands'

            embed = discord.Embed(title=embed_title, color=self.color)
            await ctx.send(embed=embed) 
開發者ID:cameronshinn,項目名稱:csgo-queue-bot,代碼行數:24,代碼來源:help.py

示例4: on_command_error

# 需要導入模塊: from discord.ext import commands [as 別名]
# 或者: from discord.ext.commands import CommandNotFound [as 別名]
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) 
開發者ID:rauenzi,項目名稱:discordbot.py,代碼行數:26,代碼來源:meta.py

示例5: on_command_error

# 需要導入模塊: from discord.ext import commands [as 別名]
# 或者: from discord.ext.commands import CommandNotFound [as 別名]
def on_command_error(self, ctx, error):
        """Command error handler"""
        manager = MessageManager(ctx)

        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.send_message("You can't use that command in a private message")

        elif isinstance(error, commands.CheckFailure):
            await manager.send_message("You don't have the required permissions to do that")

        elif isinstance(error, commands.CommandOnCooldown):
            await manager.send_message(error)

        # Non Discord.py errors
        elif isinstance(error, commands.CommandInvokeError):
            if isinstance(error.original, discord.errors.Forbidden):
                pass
            elif isinstance(error.original, asyncio.TimeoutError):
                await manager.send_private_message("I'm not sure where you went. We can try this again later.")
            else:
                raise error

        else:
            raise error

        await manager.clean_messages() 
開發者ID:jgayfer,項目名稱:spirit,代碼行數:37,代碼來源:core.py

示例6: on_command_error

# 需要導入模塊: from discord.ext import commands [as 別名]
# 或者: from discord.ext.commands import CommandNotFound [as 別名]
def on_command_error(ctx, error):
    if isinstance(error, commands.CommandNotFound):
        return
    if isinstance(error, commands.DisabledCommand):
        await ctx.send(Language.get("bot.errors.disabled_command", ctx))
        return
    if isinstance(error, checks.owner_only):
        await ctx.send(Language.get("bot.errors.owner_only", ctx))
        return
    if isinstance(error, checks.dev_only):
        await ctx.send(Language.get("bot.errors.dev_only", ctx))
        return
    if isinstance(error, checks.support_only):
        await ctx.send(Language.get("bot.errors.support_only", ctx))
        return
    if isinstance(error, checks.not_nsfw_channel):
        await ctx.send(Language.get("bot.errors.not_nsfw_channel", ctx))
        return
    if isinstance(error, checks.not_guild_owner):
        await ctx.send(Language.get("bot.errors.not_guild_owner", ctx))
        return
    if isinstance(error, checks.no_permission):
        await ctx.send(Language.get("bot.errors.no_permission", ctx))
        return
    if isinstance(error, commands.NoPrivateMessage):
        await ctx.send(Language.get("bot.errors.no_private_message", ctx))
        return
    if isinstance(ctx.channel, discord.DMChannel):
        await ctx.send(Language.get("bot.errors.command_error_dm_channel", ctx))
        return

    #In case the bot failed to send a message to the channel, the try except pass statement is to prevent another error
    try:
        await ctx.send(Language.get("bot.errors.command_error", ctx).format(error))
    except:
        pass
    log.error("An error occured while executing the {} command: {}".format(ctx.command.qualified_name, error)) 
開發者ID:ZeroEpoch1969,項目名稱:RubyRoseBot,代碼行數:39,代碼來源:bot.py

示例7: on_command_error

# 需要導入模塊: from discord.ext import commands [as 別名]
# 或者: from discord.ext.commands import CommandNotFound [as 別名]
def on_command_error(ctx, error):
    error_to_skip = [CommandNotFound, MissingRequiredArgument]

    for error_type in error_to_skip:
        if isinstance(error, error_type):
            return

    raise error

# Starting the bot. 
開發者ID:DarkStar7471,項目名稱:THM-Bot,代碼行數:12,代碼來源:main.py

示例8: on_command_error

# 需要導入模塊: from discord.ext import commands [as 別名]
# 或者: from discord.ext.commands import CommandNotFound [as 別名]
def on_command_error(ctx, error):
    if isinstance(error, commands.CommandNotFound):
        return
    if isinstance(error, commands.MissingRequiredArgument):
        await ctx.send("Missing a required argument.  Do >help")
    if isinstance(error, commands.MissingPermissions):
        await ctx.send("You do not have the appropriate permissions to run this command.")
    if isinstance(error, commands.BotMissingPermissions):
        await ctx.send("I don't have sufficient permissions!")
    else:
        print("error not caught")
        print(error) 
開發者ID:NullPxl,項目名稱:NullCTF,代碼行數:14,代碼來源:nullctf.py

示例9: on_command_error

# 需要導入模塊: from discord.ext import commands [as 別名]
# 或者: from discord.ext.commands import CommandNotFound [as 別名]
def on_command_error(self, context, exception):
        if isinstance(exception, commands.BadUnionArgument):
            msg = "Could not find the specified " + human_join(
                [c.__name__ for c in exception.converters]
            )
            await context.trigger_typing()
            await context.send(embed=discord.Embed(color=self.error_color, description=msg))

        elif isinstance(exception, commands.BadArgument):
            await context.trigger_typing()
            await context.send(
                embed=discord.Embed(color=self.error_color, description=str(exception))
            )
        elif isinstance(exception, commands.CommandNotFound):
            logger.warning("CommandNotFound: %s", exception)
        elif isinstance(exception, commands.MissingRequiredArgument):
            await context.send_help(context.command)
        elif isinstance(exception, commands.CheckFailure):
            for check in context.command.checks:
                if not await check(context):
                    if hasattr(check, "fail_msg"):
                        await context.send(
                            embed=discord.Embed(color=self.error_color, description=check.fail_msg)
                        )
                    if hasattr(check, "permission_level"):
                        corrected_permission_level = self.command_perm(
                            context.command.qualified_name
                        )
                        logger.warning(
                            "User %s does not have permission to use this command: `%s` (%s).",
                            context.author.name,
                            context.command.qualified_name,
                            corrected_permission_level.name,
                        )
            logger.warning("CheckFailure: %s", exception)
        else:
            logger.error("Unexpected exception:", exc_info=exception) 
開發者ID:kyb3r,項目名稱:modmail,代碼行數:39,代碼來源:bot.py

示例10: on_command_error

# 需要導入模塊: from discord.ext import commands [as 別名]
# 或者: from discord.ext.commands import CommandNotFound [as 別名]
def on_command_error(self, ctx, error):
        # The local handlers so far only catch bad arguments so we still
        # want to print the rest
        if (isinstance(error, commands.BadArgument) or
            isinstance(error, commands.errors.CheckFailure) or
            isinstance(error, commands.errors.MissingAnyRole) or
            isinstance(error, commands.errors.MissingRequiredArgument)) and\
           hasattr(ctx.command, 'on_error'):
            return

        if isinstance(error, commands.UserInputError):
            await ctx.send("Chyba v inputu")
            return

        if isinstance(error, commands.CommandNotFound):
            prefix = ctx.message.content[:1]
            if prefix not in config.ignored_prefixes:
                await ctx.send(messages.no_such_command)
            return

        if isinstance(error, commands.CommandOnCooldown):
            await ctx.send(utils.fill_message("spamming", user=ctx.author.id))
            return

        output = 'Ignoring exception in command {}:\n'.format(ctx.command)
        output += ''.join(traceback.format_exception(type(error),
                                                     error,
                                                     error.__traceback__))
        channel = self.bot.get_channel(config.bot_dev_channel)
        print(output)
        output = utils.cut_string(output, 1900)
        if channel is not None:
            for message in output:
                await channel.send("```\n" + message + "\n```") 
開發者ID:Toaster192,項目名稱:rubbergod,代碼行數:36,代碼來源:base.py

示例11: on_command_error

# 需要導入模塊: from discord.ext import commands [as 別名]
# 或者: from discord.ext.commands import CommandNotFound [as 別名]
def on_command_error(ctx, e):

    if hasattr(ctx.cog, 'qualified_name') and ctx.cog.qualified_name == "Admin":
        # Admin cog handles the errors locally
        return

    if SETTINGS.log_errors:
        ignored_exceptions = (
            commands.MissingRequiredArgument,
            commands.CommandNotFound,
            commands.DisabledCommand,
            commands.BadArgument,
            commands.NoPrivateMessage,
            commands.CheckFailure,
            commands.CommandOnCooldown,
            commands.MissingPermissions,
            discord.errors.Forbidden,
        )

        if isinstance(e, ignored_exceptions):
            # log warnings
            # logger.warning(f'{type(e).__name__}: {e}\n{"".join(traceback.format_tb(e.__traceback__))}')
            return

        # log error
        logger.error(f'{type(e).__name__}: {e}\n{"".join(traceback.format_tb(e.__traceback__))}')
        traceback.print_exception(type(e), e, e.__traceback__, file=sys.stderr)

        if SETTINGS.msg_errors:
            # send discord message for unexpected errors
            e = discord.Embed(
                title=f"Error With command: {ctx.command.name}",
                description=f"```py\n{type(e).__name__}: {str(e)}\n```\n\nContent:{ctx.message.content}"
                            f"\n\tServer: {ctx.message.server}\n\tChannel: <#{ctx.message.channel}>"
                            f"\n\tAuthor: <@{ctx.message.author}>",
                timestamp=ctx.message.timestamp
            )
            await ctx.send(bot.owner, embed=e)

        # if SETTINGS.mode == 'development':
        raise e 
開發者ID:matnad,項目名稱:pollmaster,代碼行數:43,代碼來源:pollmaster.py

示例12: on_command_error

# 需要導入模塊: from discord.ext import commands [as 別名]
# 或者: from discord.ext.commands import CommandNotFound [as 別名]
def on_command_error(self, ctx, exc):
        if not isinstance(exc, (commands.CommandNotFound, commands.NotOwner)):
            self.log.critical(''.join(traceback.format_exception(type(exc), exc, exc.__traceback__)))
            # await ctx.send("check logs") 
開發者ID:matnad,項目名稱:pollmaster,代碼行數:6,代碼來源:bot.py

示例13: on_command_error

# 需要導入模塊: from discord.ext import commands [as 別名]
# 或者: from discord.ext.commands import CommandNotFound [as 別名]
def on_command_error(self, context, exception):
        if isinstance(exception, commands.NoPrivateMessage):
            await context.send('{}, This command cannot be used in DMs.'.format(context.author.mention))
        elif isinstance(exception, commands.UserInputError):
            await context.send('{}, {}'.format(context.author.mention, self.format_error(context, exception)))
        elif isinstance(exception, commands.NotOwner):
            await context.send('{}, {}'.format(context.author.mention, exception.args[0]))
        elif isinstance(exception, commands.MissingPermissions):
            permission_names = [name.replace('guild', 'server').replace('_', ' ').title() for name in exception.missing_perms]
            await context.send('{}, you need {} permissions to run this command!'.format(
                context.author.mention, utils.pretty_concat(permission_names)))
        elif isinstance(exception, commands.BotMissingPermissions):
            permission_names = [name.replace('guild', 'server').replace('_', ' ').title() for name in exception.missing_perms]
            await context.send('{}, I need {} permissions to run this command!'.format(
                context.author.mention, utils.pretty_concat(permission_names)))
        elif isinstance(exception, commands.CommandOnCooldown):
            await context.send(
                '{}, That command is on cooldown! Try again in {:.2f}s!'.format(context.author.mention, exception.retry_after))
        elif isinstance(exception, (commands.CommandNotFound, InvalidContext)):
            pass  # Silent ignore
        else:
            await context.send('```\n%s\n```' % ''.join(traceback.format_exception_only(type(exception), exception)).strip())
            if isinstance(context.channel, discord.TextChannel):
                DOZER_LOGGER.error('Error in command <%d> (%d.name!r(%d.id) %d(%d.id) %d(%d.id) %d)',
                                   context.command, context.guild, context.guild, context.channel, context.channel,
                                   context.author, context.author, context.message.content)
            else:
                DOZER_LOGGER.error('Error in command <%d> (DM %d(%d.id) %d)', context.command, context.channel.recipient,
                                   context.channel.recipient, context.message.content)
            DOZER_LOGGER.error(''.join(traceback.format_exception(type(exception), exception, exception.__traceback__))) 
開發者ID:FRCDiscord,項目名稱:Dozer,代碼行數:32,代碼來源:bot.py

示例14: on_command_error

# 需要導入模塊: from discord.ext import commands [as 別名]
# 或者: from discord.ext.commands import CommandNotFound [as 別名]
def on_command_error(self, ctx, error):
        # Try provide some user feedback instead of logging all errors.

        if isinstance(error, commands.CommandNotFound):
            return  # No need to log unfound commands anywhere or return feedback

        if isinstance(error, commands.MissingRequiredArgument):
            # Missing arguments are likely human error so do not need logging
            parameter_name = error.param.name
            return await ctx.send(
                f"\N{NO ENTRY SIGN} Required argument {parameter_name} was missing"
            )
        elif isinstance(error, commands.CheckFailure):
            return await ctx.send(
                "\N{NO ENTRY SIGN} You do not have permission to use that command"
            )
        elif isinstance(error, commands.CommandOnCooldown):
            retry_after = round(error.retry_after)
            return await ctx.send(
                f"\N{HOURGLASS} Command is on cooldown, try again after {retry_after} seconds"
            )

        # All errors below this need reporting and so do not return

        if isinstance(error, commands.ArgumentParsingError):
            # Provide feedback & report error
            await ctx.send(
                "\N{NO ENTRY SIGN} An issue occurred while attempting to parse an argument"
            )
        elif isinstance(error, commands.BadArgument):
            await ctx.send("\N{NO ENTRY SIGN} Conversion of an argument failed")
        else:
            await ctx.send(
                "\N{NO ENTRY SIGN} An error occured during execution, the error has been reported."
            )

        extra_context = {
            "discord_info": {
                "Channel": ctx.channel.mention,
                "User": ctx.author.mention,
                "Command": ctx.message.content,
            }
        }

        if ctx.guild is not None:
            # We are NOT in a DM
            extra_context["discord_info"]["Message"] = (
                f"[{ctx.message.id}](https://discordapp.com/channels/"
                f"{ctx.guild.id}/{ctx.channel.id}/{ctx.message.id})"
            )
        else:
            extra_context["discord_info"]["Message"] = f"{ctx.message.id} (DM)"

        self.bot.log.exception(error, extra=extra_context) 
開發者ID:CyberDiscovery,項目名稱:cyberdisc-bot,代碼行數:56,代碼來源:general.py

示例15: process_commands

# 需要導入模塊: from discord.ext import commands [as 別名]
# 或者: from discord.ext.commands import CommandNotFound [as 別名]
def process_commands(self, message):
        if message.author.bot:
            return

        if isinstance(message.channel, discord.DMChannel):
            return await self.process_dm_modmail(message)

        if message.content.startswith(self.prefix):
            cmd = message.content[len(self.prefix) :].strip()

            # Process snippets
            if cmd in self.snippets:
                snippet = self.snippets[cmd]
                message.content = f"{self.prefix}freply {snippet}"

        ctxs = await self.get_contexts(message)
        for ctx in ctxs:
            if ctx.command:
                if not any(
                    1 for check in ctx.command.checks if hasattr(check, "permission_level")
                ):
                    logger.debug(
                        "Command %s has no permissions check, adding invalid level.",
                        ctx.command.qualified_name,
                    )
                    checks.has_permissions(PermissionLevel.INVALID)(ctx.command)

                await self.invoke(ctx)
                continue

            thread = await self.threads.find(channel=ctx.channel)
            if thread is not None:
                if self.config.get("anon_reply_without_command"):
                    await thread.reply(message, anonymous=True)
                elif self.config.get("reply_without_command"):
                    await thread.reply(message)
                else:
                    await self.api.append_log(message, type_="internal")
            elif ctx.invoked_with:
                exc = commands.CommandNotFound(
                    'Command "{}" is not found'.format(ctx.invoked_with)
                )
                self.dispatch("command_error", ctx, exc) 
開發者ID:kyb3r,項目名稱:modmail,代碼行數:45,代碼來源:bot.py


注:本文中的discord.ext.commands.CommandNotFound方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。