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

Discord验证按钮实现报错:点击提示‘This Interaction Failed’

Discord验证按钮交互失败问题修复

问题原因

你的代码使用了过时的button_click事件监听方式,且未给按钮绑定点击回调函数,导致Discord无法找到交互处理逻辑,触发「This Interaction Failed」错误。discord.py v2.x及以上版本,官方推荐通过自定义View类并绑定按钮回调的方式处理组件交互。

修正后的代码

import discord
from discord.ext import commands
import asyncio

bot = commands.Bot(command_prefix=".", intents=discord.Intents.all(), help_command=None)

@bot.event
async def on_ready():
    print("Bot is online!")

# 自定义验证按钮的View类
class VerifyView(discord.ui.View):
    def __init__(self, ctx):
        super().__init__(timeout=30.0)  # 设置30秒超时
        self.ctx = ctx

    # 按钮点击回调函数
    @discord.ui.button(style=discord.ButtonStyle.green, label='Verify')
    async def verify_button_callback(self, interaction: discord.Interaction, button: discord.ui.Button):
        # 检查点击者是否是发起命令的用户
        if interaction.user.id != self.ctx.author.id:
            await interaction.response.send_message("你不是发起验证的用户,无法操作此按钮!", ephemeral=True)
            return
        
        # 获取Verified角色
        role = discord.utils.get(self.ctx.guild.roles, name='Verified')
        if not role:
            await interaction.response.send_message("服务器中不存在名为'Verified'的角色!", ephemeral=True)
            return
        
        # 添加角色
        await interaction.user.add_roles(role)
        # 回复交互并更新消息
        await interaction.response.edit_message(content='你已完成验证!', view=None)

    # 超时处理
    async def on_timeout(self):
        # 超时后禁用按钮
        for item in self.children:
            item.disabled = True
        await self.ctx.edit(view=self)

@bot.command()
async def verify(ctx):
    # 创建自定义View实例
    view = VerifyView(ctx)
    # 发送带按钮的消息
    message = await ctx.send('点击下方按钮完成验证', view=view)
    # 绑定消息到View,方便超时后编辑
    view.message = message

# 运行机器人
bot.run("你的机器人令牌")

关键修改说明

  • 自定义VerifyView类继承discord.ui.View,统一管理按钮和交互逻辑
  • 给按钮添加@discord.ui.button装饰器定义回调函数,直接处理点击事件
  • 内置超时处理逻辑,超时后自动禁用按钮
  • 增加角色不存在、非命令发起者点击的错误处理,提升鲁棒性
  • 使用interaction.response正确回复交互,避免Discord判定交互失败

额外注意事项

  • 确保机器人拥有管理角色的权限,否则无法给用户添加角色
  • 确认服务器中存在名为Verified的角色,或根据实际情况修改角色名称
  • 使用最新版本的discord.py,避免版本兼容问题

内容的提问来源于stack exchange,提问作者Senne

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 00:47:12