简体   繁体   中英

Make my discord bot send message at specific hours

I have a problem I almost resolved but i'm now stuck.

I want to make my bot send a message in a channel at mirror hours (00h00, 01h01, 02h02...) for a running gag with my friends and currently I made this: At the top of my code I have var currentdate = new Date();

And then, later in my source code:

if(currentdate.getMinutes() == currentdate.getHours())
{
    bot.channels.get('SPECIFICCHANNELID').send('Touchez votre nez :nose:');
}

It's sort of working since the message is sent by the bot in the right channel, but the message is only sent when the bot detects a message, so if during any mirror hour, no one send a message, then the bot will not send anything.

And if there is multiples messages during this interval of time, the bot will also send the message multiple times, of course I want it to send the message only 1 time for exemple at 11:11:00.

Thank you for the help and sorry if my english is bad !

You need to be checking at some interval whether or not to send a message.

Something like setInterval would work.

setInterval(function(){
    if(currentdate.getMinutes() == currentdate.getHours())
    {
        bot.channels.get('SPECIFICCHANNELID').send('Touchez votre nez :nose:');
    }
}, MIN_INTERVAL)


You want MIN_INTERVAL to be the minimum amount of time in milliseconds to check for sending messages.

If you want to check every minute

const MIN_INTERVAL = 1000 * 60

由于使用了node-cron模块,问题得以解决。

You have to use if statement and you didn't specified hour or minutes, so the bot can't send message.


 async function verifyTime() {
    var d = new Date();

    if (d.getHours() == d.getMinutes()) {

           //your code goes here
          
        } catch (error) {

            console.log(error);

        }
        setTimeout(() => {
            verifyTime();
        }, 61 * 1000);
    } else {
        setTimeout(() => {
            verifyTime();
        }, 1000);
    }
 }


client.login(token);

//⬇ remember to place this under your client.login

setTimeout(() => {
 verifyTime();
 }, 5000);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM