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 .
![](https://habrastorage.org/webt/me/ho/jp/mehojpyjzgzowoe5ib22mirhdcu.png)
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.
![](https://habrastorage.org/webt/fv/3k/oi/fv3koicjgl19vlrag9xbdoq2fki.png)
It remains only to copy the token.
![](https://habrastorage.org/webt/ay/5s/g5/ay5sg5x3n19coc_wc_oxp1app4e.png)
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.
![](https://habrastorage.org/webt/vh/k3/63/vhk363wxfcb_nybrmcaqqpjudis.png)
Writing the "body" of the bot
First you need to create a bot description.
npm init
, ( , Enter). .
![](https://habrastorage.org/webt/s0/lf/cn/s0lfcn_yzurzagwinkthpwvqyhe.png)
npm install
npm install discord.js
, .
! , , , .
, .
![](https://habrastorage.org/webt/ku/k_/eh/kuk_eh2jsoxnnk6wxz7p8dsodm0.png)
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.
![](https://habrastorage.org/webt/r_/qg/m5/r_qgm5v2juavis-z-3bphjza788.png)
That's all, our bot is ready!
![](https://habrastorage.org/webt/d-/re/xn/d-rexngfnzs_nv3ngbvmxse98m0.png)