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

Discord.js V13 固定消息开发求助:实现自动更新的底部嵌入消息

解决Discord.js V13固定嵌入消息(自动替换旧消息)的方案

核心逻辑

每次用户在指定频道发消息时,先定位机器人之前发送的嵌入消息并删除,再发送新的嵌入,同时记录新消息的ID,供下次操作时定位旧消息。

实现代码

先声明变量存储旧消息ID(单频道场景用单个变量即可,多频道/多服务器建议用对象或数据库存储对应频道的消息ID):

// 存储机器人发送的嵌入消息ID
let botEmbedMessageId = null;

在messageCreate事件中处理完整流程:

const { MessageEmbed } = require('discord.js');

client.on('messageCreate', async (message) => {
  // 跳过机器人自身消息,避免循环触发
  if (message.author.bot) return;

  // 替换为你的目标频道ID
  const targetChannelId = '你的频道ID';
  if (message.channel.id !== targetChannelId) return;

  try {
    // 删除旧嵌入消息(如果存在)
    if (botEmbedMessageId) {
      const oldMessage = await message.channel.messages.fetch(botEmbedMessageId).catch(err => null);
      if (oldMessage) await oldMessage.delete();
    }

    // 创建并发送新嵌入
    const embed = new MessageEmbed()
      .setTitle('Bot Commands')
      .setDescription('这里填写机器人命令列表内容')
      .setColor('#0099ff');
    
    const newEmbedMsg = await message.channel.send({ embeds: [embed] });

    // 更新存储的消息ID
    botEmbedMessageId = newEmbedMsg.id;
  } catch (err) {
    console.error('处理嵌入消息出错:', err);
  }
});

关键注意事项

  • 确保机器人拥有管理消息权限,否则无法执行删除操作。
  • 多频道场景下,将botEmbedMessageId替换为对象,比如const botEmbedMsgMap = {};,用botEmbedMsgMap[message.channel.id]来存储对应频道的消息ID。
  • 必须跳过机器人自身消息,否则会触发无限循环。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 15:20:55