Learn to Code via Tutorials on Repl.it!

← Back to all posts
Let's code a Discord bot in JavaScript! (discord.js)
h
Ghostwolf (3)

👋 Hey there! In this tutorial, I'll teach you how to create a Discord bot, which will let you add and respond with "tags" - responses that you can send using the bot!


Problem

Have you ever felt like people kept asking you the same question over and over again? If yes, then today we'll be building a solution to that. If no, you're lucky, but I'd suggest still following this tutorial, because who knows, you might be in the same situation too in the future!


What we're going to use?

  • Discord (you need to have a Discord account)
  • JavaScript (Node.js)
  • Discord.js package
  • Repl.it Database to store responses

Don't worry, if you don't understand these things. I'll explain them later on! Just make sure you have a Discord account already!


Creating the bot account on Discord

Navigate to Discord Developers page, login if you need to and press "New Application" in the top right corner! Give it a name and click "Create"!

If you want to, give it a cool looking avatar too! Just don't forget to save changes after doing that!

Navigate to "Bot" tab and click "Add Bot" button and then confirm your action by clicking "Yes, do it!".

🎉 Tada~~! We've created the account for our new bot! The page should look like this:

I'd also suggest you to turn off "Public Bot" setting, this will make it so only you can add bots to Discord servers, so you wouldn't experience any issues in the future! Don't forget to save the settings again!

And finally, let's add the new bot to your Discord server! Use the following link to do that:
https://discord.com/api/oauth2/authorize?client_id=BOT_ID&permissions=0&scope=bot

Replace BOT_ID with the application ID, which you can find in "General Information" tab!

Select your server (if you don't see any, you'll need to create one), click "Authorize" and solve the captcha.

That's it! The bot is now in our server!

You can close that page, that tells you "Authorized"!

Don't close the bot information page yet! We'll need it later on!


Let's build the bot!

Finally, it's time to code now! Create a new repl!

We're going to use Node.js, which is just server-side JavaScript.

You should see this now:

Time to install Discord.js package. If you don't know, very much simplified, packages are codes, created by the other developers for everyone else to use! I'm also including the explanation from W3schools too:

A package in Node.js contains all the files you need for a module. Modules are JavaScript libraries you can include in your project.

Let's navigate to the packages tab and search for "Discord.js".

Click the entry called "discord.js" and press the plus icon.

Let's go back to our files now! They should look like this:

Don't worry about "package.json" and "package-lock.json" files! However, don't delete them either.

Open "index.js" file and let's get to coding!

Firstly, let's add these lines of code, that'll allow us to use Discord.js package, Repl.it database and create a new "client" as well as database.

const Discord = require("discord.js");
const Database = require("@replit/database");

const client = new Discord.Client({ disableMentions: 'everyone' });
const db = new Database();

{ disableMentions: 'everyone' } will prevent the bot from mentioning @everyone and @here, because, otherwise, it could cause mess in your server D:

Now, let's add this code:

client.on('message', (message) => {
  // Code
});

What's going to happen here is that when anyone sends a message in a channel that the bot is able to see, it'll run the written code. We should test it out! Replace // Code with this:

if (message.content == "hello") {
  message.reply("Hi! :)");
}

Lastly, your bot will need to login to Discord! Open the bot information page, where we created our bot account, go to "Bot" tab and copy the bot token!

⚠️ Make sure to keep this token a secret! Never share it with anyone, treat it like your password!

Navigate to "Envitonment variables" tab on replit:

Click "Got it!". We'll keep our bot token here! Let's add our first secret. Type "token" as the key, paste your Discord bot token into the value field and click "Add".

And finally, at the bottom of our code, type this code.

client.login(process.env.token);

This will let your bot to login into Discord!

We're all almost set! If you want to, let's add just a few more lines of code just to know when the bot has logged in.

client.on('ready', () => {
  console.log("Hello! I'm alive! I'm logged in as " + client.user.tag);
});

Your code should look something like this:

const Discord = require("discord.js");
const Database = require("@replit/database");

const client = new Discord.Client({ disableMentions: 'everyone' });
const db = new Database();

client.on('ready', () => {
  console.log("Hello! I'm alive! I'm logged in as " + client.user.tag);
});

client.on('message', (message) => {
  if (message.content == "hello") {
    message.reply("Hi! :)");
  }
});

client.login(process.env.token);

Let's run the app! Click the "Run" button at the top. When it responds with "Hello! I'm alive! I'm logged in as ..." in the console, let's go to Discord and send "hello" into the channel!

Congratulations! Your bot is online and working! :D

Let's do something more! Let's make it save an reply with responses!


Build something even bigger!

I'll assume that you know more JavaScript in this part. I hope you know things like string methods :)
We're going to use Repl.it Database to save our responses!

Firstly, we don't want other bots to use our bot. That's a common practice on Discord. Replace the existing client.on('message') (line 11 in our full example somewhere above) code with this:

client.on('message', (message) => {
  if (message.author.bot) return;

  // Code
});

The new line in this code stops your bot from execute the code further if the new message was send by another Discord bot.

We should also add a prefix - a symbol, that the human needs to put first in the message so we would know that they want to do something with our bot! Let's use ? as our prefix. Add another line of code, that stops the code execution if the message doesn't start with ?.

if (!message.content.startsWith("?")) return;

Do you know what ! in this line does? :)

Let's add commands! Let's say, we'll only need add and remove commands to manage tags! Add the following code:

var tag = message.content.slice(1).split(" ");
if (tag == "add") {
  // Code
} else if (tag == "remove") {
  // Code
} else {
  // Code
}

Let's say, I just ran a command to add a new tag ?add hello Hello world!. Let's add it to our database!

db.set(tag[1], tag.splice(2).join(" ")).then(() => {
  message.reply(`Added a new tag: \` ${tag[1]} \``);
});

What this does is it sets a new key in the database with the value and then replies with the new tag's name if everything's alright or with an error, if something went wrong.

Let's add the deletion too! Let's say, we run ?remove hello.

db.delete(tag[1]).then(() => {
  message.reply(`Deleted: \` ${tag[1]} \``);
});

Lastly, let's assume that the user wanted to get the response! Replace the last // Code with this:

db.get(tag[0]).then((tag) => {
  if (tag == null) return;
  message.reply(tag);
});

What it does is it checks if the tag actually exists and then sends a message if the response is found!

Your code should look like this now!

const Discord = require("discord.js");
const Database = require("@replit/database");

const client = new Discord.Client({ disableMentions: 'everyone' });
const db = new Database();

client.on('ready', () => {
  console.log("Hello! I'm alive! I'm logged in as " + client.user.tag);
});

client.on('message', (message) => {
  if (message.author.bot) return;
  if (!message.content.startsWith("?")) return;

  var tag = message.content.slice(1).split(" ");
  if (tag[0] == "add") {
    db.set(tag[1], tag.splice(2).join(" ")).then(() => {
      message.reply(`Added a new tag: \` ${tag[1]} \``);
    });
  } else if (tag[0] == "remove") {
    db.delete(tag[1]).then(() => {
      message.reply(`Deleted: \` ${tag[1]} \``);
    });
  } else {
    db.get(tag[0]).then((tag) => {
      if (tag == null) return;
      message.reply(tag);
    });
  }
});

client.login(process.env.token);

Let's test the bot out on Discord!

It works! We did it! :D


Extra challenges

Here are some more things that you can try to add to this bot by yourself! I've also provided hints where to look and results how to solve the challenges. Just remember, you can solve these tasks your way, it's just how I would solve them!

  • Create a command that lists all existing tags! (Hint, Result)
  • Make it so the tag responses would be in embeds! (Hint, Result)
  • Make it so only server administrators could add and remove tags! (Hint, Result)

Resources

Here are some resources, that should help you learn discord.js!


I hope you learnt something new! :)

That's it! Good luck with your future projects!

Comments
hotnewtop