Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 8 additions & 10 deletions docs/examples.md
Original file line number Diff line number Diff line change
@@ -1,47 +1,45 @@
# Examples

Each example is a complete program in the repository's `examples/` folder, typechecked with the
library on every change. Run one with your instance and token in the environment:
Complete programs from the repository's `examples/` folder. Run one with:

```sh
STRAFE_INSTANCE=app.strafe.chat STRAFE_TOKEN=your-token node examples/ping-pong.ts
```

Node.js 22.18 and newer run TypeScript files directly; on older versions use `npx tsx`.
On Node.js older than 22.18, use `npx tsx`.

## Ping pong

The smallest useful bot. See [Your first bot](./guide/first-bot.md) for a walk-through.
The smallest bot. Walk-through in [Your first bot](./guide/first-bot.md).

<<< @/../examples/ping-pong.ts

## Embeds and files

An embed about the space, a generated file, and an uploaded image shown inside an embed with
`attachment://`.
An embed, a generated file, and an uploaded image inside an embed via `attachment://`.

<<< @/../examples/embeds.ts

## Moderation

Kick, ban, unban and purge commands with permission and hierarchy checks.
Kick, ban, unban and purge, with permission checks.

<<< @/../examples/moderation.ts

## Reaction roles

A role menu: reacting gives a role, removing the reaction takes it away.
React to get a role, unreact to lose it.

<<< @/../examples/reaction-roles.ts

## OAuth2 login

"Log in with Strafe" for a website, with PKCE and a `state` cookie, using only `node:http`.
"Log in with Strafe" for a website, with PKCE, on `node:http`.

<<< @/../examples/oauth2-login.ts

## REST only

Post a message from a script without connecting to the gateway.
Post from a script without the gateway.

<<< @/../examples/rest-only.ts
57 changes: 21 additions & 36 deletions docs/guide/coming-from-discord-js.md
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
# Coming from discord.js

strafe.js is modelled on discord.js v14: the same `Client`, `Events`, `Collection`, managers with
`cache` and `fetch()`, `EmbedBuilder`, `PermissionsBitField`, and the same method names on
messages, members and roles. What changes is the vocabulary, a handful of options that Strafe does
not need, and a few things Strafe cannot do.
strafe.js is modelled on discord.js v14: the same `Client`, `Events`, `Collection`, managers,
builders and method names. The vocabulary changes, and a few options go away.

## The words

Expand Down Expand Up @@ -38,14 +36,14 @@ not need, and a few things Strafe cannot do.
| `message.guild`, `message.guildId`, `message.inGuild()` | `message.space`, `message.spaceId`, `message.inSpace()` | |
| `message.channel`, `message.channelId` | `message.room`, `message.roomId` | |
| `user.createDM()`, `user.dmChannel` | `user.createPM()`, `user.pmRoom` | A bot cannot post in a PM |
| `user.tag` | `user.tag` | The handle: `name`, or `name@domain` for other instances. No discriminators |
| `user.tag` | `user.tag` | `name`, or `name@domain` for other instances |
| `channelMention()` | `roomMention()` | `<#id>` |
| `client.generateInvite({ guild, disableGuildSelect })` | `client.generateInvite({ space, disableSpaceSelect })` | |
| `client.application.id` | `client.application.id` | The bot's user id: Strafe uses one id for the bot and its application. `client.application` has no other fields (no `fetch()`, owner or commands) |
| `guild.memberCount` | none | Spaces carry no member count. `await space.members.fetch()`, then `space.members.cache.size`; an invite preview has `invite.memberCount` |
| `channel.awaitMessages()`, `createMessageCollector()`, `message.awaitReactions()`, `createReactionCollector()` | the same, on rooms and messages | Same options and end reasons, plus `roomDelete`, `threadDelete` and `spaceDelete`; see [Waiting for replies and reactions](./messages.md#waiting-for-replies-and-reactions) |
| `client.application.id` | `client.application.id` | The bot's user id. No other fields |
| `guild.memberCount` | none | Use `space.members.cache.size` after `space.members.fetch()` |
| `channel.awaitMessages()`, `createMessageCollector()`, `message.awaitReactions()`, `createReactionCollector()` | the same | Extra end reasons `roomDelete`, `threadDelete`, `spaceDelete` ([Collectors](./messages.md#waiting-for-replies-and-reactions)) |
| `OAuth2Scopes.Guilds`, `GuildsJoin` | `OAuth2Scopes.Spaces`, `SpacesJoin` | |
| `DiscordAPIError`, `DiscordjsError`, `RESTJSONErrorCodes` | `StrafeAPIError`, `StrafeError`, `APIErrorCodes` | Strafe's codes are string slugs, and most errors have none |
| `DiscordAPIError`, `DiscordjsError`, `RESTJSONErrorCodes` | `StrafeAPIError`, `StrafeError`, `APIErrorCodes` | Codes are string slugs; most errors have none |
| `SnowflakeUtil` | `SnowflakeUtil` | Strafe's epoch is 1288834974657 |

## Events
Expand All @@ -63,14 +61,14 @@ not need, and a few things Strafe cannot do.
| `Events.Invalidated` | `Events.Invalidated` (the session was revoked) |
| `Events.GuildBanAdd`, `GuildBanRemove`, `InviteCreate`, `InteractionCreate`, `WebhooksUpdate`... | none |

These keep their names and arguments: `MessageCreate`, `MessageUpdate`, `MessageDelete`,
Unchanged: `MessageCreate`, `MessageUpdate`, `MessageDelete`,
`MessageReactionAdd`, `MessageReactionRemove`, `TypingStart`, `ThreadCreate`, `ThreadUpdate`,
`ThreadDelete`, `ThreadMembersUpdate`, `PresenceUpdate`, `UserUpdate`, `VoiceStateUpdate`, `Raw`,
`Debug`, `Warn`, `Error`.

## Permissions

Strafe's bits have their own values: always use `PermissionFlagsBits`, never numbers from Discord.
The bit values differ from Discord's. Always use `PermissionFlagsBits`.

| discord.js `PermissionFlagsBits` | strafe.js |
| --- | --- |
Expand All @@ -83,11 +81,11 @@ Strafe's bits have their own values: always use `PermissionFlagsBits`, never num
| `SendMessagesInThreads`, `ManageThreads`, `CreatePublicThreads`, `CreatePrivateThreads` | the same |
| `ViewAuditLog`, `ManageWebhooks`, `ModerateMembers`, `UseApplicationCommands`, `SendTTSMessages`, `ManageEvents` | none |

The rest (`SendMessages`, `ReadMessageHistory`, `AddReactions`, `UseExternalEmojis`,
Unchanged: `SendMessages`, `ReadMessageHistory`, `AddReactions`, `UseExternalEmojis`,
`MentionEveryone`, `ManageMessages`, `ManageRoles`, `KickMembers`, `BanMembers`, `Administrator`,
`Connect`, `Speak`, `MuteMembers`, `DeafenMembers`, `MoveMembers`, `UseVAD`, `PrioritySpeaker`,
`AttachFiles`, `ChangeNickname`, `ManageNicknames`, `EmbedLinks`) keep their names. The role
hierarchy rules are Discord's. See [Permissions](./permissions.md).
`AttachFiles`, `ChangeNickname`, `ManageNicknames`, `EmbedLinks`. Role hierarchy follows Discord's
([Permissions](./permissions.md)).

## Options you can drop

Expand All @@ -102,23 +100,15 @@ const client = new Client({
const client = new Client({ instance: 'app.strafe.chat' });
```

- **Intents**: none. A bot receives every event about what it can see, message text included
(unless the room is end-to-end encrypted).
- **Partials**: always on. Events about uncached messages, reactions and members arrive with
partial objects.
- **Sharding**: none. One connection carries everything.
- **`allowedMentions`**: does not exist; Strafe cannot send a mention that does not notify. Use
`escapeMentions()`.

Passing `intents`, `partials`, `shards` or `allowedMentions` anyway emits a warning explaining why.
Intents, partials and sharding are not needed: a bot gets every event it can see, uncached objects
arrive as partials, and one connection carries everything. `allowedMentions` does not exist; use
`escapeMentions()`. Passing any of these emits a warning.

## What does not exist

Slash commands and other interactions (buttons, select menus, modals, context menus), webhooks,
stickers, polls, scheduled events, stage and forum channels, crossposting, and joining voice calls
are not part of Strafe. Bots use message commands and reactions. [Limits and differences](./limits.md)
lists every gap, including PMs (a bot cannot send one: they are always end-to-end encrypted) and
user lookups (`client.users.fetch()` only works for the bot itself).
No interactions (slash commands, buttons, menus, modals), webhooks, stickers, polls, scheduled
events, stage or forum rooms, crossposting or voice joining. A bot cannot send a PM, and
`client.users.fetch()` only finds the bot itself. See [Limits and differences](./limits.md).

## A bot, ported

Expand Down Expand Up @@ -169,14 +159,9 @@ client.on(Events.MessageCreate, async (message) => {
await client.login(process.env.STRAFE_TOKEN);
```

The differences: an instance instead of intents, `content === null` for encrypted rooms, a room
that might be encrypted (`isSendable()`), and members fetched rather than assumed cached, because
member lists are not part of `READY`.
Members are fetched, not assumed cached, because member lists are not in `READY`.

## Upgrading from strafe.js 1.x

strafe.js 1.x targeted Strafe's retired pre-2026 backend (msgpack over the old gateway). Nothing in
2.0 is compatible with it: the endpoints, events and payloads all changed. Start from
[Getting started](./getting-started.md). The few names that survive (`client.on('messageCreate')`,
`room.send()`) behave as described in this guide, and the old `config` object is replaced by the
`instance` option.
strafe.js 1.x targeted Strafe's retired backend, and 2.0 is not compatible with it. Start from
[Getting started](./getting-started.md). The old `config` object is now the `instance` option.
88 changes: 38 additions & 50 deletions docs/guide/errors.md
Original file line number Diff line number Diff line change
@@ -1,18 +1,17 @@
# REST, errors and rate limits

Every request goes through `client.rest`, a `REST` client that queues requests, waits out rate
limits, retries what is safe to retry, and turns error responses into typed errors. It also works
on its own, without a gateway connection.
Every request goes through `client.rest`. It queues requests, waits out rate limits, retries what is
safe to retry and throws typed errors. It also works without a gateway connection.

## Errors

| Class | Thrown when | Useful fields |
| --- | --- | --- |
| `StrafeError`, `StrafeTypeError`, `StrafeRangeError` | The library refuses something itself, before any request | `code` (an `ErrorCodes` value), `path` |
| `StrafeError`, `StrafeTypeError`, `StrafeRangeError` | The library refuses something before any request | `code` (an `ErrorCodes` value), `path` |
| `StrafeAPIError` | The server answered with an error | `status`, `code`, `path`, `message`, `rawError`, `method`, `url`, `requestBody` |
| `HTTPError` | The server answered with an error that is not JSON (a proxy's error page) | `status`, `statusText`, `body` |
| `RateLimitError` | A rate limit you asked not to wait for (see below) | `retryAfter`, `route`, `scope` |
| `BulkDeleteError` | Some deletions of `bulkDelete()` failed | `deleted`, `failed` |
| `HTTPError` | The server answered with a non-JSON error | `status`, `statusText`, `body` |
| `RateLimitError` | A rate limit you chose not to wait for | `retryAfter`, `route`, `scope` |
| `BulkDeleteError` | Some deletions in `bulkDelete()` failed | `deleted`, `failed` |

```ts
import { ErrorCodes, StrafeAPIError, StrafeError } from '@strafechat/strafe.js';
Expand All @@ -21,7 +20,7 @@ try {
await room.send({ embeds: [embed] });
} catch (error) {
if (error instanceof StrafeError && error.code === ErrorCodes.RoomEncrypted) {
// the room is end-to-end encrypted: nothing was sent
// nothing was sent
} else if (error instanceof StrafeAPIError && error.status === 403) {
console.warn(`Missing a permission: ${error.message}`);
} else {
Expand All @@ -30,18 +29,15 @@ try {
}
```

`StrafeTypeError` and `StrafeRangeError` extend `TypeError` and `RangeError`, not `StrafeError`;
all three carry `code`.
`StrafeTypeError` and `StrafeRangeError` extend `TypeError` and `RangeError`, not `StrafeError`.
All three carry `code`.

### Ids from user input

Commands often pass what someone typed straight on: `space.members.kick(args[0])`. Every id that
goes into a request path is checked first: it must be a decimal snowflake, or `@me`. Anything else
(`../rooms/123`, a name, an empty string) rejects with a `StrafeTypeError` whose code is
`ErrorCodes.IdInvalid`, and no request is made, so typed input can never reach another endpoint
with the bot's permissions. A reaction emoji or an invite code of `.` or `..` is refused the same
way (`EmojiInvalid`, `InviteInvalid`), and `rest.get()` and friends refuse a path with a `.` or `..`
segment or a backslash (`RouteInvalid`).
Every id in a request path must be a decimal snowflake or `@me`. Anything else rejects with
`ErrorCodes.IdInvalid` and no request is made. Emoji and invite codes of `.` or `..` are refused
too (`EmojiInvalid`, `InviteInvalid`), as are `rest.get()` paths with `.`, `..` or a backslash
(`RouteInvalid`).

```ts
try {
Expand All @@ -54,10 +50,9 @@ try {

### What the server says

Strafe's errors are `{ "error": "message" }` with an HTTP status: `400` bad input, `401` bad
credentials, `403` not allowed, `404` not found, `409` conflict, `413` too large, `429` too many
requests. `error.message` is the server's message. Some errors add a machine-readable slug, in
`error.code` and listed in `APIErrorCodes`:
Server errors are `{ "error": "message" }` with a status: `400` bad input, `401` bad credentials,
`403` not allowed, `404` not found, `409` conflict, `413` too large, `429` too many requests. Some
add a slug in `error.code`:

| `APIErrorCodes` | `code` | Meaning |
| --- | --- | --- |
Expand All @@ -69,23 +64,20 @@ requests. `error.message` is the server's message. Some errors add a machine-rea
| `InsufficientScope` | `insufficient_scope` | An OAuth2 token reached a route its scopes do not allow |
| `InvalidGrant`, `InvalidClient`, `InvalidScope`, `InvalidRequest`... | RFC 6749 codes | OAuth2 token endpoint errors |

Most `403`s and `404`s carry no slug, so check `status` (and the message when it matters). The
library refuses most mistakes before the request, with a `StrafeError` whose `code` names the rule.
Most `403`s and `404`s have no slug, so check `status`.

## Rate limits

Strafe limits requests per account and per route. The REST client reads the `X-RateLimit-*`
headers and waits before it would exceed a limit; when a `429` arrives anyway it waits for
`Retry-After` and sends the request again. You do not need to handle `429`s.
The REST client reads the `X-RateLimit-*` headers and waits before hitting a limit. On a `429` it
waits for `Retry-After` and retries. You do not need to handle `429`s.

- Requests to the same route and room (or space) run one at a time, in order. Messages sent to a
room arrive in the order you sent them; other rooms are not held up.
- **Slowmode** answers `429` too. It holds only that room's queue, and is reported with
`scope: 'shared'`. Members with Manage Messages or Manage Rooms are exempt.
- A wait longer than `maxRetryAfter` (60 seconds by default), such as a long slowmode, rejects with
`RateLimitError` instead of stalling every later message to that room.
- `rejectOnRateLimit` rejects instead of waiting: `true`, a list of route prefixes
(`['/rooms']`), or a function of the limit.
- Requests to the same route and room (or space) run in order, one at a time. Other rooms are not
held up.
- Slowmode also answers `429`, with `scope: 'shared'`, and holds only that room's queue. Members
with Manage Messages or Manage Rooms are exempt.
- A wait longer than `maxRetryAfter` (60 seconds) rejects with `RateLimitError`.
- `rejectOnRateLimit` rejects instead of waiting: `true`, route prefixes (`['/rooms']`), or a
function.

```ts
import { RESTEvents } from '@strafechat/strafe.js';
Expand All @@ -101,13 +93,12 @@ client.rest.on(RESTEvents.RateLimited, (info) => {
| --- | --- | --- |
| `429` | Waited out and retried (not counted) | Waited out and retried (not counted) |
| Network error before anything was sent | Retried | Retried |
| Timeout, connection reset, `5xx` | Retried, up to `retries` (3) times with backoff | Retried on `503` only |
| Timeout, connection reset, `5xx` | Retried up to `retries` (3) times with backoff | Retried on `503` only |

Strafe has no idempotency key, so retrying a `POST` that may have reached the server could post a
message twice; the library does not take that risk (discord.js does).
Strafe has no idempotency key, so a `POST` is not retried when it may have reached the server.

Requests time out after 15 seconds (`rest.timeout`), uploads after at least 120 seconds. Each
request also takes an `AbortSignal`.
Requests time out after 15 seconds (`rest.timeout`), uploads after at least 120. Each request also
takes an `AbortSignal`.

```ts
const client = new Client({
Expand All @@ -125,23 +116,20 @@ client.rest.on(RESTEvents.Response, (request, response) => {
});
```

Errors keep what was sent (`error.requestBody`), and so does the `response` event
(`request.data`). In both, OAuth2 secrets and the access token of `space.members.add()` show as
`[redacted]`; a raw `rest.request()` can do the same for its own fields with `redact: ['field']`.
The token is never logged or serialized: neither `client` nor `client.rest` shows it when
inspected or turned into JSON.
Errors keep the request body in `error.requestBody`, and the `response` event in `request.data`.
OAuth2 secrets and the access token of `space.members.add()` show as `[redacted]`. Redact your own
fields in `rest.request()` with `redact: ['field']`. The bot token never appears when `client` or
`client.rest` is inspected or serialized.

## REST without a gateway

Scripts, cron jobs and serverless functions often only need to send something. `REST` with
`Routes` does that without connecting to the gateway or caching anything:
For scripts and serverless functions, use `REST` with `Routes`. Nothing connects or caches:

<<< @/../examples/rest-only.ts

`Routes` holds every route a bot can use (`Routes.roomMessages(roomId)`,
`Routes.spaceMember(spaceId, userId)`...), and the wire types (`APIMessage`, `APISpace`,
`RESTPostAPIRoomMessageJSONBody`...) describe the JSON. The wire format is the server's own: the
message text is `plaintext`, ids are strings, permissions are numbers.
`Routes` has every route a bot can use, and the wire types (`APIMessage`, `APISpace`,
`RESTPostAPIRoomMessageJSONBody`...) describe the JSON. Message text is `plaintext`, ids are
strings, permissions are numbers.

```ts
import { REST, Routes, type APIMember } from '@strafechat/strafe.js';
Expand Down
Loading
Loading