No description
Find a file
Andromeda 21b36f7e66
Merge pull request #820 from Androz2091/dependabot/npm_and_yarn/develop/typescript-eslint/parser-4.32.0
chore(deps-dev): bump @typescript-eslint/parser from 4.31.2 to 4.32.0
2021-09-28 15:21:43 +05:45
.github 📝 Fix issue template 2021-08-26 18:18:31 +02:00
.husky chore: setup husky 2021-08-05 14:30:02 +05:45
docs refactor(Queue): rename createStream to onBeforeCreateStream 2021-09-25 21:20:19 +05:45
example fix(StreamDispatcher): check if resource has ended 2021-08-23 18:36:03 +05:45
src Merge branch 'develop' of https://github.com/Androz2091/discord-player into develop 2021-09-25 21:20:50 +05:45
.eslintignore chore: add bundlers 2021-08-05 14:50:42 +05:45
.eslintrc.json remove StreamUtils 2021-06-25 14:30:23 +05:45
.gitattributes spotify 2021-05-10 10:56:28 +05:45
.gitignore fix(example): use dotenv 2021-08-08 11:46:09 +05:45
.npmignore fix docs 2021-04-21 10:53:33 +05:45
.prettierrc basic slash commands bot 2021-06-13 13:51:19 +05:45
CODE_OF_CONDUCT.md CODE_OF_CONDUCT 2021-04-18 23:29:12 +05:45
CONTRIBUTING.md Fix minor typos 2021-08-09 16:56:40 +02:00
jsdoc.json fix docs 2021-04-21 10:53:33 +05:45
LICENSE merge master 2021-04-18 23:20:18 +05:45
package.json chore: add prepare script 2021-09-25 20:59:05 +05:45
README.md refactor(Queue): rename createStream to onBeforeCreateStream 2021-09-25 21:20:19 +05:45
tsconfig.eslint.json setup linter 2021-06-22 16:09:05 +05:45
tsconfig.json chore: add bundlers 2021-08-05 14:50:42 +05:45
yarn.lock chore(deps-dev): bump @typescript-eslint/parser from 4.31.2 to 4.32.0 2021-09-28 04:16:01 +00:00

Discord Player

Complete framework to facilitate music commands using discord.js.

downloadsBadge versionBadge discordBadge wakatime CodeFactor

Installation

Install discord-player

$ npm install --save discord-player

Install @discordjs/opus

$ npm install --save @discordjs/opus

Install FFmpeg or Avconv

Features

  • Simple & easy to use 🤘
  • Beginner friendly 😱
  • Audio filters 🎸
  • Lightweight 🛬
  • Custom extractors support 🌌
  • Lyrics 📃
  • Multiple sources support ✌
  • Play in multiple servers at the same time 🚗

Documentation

Getting Started

First of all, you will need to register slash commands:

const { REST } = require("@discordjs/rest");
const { Routes } = require("discord-api-types/v9");

const commands = [{
    name: "play",
    description: "Plays a song!",
    options: [
        {
            name: "query",
            type: "STRING",
            description: "The song you want to play",
            required: true
        }
    ]
}]; 

const rest = new REST({ version: "9" }).setToken(process.env.DISCORD_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, Intents } = require("discord.js");
const client = new Discord.Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES, Intents.FLAGS.GUILD_VOICE_STATES] });
const { Player } = require("discord-player");

// Create a new Player (you don't need any API Key)
const player = new Player(client);

// add the trackStart event so when a song will be played this message will be sent
player.on("trackStart", (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.isCommand()) return;

    // /play Despacito
    // will play "Despacito" in the voice channel
    if (interaction.commandName === "play") {
        if (!interaction.member.voice.channelId) return await interaction.reply({ content: "You are not in a voice channel!", ephemeral: true });
        if (interaction.guild.me.voice.channelId && interaction.member.voice.channelId !== interaction.guild.me.voice.channelId) return await interaction.reply({ content: "You are not in my voice channel!", ephemeral: true });
        const query = interaction.options.get("query").value;
        const queue = player.createQueue(interaction.guild, {
            metadata: {
                channel: interaction.channel
            }
        });
        
        // verify vc connection
        try {
            if (!queue.connection) await queue.connect(interaction.member.voice.channel);
        } catch {
            queue.destroy();
            return await interaction.reply({ content: "Could not join your voice channel!", ephemeral: true });
        }

        await interaction.deferReply();
        const track = await player.search(query, {
            requestedBy: interaction.user
        }).then(x => x.tracks[0]);
        if (!track) return await interaction.followUp({ content: `❌ | Track **${query}** not found!` });

        queue.play(track);

        return await interaction.followUp({ content: `⏱️ | Loading track **${track.title}**!` });
    }
});

client.login(process.env.DISCORD_TOKEN);

Supported websites

By default, discord-player supports YouTube, Spotify and SoundCloud streams only.

Optional dependencies

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/extractor (optional)

Optional package that adds support for vimeo, reverbnation, facebook, attachment links and lyrics. You just need to install it using npm i --save @discord-player/extractor (discord-player will automatically detect and use it).

@discord-player/downloader (optional)

@discord-player/downloader is an optional package that brings support for +700 websites. The documentation is available here.

Examples of bots made with Discord Player

These bots are made by the community, they can help you build your own!

Advanced

Use cookies

const player = new Player(client, {
    ytdlOptions: {
        requestOptions: {
            headers: {
                cookie: "YOUR_YOUTUBE_COOKIE"
            }
        }
    }
});

Use custom proxies

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 }
    }
});

Custom stream Engine

Discord Player by default uses node-ytdl-core for youtube and some other extractors for other sources. If you need to modify this behavior without touching extractors, you need to use createStream functionality of discord player. Here's an example on how you can use play-dl to download youtube streams instead of using ytdl-core.

const playdl = require("play-dl");

// other code
const queue = player.createQueue(..., {
    ...,
    async onBeforeCreateStream(track, source, _queue) {
        // only trap youtube source
        if (source === "youtube") {
            // track here would be youtube track
            return (await playdl.stream(track.url)).stream;
            // we must return readable stream or void (returning void means telling discord-player to look for default extractor)
        }
    }
});

<Queue>.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 video source. Streams from onBeforeCreateStream are then piped to FFmpeg and finally sent to Discord voice servers.