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

discord.py按钮交互超时失效问题求助

解决Discord.py按钮5分钟后失效的Interaction failed问题

这个问题的核心原因是Discord交互的默认超时机制:通过临时响应(如interaction.response.send_message())发送的带组件的消息,其交互有效期默认是5分钟(300秒)。超时后Discord会拒绝处理该消息上的组件交互请求,直接触发"Interaction failed"报错。

以下是针对性的解决方法:

1. 使用持久化组件(推荐,支持长期有效)

这是实现永久有效按钮的标准方案,需要满足三个条件:

  • 给按钮设置固定的custom_id(不能是动态生成的临时ID,比如随机字符串)
  • 在Bot启动时注册对应的View类
  • View实例设置timeout=None,discord.py v2.0+会自动处理持久化逻辑

示例代码:

import discord
from discord import ui

# 定义持久化View类
class ModalButtonView(ui.View):
    def __init__(self):
        super().__init__(timeout=None)  # 禁用View自身的超时

    # 给按钮设置固定custom_id
    @ui.button(label="打开模态框", style=discord.ButtonStyle.primary, custom_id="open_modal_btn")
    async def trigger_modal(self, interaction: discord.Interaction, button: ui.Button):
        # 创建并发送模态框
        modal = ui.Modal(title="示例模态框")
        modal.add_item(ui.TextInput(label="输入内容", placeholder="在这里输入", custom_id="modal_input_field"))
        await interaction.response.send_modal(modal)

# Bot启动时注册持久化View
@bot.event
async def on_ready():
    bot.add_view(ModalButtonView())
    print(f"Bot已登录:{bot.user}")

# /add_button 指令
@bot.tree.command(name="add_button", description="发送带按钮的消息")
async def add_button(interaction: discord.Interaction):
    view = ModalButtonView()
    await interaction.response.send_message("点击下方按钮打开模态框", view=view)

2. 临时延长超时(适用于短期有效场景)

如果不需要按钮永久有效,只是想延长超时时间,可以在初始化View时设置timeout参数(单位为秒),比如延长至1小时:

class TempButtonView(ui.View):
    def __init__(self):
        super().__init__(timeout=3600)  # 设置超时为3600秒(1小时)

注意:这种方式仍有时间限制,且Bot重启后未处理的交互会直接失效。

3. 常见错误排查点

  • 避免使用动态生成的custom_id(比如每次创建按钮都用随机字符串),否则Bot重启或超时后无法匹配组件
  • 不要在发送消息后修改View的结构或重新创建View实例,这会导致Discord无法识别组件
  • 如果使用wait_for("interaction")监听组件,务必设置足够长的timeout参数,并捕获超时异常

内容的提问来源于stack exchange,提问作者Rodopoulos X Games

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 18:43:21