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

Discord.py中@app_commands.required属性不存在的报错问题

解决Discord.py中@app_commands.required的AttributeError问题

问题场景

你编写了以下Discord.py命令代码,试图用@app_commands.required设置可选参数:

@client.tree.command(name='decide', description='Bing will now help you to decide what happens')        
@app_commands.describe(choice1 = "What is your 1st choice?")
@app_commands.describe(choice2 = "What is your 2nd choice?")
@app_commands.describe(choice3 = "What is your 3rd choice?")
@app_commands.required(choice3 = False)
@app_commands.describe(choice4 = "What is your 4th choice?")
@app_commands.requiredt(choice3 = False)  # 此处存在装饰器名称拼写错误
@app_commands.describe(choice5 = "What is your 5th choice?")
@app_commands.required(choice3 = False)
async def decide(interaction: discord.Interaction, choice1: str, choice2: str, choice3: str, choice4: str, choice5: str):
    print(choice1, choice2, choice3, choice4, choice5)

运行时触发报错:

Traceback (most recent call last):
  File "C:\Users\relen\Downloads\BingChatAI.py", line 987, in <module>
    @app_commands.required(choice3 = False)
AttributeError: module 'discord.app_commands' has no attribute 'required'

错误原因

discord.app_commands模块不存在required装饰器,你可能误读了文档或混淆了其他框架的写法。同时代码中还出现了拼写错误的requiredt装饰器,这也是无效的。

正确的参数必填设置方式

在Discord.py的app_commands框架中,标记参数为可选的正确方式是:

  • 给函数参数设置默认值= None
  • 配合@app_commands.describe添加参数描述即可

具体操作:

  1. 删除所有@app_commands.required和写错的@app_commands.requiredt装饰器
  2. 给需要设为可选的参数(choice3、choice4、choice5)添加默认值= None
  3. 保留@app_commands.describe来定义每个参数的说明文本

修正后的完整代码

@client.tree.command(name='decide', description='Bing will now help you to decide what happens')        
@app_commands.describe(choice1 = "What is your 1st choice?")
@app_commands.describe(choice2 = "What is your 2nd choice?")
@app_commands.describe(choice3 = "What is your 3rd choice?")
@app_commands.describe(choice4 = "What is your 4th choice?")
@app_commands.describe(choice5 = "What is your 5th choice?")
async def decide(interaction: discord.Interaction, choice1: str, choice2: str, choice3: str = None, choice4: str = None, choice5: str = None):
    print(choice1, choice2, choice3, choice4, choice5)

修改后,choice1和choice2会被自动标记为必填参数,choice3到choice5则为可选参数,不会再触发AttributeError。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 05:02:43