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

如何在Discord斜杠命令中创建可选的物品选择列表?

解决Discord斜杠命令/inspect的物品选择与可选参数问题

1. 转换数据库结果为合法的choices格式

@app_commands.choices不接受普通字符串列表,它需要的是app_commands.Choice对象的集合。你需要把数据库查询到的物品列表转换成这种格式——通常可以给用户显示友好的名称(比如把iron_ore转成Iron Ore),同时保留后台识别用的原始值。

2. 设置参数为可选类型

要让item参数可选,需要用typing.Optional标记类型,并给参数设置默认值None,之后在函数内处理未传入参数的场景。

修改后的完整代码示例

from typing import Optional
import discord
from discord import app_commands

# 假设get_all_items_in_db()返回物品标识字符串列表,例如["iron_ore", "copper_ore"]
db_query = get_all_items_in_db()

# 将数据库结果转换为Choice对象列表
item_choices = [
    app_commands.Choice(
        name=item.replace("_", " ").title(),  # 给用户显示友好名称,如Iron Ore
        value=item  # 后台使用的原始标识,如iron_ore
    ) for item in db_query
]

@tree.command(name="inspect", description="Examine an item in more detail")
@app_commands.describe(item="Select an item to inspect")
@app_commands.choices(item=item_choices)  # 传入转换后的choices集合
async def inspect(interaction: discord.Interaction, item: Optional[str] = None):
    if not item:
        # 用户未选择物品时的处理逻辑,比如提示选择或展示个人物品
        await interaction.response.send_message("请选择一个要查看的物品!")
        return
    
    # 用户选择物品后的逻辑
    await interaction.response.send_message(f"You inspect {item}!")

额外说明

  • 如果数据库返回的是包含物品名称、标识的ORM模型对象,可以调整列表推导式,例如app_commands.Choice(name=item.display_name, value=item.id)。
  • 若物品列表会动态更新(比如新增物品),可以考虑在命令加载前重新查询数据库生成choices,或者使用autocomplete功能(适合物品数量较多的场景)。

内容的提问来源于stack exchange,提问作者UnskilledCoder

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 14:10:34