You need to enable JavaScript to run this app. Discord.js实现消息编辑删除日志功能时报EMBED_FIELD_VALUE错误如何解决
优惠活动
大模型
产品
解决方案
定价
更多

Discord.js实现消息编辑删除日志功能时报EMBED_FIELD_VALUE错误如何解决

报错根因定位

直接触发原因

MessageEmbed的字段value不允许传入空字符串、null、undefined类型的值,只要任意字段命中就会抛出RangeError [EMBED_FIELD_VALUE],对应你代码里的空值来源有:

  • 当编辑的消息为附件、无文本内容、缓存未加载的历史消息时,message.content返回值为空
  • 当编辑的是机器人消息、webhook消息时,message.author返回值为null,后续拼接的${message.author.tag}会变成undefined
  • 你当前messageUpdate事件的回调签名错误:Discord.js 中该事件回调固定接收(oldMessage, newMessage)两个参数,单参数写法拿到的是旧消息对象,无法匹配编辑前后的内容对比逻辑,也更容易拿到缓存不全的空值数据

附带逻辑问题(非报错直接来源)

  • 防重复用的messages数组在事件回调内部初始化,每次触发事件都会重置为空数组,防重复逻辑完全失效
  • 重复编写了两次查找日志频道的代码,第一次获取的channel变量没有被使用,属于冗余逻辑

修复方案

针对报错点加兜底逻辑,修正事件回调签名,调整为如下代码即可解决报错:

// 防重复缓存移到事件外层,避免每次触发被重置
const editedMsgCache = [];
client.on("messageUpdate", async (oldMsg, newMsg) => {
  // 跳过机器人消息、缓存不全的消息
  if (!oldMsg.author || oldMsg.author.bot || !oldMsg.guild) return;
  // 跳过内容没有实际变化的触发
  if (oldMsg.content === newMsg.content) return;
  // 防重复判断
  if (editedMsgCache.includes(oldMsg.id)) return;
  editedMsgCache.push(oldMsg.id);
  // 定时清理缓存,避免数组无限增长
  setTimeout(() => editedMsgCache.splice(editedMsgCache.indexOf(oldMsg.id), 1), 30000);

  // 查找日志频道
  const logChannel = client.channels.cache.get('你的日志频道ID');
  if (!logChannel) return;

  const editEmbed = new Discord.MessageEmbed()
    .setColor(1752220)
    .setTitle(":pencil: Message Edited")
    .addFields(
      { name: "__Channel:__", value: `<#${oldMsg.channel.id}>` },
      { name: "__Message Author:__", value: `${oldMsg.author.tag} - <@${oldMsg.author.id}>` },
      // 给原消息内容加兜底,截断超长内容避免超过embed字段的1024字符限制
      { name: "__Original Message:__", value: oldMsg.content.slice(0, 1024) || "*消息无文本内容*" }
    )
    .setTimestamp()
    .setThumbnail(oldMsg.author.avatarURL({ size: 256 }))
    .setFooter("super cool api");

  await logChannel.send({ embeds: [editEmbed] });
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.31 19:15:08