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

编程入门 行业动态 更新时间:2024-10-25 12:19:13
本文介绍了如何每天在特定时间发送消息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

I'm trying to make the bot writing messages at specific times. Example:

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!"); } });

不幸的是,它只有在我触发另一个命令后才起作用:

Unfortunately, it only works once I trigger another command like:

if (message.content.startsWith("!ping")) { message.channel.send("pong!"); }

my message: !ping (at 10:10 o'clock) -> pong! -> Hello World!

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

I guess it needs something that constantly checks the time variables.

推荐答案

我会使用 cron :使用此程序包,可以设置日期与给定模式匹配时要执行的功能。 构建模式时,可以使用 * 表示可以使用该参数的任何值来执行,并且范围仅指示特定值: 1-3,7 表示您接受 1、2、3、7 。

I would use cron: with this package you can set functions to be executed if the date matches the given pattern. When building the pattern, you can use * to indicate that it can be executed with any value of that parameter and ranges to indicate only specific values: 1-3, 7 indicates that you accept 1, 2, 3, 7.

这些是可能的范围:

  • 秒: 0-59
  • 分钟: 0-59
  • 工作时间: 0-23
  • 每月的天数: 1-31
  • 月的时间: 0-11 (1月至12月)
  • 星期几: 0-6 (周日至周六)
  • Seconds: 0-59
  • Minutes: 0-59
  • Hours: 0-23
  • Day of Month: 1-31
  • Months: 0-11 (Jan-Dec)
  • Day of Week: 0-6 (Sun-Sat)

这里是一个例子:

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();

在您的情况下,我会这样做:

In your case, I would do something like this:

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

更多推荐

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

本文发布于:2023-11-25 18:38:37,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1630888.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:发送消息   时间   在特定

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!