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

如何获取Discord斜杠命令中已输入item参数值以实现amount自动补全

解决方案

要实现根据已选择的item参数动态生成amount的自动补全选项,你可以通过interaction.data获取用户当前已输入的参数值,再匹配对应商品的最大购买量来生成可选数值。

步骤1:编写amount的自动补全函数

async def amount_autocomplete(interaction: discord.Interaction, current: str):
    # 从交互数据中提取用户已选的item参数
    selected_item = None
    if "options" in interaction.data:
        for option in interaction.data["options"]:
            if option["name"] == "item":
                selected_item = option["value"]
                break
    
    # 用户未选商品时返回空列表
    if not selected_item:
        return []
    
    # 匹配对应商品的最大购买量
    max_qty = None
    for item in shop_items:
        if item["name"] == selected_item:
            max_qty = item["max_quantity"]
            break
    
    # 生成1到max_qty的可选数值,支持模糊匹配用户当前输入
    if max_qty:
        return [
            app_commands.Choice(name=str(num), value=num)
            for num in range(1, max_qty + 1)
            if current in str(num)
        ]
    return []

步骤2:更新斜杠命令,绑定amount的自动补全

@bot.tree.command(name="buy", description="Buy an item from the shop")
@app_commands.autocomplete(item=item_autocomplete, amount=amount_autocomplete)
async def buy(interaction: discord.Interaction, item: str, amount: int):
    # 这里编写你的命令逻辑
    await interaction.response.send_message(f"已购买{amount}个{item}")

关键说明

  • interaction.data存储了用户当前输入的所有参数信息,遍历options即可拿到已选择的item值。
  • 若用户还未选择商品,自动补全列表会返回空,避免展示无效数值。
  • 数值选项生成时加入了模糊匹配逻辑,用户输入部分数字也能过滤出对应结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 01:40:25