What is a Discord bot and how does it work?

A Discord bot is a program that uses a bot account to receive events from servers and respond through the Discord API. It needs a process running on some computer to work.

Updated 6 min read

Learning objectives

After reading this article you will be able to:

  • Understand what a Discord bot is and what it can do
  • Learn how the Gateway, the REST API, intents and slash commands connect
  • Know the platform limits and what a bot needs to stay online
On this page

Almost every large Discord server has at least one bot: one hands out roles, another plays music, another removes spam or answers questions. To users they look like regular members with a tag next to their name. Behind them are programs that someone wrote and keeps running.

Knowing how that program talks to Discord helps you build your own, choose where to host it and figure out why a bot disappears or stops responding. The rules quoted here come from Discord's official developer documentation, where you can check the current values.

DiscordChannel/pingGatewayWebSocketAPI RESTHTTPBotyour code,always on12event3reply4
Discord doesn't run your code: it delivers events through the Gateway and takes replies through the REST API.

What is a Discord bot?#

A Discord bot is a program tied to a bot account. You create an application in the Discord Developer Portal, the portal generates a bot user and a token, and your code uses that token to authenticate. From then on, the program receives events (someone joined, someone sent a message, someone used a command) and acts through the API (sends a message, gives a role, creates a channel).

The part that confuses beginners: Discord does not run your code. It only delivers events and accepts instructions. The code lives on your computer, on a server or on a hosting platform, and the bot only shows as online while that process is running and connected.

The token works like a password. Whoever has it controls the bot, so keep it out of your code and out of Git. See how to get and protect your bot token.

How does a Discord bot work under the hood?#

Two channels work together:

  1. The Gateway (incoming). A persistent WebSocket connection between the bot and Discord. Real-time events arrive through it. On connect, Discord sends a Hello message with the heartbeat interval, and the bot must send a heartbeat at that pace. If the heartbeats stop arriving, the connection drops and the bot has to resume the session.
  2. The REST API (outgoing). To do something, the bot calls HTTP endpoints: send a message, reply to a command, edit a role. Each call carries the token in the Authorization header.

A full round trip looks like this: the user types /ping; Discord sends an interaction event through the Gateway; the bot handles it and calls the API to reply; the reply appears in the channel. On a good network, the whole round trip takes a few hundred milliseconds.

Because the Gateway is a WebSocket, the bot process has to stay on all the time. That is why a bot goes offline when you turn off your computer: the connection closes with the program.

What are intents and why do they matter?#

Intents are filters the bot declares when it connects to the Gateway. Each intent turns on a group of events: servers, members, messages, reactions, voice states. Without the intent, the bot does not get those events, even if it has permission in the server.

Three intents are privileged: GUILD_MEMBERS (member list), GUILD_PRESENCES (status and activity) and MESSAGE_CONTENT (message text). You have to turn them on in the portal before your code requests them. If the code requests a privileged intent that is not enabled, the Gateway closes the connection with code 4014. Apps with fewer than 10,000 users can turn these intents on directly in the portal; above that, Discord requires a review.

In practice, this is why so many bots moved from prefix commands (!help) to slash commands: the command arrives as an interaction, with no need to read the text of every message.

What does the code of a simple bot look like?#

With discord.js v14 (which needs a recent Node.js version), a bot that answers /ping fits in a few lines:

js
import { Client, Events, GatewayIntentBits } from "discord.js";

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

client.once(Events.ClientReady, async (c) => {
  // Registers the /ping command. In production, register with a separate script.
  await c.application.commands.set([
    { name: "ping", description: "Replies with pong" },
  ]);
  console.log(`Online as ${c.user.tag}`);
});

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

client.login(process.env.DISCORD_TOKEN);

client.login opens the Gateway; InteractionCreate is the event that arrives through it; interaction.reply is a REST API call. The token comes from an environment variable. In Python, the equivalent library is discord.py 2.x. The full walkthrough, from the portal to the invite link, is in how to make a Discord bot.

Can a Discord bot work without the Gateway?#

Yes, for one specific case. Discord can deliver interactions (slash commands, buttons, menus) in two ways, and they are mutually exclusive: through the Gateway or over HTTP, to an Interactions Endpoint URL you set in the portal. In HTTP mode, each command arrives as a POST request to your server, and there is no WebSocket to keep open.

In either mode, the initial response to an interaction must go out within 3 seconds, and the interaction token stays valid for 15 minutes for follow-up responses. If the work takes longer, the bot replies with a "thinking" state (deferred) and edits the message later.

HTTP mode suits bots that only answer commands. Anything that reacts to messages, member joins or voice still depends on the Gateway.

What are Discord bots used for?#

The most common uses:

  • Moderation: deleting spam, applying timeouts, logging actions to a channel.
  • Utilities: reaction roles, welcome messages, reminders, polls, support tickets.
  • Music and audio: playing tracks in voice channels, often with a separate audio server such as Lavalink.
  • Integrations: announcing deploys, streams, sales or alerts from other systems.
  • Games and economy: virtual currency, leaderboards, mini games.
  • AI: answering questions with a language model.

If all you need is to post automatic announcements in a channel, you may not need a bot at all: a channel webhook can post messages without a bot account or an open connection. See the difference in Discord webhook or bot.

What limits does a bot have to respect?#

  • API rate limit: up to 50 requests per second per bot, plus a limit on each route. Going over returns a 429 error. Details in Discord 429 errors.
  • Gateway connections: at most 1,000 identifies (IDENTIFY) every 24 hours. A bot stuck in a restart loop can hit that limit, and Discord then ends its sessions and resets the token.
  • Sharding: each connection (shard) handles at most 2,500 servers. Past that, the bot has to split the load across several shards.
  • Verification: bots in 100 or more servers must be verified by Discord.

What does a bot need to stay online 24/7?#

It needs a process that never stops, a stable internet connection and an automatic restart if the program crashes. On your own computer that lasts until you shut the machine down. For a real bot, the options are a VPS that you set up yourself, or an application hosting platform that already provides an always-on process. The comparison is in how to keep a Discord bot online 24/7, and price estimates are in how much it costs to host a Discord bot.

How to do this on Square Cloud#

On Square Cloud, your bot runs in an isolated container that is always on, with no sleep mode and automatic restart (on by default for dashboard deploys) when the process exits with an error. The Gateway connection stays open even when your own computer is off, and the average latency to the Discord Gateway is around 30 ms. You can use discord.js, discord.py, JDA, Discord.Net or another Gateway library, with sharding and voice, and FFmpeg is already in the container.

You deploy with a ZIP in the dashboard, the CLI, GitHub or the VS Code extension. The token lives in an environment variable of the application, not in your code. The squarecloud.app file is optional: the dashboard generates the runtime, memory and main file on deploy, and writing it at the project root is the alternative.

Every plan is paid. Hobby starts at R$12.49 per month with 1 GB of RAM, and the plan's RAM is shared across your applications, with a minimum of 256 MB per bot. See the details on Discord bot hosting.

Bot hosting

Keep your bot online 24/7 with automatic restarts

Learn more

FAQs

Is a Discord bot the same as a webhook?

No. A webhook only posts messages to a channel and receives nothing. A bot has its own account, receives events and responds to user commands.

Does the bot go online by itself after I create it in the portal?

No. Creating the app in the Developer Portal only generates the account and the token. The bot shows as online only while your program is running and connected to the Gateway.

Do I need to code to have a bot?

For your own bot, yes. You write the code with a library such as discord.js (JavaScript) or discord.py (Python). Without coding, the alternative is adding a ready-made bot built by someone else to your server.

Can a Discord bot read every message?

Only if the privileged Message Content intent is enabled in the portal and requested in code. Without it, the bot gets the message event but the text is empty, except for mentions and direct messages to the bot.

Next articleWhat is Discord sharding and when does your bot need it?Sharding splits your bot's Discord connection into several sessions, each handling part of the servers. It is required from 2,500 servers. Learn how it works.