如何在discord.py命令自动补全时显示无效参数错误?
在discord.py中处理无效参数并显示错误提示
方法一:自定义转换器(推荐用于自动补全场景)
自定义转换器能在参数解析阶段直接验证输入,抛出明确错误,适合和自动补全配合使用。以角色参数为例:
from discord.ext import commands import discord class ValidRole(commands.Converter): async def convert(self, ctx, argument): try: # 复用内置的角色转换器尝试匹配 role = await commands.RoleConverter().convert(ctx, argument) return role except commands.BadArgument: # 抛出带自定义提示的错误 raise commands.BadArgument(f"`{argument}` 不是有效的角色") # 带自动补全的Slash命令示例 @bot.tree.command(name="test_role") async def test_role(interaction: discord.Interaction, role: str): try: # 用自定义转换器验证参数 valid_role = await ValidRole().convert(interaction, role) await interaction.response.send_message(f"你选择了角色:{valid_role.name}") except commands.BadArgument as e: # 发送仅用户可见的错误提示 await interaction.response.send_message(str(e), ephemeral=True) # 自动补全逻辑 @test_role.autocomplete("role") async def role_autocomplete(interaction: discord.Interaction, current: str): roles = interaction.guild.roles return [ discord.app_commands.Choice(name=role.name, value=role.name) for role in roles if current.lower() in role.name.lower() ]
方法二:命令错误处理装饰器(适合传统前缀命令)
如果是前缀命令,可以用错误装饰器捕获参数错误:
@bot.command() async def add_role(ctx, role: discord.Role): await ctx.send(f"将为你添加角色:{role.name}") @add_role.error async def add_role_error(ctx, error): if isinstance(error, commands.BadArgument): # 提取无效参数并给出提示 invalid_arg = error.args[0].split(" ")[-1] await ctx.send(f"`{invalid_arg}` 不是有效的角色")
方法三:手动验证参数(轻量场景)
不想用转换器的话,也可以在命令逻辑里直接校验输入:
@bot.tree.command(name="assign_role") async def assign_role(interaction: discord.Interaction, role_name: str): target_role = discord.utils.get(interaction.guild.roles, name=role_name) if not target_role: await interaction.response.send_message(f"`{role_name}` 不是有效的角色", ephemeral=True) return # 执行后续逻辑 await interaction.response.send_message(f"已为你分配角色:{target_role.name}") @assign_role.autocomplete("role_name") async def role_name_autocomplete(interaction: discord.Interaction, current: str): roles = interaction.guild.roles return [ discord.app_commands.Choice(name=role.name, value=role.name) for role in roles if current.lower() in role.name.lower() ]
实用提示
- 用
ephemeral=True发送错误提示,仅触发命令的用户能看到,避免频道刷屏 - 自定义转换器可以复用在多个命令中,统一参数校验逻辑
- Slash命令要求3秒内给出响应,错误提示要及时发送
内容的提问来源于stack exchange,提问作者Kaghra
相关产品推荐
相关产品推荐

