如何在discord.py中为application commands添加命令选项列表?
在discord.py中为应用命令添加选项列表
要实现用户调用命令时显示可选功能列表,你需要使用discord.py v2.x版本的app_commands模块,通过@app_commands.choices()装饰器定义选项。以下是针对customize命令的具体实现:
完整代码示例
import discord from discord import app_commands # 初始化客户端和命令树 intents = discord.Intents.default() client = discord.Client(intents=intents) tree = app_commands.CommandTree(client) # 定义customize命令及选项 @tree.command(name="customize", description="自定义你的用户体验功能") @app_commands.choices(feature=[ app_commands.Choice(name="开启深色模式", value="dark_mode"), app_commands.Choice(name="开启通知提醒", value="notification_alerts"), app_commands.Choice(name="设置自定义前缀", value="custom_prefix"), ]) async def customize(interaction: discord.Interaction, feature: str): # 根据用户选择执行对应逻辑 match feature: case "dark_mode": await interaction.response.send_message("已为你开启深色模式!") case "notification_alerts": await interaction.response.send_message("已为你开启通知提醒!") case "custom_prefix": await interaction.response.send_message("请回复你想要设置的自定义前缀:") # 此处可添加后续输入处理逻辑 # 登录后同步命令 @client.event async def on_ready(): await tree.sync() # 全局同步,如需服务器同步可指定guild参数 print(f"已登录为 {client.user}") # 启动Bot client.run("你的Bot令牌")
关键说明
- 选项定义:
@app_commands.choices()装饰器用来批量设置命令的下拉选项,每个Choice的name是用户看到的显示文本,value是后台处理用的标识值。 - 命令同步:必须调用
tree.sync()将命令同步到Discord,全局命令同步后可能需要数分钟生效,如需快速在指定服务器生效,可使用await tree.sync(guild=discord.Object(id="你的服务器ID"))。 - 权限要求:确保邀请Bot到服务器时勾选了
applications.commands权限,否则用户无法看到应用命令。
动态选项扩展
如果需要根据场景动态生成选项(比如从数据库读取可选功能),可以在命令注册时动态构建choices列表:
# 示例:从列表动态生成选项 available_features = [ ("开启深色模式", "dark_mode"), ("开启通知提醒", "notification_alerts"), ("设置自定义前缀", "custom_prefix"), ("开启自动回复", "auto_reply") ] @tree.command(name="customize", description="自定义你的用户体验功能") @app_commands.choices(feature=[app_commands.Choice(name=n, value=v) for n, v in available_features]) async def customize(interaction: discord.Interaction, feature: str): # 处理逻辑同上
内容的提问来源于stack exchange,提问作者Matthew
相关产品推荐
相关产品推荐

