Im trying to add a play command to my discord bot but

Viewed 70

I'm trying to add a play command to my discord bot so it can play music from youtube and maybe other places later but right now i just tried getting it to play a audio file from my computer to test if i could make it join and play something before getting into the more complicated stuff like figuring out how to get it to play a song/audio from a youtube url

right now, this is what i have

Crashbot.on('message', async message => {

    let args = message.content.substring(PREFIX.length).split(" ");

    switch (args[0]) {
        case 'play':
            if (message.member.voice.channel) {
                const connection = await message.member.voice.channel.join().then(() => {

                    const dispatcher = connection.play('audio.mp3');

                    dispatcher.on('start', () => {

                    });

                    dispatcher.on('error', console.error);

                })
            }
    }

})

and every time i run it i get this error

(node:18884) UnhandledPromiseRejectionWarning: ReferenceError: Cannot access 'connection' before initialization
    at C:\Users\Michael\Desktop\Crashbot\index.js:213:40
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
    at async Client.<anonymous> (C:\Users\Michael\Desktop\Crashbot\index.js:211:36)
(node:18884) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:18884) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
1 Answers

Try removing the .then(...). Since there is an await, it runs well without .then(). And the connection is, in your code, the returned value of the promise. So it throws an error.

Try this code:

const connection = await message.member.voice.channel.join();

const dispatcher = connection.play('audio.mp3');

dispatcher.on('start', () => {});

dispatcher.on('error', console.error);
Related