Player

The player class makes you able to easily customize your music bot.

Creating a player

You can create a player by using the Player class. The class requires the channel parameter which is the channel where you want to create a player for.

const {Player} = require('discordaudio');
const discord = require('discord.js');

const client = new discord.Client({intents: [discord.Intents.FLAGS.GUILDS]});

const channel = client.channels.cache.get('0123456789');

const player = new Player(channel);

Playing a song

You can play a song by using the play function. The function requires the stream parameter and has an optional options parameter and returns a Promise. The stream parameter is the stream that you want to play (YouTube url's are also allowed). The options parameter has the following options:

  • autoleave: If the bot should leave the channel when the song ended and has to be a boolean. (default is false)

  • quality: The quality of the song. The quality options are:

    • 'high': Sets the quality to high

    • 'low': Sets the quality to low (default)

  • selfDeaf: If the bot should deaf itself and has to be a boolean. (default is true)

  • selfMute: If the bot should mute itself and has to be a boolean. (default is false)

  • audiotype: The audiotype of the song. This can be the following things:

    • 'arbitrary': For mp3 audio (default)

    • 'ogg/opus': For ogg audio

    • 'webm/opus': For webm audio

    • 'opus': For opus audio

    • 'raw': For raw audio

const {Player} = require('discordaudio');
const discord = require('discord.js');

const client = new discord.Client({intents: [discord.Intents.FLAGS.GUILDS]});

const channel = client.channels.cache.get('0123456789');

const player = new Player(channel);

player.play(`https://www.youtube.com/watch?v=dQw4w9WgXcQ`, {
    autoleave: false,
    quality: 'high',
    selfDeaf: true,
    selfMute: false,
    audiotype: 'arbitrary'
}).then(stream => console.log(`Playing ${stream}`).catch(console.log);

Destroy the player

You can destroy the player by using the destroy function.

const {Player} = require('discordaudio');
const discord = require('discord.js');

const client = new discord.Client({intents: [discord.Intents.FLAGS.GUILDS]});

const channel = client.channels.cache.get('0123456789');

const player = new Player(channel);
...
player.destroy();

Disconnect to the voice channel

You can disconnect to the voice channel by using the disconnect function.

const {Player} = require('discordaudio');
const discord = require('discord.js');

const client = new discord.Client({intents: [discord.Intents.FLAGS.GUILDS]});

const channel = client.channels.cache.get('0123456789');

const player = new Player(channel);
...
player.disconnect();

Reconnect to the voice channel

You can reconnect to the voice channel by using the reconnect function. The reconnect function requires the timeout parameter which is the miliseconds it should wait before rejoining the voice channel again. The default timeout is 2000 miliseconds (2 seconds);

const {Player} = require('discordaudio');
const discord = require('discord.js');

const client = new discord.Client({intents: [discord.Intents.FLAGS.GUILDS]});

const channel = client.channels.cache.get('0123456789');

const player = new Player(channel);
...
player.reconnect(2000);

Pause the song

You can pause the song by using the pause function.

const {Player} = require('discordaudio');
const discord = require('discord.js');

const client = new discord.Client({intents: [discord.Intents.FLAGS.GUILDS]});

const channel = client.channels.cache.get('0123456789');

const player = new Player(channel);
...
player.pause();

Resume the song

You can resume the song by using the resume function.

const {Player} = require('discordaudio');
const discord = require('discord.js');

const client = new discord.Client({intents: [discord.Intents.FLAGS.GUILDS]});

const channel = client.channels.cache.get('0123456789');

const player = new Player(channel);
...
player.resume();

Get the status of the song

You can check whether the song is playable or not. You can do this by using the getStatus function. The function will return a boolean. true if the song is playable, false if it's not.

const {Player} = require('discordaudio');
const discord = require('discord.js');

const client = new discord.Client({intents: [discord.Intents.FLAGS.GUILDS]});

const channel = client.channels.cache.get('0123456789');

const player = new Player(channel);
...
player.getStatus() === true ? console.log(`The song is playable`) : console.log(`The song is not playable`);

Get the members in the voice channel

You can see how many members there are in the voice channel where the bot is in. You can do this by using the getListeners function. It will return a number with the amount of members in the voice channel.

const {Player} = require('discordaudio');
const discord = require('discord.js');

const client = new discord.Client({intents: [discord.Intents.FLAGS.GUILDS]});

const channel = client.channels.cache.get('0123456789');

const player = new Player(channel);
...
console.log(`${player.getListeners()} members in the voice channel`);

Change the volume

You can change the volume by using the volume function. The volume function requires the volume parameter. This parameter can be a string or a number. In case it's a number the max is 10. If the parameter is a string you can customize it to how you want it. You can set the max by splitting it with the "/".

const {Player} = require('discordaudio');
const discord = require('discord.js');

const client = new discord.Client({intents: [discord.Intents.FLAGS.GUILDS]});

const channel = client.channels.cache.get('0123456789');

const player = new Player(channel);
...
player.volume(3); // Sets the volume to 3/10
player.volume("3/20"); // Sets the volume to 3/20

Event listeners

The Player class also has 4 events:

  • play: When a song starts playing

    • Returns the stream

  • stop: When a song has ended

    • Returns the stream

  • destroy: When the player gets destroyed

    • Returns the channel id of the channel which was connected with the player

  • disconnect: When the bot gets disconnected to a voice channel

    • Returns the channel id of the channel which was connected with the player

const {Player} = require('discordaudio');
const discord = require('discord.js');

const client = new discord.Client({intents: [discord.Intents.FLAGS.GUILDS]});

const channel = client.channels.cache.get('0123456789');

const player = new Player(channel);
...
player.on('play', stream => console.log(`Started playing ${stream}`));

player.on('stop', stream => console.log(`Song ${stream} ended`));

player.on('destroy', channelid => console.log(`The player of the channel with the id ${channelid} got destroyed`));

player.on('disconnect', channelid => console.log(`The player of the channel with the id ${channelid} got disconnected`));

Example

Other examples (also from other Discord.js version) can be found in the examples folder in the package.

/*
    Written by Luuk - Extive Marketing Manager
    Website: https://www.extive.eu
    Discord: https://www.extive.eu/discord
*/
process.env.TZ = 'Europe/London'; // Timezone
const Discord = require('discord.js');
const discordaudio = require('discordaudio');
const ytdl = require('ytdl-core');

const client = new Discord.Client({intents: [Discord.Intents.FLAGS.GUILD_VOICE_STATES, Discord.Intents.FLAGS.GUILD_MESSAGES, Discord.Intents.FLAGS.GUILDS]});

const queue = new Map();

const config = {
    token: 'YOUR-SECRET-TOKEN',
    prefix: '-',
    embedcolor: `#3498eb`
};

client.once('ready', () => {
    console.log(`Started up at ${new Date().toString()}`);
    client.user.setActivity(`music`, {type: 'LISTENING'});
});

client.on('messageCreate', async message => {
    if(message.author.bot || message.channel.type === `dm`) return;
    if(!message.content.startsWith(config.prefix)) return;

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

    const serverQueue = queue.get(message.guild.id);

    switch(args[0].toLowerCase()){
        case 'play':
            if(!args[1]) return message.channel.send({content: `Please provide a stream url`});
            if(!args[1].startsWith("https://") && !args[1].startsWith("http://")) return message.channel.send({content: `The provided stream url is not a valid url!`});
            const voicechannel = message.member.voice.channel;
            if(!voicechannel) return message.channel.send({content: `You need to join a voice channel before you can play a song`});
            const permissions = voicechannel.permissionsFor(message.guild.me);
            if(!permissions.has("CONNECT") || !permissions.has("SPEAK")) return message.channel.send({content: `I don't have the permissions to play something in this channel!`});
            const yturl = ytdl.validateURL(args[1]) ? true : false;
            if(!serverQueue){
                const songobject = {
                    url: args[1],
                    youtubeurl: yturl
                };
                const player = new discordaudio.Player(voicechannel);
                const construct = {
                    voicechannel: voicechannel,
                    textchannel: message.channel,
                    songs: [songobject],
                    player: player,
                    loop: false
                };
                queue.set(message.guild.id, construct);
                play(message.guild.id, songobject);
            } else {
                serverQueue.songs.push({url: args[1], youtubeurl: yturl});
                message.channel.send({content: `Your song has been added to the queue!`});
            }
            break;
        case 'skip':
            if(!message.member.voice.channel) return message.channel.send({content: `You have to be in a voice channel to skip a song`});
            if(!serverQueue) return message.channel.send({content: `There is nothing in the queue at the moment`});
            serverQueue.songs.shift();
            const songobject = serverQueue.songs[0];
            play(message.guild.id, songobject);
            message.channel.send({content: `Song skipped!`});
            break;
        case 'loop':
            if(!message.member.voice.channel) return message.channel.send({content: `You have to be in a voice channel to enable/disable the loop`});
            if(!serverQueue) return message.channel.send({content: `There is nothing in the queue at the moment`});
            serverQueue.loop = serverQueue.loop === true ? false : true;
            message.channel.send({content: `Loop is now **${serverQueue.loop === true ? 'enabled' : 'disabled'}**!`});
            break;
        case 'stop':
            if(!message.member.voice.channel) return message.channel.send({content: `You have to be in a voice channel to stop a song`});
            if(!serverQueue) return message.channel.send({content: `There is nothing in the queue at the moment`});
            serverQueue.player.destroy();
            queue.delete(message.guild.id);
            message.channel.send({content: `Successfully stopped the player!`});
            break;
        case 'queue':
            if(!message.member.voice.channel) return message.channel.send({content: `You have to be in a voice channel to see the queue`});
            if(!serverQueue) return message.channel.send({content: `There is nothing in the queue at the moment`});
            var songs = `__**Queue**__`;
            let tot = 1;
            serverQueue.songs.forEach(song => {songs += `\n**[${tot}]** ${song.url}`; ++tot;});
            const queueEmbed = new Discord.MessageEmbed()
            .setAuthor(message.member.user.username, message.member.user.displayAvatarURL({dynamic: true}))
            .setColor(config.embedcolor)
            .setTitle(`Queue`)
            .setDescription(songs);
            message.channel.send({embeds: [queueEmbed]}).catch(err => {});
            break;
        case 'pause':
            if(!message.member.voice.channel) return message.channel.send({content: `You have to be in a voice channel to pause a song`});
            if(!serverQueue) return message.channel.send({content: `There is nothing in the queue at the moment`});
            serverQueue.player.pause();
            message.channel.send({content: `Music got paused`});
            break;
        case 'resume':
            if(!message.member.voice.channel) return message.channel.send({content: `You have to be in a voice channel to resume a song`});
            if(!serverQueue) return message.channel.send({content: `There is nothing in the queue at the moment`});
            serverQueue.player.resume();
            message.channel.send({content: `Music is playing again`});
            break;
        case 'volume':
            if(!message.member.voice.channel) return message.channel.send({content: `You have to be in a voice channel to change the volume of a song`});
            if(!serverQueue) return message.channel.send({content: `There is nothing in the queue at the moment`});
            if(!args[1]) return message.channel.send({content: `Please provide the volume in the second argument of the command`});
            if(!isNaN(Number(args[1]))){
                if(Number(args[1]) > 10 || Number(args[1]) < 1) message.channel.send({content: `The volume must be between the number 1-10`});
                else {
                    serverQueue.player.volume(Number(args[1]));
                    message.channel.send({content: `The volume has been changed`});
                }
            } else if(!args[1].includes("/")) return message.channel.send({content: `Invalid volume`});
            else {
                let volume = args[1].split("/");
                if(isNaN(Number(volume[0])) || isNaN(Number(args[1]))) return message.channel.send({content: `Invalid volume`});
                if(Number(volume[0]) > Number(volume[1])) return message.channel.send({content: `Invalid volume`});
                serverQueue.player.volume(`${volume[0]}/${volume[1]}`);
                message.channel.send({content: `The volume has been changed`});
            }
            break;
        case 'reconnect':
            if(!message.member.voice.channel) return message.channel.send({content: `You have to be in a voice channel to change the volume of a song`});
            if(!serverQueue) return message.channel.send({content: `There is nothing in the queue at the moment`});
            serverQueue.player.reconnect(2500);
            message.channel.send({content: `Reconnected :thumbsup:`});
            break;
    }
});

function play(guildId, song){
    const serverQueue = queue.get(guildId);
    serverQueue.player.on('stop', () => {
        if(serverQueue.loop === false) serverQueue.songs.shift();
        play(guildId, serverQueue.songs[0]);
    });
    serverQueue.player.on('play', () => {
        var embed = new Discord.MessageEmbed()
        .setAuthor(client.user.username, client.user.displayAvatarURL({dynamic: true}))
        .setColor(config.embedcolor)
        .setTitle(`Playing a new song`)
        .setDescription(`I am now playing [${serverQueue.songs[0].url}](${serverQueue.songs[0].url})`);
        if(serverQueue.songs[0].youtubeurl === true){
            ytdl.getInfo(serverQueue.songs[0].url).then(info => {
                embed = new Discord.MessageEmbed()
                .setAuthor(client.user.username, client.user.displayAvatarURL({dynamic: true}))
                .setColor(config.embedcolor)
                .setTitle(`Playing ${info.videoDetails.title}`)
                .setDescription(`I am now playing **[${info.videoDetails.title}](${serverQueue.songs[0].url})** by **${info.videoDetails.author.name}**`)
                .setThumbnail(info.videoDetails.thumbnails[0].url);
                serverQueue.textchannel.send({embeds: [embed]});
            }).catch(err => {
                serverQueue.textchannel.send({embeds: [embed]});
                console.log(err);
            });
        } else serverQueue.textchannel.send({embeds: [embed]});
    });
    if(!song){
        serverQueue.player.destroy();
        queue.delete(guildId);
        return;
    }
    serverQueue.player.play(song.url, {
        quality: 'high',
        autoleave: false
    }).catch(err => {
        console.log(err);
        serverQueue.textchannel.send({content: `There was an error while connecting to the voice channel`});
    });
}

client.login(config.token);

Last updated