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


Python commands.UserInputError方法代码示例

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


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

示例1: on_command_error

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

示例3: handle_aliases

# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import UserInputError [as 别名]
def handle_aliases(self, message):
        prefix = await self.bot.get_server_prefix(message)
        if message.content.startswith(prefix):
            alias = message.content[len(prefix):].split(' ')[0]
            execution_type = "alias"
            if message.guild:
                the_alias = await self.bot.mdb.aliases.find_one({"owner": str(message.author.id), "name": alias})
                if the_alias is None:
                    the_alias = await self.bot.mdb.servaliases.find_one(
                        {"server": str(message.guild.id), "name": alias})
                    execution_type = "servalias"
            else:
                the_alias = await self.bot.mdb.aliases.find_one({"owner": str(message.author.id), "name": alias})

            if the_alias:
                await self.bot.mdb.analytics_alias_events.insert_one(
                    {"type": execution_type, "object_id": the_alias['_id'], "timestamp": datetime.datetime.utcnow()}
                )

                command = the_alias['commands']
                try:
                    message.content = await self.handle_alias_arguments(command, message)
                except UserInputError as e:
                    return await message.channel.send(f"Invalid input: {e}")
                ctx = await self.bot.get_context(message)
                char = None
                try:
                    char = await Character.from_ctx(ctx)
                except NoCharacter:
                    pass

                try:
                    if char:
                        message.content = await char.parse_cvars(message.content, ctx)
                    else:
                        message.content = await helpers.parse_no_char(message.content, ctx)
                except EvaluationError as err:
                    return await helpers.handle_alias_exception(ctx, err)
                except Exception as e:
                    return await message.channel.send(e)
                await self.bot.process_commands(message) 
开发者ID:avrae,项目名称:avrae,代码行数:43,代码来源:customization.py

示例4: on_command_error

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

示例5: on_command_error

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

示例6: convert

# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import UserInputError [as 别名]
def convert(self, ctx, argument):
		converted = []
		view = StringView(argument)
		while not view.eof:
			args = []
			for converter in self.converters:
				view.skip_ws()
				arg = view.get_quoted_word()
				if arg is None:
					raise commands.UserInputError(_('Not enough arguments.'))
				args.append(await self._do_conversion(ctx, converter, arg))
			converted.append(tuple(args))
		return converted 
开发者ID:EmoteBot,项目名称:EmoteCollector,代码行数:15,代码来源:converter.py

示例7: modcore

# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import UserInputError [as 别名]
def modcore(self, ctx, player: str = None):
        if player is None:
            return await ctx.error("You must provide a player to check their profile")
        uuid = await self.bot.get_cog('Sk1er Discord').name_to_uuid(player)
        if not uuid:
            raise commands.UserInputError('Couldn\'t find that player\'s UUID')
        route = Route(
            'GET',
            f'/profile/{uuid}'
        )
        try:
            profile = await self.bot.http.modcore.request(route)
        except Exception:
            return await ctx.error(f'Failed to fetch profile')
        purchases = [self.modcoref(c) for c, e in profile.get('purchase_profile', {'No Cosmetics': True}).items() if e]
        for c, s in profile.get('cosmetic_settings', {}).items():
            if s != {} and s.get('enabled', False):
                if 'id' in s:
                    cid = s['id']
                    purchases = [p.replace(self.modcoref(c), f'**[{self.modcoref(c)}](https://api.modcore.sk1er.club/serve/{"cape" if "CAPE" in c else "skin"}/{"static" if "STATIC" in c else "dynamic"}/{cid})**') for p in purchases]
        purchases = ', '.join([i for i in purchases])
        embed = discord.Embed(title=f'{player}\'s Modcore Profile', color=ctx.author.color)
        embed.add_field(name='UUID', value=uuid, inline=False)
        embed.add_field(name='Enabled Cosmetics', value=purchases or 'No Cosmetics', inline=False)
        embed.add_field(name='Status' if profile['online'] else 'Last Seen', value=profile.get('status', None) or '¯\_(ツ)_/¯', inline=False)
        return await ctx.send(embed=embed) 
开发者ID:FireDiscordBot,项目名称:bot,代码行数:28,代码来源:modcore.py

示例8: on_command_error

# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import UserInputError [as 别名]
def on_command_error(self, context: commands.Context, exception: DiscordException) -> None:
        """Check command errors for UserInputError and reset the cooldown if thrown."""
        if isinstance(exception, commands.UserInputError):
            context.command.reset_cooldown(context)
        else:
            await super().on_command_error(context, exception) 
开发者ID:python-discord,项目名称:seasonalbot,代码行数:8,代码来源:bot.py

示例9: on_command_error

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

示例10: process_user_input_error

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

        These are exceptions raised due to the user providing invalid or incorrect input."""
        if isinstance(error, commands.MissingRequiredArgument):
            await ctx.error(f"The correct syntax is: `{ctx.clean_prefix}{ctx.command.qualified_name} {ctx.usage}`.\n"
                            f"Try `{ctx.clean_prefix}help {ctx.command.qualified_name}` for more info.")
        elif isinstance(error, commands.BadArgument):
            _type, param = self.parse_bad_argument(str(error))
            # Making these errors more understandable.
            if _type == "int":
                error = f"Parameter `{param}` must be numeric."
            await ctx.error(f"{error}\nTry `{ctx.clean_prefix}help {ctx.command.qualified_name}` for more info.") 
开发者ID:NabDev,项目名称:NabBot,代码行数:15,代码来源:core.py

示例11: on_command_error

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

示例12: on_command_error

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

示例13: on_command_error

# 需要导入模块: from discord.ext import commands [as 别名]
# 或者: from discord.ext.commands import UserInputError [as 别名]
def on_command_error(self, ctx, error):
        """Task when an error occurs."""

        if isinstance(error, commands.CommandNotFound):
            return logger.info(f"{ctx.author} used {ctx.message.content} "
                               f"but nothing was found.")

        if isinstance(error, commands.MissingRequiredArgument):
            logger.info(f"{ctx.author} called {ctx.message.content} and "
                        f"triggered MissingRequiredArgument error.")
            return await ctx.send(f"`{error.param}` is a required argument.")

        if isinstance(error, commands.CheckFailure):
            logger.info(f"{ctx.author} called {ctx.message.content} and triggered"
                        f" CheckFailure error.")
            return await ctx.send("You do not have permission to use this command!")

        if isinstance(error, (commands.UserInputError, commands.BadArgument)):
            logger.info(f"{ctx.author} called {ctx.message.content} and triggered"
                        f" UserInputError error.")
            return await ctx.send("Invalid arguments.")

        if isinstance(error, commands.CommandOnCooldown):
            logger.info(f"{ctx.author} called {ctx.message.content} and"
                        f" triggered ComamndOnCooldown error.")
            return await ctx.send(f"Command is on cooldown!"
                                  f" Please retry after `{error.retry_after}`")

        if isinstance(error, commands.BotMissingPermissions):
            logger.info(f"{ctx.author} called {ctx.message.content} and triggered"
                        f" BotMissingPermissions error.")
            embed = discord.Embed()
            embed.colour = discord.Colour.blue()
            title = "The bot lacks the following permissions to execute the command:"
            embed.title = title
            embed.description = ""
            for perm in error.missing_perms:
                embed.description += str(perm)
            return await ctx.send(embed=embed)

        if isinstance(error, commands.DisabledCommand):
            logger.info(f"{ctx.author} called {ctx.message.content} and"
                        f" triggered DisabledCommand error.")
            return await ctx.send("The command has been disabled!")

        logger.warning(f"{ctx.author} called {ctx.message.content} and"
                       f" triggered the following error:\n {error}") 
开发者ID:python-discord,项目名称:code-jam-5,代码行数:49,代码来源:error_handler.py


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