Discord.py 2.0报错:缺少必填参数interaction,交互消息发送失败
问题分析
你的代码错误根源在于混淆了普通前缀命令和斜杠命令的使用方式:
@client.command定义的是传统前缀触发的命令,这类命令仅会传入ctx(上下文)参数,不会自动提供discord.Interaction对象,因此会触发「缺少interaction参数」的错误。- 若要通过
interaction发送消息,必须使用**斜杠命令(Application Command)**来实现。
修正后的代码
from discord import app_commands @client.tree.command(name="button", description="Send a message with a button!") async def button(interaction: discord.Interaction): view = discord.ui.View() style = discord.ButtonStyle.gray item = discord.ui.Button(style=style, label="Read the docs!", url="https://discordpy.readthedocs.io/en/master") view.add_item(item=item) # 首次响应交互请求 await interaction.response.send_message("This message has buttons!", view=view) # 后续发送消息需使用followup方法 await interaction.followup.send(content="Hi", ephemeral=True)
关键注意事项
- 斜杠命令需用
@client.tree.command装饰器定义,参数为interaction而非传统命令的ctx。 interaction.response.send_message仅能调用一次,用于首次响应交互;后续发送消息必须使用interaction.followup.send,否则会触发交互已被响应的错误。- 斜杠命令需要同步到Discord服务器,可在bot启动完成后执行
await client.tree.sync()(生产环境建议针对指定服务器同步,避免全局同步的限制)。
内容的提问来源于stack exchange,提问作者Flash Senko
相关产品推荐
相关产品推荐

