From 604248c28cb2827ec3fd75b0538518f6480b367f Mon Sep 17 00:00:00 2001 From: BrydenIsNotSmart Date: Tue, 10 Nov 2026 22:11:53 -0600 Subject: [PATCH 1/2] docs: drop the badge above the home page headline Co-Authored-By: Claude Opus 5.5 --- docs/index.md | 1 - 1 file changed, 1 deletion(-) diff --git a/docs/index.md b/docs/index.md index b1df72d..9f1a6a3 100644 --- a/docs/index.md +++ b/docs/index.md @@ -4,7 +4,6 @@ markdownStyles: false # Rendered by docs/.vitepress/theme/StrafeHome.vue. `{word}` in the headline is drawn in green. strafe: - badge: The official TypeScript library headline: Build on {Strafe} with TypeScript lede: strafe.js talks to any Strafe instance's gateway, REST API and OAuth2. Spaces, rooms, members and messages arrive as typed events, requests wait out rate limits on their own, and "Log in with Strafe" takes a few lines. actions: From 433173f0d3619e759476bfd7e194a6da72012f34 Mon Sep 17 00:00:00 2001 From: BrydenIsNotSmart Date: Tue, 10 Nov 2026 22:11:53 -0600 Subject: [PATCH 2/2] docs: shorter, plainer guide The guide read like a wall of caveats. Each page now says what to do and shows the code: reasoning asides, repeated warnings, meta-talk, bold lead-ins and tables that restated the prose are gone (about 12,200 words down to 8,500, most of what remains being code and reference tables). Every code example, reference table and linked heading is kept. Co-Authored-By: Claude Opus 5.5 --- docs/examples.md | 18 ++- docs/guide/coming-from-discord-js.md | 57 ++++----- docs/guide/errors.md | 88 ++++++-------- docs/guide/events.md | 113 ++++++++--------- docs/guide/first-bot.md | 65 ++++------ docs/guide/getting-started.md | 91 ++++++-------- docs/guide/instances.md | 71 ++++------- docs/guide/limits.md | 102 +++++++--------- docs/guide/messages.md | 173 ++++++++++++--------------- docs/guide/oauth2.md | 112 +++++++---------- docs/guide/permissions.md | 124 ++++++++----------- docs/guide/spaces.md | 138 +++++++-------------- 12 files changed, 461 insertions(+), 691 deletions(-) diff --git a/docs/examples.md b/docs/examples.md index 99a78df..6e5a82a 100644 --- a/docs/examples.md +++ b/docs/examples.md @@ -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 diff --git a/docs/guide/coming-from-discord-js.md b/docs/guide/coming-from-discord-js.md index d2398c9..bd0c71f 100644 --- a/docs/guide/coming-from-discord-js.md +++ b/docs/guide/coming-from-discord-js.md @@ -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 @@ -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 @@ -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 | | --- | --- | @@ -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 @@ -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 @@ -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. diff --git a/docs/guide/errors.md b/docs/guide/errors.md index 9ecdfb9..3ddb585 100644 --- a/docs/guide/errors.md +++ b/docs/guide/errors.md @@ -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'; @@ -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 { @@ -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 { @@ -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 | | --- | --- | --- | @@ -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'; @@ -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({ @@ -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'; diff --git a/docs/guide/events.md b/docs/guide/events.md index 9441944..98438f6 100644 --- a/docs/guide/events.md +++ b/docs/guide/events.md @@ -1,8 +1,7 @@ # Events -The client is an event emitter: `on`, `once`, `off`, `emit`, `removeAllListeners` and -`listenerCount` (the same method names as discord.js). Event names are the camelCase values of the -`Events` enum, and the `ClientEvents` interface types each listener's arguments. +The client is an event emitter with `on`, `once`, `off`, `emit`, `removeAllListeners` and +`listenerCount`. Event names come from the `Events` enum; `ClientEvents` types each listener. ```ts import { Events } from '@strafechat/strafe.js'; @@ -13,57 +12,54 @@ client.on(Events.SpaceMemberAdd, async (member) => { }); ``` -There are no intents. A bot is subscribed by the server to every space, room and thread it can -see, from `READY` on and as it gains access, and it receives every event about them. +There are no intents. The bot receives every event about the spaces, rooms and threads it can see. ## The events | Event | Listener arguments | When | | --- | --- | --- | -| `ClientReady` (`'clientReady'`, also `'ready'`) | `client: Client` | The first `READY`; once per `login()` | +| `ClientReady` (`'clientReady'`, also `'ready'`) | `client: Client` | First `READY`; once per `login()` | | `GatewayReady` | none | Every `READY`, reconnects included | | `Reconnecting` | none | The connection dropped; a reconnect is scheduled | -| `Reconnected` | none | A reconnect reached `READY` and the caches were reconciled | -| `Invalidated` | `reason: string` | The session ended for good (token reset, account banned); the client stopped | -| `MessageCreate` | `message` | A message was sent (system notices and encrypted messages included) | +| `Reconnected` | none | A reconnect reached `READY` and caches were reconciled | +| `Invalidated` | `reason: string` | The session ended for good; the client stopped | +| `MessageCreate` | `message` | A message was sent, including system and encrypted ones | | `MessageUpdate` | `oldMessage`, `newMessage` | A message was edited | | `MessageDelete` | `message` | A message was deleted | | `MessageReactionAdd` | `reaction`, `user` | Someone reacted | -| `MessageReactionRemove` | `reaction`, `user` | Someone removed their reaction | +| `MessageReactionRemove` | `reaction`, `user` | Someone removed a reaction | | `RoomPinsUpdate` | `room`, `date: Date \| null`, `details` | A message was pinned or unpinned (`details.messageId`, `pinned`, `userId`) | | `TypingStart` | `typing` | Someone started typing | -| `SpaceCreate` | `space` | The bot joined a space (or was installed in one) | +| `SpaceCreate` | `space` | The bot joined or was installed in a space | | `SpaceUpdate` | `oldSpace`, `newSpace` | A space's settings changed | | `SpaceDelete` | `space` | The bot left or was removed, or the space was deleted | | `SpaceMemberAdd` | `member` | Someone joined a space | | `SpaceMemberUpdate` | `oldMember`, `newMember` | Roles, nickname or space profile changed | | `SpaceMemberRemove` | `member` | Someone left, or was kicked or banned | -| `RoomCreate`, `RoomDelete` | `room` | A room was created or deleted (or became visible or invisible to the bot) | -| `RoomUpdate` | `oldRoom`, `newRoom` | A room's settings, position or permission overrides changed | +| `RoomCreate`, `RoomDelete` | `room` | A room was created or deleted, or became visible or invisible | +| `RoomUpdate` | `oldRoom`, `newRoom` | Settings, position or permission overrides changed | | `RoleCreate`, `RoleDelete` | `role` | A role was created or deleted | | `RoleUpdate` | `oldRole`, `newRole` | A role changed | | `ThreadCreate` | `thread`, `newlyCreated: boolean` | A thread was created (`false` when an existing one became visible) | -| `ThreadUpdate` | `oldThread`, `newThread` | A thread changed (name, archived, locked...) | +| `ThreadUpdate` | `oldThread`, `newThread` | A thread changed | | `ThreadDelete` | `thread` | A thread was deleted | | `ThreadMembersUpdate` | `added`, `removed`, `thread` | People joined or left a thread | | `EmojiCreate`, `EmojiDelete` | `emoji` | A custom emoji was added or deleted | | `EmojiUpdate` | `oldEmoji`, `newEmoji` | A custom emoji was renamed | -| `PresenceUpdate` | `oldPresence \| null`, `newPresence` | Someone's status or activity changed | -| `UserUpdate` | `oldUser`, `newUser` | Someone's profile changed | -| `VoiceStateUpdate` | `oldState`, `newState` | Someone joined, left or moved in voice, or was muted | -| `Raw` | `packet` | Every gateway frame, as received | -| `Debug` | `message: string` | Diagnostics (`[gateway] ...` lines and more) | -| `Warn` | `message: string` | Something odd that did not stop the client: a gateway error frame, an option Strafe does not have | -| `Error` | `error: Error` | An error from a listener or from the library's event handling | +| `PresenceUpdate` | `oldPresence \| null`, `newPresence` | Status or activity changed | +| `UserUpdate` | `oldUser`, `newUser` | A profile changed | +| `VoiceStateUpdate` | `oldState`, `newState` | Someone joined, left, moved or was muted in voice | +| `Raw` | `packet` | Every gateway frame | +| `Debug` | `message: string` | Diagnostics | +| `Warn` | `message: string` | A non-fatal problem, such as a gateway error frame or an unsupported option | +| `Error` | `error: Error` | An error from a listener or from event handling | -Gateway events the client does not turn into one of these (read receipts, call signalling, -encryption key traffic) are still available through `Events.Raw`. +Other gateway events, such as read receipts and call signalling, arrive through `Events.Raw`. ## Old and new objects -Update events pass the cached object as it was before the change (a copy) and the cached object as -it is now. The new one is the live cache entry, patched in place: if you need a value as it is at -this moment, copy the value, not the object. +Update events pass a copy of the object before the change and the live cache entry after it. The +live entry is patched in place, so copy values you want to keep. ```ts client.on(Events.SpaceMemberUpdate, (oldMember, newMember) => { @@ -74,10 +70,8 @@ client.on(Events.SpaceMemberUpdate, (oldMember, newMember) => { ## Partial objects -Strafe sends events about things the client may not have cached: a reaction on a message from -before the bot started, an edit of an uncached message, a member who left before the member list -was fetched. Those events still fire, with **partial** objects that hold only what the event said. -Check `partial` and fetch when you need more: +Events about uncached things still fire, with **partial** objects. Check `partial` and fetch when +you need more: ```ts client.on(Events.MessageReactionAdd, async (reaction, user) => { @@ -86,21 +80,18 @@ client.on(Events.MessageReactionAdd, async (reaction, user) => { }); ``` -- A partial message has its `id`, `room` and `space`; `author` and `content` are `null` until - fetched. `MessageDelete` gives a partial message when the message was not cached (it cannot be - fetched any more). -- A reaction from an event may not know its `count` (`reaction.partial`); `reaction.fetch()` - re-reads the message. -- `oldMember` in `SpaceMemberUpdate`, and the member in `SpaceMemberRemove`, are partial when the +- A partial message has `id`, `room` and `space`. `author` and `content` are `null` until fetched. + A deleted uncached message stays partial. +- A reaction may lack its `count`; `reaction.fetch()` re-reads the message. +- `oldMember` in `SpaceMemberUpdate` and the member in `SpaceMemberRemove` are partial when the member was not cached. -There is no `partials` option to turn this on: it is always on. +Partials are always on; there is no `partials` option. ## Members are not in READY -`READY` carries the bot's spaces with their roles, rooms, emojis and voice states, but not their -member lists. `space.members.cache` starts empty and fills from events and fetches. Fetch the list -once if the bot needs it: +`READY` carries spaces, roles, rooms, emojis and voice states, but no member lists. +`space.members.cache` starts empty. Fetch it once if you need it: ```ts client.on(Events.ClientReady, async (ready) => { @@ -108,39 +99,31 @@ client.on(Events.ClientReady, async (ready) => { }); ``` -`message.member` is `null` until the author's member is cached; `space.members.fetch(id)` returns -the cached member when there is one. +`message.member` is `null` until the author's member is cached. ## Reconnects -The connection drops sometimes: a server restart, a network change. The client reconnects on its -own with exponential backoff and jitter (1 second, doubling, at most a minute, configurable through +The client reconnects on its own with exponential backoff (1 second, doubling, up to a minute; set `ws.reconnectDelay` and `ws.maxReconnectDelay`) and emits `Reconnecting`. Strafe has no session resume. Each reconnect gets a fresh `READY`, and the client reconciles its -caches with it: - -- Spaces, rooms and threads that appeared or disappeared while offline are reported as - `SpaceCreate`/`SpaceDelete`, `RoomCreate`/`RoomDelete` and `ThreadDelete`, then `GatewayReady` - and `Reconnected` fire. `ClientReady` does not fire again. -- `READY` lists only active threads and the archived threads the bot joined. A cached thread it - leaves out is kept and marked `archived` (and not joined) rather than reported deleted; it goes - away on `ThreadDelete` or with its parent room. -- Cached objects keep their identity and are patched in place. Changes to room or space settings - made while offline are applied without an event. -- Messages sent while the bot was offline are not replayed. Fetch them if they matter: - `room.messages.fetch({ after: lastSeenId })`. -- Member lists are not in `READY`, so they keep what they had and may have missed joins, leaves and - role changes. Fetch them again after `Reconnected` if the bot depends on them. - -If the token is reset, or the account is banned from the instance, the server revokes the session. -The client emits `Invalidated` and stops without reconnecting. +caches: + +- Spaces, rooms and threads that changed while offline emit `SpaceCreate`/`SpaceDelete`, + `RoomCreate`/`RoomDelete` and `ThreadDelete`. Then `GatewayReady` and `Reconnected` fire. + `ClientReady` does not fire again. +- A cached thread missing from `READY` is marked `archived` instead of deleted. +- Cached objects are patched in place. Settings changes made while offline emit no event. +- Missed messages are not replayed. Use `room.messages.fetch({ after: lastSeenId })`. +- Member lists may be stale. Fetch them again after `Reconnected` if you depend on them. + +If the token is reset or the account is banned, the client emits `Invalidated` and stops. ## Latency and raw frames -`client.ws.ping` is the round-trip time of the last latency ping, in milliseconds (`-1` until the -first one). `client.ws.status` is the connection state. `Events.Raw` receives every frame; the -payload shapes are exported as `GatewayDispatchDataMap` and `GatewayReceivePayload`. +`client.ws.ping` is the last round-trip time in milliseconds (`-1` before the first). +`client.ws.status` is the connection state. Raw payload types are exported as +`GatewayDispatchDataMap` and `GatewayReceivePayload`. ```ts client.on(Events.Debug, (line) => console.debug(line)); @@ -149,7 +132,7 @@ client.on(Events.Warn, (line) => console.warn(line)); ## Organising handlers -The `ClientEvents` interface makes a typed handler-per-file layout straightforward: +Use `ClientEvents` to type one handler per file: ```ts // events/messageCreate.ts diff --git a/docs/guide/first-bot.md b/docs/guide/first-bot.md index 4fe19e5..c2a6d55 100644 --- a/docs/guide/first-bot.md +++ b/docs/guide/first-bot.md @@ -1,7 +1,6 @@ # Your first bot -This page walks through `examples/ping-pong.ts` from the repository: a bot that answers `!ping` with -"Pong!" and the gateway latency. +A bot that answers `!ping` with "Pong!" and the gateway latency (`examples/ping-pong.ts`): <<< @/../examples/ping-pong.ts @@ -12,40 +11,27 @@ STRAFE_INSTANCE=app.strafe.chat STRAFE_TOKEN=your-token node bot.ts ``` Say `!ping` in a room the bot can see. If nothing happens, check that the room is not end-to-end -encrypted (a lock in the web client): a bot sees encrypted messages with `content === null` and -cannot answer there. +encrypted (a lock icon in the web client). Bots cannot read or answer there. ## Line by line -**`new Client({ instance })`** creates the client. Nothing connects yet. The options are few -because a Strafe bot has no intents to declare: it receives every event about what it can see. - -**`client.once(Events.ClientReady, ...)`** runs once, when the first `READY` has filled the -caches. The argument is the client typed as `Client`, whose `user`, `readyAt` and `uptime` -are not `null`. `'ready'` is emitted at the same moment, for code written that way. After a -reconnect the client emits `gatewayReady` and `reconnected` instead; see [Events](./events.md). - -**`client.on(Events.MessageCreate, ...)`** fires for every message in every room the bot can see: -its own, other bots', and system notices (a member joined, a message was pinned) included. Two -checks come first in almost every handler: - -- `message.author.bot` skips bots, including this one, so two bots never answer each other forever. -- `message.content === null` skips what the bot cannot read: messages in end-to-end encrypted rooms - arrive with `encrypted === true` and no text. - -**`message.reply()`** sends a reply in the same room. `room.send()` sends without the reply link. -Both return the sent `Message`. - -**`client.login()`** checks the token with the REST API (a wrong token rejects with -`TokenInvalid` here, before any connection), reads the instance's public index, connects to the -gateway and resolves with the token once `clientReady` has been emitted. +- `new Client({ instance })` creates the client without connecting. There are no intents: the bot + receives every event about what it can see. +- `Events.ClientReady` fires once, after the first `READY` fills the caches. Its argument is a + `Client`, so `user` is not `null`. Reconnects emit `gatewayReady` and `reconnected` + instead ([Events](./events.md)). +- `Events.MessageCreate` fires for every message the bot can see, including its own and system + notices. Skip `message.author.bot` so bots don't answer each other, and skip + `message.content === null`, which marks encrypted messages. +- `message.reply()` replies in the same room; `room.send()` sends without the reply link. Both + return the sent `Message`. +- `client.login()` validates the token (rejecting with `TokenInvalid`), connects, and resolves once + `clientReady` fires. ## Listeners can be async -Event listeners may be `async`. When one throws or its promise rejects, the client emits the error -as `Events.Error` (when something listens to it) and keeps going; the other listeners and later -events are not affected. Without an `error` listener the error is rethrown asynchronously, like an -uncaught exception. +If a listener throws or rejects, the client emits `Events.Error` and keeps going. With no `error` +listener, the error is rethrown as an uncaught exception. ## Presence @@ -56,9 +42,8 @@ client.once(Events.ClientReady, async (ready) => { }); ``` -Only "Playing" activities exist. The activity goes over the gateway and is sent again after every -reconnect; status and custom status are saved through the API. `new Client({ presence })` applies a -presence after the first `READY`. +Only "Playing" activities exist. The activity is re-sent after every reconnect. You can also pass +`new Client({ presence })`. ## Stopping @@ -69,14 +54,12 @@ process.on('SIGINT', async () => { }); ``` -`destroy()` closes the connection, stops reconnecting and forgets the token. The caches are kept and -`login()` may be called again. `await using client = new Client(...)` destroys it at the end of the -scope. +`destroy()` closes the connection and forgets the token. The caches are kept and `login()` can be +called again. `await using client = new Client(...)` destroys it at the end of the scope. ## Deploying -One process and one connection are enough for any number of spaces: Strafe has no sharding. Run the -bot under a process manager or in a container, pass the token through the environment, and let the -client reconnect on its own after network trouble (it backs off up to a minute between attempts). -If the token is reset or the account is banned from the instance, the client emits -`Events.Invalidated` and stops for good; exit and alert someone. +Strafe has no sharding: one process serves any number of spaces. Run it under a process manager or +in a container, with the token in the environment. The client reconnects on its own, backing off up +to a minute. If the token is reset or the account is banned, it emits `Events.Invalidated` and +stops for good; exit and alert someone. diff --git a/docs/guide/getting-started.md b/docs/guide/getting-started.md index 7f28aa7..86337b7 100644 --- a/docs/guide/getting-started.md +++ b/docs/guide/getting-started.md @@ -1,37 +1,28 @@ # Getting started strafe.js is the official TypeScript library for [Strafe](https://github.com/StrafeChat), a -federated, self-hostable chat platform. It covers three things: +federated, self-hostable chat platform. Use it to write bots, call the REST API, or add "Log in with +Strafe" (OAuth2 with PKCE) to a website. -- **Bots**: a `Client` that connects to an instance's gateway, keeps caches of spaces, rooms, - members and messages, and emits typed events. -- **The REST API**: a `REST` client with rate-limit queues and retries, usable on its own. -- **OAuth2**: "Log in with Strafe" for websites, with PKCE. - -On Strafe, a **Space** is a community with its own members, roles and invites, a **Room** is a text -or voice room in it, a **Section** groups rooms, and a **PM** is a private message. +A **Space** is a community with members, roles and invites. A **Room** is a text or voice room in +it, a **Section** groups rooms, and a **PM** is a private message. ::: details Coming from discord.js -Strafe uses the same interaction model as Discord under its own names: a Space is a server and a -Room is a text or voice room. The library keeps discord.js's class shapes and method names and uses -Strafe's nouns, so `guild.members.fetch()` becomes `space.members.fetch()`. -[Coming from discord.js](./coming-from-discord-js.md) has the full mapping. +The class shapes and method names match discord.js, with Strafe's nouns: +`guild.members.fetch()` becomes `space.members.fetch()`. +See [Coming from discord.js](./coming-from-discord-js.md) for the full mapping. ::: -Two things set Strafe apart, and both show up in the API: - -- **There is no central server.** Each instance runs its own API, gateway and applications. A bot - belongs to the instance its application was created on, so every client starts by naming one. -- **Private messages are end-to-end encrypted.** A bot cannot read or post in an encrypted room; - see [Limits and differences](./limits.md#encryption-and-what-a-bot-can-see). +Every instance is independent, so every client names the instance its bot belongs to. PMs are +end-to-end encrypted, and a bot cannot read or post in an encrypted room +([Limits and differences](./limits.md#encryption-and-what-a-bot-can-see)). ## Requirements -- Node.js 22.12 or newer, Bun, or Deno 2.5 or newer. -- An account on a Strafe instance, and a space you manage to test in. +- Node.js 22.12+, Bun, or Deno 2.5+. +- An account on a Strafe instance and a space you manage. -strafe.js has no runtime dependencies: it uses the platform's `fetch`, `WebSocket`, `FormData` -and `Blob`. +The library has no runtime dependencies. ## Installation @@ -39,33 +30,27 @@ and `Blob`. npm install @strafechat/strafe.js ``` -The package is ESM. `import` it; `require()` also works on Node.js 22.12 and newer: - ```ts import { Client, Events } from '@strafechat/strafe.js'; -// const { Client, Events } = require('@strafechat/strafe.js'); +// or: const { Client, Events } = require('@strafechat/strafe.js'); ``` -For TypeScript, use `"module": "nodenext"` (or `"moduleResolution": "bundler"`) in your -`tsconfig.json`. Node.js 22.18 and newer run `.ts` files directly (`node bot.ts`); on older -versions use a runner such as `tsx`. +For TypeScript, set `"module": "nodenext"` (or `"moduleResolution": "bundler"`). Node.js 22.18+ +runs `.ts` files directly; on older versions use `tsx`. ::: tip WebSocket on Node.js -The gateway sends the bot token in a header of the WebSocket handshake, so the client creates its -socket as `new WebSocket(url, { headers })`. The built-in `WebSocket` of Node.js and Bun accepts that -(Deno added the option in 2.5). If yours does not, pass a class that does, such as the one from the -`ws` package: `new Client({ ws: { WebSocket } })`. Browsers cannot send the header, so bots do not -run in a browser. +The gateway needs the token in a WebSocket handshake header. Node.js, Bun and Deno 2.5+ support +this. Otherwise, pass a compatible class such as `ws`'s: `new Client({ ws: { WebSocket } })`. Bots +do not run in browsers. ::: ## Creating a bot -1. In the Strafe web client, open **Settings → Developers** and create an application. It has a - **client id** and a **client secret**. -2. **Add a bot** to the application and copy its **token**. It is shown once; treat it like a - password. **Reset token** disconnects every session that used the old one. -3. Add the bot to a space you manage. The developer settings build an install link, or the bot can - build its own once it runs: +1. In the Strafe web client, open **Settings → Developers** and create an application. +2. Add a bot and copy its token. It is shown once. Resetting it disconnects every session using the + old one. +3. Add the bot to a space where you have Manage Space, using the link from the developer settings + or one the bot builds: ```ts import { PermissionFlagsBits } from '@strafechat/strafe.js'; @@ -75,38 +60,30 @@ run in a browser. }); ``` - Whoever opens the link picks a space where they have Manage Space. The bot joins with a - **managed role** holding the requested permissions (as far as that person may grant them). The - managed role starts at the bottom of the role list; move it up if the bot should manage members - or hand out roles. + The bot gets a managed role with the requested permissions, capped at what the installer may + grant. The role starts at the bottom of the list; move it up if the bot manages members or roles. -The bot's user id is the same as its application's client id. +The bot's user id is its application's client id. ## Configuration -Two environment variables cover most bots: - | Variable | Used by | Example | | --- | --- | --- | | `STRAFE_INSTANCE` | `new Client()`, `new REST()`, `new OAuth2Client()` when no `instance` is passed | `app.strafe.chat` | | `STRAFE_TOKEN` | `client.login()` when no token is passed | the bot token | -Keep them in a `.env` file that is not committed, and load it with `node --env-file=.env bot.ts` -(or your runtime's equivalent). - -`instance` accepts a domain (`app.strafe.chat`) or a URL. A domain gets the standard layout: the API -at `https://app.strafe.chat/api` and the gateway at `wss://app.strafe.chat/gateway/events`. For -development servers and unusual layouts, see [Instances and federation](./instances.md). +Keep them in an uncommitted `.env` and run `node --env-file=.env bot.ts`. ```ts const client = new Client({ instance: 'app.strafe.chat' }); ``` -There is no default instance: every instance is independent, and a missing one throws -`InstanceMissing` with a message naming `STRAFE_INSTANCE`. +`instance` takes a domain or a URL. A domain uses the API at `https:///api` and the gateway +at `wss:///gateway/events`; for other layouts see [Instances and federation](./instances.md). +There is no default: a missing instance throws `InstanceMissing`. ## Next steps -- [Your first bot](./first-bot.md): a complete bot, line by line. -- [Events](./events.md): what the client emits and when. -- [Examples](../examples.md): runnable bots and an OAuth2 login server. +- [Your first bot](./first-bot.md) +- [Events](./events.md) +- [Examples](../examples.md) diff --git a/docs/guide/instances.md b/docs/guide/instances.md index 0d0d562..f8b1883 100644 --- a/docs/guide/instances.md +++ b/docs/guide/instances.md @@ -1,22 +1,18 @@ # Instances and federation -Strafe is federated. Each instance is an independent server with its own domain, accounts, API, -gateway and applications, and instances talk to each other so that people can join spaces and -message people elsewhere. No instance is the official one, so strafe.js has no default: every +Strafe is federated: each instance has its own domain, accounts and API. There is no default, so every `Client`, `REST` and `OAuth2Client` names its instance. ## Pointing at an instance ```ts -new Client({ instance: 'app.strafe.chat' }); // a domain -new Client({ instance: 'https://chat.example.org' }); // an origin -new Client({ instance: 'https://example.org/strafe/api' }); // the API base itself -new Client({ instance: 'http://localhost:4000' }); // a development server -new Client(); // STRAFE_INSTANCE +new Client({ instance: 'app.strafe.chat' }); +new Client({ instance: 'https://chat.example.org' }); +new Client({ instance: 'https://example.org/strafe/api' }); +new Client({ instance: 'http://localhost:4000' }); +new Client(); // STRAFE_INSTANCE ``` -The URLs are derived without any request: - | `instance` | API | Gateway | Web client | | --- | --- | --- | --- | | `app.strafe.chat` or `https://app.strafe.chat` | `https://app.strafe.chat/api` | `wss://app.strafe.chat/gateway/events` | `https://app.strafe.chat` | @@ -24,31 +20,28 @@ The URLs are derived without any request: | Another URL with a path | that URL | `wss:///gateway/events` | the origin | | An origin with a port (`http://localhost:4000`) | that origin | the next port: `ws://localhost:4001/events` | the origin | -Local names (`localhost`, `*.localhost`, `*.local`, `*.test`, IP addresses) default to `http` and -`ws`; everything else to `https` and `wss`. `client.urls` shows the result. +Local names (`localhost`, `*.localhost`, `*.local`, `*.test`, IPs) use `http` and `ws`. `client.urls` +shows the result. -At login, the client reads the instance's public index (`GET /`). It records the instance's -federation domain (`client.federationDomain`), and takes the CDN and gateway addresses the -instance advertises, unless you set them yourself. `client.fetchInstance()` returns the whole index -(version, features, services). +At login the client reads the instance index and picks up its CDN, gateway and +`client.federationDomain`. `client.fetchInstance()` returns the whole index. ### Unusual layouts -Any address can be set explicitly; explicit values always win: +Explicit addresses always win: ```ts const client = new Client({ instance: 'chat.example.org', rest: { api: 'https://api.chat.example.org' }, ws: { gateway: 'wss://gateway.chat.example.org/events' }, - web: 'https://chat.example.org', // invite links and the OAuth2 consent page + web: 'https://chat.example.org', // invite links, OAuth2 consent cdn: 'https://cdn.chat.example.org', }); ``` -`discoverInstance(instance)` finds the addresses over the network instead, the way the desktop app -does: it tries the URL as an API, then `https:///.well-known/strafe`, then the standard -layout, and returns `{ urls, version, federationDomain, index }`. Pass its `urls` back as overrides. +`discoverInstance()` finds them over the network, trying the URL, then `/.well-known/strafe`, then the +standard layout: ```ts import { Client, discoverInstance } from '@strafechat/strafe.js'; @@ -59,14 +52,10 @@ const client = new Client({ instance: urls.origin, rest: { api: urls.api }, ws: ## A bot belongs to one instance -A bot is an account on the instance where its application was created, and it connects to that -instance only. It still reaches the rest of the network through it: spaces hosted elsewhere that -it joins are mirrored on its home instance, and people from other instances appear in its spaces. +A bot connects only to its application's instance. Spaces it joins elsewhere are mirrored there. ## People from other instances -Users carry where they come from: - | Property | Local user | User from `other.example` | | --- | --- | --- | | `user.username` | `alice` | `alice` | @@ -75,32 +64,24 @@ Users carry where they come from: | `user.isRemote` | `false` | `true` | | `user.originId` | the same as `id` | the user's id on their own instance | -Ids are per instance: the same person has a different id on each instance that knows them. Use -`user.id` within the bot's instance, and `handle` when showing or storing who someone is across -the network. Strafe has no discriminators: a handle is unique. +Ids differ per instance. Use `user.id` locally and `handle`, which is unique, to identify someone across the network. ## Spaces on other instances -A space can live on another instance and be mirrored on the bot's. Its `space.federated` is `true` -and `space.federation` names the origin; rooms carry `room.federation` too. Everything works the -same way: messages, members and moderation go to the origin through the bot's instance, and the -events come back over the bot's own gateway. +A mirrored space has `space.federated` set to `true`, and `space.federation` and `room.federation` +name the origin. Everything works the same. ## Invites across instances -Invite codes are local to an instance. A code for a space on another instance is written -`code@domain`: +A code for a space on another instance is written `code@domain`: ```ts -await client.fetchInvite('abc123'); // this instance -await client.fetchInvite('abc123@other.example'); // a space hosted on other.example -await client.fetchInvite('https://other.example/invite/abc123'); // read as abc123@other.example +await client.fetchInvite('abc123'); +await client.fetchInvite('abc123@other.example'); +await client.fetchInvite('https://other.example/invite/abc123'); // abc123@other.example ``` -`client.fetchInvite()` works before login. A link from another instance's web client becomes -`code@host`, so the bot's instance fetches it from that host over federation. If your bot reads -invite links from messages, decide first whether it should follow links to other hosts at all: -`parseInviteCode(text)` returns `{ code, domain, linkHost }` without any request. +`fetchInvite()` works before login. To check a link without a request, use `parseInviteCode()`: ```ts import { parseInviteCode } from '@strafechat/strafe.js'; @@ -108,10 +89,8 @@ import { parseInviteCode } from '@strafechat/strafe.js'; const { code, linkHost } = parseInviteCode('https://other.example/invite/abc123'); ``` -`invite.url` is a link on the bot's own instance's web client. +`invite.url` always points at the bot's own instance. ## Developer documentation of an instance -Every instance serves the documentation of its own API and gateway at `https:///docs/`. -strafe.js follows the server's code where the two disagree, but the instance's pages are the -reference for the raw protocol. +Each instance serves its API reference at `https:///docs/`. diff --git a/docs/guide/limits.md b/docs/guide/limits.md index 8d43177..70f225c 100644 --- a/docs/guide/limits.md +++ b/docs/guide/limits.md @@ -1,79 +1,65 @@ # Limits and differences -Some things are not possible on Strafe, or work differently: rooms can be end-to-end encrypted, -every instance is independent, and some features other platforms have do not exist here. The -library does not paper over them: where the server would refuse, it refuses first with a typed -error, and where an option cannot work, it does not exist. This page lists them in one place, with -the discord.js name beside each for anyone porting a bot. +What Strafe cannot do, or does differently, with the discord.js name beside each. Where the server +would refuse, the library refuses first with a typed error. ## Encryption and what a bot can see -Strafe encrypts private messages end to end: the server stores and relays text it cannot read. +- 1:1 PMs are always end-to-end encrypted. +- Group PMs are encrypted by default. The creator can turn it off. +- Space rooms are plain by default and can opt in. -- **1:1 PMs** are always end-to-end encrypted. -- **Group PMs** are encrypted by default; the group's creator can turn it off. -- **Space rooms** are plain by default; a room can opt in, and then shows a lock in the client. - -A bot has no encryption keys, so it can neither read nor write in an encrypted room. Messages -there still arrive as events, with `message.encrypted === true` and `content === null`, so a bot -knows that something was said but not what. Sending (`room.send()`, `message.reply()`, -`message.edit()`) rejects with `RoomEncrypted` before any request; `room.isEncrypted()` and -`room.isSendable()` tell you beforehand. This is by design, not a missing feature: a bot that -could read encrypted rooms would break the encryption for everyone in them. +A bot has no encryption keys, so it cannot read or write in an encrypted room. Messages there still +arrive, with `message.encrypted === true` and `content === null`. `room.send()`, `message.reply()` and +`message.edit()` reject with `RoomEncrypted` before any request. Check `room.isEncrypted()` or `room.isSendable()` first. ### Bots and PMs -Because 1:1 PMs are always encrypted, **a bot cannot send a PM**. `user.send()` and -`member.send()` exist for discord.js compatibility and always reject with `PMsEncrypted`. -`user.createPM()` opens (or finds) the PM room, but the bot cannot post in it. Answer people in a -space room instead, or point them to a website. A group PM whose creator turned encryption off -works like any plain room. +A bot cannot send a PM. `user.send()` and `member.send()` always reject with `PMsEncrypted`. +`user.createPM()` returns the PM room, but the bot cannot post in it. Reply in a space room instead. +A group PM with encryption turned off works like any plain room. ## Things that do not exist | discord.js | Strafe | | --- | --- | -| Gateway intents, `partials` | Not needed: a bot receives every event about what it can see, and events about uncached objects always arrive as [partial objects](./events.md#partial-objects). Passing `intents` or `partials` emits a warning. | -| Sharding, `ShardingManager`, `shards` | Not needed: one connection carries everything. | -| Slash commands, context menus, buttons, select menus, modals | Not on Strafe. Use message commands (`!help`) and reactions. | -| Webhooks | Not on Strafe. A bot can post where it has permission. | -| `allowedMentions` | Strafe has no way to send a mention that does not notify. Use `escapeMentions()` on text you did not write. Passing the option emits a warning. | -| Joining voice (`@discordjs/voice`) | Calls are end-to-end encrypted with per-device keys a bot does not have. A bot can see voice states and move, mute or disconnect people. | -| Session resume | Every reconnect is a fresh `READY`; the client reconciles its caches and reports what changed ([Reconnects](./events.md#reconnects)). | -| Looking up any user (`client.users.fetch(id)`) | Only the bot's own user can be fetched. Others come from messages, members and events; `space.members.fetch(id)` brings a member's user along. | -| Removing someone else's reaction, or all reactions | Only the bot's own reaction can be removed. | -| Bulk delete endpoint | `room.bulkDelete()` sends one `DELETE` per message (at most 100), through the rate limiter. | -| Audit log reasons on most actions | Only bans record a reason. `reason` arguments elsewhere are accepted and ignored. | -| Message links | The web client has no link to a single message: `message.url` is the room's URL. | -| Default avatars | `user.displayAvatarURL()` is `null` for someone without an avatar. | -| A space's member count (`space.memberCount`) | Spaces carry no count. Fetch the members once (`space.members.fetch()`) and use `space.members.cache.size`; an invite preview has `invite.memberCount`. | -| Application details (`client.application.fetch()`, owner, commands) | `client.application` is only `{ id }`, the bot's user id, which is also its application's client id. | +| Gateway intents, `partials` | Not needed. A bot gets every event about what it can see; uncached objects arrive as [partial objects](./events.md#partial-objects). Passing either emits a warning. | +| Sharding, `ShardingManager`, `shards` | Not needed. One connection carries everything. | +| Slash commands, context menus, buttons, select menus, modals | Use message commands (`!help`) and reactions. | +| Webhooks | A bot can post where it has permission. | +| `allowedMentions` | Every mention notifies. Use `escapeMentions()` on text you did not write. Passing the option emits a warning. | +| Joining voice (`@discordjs/voice`) | Calls are end-to-end encrypted. A bot can see voice states and move, mute or disconnect people. | +| Session resume | Every reconnect is a fresh `READY` ([Reconnects](./events.md#reconnects)). | +| `client.users.fetch(id)` | Only the bot's own user. `space.members.fetch(id)` brings a member's user along. | +| Removing others' reactions, or all reactions | Only the bot's own reaction. | +| Bulk delete endpoint | `room.bulkDelete()` sends one `DELETE` per message (at most 100). | +| Audit log reasons | Only bans record a reason. Other `reason` arguments are ignored. | +| Message links | `message.url` is the room's URL. | +| Default avatars | `user.displayAvatarURL()` is `null` without an avatar. | +| `space.memberCount` | Use `space.members.cache.size` after `space.members.fetch()`, or `invite.memberCount`. | +| `client.application.fetch()`, owner, commands | `client.application` is only `{ id }`, the bot's user id. | | Crossposting, stickers, polls, scheduled events, stage rooms, forum rooms | Not on Strafe. | ## Things that work differently -- **Member lists are not in `READY`.** `space.members.cache` starts empty; fetch it once with - `space.members.fetch()` when you need it. After a reconnect it may have missed changes. -- **Editing is limited to text and embeds**, and only for the author. Files cannot be added or - removed and the text cannot be cleared. -- **Embeds are for bots only**, need Embed Links, and cannot go into encrypted rooms. Their limits - count Unicode code points, not UTF-16 units, so emoji-heavy text hits them sooner than on Discord. -- **Message text** is at most 4000 code points; at most 10 files, 10 embeds, 20 different reaction - emoji per message, and 50 pins per room. -- **Kicks record no reason**, bans do. -- **Bots are exempt from verification levels** but not from automod. -- **POST requests are not retried** after a timeout or a `5xx` other than `503`, because Strafe has - no idempotency key and a retry could post twice ([Retries](./errors.md#retries-and-timeouts)). -- **There is no default instance.** Every client names one ([Instances](./instances.md)). +- `space.members.cache` starts empty, and after a reconnect it may have missed changes. Call + `space.members.fetch()` when you need it. +- Only the author can edit, and only text and embeds: files cannot be added or removed. Text cannot be + cleared. +- Embeds are bot-only, need Embed Links, and cannot go into encrypted rooms. Their limits count + code points, not UTF-16 units. +- Messages: at most 4000 code points, 10 files, 10 embeds and 20 different reaction emoji. Rooms: + at most 50 pins. +- Bots are exempt from verification levels, not from automod. +- `POST` requests are not retried after a timeout or a non-`503` `5xx` + ([Retries](./errors.md#retries-and-timeouts)). +- There is no default instance ([Instances](./instances.md)). ## Gateway limits -- The server buffers at most 512 unsent frames per connection and silently drops events when the - buffer is full. strafe.js reads frames as they arrive and handles them from its own queue, so a - slow listener (or a fetch for an uncached room) never blocks the socket. Events are still handled - in order. -- A connection can hold at most 5000 subscriptions. A bot is subscribed by the server to its spaces, - rooms and threads; past 5000, further subscriptions are silently ignored and their events do not - arrive. `client.ws.subscribe()` and `unsubscribe()` exist for completeness; bots rarely need them. -- One connection per bot is enough. An account may hold at most 25 connections; logging in twice - with the same token opens two connections that both receive everything. +- The server buffers at most 512 unsent frames per connection and drops events past that. + strafe.js reads frames as they arrive, so a slow listener never blocks the socket. +- A connection holds at most 5000 subscriptions. Past that, events for further spaces, rooms and + threads do not arrive. +- An account may hold at most 25 connections. Logging in twice opens two connections that both + receive everything. diff --git a/docs/guide/messages.md b/docs/guide/messages.md index d9dd27a..da62b34 100644 --- a/docs/guide/messages.md +++ b/docs/guide/messages.md @@ -2,8 +2,8 @@ ## Sending -Every room that holds messages has `send()`: space text rooms, the text chat of voice rooms, -threads, and group PMs. It takes a string or an options object and returns the sent `Message`. +Space text rooms, voice-room chats, threads and group PMs all have `send()`. It takes a string or +options and returns the sent `Message`. ```ts await room.send('Hello!'); @@ -15,30 +15,28 @@ await room.send({ reply: { messageReference: someMessage }, // or its id }); -await message.reply('Got it.'); // the same as send() with reply set +await message.reply('Got it.'); ``` | Option | Notes | | --- | --- | -| `content` | At most 4000 characters, counted in Unicode code points. Mentions in it notify people. | -| `embeds` | At most 10. `EmbedBuilder`, a received `Embed`, or plain data. Bots only, with Embed Links. | -| `files` | At most 10. Uploaded to the room first, then attached. Needs Attach Files. | -| `reply` | `{ messageReference }`: a message of the same room, or its id. | +| `content` | Up to 4000 Unicode code points. Mentions notify. | +| `embeds` | Up to 10. Bots only, with Embed Links. | +| `files` | Up to 10. Needs Attach Files. | +| `reply` | `{ messageReference }`: a message in the same room, or its id. | -A message needs at least one of `content`, `embeds` or `files`. Everything the library can check -is checked before any request, and breaking a rule throws instead of sending: +A message needs content, embeds or files. The library validates before sending and throws: | Error code | Why | | --- | --- | -| `RoomEncrypted` | The room is end-to-end encrypted. A bot can neither read nor post there. | -| `PMsEncrypted` | The room is a 1:1 PM, which is always encrypted. `user.send()` always rejects with this. | -| `RoomNotTextBased` | The room is a section, which holds no messages. | +| `RoomEncrypted` | The room is end-to-end encrypted. | +| `PMsEncrypted` | The room is a 1:1 PM, which is always encrypted. `user.send()` always throws this. | +| `RoomNotTextBased` | The room is a section. | | `MessageEmpty` | No content, embeds or files. | -| `MessageTooLarge` | More than 4000 characters, 10 embeds or 10 files. | +| `MessageTooLarge` | Over 4000 characters, 10 embeds or 10 files. | | `EmbedInvalid` | An embed breaks a limit; `error.path` says where (`embeds[0].fields[3].value`). | -`room.isSendable()` tells you up front whether a room holds messages and is not encrypted. It -narrows the type, so `send()` is available after it: +`room.isSendable()` checks that a room holds messages and is not encrypted, and narrows its type: ```ts const room = client.rooms.cache.get(roomId); @@ -47,12 +45,8 @@ if (room?.isSendable()) await room.send('Still here.'); ### No allowedMentions -Strafe finds mentions in the text itself (`<@id>`, `<@&roleId>`, `@everyone`, `@here`) and has no -way to send text without notifying the people it names. The library therefore has no -`allowedMentions` option: offering it would promise something it cannot do. Passing one anyway -emits a single warning. - -When you repeat text you did not write, defuse it first: +Strafe always notifies whoever the text mentions (`<@id>`, `<@&roleId>`, `@everyone`, `@here`), so +there is no `allowedMentions` option. Passing one logs a warning. Escape text you did not write: ```ts import { escapeMentions } from '@strafechat/strafe.js'; @@ -60,13 +54,11 @@ import { escapeMentions } from '@strafechat/strafe.js'; await room.send(`You said: ${escapeMentions(message.content ?? '')}`); ``` -`@everyone` and `@here` only notify when the author has Mention Everyone, and a role mention only -notifies when the role is mentionable or the author has Mention Everyone. +`@everyone` and `@here` need Mention Everyone. A role mention needs a mentionable role or Mention +Everyone. ### Formatting -Strafe renders Markdown much like Discord. The formatters build it for you: - ```ts import { bold, codeBlock, hyperlink, roleMention, roomMention, time, TimestampStyles, userMention } from '@strafechat/strafe.js'; @@ -74,62 +66,56 @@ await room.send(`${userMention(user.id)} ${bold('read')} ${roomMention(rulesRoom await room.send(codeBlock('ts', 'const answer = 42;')); ``` -`escapeMarkdown()` escapes Markdown in text you did not write. Structures stringify to their -mention: `` `${user}` `` is `<@id>`, `` `${room}` `` is `<#id>`, `` `${role}` `` is `<@&id>`. +`escapeMarkdown()` escapes Markdown. Users, rooms and roles stringify to their mentions +(`<@id>`, `<#id>`, `<@&id>`). ## Editing and deleting ```ts const sent = await room.send('Working...'); await sent.edit('Done.'); -await sent.edit({ embeds: [embed] }); // the text stays as it was +await sent.edit({ embeds: [embed] }); // keeps the text await sent.delete(); ``` -Only the author can edit a message, and only its text and embeds: files cannot be added or -removed, and the text cannot be cleared (an empty `content` keeps the old text). `embeds: []` -removes the embeds. `message.editable` and `message.deletable` say whether the client may. +Only the author can edit, and only text and embeds. An empty `content` keeps the old text; +`embeds: []` removes embeds. Check `message.editable` and `message.deletable`. -The bot can delete its own messages anywhere, and other people's messages in space text rooms and -threads with Manage Messages. Other people's messages in PMs and in voice-room chats can never be -deleted. +The bot can delete its own messages anywhere. With Manage Messages it can delete others' messages in +space text rooms and threads, but never in PMs or voice-room chats. ### Bulk delete ```ts -const deleted = await room.bulkDelete(50); // the 50 newest messages +const deleted = await room.bulkDelete(50); // the 50 newest await room.bulkDelete([idA, idB]); ``` -Strafe has no bulk-delete endpoint, so `bulkDelete()` sends one `DELETE` per message (at most 100 -per call) through the rate limiter. A large batch takes a while. When some deletions fail it throws -a `BulkDeleteError` holding `deleted` and `failed` collections. +`bulkDelete()` sends one rate-limited `DELETE` per message, up to 100 per call, so large batches are +slow. Partial failure throws a `BulkDeleteError` with `deleted` and `failed` collections. ## Reactions ```ts await message.react('👍'); -await message.react('<:party:2102226824774811648>'); // a custom emoji: its text form, id, or Emoji +await message.react('<:party:2102226824774811648>'); // text form, id, or Emoji const reaction = message.reactions.cache.get('👍'); -await reaction?.remove(); // removes the bot's own reaction +await reaction?.remove(); // the bot's own reaction const users = await reaction?.users.fetch(); ``` -- Starting a new reaction needs Add Reactions; adding to an existing one does not. A message holds - at most 20 different emoji. -- The bot can only remove its own reactions. Strafe has no endpoint to remove someone else's - reaction or all reactions, so `reaction.users.remove(otherUser)` and +- A new reaction needs Add Reactions; joining an existing one does not. A message holds up to 20 + different emoji. +- The bot can only remove its own reactions. `reaction.users.remove(otherUser)` and `message.reactions.removeAll()` reject. -- `message.reactions.cache` is keyed by the unicode emoji, or by the custom emoji's id. - `reaction.emoji` is the space's `SpaceEmoji` when it is cached, otherwise a `ReactionEmoji`. +- `message.reactions.cache` is keyed by the Unicode emoji or the custom emoji's id. ## Waiting for replies and reactions -Collectors work as in discord.js: every room that holds messages has `createMessageCollector()` -and `awaitMessages()`, and every message has `createReactionCollector()` and `awaitReactions()`. +Rooms have `createMessageCollector()` and `awaitMessages()`; messages have +`createReactionCollector()` and `awaitReactions()`. ```ts -// A confirmation: the next message from the same person, within 30 seconds. await message.reply('Type `yes` to confirm.'); try { const replies = await message.room.awaitMessages({ @@ -143,37 +129,32 @@ try { await message.reply('No answer; cancelled.'); } -// A poll: count the votes for a minute. const poll = await room.send('Lunch at noon? React with 👍 or 👎.'); const collector = poll.createReactionCollector({ time: 60_000 }); collector.on('collect', (reaction, user) => console.log(`${user.username} voted ${reaction.emoji.name}`)); collector.on('end', (collected) => console.log(`${collected.get('👍')?.count ?? 0} for, ${collected.get('👎')?.count ?? 0} against`)); ``` -- The options are discord.js's: `filter`, `max`, `time`, `idle` and `dispose`, plus `maxProcessed` - for messages and `maxEmojis` and `maxUsers` for reactions. `collector.stop()` ends one early. -- `await*` resolves with the collection when the collector ends, or rejects **with that - collection** when its end reason is listed in `errors` (`['time']`), as in discord.js. -- A collector also ends when its room, thread, space or (for reactions) message is deleted, with - the reason `roomDelete`, `threadDelete`, `spaceDelete` or `messageDelete`. -- Messages in an end-to-end encrypted room are collected too, with `content === null`. -- Reaction collectors are keyed like `message.reactions.cache`: the unicode emoji, or the custom - emoji's id. +- Options: `filter`, `max`, `time`, `idle`, `dispose`, plus `maxProcessed` (messages) and + `maxEmojis`, `maxUsers` (reactions). `collector.stop()` ends one early. +- `await*` rejects with the collection when the end reason is in `errors`. +- Deleting the room, thread, space or message ends a collector with `roomDelete`, `threadDelete`, + `spaceDelete` or `messageDelete`. +- Encrypted messages are collected with `content === null`. ## Pins and typing ```ts await message.pin(); // Manage Messages in spaces; anyone in a PM await message.unpin(); -const pins = await room.messages.fetchPins(); // newest pin first, at most 50 per room +const pins = await room.messages.fetchPins(); // newest first, up to 50 per room -await room.sendTyping(); // shows "typing..." for about 5 seconds +await room.sendTyping(); // about 5 seconds ``` ## Fetching messages -`room.messages` caches the newest 200 messages per room by default (see -[Caching](./spaces.md#caching)). Fetch older ones, or one by id: +`room.messages` caches the newest 200 messages per room ([Caching](./spaces.md#caching)). ```ts const latest = await room.messages.fetch(); // the newest 50 @@ -182,32 +163,30 @@ const around = await room.messages.fetch({ around: messageId, limit: 25 }); const one = await room.messages.fetch(messageId); ``` -`limit` is 1 to 100 (default 50) and at most one of `before`, `after` and `around` applies. Pages -come back as a `Collection` sorted newest first, whatever the cursor. +`limit` is 1 to 100 (default 50). Use at most one of `before`, `after` and `around`. Results are +sorted newest first. -`room.messages.search({ query, author, mentions, has, before, limit })` searches a room's history. -Encrypted rooms answer `searchable: false`. +`room.messages.search({ query, author, mentions, has, before, limit })` searches history. Encrypted +rooms return `searchable: false`. ## What a message carries | Property | Notes | | --- | --- | -| `content` | The text, or `null` when the bot cannot read it (`encrypted === true`) or the message is partial. | -| `author`, `member` | The sender, and their member when cached (`null` in PMs or before the member list is fetched). | -| `room`, `space` | `space` is `null` in PMs; `message.inSpace()` narrows it to `Space`. | -| `embeds`, `attachments` | Received embeds (`Embed`) and files (`Attachment`, with `url`, `name`, `contentType`, `size`). | -| `mentions` | `users`, `roles`, `rooms`, `everyone`, `repliedUser`, and `has()`. | -| `reference` | The message this one replies to; `fetchReference()` fetches it. | -| `system`, `systemData` | System notices (member joined, message pinned, thread created...) with their parsed data. | +| `content` | The text, or `null` when encrypted or partial. | +| `author`, `member` | The sender, and their member when cached (`null` in PMs). | +| `room`, `space` | `space` is `null` in PMs; `message.inSpace()` narrows it. | +| `embeds`, `attachments` | `Embed`s and `Attachment`s (`url`, `name`, `contentType`, `size`). | +| `mentions` | `users`, `roles`, `rooms`, `everyone`, `repliedUser`, `has()`. | +| `reference` | The replied-to message; `fetchReference()` fetches it. | +| `system`, `systemData` | System notices and their parsed data. | | `pinned`, `createdAt`, `editedAt` | | -`cleanContent` is the text with mentions replaced by names. +`cleanContent` replaces mentions with names. ## Embeds -Embeds are rich cards under a message: a title, a description, fields, images, an author and a -footer. On Strafe only bots can send them, they need the Embed Links permission, and they cannot go -into end-to-end encrypted rooms. +Only bots can send embeds. They need Embed Links and cannot go into encrypted rooms. ```ts import { EmbedBuilder } from '@strafechat/strafe.js'; @@ -228,7 +207,7 @@ const embed = new EmbedBuilder() await room.send({ embeds: [embed] }); ``` -The limits are Discord's numbers, counted in Unicode code points after trimming: +Limits are in Unicode code points after trimming: | | Limit | | --- | --- | @@ -241,31 +220,29 @@ The limits are Discord's numbers, counted in Unicode code points after trimming: | All of the above, over every embed of a message | 6000 | | Any URL | 2048 bytes, `http` or `https` | -`EmbedLimits` exports them, and `validateEmbed()` checks an embed without sending it. +`EmbedLimits` exports them. `validateEmbed()` checks an embed without sending. ### Images -External images are fetched by the instance and served through its image proxy, so readers never -contact the site that hosts them; any public `http(s)` image works. A received embed has the -proxied address in `embed.image?.proxyURL` (and likewise for the thumbnail and icons). +The instance proxies external images, so readers never contact the host. Any public `http(s)` image +works. Received embeds expose the proxied address as `embed.image?.proxyURL` (and likewise for +thumbnails and icons). -To show a file you upload with the message, name it with `attachment://` in the image, thumbnail, -author icon or footer icon. It must be a png, jpeg, gif or webp image: +To use an uploaded file, reference it as `attachment://name` in the image, thumbnail or an icon. It +must be png, jpeg, gif or webp: <<< @/../examples/embeds.ts#chart{ts} ## Files -`files` takes `AttachmentBuilder`s, `{ attachment, name }` objects, received `Attachment`s (downloaded -and uploaded again), or the data itself: a `Buffer` or other bytes, a `Blob`, a `ReadableStream`, a -local file as a `file:` `URL` object (Node.js, Bun and Deno), or an `http(s)` URL to download. +`files` accepts `AttachmentBuilder`s, `{ attachment, name }`, received `Attachment`s, bytes +(`Buffer`, `Blob`, `ReadableStream`), a `file:` `URL`, or an `http(s)` URL to download. -Unlike discord.js, **a string is never read as a local path**. Strings are often user input, and -`message.reply({ files: [args[0]] })` would otherwise post `/proc/self/environ` or your `.env` -(with the bot token) to the room. Name local files explicitly with `new URL('./file', import.meta.url)` -or `pathToFileURL(path)` from `node:url`; any other string rejects with `FileInvalid`. Downloading an -`http(s)` URL that someone else chose still fetches it from the bot's network, so check the host -before passing user input. +::: warning Strings are never local paths +Unlike discord.js, a string path rejects with `FileInvalid`, so user input cannot upload your `.env`. +Use `new URL('./file', import.meta.url)` or `pathToFileURL(path)`. An `http(s)` URL is fetched from +the bot's network, so check the host before passing user input. +::: ```ts import { pathToFileURL } from 'node:url'; @@ -275,8 +252,8 @@ await room.send({ files: [pathToFileURL('./logs/today.txt')] }); await room.send({ files: [new AttachmentBuilder(pngBuffer, { name: 'chart.png', width: 800, height: 400 })] }); ``` -The instance sets the largest file it accepts; a larger one fails with a `413` `StrafeAPIError` -whose `rawError.max_bytes` gives the limit. +Files over the instance's limit fail with a `413` `StrafeAPIError`; `rawError.max_bytes` gives the +limit. ## Threads @@ -287,5 +264,5 @@ await thread.send('Thoughts?'); const standalone = await textRoom.threads.create({ name: 'Planning', private: true }); ``` -Threads are rooms (`ThreadRoom`) under a space text room. They inherit the parent room's -permissions, and posting in them needs Send Messages in Threads. +Threads (`ThreadRoom`) live under space text rooms and inherit their permissions. Posting needs Send +Messages in Threads. diff --git a/docs/guide/oauth2.md b/docs/guide/oauth2.md index 3051fb3..1f59098 100644 --- a/docs/guide/oauth2.md +++ b/docs/guide/oauth2.md @@ -1,15 +1,12 @@ # OAuth2 login -"Log in with Strafe" lets a website or app identify a Strafe user without handling their password. -It is the standard OAuth2 authorization-code flow with PKCE. `OAuth2Client` does every step and -needs no bot and no gateway connection. +"Log in with Strafe" uses the OAuth2 authorization-code flow with PKCE. `OAuth2Client` handles it +without a bot or gateway. ## Setup -1. In **Settings → Developers**, create an application (or use your bot's). Note its **client id** - and **client secret**. -2. Register your **redirect URI** on the application, exactly as your server will send it - (`https://example.org/callback`). It must match character for character. +1. In Settings → Developers, create an application and note its client id and secret. +2. Register your redirect URI. It must match exactly. 3. Create the client on your server: ```ts @@ -23,51 +20,38 @@ const oauth = new OAuth2Client({ }); ``` -The application lives on one instance, and so do its users: people with an account on another -instance cannot sign in to it with that account. Use the instance your users are on. +Only accounts on the application's instance can sign in. ## Scopes | `OAuth2Scopes` | Value | Gives | | --- | --- | --- | -| `Identify` | `identify` | `oauth.fetchUser()`: id, name, avatar and profile | -| `Email` | `email` | The same, plus `email` and `verified` | -| `Spaces` | `spaces` | `oauth.fetchSpaces()`: the spaces they are in, with their permissions | -| `SpacesJoin` | `spaces.join` | Lets your bot add them to a space | -| `Bot` | `bot` | Installs your bot in a space they manage | +| `Identify` | `identify` | `oauth.fetchUser()` | +| `Email` | `email` | Adds `email` and `verified` | +| `Spaces` | `spaces` | `oauth.fetchSpaces()`, with permissions | +| `SpacesJoin` | `spaces.join` | Your bot can add them to a space | +| `Bot` | `bot` | Installs your bot | -A request asks for 1 to 10 scopes. An access token only ever reaches `GET /users/@me`, -`GET /users/@me/spaces` and `GET /oauth2/@me`; it can never open the gateway or act as the person -elsewhere. +Ask for 1 to 10 scopes. A token reaches only `GET /users/@me`, `GET /users/@me/spaces` and +`GET /oauth2/@me`. ## The flow <<< @/../examples/oauth2-login.ts#flow{ts} -Step by step: - -1. **`createState()`** makes a random value tied to the person's browser (a cookie here). The - redirect back must carry the same value, or `parseCallback()` throws `OAuth2StateMismatch`: this - stops someone else's login from being slipped into your site. -2. **`createPKCE()`** makes a verifier, kept on your server, and its SHA-256 challenge, sent in the - URL. Only the holder of the verifier can redeem the code. -3. **`generateAuthURL()`** builds the consent page URL on the instance's web client. Send the - person there. It refuses locally what the server would refuse: no scopes or too many, no - redirect URI, a malformed challenge. -4. The person approves (or declines) and comes back to your redirect URI. - **`parseCallback(url, state)`** checks the state, turns a refusal into `OAuth2AccessDenied`, and - returns the `code`. The expected state is required: when it is `undefined` or `''` (the - session or cookie was lost, or the person never started a login), the check fails with - `OAuth2StateMismatch` instead of being skipped. Pass `null` only for an authorization you started - without a state. -5. **`exchangeCode(code, { codeVerifier })`** trades the code for tokens. Codes are single-use and - expire after 10 minutes. - -The code exchange always needs the client secret, even with PKCE: Strafe has no public clients. -Keep the exchange on a server. A browser can still build the authorization URL with the standalone +1. `createState()` makes a value tied to the browser. +2. `createPKCE()` makes a verifier for your server and a challenge for the URL. +3. `generateAuthURL()` builds the consent page URL. It throws on missing scopes, redirect URI or a bad + challenge. +4. `parseCallback(url, state)` returns the `code`. It throws `OAuth2StateMismatch` when the state + differs or is missing, and `OAuth2AccessDenied` when the person declines. Pass `null` only if you + started without a state. +5. `exchangeCode(code, { codeVerifier })` returns tokens. Codes are single-use and last 10 minutes. + +The exchange always needs the client secret, so keep it on a server. A browser can build the URL with `generateAuthorizationURL({ instance, clientId, scopes, redirectUri, state, codeChallenge })`. -The whole server, using only `node:http`, is in [the examples](../examples.md#oauth2-login). +The full server is in [the examples](../examples.md#oauth2-login). ## Tokens @@ -75,37 +59,35 @@ The whole server, using only `node:http`, is in [the examples](../examples.md#oa const tokens = await oauth.exchangeCode(code, { codeVerifier }); // { accessToken, refreshToken, tokenType: 'Bearer', expiresIn, expiresTimestamp, scopes } -const user = await oauth.fetchUser(tokens); // or fetchUser(tokens.accessToken) -const spaces = await oauth.fetchSpaces(tokens); // Collection of OAuth2Space -const fresh = await oauth.refreshToken(tokens); // replaces the pair: store the new one -await oauth.revokeToken(fresh); // "log out": revokes both tokens and the consent +const user = await oauth.fetchUser(tokens); +const spaces = await oauth.fetchSpaces(tokens); +const fresh = await oauth.refreshToken(tokens); // store the new pair +await oauth.revokeToken(fresh); // revokes both tokens and the consent ``` -- There is one live token pair per person and application. Refreshing replaces it: the old access - and refresh tokens stop working, so save the new pair before using it. -- Refresh tokens do not expire on their own; revoking either token of a pair revokes both and - withdraws the consent. -- `OAuth2Tokens` is plain data (`expiresTimestamp` is an absolute time), so it can go straight - into a database. -- `fetchUser()` returns an `OAuth2User`: the read side of a `User` (`username`, `displayName`, - `handle`, `avatarURL()`, `flags`...) plus `email` and `verified`. `email` is `null` without the - `email` scope. +- Each person has one live token pair per application. Refreshing invalidates the old pair. +- Refresh tokens don't expire. Revoking either token revokes both. +- `OAuth2Tokens` is plain data and can be stored as is. +- `OAuth2User` has the read side of a `User`, plus `email` and `verified` (`null` without `email`). ### Errors -The token endpoint answers with the RFC 6749 error codes, which arrive as a `StrafeAPIError` whose -`code` is the error: `invalid_grant` for a used, expired or mismatched code (or a wrong verifier), -`invalid_client` for a wrong client id or secret (Strafe answers `400` for it, not `401`), -`invalid_scope`, `invalid_request`. The code, verifier, refresh token and secret are removed from -the request body kept on the error. The endpoint allows 20 requests a minute per IP address. +Token errors are a `StrafeAPIError` whose `code` is the RFC 6749 error: -## Installing a bot with OAuth2 +| `code` | Cause | +| --- | --- | +| `invalid_grant` | Used, expired or mismatched code, or wrong verifier | +| `invalid_client` | Wrong client id or secret (status `400`) | +| `invalid_scope` | Unknown scope | +| `invalid_request` | Malformed request | -The `bot` scope installs your application's bot. On its own it needs no redirect: the person picks -a space and is done. `client.generateInvite()` and `oauth.generateBotInvite()` build that link. +Secrets are stripped from the error. The endpoint allows 20 requests a minute per IP. + +## Installing a bot with OAuth2 -With more scopes, or an explicit `redirectUri`, the person comes back to your site with a code, the -chosen space and the granted permissions: +The `bot` scope alone needs no redirect. `client.generateInvite()` and `oauth.generateBotInvite()` +build the link. With more scopes or a `redirectUri`, the person returns with a code, space and +permissions: ```ts const link = oauth.generateBotInvite({ @@ -114,19 +96,17 @@ const link = oauth.generateBotInvite({ state, }); -// On the redirect: const { code, spaceId, permissions } = oauth.parseCallback(request.url, state); ``` ## Adding people to a space -With the `spaces.join` scope, your bot can add the person to a space it is in. The bot needs Create -Invite there: +With `spaces.join`, your bot can add the person to a space where it has Create Invite: ```ts const tokens = await oauth.exchangeCode(code, { codeVerifier }); const user = await oauth.fetchUser(tokens); -const space = client.spaces.cache.get(spaceId)!; // the bot's Client +const space = client.spaces.cache.get(spaceId)!; await space.members.add(user, { accessToken: tokens }); ``` diff --git a/docs/guide/permissions.md b/docs/guide/permissions.md index 68f5b32..a413af5 100644 --- a/docs/guide/permissions.md +++ b/docs/guide/permissions.md @@ -1,11 +1,9 @@ # Permissions -Roles carry permissions, rooms can override them per role or per member, and the space owner and -Administrators get everything. Each permission is a bit, named in `PermissionFlagsBits`. +Roles carry permissions and rooms override them. The owner and Administrators have everything. ::: warning Coming from discord.js -The model is Discord's, but the names and the bit values are Strafe's own (Send Messages is -`1n << 1n` here). Use `PermissionFlagsBits` rather than numbers copied from Discord documentation. +Strafe's bit values differ from Discord's. Use `PermissionFlagsBits`, never copied numbers. ::: ## PermissionsBitField @@ -15,130 +13,112 @@ import { PermissionFlagsBits, PermissionsBitField } from '@strafechat/strafe.js' const perms = new PermissionsBitField([PermissionFlagsBits.SendMessages, PermissionFlagsBits.EmbedLinks]); perms.has(PermissionFlagsBits.SendMessages); // true -perms.has(['SendMessages', 'AddReactions']); // flag names work too: false +perms.has(['SendMessages', 'AddReactions']); // false perms.any(PermissionFlagsBits.ManageMessages); // false perms.add('AddReactions').remove('EmbedLinks'); perms.toArray(); // ['SendMessages', 'AddReactions'] perms.serialize(); // { ViewRoom: false, SendMessages: true, ... } ``` -The value is a `bigint` inside (`perms.bitfield`). The API sends permissions as JSON numbers, and -the library converts in both directions. `has()`, `any()` and `missing()` treat Administrator as -holding everything unless you pass `false` as the second argument. +The value is a `bigint` (`perms.bitfield`). `has()`, `any()` and `missing()` count Administrator as +everything unless the second argument is `false`. -`PermissionsBitField.Default` is what `@everyone` gets in a new space, `PermissionsBitField.All` is -every bit, and `AllRoom`, `AllVoice` and `AllThreads` are the bits that make sense in a room -override, for voice, and for threads. +`PermissionsBitField.Default` is `@everyone` in a new space. `All` is every bit. `AllRoom`, `AllVoice` +and `AllThreads` are the bits valid in room overrides, voice and threads. ## The flags | Flag | Value | Notes | | --- | --- | --- | -| `ViewRoom` | `1 << 0` | Without it, nothing else in the room applies | -| `SendMessages` | `1 << 1` | Without it, Attach Files, Embed Links and Mention Everyone do not apply either | +| `ViewRoom` | `1 << 0` | Required for anything else in the room | +| `SendMessages` | `1 << 1` | Required for Attach Files, Embed Links, Mention Everyone | | `ReadMessageHistory` | `1 << 2` | | -| `AddReactions` | `1 << 3` | Needed to start a new reaction, not to join one | +| `AddReactions` | `1 << 3` | New reactions only | | `UseExternalEmojis` | `1 << 4` | | -| `MentionEveryone` | `1 << 5` | `@everyone`, `@here`, and pinging roles that are not mentionable | -| `ManageMessages` | `1 << 6` | Delete others' messages, pin; exempt from slowmode | -| `ManageRoles` | `1 << 7` | Roles below your highest; room overrides | -| `ManageRooms` | `1 << 8` | Create, edit, move and delete rooms and sections | +| `MentionEveryone` | `1 << 5` | `@everyone`, `@here`, unmentionable roles | +| `ManageMessages` | `1 << 6` | Delete, pin; skips slowmode | +| `ManageRoles` | `1 << 7` | Roles below yours; room overrides | +| `ManageRooms` | `1 << 8` | Rooms and sections | | `KickMembers` | `1 << 9` | | | `BanMembers` | `1 << 10` | | -| `Administrator` | `1 << 11` | Everything, still bound by the role hierarchy | -| `ManageSpace` | `1 << 12` | Space settings, audit log, installing bots | -| `CreateInvite` | `1 << 13` | Also needed to add people with an OAuth2 `spaces.join` token | +| `Administrator` | `1 << 11` | Everything, within the role hierarchy | +| `ManageSpace` | `1 << 12` | Settings, audit log, bot installs | +| `CreateInvite` | `1 << 13` | Also for `spaces.join` adds | | `ManageEmojis` | `1 << 14` | | -| `Connect` | `1 << 15` | Join voice rooms | +| `Connect` | `1 << 15` | | | `Speak` | `1 << 16` | | -| `Video` | `1 << 17` | Camera and screen sharing | +| `Video` | `1 << 17` | Camera and screen share | | `MuteMembers` | `1 << 18` | | | `DeafenMembers` | `1 << 19` | | -| `MoveMembers` | `1 << 20` | Move and disconnect people in voice | -| `UseVAD` | `1 << 21` | Voice activity instead of push-to-talk | +| `MoveMembers` | `1 << 20` | Move and disconnect | +| `UseVAD` | `1 << 21` | | | `PrioritySpeaker` | `1 << 22` | | | `AttachFiles` | `1 << 23` | | | `CreatePublicThreads` | `1 << 24` | | | `CreatePrivateThreads` | `1 << 25` | | -| `SendMessagesInThreads` | `1 << 26` | Posting in threads (instead of Send Messages) | +| `SendMessagesInThreads` | `1 << 26` | | | `ManageThreads` | `1 << 27` | | -| `ChangeNickname` | `1 << 28` | Your own nickname | -| `ManageNicknames` | `1 << 29` | Others' nicknames and space profiles | -| `EmbedLinks` | `1 << 30` | Sending embeds (bots) | +| `ChangeNickname` | `1 << 28` | | +| `ManageNicknames` | `1 << 29` | Includes space profiles | +| `EmbedLinks` | `1 << 30` | Bot embeds | -Discord permissions with no Strafe counterpart (View Audit Log, Manage Webhooks, Moderate Members, -Use Application Commands and others) do not exist; View Audit Log is part of Manage Space. +There is no View Audit Log, Manage Webhooks or Moderate Members. ## A member's permissions ```ts -member.permissions.has(PermissionFlagsBits.KickMembers); // space-wide +member.permissions.has(PermissionFlagsBits.KickMembers); // space-wide member.permissionsIn(room).has(PermissionFlagsBits.SendMessages); // in one room -room.permissionsFor(member)?.has(PermissionFlagsBits.ViewRoom); // the same, from the room -room.permissionsFor(role); // what a role gets in the room +room.permissionsFor(member)?.has(PermissionFlagsBits.ViewRoom); +room.permissionsFor(role); ``` -These compute locally, from the cache, with the server's algorithm: +These compute from the cache, the same way the server does: -1. The owner has every permission. So does anyone whose roles include Administrator. -2. Otherwise start from `@everyone`'s permissions plus those of each of the member's roles. -3. In a room, apply the overrides: `@everyone`'s, then the member's roles' (denies, then allows), - then the member's own. -4. Without View Room, the member has nothing in the room. Without Send Messages, they also lose - Attach Files, Embed Links and Mention Everyone there. +1. The owner and Administrators have everything. +2. Otherwise, combine `@everyone` and the member's roles. +3. In a room, apply overrides: `@everyone`, then roles (denies, then allows), then the member. +4. Without View Room, nothing applies. Without Send Messages, Attach Files, Embed Links and Mention + Everyone don't either. -A room in a section with `permissionsSynced` uses the section's overrides. A thread uses its -parent room's, and a private thread is invisible to people who are neither in it nor have Manage -Threads. +A synced room uses its section's overrides. A thread uses its parent's. A private thread is hidden +from anyone not in it and without Manage Threads. -`member.permissionsIn()` needs the member to be cached, with roles: fetch it first if needed (see -[members are not in READY](./events.md#members-are-not-in-ready)). For the bot itself, -`space.members.me` (after `space.members.fetchMe()`). +The member must be cached first (see [members are not in READY](./events.md#members-are-not-in-ready)). ## Overrides ```ts -// Make a read-only announcements room. await room.permissionOverwrites.edit(space.everyoneRoleId!, { SendMessages: false }); await room.permissionOverwrites.edit(moderatorRole, { SendMessages: true }); -// Replace an override entirely, or remove it. -await room.permissionOverwrites.create(member, { ViewRoom: true }); +await room.permissionOverwrites.create(member, { ViewRoom: true }); // replaces await room.permissionOverwrites.delete(member); ``` -`edit()` changes the named permissions and keeps the rest (`null` resets one), `create()` replaces -the whole override, `set()` replaces every override of the room. Editing overrides needs Manage -Roles (not Manage Rooms), and you can only allow or deny permissions you have in that room. +`edit()` changes the named bits (`null` resets one). `create()` replaces one override, `set()` all of +them. Overrides need Manage Roles, and you can only grant bits you have in that room. ## The role hierarchy -Strafe follows Discord's rules: +- Rank is your highest role's position. The owner is above everyone. +- Giving or removing a role checks the role: it must be below your highest. The member can be anyone, + owner included. +- Kick, ban and nickname changes check the member: their highest role must be below yours. The owner + can't be kicked or banned. +- You can only edit roles below yours and grant permissions you have. +- A bot's managed role stays with its bot. -- A member's rank is their highest role's position. The owner is above everyone. Administrators - are still bound by the hierarchy. -- **Giving or taking a role** depends only on the role: with Manage Roles you can give or remove any - role strictly below your own highest, on anyone, including members above you and the owner. -- **Kicking, banning and changing nicknames** depends on the member: their highest role must be - below yours. The owner can never be kicked or banned. -- **Creating, editing and moving roles** only touches roles below yours, and you cannot grant - permissions you do not have yourself. -- A bot's managed role (created when it is installed) cannot be given to anyone else or taken from - the bot. - -`member.manageable`, `member.kickable`, `member.bannable` and `role.editable` check these rules from -the cache. New roles and the bot's managed role start at position 1, just above `@everyone`, so a -bot that moderates or hands out roles needs its role moved up by an admin. +`member.manageable`, `member.kickable`, `member.bannable` and `role.editable` check these rules. The +bot's role starts just above `@everyone`, so an admin must move it up before it can moderate. ## Installing with permissions -`client.generateInvite({ permissions })` (or `generateBotInvite`) asks for permissions in the -install link. The person installing the bot can grant at most what they have; the bot gets them on -its managed role. +The installer can grant at most what they have. The bot gets them on its managed role. ```ts const link = client.generateInvite({ permissions: new PermissionsBitField(['SendMessages', 'EmbedLinks', 'ManageRoles']), - space: '2102226824774811648', // optional: preselect a space + space: '2102226824774811648', // optional }); ``` diff --git a/docs/guide/spaces.md b/docs/guide/spaces.md index 957cceb..4d83049 100644 --- a/docs/guide/spaces.md +++ b/docs/guide/spaces.md @@ -1,29 +1,13 @@ # Spaces, members and roles -A **space** holds rooms, roles, members, custom emojis, invites and bans. Each is reached through a -manager on the `Space`: a `cache` (a [`Collection`](#collections)), `fetch()`, `resolve()` and -`resolveId()`, plus `create`/`edit`/`delete` where the API allows. - -| Manager | Holds | Filled from | -| --- | --- | --- | -| `client.spaces` | Spaces the bot is in | `READY`, then events | -| `client.rooms` | Every room: space rooms, threads, PMs | `READY`, then events | -| `client.users` | Users the bot has seen | Messages, members, events | -| `client.emojis` | Custom emojis of every space | `READY`, then events | -| `space.rooms` | The space's rooms and sections | `READY` | -| `space.members` | Members | **Fetches** and events (not in `READY`) | -| `space.roles` | Roles | `READY` | -| `space.emojis`, `space.bans`, `space.invites` | Emojis; bans and invites when fetched | | -| `space.voiceStates` | Who is in which voice room | `READY` | -| `member.roles` | The member's roles | The member | -| `room.messages` | Messages of a room | Events and fetches | -| `textRoom.threads` | Threads of a text room | `READY`, events | +A space holds rooms, roles, members, emojis, invites and bans. Each has a manager with a `cache`, `fetch()`, +`resolve()` and, where the API allows, `create`/`edit`/`delete`. ## Spaces ```ts -const cached = client.spaces.cache.get(spaceId); // undefined when the bot is not in it -const space = await client.spaces.fetch(spaceId); // asks the server +const cached = client.spaces.cache.get(spaceId); +const space = await client.spaces.fetch(spaceId); await space.edit({ name: 'Book club', description: 'Reading together' }); await space.setIcon(new URL('./icon.png', import.meta.url)); @@ -31,20 +15,15 @@ const owner = await space.fetchOwner(); await space.leave(); ``` -A few settings have Strafe names: the inactive voice room (Discord's AFK room) is -`space.inactiveRoomId` with `inactiveTimeout`, the system messages room is `space.systemRoomId`, and -the space widget is `space.widgetEnabled` / `space.fetchWidget()`. `space.fetchAuditLogs()` reads the -audit log (it needs Manage Space; Strafe has no separate View Audit Log permission). Transferring and deleting a space are for its -owner only. +The inactive voice room is `space.inactiveRoomId` with `inactiveTimeout`. The system messages room is +`space.systemRoomId`. The space widget is `space.widgetEnabled` and `space.fetchWidget()`. +`space.fetchAuditLogs()` needs Manage Space. Only the owner can transfer or delete a space. -A space can be hosted on another instance and mirrored on the bot's own: then `space.federated` is -`true` and `space.federation` names the origin. The API is the same; see +A space hosted on another instance has `space.federated` set to `true`. See [Instances and federation](./instances.md). ## Rooms and sections -Rooms are typed by `type` (the `RoomType` enum) and the classes narrow with guards: - | Class | `RoomType` | Guard | | --- | --- | --- | | `PMRoom` | `PM` (1) | `isPM()`, `isPMBased()` | @@ -54,68 +33,55 @@ Rooms are typed by `type` (the `RoomType` enum) and the classes narrow with guar | `SectionRoom` | `SpaceSection` (5) | `isSection()` | | `ThreadRoom` | `Thread` (6) | `isThread()` | -`isTextBased()` (anything with messages, which includes a voice room's text chat), `isSendable()` -(text-based and not encrypted), `isSpaceBased()` and `isEncrypted()` work on every room. - -A **section** groups rooms in the sidebar. Rooms in a section can keep -their permissions synced with it. +Every room also has `isTextBased()`, `isSendable()`, `isSpaceBased()` and `isEncrypted()`. ```ts import { RoomType } from '@strafechat/strafe.js'; const section = await space.rooms.create({ name: 'Projects', type: RoomType.SpaceSection }); const room = await space.rooms.create({ name: 'roadmap', parent: section, topic: 'What is next' }); -await room.setRateLimitPerUser(10); // slowmode, in seconds -await room.setParent(null); // out of the section -await room.lockPermissions(); // sync with the section again +await room.setRateLimitPerUser(10); // slowmode, seconds +await room.setParent(null); +await room.lockPermissions(); // sync with the section for (const child of section.children.values()) console.log(child.name); ``` -Creating, editing, moving and deleting rooms needs Manage Rooms. `room.permissionOverwrites` edits -the room's overrides; see [Permissions](./permissions.md#overrides). +Managing rooms needs Manage Rooms. For overrides, see [Permissions](./permissions.md#overrides). ## Members -Member lists are **not** part of `READY`. `space.members.cache` holds only the members the bot has -fetched or seen in events, so fetch before relying on it: +Members are not in `READY`. Fetch them before reading `space.members.cache`. ```ts -await space.members.fetch(); // everyone, cached -const member = await space.members.fetch(userId); // one (cached when possible) -const me = await space.members.fetchMe(); // the bot itself -``` - -`space.members.me` is the bot's member once cached. +await space.members.fetch(); +const member = await space.members.fetch(userId); +const me = await space.members.fetchMe(); // then space.members.me -```ts await member.setNickname('Helper'); -await member.edit({ nick: null, pronouns: null, bio: null }); // a moderator can clear profile fields -await space.members.me?.edit({ pronouns: 'it/its' }); // ...but only set them for the bot itself +await member.edit({ nick: null, pronouns: null, bio: null }); +await space.members.me?.edit({ pronouns: 'it/its' }); await member.kick(); -await member.ban({ reason: 'Spam' }); // the reason goes to the audit log +await member.ban({ reason: 'Spam' }); await space.members.unban(userId); ``` -- Kick and ban need Kick Members and Ban Members, and the bot must outrank the member (the owner - outranks everyone; otherwise its highest role must be higher). `member.kickable`, - `member.bannable` and `member.manageable` check that from the cache. -- Strafe records no reason for kicks; `kick(reason)` accepts one and ignores it. Bans keep theirs. -- A member's space profile (nickname, avatar, banner, bio, pronouns) overrides their account's in - that space. `member.displayName` and `member.displayAvatarURL()` take it into account. -- Only the nickname can be set on someone else (with Manage Nicknames). The bio, about me, - pronouns, avatar and banner can only be set by the member themselves; a moderator can only clear - them (`null`), and setting a value on another member fails with a `403` `StrafeAPIError` whose - `code` is `APIErrorCodes.CannotEditMemberProfile`. +- Kick and ban need Kick Members and Ban Members, and the bot must outrank the member. + `member.kickable`, `member.bannable` and `member.manageable` check this. +- Kicks record no reason. Bans do. +- A member's space profile overrides their account's. `member.displayName` and + `member.displayAvatarURL()` use it. +- On other members, a moderator can set the nickname (Manage Nicknames) and clear the other profile + fields with `null`. Setting them fails with `403` and `APIErrorCodes.CannotEditMemberProfile`. ### Adding people with OAuth2 -A website that logged someone in with the `spaces.join` scope can have the bot add them to a space: +With a `spaces.join` token, the bot can add someone to a space. It needs Create Invite. ```ts await space.members.add(user, { accessToken: tokens }); ``` -The bot needs Create Invite. See [OAuth2 login](./oauth2.md#adding-people-to-a-space). +See [OAuth2 login](./oauth2.md#adding-people-to-a-space). ## Roles @@ -128,19 +94,15 @@ const role = await space.roles.create({ }); await member.roles.add(role); await member.roles.remove(role); -await member.roles.set([roleA, roleB]); // replace the list +await member.roles.set([roleA, roleB]); await role.setPosition(3); await role.delete(); ``` -- Strafe follows Discord's role hierarchy. With Manage Roles you may give or take away any role - **strictly below your own highest role**, on anyone, the owner included. Roles at or above yours - that the member holds are kept whatever you send. -- New roles start at position 1, just above `@everyone`. The bot's managed role (the one it got - when it was installed, `space.roles.botRoleFor(client.user)`) also starts there and cannot be - given to anyone else; ask an admin to move it up if the bot hands out roles. -- `member.roles.highest`, `member.roles.color` and `member.roles.hoist` work as in discord.js; - `space.roles.everyone` is `@everyone`. `role.members` lists cached members holding it. +- With Manage Roles you can give or remove any role below your highest, on anyone. +- New roles start at position 1, above `@everyone`. So does the bot's managed role + (`space.roles.botRoleFor(client.user)`), which can't be given to anyone else. +- `space.roles.everyone` is `@everyone`. `role.members` lists cached members with the role. ## Invites, emojis, bans @@ -157,20 +119,17 @@ await message.react(emoji); const bans = await space.bans.fetch(); ``` -Invite codes from another instance look like `code@domain`; see -[Instances and federation](./instances.md#invites-across-instances). +For `code@domain` invites, see [Instances and federation](./instances.md#invites-across-instances). ## Voice -`space.voiceStates` and `member.voice` show who is in which voice room, and moderators can act on -them: `member.voice?.setMute(true)`, `setDeaf()`, `setRoom(otherVoiceRoom)`, `disconnect()`. A bot -cannot join a voice call itself: calls are end-to-end encrypted with per-device keys that a bot does -not have. +`space.voiceStates` and `member.voice` show who is in voice. Moderators can call `setMute()`, +`setDeaf()`, `setRoom()` and `disconnect()` on a voice state. Bots can't join calls, because calls are +end-to-end encrypted. ## Caching -The client caches what it sees. By default it keeps everything except messages, where it keeps the -newest 200 per room. `makeCache` changes that per manager: +By default the client caches everything except messages, where it keeps the newest 200 per room. ```ts import { Client, Options } from '@strafechat/strafe.js'; @@ -179,28 +138,23 @@ const client = new Client({ instance: 'app.strafe.chat', makeCache: Options.cacheWithLimits({ ...Options.DefaultMakeCacheSettings, - MessageManager: 50, // newest 50 messages per room - ReactionManager: 0, // do not cache reactions + MessageManager: 50, + ReactionManager: 0, }), }); ``` -`Options.cacheEverything()` keeps everything. Anything missing from a cache can be fetched; events -about uncached objects arrive with [partial objects](./events.md#partial-objects). +`Options.cacheEverything()` removes the limits. Events about uncached objects carry +[partial objects](./events.md#partial-objects). -There is no user lookup on Strafe: `client.users.fetch(id)` works only for the bot itself. Other -users reach the cache through messages, members, reactions and presence events; for a member, -`space.members.fetch(id)` brings the user along. +`client.users.fetch(id)` works only for the bot itself. Other users enter the cache through messages, +members, reactions and presence. ## Collections -`Collection` extends `Map` with discord.js's helpers: `find`, `filter`, `map`, `mapValues`, -`first`, `last`, `random`, `some`, `every`, `reduce`, `partition`, `sort`, `sorted`, `ensure`, -`hasAll`, `hasAny`, `at`, `keyAt`, `concat`, `equals`, and more. +`Collection` is a `Map` with discord.js's helpers (`find`, `filter`, `first`, `sorted` and the rest). ```ts const admins = space.members.cache.filter((m) => m.permissions.has(PermissionFlagsBits.Administrator)); const newest = space.members.cache.sorted((a, b) => (b.joinedTimestamp ?? 0) - (a.joinedTimestamp ?? 0)).first(5); ``` - -`map()` returns an array and `filter()` a new `Collection`, as in discord.js.