6

I've just started on Javascript and Node.js, so I don't really know what to do. Please be patient with me. Thanks!

So I've hosted a node.js on my physical server. I wanted to create a Discord Bot that sends a daily message on specific timings on my server, for example, I want to send a message to a channel saying "Good Morning" every day at 8 am. How do I do it?

Currently, I only have this code to ping the bot (and the server)

/*
 A ping pong bot, whenever you send "ping", it replies "pong".
*/

// Import the discord.js module
const Discord = require('discord.js');

// Create an instance of a Discord client
const client = new Discord.Client();

// The token of your bot - https://discordapp.com/developers/applications/me
const token = 'your bot token here';

// The ready event is vital, it means that your bot will only start reacting to information
// from Discord _after_ ready is emitted
client.on('ready', () => {
  console.log('I am ready!');
});

// Create an event listener for messages
client.on('message', message => {
  // If the message is "ping"
  if (message.content === 'ping') {
    // Send "pong" to the same channel
    message.channel.send('pong');
  }
});

// Log our bot in
client.login(token);

Also, how do I loop this code to ensure that it sends a message everyday? Thanks in advance.

Federico Grandi
  • 6,785
  • 5
  • 30
  • 50
Samuel Smith
  • 139
  • 1
  • 1
  • 13

1 Answers1

8

so there is an answer for this:

There are two ways to do that, with cron (or something else on different platforms) and setInterval

1) Cron

Create a new file, goodmorning.js with this:

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

client.login("token").then(() => {
    console.log("I am ready");
    var guild = client.guilds.get('guildid');
    if(guild && guild.channels.get('channelid')){
        guild.channels.get('channelid').send("Good Morning").then(() => client.destroy());
    } else {
        console.log("nope");
        //if the bot doesn't have guild with the id guildid
        // or if the guild doesn't have the channel with id channelid
    }
    client.destroy();
});

(edit all the needed values: token, guildid and channelid)
And add a cronjob to run everyday at 8am.
This script will attempt to login into Discord and after successful login proceeds to find a guild and a channel, then just send the message, then finally logout (client.destroy()). If it wasn't found a guild or channel, just simply destroy.

2) setInterval

The first problem with this would be that you need to start the script at the exact time you want the code to run, or get a setTimeout to start the setInterval to repeat the code over and over.
untested but should work with possibly some tweaking needed:

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

client.on('message', message => {
    //...
});

client.on('ready', () => {
    setTimeout(function(){ // in leftToEight() milliseconds run this:
        sendMessage(); // send the message once
        var dayMillseconds = 1000 * 60 * 60 * 24;
        setInterval(function(){ // repeat this every 24 hours
            sendMessage();
        }, dayMillseconds)
    }, leftToEight())
})

function leftToEight(){
    var d = new Date();
    return (-d + d.setHours(8,0,0,0));
}

function sendMessage(){
    var guild = client.guilds.get('guildid');
    if(guild && guild.channels.get('channelid')){
        guild.channels.get('channelid').send("Good Morning");
    }

}

client.login("token");

I would definitely go for the cron option, doesn't require you to have the process running all the time (unless you already have it)

André
  • 4,417
  • 4
  • 29
  • 56
  • Watch out if you are running this option 2 AFTER 8 am, because in that case, it will trigger imediately, and then 24h from that point forward. since d.setHours will set the timestamp to BEFORE the current time, the result of leftToEight() will be negative. and when setTimeout receives negative input, it will use the minimum (which i would guess is 1 ms?) – Fre Timmerman Apr 08 '19 at 17:19
  • does the cron options will interfered with the ongoing running code like my `main.js` which is on 24/7 – Ryuujo Feb 13 '20 at 07:18
  • @Ryuujo it won't. – renov8 Feb 23 '20 at 07:55
  • Where is the cron part of it? Where do you say the program to run by the cron expression? – avivgood2 May 31 '20 at 12:03
  • @avivgood2 It is not mentioned here. Cron is a seperate scheduler which you can use to invoke the script. I.e, whenever you run the script, it sends the corresponding message. Cron does the job of running at a specified time. – Nevin Baiju Jun 29 '20 at 06:15
  • @NevinBaiju can't I set the CRON expression within the program? so for example I can get from the user a date it will call the function by the date the user has entered? or it just have to be some outside service that run the code according to the cron expreresion? – avivgood2 Jun 29 '20 at 07:50
  • I guess you will have to look around for CRON interfaces with javascript. A couple years back I believe I've come across a Python interface which lets you do this. I've found this module on a surface level search, hope it will be useful. https://github.com/kelektiv/node-cron – Nevin Baiju Jun 29 '20 at 08:07