Basics of DiscordJS

Last time you learned how to use the basic NodeJS console commands, so let's expand this knowledge to make something actually useful - a discord bot.

Note: If you haven't seen the last tutorial, be sure to check it here

In this tutorial you are going to learn:
1. How to create a Discord bot account
2. How to make your bot online
3. How to make your bot respond to commands

Now, let's get started!


Preparations and requirements:

NodeJS v12 or newer, you can check your node version by using node -v.

IDE such as Visual Studio Code or Atom.

Discord Account (obviously).


Creating your project:

Now that you have everything you need, go on and create your project. This has to be a folder located anywhere on your pc.

Sn-mek-obrazovky-2020-10-15-v-17.40.27
Once you have that, open the folder in your IDE (or CD to it in terminal using cd <Path>). Now open the terminal window in your IDE, execute npm init and go through the initiation process.

Sn-mek-obrazovky-2020-10-15-v-17.44.22
This should create a file called package.js. If you have this file showing up in your IDE, you are good to go to the next step.


Creating the bot.

Now the fun begins, create files called config.json and index.js in your folder and open config.json in your IDE. Your folder should now have those files:

Sn-mek-obrazovky-2020-10-15-v-17.51.18
Start editing config.json and paste the following code into it:

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

Now, a little bit of explaining: .json files always start with { and end with }, in between of those brackets we can put items, the part before the semicolon is always the name of the value that is after the semicolon, we can get the value by "calling it's name".
You might have noticed that the value "token" is empty, we are going to get the token now. Head over here and click New Application.

Sn-mek-obrazovky-2020-10-15-v-17.56.53
After clicking that, you will be presented with a text field, just name your application however you want it to be named and click create, the website should show you something like this:

Sn-mek-obrazovky-2020-10-15-v-17.59.40
You will want to head over to the bot tab on the left of your screen.

Sn-mek-obrazovky-2020-10-15-v-18.01.22
Now click on add bot. Below the username you will have a text field saying click to reveal token, you will want to press the button below saying copy.

Sn-mek-obrazovky-2020-10-15-v-18.03.48
Now head back to your config.json file and paste the token into the token field, it should look a little something like this:

{
    "token": "NzY2MzI5NDA5MjcxMzY1Njcy.SomeSuperSecretStuff",
    "prefix": "!"
}

Note: Never share your bot token with anyone as this is the piece of data that will make you control the bot.

Go back to the Discord Developer Portal page and click on the OAuth2 page on the left side of your screen. You will see a table with a lot of items, the only one you want to press is bot.

Sn-mek-obrazovky-2020-10-15-v-18.08.15
Copy the URL on the bottom and paste it into your browser, but before opening it change the 0 in the &permissions=0 part of the URL to 8 (&permissions=8), this will give your bot administrator permissions. Add the bot to any server you want. Congratulations, you just made a bot, but before you can do anything with it you will have to give it a brain, and that means more code!


Coding the bot.

Before you can do anything, you have to install a library called DiscordJS run npm i discord.js in the IDE terminal.

Sn-mek-obrazovky-2020-10-15-v-18.14.31
Now head over to index.js and we will start coding!
Let's start with something easy. I will comment every part of the code so you can easily understand what does what.

const Discord = require('discord.js'); // specifying that we will use Discord.js for this projectDiscord
const client = new Discord.Client(); // specifying that we want to create a new client with discord
const config = require('./config.json') // specifying that we want to load Config.json 
const prefix = config.prefix; // specifying that the value prefix will be the same as the prefix specified in the config file
 
client.on('ready', () => {
    // Saying that the bot logged into the account successfully and that the bot is running
  console.log(`Logged in as ${client.user.tag}!`);
});
 
client.on('message', msg => {
// telling the bot to respond with "pong" to every message that is prefix + ping (!ping)
  if (msg.content === prefix + 'ping') {
    msg.reply('pong');
  }
});

// logging the discord bot into the account
client.login(config.token);

You can try the bot in your discord server, but just saying "pong" is not really helpful, is it? Well, let's make the bot tell us the ping in ms!
I am simply going to replace the command with this:

client.on('message', msg => {
  if (msg.content === prefix + 'ping') {
    //send a message saying that the bot is getting a ping
    msg.channel.send('Pinging...')
    .then(m => { //then edit the message with the time it took to edit it after sending the message. 
      m.edit(`Pong! \`${m.createdTimestamp - msg.createdTimestamp}\`ms`)
    })
  }
});

If you found that a little bit confusing, let me explain it more. We are grabbing the precise time when the message was sent (m,createdTimestamp) and subtracting the time the message was edited from that time (msg.createdTimestamp). Why does this work? Discord saves all the timestamps in milliseconds - for example 1602779574011 means Thu Oct 15 2020 16:32:54, so we are just grabbing both of those timestamps and subtracting the smaller one from the bigger one.


Conclusion

I believe this will do for today, the whole index.js code without comments is here:

const Discord = require('discord.js');
const client = new Discord.Client();
const config = require('./config.json')
const prefix = config.prefix;
 
client.on('ready', () => {
  console.log(`Logged in as ${client.user.tag}!`);
});
 
client.on('message', msg => {
  if (msg.content === prefix + 'ping') {
    msg.channel.send('Pinging...')
    .then(m => {
      m.edit(`Pong! \`${m.createdTimestamp - msg.createdTimestamp}\`ms`)
    })
  }
});

client.login(config.token);

If you have any questions or opinions about this tutorial, be sure to hit us up on discord.

Happy coding and i will see you next time!