0
votes

First of All I'm sorry for my bad English. I'm working on a discord music bot, I wanna add a feature to make the bot stay for 30seconds before it disconnect from the voice channel (when idle = all music ended nothing to play more)

async function play(guild, song) {
    const serverQueue = queue.get(guild.id);
    if (!song) {
        setTimeout(function() {serverQueue.voiceChannel.leave();}, 30000);
        queue.delete(guild.id);
        return;
    }
    console.log(serverQueue.songs);
    const dispatcher = serverQueue.connection.playOpusStream(await ytdl(song.url))
        .on('end', reason => {
            console.log(reason)
            serverQueue.songs.shift()
            play(guild, serverQueue.songs[0])
        })
        .on('error', error => console.error(error));
    serverQueue.textChannel.send(`\`\`\`Start playing : ${song.title}\`\`\``);
}

but i want to make it disconnect immediately from the voice channel and End everything, when "stop" command used

else if (command === 'play') {

    const voiceChannel = message.member.voiceChannel;
    ...
}
else if (command === 'stop') {
    if (!message.member.voiceChannel) return message.channel.send("you are not in a voice channel")
    if (!serverQueue) return message.channel.send("nothing to stop!")
    serverQueue.songs = []
    serverQueue.connection.dispatcher.end();

    serverQueue.voiceChannel.leave();

    return undefined;
}
else if (command === 'next') {
    if (!message.member.voiceChannel) return message.channel.send("you are not in a voice channel")
    if (!serverQueue) return message.channel.send("nothing!")
    serverQueue.connection.dispatcher.end();
    message.channel.send("```Next music!```");
    return undefined;
}

When it end from playing a piece of music it wait 30 seconds, and disconnect, Ok! BUT The problem is : if anyone used 'play' command when waiting for that 30s, it play his music track but it cut everything after 30s (even if the second track didn't end)

.

1

1 Answers

1
votes

You will want to assign the setTimeout to a variable. Then use the clearTimeout function when you play again. To cancel the serverQueue.voiceChannel.leave().

The docs explain how to use it here