如何在Discord.js v14中使用斜杠命令定时发送机器人消息?
我需要用机器人给用户定时发送消息,希望能自定义消息的发送日期和时间。我完全没接触过这部分开发,来寻求帮助。我的代码结构是在commands文件夹里添加对应命令的.js文件,这个命令的初始代码如下:
const Discord = require("discord.js") module.exports = { name: "schedule", // 命令名称 description: "定时发送消息。", // 命令描述 type: Discord.ApplicationCommandType.ChatInput, options: [ { name: "schedule", description: "定时发送消息。", type: Discord.ApplicationCommandOptionType.String, required: true, } ], run: async (client, interaction) => {
解决方案
1. 重构命令参数选项
把单一的模糊参数拆分成明确的必填项,让用户能精准输入定时需求:
options: [ { name: "channel", description: "选择要发送消息的频道", type: Discord.ApplicationCommandOptionType.Channel, channel_types: [Discord.ChannelType.GuildText], // 限制为文本频道 required: true, }, { name: "message", description: "要定时发送的消息内容", type: Discord.ApplicationCommandOptionType.String, required: true, }, { name: "time", description: "发送时间(格式:YYYY-MM-DD HH:mm,例如2024-05-20 14:30)", type: Discord.ApplicationCommandOptionType.String, required: true, }, ],
2. 实现定时核心逻辑
补全run函数,完成时间解析、合法性校验和定时任务调度:
run: async (client, interaction) => { // 提取用户输入的参数 const targetChannel = interaction.options.getChannel("channel"); const messageContent = interaction.options.getString("message"); const inputTime = interaction.options.getString("time"); // 解析输入时间为Date对象 const scheduledTime = new Date(inputTime); // 校验时间有效性:必须是合法的未来时间 if (isNaN(scheduledTime.getTime()) || scheduledTime < new Date()) { return interaction.reply({ content: "⚠️ 请输入有效的未来时间,格式为YYYY-MM-DD HH:mm", ephemeral: true, // 仅发起者可见 }); } // 计算当前到定时时间的毫秒差 const delay = scheduledTime.getTime() - Date.now(); // 设置定时器执行发送任务 setTimeout(async () => { try { await targetChannel.send(messageContent); // 可选:给发起者发送任务完成通知 interaction.user.send(`✅ 定时消息已发送到${targetChannel}:\n${messageContent}`).catch(() => {}); } catch (error) { console.error("定时消息发送失败:", error); interaction.user.send(`❌ 定时消息发送失败:${error.message}`).catch(() => {}); } }, delay); // 给发起者反馈任务已创建 await interaction.reply({ content: `✅ 定时任务已创建!消息将在${scheduledTime.toLocaleString()}发送到${targetChannel}`, ephemeral: true, }); },
3. 关键注意事项
- 时区问题:默认使用机器人服务器的时区,若需匹配用户本地时区,可引入
moment-timezone库处理(新手阶段可先忽略)。 - 任务持久化:机器人重启后未执行的定时任务会丢失,若需持久化,可将任务数据存入SQLite/MongoDB,启动时重新加载未完成任务。
- 权限控制:可添加代码校验用户是否拥有频道管理权限,避免普通用户滥用命令。
内容的提问来源于stack exchange,提问作者Luis Carvalho
相关产品推荐
相关产品推荐

