Discord music bot in Javascript

Viewed 95

After running this script there is no errors, but somehow when I try to use any of arguments like play nothing happens. I don't get any errors. Script just logs into Discord bot and nothing happens except that last line in which script gives feedback about proper login.

const { Client, Intents, Attachment} = require('discord.js');
const client = new Client({ intents: [Intents.FLAGS.GUILDS] });
const PREFIX = '!';
const ytdl = require("ytdl-core");

var servers = {};

client.on('message', message => {
    let args = message.content.substring(PREFIX.length).split(" ");

    switch (args[0]) {
        case 'play':

            function play(connection, message){
                var server = servers[message.guild.id];

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

                server.queue.shift();

                server.dispatcher.on("end", function(){
                    if(server.queue[0]){
                        play(connection, message);
                    }else {
                        connection.disconnect();
                    }
                });
            }

            if(!args[1]){
                message.channel.send("give a link");
                return;
            }

            if(!message.member.voiceChannel){
                message.channel.send("you must be on voice chat to play music");
                return;
            }

            if(!servers[message.guild.id]) servers[message.guild.id] = {
                queue: []
            }

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

            server.queue.push(args[1]);

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

        break;

        case "ping":
            message.channel.send("pong");
            console.log("pong");
            break;
    }
});

client.login(token);

client.on('ready', () => {
    console.log(`Logged in as ${client.user.tag}!`);
  });
1 Answers

Try using the "play-dl" module instead of ytdl-core.

So to play a music it is now

const ytdl = require('play-dl');

// Play a music
await ytdl.stream(song_url, { filter: "audioonly" })

// Search something on YouTube
await ytdl.search(arguments, { source: { youtube: "video" } })

// Test if is a YouTube url
if (ytdl.yt_validate(url) === "video" && string.startsWith('https'))

This module can also play from Deezer, Spotify and SoundCloud

Hope this helps :)

Related