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

如何实现Discord.py中随用户变化的斜杠命令选项

实现discord.py动态斜杠命令选项

要让斜杠命令的选项根据调用用户动态变化,你需要替换静态的@app_commands.choices装饰器,改用**自动补全(autocomplete)**功能。以下是具体实现步骤和示例:

核心思路

通过@app_commands.autocomplete()为目标参数绑定一个动态生成选项的函数,在这个函数里根据调用命令的用户(interaction.user)返回对应的选项列表。

示例代码

from discord import Interaction
from discord.app_commands import command, describe, autocomplete, Choice

# 定义自动补全函数,根据用户生成不同的水果选项
async def fruit_autocomplete(interaction: Interaction, current: str) -> list[Choice[int]]:
    # 可根据用户ID、角色、权限等条件返回不同选项
    # 示例:管理员用户获得额外选项,普通用户仅获得基础选项
    is_admin = any(role.name == "管理员" for role in interaction.user.roles)
    
    base_fruits = [
        Choice(name='apple', value=1),
        Choice(name='banana', value=2),
        Choice(name='cherry', value=3),
    ]
    admin_extra = [Choice(name='durian', value=4)]
    
    return base_fruits + admin_extra if is_admin else base_fruits

@app_commands.command()
@app_commands.describe(fruits='fruits to choose from')
# 给fruits参数绑定自动补全函数
@app_commands.autocomplete(fruits=fruit_autocomplete)
async def fruit(interaction: Interaction, fruits: int):
    # 根据value映射回水果名称(也可直接将value设为名称简化逻辑)
    fruit_map = {1: 'apple', 2: 'banana', 3: 'cherry', 4: 'durian'}
    await interaction.response.send_message(f'Your favourite fruit is {fruit_map[fruits]}.')

关键说明

  1. 自动补全函数规范:必须接收interaction和current两个参数,返回list[Choice]类型。current是用户当前输入的内容,可用于实现模糊匹配(比如仅返回包含用户输入字符串的选项)。
  2. 参数类型调整:原代码中的fruits: Choice[int]需改为fruits: int,因为自动补全是为基础数据类型(int/str等)提供可选值。
  3. 动态逻辑扩展:你可以基于用户的任意属性生成选项,比如给特定ID的用户专属选项、根据用户所在服务器返回定制化列表等。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 03:34:58