Discord.js Beginner's Guide

Collin - Discolytics CEO,discord.jsguide

Creating a Discord bot has neve been easier. Create your bot with discord.js in 6 simple steps, no experience required.

What is discord.js?

Discord.js is a library that allows you to create a Discord bot in Node.js. It provides a simple and easy-to-use API for interacting with the Discord API, making it easy to build powerful and interactive bots. If you don't know what a library is yet, don't worry. We'll explain all this and more in the upcoming beginner's guide.

Here, we'll walk you through the steps of creating your first bot. Our bot will use JavaScript and discord.js to run.

Step 1. Download Node.js

Node.js is the runtime that will run your JavaScript code. A runtime is a program that reads the code you write and executes it. Download it from the offical website:

https://nodejs.org/en/download/package-manager (opens in a new tab)

Step 2. Create your Bot

To create a Discord bot, you'll need to create a new application on the Discord Developer Portal. This will give you a token that you'll use to connect your bot.

  1. Go to https://discord.com/developers/applications (opens in a new tab) and click New Application.

  2. Name your bot, accept the terms of service, and click Create.

  1. On your application's page, select the Bot tab and click Reset Token. This will regenerate your bot's token. Copy this, we'll need it later.
⚠️

The token is like the password for your bot. Don't share it with anyone you don't trust, or else they can login to your bot.

Step 3. Invite your Bot to your Server

Generate your invite link on the OAuth2 tab of your application's page. On this page under OAuth2 URL Generator, select the following permissions and scopes:

  • bot
  • applications.commands
  • Administrator (or whatever permissions your bot needs)

Copy the link generated at the bottom of the page. Open the link in your browser and invite the bot to your server. You'll notice the bot isn't online yet. We'll fix that in the upcoming steps.

Step 4. Project Setup

Using your text editor of choice (we'll be using VS Code for this example), create a new folder. Here will lie the code and files for your bot.

💡

You can download VS Code from the official website: https://code.visualstudio.com/download (opens in a new tab)

Open the terminal in VS Code (CTRL + Shift + ` or use toolbar at top). The terminal is a place where you can run commands on your system. Run the command npm init -y. This will setup your project structure for Node.js to begin coding.

npm init -y

Install the discord.js and dotenv libraries by running the following command in your terminal. A library is a piece of code published by a developer to be used by other developers. Libraries are used all the time in nearly every language, and make software development much easier. As a developer, you'll use libraries all the time to make coding faster and easier, and solve problems you don't know how to solve (but another dev does).

npm install discord.js dotenv

Finally, create a file called index.js. This is the main file where we'll be writing most of our code. At the end, this is what our file structure should look like:

    • index.js
    • package-lock.json
    • package.json
  • Step 5. Write the Code

    Create a new file called .env. A .env file is used to store environment variables. An environment variable contains information, usually secretive, that will be used by our code.

    Inside the .env file, add the following line. Paste your bot token in here from the previous step.

    TOKEN=your-bot-token-here

    Open your index.js file and add the following code. These lines initiate the discord.js library and connect your bot.

    require("dotenv").config();
    const { Client } = require("discord.js");
     
    const client = new Client({
      intents: ["Guilds"],
    });
     
    client.login(process.env.TOKEN);

    Add the following lines. These lines will listen for the ready event, which occurs when your bot connects to Discord. When we receive this event, we log to the terminal, and create the /ping command. Paste your server ID where it says YOUR_GUILD_ID. This will create the command in that server.

    client.on("ready", () => {
      console.log(`Logged in as ${client.user.tag}!`);
     
      client.application.commands.set(
        [
          {
            name: "ping",
            description: "Replies with Pong!",
          },
        ],
        "YOUR_GUILD_ID",
      );
    });

    Add the following lines. These lines will listen for the interactionCreate event, which occurs when a user interacts with your bot. We check to see if the interaction is a slash command, and if the command is named ping, we reply with Pong!.

    client.on("interactionCreate", async (interaction) => {
      if (!interaction.isChatInputCommand()) return;
     
      if (interaction.commandName === "ping") {
        interaction.reply({ content: "Pong!" });
      }
    });

    At the end, this is what your index.js file should look like:

    require("dotenv").config();
    const { Client } = require("discord.js");
     
    const client = new Client({
      intents: ["Guilds"],
    });
     
    client.login(process.env.TOKEN);
     
    client.on("ready", () => {
      console.log(`Logged in as ${client.user.tag}!`);
     
      client.application.commands.set(
        [
          {
            name: "ping",
            description: "Replies with Pong!",
          },
        ],
        "YOUR_GUILD_ID",
      );
    });
     
    client.on("interactionCreate", async (interaction) => {
      if (!interaction.isChatInputCommand()) return;
     
      if (interaction.commandName === "ping") {
        interaction.reply({ content: "Pong!" });
      }
    });

    Step 6. Run your Bot

    In your terminal, run the following command. This will run the code in the index.js file and start your bot.

    node index.js

    You should see the log in your terminal, Logged in as x. Your bot is now running and responding to the /ping command! Press CTRL + C or the trash icon to stop the bot.

    Conclusion

    You now have your own bot running on Discord! You can expand this code to customize and add more features to your bot. For more information, check out the Discord.js documentation:

    https://discord.js.org/docs (opens in a new tab)

    Here is the source code:

    https://github.com/discolytics/articles/tree/main/discordjs-guide (opens in a new tab)

    discolytics logo

    Bot monitoring, analytics, and more. We'll call you when your bot goes down.

    © 2024 Discolytics