How to Code a Discord Bot in JavaScript

Having a Discord bot on your server can be a great deal useful, and coding one for yourself is a nice way to practice your coding skills, get a better reputation in the community, and do some marketing.

In February 2020, I’ve released my first ever Discord bot, Art Prompts. It’s a fairly simple concept, only a few tens of lines of code. However, on my coding journey, I struggled to find a good, beginner-friendly, comprehensive guide to creating and hosting a Discord bot. I’d like this article to be that guide for you.

What Can Discord Bots Do?

A Discord bot, if public, can be added to any Discord server. Once there, the bot can do pretty much anything you code it to do, provided it has the necessary permissions. Here’s a rundown of some bots; check them out so you know what you can achieve with a bot.

As you can see, some of these bots get pretty complex. However, that doesn’t mean you can’t have success with a simple bot – as long as it’s useful, or entertaining, and you do a good job maintaining and marketing it, people are still going to add it to their servers.

Tools Used to Create Discord Bots

You can create a Discord bot in many programming languages, including Java (check out this series by Caleb Garcia if you want to code bots in Java), Python, PHP, C#, Go, Lua, Ruby, and I’m sure you could find libraries for many other languages. However, in this article, I’d like to use JavaScript, more specifically NodeJS, and the library Discord.js. I believe JavaScript is one of the most beginner-friendly of the bunch, so if you’ve never tried coding, it’s a good place to start. Plus I coded my bot in JS, so I have more experience there than with the other languages.

You’re also going to need some sort of editor to work with your code. I use Visual Studio, but that’s mainly the question of personal preference.

Those are the tools you’re going to need for coding the bot. When it comes to hosting (meaning running the bot on a server so it’s online 24/7), you can again use a halo of different tools. If you have your own server where you can run the bot, that’s amazing! Use that.

If you don’t have a server, you can use a hosting service; I use Heroku. Heroku can be used to host your bot 24/7, for free, as they offer up to 1000 hours a month without paying anything. It’s a little tough to set up, but I’m going to guide you through that. After that, it works like a charm and you don’t have to worry about anything (this isn’t sponsored, by the way).

With the tools ready to go, we can finally dive into the bot making itself.

Setting Up the Discord Bot

To be able to run your Discord bot, you first have to create it in the Discord Developer Portal. Click on the link, sign in with your Discord account, and click New Application. Name your bot, set its profile picture, and fill out its description. On this page, you will see a Client ID, and a Client Secret, just under the application’s name, and above the description text box. We won’t actually be using the Client Secret today, but we will be using the Client ID later on in the bot invite link generation section. So just remember that it’s here.

Now go to the Bot section by clicking the appropriate button in the menu on the left-hand side. Here you can click the button Add Bot. Confirm that you want to add a bot to this application, and voila, you’ve got a Discord bot!

You have to set up its profile picture and name, again. You’ll also notice a “token”, just below the name text box. We will also be using that later, to actually connect our bot code to the application you’ve just created.

Coding the Basics using NodeJS

If you’re familiar with NodeJS, you can probably skip the next few paragraphs – we’re going to set up a project folder, and get everything ready for the bot’s actual code.

The first thing you want to do is find a nice empty folder that will be storing your bot’s code. Create a new file called bot.js – this will be the bot’s main code, which will handle all the commands.

Now we’re going to add the necessary libraries. These will help connect the code you’re going to write, to Discord. Install NodeJS, if you don’t already have it.

Open the command line in your empty folder, and type “npm install discord.js”. This will install the Discord.js library.

Now let’s set up the initial code for the bot. Open the bot.js file, and copy the following code;

const Discord = require('discord.js');

const client = new Discord.Client();

console.log('Starting.');

client.on('ready', () => {

    console.log('I am ready!');

});


client.on('message', message => {

});

client.login("YOUR BOT TOKEN");

The first two lines of this code connect the code with Discord. After that, the bot prints to your private console it’s starting. The first method runs when the bot successfully logs in to its Discord account, while the second method runs every time someone sends a message on a server the bot is on.

The last line logs the bot into Discord. You’ll have to paste in your bot’s token inside the quotation marks.

Inviting the Bot to a Server

That’s pretty much it for the bot’s setup. You can invite the bot to your testing Discord server (or create one, if you don’t have it already), using this link;

https://discord.com/oauth2/authorize?client_id=123456789012345678&scope=bot

Paste your Client ID (from the Discord Developer Portal) instead of the 123456789012345678 in the link, and you should be able to invite the bot to any server you’re an admin of.

Running the Bot

While testing, you will be running your new bot from your computer. We’ll upload it to a server later on. For now, open the command line in your bot’s folder, and type “node bot.js”.

At this point, you should see the bot respond with “Starting” and “I’m ready!” in the console. After that, you should be able to see your bot actually online on the Discord server you invited it to.

To shut the bot down, go back to your terminal and press ctrl+C.

Responding to Messages

In this section, I will be guiding you through setting up the bot’s commands. For our testing purposes, we will be setting a bot that responds to “!ping” with “pong”, and to “!embed” with a Rich Embed message.

Using this basis (and the resources I will link to at the end of this article), you should be able to code anything you need for the bot.

Best Practices

Before you write your commands, you’ll want to include a few lines in the method that reads and responds to the messages. These lines will prevent your bot interacting with another bot (which could, in the worst case, lead to your bot crashing due to strain), and it will stop the bot reading the message if it doesn’t begin with your set prefix. This will speed your bot up a bit.

const COMMAND_PREFIX = "!";

client.on('message', message => {

    if (message.author.bot) {
        return;
    }

    const lowerContent = message.content.toLowerCase();

    if (!lowerContent.startsWith(COMMAND_PREFIX)) {
        return;
    }

});

This code will help your bot run a bit faster. Now, let’s set up the commands!

Setting Up Commands

While we will be setting up only two commands for the purposes of this article, “!ping” and “!embed”, you can set up as many as you want. Make sure, however, that your commands are unique. If they are something fairly obvious, such as “!help”, the command could crash with another bot, and you don’t want that to happen.

In order to be easily able to edit your commands, we will first define all of them as string variables, like this;

const COMMAND_PREFIX = "!";

const COMMAND_PING = "ping";
const COMMAND_EMBED = "embed";

After that, we will use a switch statement to check if the user typed one of the commands, and respond to it accordingly.

    switch (lowerContent) {

        case COMMAND_PREFIX + COMMAND_PING:
            Pong(message);
            break;

        case COMMAND_PREFIX + COMMAND_EMBED:
            Embed(message);
            break;
    }

Now, all we have to do is code a method for each of the commands, and the bot is essentially done.

For the first command, we simply want our bot to respond to “!ping” with “pong”. This function will be very simple, but it will teach you how a bot can write simple messages. This is the code for this command;

function Pong(message) {

    message.channel.send("pong");

}

Next up, the embed command. On this command, I would like to show you how to work with so-called Rich Embeds, which are specially formatted messages that only bots can send.

I will be creating only a fairly simple embed, but you can go much more complex; here’s a complete guide specifically on embeds by Discord.js!

An example of a Rich Embed in the Discord.js library for Discord bots.

For more complex embeds, including imagines, links, footers, and a ton of other features, check out the guide I linked above. For this simple embed, paste in this code;

function Embed(message) {

    const exampleEmbed = new Discord.MessageEmbed()
        .setColor('#ff652f')
        .setTitle('Eledris')
        .setURL('https://eledris.com/')
        .addField('Test Field Headline', 'Test Field Value', true);

    message.channel.send(exampleEmbed);

}

You can find the complete code of this little testing bot at the end of this article.

Before we set up 24/7 hosting for the bot, you need to create two new files. One of them, “package.json” is going to include all the important information about the bot. Copy the following code into it, and fill in the information about your bot.

{

  "name": "eledrisbot",

  "description": "A test bot made for an Eledris article.",

  "version": "0.1.0",

  "main": "bot.js",

  "scripts": {

    "start": "node bot.js"

  },

  "dependencies": {

    "discord.js": "12.2.0"

  }
}

Finally, we need a Procfile file. This is the point where many beginner developers screw up and hit a roadblock, so execute the next steps carefully.

  1. Create a new file called “Procfile.txt” (the capital P is important)
  2. Paste this text, without the quotation marks, into it: “worker: node bot.js”
  3. Save the file and close it.
  4. Remove the “.txt” from the name. From this point, the file should be only “Procfile“, without any file extension.

And that’s all you need to do. In the next step, we’re going to set up the bot’s 24/7 hosting on Heroku.

Hosting the Bot

Now, obviously, you don’t want to run your bot from your computer. You want the bot to run 24/7 from a secure (and preferably free) server. While there are many ways to host a bot, I personally use Heroku.

Heroku is a hosting service that you can use for free (for one bot). It can be a bit confusing to set up, so let me guide you through it. If you already have hosting figured out, you can skip this section and go straight to Next Steps.

Create an account on Heroku (or log into your existing account). Click on the Create New App button, and name the new app. Select a region for the app. Personally, I chose the United States, because that’s where most of my audience lives. Click the Create App button.

Now you have to get your bot’s files to Heroku. The easiest way to do this is via GitHub. In the Deploy section of your new Heroku Dashboard, click on Connect to GitHub, and connect your GitHub account. Upload your bot to a repository (make sure it’s a private one), and Deploy

Finally, there’s one more thing you need to do before you’re pretty much done. Go to the Resources section of your Heroku Dashboard. You should see something like this:

A screenshot of the Heroku Dashboard when setting up Discord Bot hosting.

You want to turn off the first dyno, “web”, by clicking on its Edit button and switching it to the off state. After that, turn on the lower dyno, labeled “worker”.

That’s it! Your bot should now be running 24/7. Keep in mind that Heroku is free for 1000 hours a month – this is enough for one bot, but you’ll have to pay if you want to host more bots at once. You will also need to add your credit card in your account settings, in order to unlock the full free 1000 hours.

If you have any problems with coding or hosting your bot, please feel free to let me know on darezar@eledris.com, I’ll be happy to help you out.

An ad for my Android app, Art Prompts

Next Steps

Your bot is all set up. You can now use the Discord documentation to code whatever you want to. However, there are some things you should keep in mind for the future of your bot.

Verification

Once your bot get into its 75th server, you can apply for bot and developer verification. Once your bot hits 100 servers, your actually have to be verified. Until you get verified, your bot will not be able to join more than 100 servers.

In order to get verified, you need to fill in the official Discord application form. Once you fill everything in, it might take a few days to weeks to get approved. After that, your bot will get a checkmark, and you will get a Verified Developer badge.

Caching

The Discord.js library caches a lot of data it doesn’t really need. It does this to save time, but in the process, it fills up a lot of memory. When I released my bot, around the 500 server mark, the bot started crashing due to a lack of memory on my Heroku server.

In order to solve this problem, I have switched to the Discord.js-light library. It’s pretty much the same as the default Discord.js, but it doesn’t automatically cache almost anything. You can read more about it on its GitHub page.

Sharding

If and when your bot hits its 2000th server, you will need to code in sharding. Very basically put, you will be splitting your bot into two or more processes, in order to save the bot some strain.

I will be writing a separate article on sharding for Discord bots, but in the meantime, check out this official Discord.js guide.

Help Command, Email, and a Support Server

Users of your bot will inevitably run into some issues. Maybe they won’t understand how to use your bot, or they will want to suggest a new feature, or they will find a bug that they want to report to you so you can fix it.

In order to help your users (thus provide a better experience for them), be sure to include a help command for your bot. Let it mention an email address the user can write to if they have a problem, a report, or a suggestion.

Finally, create a support server for your bot. People who use your bot will join in, talk to you, and over time, you will be able to create a whole community around your bot.

Marketing

You obviously want your bot to be on as many servers as possible. Having a popular server allows you to create a large community of supporters, promote your other projects in the future, and maybe even make some money via donations or premium features.

Perhaps the hardest part of the bot marketing journey is getting the bot on its first 250 servers. After that, the bot will kind of grow on its own (which is not to say you should stop promoting it at that point).

In order to get to those first 250 servers, you can use a variety of marketing options. The most obvious one is to add your bot to several bot list websites, such as top.gg, or Bots on Discord. It might take a few weeks until they approve your application, but those lists are the place where people search for bots, so you want to be there.

You can also post about the bot on Reddit, specifically the r/discordapp subreddit. Videos of the bot in use work especially well (that’s how I got my first 150 servers).

A big advantage over other bots, if you can afford it, is to set up a website for the bot. If you do SEO well, you can even get on the first page of Google for certain bot-related terms, which is a godsent. For example, my Art Prompts Discord bot is often added through my website, when people search for something like “discord art bot”.

Freelance Bot Coding

If this all seems a bit too complex, I would love to help you by coding your bot for you! I offer my freelance services on bot coding on the Fiverr platform; check out my gig if you need a quality bot coded for you.

A promo image for my Fiverr Gig on coding Discord bots, starting at $20.

Project Files

We coded a lot of stuff today. You can download a free template for your Discord bot (along with a ton of other exclusive resources) by signing up to my newsletter.

Subscribe to Eledris


 

Conclusion

Discord bots are a very useful tool. With Discord planning on better implementation for bots, this is the time to develop your own bot. You can use the bot to grow your community and income.

Thank you for reading this far! If you want to join our awesome community around the Eledris blog, consider checking out our Discord server.

FAQ

Do you need money to make a Discord bot?

Short answer; no. You can learn to code a bot yourself, and set up free hosting on sites like Heroku.

How do I code a Discord bot?

You can code a Discord bot in a variety of different languages, but I prefer NodeJS. You have to set the bot’s file up, connect it to Discord, and code all the commands. After that, you have to set up hosting and marketing.

Leave a comment