Skip to content
Tutorials Center
My learning

Topics

Lesson 5 of 37 ยท Getting Started

Your First Discord Bot

Build your first Discord bot concept step by step - authenticate with the Bot header, call the REST API to read the bot user and send a message, and see how the gateway delivers events to a client.

A Discord bot talks to Discord in two ways. It calls the REST API to do things (send a message, create a channel, ban a member), and it listens to the gateway, a long-lived websocket connection on which Discord pushes events (a message was created, a member joined). Libraries such as discord.js hide both behind a friendly client object. In this lesson you learn what that object does underneath, then see the real library code you will use in production.

Stand-in. Discord's servers and a real token are not available in the sandbox. The examples below run a fake REST server on 127.0.0.1 that follows Discord's real URL layout (/api/v10/...), authorisation header and JSON shapes, and they imitate the gateway with a plain Node EventEmitter. The discord.js listing at the end is real library code, shown read-only because it needs npm and a real token.

Authenticating REST calls

Discord expects an Authorization header with the word Bot, a space and your token. A descriptive User-Agent is also required by the documentation, in the form DiscordBot (url, version). Without the right header you get 401 Unauthorized.

The base URL is https://discord.com/api/v10 (the number is the API version; pin it so your bot does not break when a new version arrives). Two calls give you a quick tour:

  • GET /users/@me returns the bot's own user (id, username).
  • POST /channels/{channel.id}/messages with {"content": "hello"} sends a message and returns the created message object.
Node.js REST: users/@me and sending a message

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Two details to notice. IDs are strings, not numbers: Discord ids (snowflakes) are 64-bit integers that exceed JavaScript's safe integer range, so the JSON carries them as strings, and you must keep them as strings (or BigInt). Errors carry a numeric code such as 50006 in addition to the HTTP status, which is more specific than the status alone. Discord REST API and Snowflakes goes deeper.

The gateway in one picture

REST alone cannot tell you when someone writes a message. For that you open the gateway:

Gateway handshake

  1. Connect
Open the websocket
  1. Hello
Server sends heartbeat time
  1. Identify
Token plus intents
  1. Ready
Events start flowing

Libraries do all four steps for you

1 / 2

Your bot declares intents when it identifies: families of events it wants. If you do not ask for message events, Discord will not send them. We cover this in Discord Gateway and Intents.

A client with events

discord.js exposes this as client.once('ready', ...) and client.on('messageCreate', ...). The next example builds the same shape on top of an EventEmitter, so you see how a bot reacts to a stream of dispatches and answers through REST. The "gateway" here is simulated: events are emitted by hand.

Node.js A client that reacts to events (simulated gateway)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The guard if (message.author.bot) return; is the first line of nearly every message handler. Without it, two bots can answer each other forever, or a bot can answer its own replies.

The real thing with discord.js

This is how the same bot looks with the official-style library. It is read-only: it needs npm install discord.js and a token.

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

const client = new Client({
  intents: [
    GatewayIntentBits.Guilds,
    GatewayIntentBits.GuildMessages,
    GatewayIntentBits.MessageContent, // privileged: enable in the Developer Portal
  ],
});

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

client.on(Events.MessageCreate, async (message) => {
  if (message.author.bot) return;
  if (message.content === '!ping') {
    await message.reply('Pong!');
  }
});

client.login(process.env.DISCORD_TOKEN);

client.login opens the gateway, identifies with your intents and starts the heartbeat. message.reply performs the REST call you saw above. Everything else in this course applies whichever library you pick.

For new bots prefer slash commands over !ping style commands. They need no message content intent and give users autocomplete. See Discord Slash Commands.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which header authenticates a Discord bot's REST calls?

    Discord expects the word Bot followed by a space and the token in the Authorization header.
  2. 2. Why are Discord ids strings in JSON?

    Snowflake ids need up to 64 bits. JavaScript numbers lose precision above 2^53, so ids stay strings or BigInt.
  3. 3. What is the gateway used for?

    The gateway is a websocket that pushes events to the bot; REST is used to act.
  4. 4. Why does a message handler start with message.author.bot check?

    Ignoring bot authors prevents two bots (or the bot and its own replies) from triggering each other forever.

Summary

  • Discord bots use REST (https://discord.com/api/v10) to act and the gateway websocket to listen.
  • Authenticate with Authorization: Bot <token> and send a descriptive User-Agent.
  • Ids are strings. Error bodies include a numeric code beside the HTTP status.
  • Declare only the intents you need; message content is privileged.
  • Ignore messages from bots, and prefer slash commands for new commands.

Next: HTTP and JSON for Bot APIs