Discord.py中app_commands.Argument触发TypeError错误求助
问题解决:TypeError: init() got an unexpected keyword argument 'name'
错误原因
你用错了app_commands.Argument装饰器:
- 这个类的初始化方法根本不接受
name参数,所以传name="xxx"会直接触发TypeError。 - 更关键的是,discord.py中定义斜杠命令的参数不需要用
@app_commands.Argument装饰器,函数的参数会自动映射为命令的输入参数,无需额外装饰。
修正后的代码
把所有@app_commands.Argument装饰器删掉,同时给可选参数设置默认值(以此标记它为非必填):
import discord from discord import app_commands Intents = discord.Intents.default() Intents.guild_messages = True Intents.message_content = True # 假设MyClient是你自定义的Client类,若使用默认Client可替换为discord.Client client = MyClient(intents=Intents) tree = app_commands.CommandTree(client) @tree.command(name="mycommandname", guild = discord.Object(id = MyDiscordGuild)) async def mycommandname(interaction: discord.Interaction, NewParameter0: str, NewParameter1: str, NewParameter2: str = ""): # 无需重复赋值参数,直接使用即可,特殊处理场景除外 await interaction.response.send_message(content="Validation message", delete_after=60)
额外说明:自定义参数属性
如果需要给参数添加描述、修改显示名称等,应该用@app_commands.describe()装饰器或者app_commands.Parameter注解,示例如下:
方式1:用describe统一设置参数描述
@tree.command(name="mycommandname", guild = discord.Object(id = MyDiscordGuild)) @app_commands.describe( NewParameter0="第一个必填参数的说明", NewParameter1="第二个必填参数的说明", NewParameter2="可选的第三个参数说明" ) async def mycommandname(interaction: discord.Interaction, NewParameter0: str, NewParameter1: str, NewParameter2: str = ""): await interaction.response.send_message(content="Validation message", delete_after=60)
方式2:用Parameter单独配置参数
async def mycommandname( interaction: discord.Interaction, NewParameter0: str = app_commands.Parameter(description="第一个参数", required=True), NewParameter1: str, NewParameter2: str = app_commands.Parameter(description="可选参数", required=False, default="") ): await interaction.response.send_message(content="Validation message", delete_after=60)
内容的提问来源于stack exchange,提问作者Darkin Man
相关产品推荐
相关产品推荐

