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

DiscordJS v14:实现发送嵌入消息时计数器递增功能求助

解决Discord机器人指定频道消息计数与嵌入转发问题

现有代码的核心问题

  • count变量未声明初始化,机器人启动后首次运行会报错;且当前计数仅存在内存中,重启机器人后会重置。
  • displayAvatarURL方法没有text参数,你想添加的「Review #X」无法通过这个配置实现,需要调整到嵌入的其他位置(如作者名称、标题)。
  • message.delete()是异步操作,未加await可能导致原消息还没删除就发送嵌入,逻辑顺序混乱。

修正后的基础版本(内存计数,适合测试)

// 初始化计数器,重启机器人后会重置为0
let count = 0;

client.on("messageCreate", async (message) => {
  // 替换成你的目标频道ID
  const targetChannelId = "ChannelID";
  if (message.channel.id !== targetChannelId) return;
  // 忽略机器人发送的消息
  if (message.author.bot) return;

  // 格式化当前日期
  const today = new Date();
  const dd = String(today.getDate()).padStart(2, "0");
  const mm = String(today.getMonth() + 1).padStart(2, "0");
  const yyyy = today.getFullYear();
  const formattedDate = `${dd}/${mm}/${yyyy}`;

  // 计数器自增,生成编号
  count++;
  const reviewNumber = `Review #${count}`;

  try {
    // 先异步删除原消息,确保机器人有「删除消息」权限
    await message.delete();

    // 构建嵌入消息
    const reviewsEmbed = new EmbedBuilder()
      .setAuthor({
        name: `${message.member.user.tag} | ${reviewNumber}`,
        iconURL: message.member.displayAvatarURL({
          dynamic: true,
          size: 4096,
        }),
      })
      .setDescription(`**${message.content}**`)
      .setColor(botConfig.EmbedColor)
      .setFooter({
        text: `${botConfig.Text} | ${formattedDate}`,
      });

    // 发送嵌入消息到当前频道
    await message.channel.send({ embeds: [reviewsEmbed] });
  } catch (error) {
    console.error("处理消息时出错:", error);
    // 可选:如果需要,这里可以发送错误提示到频道或记录详细日志
  }
});

持久化计数版本(重启不丢失)

如果需要机器人重启后计数不重置,可以用本地JSON文件存储计数:

const fs = require('fs').promises;
const path = require('path');

// 计数存储文件的路径,会在机器人目录下生成reviewCount.json
const countFilePath = path.join(__dirname, 'reviewCount.json');

// 加载已保存的计数
async function loadCount() {
  try {
    const data = await fs.readFile(countFilePath, 'utf8');
    return JSON.parse(data).count || 0;
  } catch (error) {
    // 文件不存在时返回初始值0
    return 0;
  }
}

// 保存计数到文件
async function saveCount(count) {
  await fs.writeFile(countFilePath, JSON.stringify({ count }), 'utf8');
}

// 初始化计数器
let count = 0;
loadCount().then(loadedCount => {
  count = loadedCount;
});

client.on("messageCreate", async (message) => {
  const targetChannelId = "ChannelID";
  if (message.channel.id !== targetChannelId) return;
  if (message.author.bot) return;

  const today = new Date();
  const dd = String(today.getDate()).padStart(2, "0");
  const mm = String(today.getMonth() + 1).padStart(2, "0");
  const yyyy = today.getFullYear();
  const formattedDate = `${dd}/${mm}/${yyyy}`;

  count++;
  const reviewNumber = `Review #${count}`;

  try {
    await message.delete();

    const reviewsEmbed = new EmbedBuilder()
      .setAuthor({
        name: `${message.member.user.tag} | ${reviewNumber}`,
        iconURL: message.member.displayAvatarURL({ dynamic: true, size: 4096 }),
      })
      .setDescription(`**${message.content}**`)
      .setColor(botConfig.EmbedColor)
      .setFooter({ text: `${botConfig.Text} | ${formattedDate}` });

    await message.channel.send({ embeds: [reviewsEmbed] });
    // 保存更新后的计数
    await saveCount(count);
  } catch (error) {
    console.error("处理消息时出错:", error);
    // 如果保存失败,回滚计数避免错误累计
    count--;
  }
});

关键调整说明

  1. 计数器初始化与持久化:基础版本用内存变量存储计数,持久化版本通过JSON文件保存,重启后自动加载。
  2. 嵌入消息调整:把「Review #X」加到作者名称中,移除无效的text参数,符合Discord.js的API规范。
  3. 异步操作处理:给message.delete()和message.channel.send()添加await,确保操作按顺序执行。
  4. 错误捕获:用try/catch捕获可能的权限错误、文件读写错误等,方便调试和问题排查。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 05:11:11