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

discord.py 2.1.1版本按钮交互失效问题求助

Discord.py 2.1.1按钮交互失败问题解决

问题核心错误

你的代码存在三个关键问题导致按钮交互失败:

  • 自定义MyView类的回调方法不符合discord.py规范,discord.ui的按钮需要通过装饰器绑定回调,而非自定义on_button_click方法。
  • 手动调用bot.wait_for("button_click")和view.callback(interaction)是冗余且错误的操作,View会自动管理交互生命周期,无需手动等待。
  • 直接用view.add_item(Button(label='My Button'))添加的按钮没有绑定任何回调函数,点击自然不会触发逻辑。

修正后的完整代码

import discord
import os  # 补充缺失的os模块导入
from discord.ext import commands
from discord.ui import Button, View
from dotenv import load_dotenv

load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')

intents = discord.Intents.default()
intents.message_content = True
intents.guild_reactions = True
intents.guild_messages = True

bot = commands.Bot(command_prefix='!', intents=intents)

# 正确定义带按钮回调的View类
class MyView(View):
    def __init__(self):
        super().__init__(timeout=None)  # timeout=None让视图永久有效,可选

    # 用装饰器绑定按钮回调,参数与按钮属性匹配
    @discord.ui.button(label='My Button', style=discord.ButtonStyle.primary)
    async def my_button_callback(self, interaction: discord.Interaction, button: Button):
        print('Test')
        # 必须先响应交互,否则会出现"This interaction failed"
        await interaction.response.send_message('Button clicked!', ephemeral=True)  # ephemeral=True仅自己可见,可选

@bot.command()
async def test_button(ctx):
    embed = discord.Embed(title='My Embedded Object', description='This is an embedded object with a button.')
    view = MyView()
    # View内已通过装饰器定义按钮,无需手动add_item
    await ctx.send(embed=embed, view=view)

bot.run(TOKEN)

关键修正点说明

  1. View类规范写法:

    • 使用@discord.ui.button装饰器定义按钮及其回调函数,装饰器可指定按钮的label、样式、emoji等属性。
    • 回调函数参数固定为self, interaction, button,必须调用interaction.response相关方法响应交互,否则Discord会判定交互失败。
  2. 移除冗余逻辑:

    • 删除bot.wait_for("button_click")和手动调用view.callback的代码,View会自动处理按钮点击事件。
  3. 补充依赖与优化:

    • 补充了缺失的os模块导入,确保os.getenv正常运行。
    • 可选设置timeout=None让按钮永久有效(默认180秒后失效),ephemeral=True让回复仅触发者可见。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 16:25:15