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

Discord.py按钮点击无响应,无法触发后续代码执行

Discord.py按钮点击后后续代码不执行的解决方案

问题根源

  • Discord.py没有单独的button或button_click事件,按钮触发的是通用的interaction事件,你之前监听的事件类型完全错误。
  • 按钮回调函数里没有对交互进行响应,Discord会认为这个交互未处理,直接阻塞后续操作。
  • wait_for的检查条件逻辑错误,没区分交互类型,也没正确匹配用户。

修正步骤

1. 修复按钮回调的交互响应

按钮被点击后,必须调用interaction.response的方法完成响应,否则Discord会判定交互超时。示例:

@discord.ui.button(label="Modrá 🟦", style=discord.ButtonStyle.grey)
async def modra(self, interaction: discord.Interaction, button: discord.ui.Button):
    self.kolej = "Modrá"
    # 发送临时确认消息,仅用户可见
    await interaction.response.send_message(f"Vybral jsi kolej {self.kolej}!", ephemeral=True)
    # 如果不需要显示消息,也可以用静默响应:
    # await interaction.response.defer(ephemeral=True)

2. 修正wait_for的事件监听逻辑

把监听的事件改成interaction,同时添加检查条件筛选按钮交互和目标用户:

await interaction.response.send_message(embed=embed, view=vyber_kolej())

# 监听按钮交互,确保是当前用户触发的
button_interaction = await bot.wait_for(
    'interaction',
    check=lambda i: i.type == discord.InteractionType.component and i.user == interaction.user
)

# 可以从view实例中获取选中的kolej值
selected_kolej = button_interaction.view.kolej

embed.remove_field(0)
embed.add_field(name="Rocnik", value="vyber ročník žáka", inline=False)
await interaction.followup.send(embed=embed, view=vyber_rocniku())

额外说明

  • 所有组件(按钮、选择菜单、文本输入)的交互都属于interaction事件,必须通过i.type来区分具体类型。
  • 如果你的vyber_kolej是自定义的discord.ui.View子类,确保类定义正确,并且按钮方法是类的成员(注意缩进)。

内容的提问来源于stack exchange,提问作者Tadeáš Ryška

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 18:42:48