Chin Hong Tan
Chin Hong Tan

Reputation: 167

TypeError: Cannot set property 'dispatcher' of undefined

I am doing a discord music bot, and I wrote the code below:

module.exports = {
    name: 'play',
    aliases: ['p'],
    description: 'Play a song',
    guildOnly: true,

    execute(message, args) {
        const ytdl = require("ytdl-core");
        
        var servers = {}
        var server = servers[message.guild.id];
        var queue = []
        
        function play(connection, message){
            var server = servers[message.guild.id];
            var str = String(message)
            var key = str.split(/\s/);


            // If user inputs skip, skip the song
            try {
                server.dispatcher = connection.play(ytdl(queue[0], {filter: "audio"}));
            } catch (error) {
                if (key[1] == "skip") {
                    server.dispatcher.destroy();
                } else {
                    message.channel.send("You need to provide a correct url!");
                    console.log(error)
                    }
                return;
                }

            queue.shift();

            server.dispatcher.on("finish", function(){
            if (queue[0]){
                play(connection, message);
            } else {
                connection.disconnect();
            }
        });
        }
//------------function ends here-------------------

        if (!args[0]) {
            message.channel.send("You need to provide a link!");
            return;
        }

        if (!message.member.voice.channel){
            message.channel.send("You must be in a voice channel to use this command!");
            return;
        }

        queue.push(args[0]);

        if (!message.guild.voiceConnection) message.member.voice.channel.join().then(function(connection){
            play(connection, message);
        });
}}

Whenever I run the code, it always give me the error

TypeError: Cannot set property 'dispatcher' of undefined

The error occured in line 22, which is

server.dispatcher = connection.play(ytdl(queue[0], {filter: "audio"}));

As far as I know, when a variable is declared but has not been assigned a value, it will throw the error. But I just assigned the value above it, and I cannot understand why it gives me the error.

By the way the song queue and skip functions never worked, so I will really appreciate it if someone can help me to correct the errors, thanks a lot!

Upvotes: 0

Views: 361

Answers (1)

Saar Davidson
Saar Davidson

Reputation: 1382

var servers = {}
var server = servers[message.guild.id];

since servers is an empty object you shouldn't expect it to have message.guild.id property

Upvotes: 1

Related Questions