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添加参数描述即可
具体操作:
- 删除所有
@app_commands.required和写错的@app_commands.requiredt装饰器 - 给需要设为可选的参数(choice3、choice4、choice5)添加默认值
= None - 保留
@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
相关产品推荐
相关产品推荐

