You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在discord.py中为斜杠命令的参数添加可选选项?

原生discord.py实现命令参数可选分类选项的思路示例

核心思路

使用discord.py原生提供的app_commands.Choice和app_commands.Parameter类定义参数的可选选项,无需依赖外部库。

实现步骤与代码示例

  1. 你的代码已导入app_commands,直接基于现有代码修改命令参数即可
  2. 两种实现方式:
    • 方式一:参数类型为str,直接获取选中的实际值
      @tree.command(name='test')
      async def test(interaction: discord.Interaction, 
                     option: str = app_commands.Parameter(
                         choices=[
                             app_commands.Choice(name="测试选项1", value="test1"),
                             app_commands.Choice(name="测试选项2", value="test2")
                         ]
                     )):
          # 此时option直接等于用户选择的value(如"test1"或"test2")
          await interaction.response.send_message(f"你选择了: {option}")
      
    • 方式二:参数类型为app_commands.Choice[str],可同时获取显示名称和实际值
      @tree.command(name='test')
      async def test(interaction: discord.Interaction, 
                     option: app_commands.Choice[str] = app_commands.Parameter(
                         choices=[
                             app_commands.Choice(name="测试选项1", value="test1"),
                             app_commands.Choice(name="测试选项2", value="test2")
                         ]
                     )):
          # 通过option.name获取界面显示的名称,option.value获取代码用的实际值
          await interaction.response.send_message(f"你选择了[{option.name}]: {option.value}")
      

说明

  • name是用户在Discord命令界面看到的选项名称,value是代码中实际接收的对应值,两者可自定义,不必完全一致
  • 命令同步后,用户输入/test时,参数option会自动弹出下拉选择框

内容的提问来源于stack exchange,提问作者Black'n'White

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 17:30:54