如何在discord.py中为斜杠命令配置预定义可选参数?
如何在discord.py中将/alerttype命令的参数设为预定义选择项?
要把手动输入的alert_type参数改成下拉选择的预定义选项,你可以用discord.py的app_commands.Choice类来实现,这样Discord客户端会自动给用户展示可选的下拉框,用户无需手动输入,同时也能避免无效输入的情况。
修改步骤:
- 确保导入
app_commands模块(如果没导入的话) - 将原参数
alert_type: str的注解改为app_commands.Choice[str],并通过choices参数指定所有预定义选项 - 因为使用
Choice类型后,参数的值需要通过.value属性获取,所以代码中用到alert_type的地方要改成alert_type.value - 可以去掉原来的无效输入判断逻辑,因为用户只能选择指定选项,不会出现不符合要求的输入
修改后的完整代码:
from discord import app_commands # 确保导入这个模块 @bot.tree.command(name="alerttype", description="设置要接收的警报类型") @app_commands.describe(alert_type="选择警报类型") @app_commands.choices( alert_type=[ app_commands.Choice(name="The Gathering Legions", value="The Gathering Legions"), app_commands.Choice(name="World Boss", value="World Boss"), app_commands.Choice(name="The Helltide Rises", value="The Helltide Rises"), app_commands.Choice(name="All Alerts", value="All Alerts") ] ) async def alerttype(interaction: discord.Interaction, alert_type: app_commands.Choice[str]): if interaction.guild is None: await interaction.response.send_message("此命令不能在DM中使用。") return if not interaction.user.guild_permissions.manage_channels: await interaction.response.send_message("你没有执行此命令的权限。") return # 注意这里用alert_type.value获取选择的实际值 selected_type = alert_type.value c.execute("UPDATE Channels SET alert_types = ? WHERE guild_id = ?", (selected_type, interaction.guild.id)) conn.commit() await interaction.response.send_message(f"警报类型已设置为:{selected_type}。")
说明:
@app_commands.choices装饰器用来给指定参数设置可选选项,每个Choice的name是用户在Discord里看到的显示文本,value是后端实际接收的值- 参数类型改成
app_commands.Choice[str]后,必须通过.value才能拿到实际的字符串值 - 原代码中的无效输入判断可以直接删除,因为用户只能从给定选项中选择,不会传入不在列表里的值
内容的提问来源于stack exchange,提问作者awakengaming83
相关产品推荐
相关产品推荐

