'Discord radio bot randomly disconnecting

Djs (v12)

Maybe someone is already familiar with this problem in their code and knows the solution. After a few hours of listening, the bot just randomly stops playing music from the web by URL and leaves the voice channel.

Here's a bit of my code where the problem is hiding, thanks for any answers or solutions :-)

const commands = {
    "play-join": {
        process: function(message) {
            
            if (message.content.toLowerCase() == "?play-join") {
        if (message.channel.type == "dm") return;

        const role = message.guild.roles.cache.find((r) => r.name === 'DJ')

        if (!role) return message.reply(`**DJ** role is not created`)
        if (!message.member.roles.cache.has(role.id)) return message.reply(`You need to have ${role} role.`);

        var shuffle1 = Math.floor(Math.random() * connect_log.length);

        const voiceChannel = message.member.voice.channel
        if (voiceChannel) {

            if (!client.voice.connections.some(conn => conn.channel.id == voiceChannel.id)) {
                
            var EventEmitter = require('events');
            const emitter = new EventEmitter()
            emitter.setMaxListeners(0)

                message.member.voice.channel.join().then(connection => {
                        require('http').get("http://STREM_URL", (res) => {
                            connection.play(res);
                            message.channel.send(connect_log[shuffle1]);
                            connection.voice.setSelfDeaf(true);

                        });
                    });
                }
            } else {
                message.reply("Be in a Voice Channel!");
            }}
        }
    }
}


Solution 1:[1]

After some time, I had figured it out. If someone is having problems as I did, use stateChange and Idle event, then reconnect if the state changes from playing to Idle. Thanks for your answers guys it really helped!

Solution 2:[2]

If you're hosting your bot on Heroku you can try this:

  • Add a new file named Procfile to your root directory
  • Open the file and paste in this line: worker: node index.js and save it
  • Push it to your git repo
  • Open up your Heroku project
  • Navigate to the Resources tab
  • Now there should be a new option called worker: node index.js, edit it so you can activate it

Before hosting my bot on a VPS I hosted it on Heroku too and following this steps made my bot never fall asleep. Hope it helps for you too :)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Term
Solution 2 Toasty