Post your build ideas
LocalASO Track App Store keyword ranks in every countryFind your vibe. Find you job which is just for you and your dataDealtab Brand Deal Tracker That Does The Work For YouIs Major Cooked? Free AI risk score + roast for your college majorWiral.Social LinkedIn, Scheduler, Scheduling Tool, Ghostwriter
Solo Era solo activities, solo maxxing, sidequests, challengeCadentiq daily routine, wellbeing, self care, healthy habitsTexeva Your businessKeepsake Project Management, Freelancers, DesignersOrvyx AI You create

How to build a Discord bot with discord.js or discord.py, from portal to server

To build a Discord bot, create an application in the Discord Developer Portal, reset and store its bot token, add the bot and applications.commands scopes, install it on a test server, then run code that logs in with the token. discord.js (JavaScript) and discord.py (Python) both handle the connection, so a first slash command is under 20 lines.

What is a Discord bot, and what do you need to build one?

Discord’s documentation calls bots apps. An app is code that talks to Discord through its APIs, and a bot user lets that app appear in a server like a member. Discord’s getting started guide says newly created apps have a bot user enabled by default. You write the code, run it somewhere, and Discord sends it events such as someone using a command.

  • A Discord account and a test server. Build and test in a server that nobody else uses. Discord’s guide says you can create one for free.
  • A language you can run. discord.js is for JavaScript and Node.js. discord.py is for Python; its documentation says it works with Python 3.8 or higher.
  • A place to keep a secret. The bot token is a password. Discord says never to share it or check it into version control.
  • One clear job. Pick a single command that does something useful before you add a second.

Unlike a website, a bot has no page to visit. It is a program that must be running to answer. That shapes everything about where you host it, which is covered below. For the general approach to choosing and scoping a build, see how to make an app.

How do you set up the app in the Discord Developer Portal?

Every bot starts in the Developer Portal. These steps follow Discord’s official quick start.

  1. Create the app. Create a new application, give it a name and press Create. You land on General Information, which shows the Application ID.
  2. Reset and copy the token. On the Bot page, click Reset Token under Token. Discord says you cannot view the token again unless you regenerate it, so put it straight into a password manager or your .env file.
  3. Pick the installation contexts. On the Installation page, choose where the app can be installed: servers, users or both. Server-installed apps must be authorized by a member with the Manage Server permission. User-installed apps are limited to commands.
  4. Add scopes. For Guild Install, add the applications.commands scope and the bot scope. Choosing bot reveals a Permissions menu; select only what you need, such as Send Messages.
  5. Install it. Copy the Install Link from the Installation page, open it in a browser and choose Add to server. Select your test server. The bot appears in the member list, offline until your code runs.

Keep permissions minimal. A bot that only answers slash commands needs very few, and every extra permission is something a server owner has to trust you with.

How do you build the bot with discord.js?

discord.js is a widely used JavaScript library for Discord, and its guide is the reference for the patterns below. Check the discord.js README for the Node.js version it currently requires. Create a folder and set it up:

Terminal: project setup
mkdir my-bot && cd my-bot
npm init -y
npm pkg set type=module
npm install discord.js
printf 'DISCORD_TOKEN=\nCLIENT_ID=\nGUILD_ID=\n' > .env
printf '.env\nnode_modules\n' > .gitignore

Fill in .env: the token from the Bot page, the Application ID as CLIENT_ID, and your test server’s ID as GUILD_ID. To copy a server ID, turn on Developer Mode in Discord’s advanced settings and right-click the server name. The discord.js guide recommends Node’s --env-file flag for loading environment variables, which the commands below use.

register.js (run once to add the slash command)
import { REST, Routes } from "discord.js";

const { DISCORD_TOKEN, CLIENT_ID, GUILD_ID } = process.env;

const rest = new REST({ version: "10" }).setToken(DISCORD_TOKEN);

await rest.put(
  Routes.applicationGuildCommands(CLIENT_ID, GUILD_ID),
  { body: [{ name: "ping", description: "Replies with Pong!" }] },
);

console.log("Registered /ping");
index.js (the bot)
import { Client, Events, GatewayIntentBits } from "discord.js";

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

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

client.on(Events.InteractionCreate, async (interaction) => {
  if (!interaction.isChatInputCommand()) return;
  if (interaction.commandName === "ping") {
    await interaction.reply("Pong!");
  }
});

const { DISCORD_TOKEN } = process.env;
client.login(DISCORD_TOKEN);
Terminal: run it
node --env-file=.env register.js
node --env-file=.env index.js

Type /ping in your test server. Discord’s command documentation says guild commands update instantly and recommends them for quick testing, with global commands for when the bot is ready for public use. That is why the registration script targets one server. When you move to global commands, switch Routes.applicationGuildCommands to Routes.applicationCommands(CLIENT_ID).

How do you build the bot with discord.py?

discord.py does the same job in Python. Install it with python3 -m pip install -U discord.py, preferably inside a virtual environment, and set DISCORD_TOKEN and GUILD_ID in your shell before running.

bot.py
import os
import discord
from discord import app_commands

GUILD = discord.Object(id=int(os.environ["GUILD_ID"]))


class Bot(discord.Client):
    def __init__(self):
        super().__init__(intents=discord.Intents.default())
        self.tree = app_commands.CommandTree(self)

    async def setup_hook(self):
        self.tree.copy_global_to(guild=GUILD)
        await self.tree.sync(guild=GUILD)


bot = Bot()


@bot.tree.command(name="ping", description="Replies with Pong!")
async def ping(interaction: discord.Interaction):
    await interaction.response.send_message("Pong!")


bot.run(os.environ["DISCORD_TOKEN"])

The setup_hook copies the command to your test server and syncs it, so it appears at once. Choose the library by the language you already know. The features line up closely enough that a first bot is the same in either.

discord.js or discord.py
discord.jsdiscord.py
LanguageJavaScript or TypeScript on Node.jsPython
Good fit whenYou also build websites, or want one language across the stackYou write scripts, data work or machine-learning code in Python
Command registrationA REST call, or the library’s command managerA command tree that you sync
Guidediscordjs.guidediscordpy.readthedocs.io

What are intents, and what limits apply to slash commands?

Intents decide which events Discord sends your bot. Discord’s quick start says standard intents need no extra configuration, while privileged intents expose potentially sensitive data such as message contents and must be toggled on the Bot page. Discord’s Gateway documentation lists the privileged intents as GUILD_PRESENCES, GUILD_MEMBERS and MESSAGE_CONTENT, and says apps in 100 or more guilds must be verified and have those intents approved.

The practical advice is to design around slash commands. Reacting to every message needs the message content intent, which is the one most likely to stop you later. A command like /summarize gets what it needs in the interaction itself. Discord’s application commands documentation sets these limits:

  • Command names are 1 to 32 characters, and chat input names must be lowercase where a lowercase form exists.
  • Descriptions are 1 to 100 characters.
  • A command can have at most 25 options.
  • A closed connection with code 4014 means you requested a privileged intent that is not enabled or approved.

Where do you host a Discord bot, and can an AI agent write it?

A bot that connects through the Gateway answers only while its process is running. A laptop that sleeps is an offline bot. For real use you need a small always-on server or a host that runs long-lived processes, and you set the token as an environment variable there, not in the repository. Discord’s quick start also shows the other model: an Interactions Endpoint URL, where Discord sends your app web requests instead of holding a connection, which does not need a process holding a connection open. Check each host’s plan terms for sleep and uptime before relying on it.

Bots suit AI coding agents well, since the code is small and the loop is quick: edit, restart, try the command. Give the agent the constraints so it does not invent ones. The free AI Coding Prompt Builder can draft the brief, and the agent guide covers the working method.

Build prompt for a Discord bot (copy and fill in)
Build a Discord bot called [name] in [JavaScript with discord.js / Python with discord.py], in the project folder that is already open.

User: [the kind of server and the people who will use the bot].
Job: [the one thing the bot does, in one sentence].
Commands:
1. /[command]: [what it does, its options and what it replies]
2. /[command]: [what it does]

Rules:
- Slash commands only. Do not use the message content intent or any other privileged intent.
- Read DISCORD_TOKEN, CLIENT_ID and GUILD_ID from environment variables. Never write a token in code.
- Register commands to my test guild first, and show me how to switch to global commands later.
- Reply with an ephemeral message when a command fails, and never crash on bad input.
- Request the fewest permissions possible and tell me which ones you need and why.
- Keep data in memory or a local file for now; no database.

Out of scope: music, moderation, dashboards, payments.

Before writing code, list the files, the commands and the permissions you will use, then wait for my go-ahead. After each step, tell me how to run it and what I should see in Discord.

Not sure what to build? The Discord bot ideas list has small, scoped starting points, and the board has more under categories like social and gaming. Each idea has a generated build prompt. If you have a bot idea you will not build yourself, post it; it is free and needs no account.

Frequently asked questions

How do I make a Discord bot?

Create an application in the Discord Developer Portal, reset and copy the bot token from the Bot page, add the bot and applications.commands scopes on the Installation page, and install it on a test server. Then run code using discord.js or discord.py that logs in with the token and answers a slash command.

Is it free to build a Discord bot?

Creating an application and a test server in Discord is free, and discord.js and discord.py are open-source libraries. The cost is hosting: a Gateway bot must keep running to answer, so you need an always-on process. Check the terms of any free host for sleep and usage limits.

Should I use discord.js or discord.py?

Use the one in the language you already know. discord.js runs on Node.js and suits JavaScript or TypeScript developers. discord.py works with Python 3.8 or higher and suits scripting and data work. Both can register slash commands and respond to interactions, so a first bot is equally easy in either.

Where do I find my Discord bot token?

In the Developer Portal, open your application, go to the Bot page and click Reset Token under Token. Discord says you cannot view the token again unless you regenerate it, so store it in a password manager or an environment variable. Never commit it to a repository.

Do I need the message content intent?

Not for slash commands. Message content is a privileged intent that must be enabled on the Bot page, and Discord says apps in 100 or more guilds need verification and approval to keep using privileged intents. Design the bot around slash commands and you avoid the issue.

Why does my slash command not show up?

Check that the app was installed with the applications.commands scope, that you registered the command, and that you are looking in the right server. Discord says guild commands update instantly, while global commands are meant for finished bots. Register to a test guild first, then retry.

Created with AI assistance and edited for this site. Examples are illustrative and do not represent customer research. About the publisher.