【问题标题】:sending a scheduled message with cron & node.js使用 cron 和 node.js 发送预定消息
【发布时间】:2021-01-18 07:02:48
【问题描述】:

我是使用 node.js、cron 的新手,并且从非常基本的知识中再次学习 Javascript,所以请多多包涵。谢谢!

我的目标是运行一个 Discord 机器人,它每天在特定时间在我的服务器上发送特定消息。这里的很多用户都建议使用 cron 来实现这种功能,所以我安装了它并尝试使用他们建议的片段。

const cron = require('cron');
const Discord = require('discord.js');
const client = new Discord.Client();
const { token, guildid, channelid } = require('./config.json');

client.on('ready', () => {
    console.log('Good to go.');
});

const scheduledMessage = new cron.CronJob('00 00 08 * * *', () => {
const guild = client.guilds.cache.get(guildid);
const channel = client.channels.cache.get(channelid);
channel.send('My Message');
});


scheduledMessage.start()

我得到的错误是 TypeError: Cannot read property 'send' of undefined,虽然我很确定我可能会遇到更多问题,而且我认为我根本没有正确使用 cron 作业。

感谢任何帮助!

【问题讨论】:

  • 我不认为问题出在 cron 上,问题是 Discord 找不到您引用的频道。仔细检查 channelid 变量以确保它是有效的频道 ID

标签: javascript node.js cron discord.js


【解决方案1】:

你可以换个方向,完全只使用节点:

 var countDownDate = new Date("October 2, 2020 00:00:00").getTime();
 
    var currentTime = new Date().getTime();
 
    var timeDifference = countDownDate - currentTime;
 
    // If the count down is over, send the message
    if (timeDifference == 0) {
        let channel client.channels.cache.get('channelID');
        channel.send('messageHere')
    }
}

【讨论】:

    猜你喜欢
    • 2021-01-31
    • 2018-05-12
    • 1970-01-01
    • 2011-06-06
    • 1970-01-01
    • 2022-12-23
    • 2020-11-16
    • 2012-05-24
    • 2013-01-08
    相关资源
    最近更新 更多