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

# Reactions

> Add and remove reactions on server messages, and listen for reaction changes.

Your bot can react to any server message it can see, remove its own reaction, and hear when reactions change anywhere it is watching. Reactions are keyed by an opaque `reactionId`: a unicode emoji for the common case, or a custom emoji id for server-specific emoji. This page covers both sides, adding reactions and listening for them.

> [!WARNING]
>
> `react()` and `unreact()` on a direct message need a backend that honors wire version 3, which is what gives a DM message its `createdAt`. On an older backend a DM message carries no timestamp and both reject with a plain `Error` saying so, before a frame is built. Direct messages arrive on the same `messageCreate` event as server messages, so guard every handler that does server-scoped work. See [Direct messages](https://docs.cloak.chat/guides/direct-messages.md#what-a-wire-version-3-backend-adds).

## Add a reaction

Call `msg.react(reactionId)` on a `Message` to add the bot's reaction. It returns `Promise<void>` and requires the `reaction_add` permission. For a plain emoji, pass the unicode character directly.

```ts theme={null}
client.on('messageCreate', (msg) => {
  if (msg.authorId === client.user?.id) return; // ignore our own messages
  if (msg.isDM || !msg.serverId) return; // can() needs a server id
  if (msg.content.trim() !== '!celebrate') return;
  if (!client.can('reaction_add', msg.serverId)) return; // advisory pre-gate
  msg.react('🎉').catch((e) => console.error('react failed', e));
});
```

The `if (msg.isDM || !msg.serverId) return;` guard narrows `msg.serverId` from `string | null` to `string` so `can()` accepts it, since a permission grant is a server concept. Without it, TypeScript rejects the `can()` call and plain JavaScript silently returns false for a null server. A bot that also reacts inside DMs skips `can()` on that branch and calls `msg.react()` directly.

The `reactionId` is opaque. The SDK does not validate it and passes it straight through to the server. An invalid id is refused by the server, not caught locally.

## Remove the bot's reaction

Call `msg.unreact(reactionId)` to remove the bot's own reaction from a message. It only affects the reaction the bot added, not anyone else's.

```ts theme={null}
await msg.react('👀');
// later, once the bot is done looking
await msg.unreact('👀');
```

## React with a custom emoji

For a server's custom emoji, pass its id instead of a unicode character. Get ids from `client.fetchEmojis()`, which returns `Promise<{ emojis, category }>`, the global emoji catalog. Its ids are exactly the custom-emoji ids that `react()` accepts.

```ts theme={null}
const { emojis, category } = await client.fetchEmojis();
// The shape of emojis and category is server-defined. Treat the catalog
// as data you look an id up in, then hand that id to react().
const partyId = findEmojiId(emojis, 'party_blob');
await msg.react(partyId);
```

> [!NOTE]
>
> The shape of `emojis` and `category` is defined by the server, so treat them as data to look ids up in rather than a fixed structure.

## Listen for reaction changes

The `reactionUpdate` event fires when a reaction is added or removed on a message your bot can see. It is not scoped to a channel you selected: on a current Cloak server it arrives for every server the bot is in, the same way `messageCreate` does. Filter on `channelId` if you care about one place.

```ts theme={null}
client.on('reactionUpdate', ({ messageId, reactionId, count, operation, userId, serverId, channelId }) => {
  if (channelId !== watchedChannelId) return;
  console.log(`${reactionId} on ${messageId} is now at ${count} (${operation})`);
});
```

**messageId** `string`

The message whose reactions changed.

**reactionId** `string`

The reaction that changed, the same opaque id you pass to `react()`.

**count** `number`

The new total for that reaction on the message. The wire carries only this total, never an add-or-remove flag.

**operation** `'add' | 'remove' | 'unknown'`

Inferred by comparing `count` with `previousCount`. `'unknown'` when the SDK has no earlier count for this message and reaction (the first hook for it since the bot started, or an evicted entry) or when the total did not change.

**previousCount** `number | null`

The last total this session saw for the same message and reaction, or `null`.

**userId** `string`

The user who added or removed the reaction.

**serverId** `string`

The server the message belongs to.

**channelId** `string`

The channel the message belongs to.

Because `count` is the new total and the wire includes no add-or-remove flag, `operation` is only as good as the SDK's memory of the previous total. It is exact for any reaction the bot has watched since it started; the first hook for a reaction after a restart reads `'unknown'`. Treat the event as "this reaction now has this many", and use `operation` when a direction is needed and `'unknown'` is acceptable.

### Filter out the bot's own reactions

`reactionUpdate` fires for the bot's own reactions too, including the ones it adds with `react()`. When that matters, filter on `userId`.

```ts theme={null}
client.on('reactionUpdate', (evt) => {
  if (evt.userId === client.user?.id) return; // skip our own reactions
  console.log(`someone reacted with ${evt.reactionId}`);
});
```

> [!NOTE]
>
> On an older Cloak server, `serverId` and `channelId` on `reactionUpdate` can fall back to the bot's currently selected server and channel. An up-to-date Cloak server always reports the message's own location.

## React to being mentioned

A reaction acknowledges something without adding a message to the channel, which makes it a good pairing with `msg.mentionsMe`.

```ts theme={null}
client.on('messageCreate', (msg) => {
  if (msg.isDM || !msg.serverId) return;
  if (!msg.mentionsMe) return;
  if (!client.can('reaction_add', msg.serverId)) return;
  msg.react('👍').catch((e) => console.error('react failed', e));
});
```

See [Mentions and replies](https://docs.cloak.chat/guides/mentions-and-replies.md) for what `mentionsMe` does and does not cover.

## Handling errors

Three different failures are worth telling apart.

> [accordion] Plain Error, before the wire
>
> `react()` and `unreact()` reject with a plain `Error` when the message has no `createdAt`, which the server needs to locate the row. Live server messages and messages loaded with `fetchMessages` always carry it. A DM message carries it only on a backend that honors wire version 3, so in practice the case that comes up is a DM on an older backend.

> [accordion] CloakActionError, from the server
>
> Both methods reject with `CloakActionError` when the server refuses. Read `.code` for the reason and `.permission` for the missing permission when the code maps to one.
>
> | Code | Meaning |
> | - | - |
> | `-1` | Not authenticated |
> | `-2` | Server error while updating the reaction |
> | `-3` | No reaction to remove on that message |
> | `-4` | Reaction limit reached for that message |
> | `-5` | Message or reaction not found |
> | `-6` | Already reacted with that emoji |
> | `-7` | No existing reaction from you to remove |
> | `-8` | Missing `reaction_add` |
> | `-9` | Rate limited (bot reaction throttle) |
> | `-10` | The bot is timed out in this server |

> [accordion] A timeout on an older server
>
> Confirming a reaction needs a Cloak server new enough to send the bot a success acknowledgement. Against an older backend the call cannot confirm and times out even though the reaction landed. See [What the server must support](https://docs.cloak.chat/production/backend-requirements.md).

Pre-gate with `can('reaction_add', serverId)` to skip actions the server would only refuse, and still catch the promise for the cases you cannot predict.

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

try {
  await msg.react('👍');
} catch (err) {
  if (err instanceof CloakActionError) {
    console.error(`the server refused the reaction (${err.code}): ${err.message}`);
    if (err.permission) console.error(`missing ${err.permission}`);
  } else {
    console.error('could not react', err);
  }
}
```

## Next

> [card] [Editing, deleting, and pinning](https://docs.cloak.chat/guides/editing-and-pinning.md)
>
> The other four message actions, under the same DM rule.

> [card] [The Message object](https://docs.cloak.chat/api-reference/types.md#message)
>
> Every field and method a received message carries.

> [card] [Handling errors](https://docs.cloak.chat/guides/handling-errors.md)
>
> Working with `CloakActionError` and friends.

> [card] [Permissions](https://docs.cloak.chat/concepts/permissions.md)
>
> Why `reaction_add` must be granted first.


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