Skip to content
Advertisement

How to I make my music bot play a finite playlist of songs?

Building further on my music bot… I’m trying to make the jump from having him play a single song, and then leave, to having him play a finite list of songs, and then leave.

This should not be confused with a queue – the list of songs is predetermined and finite. It can’t be added to or changed by the bot, at least at this time. The bot DOES shuffle the list though.

The problem right now is that instead of playing the songs in the list, one by one – he plays the first song, then the second… and stops dead.

I’ve tried setting up a loop based on the length of the SongToPlay array, but all that does is make the bot rapidly spam through each song (before the previous song had time to play), and leave.

const connection = message.member.voice.channel.name;
            const channel = message.member.voice.channel;
            message.channel.send("Now playing Scythe OST in the "+connection+" channel.");
            var SongToPlay = shuffle(testbells);
            channel.join().then(connection => {
                console.log('Now playing '+SongToPlay[0]+'.');
                message.channel.send('Now playing '+SongToPlay[0]+'.');
                const dispatcher = connection.play('./Scythe Digital Edition - Soundtrack/'+SongToPlay[0]+'.mp3');
                dispatcher.setVolume(0.1);
                dispatcher.on("finish", () => {
                    SongToPlay.shift();
                    console.log('Now playing '+SongToPlay[0]+'.');
                    message.channel.send('Now playing '+SongToPlay[0]+'.');
                    connection.play('./Scythe Digital Edition - Soundtrack/'+SongToPlay[0]+'.mp3');
                    dispatcher.setVolume(0.1);
                });
                channel.leave();
            })
            .catch(console.error);

Advertisement

Answer

const connection = message.member.voice.channel.name; const channel = message.member.voice.channel; message.channel.send("Now playing Scythe OST in the "+connection+" channel.");

var SongToPlay = shuffle(testbells); channel.join().then(connection => {
    let currentSong = 0;
    const keepPlaying = () => {
        console.log(`Now playing ${SongToPlay[currentSong]}.`);
        message.channel.send(`Now playing ${SongToPlay[currentSong]}.`);
        const dispatcher =
        connection.play(`./Scythe Digital Edition - Soundtrack/${SongToPlay[currentSong]}.mp3`);
        dispatcher.setVolume(0.1);
        dispatcher.on("finish", () => {
            if (currentSong < SongToPlay.length - 1) {
                currentSong++;
                keepPlaying();
            }

        });
    }
    keepPlaying();
}).catch(console.error);
Advertisement