# Gateway

> How a bot stays connected to Klang’s gateway. The address, compression, intents, what arrives after connecting, resuming a session and the close codes, as Klang uses them.

## Connecting

Bots connect to their own gateway, separate from the one the Klang app uses:

```text
wss://bot-gateway.klang.gg/?v=10&encoding=json&compress=zlib-stream
```

`GET /api/v10/gateway` returns that address without a token, and `GET /api/v10/gateway/bot`
returns it with the session limits for your bot (one shard, and how many connections it can still
open today). Libraries that ask for it don’t need the address set by hand; the others do (see
[Connect your library](https://docs.klang.gg/bots/libraries/)).

The query string:

| Parameter  | Values                         | Notes                                                                              |
| ---------- | ------------------------------ | ---------------------------------------------------------------------------------- |
| `v`        | `10` or `9`                    | `9` behaves as `10`. Leaving it out means `10`; another number closes with `4012`. |
| `encoding` | `json`                         | ETF isn’t supported: it closes with `4002`.                                        |
| `compress` | `zlib-stream` or `zstd-stream` | Optional. Without it, frames go as plain JSON text.                                |

## Compression

Klang compresses the whole connection, never single messages:

- **`zlib-stream`**: one zlib context for the whole connection. Each message ends with the bytes
  `00 00 ff ff`, so you know when to decompress.
- **`zstd-stream`**: one Zstandard stream for the whole connection, flushed after each message.
- Compressed messages go as binary frames, in order.

If an `IDENTIFY` sets `"compress": true` (compression of single payloads, which discord.py always
sends), Klang ignores it and uses whatever the address asked for. The WebSocket extension
`permessage-deflate` isn’t offered.

## The first messages

Right after the connection opens, Klang sends **Hello** (op `10`) with a `heartbeat_interval` of
41,250 ms. Your library then sends **Identify** (op `2`) with:

- `token`: the bot token, without the `Bot ` prefix;
- `intents`: the events it wants (see [Intents](https://docs.klang.gg/bots/gateway/#intents));
- `properties`: anything that names your library and system;
- `large_threshold` (optional): from 50 to 250, 50 by default;
- `shard` (optional): only `[0, 1]`. Klang runs one shard per bot for now;
- `presence` (optional): see [Presence](https://docs.klang.gg/bots/gateway/#presence).

Klang checks the token, the app and the intents, and answers with **Ready**: the bot’s user, a
`session_id`, a `resume_gateway_url`, the app’s `id` and `flags`, the list of its servers, each
marked as unavailable, and `private_channels`, always empty: direct messages arrive as events.
Then comes one `GUILD_CREATE` for each server, with:

- the server, its roles, emojis and stickers;
- the channels and threads the bot can see (up to 500 active threads, the most recent first);
- its member count, when the bot joined it and whether it’s `large`;
- the members: all of them if the server has no more members than `large_threshold` and the
  bot has `GUILD_MEMBERS`; otherwise, only the bot itself;
- `presences`, `voice_states`, `stage_instances`, `guild_scheduled_events` and
  `soundboard_sounds`, always empty but present.

Channels the bot can’t see never arrive, not even with their name hidden.

### Heartbeats

Send a **Heartbeat** (op `1`) every `heartbeat_interval`; the first after a random fraction of it.
Klang answers each with op `11`. If one is 10 seconds late, Klang asks for it with an op `1` of its
own; 20 seconds late, it closes the connection with `4000`, and the session waits for a resume.

### Rules for the first frames

- Before identifying, only heartbeats, **Identify** and **Resume** are accepted; anything else
  closes with `4003`.
- Without an **Identify** or a **Resume** within 30 seconds, the connection closes with `4003`.
- A second **Identify** or **Resume** on the same connection closes it with `4005`.
- An opcode Klang doesn’t know closes with `4001`, and a frame that isn’t valid JSON with `4002`.
- Frames you send can be up to 16 KB.

## Intents

Every bit Discord’s API defines for version 10 is accepted. A bit that isn’t an intent closes the
connection with `4013`. The three privileged intents work like this on Klang:

- **`GUILD_MEMBERS`** (`1 << 1`) and **`MESSAGE_CONTENT`** (`1 << 15`): switch them on in the
  portal first, or the connection closes with `4014`. Past 100 servers, only the ones Klang’s team
  has reviewed stay on: the others are switched off at the 101st server
  ([Above 100 servers](https://docs.klang.gg/bots/getting-started/#above-100-servers)).
- **`GUILD_PRESENCES`** (`1 << 8`): not available yet. Asking for it closes with `4014`.

Without `MESSAGE_CONTENT`, the messages your bot gets from servers have `content`, `embeds`,
`attachments`, `components`, `poll` and `sticker_items` empty. Three kinds keep them: messages
that mention the bot, messages it sent, and its direct messages. The same rule applies to
messages read through the REST API.

Which event needs which intent is in the [compatibility table](https://docs.klang.gg/bots/compatibility/#gateway-events).

## Events

The gateway sends events in Discord’s shape and names, with `t`, `s` and `d`, and compatible IDs
(see [IDs](https://docs.klang.gg/bots/differences/#ids)). A few things to know:

- **Structure changes come as single events.** When channels, roles or the server change, or
  when the bot gains or loses access to something, Klang compares what the bot saw before and
  sends the `CHANNEL_*`, `THREAD_*`, `GUILD_ROLE_*` and `GUILD_UPDATE` events that describe the
  change, or `GUILD_DELETE` if it can no longer see the server. A channel’s `CHANNEL_CREATE`
  always arrives before the first message in it.
- **Emoji and sticker changes** arrive as a `GUILD_UPDATE` that carries the whole new lists.
- **Direct messages** arrive without `guild_id` or `member`, with `channel_type` `1`. Opening a
  DM doesn’t send a `CHANNEL_CREATE`.
- **Messages in threads** carry `channel_type` `11` and follow the permissions of the thread’s
  channel.
- **`referenced_message`** in a reply is filled when the gateway has the original among the
  messages it saw recently. If not, it’s `null`: fetch it with
  `GET /channels/{channel.id}/messages/{message.id}`.
- **Being added** to a server sends its `GUILD_CREATE` at once, and **being removed** sends
  `GUILD_DELETE` with `unavailable: false`.
- **A bot’s own member** changes (its roles, its nickname) arrive as `GUILD_MEMBER_UPDATE` even
  without `GUILD_MEMBERS`.
- **`INTERACTION_CREATE`**, when someone uses one of the bot’s commands, needs no intent and goes
  to one connection only, the newest. See [Responding to interactions](https://docs.klang.gg/bots/interactions/).

## Presence

**Presence Update** (op `3`) sets your bot’s status: `online`, `idle`, `dnd` or `invisible`
(`offline` counts as `invisible`). Activities (“Playing…”) are accepted and ignored for now. Up
to 5 updates every 20 seconds per session count, also across a resume; the rest are ignored.

**Voice State Update** (op `4`) and **Request Guild Members** (op `8`) are accepted and do nothing
for now: bots can’t join voice yet, and the member list comes from `GUILD_CREATE` or
`GET /guilds/{guild.id}/members`.

## Resuming

If the connection drops, reconnect to `resume_gateway_url` and send **Resume** (op `6`) with the
`token`, the `session_id` and the last `seq` you got. Klang sends everything you missed and then
`RESUMED`.

- **A session outlives its connection for about 3 minutes.** During that time it keeps
  collecting events: up to the last 2,000, and at most 5 MB between them. An event bigger than
  64 KB, such as a large `GUILD_CREATE`, isn’t kept: a resume from before it gets **Invalid
  Session**.
- **When a session can’t be resumed** (it expired, it belongs to another bot, the app resumed
  more than 20 times in the last minute, or the resume has no `session_id` at all), Klang
  answers **Invalid Session** (op `9`) with `false`. Identify again; on the same connection is
  fine.
- **Intents are checked again on resume.** If a privileged intent the session uses was switched
  off in the portal, or when the bot went past 100 servers without its review, the resume closes
  with `4014`. A connected session keeps its intents until then.
- **When Klang restarts** for an update, each bot gets **Reconnect** (op `7`) followed by a close
  with `4000`, and resumes on the new instance.
- **Resetting the token**, suspending or deleting the app closes every connection with `4004`,
  and those sessions can’t be resumed.

## Close codes

Klang uses the gateway’s close codes with these meanings. A library should reconnect after the
ones marked “yes”, and stop after the others: trying again won’t help.

| Code   | What happened                                                                                                                                  | Reconnect         |
| ------ | ---------------------------------------------------------------------------------------------------------------------------------------------- | ----------------- |
| `4000` | Unknown error, a missed heartbeat, or Klang restarting                                                                                         | Yes, and resume   |
| `4001` | An opcode Klang doesn’t know                                                                                                                   | Yes               |
| `4002` | A frame that can’t be decoded, ETF, or `zstd-stream` when it’s not available                                                                   | Yes               |
| `4003` | A frame before identifying, or no **Identify** within 30 seconds                                                                               | Yes               |
| `4004` | The token is wrong or was reset, the app is suspended or deleted, or bots are off                                                              | **No**            |
| `4005` | A second **Identify** or **Resume** on the same connection                                                                                     | Yes               |
| `4007` | **Resume** with a `seq` the session never sent                                                                                                 | Yes, and identify |
| `4008` | Too many frames, an **Identify** too soon or one too many today, or too many failed logins from this address ([Limits](https://docs.klang.gg/bots/limits/#gateway)) | Yes, later        |
| `4009` | A third connection of the same app opened, and this one was the oldest                                                                         | Yes, and identify |
| `4010` | A `shard` other than `[0, 1]`                                                                                                                  | **No**            |
| `4011` | Sharding required. Klang doesn’t send it for now                                                                                               | **No**            |
| `4012` | An API version other than 9 or 10                                                                                                              | **No**            |
| `4013` | A bit in `intents` that isn’t an intent                                                                                                        | **No**            |
| `4014` | A privileged intent not switched on in the portal (or switched off past 100 servers without review), or `GUILD_PRESENCES`                      | **No**            |

Klang sends no reason text with them. These are the bot gateway’s codes: the gateway the Klang
app uses has its own, and some of the same numbers mean something else there.
