首页 > 解决方案 > 使用 node-cron 进行调度部署 Discord.js 机器人时的端口绑定时间问题

问题描述

从 2020 年 3 月 22 日到 2020 年 4 月 27 日,我一直在尝试创建一个 Discord 机器人,它会在每天上午 9:00 和晚上 9:00 发布提醒。

调度过程是我最初陷入困境的地方。我采用了 2 种方法: 1. 自己做,使用 12 小时长的 setInterval(),当我这样做时,我收到一个错误,指出程序未能在 60 秒内绑定到端口。

  1. 使用 node.js cron 库https://github.com/kelektiv/node-cron。但在这种情况下,代码本身并没有像我期望的那样工作


const Discord = require('discord.js');
const cron = require('cron')
const client = new Discord.Client();

const dolChannelID = '<a working channel's id>'
let dolChannel = null

const msgs = {
    'morning': 'Morning msg',
    'evening': 'Evening msg',
    'finale': 'Final msg before ending'
}
const startTime = new Date('March 22, 2020 9:38:00')
const lastDate = new Date('April 27, 2020 21:00:00')

// --------------------------------------------------

client.on('ready', () => {

    console.log('we\'re up and running!')

    client.channels.fetch(dolChannelID)
    .then(channel => {
        dolChannel = channel
        dolChannel.send('Bot\'s working')
    })
    .then(() => {
        let execJob = new cron.CronJob('50 9,21 * * *', function() {
            let rn = new Date()
            console.log('time', rn)
            // IDEALLY HERE I'D EXPECT TO GET A CONSOLE LOG TELLING ME THE TIME twice a day, 
            // starting at 9:50 AM, but that didn't happen
            // ALTHOUGH, when my cron time expression: '* * * * * *', then things worked somehow 
            //i.e. I got an console.log every sec.


        }, null, true, 'Asia/Kolkata')
        execJob.start()
    })
    .catch((err) => {
        console.log('error \n \n', err)
    })
})


client.login(<my secret>);


我将不胜感激任何帮助。我似乎无法弄清楚

标签: node.jsherokucrondiscord.jsnode-cron

解决方案


推荐阅读