Create Bot for your Discord server.
By Prgmaz 26 May 2021

THUMBNAIL HERE

What we need for this tutorial

  • NodeJs and NPM installed
  • discord.js
  • dotenv

Setting up project

Create a folder named discord_bot and initialize a node project in that folder with npm init -y command. Now Let’s install some packages by typing this command npm i discord.js dotenv.

THUMBNAIL HERE

Let’s create a file named .env. This file will contain our Environment variables like TOKEN and PREFIX for our bot.

Let’s get our token for our discord bot. Go to Discord Developer Portal and Sign up if you haven’t already. Now open Applications tab and Click on New Application. Type a name and press Create.

THUMBNAIL HERE

Now that you have created a application, Set it up by typing name and giving it a Profile Picture.

Click on the Bot tab, and Copy the Token. THUMBNAIL HERE

Paste it in your .env file. Your file should look like this

TOKEN=PASTE YOUR TOKEN HERE
PREFIX=!

Let’s invite our bot to our server by going to OAuth2 tab and giving it scope of bot and permission of Administrator, Copy the url and paste it in your Browser, Now select your server and Press Continue.

THUMBNAIL HERE

Now we are setup to create our Discord bot.

Logging in to our bot

Create index.js file inside your project and start typing your code.

require("dotenv").config(); // Telling Nodejs, We are using dotenv to get environment variables
const discord = require("discord.js"); // Importing discord.js library
const client = new discord.Client(); // Creating a client for our bot
const fs = require("fs"); // We are gonna need filesystem module for later.

// Your CODE WILL GO HERE

client.login(process.env.TOKEN); // Login into your discord bot you created by this method and passing it the token

Let’s listen to the ready event (it fires when our bot is ready to use).

require("dotenv").config(); // Telling Nodejs, We are using dotenv to get environment variables
const discord = require("discord.js"); // Importing discord.js library
const client = new discord.Client(); // Creating a client for our bot
const fs = require("fs"); // We are gonna need filesystem module for later.

client.on('ready', () => {
    console.log("Hello World!");
});

client.login(process.env.TOKEN); // Login into your discord bot you created by this method and passing it the token

Now if you run your bot by typing nodemon index in your powershell. You will see Hello World! logged into your terminal.

THUMBNAIL HERE

Creating commands

To create commands, create directory named commands in your project. Let’s create a basic command ping for our bot. Create file named ping in our commands directory.

// Importing Message data type from `discord.js`
const { Message } = require("discord.js");

/* 
    Exporting a object with name, description and execute properties.
    1. name - this will be the name of the commands and used to call the commands
    2. description - This will be helpful for getting help message.
    3. execute - This will contain the function of the command. message and args will be passed to it.
*/
module.exports = {
    name: "ping",
    description: "Gets the ping of the Bot.",
    execute: (message, args) => {
        // Creating a new message
        const msg = new Message();
        // Setting content of the message to 'Pong!'
        msg.content = "Pong!";
        // Sending the message to the current channel
        message.channel.send(msg);
    }
}

You can add more commands as you desire, like this.

Executing commands

We are gonna listen for messages on any channel of the server and see that message is starting with our PREFIX we used in our .env file. For this we are gonna listen for message event (This event fires whenever there is a new message).

require("dotenv").config(); // Telling Nodejs, We are using dotenv to get environment variables
const discord = require("discord.js"); // Importing discord.js library
const client = new discord.Client(); // Creating a client for our bot
const fs = require("fs"); // We are gonna need filesystem module for later.

client.on('ready', () => {
    console.log("Hello World!");
});

client.on("message", (message) => {
    // If message doesn't start with our prefix and author of that message is a bot, we are gonna break the execution any further
	if (!message.content.startsWith(process.env.PREFIX) || message.author.bot)
		return; 
		
    // Removing prefix, Getting command and arguments 
	const args = message.content.slice(process.env.PREFIX.length).split(/ +/); 
	const command = args.shift().toLowerCase(); // Getting command name.

});

client.login(process.env.TOKEN); // Login into your discord bot you created by this method and passing it the token

Now we have our command and arguments that were called with message. We can create commands. To Do this, First we’re gonna make some changes to our ready event listener.

client.on("ready", () => {
	console.log("Hello World!");
	// Creating new Collection Datatype from discord.js(You can learn about it from the documentation of discord.js)
	client.commands = new discord.Collection(); 

    // Getting all file names with extension of `.js` in the `commands` directory
	const commandFiles = fs
		.readdirSync("./commands/")
		.filter((file) => file.endsWith(".js")); 
		
    // Looping through the file and getting all the commands from it and setting it by name and command.
	for (const file of commandFiles) {
		const command = require(`./commands/${file}`);
		client.commands.set(command.name, command);
	}
});

Now changing our message event to execute the command.

client.on("message", (message) => {
	if (!message.content.startsWith(process.env.PREFIX) || message.author.bot)
		return;

	const args = message.content.slice(process.env.PREFIX.length).split(/ +/);
	const command = args.shift().toLowerCase();

    // Checking if command exist it, if it does, calling execute function. Else sending error message to the channel where the command was called from.
	if (client.commands.has(command)) {
		client.commands.get(command).execute(message, args);
	} else {
		message.channel.send(
			`No command named **${command}** is found. Type **help** for all commands.`
		);
	}
});

If you send a message to the server, It will result in command being executed. THUMBNAIL HERE

Creating help command

To create help command, create a file named help.js in the commands directory.

// Importing Message embed data type
const { MessageEmbed } = require("discord.js");
// Importing Filesystem module
const fs = require("fs");

module.exports = {
	name: "help",
	description: "Help command gives you the information about the commands",
	execute: function (message, args) {
	    // Instantiating new MessageEmbed
		const embed = new MessageEmbed();
		// Setting title and description of the embed
		embed.setTitle("Help");
		embed.setDescription("Type help <command> to get help for the command");

        // If no command specified after !help then execute this.
		if (args.length < 1) {
		    // Reading all the commands
			const commandFiles = fs
				.readdirSync("./commands/")
				.filter((file) => file.endsWith(".js"));

			for (const file of commandFiles) {
				const command = require(`./${file}`);
                // Adding to the embed command name and its description
				embed.addField(command.name, command.description, true);
			}
		} else {
			const command = require(`./${args[0]}.js`);
			if (!command) {
				return message.channel.send("No command found");
			}

			embed.addField(command.name, command.description, true);
		}
		// Sending the embed to the channel.
		message.channel.send(embed);
	},
};

Now if you type !help or !help command then it will be executed. THUMBNAIL HERE

To run this bot 24/7, You need to host it on a hosting provider like heroku, Digital Ocean or Google Cloud.

Link to the Project

Follow me on my socials.

Naman Baranwal
Hi, I’m Prgmaz. I’m a Web, Game and App Developer.

Tags

  • nodejs
  • javascript
  • typescript
  • discord
  • bot
  • server