Amazon holiday deals See deals →ad

Mets Minor League Blog

Music theory, instruments and musicians

Mets Minor League Blog

Music theory, instruments and musicians

Discord.js Guide: Build and Run a Discord Bot

A Discord.js guide explains how to build a Discord bot in JavaScript using the Discord API through the Discord.js library. To get started, create a Discord application and bot, install a supported Node.js version and Discord.js, then write and run code that listens for events such as messages or slash commands.

What Discord.js Does

Discord.js is a community-maintained JavaScript library for interacting with Discord’s API. Instead of manually constructing every API request and handling gateway events, developers use its objects and methods to work with bots, servers (called guilds in the API), channels, users, and interactions.

A bot is the application’s automated account. It can respond to commands, post messages, manage eligible server features, or connect to voice features, depending on its code and permissions. Discord.js does not host the bot: the program must run on your computer or a server to receive events and perform tasks.

The library’s interface changes over time. Check the documentation for the version you install, and avoid copying older examples without checking whether they match. This guide uses the modern interaction and slash-command approach rather than relying on the older message-prefix pattern.

What You Need Before Coding

  • Node.js: Install a current, supported release. Discord.js version requirements can change, so check the installation instructions for the version you plan to use.
  • A Discord account: You need access to the Discord Developer Portal to create an application and bot.
  • A test server: Use a server where you have permission to add the bot. Testing in a private server is safer than experimenting in a busy community.
  • A code editor and terminal: You will use these to create the project, install packages, and run the bot.

In the Developer Portal, create an application and add a bot under its bot settings. Copy its token for local use, but treat it like a password: anyone who obtains it can control the bot. Never put the token in source code you share or commit to a public repository. If it leaks, reset it through the portal.

Install Discord.js and Set Up a Project

Create a project folder, open a terminal there, and initialize it with npm init -y. Install Discord.js using npm install discord.js. A minimal project can use a JavaScript file such as index.js and a .env file for secrets. If you use environment variables, install a suitable loader such as dotenv, and add the file containing secrets to .gitignore.

A minimal bot can log in and report when it connects:

require('dotenv').config();
const { Client, GatewayIntentBits } = require('discord.js');

const client = new Client({
  intents: [GatewayIntentBits.Guilds]
});

client.once('ready', () => {
  console.log(`Logged in as ${client.user.tag}`);
});

client.login(process.env.DISCORD_TOKEN);

Put the token in the environment as DISCORD_TOKEN, then run the file with node index.js. A successful login confirms that the program reached Discord, but it does not automatically create commands or make the bot useful in a server.

Intents, Permissions, and Slash Commands

Intents tell Discord which categories of gateway events the bot wants to receive. The example requests the guild-related events needed for many basic server bots. More capabilities may require additional intents. Some, including privileged intents that expose sensitive information such as message content, must be enabled in the Developer Portal and may require approval for larger bots. Request only what your features need.

Intents are not the same as server permissions. Intents control which events Discord sends to the bot; permissions control what it may do in a server. For example, posting messages requires suitable channel permissions, while managing members requires a higher-risk permission. Give a bot only the permissions needed for its job.

Slash commands, registered as application commands, are generally a better starting point than commands that inspect every message for a prefix. Users invoke them through Discord’s command interface, and the bot receives an interaction to handle. Commands must be registered with Discord; defining a handler in your JavaScript alone does not make a command appear. During development, use a test guild for quick iteration, then follow Discord’s application-command guidance when deploying commands more broadly.

Handling an Interaction

Once a command is registered, listen for interaction events and check that the event is a chat-input command before handling it. For a simple reply, the essential operation is interaction.reply({ content: 'Hello!' }). A production bot should organize command definitions and handlers as the project grows, and handle errors so a failed operation does not leave users with no response.

Discord expects interactions to be acknowledged promptly. If a task may take longer than the response window, defer the reply and edit it when the work is complete. Also consider whether the response should be visible only to the person who invoked the command, especially when it contains private or diagnostic information. Follow the current Discord.js documentation for the exact interaction methods and timing requirements.

Testing, Hosting, and Common Problems

Run the bot locally while developing, and invite it to a test server through the Developer Portal’s installation or OAuth2 settings. Select the appropriate installation context and scopes, such as bot and applications.commands when applicable, then grant only the permissions it needs.

  • Invalid token: Check that the environment variable is loaded and contains the bot token, not the application ID or public key.
  • Command is missing: Confirm registration succeeded, the bot has the application-command scope, and you are checking the correct server or account.
  • Bot cannot perform an action: Check channel-specific permissions as well as server roles; a role’s position can also limit moderation actions.
  • Message events do not arrive: Verify the requested intents and any required privileged-intent settings. Prefer slash commands where reading message content is not necessary.
  • Bot goes offline: A local process stops when your computer shuts down. For continuous availability, run it on an appropriate host and monitor its logs and restarts.

Hosting costs depend on the provider, resource needs, and whether a free tier is available; there is no Discord.js hosting service included with the library. Keep credentials in environment variables or a secrets manager, restrict access to deployment settings, and avoid logging tokens or private user data. A bot should follow Discord’s Developer Policy and Terms of Service, including limits on unsolicited activity and automation.

Frequently Asked Questions

Is Discord.js free?
Discord.js is an open-source library, and you can develop a bot without paying for the library itself. Hosting, databases, or other services may cost money, depending on what you build.

Do I need JavaScript to use Discord.js?
Yes. Discord.js is a JavaScript library for Node.js. If you prefer another language, look for a library designed for that language and check its current maintenance and documentation.

Can I run a Discord bot on my computer?
Yes. A bot can run locally while your computer and program are on. It will generally be unavailable when the process stops, so a hosted environment is more suitable for a bot that must stay online.

Why does my bot need intents?
Intents specify which event categories the bot subscribes to. They are separate from permissions and do not, by themselves, authorize actions in a server.

Should I use slash commands or message-prefix commands?
Slash commands are a practical default for new bots because they use Discord’s interaction system and do not require scanning ordinary message text for a command prefix. Choose message-based behavior only when your feature genuinely requires it and you can meet the applicable intent and policy requirements.

Discord.js Guide: Build and Run a Discord Bot
Scroll to top