当前位置: 首页>>代码示例>>Python>>正文


Python commands.CommandInvokeError方法代码示例

本文整理汇总了Python中discord.ext.commands.CommandInvokeError方法的典型用法代码示例。如果您正苦于以下问题:Python commands.CommandInvokeError方法的具体用法?Python commands.CommandInvokeError怎么用?Python commands.CommandInvokeError使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在discord.ext.commands的用法示例。


在下文中一共展示了commands.CommandInvokeError方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: process_command_invoke_error

# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import CommandInvokeError [as 别名]
def process_command_invoke_error(self, ctx: context.NabCtx, error: commands.CommandInvokeError):
        """Handles CommandInvokeError.

        This exception is raised when an exception is raised during command execution."""
        error_name = error.original.__class__.__name__
        if isinstance(error.original, errors.NetworkError):
            log.error(f"{error_name} in command {ctx.clean_prefix}{ctx.command.qualified_name}: {error.original}")
            return await ctx.error("I'm having network issues right now. Please try again in a moment.")
        log.error(f"{self.tag} Exception in command: {ctx.message.clean_content}", exc_info=error.original)
        if isinstance(error.original, discord.HTTPException):
            await ctx.error("Sorry, the message was too long to send.")
        else:
            if ctx.bot_permissions.embed_links:
                embed = discord.Embed(colour=discord.Colour(0xff1414))
                embed.set_author(name="Support Server", url="https://discord.gg/NmDvhpY",
                                 icon_url=self.bot.user.avatar_url)
                embed.set_footer(text="Please report this bug in the support server.")
                embed.add_field(name=f"{ctx.tick(False)}Command Error",
                                value=f"```py\n{error_name}: {error.original}```",
                                inline=False)
                await ctx.send(embed=embed)
            else:
                await ctx.error(f'Command error:\n```py\n{error_name}: {error.original}```') 
开发者ID:NabDev,项目名称:NabBot,代码行数:25,代码来源:core.py

示例2: on_command_error

# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import CommandInvokeError [as 别名]
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.AppInfo.owner.send(embed=embed)
            except:
                pass 
开发者ID:Der-Eddy,项目名称:discord_bot,代码行数:22,代码来源:main.py

示例3: on_command_error

# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import CommandInvokeError [as 别名]
def on_command_error(ctx, error):
    if isinstance(error, commands.CommandInvokeError):
        error = error.original

    if isinstance(error, (AvraeException, DiscordException)):
        return
    pytest.fail(f"Command raised an error: {error}")
    raise error 
开发者ID:avrae,项目名称:avrae,代码行数:10,代码来源:conftest.py

示例4: on_command_error

# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import CommandInvokeError [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

示例5: on_command_error

# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import CommandInvokeError [as 别名]
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 
开发者ID:lehnification,项目名称:Discord-SelfBot,代码行数:13,代码来源:selfbot.py

示例6: on_command_error

# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import CommandInvokeError [as 别名]
def on_command_error(self, context, error):
		if isinstance(error, commands.NoPrivateMessage):
			await context.author.send(_('This command cannot be used in private messages.'))
		elif isinstance(error, commands.DisabledCommand):
			message = _('Sorry. This command is disabled and cannot be used.')
			try:
				await context.author.send(message)
			except discord.Forbidden:
				await context.send(message)
		elif isinstance(error, commands.NotOwner):
			logger.error('%s tried to run %s but is not the owner', context.author, context.command.name)
			with contextlib.suppress(discord.HTTPException):
				await context.try_add_reaction(utils.SUCCESS_EMOJIS[False])
		elif isinstance(error, (commands.UserInputError, commands.CheckFailure)):
			await context.send(error)
		elif (
			isinstance(error, commands.CommandInvokeError)
			# abort if it's overridden
			and
				getattr(
					type(context.cog),
					'cog_command_error',
					# treat ones with no cog (e.g. eval'd ones) as being in a cog that did not override
					commands.Cog.cog_command_error)
				is commands.Cog.cog_command_error
		):
			if not isinstance(error.original, discord.HTTPException):
				logger.error('"%s" caused an exception', context.message.content)
				logger.error(''.join(traceback.format_tb(error.original.__traceback__)))
				# pylint: disable=logging-format-interpolation
				logger.error('{0.__class__.__name__}: {0}'.format(error.original))

				await context.send(_('An internal error occurred while trying to run that command.'))
			elif isinstance(error.original, discord.Forbidden):
				await context.send(_("I'm missing permissions to perform that action."))

	### Utility functions 
开发者ID:EmoteBot,项目名称:EmoteCollector,代码行数:39,代码来源:__init__.py

示例7: on_help_command_error

# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import CommandInvokeError [as 别名]
def on_help_command_error(self, ctx, error):
		if isinstance(error, commands.CommandInvokeError):
			await ctx.send(str(error.original)) 
开发者ID:EmoteBot,项目名称:EmoteCollector,代码行数:5,代码来源:meta.py

示例8: on_command_error

# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import CommandInvokeError [as 别名]
def on_command_error(self, ctx: context.NabCtx, error: commands.CommandError):
        """Handles command errors"""
        if isinstance(error, commands.errors.CommandNotFound):
            return
        elif isinstance(error, commands.CommandOnCooldown):
            await ctx.error(f"You're using this too much! "
                            f"Try again {timing.HumanDelta.from_seconds(error.retry_after).long(1)}.")
        elif isinstance(error, commands.CheckFailure):
            await self.process_check_failure(ctx, error)
        elif isinstance(error, commands.UserInputError):
            await self.process_user_input_error(ctx, error)
        elif isinstance(error, commands.CommandInvokeError):
            await self.process_command_invoke_error(ctx, error)
        else:
            log.warning(f"Unhandled command error {error.__class__.__name__}: {error}") 
开发者ID:NabDev,项目名称:NabBot,代码行数:17,代码来源:core.py

示例9: cog_command_error

# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import CommandInvokeError [as 别名]
def cog_command_error(self, ctx, error):
        if isinstance(error, commands.CommandInvokeError):
            await ctx.send(error.original)
            # The above handles errors thrown in this cog and shows them to the user.
            # This shouldn't be a problem as the only errors thrown in this cog are from `ensure_voice`
            # which contain a reason string, such as "Join a voicechannel" etc. You can modify the above
            # if you want to do things differently. 
开发者ID:Devoxin,项目名称:Lavalink.py,代码行数:9,代码来源:music.py

示例10: ensure_voice

# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import CommandInvokeError [as 别名]
def ensure_voice(self, ctx):
        """ This check ensures that the bot and command author are in the same voicechannel. """
        player = self.bot.lavalink.player_manager.create(ctx.guild.id, endpoint=str(ctx.guild.region))
        # Create returns a player if one exists, otherwise creates.
        # This line is important because it ensures that a player always exists for a guild.

        # Most people might consider this a waste of resources for guilds that aren't playing, but this is
        # the easiest and simplest way of ensuring players are created.

        # These are commands that require the bot to join a voicechannel (i.e. initiating playback).
        # Commands such as volume/skip etc don't require the bot to be in a voicechannel so don't need listing here.
        should_connect = ctx.command.name in ('play',)

        if not ctx.author.voice or not ctx.author.voice.channel:
            # Our cog_command_error handler catches this and sends it to the voicechannel.
            # Exceptions allow us to "short-circuit" command invocation via checks so the
            # execution state of the command goes no further.
            raise commands.CommandInvokeError('Join a voicechannel first.')

        if not player.is_connected:
            if not should_connect:
                raise commands.CommandInvokeError('Not connected.')

            permissions = ctx.author.voice.channel.permissions_for(ctx.me)

            if not permissions.connect or not permissions.speak:  # Check user limit too?
                raise commands.CommandInvokeError('I need the `CONNECT` and `SPEAK` permissions.')

            player.store('channel', ctx.channel.id)
            await self.connect_to(ctx.guild.id, str(ctx.author.voice.channel.id))
        else:
            if int(player.channel_id) != ctx.author.voice.channel.id:
                raise commands.CommandInvokeError('You need to be in my voicechannel.') 
开发者ID:Devoxin,项目名称:Lavalink.py,代码行数:35,代码来源:music.py

示例11: ensure_voice

# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import CommandInvokeError [as 别名]
def ensure_voice(self, ctx):
        """ This check ensures that the bot and command author are in the same voicechannel. """
        player = self.bot.lavalink.players.create(
            ctx.guild.id, endpoint=str(ctx.guild.region)
        )
        # Create returns a player if one exists, otherwise creates.

        should_connect = ctx.command.name in (
            "play"
        )  # Add commands that require joining voice to work.

        if not ctx.author.voice or not ctx.author.voice.channel:
            raise commands.CommandInvokeError("Join a voicechannel first.")

        if not player.is_connected:
            if not should_connect:
                raise commands.CommandInvokeError("Not connected.")

            permissions = ctx.author.voice.channel.permissions_for(ctx.me)

            if (
                not permissions.connect or not permissions.speak
            ):  # Check user limit too?
                raise commands.CommandInvokeError(
                    "I need the `CONNECT` and `SPEAK` permissions."
                )

            player.store("channel", ctx.channel.id)
            await self.join(ctx=ctx, channel=str(ctx.author.voice.channel.id))
        else:
            if int(player.channel_id) != ctx.author.voice.channel.id:
                raise commands.CommandInvokeError("You need to be in my voicechannel.") 
开发者ID:officialpiyush,项目名称:modmail-plugins,代码行数:34,代码来源:music.py

示例12: on_command_error

# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import CommandInvokeError [as 别名]
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) 
开发者ID:rauenzi,项目名称:discordbot.py,代码行数:11,代码来源:discordbot.py

示例13: _on_command_error

# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import CommandInvokeError [as 别名]
def _on_command_error(self, ctx, error, bypass = False):
        name, content = None, None
        raised = False

        if hasattr(ctx.command, 'on_error') or (ctx.command and hasattr(ctx.cog, f'_{ctx.command.cog_name}__error')) and not bypass:
            # Do nothing if the command/cog has its own error handler and the bypass is False
            return
        if isinstance(error, commands.CommandInvokeError) and hasattr(error, 'original'):
            error = error.original
            raised = True
        if isinstance(error, commands.CommandNotFound) or isinstance(error, commands.NotOwner):
            return
        elif isinstance(error, commands.MissingRequiredArgument):
            name = "SyntaxError"
            content = f"Command `{ctx.command.name}` missing 1 required argument: `{error.param.name}`"
        elif isinstance(error, commands.BadArgument):
            name = "TypeError"
            content = str(error.args[0])
        elif isinstance(error, commands.CommandOnCooldown):
            name = "TimeoutError"
            content = f"Command on cooldown. Retry in `{format(error.retry_after, '.2f')}s`."
        elif isinstance(error, commands.CheckFailure):
            name = "PermissionError"
            content = "Escalation failed: you are not in the sudoers file.\nThis incident will be reported"
        elif isinstance(error, discord.Forbidden) or isinstance(error, discord.HTTPException):
            # We may not be able to send an embed or even send a message at this point
            bot_member = ctx.guild.get_member(self.bot.user.id)
            can_talk = ctx.channel.permissions_for(bot_member).send_messages
            if can_talk:
                return await ctx.send(f"```An error occurred while responding:\n{error.code} - {error.text}\n\nI need following permissions:\n\nEmbed links\nAttach files\nAdd reactions```")
        elif isinstance(error, UnicodeError):
            name = "UnicodeError"
            content = "The bot failed to decode your input or a command output. Make sure you only use UTF-8"

        if name is not None:
            emb = discord.Embed(title=name, description=content, colour=self.bot.config['RED'])
            await ctx.send(embed=emb)
        elif raised:
            print(f'{time.strftime("%d/%m/%y %H:%M:%S")} | {ctx.command.qualified_name}', file=sys.stderr)
            traceback.print_tb(error.__traceback__)
            print(f'{error.__class__.__name__}: {error}', file=sys.stderr, end='\n\n')
        else:
            print(traceback.format_exc()) 
开发者ID:FrenchMasterSword,项目名称:RTFMbot,代码行数:45,代码来源:error_handler.py

示例14: on_command_error

# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import CommandInvokeError [as 别名]
def on_command_error(self, ctx, error):
        if hasattr(ctx.command, 'on_error'):
            return
        
        ignored = (commands.MissingRequiredArgument, commands.BadArgument, commands.NoPrivateMessage, commands.CheckFailure, commands.CommandNotFound, commands.DisabledCommand, commands.CommandInvokeError, commands.TooManyArguments, commands.UserInputError, commands.CommandOnCooldown, commands.NotOwner, commands.MissingPermissions, commands.BotMissingPermissions)   
        error = getattr(error, 'original', error)
        

        if isinstance(error, commands.CommandNotFound):
            return

        elif isinstance(error, commands.BadArgument):
            await ctx.send(embed=discord.Embed(color=self.bot.color).set_footer(text=f"Seems like {error}.", icon_url=ctx.author.avatar_url))

        elif isinstance(error, commands.MissingRequiredArgument):
            await ctx.send(embed=discord.Embed(color=self.bot.color).set_footer(text=f"Seems like {error}.", icon_url=ctx.author.avatar_url))

        elif isinstance(error, commands.NoPrivateMessage):
            return

        elif isinstance(error, commands.CheckFailure):
            await ctx.send(embed=discord.Embed(color=self.bot.color).set_footer(text=f"Seems like this command is thought for other users. You can't use it.", icon_url=ctx.author.avatar_url))

        elif isinstance(error, commands.DisabledCommand):
            await ctx.send(embed=discord.Embed(color=self.bot.color).set_footer(text=f"Seems like this command in disabled.", icon_url=ctx.author.avatar_url))

        elif isinstance(error, commands.CommandInvokeError):
            await ctx.send(embed=discord.Embed(color=self.bot.color).set_footer(text=f"Seems like something went wrong. Report this issue to the developer.", icon_url=ctx.author.avatar_url))

        elif isinstance(error, commands.TooManyArguments):
            await ctx.send(embed=discord.Embed(color=self.bot.color).set_footer(text=f"Seems like you gave too many arguments.", icon_url=ctx.author.avatar_url))

        elif isinstance(error, commands.UserInputError):
            await ctx.send(embed=discord.Embed(color=self.bot.color).set_footer(text=f"Seems like you did something wrong.", icon_url=ctx.author.avatar_url))

        elif isinstance(error, commands.CommandOnCooldown):
            await ctx.send(embed=discord.Embed(color=self.bot.color).set_footer(text=f"Seems like {error}.", icon_url=ctx.author.avatar_url))

        elif isinstance(error, commands.NotOwner):
            await ctx.send(embed=discord.Embed(color=self.bot.color).set_footer(text=f"Seems like you do not own this bot.", icon_url=ctx.author.avatar_url))

        elif isinstance(error, commands.MissingPermissions):
            await ctx.send(embed=discord.Embed(color=self.bot.color).set_footer(text=f"Seems like {error}.", icon_url=ctx.author.avatar_url))

        elif isinstance(error, commands.BotMissingPermissions):
            await ctx.send(embed=discord.Embed(color=self.bot.color).set_footer(text=f"Seems like {error}.", icon_url=ctx.author.avatar_url)) 
开发者ID:F4stZ4p,项目名称:DJ5n4k3,代码行数:48,代码来源:handler.py


注:本文中的discord.ext.commands.CommandInvokeError方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。