I set up a discord bot for taking youtube url's and playing them in the current voice channel the user who initiated the bot command is in. The bot can create a queue of multiple youtube links but when the first song in queue finishes playing the following code below is giving me an issue where it seems that it will run the logic as many times as there are songs in the queue. For example, if there are 6 songs in queue, the server.dispatcher.on(finish) logic executes 6 times in a row removing the songs in queue one by one until there are no songs left in queue and then the bot disconnects from the voice channel.
function playF(connectionF, message){
console.log("starting the play function ");
var server = servers[message.guild.id];
if(!playingMusic){
console.log("not playing music, running this logic ");
server.dispatcher = connectionF.play(ytdl(server.queue[0], {filter: "audioonly"}));
server.queue.shift();
playingMusic = true;
}
server.dispatcher.on("finish", () => {
console.log("running the finish logic ");
console.log("heres your queue length in finish " + server.queue.length);
playingMusic = false;
if(server.queue[0]){
playF(connectionF, message);
} else {
connectionF.disconnect();
}
});
}
```
So I figured out that I needed to restructure a bit to add the .on("finish") to the server.dispatcher on line 8. The following code is what fixed my issue.
function playF(connectionF, message){
console.log("starting the play function ");
var server = servers[message.guild.id];
if(!playingMusic){
playingMusic = true;
console.log("not playing music, running this logic ");
server.dispatcher = connectionF.play(ytdl(server.queue[0], {filter: "audioonly"})).on("finish", () =>{
playingMusic = false;
if(server.queue[0]){
playF(connectionF, message);
} else {
connectionF.disconnect();
}
});
server.queue.shift();
}
}
```