如何让Discord机器人实现每周五自动定时发送消息的功能?
实现每周五自动发送视频的方案
第一步:安装定时任务依赖
首先安装node-cron包,这是Node.js下常用的cron任务实现库:
npm install node-cron
第二步:修改主文件index.js
首先引入依赖,同时提前获取你要发送视频的Discord频道ID(开启Discord开发者模式后右键频道即可复制ID):
const Discord = require("discord.js"); const fs = require("fs"); const cron = require('node-cron'); // 新增引入cron依赖 require("dotenv").config() const token = process.env.token; const { prefix } = require("./config.js"); // 替换为你实际要发送消息的频道ID const TARGET_CHANNEL_ID = '你复制的目标频道ID'; // 和现有beeame命令使用的视频路径保持一致 const VIDEO_PATH = "./beeame.mp4"; const client = new Discord.Client(); const commands = {}; // load commands const commandFiles = fs.readdirSync("./commands").filter(file => file.endsWith(".js")); for (const file of commandFiles) { const command = require(`./commands/${file}`); commands[command.name] = command; } // login bot client.on("ready", () => { console.log(`Logged in as ${client.user.tag}`); // 新增定时任务:cron表达式格式为 秒(可选) 分 时 日 月 周 // 下方表达式代表每周五中午12点整触发,可按需调整时间 const fridayTask = cron.schedule('0 12 * * 5', () => { try { const targetChannel = client.channels.cache.get(TARGET_CHANNEL_ID); if (!targetChannel) { console.log('未找到目标频道,请检查频道ID是否正确'); return; } targetChannel.send("It's Friday!", { files: [VIDEO_PATH] }); console.log('周五定时消息已发送'); } catch (err) { console.error('定时任务执行出错:', err); } }, { scheduled: true, timezone: "Asia/Shanghai" // 替换为你所在的时区,避免时间偏差 }); fridayTask.start(); }); client.on("message", message => { if(!message.content.startsWith(prefix) || message.author.bot) return; const args = message.content.slice(prefix.length).trim().split(/ +/); const command = args.shift().toLowerCase(); let cmd = commands[command]; if(cmd) cmd.execute(message, args) }); client.login(token);
可选优化:复用已有的beeame命令逻辑
如果你不想重复写发送逻辑,可以修改commands/beeame.js的实现,让它同时支持手动触发和定时触发:
module.exports = { name: "beeame", description: "b", // 支持传入message对象或者直接传入channel对象 execute: (input, args = []) => { const channel = input.channel || input; channel.send("It's Friday!", { files: ["./beeame.mp4"] }); } }
修改后,index.js定时任务里的发送逻辑可以直接调用该命令,无需重复写代码:
// 定时任务中的发送部分替换为: commands['beeame'].execute(targetChannel);
注意事项
- 机器人需要保持持续运行状态,定时任务才会正常触发,你可以使用
pm2等进程管理工具让机器人后台长期运行 - 确认机器人拥有目标频道的发送消息、上传附件权限
- cron表达式可按需调整,比如每周五下午6点触发对应表达式为
0 18 * * 5
内容的提问来源于stack exchange,提问作者user16929716
相关产品推荐
相关产品推荐

