Skip to content

Discord.js events

DisTube manages the playback. The events of discord.js are what you need to handle the things around it: a user who leaves, a bot that is moved, a channel that empties.

The most common one. Without it, the bot stays alone in a voice channel forever.

const { isVoiceChannelEmpty } = require("@kattowo/distube");
client.on("voiceStateUpdate", (oldState, newState) => {
if (!isVoiceChannelEmpty(oldState)) return;
const voice = distube.voices.get(oldState);
if (voice) voice.leave();
});
client.on("voiceStateUpdate", (oldState, newState) => {
if (!isVoiceChannelEmpty(oldState)) return;
const queue = distube.getQueue(oldState);
if (queue) queue.pause();
});

And resume it when somebody comes back:

client.on("voiceStateUpdate", (oldState, newState) => {
if (isVoiceChannelEmpty(oldState)) return;
const queue = distube.getQueue(oldState);
if (queue && queue.paused) queue.resume();
});
const timers = new Map();
client.on(Events.FINISH, (queue) => {
timers.set(
queue.id,
setTimeout(() => {
queue.voice.leave();
timers.delete(queue.id);
}, 5 * 60 * 1000),
);
});
client.on(Events.PLAY_SONG, (queue) => {
clearTimeout(timers.get(queue.id));
});
client.on(Events.DELETE_QUEUE, (queue) => {
clearTimeout(timers.get(queue.id));
timers.delete(queue.id);
});
client.on("voiceStateUpdate", (oldState, newState) => {
if (oldState.member?.id !== client.user?.id) return;
if (oldState.channelId === newState.channelId) return;
const queue = distube.getQueue(oldState);
queue?.textChannel?.send(`Moved to <#${newState.channelId}>`);
});

DisTube works with any command handler. A chat input command looks like this:

client.on("interactionCreate", async (interaction) => {
if (!interaction.isChatInputCommand()) return;
if (interaction.commandName !== "play") return;
const query = interaction.options.getString("query");
const voiceChannel = interaction.member.voice?.channel;
if (!voiceChannel) {
await interaction.reply("You have to be in a voice channel.");
return;
}
await interaction.deferReply();
try {
await distube.play(voiceChannel, query, {
member: interaction.member,
textChannel: interaction.channel,
interaction,
});
await interaction.editReply("Added to the queue.");
} catch (error) {
await interaction.editReply(`Could not play that: ${error.message}`);
}
});
client.once("ready", () => {
console.log(`${client.user.tag} is ready.`);
});

Destroy DisTube before the client goes away, so every queue is stopped and every plugin is disposed.

client.on("destroy", async () => {
await distube.destroy();
});