Skip to content

Quick start

This page builds a small but complete music bot: it plays a track, shows what is playing, and handles the queue.

import { Client, GatewayIntentBits } from "discord.js";
import { DisTube, Events } from "@kattowo/distube";
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildVoiceStates,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
],
});
const distube = new DisTube(client, {
emitNewSongOnly: true,
});

emitNewSongOnly avoids emitting PLAY_SONG twice when the same track is looped.

distube.on(Events.PLAY_SONG, (queue, song) => {
queue.textChannel?.send(`Playing **${song.name}** — ${song.formattedDuration}`);
});
distube.on(Events.ADD_SONG, (queue, song) => {
queue.textChannel?.send(`Added **${song.name}** to the queue.`);
});
distube.on(Events.ERROR, (error, queue) => {
console.error(error);
queue?.textChannel?.send(`Something went wrong: ${error.message}`);
});

Use the queue of the guild, never the shortcut methods of the client:

client.on("messageCreate", async (message) => {
if (!message.content.startsWith("!play")) return;
if (!message.member?.voice?.channel) {
await message.reply("You have to be in a voice channel.");
return;
}
const query = message.content.slice(6).trim();
if (!query) return;
try {
await distube.play(message.member.voice.channel, query, {
message,
member: message.member,
textChannel: message.channel,
});
} catch (error) {
await message.reply(`Could not play that: ${error.message}`);
}
});
client.on("messageCreate", async (message) => {
const [command, ...args] = message.content.slice(1).split(" ");
const queue = distube.getQueue(message.guildId);
switch (command) {
case "skip":
if (!queue) return;
await queue.skip();
break;
case "stop":
if (!queue) return;
await queue.stop();
break;
case "pause":
if (!queue) return;
await queue.pause();
break;
case "resume":
if (!queue) return;
await queue.resume();
break;
case "volume":
if (!queue) return;
queue.setVolume(Number(args[0]));
break;
case "shuffle":
if (!queue) return;
await queue.shuffle();
break;
case "repeat":
if (!queue) return;
// undefined toggles: disabled -> song -> queue -> disabled
queue.setRepeatMode();
break;
case "queue":
if (!queue) return;
await message.reply(queue.songs.map((s, i) => `${i + 1}. ${s.name}`).join("\n"));
break;
case "nowplaying":
case "np":
if (!queue) return;
await message.reply(`**${queue.songs[0]?.name}** — ${queue.formattedCurrentTime}`);
break;
}
});

distube.search() returns a SearchResult with real Song instances, so a result can be played without resolving it a second time.

const result = await distube.search("never gonna give you up", { limit: 5 });
for (const song of result.songs) {
console.log(song.name, "—", song.uploader.name);
}

Route a query to a single source with the source option:

await distube.search("faded", { source: "my-source" });