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

如何在Python的Discord机器人中实现命令输入时显示商店物品列表?

实现Discord机器人delete命令参数自动补全的方法

要让delete命令的name参数输入时显示商店物品列表,你需要用到discord.py的**自动补全(Autocomplete)**功能,具体实现步骤如下:

1. 编写自动补全函数

定义一个异步函数,返回你的商店物品列表作为补全选项。假设你的商店物品存储在shop_items变量中(比如shop_items = ["苹果", "面包", "牛奶"]):

async def item_autocomplete(interaction: discord.Interaction, current: str) -> list[app_commands.Choice[str]]:
    # 可选:过滤出包含当前输入内容的物品,提升输入体验
    filtered_items = [item for item in shop_items if current.lower() in item.lower()]
    # Discord限制补全选项最多25个,做切片处理
    return [app_commands.Choice(name=item, value=item) for item in filtered_items[:25]]

2. 为命令参数绑定自动补全

修改你的delete命令,给name参数绑定刚才写的补全函数:

@app_commands.command(name="delete", description="delete an item from shop")
@app_commands.autocomplete(name=item_autocomplete)
async def delete(self, interaction: discord.Interaction, name: str):
    # 这里编写删除物品的业务逻辑
    await interaction.response.send_message(f"已成功删除物品:{name}")

额外注意

  • 如果商店物品是从数据库、文件等动态来源获取的,直接在补全函数里读取即可,无需硬编码
  • 补全函数必须是异步的,且参数固定为interaction和current(current代表用户当前输入的内容)

内容的提问来源于stack exchange,提问作者French fry with a fade

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 11:33:18