Security News
Weekly Downloads Now Available in npm Package Search Results
Socket's package search now displays weekly downloads for npm packages, helping developers quickly assess popularity and make more informed decisions.
discord-player
Advanced tools
Complete framework to facilitate music commands using discord.js.
$ npm install --save discord-player
$ npm install --save @discordjs/opus # Native bindings via napi
# or
$ npm install --save opusscript # WASM bindings
$ npm install --save play-dl # discord-player prefers play-dl over ytdl-core if both of them are installed
# or
$ npm install --save ytdl-core
First of all, you will need to register slash commands:
const { REST } = require('@discordjs/rest');
const { Routes, ApplicationCommandOptionType } = require('discord.js');
const commands = [
{
name: 'play',
description: 'Plays a song!',
options: [
{
name: 'query',
type: ApplicationCommandOptionType.String,
description: 'The song you want to play',
required: true
}
]
}
];
const rest = new REST({ version: '10' }).setToken('BOT_TOKEN');
(async () => {
try {
console.log('Started refreshing application [/] commands.');
await rest.put(Routes.applicationGuildCommands(CLIENT_ID, GUILD_ID), { body: commands });
console.log('Successfully reloaded application [/] commands.');
} catch (error) {
console.error(error);
}
})();
Now you can implement your bot's logic:
const { Client } = require('discord.js');
const client = new Discord.Client({
intents: ['Guilds', 'GuildVoiceStates']
});
const { Player } = require('discord-player');
// Create a new Player (you don't need any API Key)
const player = new Player(client);
// add the start and finish event so when a song will be played this message will be sent
player.events.on('playerStart', (queue, track) => queue.metadata.channel.send(`🎶 | Now playing **${track.title}**!`));
player.events.on('playerFinish', (queue, track) => queue.metadata.channel.send(`🎶 | Now playing **${track.title}**!`));
client.once('ready', () => {
console.log("I'm ready !");
});
client.on('interactionCreate', async (interaction) => {
if (!interaction.isChatInputCommand()) return;
// /play track:Despacito
// will play "Despacito" in the voice channel
if (interaction.commandName === 'play') {
const voiceChannel = interaction.member.voice.channelId;
if (!voiceChannel) return await interaction.reply({ content: 'You are not in a voice channel!', ephemeral: true });
if (interaction.guild.members.me.voice.channelId && voiceChannel !== interaction.guild.members.me.voice.channelId)
return await interaction.reply({ content: 'You are not in my voice channel!', ephemeral: true });
await interaction.deferReply({ ephemeral: true });
const query = interaction.options.getString('query');
try {
const res = await player.play(voiceChannel, query, {
nodeOptions: {
metadata: {
channel: interaction.channel
}
}
});
return await interaction.followUp({ content: `⏱️ | Loading track **${res.track.title}**!` });
} catch(e) {
return await interaction.followUp({ content: `Could not play: ${e.message}`, ephemeral: true });
}
}
});
client.login('BOT_TOKEN');
By default, discord-player supports the following sources:
QueryType.FILE
in order to play local files)You can also force a specific extractor to resolve your search query. This is useful in some cases where you don't want to use other sources.
You can do so by using ext:<EXTRACTOR_IDENTIFIER>
in searchEngine
value. Example:
const result = await player.search(query, {
// always use soundcloud extractor
searchEngine: 'ext:com.discord-player.soundcloudextractor'
});
Discord Player provides an Extractor API that enables you to use your custom stream extractor with it. Some packages have been made by the community to add new features using this API.
Discord Player supports various audio filters. There are 4 types of audio filters in discord-player.
The most common and powerful method is FFmpeg. It supports a lot of audio filters. To set ffmpeg filter, you can do:
await queue.filters.ffmpeg.setFilters(['bassboost', 'nightcore']);
Note that there can be a delay between filters transition in this method.
This equalizer is very similar to Lavalink's 15 Band Equalizer. To use this, you can do:
queue.filters.equalizer.setEQ([
{ band: 0, gain: 0.25 },
{ band: 1, gain: 0.25 },
{ band: 2, gain: 0.25 }
]);
There is no delay between filter transition when using equalizer.
This filter provides digital biquad filterer to the player. To use this, you can do:
import { BiquadFilterType } from 'discord-player';
queue.filters.biquad.setFilter(BiquadFilterType.LowPass);
// similarly, you can use other filters such as HighPass, BandPass, Notch, PeakEQ, LowShelf, HighShelf, etc.
There is no delay between filter transition when using biquad filters.
This is another type of audio filters provider. It currently supports Tremolo
and 8D
filters only. To use this, you can do:
queue.filters.filters.setFilters(['8D']);
There is no delay between filters transition using this filter.
These bots are made by the community, they can help you build your own!
const player = new Player(client, {
ytdlOptions: {
requestOptions: {
headers: {
cookie: 'YOUR_YOUTUBE_COOKIE'
}
}
}
});
Note: the above option is only used when ytdl-core is being used.
const HttpsProxyAgent = require('https-proxy-agent');
// Remove "user:pass@" if you don't need to authenticate to your proxy.
const proxy = 'http://user:pass@111.111.111.111:8080';
const agent = HttpsProxyAgent(proxy);
const player = new Player(client, {
ytdlOptions: {
requestOptions: { agent }
}
});
You may also create a simple proxy server and forward requests through it. See https://github.com/http-party/node-http-proxy for more info.
Discord Player by default uses registered extractors to stream audio. If you need to override what needs to be streamed, you can use this hook.
const fs = require('fs');
// other code
const queue = player.nodes.create(..., {
...,
async onBeforeCreateStream(track, source, _queue) {
if (track.title === 'some title') {
return fs.createReadStream('./playThisInstead.mp3');
}
}
});
\<GuildQueue>.onBeforeCreateStream
is called before actually downloading the stream. It is a different concept from extractors, where you are just downloading
streams. source
here will be a track source. Streams from onBeforeCreateStream
are then piped to FFmpeg
and finally sent to Discord voice servers.
FAQs
Complete framework to facilitate music commands using discord.js
The npm package discord-player receives a total of 3,886 weekly downloads. As such, discord-player popularity was classified as popular.
We found that discord-player demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 0 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Socket's package search now displays weekly downloads for npm packages, helping developers quickly assess popularity and make more informed decisions.
Security News
A Stanford study reveals 9.5% of engineers contribute almost nothing, costing tech $90B annually, with remote work fueling the rise of "ghost engineers."
Research
Security News
Socket’s threat research team has detected six malicious npm packages typosquatting popular libraries to insert SSH backdoors.