使用nextcord编写announce命令遇SlashOptions类型提示错误求助
Nextcord斜杠命令SlashOptions类型提示错误的解决办法
问题代码
@client.slash_command(name = 'announce', description = 'Makes XYZ announcement in your announcements channel') @application_checks.has_guild_permissions(moderate_members=True) async def announce(interaction: nextcord.Interaction, channel: nextcord.TextChannel, *, msg): await channel.send(f'{msg}')
问题描述
使用上述代码编写Nextcord斜杠命令时,持续收到与SlashOptions相关的类型提示错误,仅需将消息发送至channel参数指定的频道,询问报错原因及解决方法。
报错原因
- 参数未标记为Slash选项:Nextcord斜杠命令中,除
interaction外的自定义参数需显式声明为Slash选项,框架才能识别其类型并生成对应的命令交互界面。 - 可变参数写法不兼容:原代码中
*, msg的可变参数打包写法,不符合斜杠命令的参数规范,框架无法正确解析该参数的类型和用途。
修正方案
方案1:显式使用SlashOption标记参数
通过nextcord.SlashOption明确指定每个参数的类型和描述,让框架正确识别选项:
@client.slash_command(name='announce', description='Makes XYZ announcement in your announcements channel') @application_checks.has_guild_permissions(moderate_members=True) async def announce( interaction: nextcord.Interaction, channel: nextcord.TextChannel = nextcord.SlashOption(description="选择公告发送频道"), msg: str = nextcord.SlashOption(description="公告内容") ): await channel.send(msg) # 必须添加交互响应,避免Discord判定命令超时 await interaction.response.send_message("公告已成功发送", ephemeral=True)
方案2:利用新版本类型提示自动推断(Nextcord v2.0+)
如果使用Nextcord v2.0及以上版本,可直接通过类型提示让框架自动识别参数类型,但需移除可变参数写法:
@client.slash_command(name='announce', description='Makes XYZ announcement in your announcements channel') @application_checks.has_guild_permissions(moderate_members=True) async def announce( interaction: nextcord.Interaction, channel: nextcord.TextChannel, msg: str ): await channel.send(msg) await interaction.response.send_message("公告已成功发送", ephemeral=True)
关键注意点
- 斜杠命令必须对交互做出响应(如
interaction.response.send_message),否则Discord会返回命令超时错误。 - 避免使用
*打包剩余参数的写法,斜杠命令的每个参数都需要明确类型定义。
内容的提问来源于stack exchange,提问作者Icey
相关产品推荐
相关产品推荐

