gpt4 book ai didi

javascript - 如何在每天的特定时间发送消息?

转载 作者:行者123 更新时间:2023-12-01 01:25:47 24 4
gpt4 key购买 nike

我正在尝试让机器人在特定时间写入消息。示例:

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!

我想它需要不断检查时间变量的东西。

最佳答案

我会使用cron :使用此包,您可以设置在日期与给定模式匹配时要执行的函数。
构建模式时,您可以使用 * 来指示它可以使用该参数的任何值来执行,并使用范围来指示仅特定值:1-3, 7 指示您接受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();

对于你的情况,我会做这样的事情:

const cron = require('cron');

client.on('message', ...); // You don't need to add anything to the message event listener

let scheduledMessage = new cron.CronJob('00 30 10 * * *', () => {
// This runs every day at 10:30:00, you can do anything you want
let channel = yourGuild.channels.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

关于javascript - 如何在每天的特定时间发送消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53820970/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com