Build a Discord Bot with Node.js
What is Discord?
Discord is a widely used instant messaging platform that organizes conversations into servers and channels. Servers act like group chats, each containing multiple text, voice, or video channels—each typically named based on its purpose. For instance, a “Gaming Group” server might include an “#announcements” channel for updates.
If you’ve used Discord, you’ve likely encountered bots. They are automated users that can perform tasks like moderating conversations, playing music, or welcoming new members.
In this tutorial, you’ll learn how to make your own Discord bot using Node.js, a runtime that lets you run JavaScript on the server side. Let us start by creating our server on Discord.
Generative AI & the Azure Bot AI Service
Master Azure Bot Service: Create smart chatbots with generative AI and Copilot Studio. Deploy CLU models, explore Cognitive Services and scaling, and ensure data security.Try it for freeHow to set up a Discord server for testing your bot
Before we start building the bot, we need a place to test it—this is where a Discord server comes in. Think of it as a sandbox where your bot can live and interact.
Follow these steps to create a new Discord server:
- Open the Discord app
- To create a new server:
- On the left sidebar, click the “+” button to create a new server.
- Choose “Create My Own” when prompted.
- Give this server a name like “My Bot Server” and optionally upload an image.
- Click “Create”.
Here we have created the “Codecademy Server”:
Once created, we’ll see default channels like #general. We can add new text or voice channels later as needed.
Now that we have a server, let’s move on to setting up the Discord application and integrating it with the server.
How to create a Discord application for your bot
To build a Discord bot, we first need to register it as an application on the Discord Developer Portal. This will give us access to the bot token, which is needed to connect our code to Discord.
Follow these steps to create the application:
1. Visit the Discord Developer Portal and log in with your Discord credentials.
2. Click the “New Application” button in the top right corner.
Enter a name for the application (e.g., “My First Bot”) and click “Create” to create this application.
3. Next, we need to add a bot to this application. To do that, go to the left sidebar and click on “Bot”.
Give a name to this bot, here we are giving a name “CodecademyBot”:
Optionally, we can also upload an icon and a banner for the bot. Save the changes, and the bot has been added to our application!
4. We need to invite this bot to our server that we created earlier. To do this, we need to switch to the OAuth2 tab:
OAuth2 is a protocol that allows third-party applications (like our Discord bot) to request access to a user’s resources (in this case, our server) without sharing passwords.
In Discord’s context, OAuth2 helps us authorize our bot to join servers and assign the correct permissions it needs to function properly.
In the OAuth2 tab, under the OAuth2 URL Generator, check the “bot” option. This makes the link add our bot to a server.
Now, scroll down to the Bot Permissions section and check the permissions that our bot will need. For example:
- Send Messages
- Read Message History
- Manage Messages (if you want moderation features)
Scroll to the bottom of the page, and you’ll see a long link under Generated URL. Copy that URL and open it in a new browser tab.
Choose the server that we created earlier and click “Continue”, review the permissions, and click “Authorize”. Finally complete the CAPTCHA, and our bot should now be in the server!
Now that the bot is in the server, let us code so that we can interact with it.
Build a Discord bot using Node.js and Discord.js
It’s time to start building its functionality using Discord.js, a powerful JavaScript library for interacting with the Discord API.
Let’s begin by creating a new folder for our bot and initializing a Node.js project.
Initialize a Node.js project
Open the terminal or command prompt and run:
mkdir my-discord-botcd my-discord-botnpm init -y
This creates a package.json
file that will manage our project’s dependencies.
Install discord.js and dotenv
To install the required packages, use the following command:
npm install discord.js dotenv
Here:
discord.js
allows the bot to interact with Discord servers.dotenv
helps us safely manage our secret bot token without exposing it in the code.
Create the files
Create two files in the root of your project:
index.js
: This will contain the bot code..env
: This file will store the Discord bot token.
The project directory should look like this:
my-discord-bot/├── node_modules/├── index.js├── .env├── package.json
Write JavaScript code for the Discord bot
In the index.js file, paste the code as follows:
// Import required modulesconst { Client, GatewayIntentBits } = require('discord.js');require('dotenv').config();// Create a new Discord client with message intentconst client = new Client({intents: [GatewayIntentBits.Guilds,GatewayIntentBits.GuildMessages,GatewayIntentBits.MessageContent]});// Bot is readyclient.once('ready', () => {console.log(`🤖 Logged in as ${client.user.tag}`);});// Listen and respond to messagesclient.on('messageCreate', message => {// Ignore messages from botsif (message.author.bot) return;// Respond to a specific messageif (message.content.toLowerCase() === 'hello') {message.reply('Hi there! 👋 I am your friendly bot.');}});// Log in to Discord using token from .envclient.login(process.env.DISCORD_TOKEN);
In the code:
- dotenv loads the secret token from the .env file so it doesn’t appear in the code.
GatewayIntents
let our bot listen to specific events like messages.- The
client.on('messageCreate')
event listens for messages on the server. - If a user says
"hello"
(case-insensitive), our bot replies with a friendly message. - The
client.login()
function connects our bot to Discord using the token stored in the.env
file.
Note: In our code, the bot is trying to use an intent that is not enabled on the Discord Developer Portal. Go to the Discord Developer Portal and click “Bot” in the left sidebar to enable it. Enable the MESSAGE CONTENT INTENT under the “Under Privileged Gateway Intents”.
Next, open the .env file, and paste the token into this file. To get the token, follow the steps as follows:
- Click on the bot tab on the Discord Developer Portal
- Under the Token section, click the “Reset Token” button.
- Copy the generated token. This is what we’ll use in our code.
Paste this code in the .env file:
DISCORD_TOKEN=your-bot-token-here
Note: Never share this token or push it to GitHub. The .env file keeps it safe and hidden.
Now our bot is alive and ready to chat!
Test the Discord bot
Now that our bot’s code is ready, it’s time to see it in action on our server. Open the terminal, make sure you’re in the bot’s directory, then run:
node index.js
If everything is set up correctly, you should see something like:
This means our bot is online and connected!
And that’s it! We’ve just created and tested our own Discord bot using Node.js and Discord.js.
Conclusion
In this article, we learned how to build a basic Discord bot using Node.js and the Discord.js library. We walked through setting up a Discord server, creating an application, enabling intents, managing our bot token securely with dotenv, writing basic bot code, and finally testing it live in our server.
If you’re looking to level up your JavaScript skills and start building more advanced Discord bots or web applications, check out Codecademy’s Learn JavaScript course.
Frequently asked questions
1. What is a Node server?
A Node server is a server-side application built with Node.js that handles client requests and performs tasks like serving web pages, handling APIs, or running background services—such as a Discord bot.
2. How do I keep my bot running 24/7?
To keep your Discord bot running 24/7, you must host it on a cloud platform that always stays online. Popular options include:
Replit: It offers a free tier and is beginner-friendly. You can use uptime-monitoring services like UptimeRobot to ping your Replit-hosted bot and keep it alive.
Render: Offers a free web service with automatic redeployments.
Glitch: Another free tool for quick prototyping; works well with uptime services.
Paid VPS/Servers: Platforms like Heroku, DigitalOcean, or AWS EC2 offer more reliable uptime and flexibility.
For true 24/7 uptime, avoid running the bot only from your local machine, as it goes offline when your computer shuts down.
3. Can you run a Discord bot locally?
Yes, you can run a Discord bot locally by using Node.js and executing the bot’s script from your terminal. This is useful for development and testing, though the bot will go offline once the terminal is closed.
4. What is a Red Discord Bot?
Red is an open-source, self-hosted music and moderation bot built with Python, not JavaScript. It’s highly customizable and intended for users who want a feature-rich bot without building one from scratch.
5. How does a bot respond to messages on Discord?
A bot listens for events using the Discord API. To respond to messages, use the messageCreate
event from the discord.js
library and check the message content to decide how the bot should reply.
'The Codecademy Team, composed of experienced educators and tech experts, is dedicated to making tech skills accessible to all. We empower learners worldwide with expert-reviewed content that develops and enhances the technical skills needed to advance and succeed in their careers.'
Meet the full teamRelated articles
Learn more on Codecademy
- Free course
Generative AI & the Azure Bot AI Service
Master Azure Bot Service: Create smart chatbots with generative AI and Copilot Studio. Deploy CLU models, explore Cognitive Services and scaling, and ensure data security.Intermediate1 hour - Free course
Learn Node.js: Setting Up a Server
Build an HTTP server using Node.js to facilitate the connection between a client and a server.Beginner Friendly2 hours - Free course
Learn Testing for Web Development: Server Testing
Use test-driven development to create a JavaScript server using the Express framework.Intermediate1 hour