> ## 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.

# Members and roles

> Read a server's roles on demand, and what to do while the member roster read is out of service.

> [!WARNING]
>
> **`fetchMembers()` does not work against any current Cloak server.** The opcode it waits on became direct-message-only server-side, so a server-scoped request gets no reply frame at all, not even an error code. The promise waits out the transport's 8 second timeout and then rejects with a plain `Error`. `await` blocks your handler for the whole wait, and no roster ever arrives. For a name lookup use `searchMembers()`, below.
>
> This is not a permission problem, a flake, or something a retry fixes. There is no workaround inside the SDK. The signature will survive the rebuild, so code written against it stays valid, but it cannot run today. `fetchRoles()` is unaffected and works normally.

The `Client` has two on-demand server reads. `fetchRoles()` returns the server's roles, and it works. `fetchMembers()` returns the member roster, and it is currently out of service. Neither read caches, so each call goes to the server and gives you a point-in-time answer.

## Fetch the roles

`client.fetchRoles(serverId)` returns a `Promise<Role[]>`. It reads on demand and does not cache.

```ts theme={null}
const roles = await client.fetchRoles(serverId);
for (const role of roles) {
  console.log(`${role.name}: ${role.memberCount} members`);
}
```

Each entry describes one role in the server.

**id** `string`

The role's id.

**name** `string`

The role's name.

**color** `string | null`

The role's primary color, or `null` if none is set.

**secondColor** `string | null`

The role's secondary color, or `null` if none is set.

**position** `number | null`

The role's position, or `null` if unknown. Lower is higher in the list.

**memberCount** `number`

How many members hold this role.

### A !roles command

`fetchRoles()` is a server read, so guard the handler first. `Message.serverId` is `string | null` and is `null` for a direct message, which arrives on the same `messageCreate` event.

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

client.on('messageCreate', async (msg) => {
  if (msg.authorId === client.user?.id) return; // ignore our own messages
  if (msg.isDM || !msg.serverId) return;        // roles are server-scoped
  if (msg.content.trim() !== '!roles') return;

  try {
    const roles = await client.fetchRoles(msg.serverId);
    const lines = roles
      .sort((a, b) => (a.position ?? 99) - (b.position ?? 99))
      .map((r) => `${r.name} (${r.memberCount} members)`);
    await msg.channel.send(lines.length ? lines.join('\n') : 'This server has no roles.');
  } catch (err) {
    if (err instanceof CloakActionError) {
      await msg.channel.send(`Could not read roles: ${err.message}`);
    }
  }
});
```

The reply uses `msg.channel.send()`, a plain send. `msg.reply()` would post a true reply with a quote header and fire a "replied to you" notification, which is more than a command answer needs.

> [!NOTE]
>
> `msg.channel.send()` is fire-and-forget. Its promise resolves when the frame leaves the process, not when the server accepts it. A server-side denial arrives later on the `sendRejected` event, so listen for that if you need to know a send was refused.

## Counting members without fetchMembers()

`Role.memberCount` is the one live membership number a bot can read today. Summing it does not give you a server total, because a member holds at most one role and members with no role are counted nowhere, but it is enough for "how many people hold this role".

```ts theme={null}
const roles = await client.fetchRoles(serverId);
const moderators = roles.find((r) => r.name === 'Moderators');
console.log(`${moderators?.memberCount ?? 0} moderators`);
```

For per-person information, use what the firehose already hands you. Every `messageCreate` carries `msg.authorId` and `msg.authorName`, so a bot can build its own map of the people it has actually seen.

## Search members by name

`client.searchMembers(serverId, query, opts?)` works against every current server. It is a case-insensitive **prefix** match over username, display name, and nickname, at most 25 hits, offline members included. It is the cheap targeted lookup behind a `/whois alice` command, not enumeration.

```ts theme={null}
const hits = await client.searchMembers(serverId, 'ali', { limit: 5 });
for (const m of hits) {
  console.log(m.username, m.displayName, m.nickname, m.role?.name ?? 'no role');
}
```

**channelId** `string`

Restrict hits to members who can see this channel.

**limit** `number` (default: 25)

Clamped to the server's cap of 25.

**signal** `AbortSignal`

Cancel the wait.

Each hit is a [`MemberSearchResult`](https://docs.cloak.chat/api-reference/types#membersearchresult): `userId`, `username`, `displayName`, `nickname`, `icon`, `status`, `isBot`, `subscriptionTier`, `role` (the member's primary role, or `null`), and `onMobile`. The call does not move the selection cursor. A blank query rejects locally.

> [!WARNING]
>
> The server answers **nothing** when the bot is not a member of the server, so that case surfaces as a rejection after a 10 second wait, with a message that says so, rather than as an error code.

## The member roster read

`client.fetchMembers(serverId)` is declared as `Promise<Member[]>`. Do not call it against a live server. See the warning at the top of this page: the call waits out the transport's 8 second timeout and rejects, so a bot that reaches it stalls the handler that awaited it and gets no roster.

The shape is documented here so code you write now still compiles once the read is rebuilt.

**userId** `string`

The member's normalized id.

**username** `string`

The member's username.

**status** `number`

An online-status code. `0` means offline.

**createdAt** `Date | null`

When the account was created, when known. This is the account creation time, not the time the member joined this server. `null` when unknown.

**icon** `string | null`

The member's icon, or `null` if none is set.

**subscriptionTier** `number | null`

The member's subscription tier, or `null` if unknown.

**isBot** `boolean`

`true` if this member is a bot.

**role** `MemberRole | null`

The member's assigned role, or `null` if they have none. A `MemberRole` is `{ id, name, color, secondColor, admin }`, where `admin` is `true` when the role carries admin.

> [!WARNING]
>
> If you already ship a bot that calls `fetchMembers()`, the symptom is a handler that stalls for 8 seconds and then logs a timeout. Remove the call or put it behind a flag you leave off, and use `searchMembers()` for lookups by name.

## There is no live roster stream

These reads hit the server every time, so treat a result as a snapshot rather than a live view. Call again when you need current data.

Cloak has no continuous member-roster feed for a bot. The firehose carries messages, not membership. The one inbound membership signal is the `systemMessage` event with `type: 'member_join'`, which fires when someone joins a server the bot is in.

```ts theme={null}
client.on('systemMessage', async (evt) => {
  if (evt.type !== 'member_join') return;
  await client.send(evt.serverId, evt.channelId, `Welcome, ${evt.actorName}.`, {
    groupId: evt.groupId,
  });
});
```

`SystemMessageEvent` carries `actorId`, `actorName`, `serverId`, `channelId`, and an optional `groupId` resolved from the bot's channel-group cache. Pass `groupId` through in `SendOptions` so the send does not have to guess the channel's group.

The voice roster events are a separate thing and are not a firehose either. They reach a bot only for the server it currently has selected or is in voice in, so they are not a general membership feed.

## Read through the guild() handle

Both reads are bound on the `guild()` handle when you already have one for the server.

```ts theme={null}
const g = client.guild(serverId);
const roles = await g.fetchRoles();
```

> [!WARNING]
>
> `g.fetchMembers()` binds the same out-of-service read as the flat method and times out the same way. `g.fetchRoles()` and `g.searchMembers(query, opts?)` work.

See [The guild() handle](https://docs.cloak.chat/guides/guild-handle.md) for the rest of what the handle binds.

## Handle failures

`fetchRoles()` rejects with a `CloakActionError` when the server refuses the read or errors while serving it. Wrap it and decide what to do when the roles are not available.

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

try {
  const roles = await client.fetchRoles(serverId);
  console.log(`${roles.length} roles`);
} catch (err) {
  if (err instanceof CloakActionError) {
    console.error(`could not read roles: ${err.message}`);
  } else {
    throw err;
  }
}
```

The server decides whether your bot may read this data and is the authority on the result. A refused read rejects rather than returning a partial list.

`fetchMembers()` rejects with a plain `Error` naming the timed-out opcode, not a `CloakActionError`, so the `catch` above would rethrow it. `searchMembers()` rejects the same way when the server stays silent, with a message naming the likely cause.

## Next

> [card] [Types](https://docs.cloak.chat/api-reference/types.md)
>
> Every field on Role, Member, and MemberRole.

> [card] [Known limitations](https://docs.cloak.chat/production/known-limitations.md)
>
> What else is out of service, and what is tracked.

> [card] [The guild() handle](https://docs.cloak.chat/guides/guild-handle.md)
>
> The other way to reach these reads.

> [card] [Moderation](https://docs.cloak.chat/guides/moderation.md)
>
> Act on a member once you have their id.


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