Discord.js | Creating a bot for Discord 🤖

austinoso

orio

Posted on April 9, 2020

Discord.js | Creating a bot for Discord 🤖

0.0 Introduction

Welcome to my short tutorial on creating a bot for Discord. Just as a note, this tutorial won't be going too in depth on every single bit of code being written, it's meant to serve as a quick guide to getting starting creating your own Discord bots. Think of this as a template.

Table Of Contents

1.Creating the Bot in Discord

Let's get started by creating a Discord Application

1.1 Visit the Discord Developer Portal and click "New Application"

Discord making an app

1.2 Go to "Bot", the click "Add Bot"

bot settings
After creating the bot, we're met with a screen that gives as access to some of the bots settings. We don't need to worry too much about anything here besides our "TOKEN". We'll need this so our bot will be able to connect to the Discord API. Click "copy" paste this somewhere safe for a moment.

2. Setting Up Our Environment

Now we've creating essentially the Discord account our bot will run on. We now need to start writing some code to give some life to our bot. However before we do, we need to setup our environment.

In your terminal, run the follow commands

mkdir my-app
cd my-app
Enter fullscreen mode Exit fullscreen mode
yarn init
// or npm init
Enter fullscreen mode Exit fullscreen mode
touch index.js config.json && mkdir client commands
touch client/Client.js commands/help.js
Enter fullscreen mode Exit fullscreen mode

Nice! Now we have almost all the files we need. Now we need to install the Discord.js module.

yarn add discord.js
Enter fullscreen mode Exit fullscreen mode

And there we go. We've got our environment setup. Now time to add some code...

3. Writing the Bot

3.1 The config.json File

In ./config we need to add a few lines that configure our app.

{
  "prefix": "#", //set to what you want your command prefix to be
  "token": "YOUR-TOKEN"
}
Enter fullscreen mode Exit fullscreen mode

The "prefix" is the character(s) you want your bots to listen for and "token" is the token you copied from the Discord Bot

3.2 The index.js File

const fs = require('fs');
const Discord = require('discord.js');
const Client = require('./client/Client');
const { prefix, token } = require('./config.json');

const client = new Client();
client.commands = new Discord.Collection();
Enter fullscreen mode Exit fullscreen mode

The first few lines will just we requiring a few files. Don't worry too much about these lines, except take a look at the line const { prefix, token } = require('./config.json'). This is destructuring our config.json file and setting it to const variables we can use later.

const commandFiles = fs
    .readdirSync('./commands')
    .filter((file) => file.endsWith('.js'));

for (const file of commandFiles) {
    const command = require(`./commands/${file}`);
    client.commands.set(command.name, command);
}
Enter fullscreen mode Exit fullscreen mode

Again some lines that just paired with a quick explanation. Here we are setting commands that are available to our client.

console.log(client.commands);

client.once('ready', () => {
    console.log('Ready!');
});

client.once('reconnecting', () => {
    console.log('Reconnecting!');
});

client.once('disconnect', () => {
    console.log('Disconnect!');
});
Enter fullscreen mode Exit fullscreen mode

Here we're logging to our console our client commands and the status of our bot.

client.on('message', async (message) => {
    const args = message.content.slice(prefix.length).split(/ +/);
    const commandName = args.shift().toLowerCase();
    const command = client.commands.get(commandName);

    if (message.author.bot) return;
    if (!message.content.startsWith(prefix)) return;

    try {
        if (commandName == 'ban' || commandName == 'userinfo') {
            command.execute(message, client);
        } else {
            command.execute(message);
        }
    } catch (error) {
        console.error(error);
        message.reply('There was an error trying to execute that command!');
    }
});
Enter fullscreen mode Exit fullscreen mode

Finally, on to an interesting part. Here the bot is listening for a 'message' event and running some code based on that message.

const args = message.content.slice(prefix.length).split(/ +/);
const commandName = args.shift().toLowerCase();
const command = client.commands.get(commandName);
Enter fullscreen mode Exit fullscreen mode

Here we're parsing out our command.

if (message.author.bot) return;
if (!message.content.startsWith(prefix)) return;
Enter fullscreen mode Exit fullscreen mode

These lines are just checking if the message is first, send by out bot, and if the message starts with our set prefix, prefix coming from our ./config.json. If the conditions for the statement are true. Then we return.

try {
    command.execute(message);
} catch (error) {
    console.error(error);
    message.reply('There was an error trying to execute that command!');
}
Enter fullscreen mode Exit fullscreen mode

Now finally, finally, the part that actually runs the command. First we try to run the command with command.execute(message), if that didn't work, our catch() will tell our user something went wrong.

3.3 The Client.js file

const { Client, Collection } = require('discord.js');

module.exports = class extends Client {
    constructor(config) {
        super({
            disabledEvents: ['TYPING_START'],
        });

        this.commands = new Collection();

        this.queue = new Map();

        this.config = config;
    }
};

Enter fullscreen mode Exit fullscreen mode

Here's a short and sweet file. All we are doing here is exporting our Client class that basically holds on to our commands and other info. If you check back at line 3 on index.js, you'll see we're requiring this file const Client = require('./client/Client');

3.4 The Commands

const fs = require('fs');

module.exports = {
    name: 'help',
    description: 'List all available commands.',
    execute(message) {
        let str = '';
        const commandFiles = fs
            .readdirSync('./commands')
            .filter((file) => file.endsWith('.js'));

        for (const file of commandFiles) {
            const command = require(`./${file}`);
            str += `Name: ${command.name}, Description: ${command.description} \n`;
        }

        message.channel.send(str);
    },
};
Enter fullscreen mode Exit fullscreen mode

This is a simple 'help' command, feel free to copy and paste this for your own bot. But let's go over something a little simpler.

module.exports = {
    name: 'command-name',
    description: 'a bit about the command',
    execute(message) {
        let str = 'hello world';
        message.channel.send(str);
    },
};
Enter fullscreen mode Exit fullscreen mode

Here's a command template you can use for your own bot. Since you'll be spending most your time in this type of file. I'll go a little more in-depth.

Let's start with name: here's were you want to set what you want to command to run by.
description: It's a bit optional, but helpful for when your users use the 'help' command. Just set this to a string that describes the command.
execute(message){//your code} now for the meat of our command. Between those curly braces, you'll want to add the code that'll be executed once the command is called.

All of this gets wrapped in a JavaScript object that then get's exported with module.exports = {//object you created}

Now all you have to do when creating a new command is follow this template and write the code you'd want to execute within that execute() function.

4. Running the Bot

Finally, to run our bot, we'll want to open our package.json file and include a scripts object.

Something like this

    "scripts": {
        "start": "node index.js"
    }
Enter fullscreen mode Exit fullscreen mode

We'll want to add so our entire file looks something like

{
    "name": "my-bot",
    "version": "1.0.0",
    "main": "index.js",
    "author": "your-name",
    "license": "MIT",
    "dependencies": {
        "discord.js": "^12.1.1"
    },
    "scripts": {
        "start": "node index.js"
    }
}
Enter fullscreen mode Exit fullscreen mode

Then in our command line, just run

yarn start
//or npm start
Enter fullscreen mode Exit fullscreen mode

You now have a fully functioning Discord Bot.

5. Adding the Bot to a server

Adding the bot to a server is very easy

  • Make sure your an admin/owner of the server you're trying to add the bot to.
  • Visit your bot's application again
  • Go to the "OAuth2" tab
  • In the "OAuth2 Generator" check "bot" and copy the link bot link
  • Finally, visit the link and add the bot to your sever.

6. Conclusion

Thanks for reading. This was an extreme overview of creating a Discord Bot. I'll link more examples and below and some documentation.

Discord.js
Bot I learned from
JavaScript MDN

💖 💪 🙅 🚩
austinoso
orio

Posted on April 9, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related