> ## Documentation Index
> Fetch the complete documentation index at: https://docs.cloak.chat/llms.txt
> Use this file to discover all available pages before exploring further.

# Client

> The Client is your bot. It connects to Cloak, emits events, sends messages, and drives every action.

Everything starts with a `Client`. You construct it with your token, attach event listeners, and call `login()`.

```ts theme={null}
import { Client } from '@cloak-software/bot-sdk';

const client = new Client({
  token: process.env.CLOAK_TOKEN!,
  keystorePath: './bot.cloak-keystore.json',
  requiredPermissions: ['message_send', 'reaction_add'],
});

client.on('messageCreate', async (msg) => {
  if (msg.authorId === client.user?.id) return;
  if (msg.isDM || !msg.serverId) return;
  if (msg.content.trim() === '!ping') await msg.channel.send('pong');
});

await client.login();
```

Server-scoped methods take a `serverId` as their first argument. If a handler does several things in one server, [`guild(serverId)`](#guild) binds that id once so you can drop it from every call.

> [!WARNING]
>
> `Message.serverId` is `string | null`. It is `null` for a direct message. Guard with `if (msg.isDM || !msg.serverId) return;` before anything server-scoped, or your bot breaks on the first DM it receives. See [Direct messages](https://docs.cloak.chat/guides/direct-messages.md).

## Constructor options

### Identity and storage

**token** `string` *required*

Your bot token, in the form `botid.tokenid.secret`. Create it in the Cloak app under **Settings > My Bots**. Treat it like a password. Read it from an environment variable, never hardcode it.

**keystorePath** `string`

Path to a file where the SDK persists your bot's identity, its conversation keys, and its peer pins. Shorthand for `keystore: fileKeystore(path)`. Mutually exclusive with `keystore`: passing both throws.

A bot with no keystore of any kind is single-run only. Its second start fails permanently, because identity publication is write-once on the server. See [Keys and the keystore](https://docs.cloak.chat/concepts/keys-and-keystore.md).

**keystore** `KeystoreAdapter`

Where to persist identity and keys when a file will not do. Use `envKeystore()` on a host with no writable volume, or supply your own adapter. Mutually exclusive with `keystorePath`. See [Keystore backends](https://docs.cloak.chat/production/keystore-backends.md).

**deviceId** `string`

A stable device id used for clean takeover on reconnect. Defaults to a value derived from your token. Set it only if you have a specific reason to.

### Behavior

**requiredPermissions** `PermissionName[]`

The permissions your bot declares it needs, sent to the server on login. Declaring is a request, not a grant. A human approves a subset per server, and the resolved grant arrives on [`permissionsUpdate`](https://docs.cloak.chat/api-reference/events#permissionsupdate). See [Permissions](https://docs.cloak.chat/concepts/permissions.md).

**commandPrefix** `string` (default: /)

The prefix the text lane of the slash-command parser matches. Only the text lane uses it. A structured invocation carries the command name outright and is prefix-independent. See [Slash commands](https://docs.cloak.chat/guides/slash-commands.md).

**webhookName** `string` (default: Bot)

Display name for the webhook that [`sendEmbed()`](#sendembed) mints. Cosmetic only. Reuse is matched on creator plus channel, never on name, so renaming this does not orphan an existing webhook.

**webhookFetch** `WebhookFetch`

An injected `fetch` for the webhook ingress, for tests or a proxy. Defaults to `globalThis.fetch`. This is the only outbound HTTP the SDK performs on its own.

**debug** `boolean` (default: false)

Logs every frame the SDK sends and receives, with your bot token redacted. Useful while developing, noisy in production.

### Endpoints and transport

> [accordion] Advanced: self-hosted, local dev, and lane selection
>
> Bots against the hosted Cloak service rarely set any of these.
>
> **url** `string`
>
> The connection endpoint. Defaults to the hosted service on the lane implied by `transport`: `DEFAULT_URL` for `'ws'`, `DEFAULT_WEBTRANSPORT_URL` for `'webtransport'`. A `wss://` url speaks the WebSocket lane, an `https://` url the WebTransport lane.
>
> **transport** `'ws' | 'webtransport'` (default: ws)
>
> Which wire to speak. The default WebSocket lane rides the pure-JavaScript `ws` package, so `npm install` compiles nothing. `'webtransport'` needs the optional Quiche packages installed. See [Installing](https://docs.cloak.chat/install.md).
>
> **allowInsecure** `boolean` (default: false)
>
> Permit a plain `ws://` url, which sends the bot token in cleartext. Local development stacks only.
>
> **idleTimeoutMs** `number` (default: 60000)
>
> Treat the connection as dead after this long with no inbound data, then reconnect. Defaults to `60000` on the WebSocket lane and is disabled on WebTransport, which has its own QUIC idle timeout. `0` disables it.
>
> **serverCertificateHashes** `\{ algorithm: 'sha-256'; value: Uint8Array \}[]`
>
> WebTransport lane only: a self-signed QUIC certificate pin for a self-hosted or local stack. Throws on the WebSocket lane. Not needed for the hosted service.
>
> **restUrl** `string`
>
> The REST base that [`client.rest`](#properties) talks to. Defaults to `DEFAULT_REST_URL`. HTTPS only, except loopback. A bad value throws on the first `client.rest` call.
>
> **livekitUrl** `string`
>
> The LiveKit signalling url handed back on `VoiceConnection.url`. Defaults to `livekitUrlFor(<transport url>)`, which is the same host on port 7880. The SDK never connects to it. See [Joining voice](https://docs.cloak.chat/voice/joining.md).

## Properties

**user** `BotUser | null`

Your bot's identity after login, or `null` before `login()` completes. Its `id` is normalized, so you can compare it against `msg.authorId` to detect your bot's own messages. See [BotUser](https://docs.cloak.chat/api-reference/types.md#botuser).

**commands** `CommandRegistry`

The bot's slash-command registry. `register(decl, handler)` is synchronous.

Register before `login()`. Whatever is registered at that moment is published as the bot's menu, which server `/` pickers and, on a wire version 3 backend, the DM picker read. A command added afterwards still dispatches locally, but it does not appear in the published menu until the next login, and the SDK never re-publishes on its own. See [Slash commands](https://docs.cloak.chat/api-reference/commands.md).

**webhooks** `WebhookApi`

The incoming-webhook surface: `list`, `create`, `edit`, `regenerate`, `delete`, and `post`. The five CRUD calls require `manage_server`. `post(url, payload)` requires nothing at all and is the recommended path. See [Webhooks](https://docs.cloak.chat/api-reference/webhooks.md).

> [!WARNING]
>
> Everything posted through this lane is **not** end-to-end encrypted and renders under a webhook identity rather than your bot's.

**rest** `RestApi`

The authenticated REST lane: `request`, `json`, and `binary`. Every call transparently mints a short-lived credential over the realtime session, so your long-lived bot token never rides an HTTP header.

This is off by default server-side, so the first call usually rejects with a `CloakActionError` carrying code `-7`. See [REST](https://docs.cloak.chat/api-reference/rest.md).

**raw** `RawApi`

The escape hatch to opcodes the SDK does not map: `send(frame, opts?)` and `request(frame, replyOpcode, opts?)`. Raw frames run on the same serialized chain as every mapped action.

`request()` refuses reply opcodes the SDK correlates internally unless you pass `{ allowReserved: true }`, because awaiting one can claim a reply the SDK was waiting for. See [Raw frames](https://docs.cloak.chat/guides/raw-frames.md).

**voiceKeys**

The voice-key lane, and nothing else: `getVoiceKey`, `acquireVoiceKey`, `voiceFrameKeyFor`, and `forgetVoiceKey`. Hand this to a media session so it can install frame keys without reaching your conversation keys. See [Voice keys](https://docs.cloak.chat/voice/keys.md).

This accessor's interface type is intentionally not exported, so annotate with `typeof client.voiceKeys` if you need a name for it.

## Lifecycle

### login

```ts theme={null}
login(): Promise<void>
```

Checks the Node runtime, loads the keystore, connects, authenticates, publishes your bot's identity if it has never been published, declares the permission manifest, publishes the command menu, emits `guildCreate` for existing servers, then emits `ready`. Call it once, after attaching your listeners and registering your commands.

> [!WARNING]
>
> Two login failures are terminal and stop the automatic reconnect loop: `-2` (the token was revoked or regenerated) and `-12` (this SDK is below the backend's minimum wire version). Both emit [`disconnect`](https://docs.cloak.chat/api-reference/events#disconnect) rather than throwing from a call you can await. `-8` is transient and keeps retrying. See [Connection lifecycle](https://docs.cloak.chat/concepts/connection-lifecycle.md).

### watch

```ts theme={null}
watch(serverId: string, channelId: string, groupId?: string): Promise<void>
```

Optionally pre-selects a channel, for example to warm its key before your first send. You rarely need it, because the [firehose](https://docs.cloak.chat/concepts/message-delivery.md) already delivers every visible channel. `groupId` is auto-resolved from the server's channel list when omitted. The target is remembered and re-established after a reconnect.

### destroy

```ts theme={null}
destroy(): Promise<void>
```

Closes the connection, stops reconnecting, and flushes any queued keystore writes. The clean way to shut a bot down. See [Connection lifecycle](https://docs.cloak.chat/concepts/connection-lifecycle.md#shutting-down).

## Sending

### send

```ts theme={null}
send(serverId: string, channelId: string, text: string, opts?: SendOptions): Promise<void>
send(serverId: string, channelId: string, text: string, opts: SendOptions & { ack: true }): Promise<Message>
```

Sends an encrypted message to a channel. Sends are serialized internally so they never race each other. `opts.groupId` is auto-resolved for any channel the bot has already seen, so you usually omit it.

```ts theme={null}
import { userMention } from '@cloak-software/bot-sdk';

await client.send(serverId, channelId, `${userMention(msg.authorId)} on it`, {
  mentions: [{ userId: msg.authorId }],
  replyTo: msg,
});
```

[`SendOptions`](https://docs.cloak.chat/api-reference/types#sendoptions) is `{ groupId?, mentions?, replyTo?, poll?, threadId?, postId?, ack?, ackTimeoutMs? }`. Pass `threadId` to target a thread of the channel, `postId` to target a post of a forum channel, and `poll` to attach a native poll to the message. `threadId` and `postId` are mutually exclusive. See [Threads](https://docs.cloak.chat/guides/threads.md), [Forums](https://docs.cloak.chat/guides/forums.md), and [Polls](https://docs.cloak.chat/guides/polls.md).

> [!WARNING]
>
> The fourth argument is an options object. It was a positional `groupId` before 0.2.0, and that form is gone. `send(s, c, text, groupId)` becomes `send(s, c, text, { groupId })`.

> [!NOTE]
>
> `send()` is fire-and-forget by default. The wire has no success acknowledgement for it, so the promise resolves once the frame is out, and a server-side denial arrives later on the [`sendRejected`](https://docs.cloak.chat/api-reference/events#sendrejected) event. With `ack: true` the promise instead resolves with the persisted `Message` when the bot's own firehose echo lands, rejects with `CloakActionError` on a denial pinned to this send, and rejects with [`CloakSendTimeoutError`](https://docs.cloak.chat/api-reference/errors#cloaksendtimeouterror) when the outcome is indeterminate. See [Sending is fire-and-forget unless you ask for a receipt](https://docs.cloak.chat/concepts/message-delivery.md#sending-is-fire-and-forget-unless-you-ask-for-a-receipt).

The one local throw is a plain `Error` when your bot does not hold the server's conversation key yet, which happens in the moments right after a first join.

Most handlers use [`msg.reply()`](https://docs.cloak.chat/api-reference/types#message) or `msg.channel.send()` instead, which already know where the message came from. See [Sending messages](https://docs.cloak.chat/guides/sending-messages.md).

### sendDM

```ts theme={null}
sendDM(userId: string, text: string, opts?: SendOptions): Promise<void>
sendDM(userId: string, text: string, opts: SendOptions & { ack: true }): Promise<Message>
```

Sends an encrypted direct message, creating the DM and exchanging its conversation key on first contact. Both the dm id and the key are persisted in the keystore, so that cost is paid once per person.

Eligibility is the server's decision and it is deny-by-default: a human may hold a DM with a bot only if they own it, or they share at least one server with it. An ineligible target rejects with a [`CloakActionError`](https://docs.cloak.chat/api-reference/errors) before anything is encrypted.

Inside a DM, `replyTo` works, and role, `@everyone`, and `@here` mention pairs are dropped server-side. An `ack: true` DM send resolves on the DM lane's echo, which only a backend that honors wire version 3 delivers; on an older one it times out as indeterminate. See [Direct messages](https://docs.cloak.chat/guides/direct-messages.md).

### sendCardDM

```ts theme={null}
sendCardDM(userId: string, card: CardMessage): Promise<void>
sendCardDM(userId: string, card: CardMessage & { ack: true }): Promise<Message>
```

Posts a rich card into a direct message: [`sendCard()`](#sendcard) on the DM lane, set up exactly like [`sendDM()`](#senddm). The card takes the same v1 or v2 envelope, and `content` and the card are encrypted under the one peer-keyed DM key. `card.threadId` and `card.postId` are not valid here (a local error), `groupId` is ignored, and a bot cannot DM itself. Clicks arrive on [`interaction`](https://docs.cloak.chat/api-reference/events#interaction) with `serverId: null` and `channelId` equal to the dm id.

On a backend that honors wire version 3, the bot receives its own echo as a `messageCreate` whose `createdAt` is what `msg.editCard()` needs later. On an older backend only the legacy notify signal arrives, which has no card slot, so a DM message's `card` reads `null` there. See [Direct messages](https://docs.cloak.chat/guides/direct-messages.md#cards-in-a-dm).

### sendCard

```ts theme={null}
sendCard(serverId: string, channelId: string, card: CardMessage): Promise<void>
sendCard(serverId: string, channelId: string, card: CardMessage & { ack: true }): Promise<Message>
```

Posts a rich card. This is the **encrypted** embed lane and the one to reach for by default: the card is encrypted with the same conversation key and epoch as the message body, and it renders under your bot's own identity. It requires `message_send`, and current backends also enforce `embed_link`: the server cannot read the payload, but it can see that the embed slot is present, and a denial arrives as `-12` on [`sendRejected`](https://docs.cloak.chat/api-reference/events#sendrejected). Declare both in `requiredPermissions`.

`card.content` is required and must be non-blank. Card media must be Cloak-hosted, and anything else throws a `CloakEmbedError` locally before a frame leaves your process. `card.components` adds up to five rows of buttons and selects, and their clicks arrive on the [`interaction`](https://docs.cloak.chat/api-reference/events#interaction) event. `card.threadId` and `card.postId` place the card in a thread or a forum post. See [Rich cards](https://docs.cloak.chat/guides/rich-cards.md), [Buttons and selects](https://docs.cloak.chat/guides/components.md), and [Embeds](https://docs.cloak.chat/api-reference/embeds.md).

### editCard

```ts theme={null}
editCard(
  serverId: string | null,
  channelId: string,
  messageId: string,
  card: CardEdit,
  opts: { createdAt: Date; pinned?: boolean; groupId?: string; threadId?: string; postId?: string },
): Promise<void>
```

Replaces a message's card, embed and component rows together, and re-encrypts its text in one edit. Author-only server-side, like `edit()`. `CardEdit` is the `content`, `embed`, and `components` of a `CardMessage` without the routing keys. `opts.createdAt` is required, because the edit addresses the row by its send time; `msg.editCard(card)` on a received [`Message`](https://docs.cloak.chat/api-reference/types#message) fills the options for you. A `null` `serverId` with the dm id as `channelId` is the DM edit, under the DM key. Pass `components: []` to retire a card's buttons once a decision is made. The replacement arrives on [`messageUpdate`](https://docs.cloak.chat/api-reference/events#messageupdate) as `card`. See [Buttons and selects](https://docs.cloak.chat/guides/components.md#retire-the-controls) and [editCard](https://docs.cloak.chat/api-reference/embeds.md#editcard).

### sendEmbed

```ts theme={null}
sendEmbed(serverId: string, channelId: string, post: UnencryptedWebhookPost): Promise<void>
```

Posts a rich embed by minting or reusing a webhook for the channel. Requires `manage_server`.

> [!WARNING]
>
> This lane is **not** end-to-end encrypted. The message is stored as plaintext server-side and renders under a webhook identity, not your bot's. Your bot does not receive its own post back on `messageCreate`. Prefer [`sendCard()`](#sendcard) unless you need per-post personas, no bot account at all, or clients older than the card rollout. See [Webhook embeds](https://docs.cloak.chat/guides/webhook-embeds.md).

### sendCommand

```ts theme={null}
sendCommand(
  serverId: string,
  channelId: string,
  name: string,
  args?: CommandArgs,
  opts?: { botId: string; decl?: CommandDeclaration; groupId?: string; ack?: boolean; ackTimeoutMs?: number },
): Promise<void | Message>
```

Invokes a slash command, your bot's own or another bot's. `ack: true` resolves with the persisted invocation message, as on `send()`. `opts.botId` names the target bot and has no default. Targeting a foreign bot also requires `opts.decl`, because the SDK cannot know another bot's option order. Server channels only: there is no DM form. See [Slash commands](https://docs.cloak.chat/api-reference/commands.md).

### sendTyping

```ts theme={null}
sendTyping(serverId: string, channelId: string, isTyping?: boolean, target?: string | TypingTarget): Promise<void>
```

Shows or clears the typing indicator in a channel, a thread, or a forum post. `isTyping` defaults to `true`. `target` is the channel's group id as a string (the pre-0.5 form) or [`TypingTarget`](https://docs.cloak.chat/api-reference/types#typingtarget), `{ groupId?, threadId?, postId? }`: a thread of `channelId`, or a post of the forum `channelId`, one at most. The SDK never sends this implicitly, not even around `send()`.

Receivers clear the indicator themselves about ten seconds after the last `true`, so re-send it every few seconds during long work. A repeat of the same boolean for the same target inside about a second is dropped without touching the wire. It moves the server-side selection cursor exactly like a send to that target does (a thread is entered, a post becomes the cursor), and it is fire-and-forget. See [Typing, presence, and profile](https://docs.cloak.chat/guides/typing-presence-and-profile.md).

### fetchMessage

```ts theme={null}
fetchMessage(serverId: string | null, channelId: string, messageId: string, opts?: { signal?: AbortSignal }): Promise<Message>
```

Reads one message by id (op 804, a plan-136 backend). Explicitly addressed: `channelId` is the channel the message lives in, a thread or post id when inside one, or the dm id with `serverId` null. Needs `message_read_history`, which the server resolves against a container's parent. Rejects with `CloakActionError` on a verdict (`-5` is no such message) and with a transport timeout on an older backend. The row is a full history row, actionable like any other; `threadId` and `postId` are set when the SDK knows the container, so call [`resolveContainer()`](#resolvecontainer) first on a cold start. See [Message history](https://docs.cloak.chat/guides/message-history.md).

### resolveContainer

```ts theme={null}
resolveContainer(serverId: string, childId: string, opts?: { signal?: AbortSignal }): Promise<{ kind: 'thread' | 'post'; parentChannelId: string } | null>
```

Turns a thread or forum post id into its kind and parent channel (op 805, a plan-136 backend). Resolves `null` for a plain channel or an id that is not this server's, and rejects with `CloakActionError` when the bot is not a member. Seeds the SDK's container index, so `reply()`, `fetchMessage()` and the `Interaction` container fields route afterwards.

### capabilities

```ts theme={null}
capabilities(): BotCapabilities | null
```

What the backend declared at login: which of its optional behaviors this deployment has. `null` before `login()` and on a backend that predates the map, in which case treat every flag as false. See [BotCapabilities](https://docs.cloak.chat/api-reference/types.md#botcapabilities) and [What the server must support](https://docs.cloak.chat/production/backend-requirements.md).

### resumedLastLogin

```ts theme={null}
readonly resumedLastLogin: boolean
```

`true` when the last reconnect was a resume: the backend replayed every frame the dropped socket missed before the login reply, so nothing was lost and no history backfill is needed. `false` on a first login and on a full rebuild. See [Connection lifecycle](https://docs.cloak.chat/concepts/connection-lifecycle.md#recovering).

### sendTypingDM

```ts theme={null}
sendTypingDM(userId: string, isTyping?: boolean): Promise<void>
```

`sendTyping()` for a direct message with `userId`. First contact pays the same one-time DM setup as [`sendDM()`](#senddm). Same throttle, same fire-and-forget contract.

## Presence and profile

### setStatus

```ts theme={null}
setStatus(status: BotStatus): Promise<void>
```

Sets the bot's presence. `BotStatus` is `'invisible' | 'online' | 'away' | 'busy' | 'dnd'`. `dnd` also suppresses push notifications on every device.

This writes an account-level status to a database column, so it survives reconnects, restarts, and redeploys. Set it once on `ready`, never on a timer. Rejects with a [`CloakActionError`](https://docs.cloak.chat/api-reference/errors) if the server does not acknowledge it.

> [!NOTE]
>
> `online` means "defer to liveness" rather than "show a green dot". A bot with no live session displays as offline whatever its stored base says. The other four values pin the display outright.

### setAvatar

```ts theme={null}
setAvatar(iconUrl: string | null, miniIconUrl?: string | null): Promise<void>
```

Sets or clears the bot's avatar from an already-hosted image url. `miniIconUrl` defaults to `iconUrl`. Passing `null` clears both. Urls are capped at 512 characters server-side. The SDK does not upload avatar images, so give it a url that is already hosted. Attaching files to messages is a separate lane: see [`sendFile()`](#sendfile).

## History and reads

### fetchMessages

```ts theme={null}
fetchMessages(
  serverId: string | null,
  channelId: string,
  opts?: {
    before?: Date | Message;
    after?: Date | Message;
    around?: Date | Message;
    limit?: number;
    groupId?: string;
    threadId?: string;
    postId?: string;
    signal?: AbortSignal;
  },
): Promise<Message[]>
```

Reads message history for a channel, returned oldest to newest and auto-paginated. Each wire page is its own serialized action (the selection is re-established before every page and the chain is released between pages), and `signal` cancels between pages and the wait for the page in flight. Requires `message_read_history` on a server channel. Cursors are a `Date` or a `Message`, never a message id, because Cloak message ids are random UUIDs and not time-sortable. `around` returns a single window and is not auto-paged.

A `null` `serverId` with the dm id as `channelId` reads a **DM's** history, on a backend that honors wire version 3. The DM's peer must be known to this session (a message seen, or a send made, in it), else the call rejects and names [`fetchDmMessages()`](#fetchdmmessages) as the alternative. `threadId` and `postId` are rejected on the DM form. No permission gate applies, and a backend that denies the DM read resolves empty.

Content decrypts per row against the key for that row's own epoch, and is `''` (never raw ciphertext) when the key is missing. Returned messages are fully actionable and carry `pinned`. See [Message history](https://docs.cloak.chat/guides/message-history.md).

**threadId** `string`

Read this **thread's** history instead of the channel's. Address it exactly as [`send()`](#send) does: the thread's **parent** text channel as `channelId`, the thread id here. Every cursor above behaves identically over the thread's own messages, and the same `message_read_history` permission applies.

Returned rows carry `threadId` and `threadParentId`, and their `channelId` is the thread, matching how live thread messages report themselves. So `reply()`, `react()` and `edit()` on a fetched row act inside the thread rather than the parent channel.

**postId** `string`

Read a **forum post's** history instead. `channelId` is then the parent **forum** channel. Rows come back with `postId` and `forumChannelId` set and `channelId` equal to the post. Mutually exclusive with `threadId`. See [Forums](https://docs.cloak.chat/guides/forums.md).

```ts theme={null}
// Recover a thread's backlog after a restart.
const backlog = await client.fetchMessages(serverId, parentChannelId, {
  threadId,
  limit: 200,
});
```

> [!NOTE]
>
> Thread history needs a Cloak server that supports it. Against an older backend the call rejects rather than quietly returning the **parent channel's** messages, because that is what the wire falls back to. See [Known limitations](https://docs.cloak.chat/production/known-limitations.md).

### fetchDmMessages

```ts theme={null}
fetchDmMessages(
  userId: string,
  opts?: {
    before?: Date | Message;
    after?: Date | Message;
    around?: Date | Message;
    limit?: number;
    signal?: AbortSignal;
  },
): Promise<Message[]>
```

Reads a 1:1 DM's history by the peer's user id, on a backend that honors wire version 3. Resolves the dm the way [`sendDM()`](#senddm) does (cached, created on first contact) and reads it like `fetchMessages(null, dmId, opts)`: the same cursors and limits, oldest to newest, auto-paginated.

Rows decrypt under the peer-keyed DM key and carry `content`, `repliedTo`, `card`, `poll`, and `createdAt` from the row's own send time, with `isDM: true`, `serverId: null`, and `channelId` equal to the dm id. The bot's own messages are included, so a recovered row can be edited or have its card retired with `editCard()`. `command` is never set on a history row. No permission gate applies in a DM. See [Message history](https://docs.cloak.chat/guides/message-history.md#read-a-dms-history).

### messageLocation

```ts theme={null}
messageLocation(messageId: string): MessageLocation | undefined
```

Returns where a message the bot has seen lives, or `undefined`. This is a bounded, best-effort cache. See [MessageLocation](https://docs.cloak.chat/api-reference/types.md#messagelocation).

### fetchEmojis

```ts theme={null}
fetchEmojis(): Promise<{ emojis: unknown; category: unknown }>
```

Returns the global emoji catalog. It takes no `serverId` because the catalog is server-agnostic, and it does not move the selection cursor. Its ids are what [`msg.react()`](https://docs.cloak.chat/api-reference/types#message) accepts. `react()` itself stays an opaque pass-through with no client-side validation. See [Reactions](https://docs.cloak.chat/guides/reactions.md).

### fetchRoles

```ts theme={null}
fetchRoles(serverId: string): Promise<Role[]>
```

Reads a server's roles on demand, with no caching. Returns each role's color, position, and member count. See [Role](https://docs.cloak.chat/api-reference/types.md#role).

### fetchBans

```ts theme={null}
fetchBans(serverId: string): Promise<BanInfo[]>
```

Returns the server's ban list. Requires `member_ban`, and some older Cloak servers also require owner or admin standing. Usernames are resolved server-side and may be `null`. See [BanInfo](https://docs.cloak.chat/api-reference/types.md#baninfo).

### fetchMembers

```ts theme={null}
fetchMembers(serverId: string): Promise<Member[]>
```

> [!WARNING]
>
> **`fetchMembers()` does not work against any current Cloak backend. Do not call it.**
>
> It awaits an opcode the backend made DM-only. A server-scoped request produces no reply frame of any kind, not even an error code, so the returned promise waits out the transport's 8 second reply timeout and rejects with a plain `Error`. No roster ever arrives. This is not flakiness and not a permission problem.
>
> The rebuild is planned and the signature will survive it, so code written against this method stays valid. It just cannot run today. `guild().fetchMembers()` binds the same broken call. [`fetchRoles()`](#fetchroles) and [`searchMembers()`](#searchmembers) work.

Enumerates a server's members. See [Member](https://docs.cloak.chat/api-reference/types.md#member) and [Members and roles](https://docs.cloak.chat/guides/members-and-roles.md).

### searchMembers

```ts theme={null}
searchMembers(
  serverId: string,
  query: string,
  opts?: { channelId?: string; limit?: number; signal?: AbortSignal },
): Promise<MemberSearchResult[]>
```

Finds members by name: a case-insensitive prefix match over username, display name, and nickname, offline members included, at most 25 hits (`limit` is clamped to that). `channelId` restricts hits to members who can see that channel. Does not move the selection cursor. A blank query rejects locally, and a server that stays silent (the bot is not a member) rejects after 10 seconds with a message saying so. `guild().searchMembers(query, opts?)` binds it. See [MemberSearchResult](https://docs.cloak.chat/api-reference/types.md#membersearchresult) and [Search members by name](https://docs.cloak.chat/guides/members-and-roles.md#search-members-by-name).

## Files

End-to-end encrypted file attachments. These ride the REST lane (`client.rest`), which is off until the server operator enables bot REST credentials, and the grant write requires `upload_file`. See [File attachments](https://docs.cloak.chat/guides/file-attachments.md).

### sendFile

```ts theme={null}
sendFile(serverId: string, channelId: string, file: FileInput, opts?: SendFileOptions): Promise<void>
sendFile(serverId: string, channelId: string, file: FileInput, opts: SendFileOptions & { ack: true }): Promise<Message>
```

Encrypts and uploads the file, writes the share grant, then sends a message carrying its `[file:id:name]` token on the ordinary `send()` path. If the grant is refused, the upload is deleted and the call rejects, so a message never references an attachment nobody can open. [`FileInput`](https://docs.cloak.chat/api-reference/types#fileinput) is `{ name, bytes, contentType? }` and [`SendFileOptions`](https://docs.cloak.chat/api-reference/types#sendfileoptions) is `SendOptions & { text?, signal? }`, so `threadId`, `postId`, and `ack` all apply. With `ack: true` a denial pinned to the message deletes the upload; an indeterminate outcome leaves it. `sendFile()` is `sendFiles()` with one file.

### sendFiles

```ts theme={null}
sendFiles(serverId: string, channelId: string, files: FileInput[], opts?: SendFileOptions): Promise<void>
sendFiles(serverId: string, channelId: string, files: FileInput[], opts: SendFileOptions & { ack: true }): Promise<Message>
```

Several files under one message. Each is encrypted, uploaded, and granted in turn, and the message carries every token, which is how the Cloak clients attach several files. Any upload or grant failure deletes every blob uploaded so far and rejects, so a partial delivery never lands. `signal` cancels the upload and grant legs; the final send is never cancelled once it starts. See [File attachments](https://docs.cloak.chat/guides/file-attachments.md#send-several-files-in-one-message).

### sendFileDM

```ts theme={null}
sendFileDM(userId: string, file: FileInput, opts?: SendFileOptions): Promise<void>
sendFileDM(userId: string, file: FileInput, opts: SendFileOptions & { ack: true }): Promise<Message>
```

The DM twin of `sendFile()`. The file key is wrapped under the pairwise DM key and granted to the recipient. First contact pays the same one-time setup as [`sendDM()`](#senddm).

### sendFilesDM

```ts theme={null}
sendFilesDM(userId: string, files: FileInput[], opts?: SendFileOptions): Promise<void>
sendFilesDM(userId: string, files: FileInput[], opts: SendFileOptions & { ack: true }): Promise<Message>
```

`sendFiles()` on the DM lane.

### downloadAttachment

```ts theme={null}
downloadAttachment(fileId: string, serverId?: string | null, opts?: { signal?: AbortSignal }): Promise<{ bytes: Buffer }>
```

Downloads and decrypts an attachment referenced by [`msg.attachments`](https://docs.cloak.chat/api-reference/types#message). Pass the message's `serverId`; for a DM attachment that is `null`, which is correct.

## Threads

Threads fork out of text channels, and a thread's replies are ordinary messages whose channel is the thread. Send into one with `send(serverId, parentChannelId, text, { threadId })`, and read one with `fetchMessages(serverId, parentChannelId, { threadId })`. See [Threads](https://docs.cloak.chat/guides/threads.md) for the model and the thread permissions.

### createThread

```ts theme={null}
createThread(
  serverId: string,
  channelId: string,
  opts: {
    title: string;
    starter?: Pick<Message, 'messageId' | 'authorId' | 'createdAt'>;
    isPrivate?: boolean;
    autoArchiveMinutes?: number;
  },
): Promise<{ threadId: string }>
```

Creates a thread on a text channel. `title` is end-to-end encrypted and capped at 100 characters. Anchor it to an existing message by passing `starter` (a received `Message` fits); omit it for a standalone thread. Requires `create_public_thread`, or `create_private_thread` with `isPrivate`. `autoArchiveMinutes` is `0` (the channel default) or one of `60`, `1440`, `4320`, `10080`.

### fetchThreads

```ts theme={null}
fetchThreads(
  serverId: string,
  channelId: string,
  opts?: {
    sort?: 'activity' | 'created';
    includeArchived?: boolean;
    onlyMine?: boolean;
    onlyJoined?: boolean;
    before?: Date | number;
    limit?: number;
  },
): Promise<{ threads: ThreadInfo[]; hasMore: boolean }>
```

Pages a channel's threads, active first by default. Private threads are filtered to membership server-side, and `manage_threads` sees all. `before` continues a page from the previous page's oldest sort key.

> [!NOTE]
>
> This enumerates threads, not their contents. To read the messages inside one, pass its id to [`fetchMessages()`](#fetchmessages) as `opts.threadId`.

### joinThread

```ts theme={null}
joinThread(serverId: string, channelId: string, threadId: string): Promise<void>
```

Joins a thread, the "follow" surface. A firehose bot already receives every visible thread's messages either way. A private thread cannot be self-joined: its member list is the ACL, and someone inside must add the bot.

### leaveThread

```ts theme={null}
leaveThread(serverId: string, channelId: string, threadId: string): Promise<void>
```

Leaves a thread. Sending into it later auto-rejoins, Discord-parity.

### fetchThreadMembers

```ts theme={null}
fetchThreadMembers(serverId: string, channelId: string, threadId: string): Promise<ThreadMember[]>
```

A thread's member list: any viewer on public threads, members or `manage_threads` on private ones.

### threadParent

```ts theme={null}
threadParent(threadId: string): string | undefined
```

The parent text channel of a thread the SDK has seen, from its thread index. Synchronous and best-effort.

## Forums

Forum channels hold posts, and a post is a container like a thread: its replies are ordinary messages whose channel is the post. Send into one with `send(serverId, forumChannelId, text, { postId })`, and read one with `fetchMessages(serverId, forumChannelId, { postId })`. Every method below takes the parent forum channel id. See [Forums](https://docs.cloak.chat/guides/forums.md) for the model.

> [!NOTE]
>
> Forums add no [permission names](https://docs.cloak.chat/api-reference/permissions.md). Creating a post and sending inside one need `message_send`, resolved against the forum channel (which may override it per channel), so `can('message_send', serverId)` is the pre-check and `createForumPost()` denies `-2` without it. Moderating other members' posts (`editForumPost()`, `setForumPostState()`) needs `message_manage`. A refusal rejects with [`CloakActionError`](https://docs.cloak.chat/api-reference/errors#forum-posts).

### createForumPost

```ts theme={null}
createForumPost(
  serverId: string,
  forumChannelId: string,
  opts: {
    title: string;
    content: string;
    tagIds?: number[];
    embed?: BotEmbed;
    components?: ActionRow[];
    mentions?: MentionTarget[];
  },
): Promise<ForumPost>
```

Opens a post with its first message in one server-side operation. `title` is end-to-end encrypted and capped at 100 characters after trimming. `content` is the starter message and must be non-blank. `embed` and `components` make the starter a [card](https://docs.cloak.chat/guides/rich-cards.md). Title, body, and card encrypt under one context so they never split across an epoch change.

Resolves with the [`ForumPost`](https://docs.cloak.chat/api-reference/types#forumpost) as the server's own create event describes it, which is where `starterMessageId` comes from. If that event does not arrive within a few seconds, the row is built from what the SDK sent and `starterMessageId` is `null`; the real row lands on `forumPostUpdate` when it arrives.

### fetchForumPosts

```ts theme={null}
fetchForumPosts(
  serverId: string,
  forumChannelId: string,
  opts?: {
    sort?: 'activity' | 'created';
    tag?: number;
    includeArchived?: boolean;
    solved?: boolean;
    onlyMine?: boolean;
    onlyFollowing?: boolean;
    before?: Date | number;
    limit?: number;
    signal?: AbortSignal;
  },
): Promise<{ posts: ForumPost[]; hasMore: boolean }>
```

Pages a forum's posts, active first by default, with pinned posts at the front of the first page. `solved: true` keeps answered posts only, `false` unanswered only, and omitting it returns both. `before` continues from the previous page's oldest sort key (`lastActiveAt` for the activity sort, `createdAt` for the created sort). `limit` is clamped to 50 by the server. Rows carry `starterContent` and the bot's own `following` state.

### fetchForumMeta

```ts theme={null}
fetchForumMeta(serverId: string, forumChannelId: string): Promise<ForumMeta>
```

A forum's settings: its tags (names end-to-end encrypted, decrypted best-effort), guidelines, sort and archive defaults, default reaction, and post count. A forum created before it had a settings row answers defaults, never an error. See [ForumMeta](https://docs.cloak.chat/api-reference/types.md#forummeta).

### editForumPost

```ts theme={null}
editForumPost(
  serverId: string,
  forumChannelId: string,
  postId: string,
  changes: { title?: string; tagIds?: number[] },
): Promise<void>
```

Retitles or retags a post. Omit a field to keep it; omitting both is a local error. Author, or `message_manage`.

### setForumPostState

```ts theme={null}
setForumPostState(
  serverId: string,
  forumChannelId: string,
  postId: string,
  field: 'archived' | 'locked' | 'pinned' | 'answered' | 'move',
  value: boolean | string | Pick<Message, 'messageId' | 'authorId' | 'createdAt'> | null,
): Promise<void>
```

Flips one state on a post. `'archived'`, `'locked'`, and `'pinned'` take a boolean. `'answered'` takes the accepted answer (a received `Message` fits) or `null` to clear it. `'move'` takes the target forum channel id. Locking, pinning, and moving need `message_manage`; archiving and answering also allow the post's author. The wrong value type for a field is a local error.

### followForumPost

```ts theme={null}
followForumPost(serverId: string, forumChannelId: string, postId: string, on: boolean): Promise<void>
```

Follows or unfollows a post: the bell. A notification preference only. A firehose bot already receives every visible post's replies either way.

### reactToStarter

```ts theme={null}
reactToStarter(
  serverId: string,
  forumChannelId: string,
  postId: string,
  reactionId: string,
  add?: boolean,
): Promise<void>
```

Reacts to a post's starter message from outside the post, like the chips on a post's list card. `add` defaults to `true`. On a backend whose login capabilities say `starterReactionAck`, the call is awaited: it resolves on `[759, 1]` and rejects with `CloakActionError` on a verdict (see the 759 code table in [Errors](https://docs.cloak.chat/api-reference/errors.md)). On an older backend it stays fire-and-forget: the result is an ordinary `reactionUpdate`, and a denial produces no frame at all. Inside a post, `msg.react()` on the starter does the same thing.

### postParent

```ts theme={null}
postParent(postId: string): string | undefined
```

The parent forum channel of a post the SDK has seen, or `undefined`. Fed by every post row and every in-post message the bot receives. Synchronous and best-effort.

## Polls

Poll **creation** rides `send(serverId, channelId, text, { poll })`. The three methods below act on an existing poll and take the message's location, so a `Message`'s own ids are exactly what to pass. All three accept `threadId` or `postId` (never both) for a poll living inside a thread or a forum post. There is no vote method: the backend refuses a bot vote by design, so bots create, close, and read polls, and only humans vote. See [Polls](https://docs.cloak.chat/guides/polls.md).

### closePoll

```ts theme={null}
closePoll(
  serverId: string,
  channelId: string,
  messageId: string,
  opts?: { groupId?: string; threadId?: string; postId?: string },
): Promise<void>
```

Closes a poll now: creator or `message_manage`. Sets the close time to now and broadcasts the final tally, which doubles as the reveal for a hidden poll.

### fetchPollState

```ts theme={null}
fetchPollState(
  serverId: string,
  channelId: string,
  messageId: string,
  opts?: { groupId?: string; threadId?: string; postId?: string },
): Promise<PollStateSnapshot>
```

Reads a poll's current tally. Nothing fires server-side when a poll's end time passes, so a reader who wants the final (or hidden-poll) numbers asks, and this is the ask. Counts are `null` while a hidden poll is still open. The reply also fires [`pollUpdate`](https://docs.cloak.chat/api-reference/events#pollupdate).

### fetchPollVoters

```ts theme={null}
fetchPollVoters(
  serverId: string,
  channelId: string,
  messageId: string,
  optionIndex: number,
  opts?: { groupId?: string; threadId?: string; postId?: string },
): Promise<string[]>
```

Who picked one option of an identified poll. The refusals are the feature's promises, surfaced verbatim: an anonymous poll is never served, creator included, and a hidden poll refuses while still open.

## Moderation

All of these are server-scoped and reject with [`CloakActionError`](https://docs.cloak.chat/api-reference/errors) on a server deny. See [Moderation](https://docs.cloak.chat/guides/moderation.md).

### kick

```ts theme={null}
kick(serverId: string, userId: string): Promise<void>
```

Removes a member. Requires `member_kick`, a rank above the target, and the target not being the owner or the bot itself.

### ban

```ts theme={null}
ban(serverId: string, userId: string, reason?: string): Promise<void>
```

Kicks a member and records the ban. Requires `member_ban`. `reason` is capped at 256 characters server-side.

### unban

```ts theme={null}
unban(serverId: string, userId: string): Promise<void>
```

Lifts a ban. Requires `member_ban`. Some older Cloak servers also require owner or admin standing.

### timeout

```ts theme={null}
timeout(serverId: string, userId: string, durationSeconds: number): Promise<void>
```

Times a member out for `durationSeconds`. A timed-out member cannot send or react in that server. Passing `0` lifts the timeout. Requires `member_timeout`.

> [!NOTE]
>
> `timeout()` needs an up-to-date Cloak server. An older server drops the opcode, so the call times out rather than resolving.

### removeTimeout

```ts theme={null}
removeTimeout(serverId: string, userId: string): Promise<void>
```

Lifts a member's timeout. Equivalent to `timeout()` with `0` seconds.

## Channels and groups

Reading the channel list needs no permission beyond being able to see the server. Every method from [`createChannel`](#createchannel) down requires `manage_channels`. All of them reject with [`CloakActionError`](https://docs.cloak.chat/api-reference/errors) on a server deny. See [Channels and groups](https://docs.cloak.chat/guides/channels-and-groups.md).

### fetchChannels

```ts theme={null}
fetchChannels(serverId: string): Promise<ChannelInfo[]>
```

Lists a server's channels in the server's own order. Each entry is a [`ChannelInfo`](https://docs.cloak.chat/api-reference/types#channelinfo), carrying `id`, `name`, `groupId`, `type`, `order`, and `lastMessageAt`.

Compare `type` against [`ChannelType`](https://docs.cloak.chat/api-reference/types#channeltype) to tell a text channel from a voice one.

```ts theme={null}
import { ChannelType } from '@cloak-software/bot-sdk';

const channels = await client.fetchChannels(serverId);
const voice = channels.filter((c) => c.type === ChannelType.VOICE);
const general = channels.find((c) => c.name === 'general');
```

The list is filtered server-side to the channels your bot may view, so a channel that is absent is one the bot cannot see rather than one that does not exist. A server with no channels at all resolves to an empty array rather than rejecting.

This fetches rather than reading a cache, and deliberately so: the channel list arrives as a server push that carries no server id, so the call issues the selection itself and attributes the rows it gets back to that server. It also seeds `getChannel()`.

### getChannel

```ts theme={null}
getChannel(serverId: string, channelId: string): ChannelInfo | undefined
```

One channel from the cache, read synchronously, or `undefined`. The cache is seeded by `fetchChannels()` and kept current by `createChannel()` and the [channel lifecycle events](https://docs.cloak.chat/api-reference/events.md#channelcreate), so a hit is accurate.

A miss is not proof the channel does not exist, only that the bot has not seen it yet. Call `fetchChannels()` when you need an authoritative answer.

### createChannel

```ts theme={null}
createChannel(serverId: string, name: string, groupId: string, channelType?: number): Promise<string>
```

Creates a channel in a group and returns the new channel's id. `channelType` defaults to `0`, a text channel; pass a [`ChannelType`](https://docs.cloak.chat/api-reference/types#channeltype) value such as `ChannelType.VOICE` for anything else. The new channel is added to the [`getChannel()`](#getchannel) cache.

### editChannel

```ts theme={null}
editChannel(serverId: string, channelId: string, groupId: string, newName: string): Promise<void>
```

Renames a channel.

### deleteChannel

```ts theme={null}
deleteChannel(serverId: string, channelId: string, groupId: string): Promise<void>
```

Deletes a channel along with its messages and pins.

### moveChannel

```ts theme={null}
moveChannel(
  serverId: string,
  channelId: string,
  fromGroupId: string,
  toGroupId: string,
  newOrder: number,
): Promise<void>
```

Moves a channel to a group and position. `newOrder` is clamped to the range `0` to `126`. Moving to the same group and order is a no-op the server rejects.

### createGroup

```ts theme={null}
createGroup(serverId: string, name: string): Promise<string | undefined>
```

Creates a channel group. The acknowledgement carries no id, so the new group's id is captured best-effort from the server's create broadcast within a short window. Handle the `undefined` case.

### editGroup

```ts theme={null}
editGroup(serverId: string, groupId: string, newName: string): Promise<void>
```

Renames a group.

### deleteGroup

```ts theme={null}
deleteGroup(serverId: string, groupId: string): Promise<void>
```

Deletes a group and its channels.

> [!NOTE]
>
> There are no methods to edit or delete a server. Those actions are owner-level and surface only as the [`serverUpdate`](https://docs.cloak.chat/api-reference/events#serverupdate) and [`serverDelete`](https://docs.cloak.chat/api-reference/events#serverdelete) events.

## Voice

This is the control plane. It mints a LiveKit credential and stops there. The SDK sends no media of its own. See [Voice overview](https://docs.cloak.chat/voice/overview.md).

### joinVoice

```ts theme={null}
joinVoice(
  serverId: string,
  channelId: string,
  opts?: { groupId?: string; muted?: boolean; deafened?: boolean },
): Promise<VoiceConnection>
```

Joins a voice channel and returns the [`VoiceConnection`](https://docs.cloak.chat/api-reference/types#voiceconnection) the backend minted, including the LiveKit token and url. Requires `voice_connect` server-wide plus channel-level view.

`opts.groupId` must be the channel's real group and must never equal the channel id. That shape is Cloak's DM-call form, and the SDK refuses it locally rather than round-tripping a rejection. The group is resolved from the server's channel list when omitted.

> [!WARNING]
>
> `voice_connect` gets your bot into the channel. Hearing anyone is a separate grant, `voice_listen`. Without it the bot joins and publishes normally, receives no media, and is never given a key that could decrypt anyone. `joinVoice()` deliberately does not gate on it, so the failure mode is total silence with no error. See [Voice keys](https://docs.cloak.chat/voice/keys.md).

### leaveVoice

```ts theme={null}
leaveVoice(): Promise<void>
```

Leaves voice. A safe no-op server-side when the bot is not in a channel, so you may call it defensively.

### voiceConnection

```ts theme={null}
voiceConnection(): VoiceConnection | null
```

The bot's own voice membership, or `null`. A synchronous cache read.

### voiceConnectionReporter

```ts theme={null}
voiceConnectionReporter(): (state: 0 | 1) => void
```

The connection-state sender a `VoiceMediaSession` needs. Pass the result as `VoiceMediaOptions.connectionReporter` on every `attach()`. On a current backend the report a server-voice session sends before it publishes is what admits the microphone, and `attach()` waits for that admission (bounded by `admissionTimeoutMs`) before publishing. A session without the reporter skips the wait and is silent with no error. No-op when the bot is not in voice or is in a DM call, and it never throws. See [Microphone admission](https://docs.cloak.chat/voice/audio.md#microphone-admission).

### setVoiceSelfState

```ts theme={null}
setVoiceSelfState(state: { muted?: boolean; deafened?: boolean }): Promise<void>
```

Sets the bot's own mute and deafen flags. Requires a live join. The server never acknowledges this, so local state is updated optimistically. Deafened implies muted, mirroring both shipped Cloak clients.

> [!NOTE]
>
> `selfDeafened` is a broadcast flag, not an answer to "can I hear". Whether the bot receives audio is decided by `voice_listen` and the scope of the voice key it was handed.

### voiceRoster

```ts theme={null}
voiceRoster(channelId: string): VoiceParticipant[]
```

The cached roster of a voice channel, read synchronously. The array is a fresh copy, but its entries are the live cache objects, so copy them if you need a snapshot.

### refreshVoiceRoster

```ts theme={null}
refreshVoiceRoster(serverId: string): Promise<void>
```

Re-seeds the roster for a server by re-selecting it, because the roster snapshot is a side effect of that selection.

> [!NOTE]
>
> Voice roster events are cursor-gated, not [firehose](https://docs.cloak.chat/concepts/message-delivery.md). Your bot sees them only for the server it currently has selected or is in voice in. Do not build on them as a firehose.

## Permissions

These are advisory. They reflect the last grant the server sent, and the server re-checks every action. See [Permissions](https://docs.cloak.chat/concepts/permissions.md).

### can

```ts theme={null}
can(permission: PermissionName, serverId: string): boolean
```

Whether your bot holds `permission` in `serverId` per the last grant. `administrator` implies every permission here. Returns `false` when no grant has arrived yet, so a `false` means "not permitted, or not known yet".

### permissions

```ts theme={null}
permissions(serverId: string): PermissionSet | undefined
```

The full resolved capability set for a server, or `undefined` when no grant has arrived. See [PermissionSet](https://docs.cloak.chat/api-reference/permissions.md#permissionset).

### visibleChannelIds

```ts theme={null}
visibleChannelIds(serverId: string): string[]
```

The channel ids your bot may view in a server. Mirrors the [firehose read-gate](https://docs.cloak.chat/concepts/message-delivery.md#delivery-is-view-gated). Empty array if unknown.

## Encryption helpers

You need these only when you are building a frame by hand through [`client.raw`](#properties).

### encryptFor

```ts theme={null}
encryptFor(serverId: string, text: string): string
```

Encrypts text for a server's current epoch key, producing exactly what `send()` would put on the wire. Throws when the bot holds no key for that server.

### decryptFrom

```ts theme={null}
decryptFrom(serverId: string, wire: string): string
```

Decrypts a wire ciphertext with the key for its own epoch. Returns `''`, never raw ciphertext, when the key is missing or stale.

## Events

`Client` extends Node's `EventEmitter`, and `on`, `once`, `off`, `addListener`, `prependListener`, `prependOnceListener`, `removeListener`, and `emit` all carry typed overloads over [`ClientEvents`](https://docs.cloak.chat/api-reference/events). Your listener arguments are inferred.

```ts theme={null}
client.on('messageCreate', (msg) => {
  // msg is typed as Message
});
```

Listeners are wrapped at registration so a handler that throws surfaces on the [`error`](https://docs.cloak.chat/api-reference/events#error) event instead of vanishing. That means `client.listeners(event)` returns the wrappers rather than your original functions. `off()` and `removeListener()` still work normally: pass the same function you registered.

## guild

```ts theme={null}
guild(serverId: string)
```

Returns a lightweight handle that binds `serverId` onto every server-scoped method. Pure sugar over the flat methods, with no cache and no state.

```ts theme={null}
if (msg.isDM || !msg.serverId) return; // serverId is null in a DM

const g = client.guild(msg.serverId);
await g.timeout(msg.authorId, 300);
const roles = await g.fetchRoles();
const history = await g.fetchMessages(msg.channelId, { limit: 100 });
```

The handle exposes `id`, plus:

| Group | Bound methods |
| - | - |
| Messaging | `send(channelId, text, opts?)`, `sendCard(channelId, card)`, `sendEmbed(channelId, post)` (`sendDM` and `sendCardDM` take no server and stay on the client) |
| History | `fetchMessages(channelId, opts?)` |
| Moderation | `kick`, `ban`, `unban`, `timeout`, `removeTimeout`, `fetchBans` |
| Reads | `fetchRoles()`, `fetchMembers()` |
| Channels | `fetchChannels()`, `getChannel(channelId)`, `createChannel`, `editChannel`, `deleteChannel`, `moveChannel`, `createGroup`, `editGroup`, `deleteGroup` |
| Voice | `joinVoice(channelId, opts?)`, `refreshVoiceRoster()` |
| Webhooks | `webhooks.list`, `.create`, `.edit`, `.regenerate`, `.delete`, `.post` |
| Permissions | `can(perm)`, `permissions()`, `visibleChannelIds()` |

> [!WARNING]
>
> `guild().fetchMembers()` binds the same broken call as [`fetchMembers()`](#fetchmembers) and hangs the same way.

The handle does not bind the forum methods or `editCard()`. Call those on the client with the server id.

See [The guild() handle](https://docs.cloak.chat/guides/guild-handle.md).

## Exported constants

**DEFAULT\_URL** `string`

Cloak's hosted WebSocket endpoint, used when you omit `url`.

**DEFAULT\_WEBTRANSPORT\_URL** `string`

Cloak's hosted WebTransport endpoint, used when you omit `url` and set `transport: 'webtransport'`.

**DEFAULT\_REST\_URL** `string`

The default origin for [`client.rest`](#properties).

**livekitUrlFor** `(transportUrl: string) =\> string`

Derives the LiveKit signalling url from a transport url: same host, port 7880. Returns `''` for an unparseable url. This is what `livekitUrl` defaults to.

## Next

> [card] [Events](https://docs.cloak.chat/api-reference/events.md)
>
> All 39 events a Client emits.

> [card] [Types](https://docs.cloak.chat/api-reference/types.md)
>
> Message, SendOptions, Member, and the rest.

> [card] [Errors](https://docs.cloak.chat/api-reference/errors.md)
>
> Every error class an action can reject with.

> [card] [The guild() handle](https://docs.cloak.chat/guides/guild-handle.md)
>
> Bind a server id once.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.