如何在Python脚本中修复Discord按钮「this interaction failed」错误
问题定位
导致该错误的常见原因如下:
- Discord 官方要求所有交互必须在 3秒内 完成响应,超出时间就会直接返回「this interaction failed」提示,你的代码如果存在事件循环阻塞、响应逻辑延迟的情况,就会触发该错误。
- 你创建按钮时没有指定唯一
custom_id,仅通过label匹配点击事件,当label存在特殊字符、或者多场景下出现重名label时,会出现事件匹配失败的问题。 - 代码中的
while True死循环会持续占用协程资源,多次点击或多用户同时操作时,很容易出现响应阻塞,还会出现事件匹配混乱的问题。 - 部分Discord Python库(如discord.py v2.x、nextcord、disnake)对交互响应的方法有明确要求,直接调用
respond可能不符合API规范,导致响应失败。
修复方案
调整后的代码示例如下:
import asyncio # 需提前导入asyncio处理超时 @bot.command() async def coin(ctx): # 初始化按钮时指定唯一custom_id,确保事件匹配精准 animated_coin_btn = Button(label="Animated coin", custom_id="animated_coin_1001") await ctx.send( "This is our **bet** coin : <:coiner:902807543569584158>", components = [animated_coin_btn] ) try: # 增加超时机制,避免协程永久挂起占用资源 while True: interaction = await bot.wait_for( "button_click", # 校验custom_id和触发频道,避免无关事件干扰 check = lambda i: i.custom_id == "animated_coin_1001" and i.channel.id == ctx.channel.id, timeout=120 ) # 调用标准响应方法回复交互,可根据需要设置ephemeral=True让回复仅触发用户可见 await interaction.response.send_message(content="<a:coinanimated:9028075435695848902>") except asyncio.TimeoutError: # 超时后禁用按钮,避免用户点击无响应按钮触发错误 animated_coin_btn.disabled = True await ctx.edit(components=[animated_coin_btn])
本次修复的核心调整点:
- 给按钮添加唯一
custom_id,事件匹配优先使用custom_id而非按钮文本,稳定性更高 - 给
wait_for添加超时逻辑,超时后自动禁用按钮,避免用户点击无效按钮 - 改用标准的
interaction.response.send_message方法响应交互,符合Discord API规范 - 事件校验增加频道ID匹配,避免其他频道的同ID按钮事件触发错误响应
内容的提问来源于stack exchange,提问作者Puk3l_YT
相关产品推荐
相关产品推荐

