How to create a music bot using Discord.js

Discord bots are a very useful tool that bypasses the restriction and provides an unlimited amount of access to any discord feature. Discord music bots work on Artificial Intelligence ( AIs ). 

You can RUN it by giving some Discord commands and it starts the task automatically on your server.

Discord music bots help you to listen to the same music at the same time for the entire members of the discord server. 

Discord music bots are customizable according to user demand and their ability to find songs from different platforms like YouTube, Facebook, Spotify, or many others and play them in a Discord voice channel.

So If you connected with someone’s voice channel, then you can enjoy songs along with all members plus suggest new songs via live comments. 

This becomes a good medium to share newly released music, host listening parties with friends, or provide background music from your side.

However, there are some popular Discord music bots available that offering amazing services like Groovy, Octave, Chip, and MEE6. 

But if you want to create your own fully customize music bot for personal use in discord then this article will help you a lot.

Table of Contents

How to Make a Discord Music bot

You can create the discord bot in different languages which is compatible with you. But here am explaining making a discord bot by using Discord.js. So let’s just begin our guide but before starting you need to have some programs on your system. Therefore install these tools from the below LINKs.

How to Setup a Discord bot

After installing the above software we can proceed to the next step that is setting up a discord bot on an official discord developer portal. For setting up a bot you need to create a new application on this portal.

  • So first step is to visit the discord developer portal from here.
  • On the homepage of this URL click on the New application box.
  • A create an application window will prompt here to give a name to your application related to your bot ( better for remind ).
  • If you’re agreeing with the discord Term & Condition Policy click on create button.
  • On the next screen go to the bot tab from the left pan and under the BUILT-A-BOT section click on add bot option.

That’s it our new bot is created and we are able to perform edition operations on it. But first, for testing Invite this Bot on your discord server for that see the below section.

How to Add a Bot on your Discord Server

Adding a bot to your discord server is a very straightforward process. You can add it by simply using the OAuth2 URL Generator tool. So first browse for the OAuth2 page and after that from the below list of scoop options. Mark the bot option.

  • After that under the Oauth2 application section, we need to mark ( Add ) some permission, It will prompt whenever a new person adding this bot on their server for playing music and reading message.
  • As you choose permissions just below a unique URL address will be generated just copy that.
  • Open up a new tab in your browser and paste the copied URL into the search bar.

After pasting as you click enter it automatically added to the server list and finally click on authorize button and the bot will successfully be added to your server.

Create project for making discord music bot

So if you’re all setting up with the above two steps and added a bot to your server then this step works fine. Now create a project by using a terminal and some commands which you need to follow.

So to start the process create a new directory and move into it. For that simple use these command codes.

				
					mkdir musicbot && cd musicbot
				
			

Now use the npm init command and create our project modules. Press the enter button After entering the command and some normal questions will appear in your terminal. Answer them correctly and proceed with the further process.

After that create the two files by below code where we start our work.

				
					touch index.js && touch config.json
				
			

Then minimize the tab and use the text editor in your system and open this project. The VS code is also a better option for editing text. You can open it directly by code . command.

Install Discord js basics

So before starting the process of creating a discord music bot we need to install some dependencies via the below codes.

				
					npm install discord.js ffmpeg fluent-ffmpeg @discordjs/opus ytdl-core --save
				
			

As you hit this code the installation becomes starts and once it is completed we can begin our writing with config.json file. This is the section where we save the token of our bot as well as the informative prefix.

				
					{
"prefix": "!",
"token": "your-token"
}

				
			

You know we get a URL that we generated under the discord developer portal. Now visit this portal again and generate the token from the bot section visit Discord Developer Portal >> BUILD-A-BOT >> TOKEN

There is two option copy or regenerate just click on copy. If you want to save just regenerate it and save it somewhere else.

The config.json file is only for doing this thing nothing more. I hope you understand properly till now processes.

Now it’s time to start writing or editing our javascript code for doing that we need to import all our dependencies. This can be done by the below codes.

				
					const Discord = require('discord.js');
const {
	prefix,
	token,
} = require('./config.json');
const ytdl = require('ytdl-core');

				
			

That’s it now we are able to create our login form and the client section by accessing our generated token.

				
					const client = new Discord.Client();
client.login(token);
				
			

So before executing the project we need to add some basic listeners command which is the console.log part. For that copy the below codes.

				
					client.once('ready', () => {
 console.log('Ready!');
});
client.once('reconnecting', () => {
 console.log('Reconnecting!');
});
client.once('disconnect', () => {
 console.log('Disconnect!');
});

				
			
				
					node index.js
				
			

Codes for Reading Discord Messages

If you apply the above steps and code properly then your bot is started showing online. And we’re able to read messages and even replying to any messages. 

For reading the entire message just paste the below function on the terminal.

				
					client.on('message', async message => { })
				
			

From here we can make a robotic listener for hearing all message events. And next time if someone message, to the bot it saves it automatically in a message section. 

So check if our message comes if it is means all is working fine till here.

if (message.author.bot) return;

By this code, we ensure that the author of the particular message is our bot.

After that, if the message starts with the prefix then we can check it by applying some code. If there is no message we can define it earlier and return it.

So by applying some simple if statements command. We can test what we need to execute for that follow the below codes.

We can do so using some simple if statements.

				
					const serverQueue = queue.get(message.guild.id);

if (message.content.startsWith(`${prefix}play`)) {
    execute(message, serverQueue);
    return;
} else if (message.content.startsWith(`${prefix}skip`)) {
    skip(message, serverQueue);
    return;
} else if (message.content.startsWith(`${prefix}stop`)) {
    stop(message, serverQueue);
    return;
} else {
    message.channel.send("You need to enter a valid command!");
}

				
			

This will help you to find out which command is useful to execute and RUN the command. 

If there is some command which is not valid then we can show an error message by applying the send() function.

So if all are working perfectly and the commands know very well what to execute. Then we can start implementing one by one these commands.

How to Add songs

You can add a song by simply adding the play command. So required thing for this process is one song a guild. If you don’t know about the guild, a guild is often referred to as a server it represents an isolated collection of channels or a user itself. 

And the last thing is ytdl library which we installed before.

So for saving songs which we search, first we have to create a map with queue name.

				
					const queue = new Map();
				
			

Then we need to make an async function called to execute. This is for checking purposes if the bot working with all permissions which are required in a voice chat. If it doesn’t we can show an error message by below bunch of codes.

				
					async function execute(message, serverQueue) {
  const args = message.content.split(" ");

  const voiceChannel = message.member.voice.channel;
  if (!voiceChannel)
    return message.channel.send(
      "You need to be in a voice channel to play music!"
    );
  const permissions = voiceChannel.permissionsFor(message.client.user);
  if (!permissions.has("CONNECT") || !permissions.has("SPEAK")) {
    return message.channel.send(
      "I need the permissions to join and speak in your voice channel!"
    );
  }
}

				
			

After that, we may proceed for getting particular song information and saving it as a music object. Here the ytdl library helps which is able to get info about songs via the youtube link.

				
					const songInfo = await ytdl.getInfo(args[1]);
const song = {
    title: songInfo.videoDetails.title,
    url: songInfo.videoDetails.video_url,
};

				
			

So By using the ytdl library which we installed earlier, we get song information, and also it will be saved in a song object with the info which we allow.

While the song is saved for adding it into our queue we need to create a contract. If the music is already playing means our serverQueue is already defined so we can test it like that. 

So for adding songs in our existing serverQueue we need to place some coding also we can prompt a successfully added message. For doing that first we need to start playing music from any voice channel after joining.

				
					if (!serverQueue) {

}else {
 serverQueue.songs.push(song);
 console.log(serverQueue.songs);
 return message.channel.send(`${song.title} has been added to the queue!`);
}

				
			

If our serverQueue is empty we can check it, if it was really null, we can add a song for that we can create our contract.

				
					// Creating the contract for our queue
const queueContruct = {
 textChannel: message.channel,
 voiceChannel: voiceChannel,
 connection: null,
 songs: [],
 volume: 5,
 playing: true,
};
// Setting the queue using our contract
queue.set(message.guild.id, queueContruct);
// Pushing the song to our songs array
queueContruct.songs.push(song);

try {
 // Here we try to join the voicechat and save our connection into our object.
 var connection = await voiceChannel.join();
 queueContruct.connection = connection;
 // Calling the play function to start a song
 play(message.guild, queueContruct.songs[0]);
} catch (err) {
 // Printing the error message if the bot fails to join the voicechat
 console.log(err);
 queue.delete(message.guild.id);
 return message.channel.send(err);
}

				
			

By using this code block we can add song in song array after creating a contract. Now for testing join any user’s voice chat and call our play() function. after that, we may proceed with implementation.

Playing songs via Discord Music Bot

So till here, we are able to create a contract ( If not available ) and adding our song to a queue. And start implementing our play functionality if the contract is missing there.

For doing that we can start by making a function called play there is 2 parameter which it takes, First is a guild and the second one is our desired song which we want to play also test if the song is empty or not. If there is no song just delete the queue and leave the voice channel.

				
					function play(guild, song) {
  const serverQueue = queue.get(guild.id);
  if (!song) {
    serverQueue.voiceChannel.leave();
    queue.delete(guild.id);
    return;
  }
}

				
			

Now by using the play() function we are able to start playing our song and passing the song URL of the connection.

				
					const dispatcher = serverQueue.connection
    .play(ytdl(song.url))
    .on("finish", () => {
        serverQueue.songs.shift();
        play(guild, serverQueue.songs[0]);
    })
    .on("error", error => console.error(error));
dispatcher.setVolumeLogarithmic(serverQueue.volume / 5);
serverQueue.textChannel.send(`Start playing: **${song.title}**`);

				
			

Rather than passing the song URL, we can create a stream. We can manage two listeners at a time and decide the error event and ending part.

Point: The function recalls itself again & again or we call it the  recursive function. This function especially helps to play the next song automatically when the first song is completed.

So just by typing! play URL in the chatbox you can play a song instantly.

How to Skip a song while using Discord Bot

So till here we understood how to play a song and twisting into the next song. But there is one thing also necessary when we listening music, is How to do skipping by using codes. 

For that, we need to go in our play() function and need to end the dispatcher. By applying these changes we directly move to the next song.

				
					function skip(message, serverQueue) {
  if (!message.member.voice.channel)
    return message.channel.send(
      "You have to be in a voice channel to stop the music!"
    );
  if (!serverQueue)
    return message.channel.send("There is no song that I could skip!");
  serverQueue.connection.dispatcher.end();
}

				
			

By implementing this bot can check if the user is typed some command to skip the song in a voice channel.

How to Stop a Song

So the last and important part when we play any music is how to stop it. Here the stop() function will help you, it work almost the same as the skip() function. 

By applying the below code we are clearing the song array and it will leave the voice chat and delete the queue.

				
					function stop(message, serverQueue) {
  if (!message.member.voice.channel)
    return message.channel.send(
      "You have to be in a voice channel to stop the music!"
    );
  
  if (!serverQueue)
    return message.channel.send("There is no song that I could stop!");
    
  serverQueue.songs = [];
  serverQueue.connection.dispatcher.end();
}

				
			

The complete source code for the index.js

If you don’t want to do each and every step just you need a complete source code to create a discord music bot. Then you can copy and implement the entire code from the below section.

				
					const Discord = require("discord.js");
const { prefix, token } = require("./config.json");
const ytdl = require("ytdl-core");

const client = new Discord.Client();

const queue = new Map();

client.once("ready", () => {
  console.log("Ready!");
});

client.once("reconnecting", () => {
  console.log("Reconnecting!");
});

client.once("disconnect", () => {
  console.log("Disconnect!");
});

client.on("message", async message => {
  if (message.author.bot) return;
  if (!message.content.startsWith(prefix)) return;

  const serverQueue = queue.get(message.guild.id);

  if (message.content.startsWith(`${prefix}play`)) {
    execute(message, serverQueue);
    return;
  } else if (message.content.startsWith(`${prefix}skip`)) {
    skip(message, serverQueue);
    return;
  } else if (message.content.startsWith(`${prefix}stop`)) {
    stop(message, serverQueue);
    return;
  } else {
    message.channel.send("You need to enter a valid command!");
  }
});

async function execute(message, serverQueue) {
  const args = message.content.split(" ");

  const voiceChannel = message.member.voice.channel;
  if (!voiceChannel)
    return message.channel.send(
      "You need to be in a voice channel to play music!"
    );
  const permissions = voiceChannel.permissionsFor(message.client.user);
  if (!permissions.has("CONNECT") || !permissions.has("SPEAK")) {
    return message.channel.send(
      "I need the permissions to join and speak in your voice channel!"
    );
  }

  const songInfo = await ytdl.getInfo(args[1]);
  const song = {
        title: songInfo.videoDetails.title,
        url: songInfo.videoDetails.video_url,
   };

  if (!serverQueue) {
    const queueContruct = {
      textChannel: message.channel,
      voiceChannel: voiceChannel,
      connection: null,
      songs: [],
      volume: 5,
      playing: true
    };

    queue.set(message.guild.id, queueContruct);

    queueContruct.songs.push(song);

    try {
      var connection = await voiceChannel.join();
      queueContruct.connection = connection;
      play(message.guild, queueContruct.songs[0]);
    } catch (err) {
      console.log(err);
      queue.delete(message.guild.id);
      return message.channel.send(err);
    }
  } else {
    serverQueue.songs.push(song);
    return message.channel.send(`${song.title} has been added to the queue!`);
  }
}

function skip(message, serverQueue) {
  if (!message.member.voice.channel)
    return message.channel.send(
      "You have to be in a voice channel to stop the music!"
    );
  if (!serverQueue)
    return message.channel.send("There is no song that I could skip!");
  serverQueue.connection.dispatcher.end();
}

function stop(message, serverQueue) {
  if (!message.member.voice.channel)
    return message.channel.send(
      "You have to be in a voice channel to stop the music!"
    );
    
  if (!serverQueue)
    return message.channel.send("There is no song that I could stop!");
    
  serverQueue.songs = [];
  serverQueue.connection.dispatcher.end();
}

function play(guild, song) {
  const serverQueue = queue.get(guild.id);
  if (!song) {
    serverQueue.voiceChannel.leave();
    queue.delete(guild.id);
    return;
  }

  const dispatcher = serverQueue.connection
    .play(ytdl(song.url))
    .on("finish", () => {
      serverQueue.songs.shift();
      play(guild, serverQueue.songs[0]);
    })
    .on("error", error => console.error(error));
  dispatcher.setVolumeLogarithmic(serverQueue.volume / 5);
  serverQueue.textChannel.send(`Start playing: **${song.title}**`);
}

client.login(token);

				
			

Conclusion

Nowadays making a bot is not that difficult everything is on the internet or you just need a proper guide from start to end and a little bit of knowledge of coding if you didn’t have any, no worry !!!

I put all the required code according to their usability. You need to just follow the instruction and implement the code was it necessary and which type of bot you want to make that is also important. 

I know this is a somehow lengthy process but when you read the article one or two times then you will become a master of it. And able to create your own discord music bot. 

I mention all the important function which will be in used when you creating a bot. though if you have any questions or facing any issues regarding the music bot feels free to give feedback via the comment section.

Ritesh
Leave a Replay