How can I send a message every day at a specific hour?

前端 未结 1 1848
逝去的感伤
逝去的感伤 2021-01-07 13:17

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

const Discord = require(\"discord.js\");
const client = new Discord.Client();
client         


        
1条回答
  •  一整个雨季
    2021-01-07 13:24

    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.

    These are the possible ranges:

    • 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)

    Here's an example:

    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
    

    0 讨论(0)
提交回复
热议问题