How to avoid multiple instance of a bot in Discord server

Viewed 704

I created a bot to run on a private server. This bot checks the current datetime and gives commands at specific hours. I experienced in a previous version of the bot multiple disconnections which appeared to be caused by a discord problem. My solution was then to set a cron command to relaunch the bot every hour, just in case it crashed previously. Now, my bot is running perfectly but it seems I have multiple instances of the bot in the server, since every message is sent 4 or 5 times.

Is there a mean to chec if the node server is already active or if the bot is already logged in ?

The cron : 00 * * * * cd C:/Users/[...]/bot/ && node bootstrap.js

The bot constructor :

    let self = this;

    this.file = './env/env_'+pEnv+'.json';

    //Env file
    let tmpData = _FS.readFileSync(this.file);  
    this.params = JSON.parse(tmpData);

    //Timer setup
    this.interval = setInterval(function(){self.checkTimer();},1000);

    //Discord client launch
    this.client = new _DISCORD.Client();
    this.client.login(pToken);
    this.client.on('ready', () => {
        self.init();
    });
    self.client.on('message', (pMessage) => {
       self.reacts(pMessage);
    });
}```
1 Answers

You set cron to run every hour which will execute a new instance every hour, even if there was already an instance(s) running. I recommend using Forever to ensure the app restarts upon closing.

You can run it with forever start app.js and it'll give you what you're after.

Related