Search code examples
javascriptnode.jsdiscord.jsbotsjavascript-objects

How do I make the project to auto restart


I make bot discord Plays a radio 24/7 link radio live

The problem here is that the bot stops every once in a while Is there a solution to restart the bot every hour? When I manually restart the bot it works fine.

const Discord = require("discord.js");
const client = new Discord.Client();
const request = require('request');
const GUILDID = ''; 
const CHANNELID = '';
const url = 'https://sc.creacast.com/topmusic_strasbourg'; 
client.on('ready', async () => {
  console.log('done');
  voiceStay(GUILDID, CHANNELID);
  function voiceStay(guildid, channelid) {
    if (!guildid) throw new Error('id sv error');
    if (!channelid) throw new Error('id room error');
    let guild = client.guilds.cache.get(guildid);
    const voiceChannel = guild.channels.cache.get(channelid);;
    if (!voiceChannel) {
      return
    }
    voiceChannel.join()
      .then(connection => {
        const dispatcher = connection.play(url);
      });
  }
});
client.login("");

Note: My hosting provider only allows me to use javascript files.


Solution

  • Here are a few things you can try:

    • Using a kind of process manager:

      const { spawn } = require("child_process");
      
      function loop() {
        const bot = spawn("node", [ "file_of_bot.js" ], {
          stdio: "inherit",
        });
        bot.once("exit", (code) => {
          // prevents restarting the bot if the code had a fatal error
          if (code === 0) {
            loop();
          }
        });
      }
      loop();
      

      Then you can exit in your bot after an hour:

      setTimeout(process.exit, 1000 * 60 * 60)
      
    • Using pm2:

      npx pm2 start file_of_bot.js
      
      setTimeout(process.exit, 1000 * 60 * 60)
      
    • Destroying your client and re-logging in

      • You may need to wrap the creation of the bot to recreate it, as Client.destroy() seems to prevent Client.login() from being called in the future.
    • Exiting and re-joining the voice channel