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

点击Discord按钮时出现「This interaction failed」错误求助

解决Discord机器人按钮点击「This interaction failed」错误

你的代码出现交互失败的核心原因是按钮回调函数的写法不符合discord.py的规范,Discord无法识别自定义的on_button_click方法作为按钮的交互处理逻辑,导致交互超时触发错误。

正确的按钮回调写法

需要使用@discord.ui.button装饰器绑定按钮的交互处理函数,同时必须对Discord的交互请求进行响应(否则平台会判定交互失败)。以下是修改后的完整代码:

import discord
from discord.ext import commands


class MyView(discord.ui.View):
    def __init__(self):
        super().__init__(timeout=None)  # 设置timeout=None让视图永久生效(可选,根据需求调整)

    @discord.ui.button(style=discord.ButtonStyle.primary, label="Click me!", custom_id="my_button")
    async def my_button_callback(self, interaction: discord.Interaction, button: discord.ui.Button):
        # 先响应交互,避免Discord判定超时失败
        await interaction.response.defer(ephemeral=True)
        # 给用户发送私信
        await interaction.user.send("You clicked the button!")
        # 可选:给交互发送一个仅用户可见的提示
        await interaction.followup.send("已给你发送私信!", ephemeral=True)


class InteractiveCog(commands.Cog):
    def __init__(self, client):
        self.client = client
        self.channel_id = 1226612165453021244

    @commands.command()
    async def message(self, ctx):
        channel = self.client.get_channel(self.channel_id)
        if channel:
            embed = discord.Embed(title="Interactive Message", description="Click the button below!")
            await channel.send(embed=embed, view=MyView())


async def setup(client):
    await client.add_cog(InteractiveCog(client))

关键修改点说明

  • 装饰器绑定回调:用@discord.ui.button装饰器直接定义按钮的处理函数,Discord能自动识别这个函数为对应按钮的交互逻辑
  • 必须响应交互:调用interaction.response.defer()告诉Discord“已收到请求,正在处理”,避免超时;如果不需要后续操作,也可以直接用await interaction.response.send_message()直接回复
  • 视图超时设置:如果希望按钮长期有效,初始化View时设置timeout=None,否则默认15分钟后按钮会失效
  • 私信发送逻辑:先defer交互再发私信,确保交互流程正常完成

内容的提问来源于stack exchange,提问作者Денис Піддубний

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 04:43:15