Sign In
Sign In

How to Create a Bot in Discord

How to Create a Bot in Discord
Hostman Team
Technical writer
Node.js
16.05.2024
Reading time: 10 min

Bots are an integral part of server management. They significantly save time and allow you to efficiently solve trivial problems. There are ready-made solutions, but they are limited in functionality and are not always suitable. In this case, you can create a bot yourself. Let's look at how to create a bot in Discord that will allow you to implement all the necessary functionality.

There are several ways to create a Discord bot. To do this, you can use special software, write code in Python or discord.js. 

We will describe creating a bot in JS and adding it to the server. 

Development environment

At the initial stage, you need to select and install a development environment. We will use Visual Studio Code as an example, but you can also use other development environments, such as Atom, Eclipse, Notepad ++, and others. Having selected the environment, download it from the official website for your operating system version.

In addition to the development environment, you need to install the necessary extensions, as well as the runtime environment. The runtime environment is node.js, and extensions can be installed directly from the development environment window.

What extensions can be useful when creating a Discord bot in JS? First of all, these are tools for running selected fragments of the generated code, as well as an extension for conveniently displaying the workspace. If you use Visual Studio Code, you can find these extensions under the names Code Runner and Discord Presence.

Creating the bot

The process of creating a Discord bot begins in the developer portal. To do this, select the NEW APPLICATION option.

Image5

In the dialog box, assign a name for the new bot and click CREATE. You can easily change the bot's name while working and also add an icon.

Image4

The last step is to add the required permissions. Go to the BOT tab, and at the bottom of the page, set the permissions the bot should have. Checking the Administrator checkbox will select everything.

Image7

Before writing code, create a folder and open it in Visual Studio Code. To do this, use file -> open folder.

The next step is to create a terminal through which we will add a description of the bot. To do this, select: terminal -> create terminal.

To start creating a description of the bot in the terminal, enter:

npm init

Press Enter at the end of each line. Next, enter the following combinations:

npm install
npm install discord.js

After this, you should see a folder with files and two objects with the .json extension.

Writing code

First, create a config.json file to store basic data about the bot. In the file indicate the following:

{
"token": "your_token",
"prefix": "your_prefix"
}

The token can be obtained on the developer portal in the Bot tab. This information is displayed once, so be sure to save your token.

Image3

The starting point of the command is used as a prefix. For example, if the command $help is entered, then the $ sign will be the prefix. Usually the exclamation mark ! is used as a prefix. However, you can use almost any character as a prefix, including letters, numbers, and special characters, as long as they are not reserved or otherwise used in your bot.

The next step is to create the bot.js file, which is the body of our bot and contains its functionality, which can later be expanded and edited. A typical file looks like this:

const Discord = require('discord.js'); // Retrieving the discord.js library
const robot = new Discord.Client({ intents: [
     Discord.GatewayIntentBits.Guilds,
     Discord.GatewayIntentBits.GuildMessages,
     Discord.GatewayIntentBits.MessageContent //This directive is required for the bot to respond to the message body
]}) // Declaring that robot is a bot. This part of the code contains data that depends on the version of the discord.js library; in the example, Discord.js v14 is used
const comms = require("./comms.js"); // Retrieving a file with commands for the bot
const fs = require('fs'); // Retrieving the native node.js file system module
let config = require('./config.json'); // Retrieving a file with parameters and information
let token = config.token; //Retrieving the token from it
let prefix = config.prefix; //Retrieving the prefix from it
robot.on("ready", function() {
     /* Upon successful launch, the console will display the message “[Bot name] has launched!” */
     console.log(robot.user.username + "started!");
});
robot.on('messageCreate', (msg) => { // Respond to messages
     if (msg.author.username != robot.user.username && msg.author.discriminator != robot.user.discriminator) {
         var comm = msg.content.trim() + " ";
         var comm_name = comm.slice(0, comm.indexOf(" "));
         var messArr = comm.split(" ");
         for (comm_count in comms.comms) {
             var comm2 = prefix + comms.comms[comm_count].name;
             if (comm2 == comm_name) {
                 comms.comms[comm_count].out(robot, msg, messArr);
}
}
}
});
robot.login(token); // Bot authorization

Please note that the config.json file must be placed in the same directory as your bot.js so that the bot can read the settings from the file correctly.

To work with the bot parameters, create a file in which the commands will be described. We name the file comms.js and add the code to it:

const config = require('./config.json'); // Retrieving a file with parameters and information
const Discord = require('discord.js'); // Retrieving the discord.js library
const prefix = config.prefix; //"Pull out" the prefix
// Commands //
function test(robot, mess, args) {
mess.channel.send('Test!')
}
// List of commands //
var comms_list = [{
     name: "test",
     out: test,
     about: "Test command"
}];
// Name is the name of the command to which the bot will respond
// Out is the function with the command
// About is the description of the command
module.exports.comms = comms_list;

This is an example, if necessary, you can add more functions and commands.

Before launching the bot

Important! Latest versions of Discord require the latest versions of Node.js. For example, Discord version 13 requires at least Node 16 to run. By default, the system uses the old Node 14 version.

You can check the version with the command:

node -v

You can update the version with the commands:

For Ubuntu:

curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash - &&\
sudo apt-get install -y nodejs

For Debian:

curl -fsSL https://deb.nodesource.com/setup_20.x | bash - &&\
apt-get install -y nodejs

The error Unexpected token '??=' indicates an incorrect version; you will need Node 16+.

Launching the bot

Now let's run the bot in the terminal.

node bot.js

After launch, you can select privileges. To do this you need:

  1. Go to the OAuth2 tab.

  2. In the Scopes block, check the box next to bot.

Image6

  1. In the Bot permissions block that appears, check the required privileges. Checking the Administrator checkbox selects everything.

  2. Below in the same tab, you can get a link to the bot. Just copy it and paste it into the address bar of your browser.

Image2

  1. Also enable the Message Content Intent option on the Bot tab:

34a5ed5f 34dc 4604 97b8 3f49a144accf

How to create a server and connect a bot

For the bot you need to create a channel in Discord.

  1. Log into your Discord account in a browser.

  2. To add a server, click the "+" icon in the sidebar and indicate which server template you want to use and for what purposes you will use it.

  3. In the next step, assign a server name and image.

  4. Click Create.

By default, the new server has voice and text channels. Each of them has settings that can be changed by clicking on the gear icon. You can add more channels by clicking the "+" icon. To assign an ID to a channel, you need to switch to developer mode: app settings -> advanced -> developer mode.

To connect a bot, you need to get a link in OAuth2 -> URL Generator.

Image1

As we indicated above, in Scopes check the bot box, below in Bot permissions select permissions (the Administrator selects everything).

Paste the link to the bot into the address bar.

Once you open the application, you can select a server from the drop-down list. Check that all necessary permissions for the bot are assigned. If everything is done correctly, when you return to the server, you will see a welcome message.

How to edit a bot

You can update your bot, add new options, and make the bot more user-friendly, functional, and personalized.

To make the bot encourage users, you can add a list of key phrases in response to which welcome or other messages will be displayed. To add new functionality (trigger phrase) for the bot, you need to enter data into the comms.js file. For example, we will modify the test function. An example of adding and editing trigger phrases looks like this:

const config = require('./config.json'); // Retrieving a file with parameters and information
const Discord = require('discord.js'); // Retrieving the discord.js library
const prefix = config.prefix; //Retrieving the prefix
const sad_words = ["sad", "depressed", "unhappy", "angry", "miserable"]; 
const starter_encouragements = ["Cheer up!", "Hang in there.", "You are a great person / bot!"];
// Words can be specified in any language
// Commands //
function test(robot, mess, args) {
     if (sad_words.some(word => mess.content.includes(word))) {
         mess.channel.send("Why are you sad? Maybe I can help you?");
     } else {
         mess.channel.send('Test!');
     }
}
function encourage(robot, mess, args) {
    const encouragement = starter_encouragements[Math.floor(Math.random() * starter_encouragements.length)];
    mess.channel.send(encouragement);
}
// List of commands //
var comms_list = [{
     name: "test",
     out: test,
        about: "Edited test command"
    },
    {
        name: "encourage",
        out: encourage,
        about: "Encouraging a user"
    }
];
module.exports.comms = comms_list;

Now your Discord bot will respond to messages containing trigger phrases/words from the sad_words list and send an appropriate response.

You can check the changes by sending a message like:

!test sad

With this directive, we add phrases with which the bot will respond to trigger words:

starter_encouragements = ["Cheer up!", "Hang in there.", "You are a great person / bot!"]

We added a new function called encourage, which will select a random phrase from the starter_encouragements list and send it to the channel. We then added this function to the comms_list, specifying the command name, the encourage function, and its description.

You will also need to make changes to the bot.js file (if the functionality was not included initially) so that it recognizes the new encourage command. Make sure you have the following code in your bot.js file:

for (comm_count in comms.comms) {
     var comm2 = prefix + comms.comms[comm_count].name;
     if (comm2 == comm_name) {
         comms.comms[comm_count].out(robot, msg, messArr);
     }
}

You can now use the !encourage command in Discord chat and the bot will send a random phrase of encouragement from the starter_encouragements list in response.

What is Discord Bot Maker

Discord Bot Maker is another option for creating a bot in Discord. Using the tool, you can not only create standard solutions, but also develop bots that send files, generate messages, and edit pictures.

To get started, you need to install the utility and click the Create button. After this, you can select the required set of functions and commands. Don't forget to save the bot, after that you can launch it on Discord.

Conclusion

We've covered the basic steps of creating a Discord bot, a channel, adding it to the server, and the basic commands that can be added if necessary. The process is not easy, it has many nuances, but you can figure them out and create your own personalized Discord bot that meets your goals.

Node.js
16.05.2024
Reading time: 10 min

Do you have questions,
comments, or concerns?

Our professionals are available to assist you at any moment,
whether you need help or are just unsure of where to start
Email us