How to make a Discord bot in 2026 (Python or JavaScript), from zero to online

, developer of Bot-Hosting

This guide takes you from nothing to a working Discord bot with two slash commands: /ping, which answers with the connection latency, and /roll, which rolls a die with as many sides as you ask for. You build it once in JavaScript with discord.js and once in Python with discord.py, side by side, so you can pick the language you already know.

Every file below was run on 30 November 2026 with the exact versions pinned here: discord.js 14.28.1 on Node.js 24 and 22, discord.py 2.7.1 on Python 3.14. Older tutorials break in small ways, like a renamed event or a missing module on a new Python. This one tells you where.

What you need before you start

  • A Discord account and a server where you have the Manage Server permission. Create an empty test server if you do not have one: you will invite your bot there first.
  • One runtime. For JavaScript, Node.js 22.12 or newer. For Python, Python 3.10 or newer; the examples were tested on 3.14.
  • A code editor and a terminal.

You do not need a server or a credit card to build and test the bot. It runs on your computer while you work on it. Keeping it online when your computer is off is the last step.

Step 1: create the application in the Developer Portal

Discord calls every bot an “application”. The bot user that appears in your server is one part of it. You set it up on four pages of the Developer Portal.

Schematic of the four Developer Portal pages used to set up a bot: New Application with a name field and Create button, General Information with the Application ID, Bot with Reset Token and three privileged intent toggles left off, Installation with Guild Install, Discord Provided Link, the applications.commands and bot scopes and the Send Messages permission
  1. New Application. On the applications list, click New Application, type a name and press Create. Members will see this name; you can change it later.
  2. General Information. This page opens next. Copy the Application ID. You will see it again as client_id in the install link.
  3. Bot. Open Bot in the left sidebar. Under Token, click Reset Token and copy the value. Discord shows it once; if you lose it, you reset it again and the old one stops working.
  4. Installation. Covered in step 3 below, once you know which permissions to ask for.

The token is the bot’s password. Anyone who has it can log in as your bot, read what it can read and post where it can post. It never goes in your code, in a screenshot or in a public repository. Discord is a partner of GitHub secret scanning, so a token pushed to a public repository is reported to Discord. Treat it as leaked and reset it; the TokenInvalid guide covers what to do when a token stops working.

Step 2: leave the privileged intents off, unless you need one

Intents tell Discord which events your bot wants to receive. Most are free to use. Three are privileged, because they expose personal data, and you switch them on in the Bot page under Privileged Gateway Intents:

IntentWhat it gives youYou need it for
Presence IntentOnline status and activity of membersStatus trackers, “now playing” roles
Server Members IntentThe member list and join/leave eventsWelcome messages, member counters, auto-roles
Message Content IntentThe text of messages that do not mention the botPrefix commands like !help, keyword filters

A bot built on slash commands needs none of them: Discord sends the command and its options directly, whatever the message content settings. That is why the bot in this guide asks for the Guilds intent alone.

Two rules to know before you turn one on:

  • Asking in code without enabling it in the portal crashes the login. Discord closes the connection with code 4014. discord.js reports it as Used disallowed intents, discord.py as PrivilegedIntentsRequired. The disallowed intents guide covers both.
  • Past 10,000 users, Discord reviews your access. Discord’s documentation says an app with fewer than 10,000 users can enable these intents in the portal. Above that threshold, counted as unique users who can see the app across its servers, the owner must submit a request and reapply every year.

Step 3: invite the bot with the right scopes and permissions

Open Installation in the sidebar and set it up like this:

  1. Installation Contexts: keep Guild Install ticked. That is the context for a bot that lives in servers. User Install is for apps people add to their own account; you can leave it on or off.
  2. Install Link: choose Discord Provided Link.
  3. Default Install Settings, under Guild Install: add the applications.commands and bot scopes. Picking bot opens a Permissions list; tick Send Messages and nothing else.
  4. Copy the link from Install Link, open it in your browser, pick your test server and confirm with Add to server.
Anatomy of a Discord install link: client_id is the Application ID, scope bot adds the bot user, applications.commands enables slash commands, permissions=2048 is Send Messages alone, and a warning that permissions=8 means Administrator

You can also write the link by hand, which helps to see what it grants. The number is a bitfield; 2048 is Send Messages:

https://discord.com/oauth2/authorize?client_id=YOUR_APP_ID&scope=bot+applications.commands&permissions=2048

Never ask for Administrator (permissions=8) to save time. A bot with it can delete channels and ban members, and so can whoever steals its token. When a feature needs more, such as Manage Roles for auto-roles, add that one permission and send the server owners a new link.

Step 4: set up the project

Pick one column. The structure is the same in both languages: the code, the dependencies with exact versions, a .env file for the token and a .gitignore that keeps secrets and installed packages out of git.

JavaScript (discord.js)          Python (discord.py)
my-bot/                          my-bot/
├── .env            secret       ├── .env            secret
├── .env.example    committed    ├── .env.example    committed
├── .gitignore                   ├── .gitignore
├── index.js                     ├── main.py
├── package.json                 ├── requirements.txt
└── node_modules/   not committed└── .venv/          not committed

.env holds the real token and is never committed. .env.example is the same file with a placeholder, so the next person, or you on a new machine, knows which variables to set:

DISCORD_TOKEN=paste-your-bot-token-here

discord.js: package.json and .gitignore

{
  "name": "my-discord-bot",
  "version": "1.0.0",
  "private": true,
  "main": "index.js",
  "scripts": {
    "start": "node --env-file-if-exists=.env index.js"
  },
  "engines": {
    "node": ">=22.12"
  },
  "dependencies": {
    "discord.js": "14.28.1"
  }
}
node_modules/
.env

--env-file-if-exists is built into Node.js since version 22.9: it loads .env when the file is there and carries on without it otherwise, so you do not need the dotenv package. The exact version 14.28.1, without a caret, means every install gets the code you tested.

Install it with npm install.

discord.py: requirements.txt and .gitignore

discord.py==2.7.1
python-dotenv==1.2.4
.env
__pycache__/
.venv/

Create a virtual environment so the packages stay inside the project, then install:

python -m venv .venv
source .venv/bin/activate        # Windows: .venvScriptsactivate
pip install -r requirements.txt

On Python 3.13 and newer, pip also installs audioop-lts. Python 3.13 removed the audioop module, and discord.py 2.5 and later pull this replacement in automatically. Pin an older discord.py on a new Python and the import fails, as the discord.py hosting guide shows.

Step 5: write the bot

Same behavior, two languages. Read the one you will use; the table after them maps one onto the other.

discord.js v14: index.js

const { Client, Events, GatewayIntentBits, MessageFlags, SlashCommandBuilder } = require('discord.js');

// 1. The slash commands, described once.
const commands = [
  new SlashCommandBuilder()
    .setName('ping')
    .setDescription('Replies with the gateway latency'),
  new SlashCommandBuilder()
    .setName('roll')
    .setDescription('Rolls a die')
    .addIntegerOption((option) =>
      option
        .setName('sides')
        .setDescription('Number of sides (default 6)')
        .setMinValue(2)
        .setMaxValue(1000),
    ),
];

// 2. The client. Slash commands only need the Guilds intent.
const client = new Client({ intents: [GatewayIntentBits.Guilds] });

// 3. On startup, register the commands (bulk overwrite, global).
client.once(Events.ClientReady, async (readyClient) => {
  await readyClient.application.commands.set(commands.map((command) => command.toJSON()));
  console.log(`Online as ${readyClient.user.tag}, ${commands.length} commands registered`);
});

// 4. Answer the commands.
client.on(Events.InteractionCreate, async (interaction) => {
  if (!interaction.isChatInputCommand()) return;

  try {
    if (interaction.commandName === 'ping') {
      await interaction.reply(`Pong! Gateway latency: ${client.ws.ping} ms`);
    } else if (interaction.commandName === 'roll') {
      const sides = interaction.options.getInteger('sides') ?? 6;
      const result = Math.floor(Math.random() * sides) + 1;
      await interaction.reply(`You rolled ${result} (d${sides})`);
    }
  } catch (error) {
    console.error(`/${interaction.commandName} failed:`, error);
    const message = { content: 'Something went wrong.', flags: MessageFlags.Ephemeral };
    if (interaction.replied || interaction.deferred) {
      await interaction.followUp(message).catch(console.error);
    } else {
      await interaction.reply(message).catch(console.error);
    }
  }
});

// 5. Log errors instead of crashing on them.
client.on(Events.Error, (error) => console.error('Client error:', error));
process.on('unhandledRejection', (error) => console.error('Unhandled rejection:', error));

// 6. Connect. A bad or missing token stops the process with a clear message.
client.login(process.env.DISCORD_TOKEN).catch((error) => {
  console.error('Login failed:', error.message);
  process.exit(1);
});

Two details that trip up code copied from older tutorials:

  • Events.ClientReady is now the string clientReady. discord.js 14.28 still fires the old ready event, with a deprecation warning, and v15 will drop it. Using the constant keeps you on the right name.
  • Ephemeral replies use flags: MessageFlags.Ephemeral. The old ephemeral: true option is marked deprecated in the 14.28 typings.

discord.py 2.7: main.py

import logging
import os
import random

import discord
from discord import app_commands
from discord.ext import commands
from dotenv import load_dotenv

load_dotenv()  # reads .env when it exists, does nothing otherwise
log = logging.getLogger("bot")


class MyBot(commands.Bot):
    async def setup_hook(self) -> None:
        # Runs once, before the bot connects: register the slash commands (bulk overwrite, global).
        synced = await self.tree.sync()
        log.info("%d commands registered", len(synced))


# Slash commands only need the default intents, none of them privileged.
bot = MyBot(command_prefix=commands.when_mentioned, intents=discord.Intents.default())


@bot.event
async def on_ready() -> None:
    log.info("Online as %s", bot.user)


@bot.tree.command(description="Replies with the gateway latency")
async def ping(interaction: discord.Interaction) -> None:
    await interaction.response.send_message(f"Pong! Gateway latency: {round(bot.latency * 1000)} ms")


@bot.tree.command(description="Rolls a die")
@app_commands.describe(sides="Number of sides (default 6)")
async def roll(interaction: discord.Interaction, sides: app_commands.Range[int, 2, 1000] = 6) -> None:
    await interaction.response.send_message(f"You rolled {random.randint(1, sides)} (d{sides})")


@bot.tree.error
async def on_app_command_error(interaction: discord.Interaction, error: app_commands.AppCommandError) -> None:
    log.error("/%s failed", interaction.command.name if interaction.command else "?", exc_info=error)
    if interaction.response.is_done():
        await interaction.followup.send("Something went wrong.", ephemeral=True)
    else:
        await interaction.response.send_message("Something went wrong.", ephemeral=True)


bot.run(os.environ["DISCORD_TOKEN"], root_logger=True)

commands.when_mentioned is there because commands.Bot requires a prefix; this bot has no prefix commands, so a mention is the harmless choice. root_logger=True makes bot.run() send your own log.info() lines through the same formatted handler as the library’s, instead of only the discord logger.

The same bot, concept by concept

discord.js 14.28.1discord.py 2.7.1
Define a commandnew SlashCommandBuilder()@bot.tree.command() on a function
Integer option, 2 to 1000.addIntegerOption() with setMinValue(2) and setMaxValue(1000)sides: app_commands.Range[int, 2, 1000] = 6
Register the commandsapplication.commands.set() in clientReadytree.sync() in setup_hook
Replyinteraction.reply()interaction.response.send_message()
Private error messageflags: MessageFlags.Ephemeralephemeral=True
Catch command errorstry/catch in the handler@bot.tree.error
Read the tokenprocess.env.DISCORD_TOKEN, loaded by --env-file-if-existsos.environ["DISCORD_TOKEN"], loaded by load_dotenv()

Both payloads were checked on the test run: each library sends the same two commands, roll with an optional integer sides that has min_value 2 and max_value 1000.

How command registration works

Sequence diagram: the bot logs in and registers its commands with one bulk overwrite; a member types /roll sides:20; Discord refuses sides:1 before sending; Discord sends INTERACTION_CREATE over the gateway; the bot must reply within 3 seconds or the member sees The application did not respond

Both bots register their commands at every start with a bulk overwrite: they send the full list, and Discord replaces what it had. For a bot with a handful of commands, that is the simplest setup that never drifts out of sync with your code. Three facts from Discord’s documentation make it safe:

  • Only new commands count against the limit. Discord allows 200 command creations per day per server, and a bulk overwrite only counts the commands that did not already exist. Restarting with the same list costs nothing.
  • Global commands are registered for every server the bot is in. Discord documents guild commands as updating instantly and does not promise a delay for global ones. If a new command does not show up in your client after a restart, press Ctrl+R (Cmd+R on macOS) to reload Discord.
  • You have 3 seconds to answer. After that, the member sees “The application did not respond”. For slower work, acknowledge first with interaction.deferReply() in discord.js or interaction.response.defer() in discord.py, then send the result as a follow-up within 15 minutes.

Once the bot has dozens of commands, move each command into its own file (a commands/ folder in discord.js, a cog per feature in discord.py) and register them from a separate script you run when the list changes. The discord.js guide calls that script deploy-commands.js.

Step 6: run it and test it locally

Put your token in .env, then start the bot:

npm start            # discord.js
python main.py       # discord.py, with the virtual environment active

A healthy start prints the commands it registered, then Online as followed by the bot’s name. Then go through this list in your test server:

  1. Type /ping. The reply shows the gateway latency in milliseconds.
  2. Type /roll with no option: a result between 1 and 6.
  3. Type /roll sides:20: a result between 1 and 20.
  4. Try /roll sides:1. Discord refuses it in the client, because the option has a minimum of 2. Your code never sees it.
  5. Stop the bot with Ctrl+C and run /ping again: after 3 seconds, “The application did not respond”. That is what members see when the bot is offline.

If the start fails, the first line of the error tells you which of these it is:

What you seeWhat it meansFix
Login failed: An invalid token was provided. (discord.js)The token is empty, mistyped or was resetPaste a fresh token from Bot > Reset Token into .env
discord.errors.LoginFailure: Improper token has been passed. (discord.py)Same causeSame fix
KeyError: 'DISCORD_TOKEN' (discord.py)The variable is not set at allCheck that .env sits next to main.py and the line starts with DISCORD_TOKEN=
Used disallowed intents or PrivilegedIntentsRequiredThe code asks for a privileged intent the portal has offEnable it in Bot, or remove it from the code
The commands never appearThe bot was invited without applications.commands, or the client has not refreshedRe-invite with the link from step 3, then Ctrl+R

We triggered the first three on purpose during the test run, with a fake token and with no token, to make sure each message matches what you will read.

Put it online 24/7

Your bot now works, and it goes offline the moment you close the terminal. A Discord bot is one long-running process holding a WebSocket connection to Discord, so it needs a machine that stays on, restarts it when it crashes and keeps the token in an environment variable rather than a file.

Read how to host a Discord bot 24/7 for every option, from a spare computer to a VPS to a managed host, with what each one costs you in money and maintenance. Then follow the guide for your language, written for the exact files above:

On Bot-Hosting the short version is: upload the folder or connect the GitHub repository, add DISCORD_TOKEN in the Environment tab, and start. The Discord bot hosting page lists what the free plan includes.

FAQ

Can I make a bot that runs on my own account?

No. A bot that automates a normal user account is a “self-bot”, and Discord’s support article on them states that automating user accounts outside the OAuth2 and bot API “is forbidden, and can result in an account termination if found”. Use a bot account from the Developer Portal, as in this guide. Bot-Hosting does not host self-bots either.

Do I need to know how to code?

To follow this guide, a little: you copy the files, but you will want to read the errors. If you would rather describe the bot and let an AI write and test it, read how to make a Discord bot with AI. Learning enough to read the code above still pays off the first time something breaks.

How much does it cost to make a Discord bot?

Building it costs nothing. The Discord API is free to use, discord.js is open source under the Apache 2.0 license and discord.py under MIT. What can cost money is keeping it online. Your own computer is free but the bot is offline whenever the computer is. On Bot-Hosting, the free plan runs one bot with 256 MB of RAM, never puts it to sleep and asks for a renewal click every 4 days; the Starter plan is $2.29 a month for 1 GB of RAM and two deployments, renewed automatically.

JavaScript or Python: which one should I pick?

The one you already know. Both libraries cover slash commands, buttons, modals and voice, and both are actively maintained: discord.js 14.28.1 was published on npm in November 2026, discord.py 2.7.1 in March 2026. If you know neither, Python reads more easily, and JavaScript is the language you will meet again in web development.

Can my bot read the messages in a channel?

Only messages that mention it, direct messages and its own messages, unless you enable the Message Content Intent. For most features a slash command with options is the better design: members see what the bot can do, and you need no privileged intent.

Sources

Checked on 30 November 2026:

Library versions move fast. If a newer release changes one of these APIs, its changelog is the reference.