Making a simple music bot for discord server, not working

Working on making a bot for a personal discord server, wanting it to simply join general voicechat when command "Blyat" is detected, play mp3 file, when its done to leave. Code:

var Discord = require('discord.js');
var client = new Discord.Client();
var isReady = true;

client.on('message', message => {
    if (command === "Blyat") {
        var VC = message.member.voiceChannel;
        if (!VC) return message.reply("MESSAGE IF NOT IN A VOICE CHANNEL")
        VC.join()
            .then(connection => {
                const dispatcher = connection.playFile('C:\Users\Wyatt\Music\soviet-anthem.mp3');
                dispatcher.on("finish", end => { VC.leave() });
            })
            .catch(console.error);
    };
});

client.login('token, not putting in code, is there in real code');

Error: "ReferenceError: command is not defined at Client. (C:\Users\jeffofBread\Desktop\Discord Bot\main.js:6:5)"

Any help or tips will be much appreciated, haven't coded in many years and have lost any knowledge I had once held.

Answers 1

  • Your problem comes from an unidentified variable. Fortunatly that is very easy to fix. All you have to do is define command before you call it.

    For this we'll splice the message content into two parts. The command and any arguments that may be included like mentions or other words. We do that with:

    const args = message.content.slice(prefix.length).split(/ +/);
    const command = args.shift().toLowerCase();
    

    Note: The args constant is an array.

    Which would make your entire onMessage event look like this:

    client.on('message', message => {
        const prefix = "!";
        const args = message.content.slice(prefix.length).split(/ +/);
        const command = args.shift().toLowerCase();
    
        if (command === "blyat") {
            var VC = message.member.voice.channel;
            if (!VC) return message.reply("MESSAGE IF NOT IN A VOICE CHANNEL")
            VC.join()
                .then(connection => {
                    const dispatcher = connection.play('C:\Users\Wyatt\Music\soviet-anthem.mp3');
                    dispatcher.on("finish", end => { VC.leave() });
                })
                .catch(console.error);
        };
    });
    

Related Articles