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

如何在discord.py中创建按钮?解决按钮初始化报错问题

Discord机器人按钮组件使用错误解决方法

问题描述

我正尝试制作一个用于更新状态消息的Discord机器人,但无法让按钮/下拉菜单正常工作。我尝试了以下代码:

button = discord.Button()
button.custom_id = "test"
button.label = "Label"
button.style = discord.ButtonStyle.primary
embed = discord.Embed()
embed.title = "title"
embed.add_field(name="test",value=button)

但出现了如下错误:

discord.app_commands.errors.CommandInvokeError: Command 'update' raised an exception: TypeError: Button.__init__() missing 1 required positional argument: 'data'

错误原因

直接实例化discord.Button()的方式不符合discord.py的组件使用规范,而且不能把按钮直接添加到Embed的字段里——Embed仅支持文本内容,按钮属于消息的交互组件,需要通过单独的view参数绑定到消息上。

正确实现方式

要使用按钮,需要创建继承自discord.ui.View的视图类,在类中定义按钮并绑定点击回调函数。示例代码如下:

import discord
from discord.ext import commands

# 初始化机器人,确保开启所需权限
bot = commands.Bot(command_prefix="!", intents=discord.Intents.all())

# 定义包含按钮的永久视图(timeout=None表示不自动失效)
class StatusUpdateView(discord.ui.View):
    def __init__(self):
        super().__init__(timeout=None)

    # 定义按钮及点击事件处理
    @discord.ui.button(label="更新状态", style=discord.ButtonStyle.primary, custom_id="status_update_btn")
    async def update_status_btn(self, interaction: discord.Interaction, button: discord.ui.Button):
        # 这里编写按钮点击后的逻辑,比如更新消息内容或Embed
        await interaction.response.edit_message(description="状态已成功更新!")

# 注册slash命令
@bot.tree.command(name="update")
async def send_status_message(interaction: discord.Interaction):
    embed = discord.Embed(title="状态更新面板", description="点击下方按钮更新状态")
    # 发送消息时传入view参数,将按钮附加到消息
    await interaction.response.send_message(embed=embed, view=StatusUpdateView())

# 运行机器人
bot.run("你的机器人Token")

关键注意事项

  • 按钮必须封装在discord.ui.View的子类中,不能直接实例化discord.Button()
  • Embed只能承载文本内容,无法嵌入按钮这类交互组件
  • 每个按钮都需要绑定回调函数来处理用户的点击操作
  • 发送消息时通过view参数将包含按钮的视图传递给消息

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 08:45:24