如何在discord.py中创建带预设选项选择的交互命令?
解决discord.py预设选项命令的错误问题
修正后的代码
@tree.command(name="createticket", description="Create a ticket", guild=discord.Object(GUILD_ID)) @app_commands.choices(choice=[ app_commands.Choice(name="Bug", value="bug"), app_commands.Choice(name="Report", value="report") # 可继续添加更多预设选项 ]) async def embed_command(interaction: discord.Interaction, choice: str): if interaction.user.guild_permissions.administrator: if choice == "bug": # 此处编写Bug工单的创建逻辑 await interaction.response.send_message("Bug工单已创建", ephemeral=True) elif choice == "report": # 此处编写举报工单的创建逻辑 await interaction.response.send_message("举报工单已创建", ephemeral=True)
错误原因及修正说明
- 装饰器参数不匹配:你使用了
@app_commands.choices(choices=[...]),但正确写法需要让装饰器内的参数名和函数定义的参数名一致,也就是@app_commands.choices(choice=[...]),这里的choice要和函数里的参数名对应。 - 参数类型错误:函数内的
choice: app_commands.Choice[str]应改为choice: str,discord.py会自动将选中的选项值(如"bug")直接传递给该参数,无需接收完整的Choice对象。 - 笔误问题:代码里的
choice.calue是拼写错误,应改为choice.value(不过修正参数类型后直接使用choice即可,无需.value)。 - 多余判断:
interaction.user永远不会为None,可以去掉and interaction.user != None这个无效判断。
内容的提问来源于stack exchange,提问作者Tousend1000
相关产品推荐
相关产品推荐

