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

Discord机器人按钮交互持续报错‘This Interaction Failed’求助

Discord机器人按钮交互失败问题解决方案

核心问题分析

你的代码存在两个关键错误,直接导致了"This Interaction Failed"错误:

  1. 重复响应交互:Discord要求每个交互只能发送一次初始响应,后续消息必须使用followup.send()而不是再次调用interaction.response.send_message()
  2. 错误的 clan 匹配逻辑:你用角色ID(value[2])和嵌入标题("Invitation to clan名称")做比较,这永远无法匹配成功

修正后的代码

import logging

# 配置日志记录(写入文件+控制台输出)
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler('bot.log'),
        logging.StreamHandler()
    ]
)
logger = logging.getLogger(__name__)

@bot.command()
async def invite(ctx, user: discord.User):
    if ctx.author.id not in clan_data:
        await ctx.send("You are not in any clan. Create a clan first.")
        return

    # Check if the author of the message is the clan creator
    clan_creator_id = ctx.author.id
    if clan_creator_id not in clan_data:
        await ctx.send("Only the clan creator can invite users.")
        return

    clan_name, channel_id, role_id, member_list= clan_data[clan_creator_id]
    embed = discord.Embed(
        title=f"Invitation to {clan_name}",
        description=f"You have been invited to {clan_name} by {ctx.author.name}",
        color=discord.Color.blurple()
    )
    embed.set_thumbnail(url=ctx.guild.icon.url)

    accept_button = Button(style=discord.ButtonStyle.green, label="Accept", custom_id="join")
    reject_button = Button(style=discord.ButtonStyle.red, label="Reject", custom_id="reject")

    action_row = View()
    action_row.add_item(accept_button)
    action_row.add_item(reject_button)

    await user.send(embed=embed, view=action_row)

@bot.event
async def on_component(interaction):
    try:
        if interaction.custom_id == "join":
            # 发送初始响应确认交互
            await interaction.response.send_message("Accepted. Processing...", ephemeral=True)
            await handle_accept(interaction)
        elif interaction.custom_id == "reject":
            await interaction.response.send_message("Invite rejected.", ephemeral=True)
    except Exception as e:
        logger.error(f"组件交互处理错误: {e}", exc_info=True)
        # 如果还未发送响应,发送错误提示
        if not interaction.response.is_done():
            await interaction.response.send_message("处理请求时发生错误。", ephemeral=True)
        else:
            await interaction.followup.send("处理请求时发生错误。", ephemeral=True)

async def handle_accept(interaction):
    try:
        user = interaction.user
        guild = bot.get_guild(1159153096191123517) # 替换为你的服务器ID
        if not guild:
            await interaction.followup.send("无法找到服务器!", ephemeral=True)
            logger.error("未找到指定ID的服务器。")
            return

        # 从嵌入标题中提取clan名称
        embed = interaction.message.embeds[0]
        if not embed.title.startswith("Invitation to "):
            await interaction.followup.send("邀请格式无效。", ephemeral=True)
            logger.error("嵌入标题格式错误。")
            return
        
        clan_name = embed.title.replace("Invitation to ", "")
        clan_creator_id = None

        # 通过clan名称查找创建者ID
        for key, value in clan_data.items():
            if value[0] == clan_name: # value[0]是clan名称
                clan_creator_id = key
                break

        if clan_creator_id is None:
            await interaction.followup.send("无效的邀请!", ephemeral=True)
            logger.warning(f"clan '{clan_name}' 未在clan_data中找到。")
            return

        role_id = clan_data[clan_creator_id][2]
        role = guild.get_role(role_id)

        if role is None:
            await interaction.followup.send("角色不存在!", ephemeral=True)
            logger.error(f"服务器中未找到ID为{role_id}的角色。")
            return

        # 添加用户到clan成员列表并分配角色
        clan_data[clan_creator_id][3].append(user.id)
        await user.add_roles(role)
        await interaction.followup.send("你已接受邀请,欢迎加入clan!", ephemeral=True)
        logger.info(f"用户{user.id}接受了{clan_name}的邀请。")

    except Exception as e:
        logger.error(f"处理接受邀请时出错: {e}", exc_info=True)
        await interaction.followup.send("接受邀请时发生错误。", ephemeral=True)

额外注意事项

  1. 角色层级:确保机器人的角色在服务器角色列表中高于要分配的clan角色,否则无法给用户添加角色
  2. 数据持久化:如果clan_data是内存中的临时数据,重启机器人后会丢失,建议使用数据库或文件存储
  3. 日志排查:在Google Cloud虚拟机中,可以通过以下命令查看日志:
    • 实时查看日志:tail -f bot.log
    • 查看完整日志:cat bot.log

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 13:03:16