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

如何在D#开发的Discord Bot中为Embed消息添加按钮?

解决方案:给Embed消息添加按钮

首先明确:按钮不是Embed的一部分,而是属于Discord消息的「交互组件」,需要和Embed一起作为消息的内容发送。你之前的问题是没把按钮关联到消息的组件参数里,下面是具体步骤:

1. 把按钮包装到ActionRow中

Discord要求所有交互组件(比如按钮)必须放在ActionRowComponent里,不能直接单独发送。修改你的按钮代码:

// 创建按钮
var myButton = new DiscordButtonComponent(ButtonStyle.Primary, "my_custom_id", "This is a button!");
// 把按钮放到ActionRow里
var actionRow = new DiscordActionRowComponent(myButton);

2. 发送消息时同时传入Embed和组件

修改你发送消息的代码,加上components参数,把刚才的ActionRow传进去:

// 先修正Embed里的语法错误(ImageUrl的引号没闭合)
var joinGames = new DiscordEmbedBuilder
{
    ImageUrl = "你的图片链接", // 补全引号,替换成实际地址
    Title = "bla bla bla",
    Color = DiscordColor.Blue,
    Description = ":bla bla bla \n" +
                  "bla bla"
};

// 发送消息时同时传入embed和components
await ctx.Channel.SendMessageAsync(embed: joinGames.Build(), components: new[] { actionRow }).ConfigureAwait(false);

注意:DiscordEmbedBuilder需要调用Build()方法转换成DiscordEmbed对象,部分版本的Discord.NET支持隐式转换,但显式调用更稳妥。

3. 处理按钮点击事件

光添加按钮还不够,你需要监听按钮的点击事件来响应操作。比如在Bot初始化代码里注册事件:

client.ButtonExecuted += ButtonHandler;

// 定义按钮点击的处理方法
private async Task ButtonHandler(SocketMessageComponent component)
{
    // 通过自定义ID判断是哪个按钮被点击
    if (component.Data.CustomId == "my_custom_id")
    {
        // 这里写按钮点击后的逻辑,比如给用户发送临时回复
        await component.RespondAsync("你点击了按钮!", ephemeral: true).ConfigureAwait(false);
    }
}

学习资源推荐

  • Discord.NET官方文档的「交互组件」章节:涵盖按钮、选择菜单等所有交互组件的详细用法,是最权威的参考资料
  • Discord.NET官方示例项目:包含完整的组件使用场景示例,能帮你快速理解交互逻辑的实现方式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 06:35:17