player.stop not stopping discord music bot

Viewed 412

I made a simple music bot that only works with URLs, and what I'm trying to do is to check if in the command argument there is 'stop' (Already done and working), and then stop the music player. The problem is that when player.stop() while music is playing it does not stop. Here is my code:

    const ytdl = require('ytdl-core');
module.exports ={
    name:'play',
    description:'aaaaaaaaaaaam',
    async execute(message, args, Discord){
        const { joinVoiceChannel, createAudioPlayer, createAudioResource} = require('@discordjs/voice');
            const stream = ytdl(args[0], {filter: 'audioonly', quality:'highestaudio', highWaterMark: 1<<25 });
            const player = createAudioPlayer();
            const resource = createAudioResource(stream);
            const {AudioPlayerStatus} = require('@discordjs/voice');
        if(ytdl.validateURL(args[0])){
            const connection = joinVoiceChannel({
                channelId: message.member.voice.channel.id,
                guildId: message.guild.id,
                adapterCreator: message.guild.voiceAdapterCreator
            })
        connection.subscribe(player);
        player.play(resource);

        } else if(args[0] === undefined){
            const embed = new Discord.MessageEmbed()
            .setColor('#0000FF')
            .setTitle('Da me chevvoi, te posso canta na canzone')
            message.channel.send({ embeds: [embed] });
        } 
        if (args[0] === 'stop'){
            player.on(AudioPlayerStatus.Playing, () => {
                player.stop();
            });
        }
        const {generateDependencyReport} = require('@discordjs/voice');
        console.log(args[0]);
        console.log(generateDependencyReport());
        
    }
}
1 Answers

The reason your AudioPlayer does not stop is because the player.stop() line is never reached. In the if-block of your stop command you create a listener to the AudioPlayer. What this does is it will listen for the AudioPlayerStatus.Playing to be reached and when it does, it will run the code block you have provided, which in this case will stop the player.

However, the way listeners work is it will only be triggered when entering that state. So when your player goes from any state to the playing state that code will trigger after the listener has been created. If you call your stop command while the player is already playing, it will not enter the playing state (since it is already in the playing state) and ergo not trigger its code block and not stop playing.

I'm guessing you're trying to check if the player is playing before attempting to stop it. You can do that by checking the player.state.status.

Related