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

Node.js(discord.js)如何实现定时检查并向指定频道发送消息与Embed

现有逻辑问题修正

你当前的判断条件存在两处错误:

  1. hours = 4是赋值操作,不是相等判断,会导致逻辑完全不符合预期,需改为hours == 4
  2. 逻辑运算符优先级问题,现有写法会导致每周任意日期的04:00~04:54都触发,如果你需要的是仅周四15:39到周五04:54触发,修正后的判断如下:
if (day == 4 && ((hours == 15 && minutes >= 39) || hours > 15 || hours < 4 || (hours == 4 && minutes < 55))) {
  // 触发逻辑
}

向指定频道发送消息实现

前置准备

  1. 开启Discord客户端开发者模式,右键目标频道复制ID
  2. 确保机器人已开启Guilds、GuildMessages权限,且在目标频道拥有发送消息、嵌入链接权限

发送普通文本消息

// 替换为你的目标频道ID
const targetChannelId = '你的频道ID';
// 拉取频道实例
const targetChannel = await client.channels.fetch(targetChannelId);

if (targetChannel) {
  // 发送普通文本
  await targetChannel.send('定时触发的消息内容');
}

发送Embed类型消息

discord.js v14 版本需先导入EmbedBuilder,v13及更低版本使用MessageEmbed即可:

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

// 构建Embed实例
const notifyEmbed = new EmbedBuilder()
  .setColor(0x0099ff) // 侧边栏颜色,支持十六进制色值
  .setTitle('定时通知')
  .setDescription('这是Embed的正文描述内容')
  .addFields(
    { name: '字段1', value: '自定义内容1', inline: true },
    { name: '字段2', value: '自定义内容2', inline: true }
  )
  .setTimestamp() // 自动添加当前时间戳
  .setFooter({ text: '底部备注内容' });

// 发送Embed到指定频道
if (targetChannel) {
  // 支持同时发送普通文本+Embed
  await targetChannel.send({
    content: '附带的普通文本内容,不需要可以删除该行',
    embeds: [notifyEmbed]
  });
}

完整可运行示例

const { Client, GatewayIntentBits, EmbedBuilder } = require('discord.js');
const client = new Client({ 
  intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages] 
});

// 替换为你的实际参数
const TARGET_CHANNEL_ID = '你的频道ID';
const BOT_TOKEN = '你的机器人Token';

client.on('ready', () => {
  console.log(`机器人已登录:${client.user.tag}`);
  // 每分钟执行一次定时检查
  setInterval(async () => {
    const now = new Date();
    const day = now.getDay(); // 0=周日,4=周四
    const hours = now.getHours();
    const minutes = now.getMinutes();

    // 修正后的触发条件
    if (day == 4 && ((hours == 15 && minutes >= 39) || hours > 15 || hours < 4 || (hours == 4 && minutes < 55))) {
      const targetChannel = await client.channels.fetch(TARGET_CHANNEL_ID);
      if (!targetChannel) return console.error('未找到目标频道');

      const notifyEmbed = new EmbedBuilder()
        .setColor(0x2ecc71)
        .setTitle('定时任务触发')
        .setDescription('当前时间符合触发规则')
        .setTimestamp();

      await targetChannel.send({ embeds: [notifyEmbed] });
    }
  }, 60 * 1000); // 检查间隔:60秒
});

client.login(BOT_TOKEN);

注意事项

  • 如果需要更高精度的定时任务,可使用node-schedule库替代setInterval
  • 机器人Token不要泄露到公开代码仓库
  • 发送Embed时最多同时传入10个Embed实例

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 23:24:03