我正在尝试使机器人在特定时间写消息。示例:
const Discord = require("discord.js");
const client = new Discord.Client();
client.on("ready", () => {
console.log("Online!");
});
var now = new Date();
var hour = now.getUTCHours();
var minute = now.getUTCMinutes();
client.on("message", (message) => {
if (hour === 10 && minute === 30) {
client.channels.get("ChannelID").send("Hello World!");
}
});
不幸的是,它只有在我触发另一个命令后才起作用:
if (message.content.startsWith("!ping")) {
message.channel.send("pong!");
}
my message: !ping (at 10:10 o'clock)
-> pong!
-> Hello World!
我想它需要不断检查时间变量的东西。
答案 0 :(得分:1)
我会使用cron
:如果日期与给定的模式匹配,则可以使用此软件包设置要执行的功能。
构建模式时,可以使用compute
表示可以使用该参数的任何值来执行,而范围则仅指示特定的值:*
表示您接受1-3, 7
。 / p>
这些是可能的范围:
1, 2, 3, 7
0-59
0-59
0-23
1-31
(一月至十二月)0-11
(周六)这是一个例子:
0-6
在您的情况下,我会这样做:
var cron = require("cron");
function test() {
console.log("Action executed.");
}
let job1 = new cron.CronJob('01 05 01,13 * * *', test); // fires every day, at 01:05:01 and 13:05:01
let job2 = new cron.CronJob('00 00 08-16 * * 1-5', test); // fires from Monday to Friday, every hour from 8 am to 16
// To make a job start, use job.start()
job1.start();
// If you want to pause your job, use job.stop()
job1.stop();
答案 1 :(得分:0)
正如 Federico 所说,这是解决这个问题的正确方法,但语法已经改变,现在随着 discord.js (v12) 的新更新,它会像:
// Getting Discord.js and Cron
const Discord = require('discord.js');
const cron = require('cron');
// Creating a discord client
const client = new Discord.Client();
// We need to run it just one time and when the client is ready
// Because then it will get undefined if the client isn't ready
client.once("ready", () => {
console.log(`Online as ${client.user.tag}`);
let scheduledMessage = new cron.CronJob('00 30 10 * * *', () => {
// This runs every day at 10:30:00, you can do anything you want
// Specifing your guild (server) and your channel
const guild = client.guilds.cache.get('id');
const channel = guild.channels.cache.get('id');
channel.send('You message');
});
// When you want to start it, use:
scheduledMessage.start()
};
// You could also make a command to pause and resume the job
但仍归功于 Federico,他救了我的命!