Creating a Discord bot based on discord.js

Background


I became interested in creating a bot for Discord, but all I found was a couple of videos on YouTube, and even there they just wrote the code, without any explanation. So I want to start a series of articles on creating bots based on discord.js.


Getting a bot token


First, we need to go to the application creation page and click New Application .



After which, we will be asked to name our application. Enter the desired name and click Create . We get to the application settings page, where we can change the name, avatar, description, etc. But we don’t need it yet, go to the Bot tab . And create a bot.



It remains only to copy the token.



Preparing a development environment


First you need to install Node.js and Visual Studio Code (VS code), in the latter, in fact, the process of creating a bot will take place. We start VS code. We open the folder in which our bot will be stored. Click View-> Terminal , after that a terminal should appear at the bottom of the application.



Writing the "body" of the bot


First you need to create a bot description.


npm init

, ( , Enter). .



npm install

npm install discord.js

, .


! , , , .


, .



botconfig.json, .


{
    "token":"Njc2MTY0NDQwNTg4MDI1ODY2.XkFyMg.cMKBXh5AJ-u0SQt501OoAd*****", //  
    "prefix":">" // ,   '!'  '>'
}

index.js, .


const Discord = require('discord.js'); 
const bot = new Discord.Client();
//  
let config = require('./botconfig.json'); 
//""   
let token = config.token; 
let prefix = config.prefix;
// -  
bot.on('ready', () => { 
    console.log(`  ${bot.user.username}`);
    bot.generateInvite(["ADMINISTRATOR"]).then(link => { 
        console.log(link);
    });
});
//,  ,    
bot.on('message', msg => {
    if (msg.content === prefix + 'habr') {
        msg.reply('The Best!');
    }
});
bot.login(token);

! .
! , .


node index.js

After which it remains to add the bot to the server using the received link.



That's all, our bot is ready!



All Articles