Discord Player
Creating a music bot

Creating a Loop Command

Learn how to create a loop command for your music bot

In this guide, we will learn how to create a loop command in your Discord bot using Discord Player. The loop command will allow users to loop the queue in different modes.

The available loop modes are

ModeDescription
offDisables looping (default mode)
trackLoops the current track
queueLoops the entire queue
autoplayLoops the similar track to the last track in the queue

You need to invoke setRepeatMode() method of the queue with QueueRepeatMode enum to set the loop mode.

Design Planning

Before we dive into the code, let's plan the design of our loop command:

  1. Command Definition: We will define a new slash command named loop using SlashCommandBuilder.
  2. Option Handling: The command will have a required option named mode to specify the loop mode.
  3. Queue Retrieval: We will use the useQueue hook to get the current queue.
  4. Mode Setting: We will set the loop mode using the setRepeatMode() method of the queue.
  5. Response: We will send a confirmation message indicating the loop mode set.
loop.js
import { SlashCommandBuilder } from 'discord.js';
import { QueueRepeatMode, useQueue } from 'discord-player';
 
export const data = new SlashCommandBuilder()
  .setName('loop') // Command name
  .setDescription('Loop the queue in different modes') // Command description
  .addNumberOption((option) =>
    option
      .setName('mode') // Option name
      .setDescription('The loop mode') // Option description
      .setRequired(true) // Option is required
      .addChoices(
        {
          name: 'Off',
          value: QueueRepeatMode.OFF,
        },
        {
          name: 'Track',
          value: QueueRepeatMode.TRACK,
        },
        {
          name: 'Queue',
          value: QueueRepeatMode.QUEUE,
        },
        {
          name: 'Autoplay',
          value: QueueRepeatMode.AUTOPLAY,
        },
      ),
  );
 
export async function execute(interaction) {
  // Get the current queue
  const queue = useQueue();
 
  if (!queue) {
    return interaction.reply('This server does not have an active player session.');
  }
 
  // Get the loop mode
  const loopMode = interaction.options.getNumber('mode');
 
  // Set the loop mode
  queue.setRepeatMode(loopMode);
 
  // Send a confirmation message
  return interaction.reply(`Loop mode set to ${QueueRepeatMode[loopMode]}`);
}

In this example:

  • We define a new slash command named loop using SlashCommandBuilder.
  • We use the useQueue hook to get the current queue.
  • If there is no active player session, we reply with an appropriate message.
  • We get the loop mode from the command options.
  • We set the loop mode using the setRepeatMode() method of the queue.
  • We send a confirmation message with the loop mode set.

On this page