Learn how to use discord-player hooks like a pro to manipulate the queue and its components
Discord-Player provides a powerful hooks system that lets you interact with various aspects of the player, queues, and audio streams. These hooks can be used anywhere in your application after initializing the Player instance.
This approach uses the HooksContextProvider, eliminating the need to pass node identifiers repeatedly:
events/interactionCreate.js
const { useMainPlayer } = require('discord-player');// Set up the context provider in your interaction handlerclient.on('interactionCreate', async (interaction) => { if (!interaction.isCommand()) return; const player = useMainPlayer(); const command = client.commands.get(interaction.commandName); // Create a context with the guild information const context = { guild: interaction.guild }; // Execute the command within the provided context await player.context.provide(context, () => command.execute(interaction));});
This approach allows you to use hooks anywhere by providing a node identifier (typically a guild ID or guild object). This is the most straightforward method:
commands/queue.js
const { useQueue } = require('discord-player');// Example command showing direct hook usageexport async function execute(interaction) { // Directly pass the guild ID to resolve the queue const queue = useQueue(interaction.guild.id); // Now you can work with the queue if (!queue) { return interaction.reply('No active queue in this server!'); }}
Then in your commands, you can use hooks without arguments:
commands/nowplaying.js
const { useQueue } = require('discord-player');export async function execute(interaction) { // The hook automatically uses the context to find the right queue const queue = useQueue(); if (!queue?.isPlaying()) { return interaction.reply('Nothing is currently playing!'); }}
Retrieves the GuildQueuePlayerNode for a specific guild, giving you control over playback and track information.
commands/nowplaying.js
const { usePlayer } = require('discord-player');// Get the player node for a guildconst player = usePlayer(interaction.guild.id);// Create a visual progress barconst progressBar = player.createProgressBar();// Get detailed timestamp informationconst timestamp = player.getTimestamp();console.log(`Progress: ${timestamp.progress}%`);
Manage and access the playback history for a guild.
commands/previous.js
const { useHistory } = require('discord-player');// Get the history instanceconst history = useHistory(interaction.guild.id);// Example: Show last played trackconst lastTrack = history.previousTrack;if (lastTrack) { console.log(`Last played: ${lastTrack.title}`);}