Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 37 ยท Bot Concepts and APIs

Discord Gateway and Intents

Learn how the Discord gateway works - the websocket handshake, opcodes, heartbeats, sequence numbers, resuming, and intents as bit flags - with a runnable simulated gateway client in Node.js.

The gateway is Discord's real-time channel. Your bot opens one websocket connection to wss://gateway.discord.gg/?v=10&encoding=json, introduces itself, and then Discord pushes JSON events down the line as they happen. Libraries implement the protocol for you, but knowing it explains many behaviours: why bots go offline for a moment, why you need to declare intents, and why a bot that is too big has to be sharded.

Simulated gateway. The sandbox cannot connect to Discord, and our runner has no websocket server module. The examples below therefore run a scripted fake gateway in memory: both sides exchange the same JSON payloads (op, d, s, t) that the real protocol uses, but over a plain function call instead of a websocket. The payload shapes, opcodes and intent numbers are the real ones.

The payload envelope

Every message in both directions has the same four fields:

Field Meaning
op Opcode: what kind of message this is
d The data (shape depends on the opcode)
s Sequence number, only on dispatches (op 0)
t Event name, only on dispatches, for example MESSAGE_CREATE

Opcodes you must know

Opcode Name Direction Purpose
0 Dispatch server to bot An event, with t and s
1 Heartbeat both Keep-alive; the bot sends its last s
2 Identify bot to server Authenticate: token, intents, properties
3 Presence Update bot to server Change the bot's status
6 Resume bot to server Continue a dropped session
7 Reconnect server to bot Please reconnect (and resume)
9 Invalid Session server to bot Session lost; d says whether you may resume
10 Hello server to bot Contains heartbeat_interval in milliseconds
11 Heartbeat ACK server to bot Server received your heartbeat

The connection lifecycle

Opening a session

Connect Open the websocket
Hello (10) heartbeat_interval
Identify (2) Token and intents
READY session_id and guilds

READY is the first dispatch

1 / 3

The heartbeat matters: if the bot does not send a heartbeat every heartbeat_interval milliseconds (about 41,250 in practice) or the server stops acknowledging, the connection is considered zombied and must be closed and resumed. Resuming keeps your session and replays events you missed, using the last sequence number you saw.

A gateway client you can run

Below, FakeGateway plays the server side (hello, ready, a few dispatches, and one forced reconnect) and GatewayClient is the bot side: a small state machine driven by opcodes.

Node.js Handshake, heartbeat, dispatch and resume

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 important behaviours are all there. The client stores the latest s from every dispatch, answers Hello by identifying the first time and resuming afterwards, and treats a missing ACK as a dead link. Real clients also reconnect with exponential backoff if the socket closes, and respond to close codes (for instance 4004 means your token is invalid, so you must stop rather than retry, and 4014 means you asked for a privileged intent you have not enabled).

Intents

An intent is a bit that tells Discord which event families to send. You pass the OR of the bits you want in the Identify payload. Fewer intents mean less traffic and fewer privacy problems.

Intent Bit Events it enables
GUILDS 0 Guild, channel, role and thread create, update, delete
GUILD_MEMBERS 1 Member join, update, leave. Privileged
GUILD_MODERATION 2 Bans, audit-log entries
GUILD_VOICE_STATES 7 Voice join and leave
GUILD_PRESENCES 8 Online status. Privileged
GUILD_MESSAGES 9 Message events in servers
GUILD_MESSAGE_REACTIONS 10 Reactions in servers
DIRECT_MESSAGES 12 Message events in DMs
MESSAGE_CONTENT 15 The text of messages. Privileged

Three are privileged (members, presences, message content). You must enable them in the Developer Portal, and bots in more than 100 servers need Discord's approval. Without the message content intent your bot still receives message events, but content, embeds, attachments and components are empty for messages that do not mention the bot or are not DMs. This is the reason slash commands are the recommended way to give commands.

Node.js Computing intent values

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.

Slash-command-only bots can use just Guilds (or even no gateway at all). Declare only what your features need, and if Discord closes your connection with code 4014, a privileged intent is missing from the Developer Portal.

Sharding in one paragraph

A single gateway connection can serve at most 2,500 servers. Beyond that you open several connections called shards; each passes shard: [id, total] in Identify, and Discord routes each guild to shard (guild_id >> 22) % total. Small bots never need to think about it, and libraries provide a sharding manager when you do.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does the bot send in response to an opcode 10 Hello the first time?

    A new session identifies. Resume (op 6) is used only when you already have a session_id and the last sequence number.
  2. 2. What is the sequence number s used for?

    You remember the last s from each dispatch, send it in heartbeats, and use it when resuming a session.
  3. 3. Without the MessageContent intent, what happens to message content?

    Message events still arrive, but content, embeds and attachments are blanked except for DMs, mentions and the bot's own messages.
  4. 4. Which intents are privileged?

    Members, presences and message content must be enabled in the Developer Portal, and larger bots need approval.

Summary

  • The gateway is a websocket carrying { op, d, s, t } payloads; dispatches (op 0) carry events.
  • Lifecycle: Hello (10) then Identify (2), READY, regular Heartbeats (1) answered by ACKs (11); Reconnect (7) and Resume (6) recover dropped sessions.
  • Remember the newest sequence number; no ACK means a dead connection.
  • Intents are bit flags that choose event families; members, presences and message content are privileged.
  • Slash-command bots need very few intents; large bots must shard.

Next: Parsing Commands