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

discord.py开发Discord按钮交互失败但代码执行正常求助

问题解决:Discord按钮交互失败但回调代码执行完成

问题原因

Discord的交互机制要求,用户触发按钮点击等交互后,必须在3秒内通过interaction.response对象返回响应。如果未执行此操作,即使回调内的业务逻辑已完成,Discord仍会判定交互失败,显示"This interaction failed"提示。

解决方法

在按钮回调函数的开头,添加交互响应操作,常用两种方式:

  • await interaction.response.defer():告知Discord“将稍后返回完整响应”,适合处理耗时逻辑,不会触发失败提示。若添加ephemeral=True,则仅触发交互的用户可见相关响应痕迹。
  • await interaction.response.send_message(content, ephemeral=True):直接发送一条仅用户可见的确认消息,完成交互响应。

修改后的代码

button = discord.ui.Button(label="Join village", emoji="🐺", style=discord.ButtonStyle.green)
async def button_callback(interaction):
    # 先发送延迟响应,避免Discord判定交互失败
    await interaction.response.defer(ephemeral=True)
    
    if interaction.user.id in Rooms[room].players:
        await interaction.user.send("You are already in room %s" % room)
        return
    
    Rooms[room].add_player(interaction.user.id)
    await interaction.user.send("You have joined room %s" % room)
    
    # 可选:发送后续确认消息(仅用户可见)
    await interaction.followup.send("Successfully joined the room!", ephemeral=True)

button.callback = button_callback
view = discord.ui.View()
view.add_item(button)
await ctx.send("Join the new %s village by clicking here!" % room, view=view)

关键修改说明

  1. 新增await interaction.response.defer(ephemeral=True):在业务逻辑执行前完成交互响应,避免超时失败。
  2. 移除原消息中的失败提示文本,因为问题已解决。
  3. 可选的followup.send:给用户明确的操作反馈,提升体验。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 15:15:36