# Events

> Follow what happens in the community: messages, reactions, members, channels, roles, typing, presence and direct messages.

Beyond its own commands and components, a bot can follow what happens in the community. It gets
only what its manifest asks for, some groups need a capability the owner grants, and it only ever
sees events for channels it can view.

## Asking for events

In `zaun-bot.toml`, `events` lists groups, exact event types, or `*` for everything the
capabilities allow:

```toml title="zaun-bot.toml"
events = ["messages", "reactions", "members"]   # groups
# events = ["message.created", "member.joined"] # or exact types
# events = ["*"]                                # everything the capabilities allow

[capabilities]
members = true   # needed for the members group
```

| Group | Event types | Needs |
|---|---|---|
| `messages` | `message.created`, `message.updated`, `message.deleted`, `messages.bulk_deleted` | — |
| `reactions` | `reaction.added`, `reaction.removed` | — |
| `members` | `member.joined`, `member.updated`, `member.left`, `member.removed`, `member.roles_updated`, `member.timed_out` | capability `members` |
| `channels` | `channel.created`, `channel.updated`, `channel.deleted`, `channel.reordered` | — |
| `roles` | `role.created`, `role.updated`, `role.deleted`, `role.reordered` | — |
| `typing` | `signal.typing` | — |
| `presence` | `signal.presence` | capability `presence` |
| `community` | `community.updated` | — |
| `commands` | `command.updated` | — |
| `dms` | `dm.created`, `dm.closed` | capability `dms` |

**Message content.** Without the `message_content` capability, other members' messages arrive with
empty content, no embeds and no attachments, except messages that mention the bot, reply to it, or
are in a direct message with it. Every member can see on the bot card whether a bot reads all
messages.

## Handlers

The `ready` event always comes first, once the bot's connection is up, with its own ids and
community. Every handler gets an **event context** to act with.

**TypeScript:**

```ts

const bot = new Bot();

bot.on('ready', (me) => bot.log.info(`up as ${me.memberId}`));

bot.on('messageCreate', (message, ctx) => {
  if (ctx.isMe(message.authorId)) return; // never answer yourself
  if (message.content.includes('hello')) {
    ctx.react(message, '👋');
    ctx.reply(message, 'Hello!');
  }
  if (message.isDM) ctx.send(message.channelId, 'Thanks for writing.');
});

bot.on('memberAdd', (member, ctx) => {
  ctx.dm(member.memberId, 'Welcome!'); // capability `dms`
});

export const { init, onEvent, onInteraction, onAutocomplete, onTimer, onVoiceEvent } = bot.exports();
```

`init` runs earlier, when the instance starts; `ready` tells the bot who it is (`bot.me`).

**Rust:**

```rust
use zaun_bot::prelude::*;

#[derive(Default)]
struct Greeter;

impl Bot for Greeter {
    fn on_message_create(&mut self, ctx: EventContext, message: Message, is_dm: bool) {
        if ctx.is_me(&message.author_id) {
            return; // never answer yourself
        }
        if message.content.contains("hello") {
            let _ = ctx.react(&message, "👋");
            let _ = ctx.reply_to(&message, "Hello!");
        }
        if is_dm {
            let _ = ctx.send(&message.channel_id, "Thanks for writing.");
        }
    }

    fn on_member_join(&mut self, ctx: EventContext, member: Member) {
        let _ = ctx.dm(&member.member_id, "Welcome!"); // capability `dms`
    }
}

export_bot!(Greeter);
```

To see events before the typed handlers, override `on_event(ctx, event)`; call
`zaun_bot::dispatch(self, ctx, event)` to keep the typed handlers too.

## Every event

| TypeScript `bot.on(..)` | Rust handler | Group |
|---|---|---|
| `ready` | `on_ready` | always |
| `messageCreate`, `messageUpdate`, `messageDelete`, `messageDeleteBulk` (messages carry `isDM`) | `on_message_create`, `on_message_update`, `on_message_delete`, `on_message_delete_bulk` | `messages` |
| `messageReactionAdd`, `messageReactionRemove` | `on_reaction_add`, `on_reaction_remove` | `reactions` |
| `memberAdd`, `memberUpdate`, `memberRemove` | `on_member_join`, `on_member_update`, `on_member_leave` | `members` |
| `removed` (this bot was kicked or banned) | `on_removed` | `members` |
| `memberRolesUpdate`, `memberTimeout` | `on_member_roles_update`, `on_member_timeout` | `members` |
| `channelCreate`, `channelUpdate`, `channelDelete` | `on_channel_create`, `on_channel_update`, `on_channel_delete` | `channels` |
| `roleCreate`, `roleUpdate`, `roleDelete` | `on_role_create`, `on_role_update`, `on_role_delete` | `roles` |
| `typingStart` | `on_typing_start` | `typing` |
| `presenceUpdate` (`{ memberId, status, activity }`; see [Status and presence](/docs/guide/bots/status-and-presence/#other-members-presence)) | `on_presence_update` | `presence` |
| `communityUpdate` | `on_community_update` | `community` |
| `commandsUpdate` | `on_commands_update` | `commands` |
| `dmCreate`, `dmDelete` | `on_dm_open`, `on_dm_close` | `dms` |
| `raw` (anything without a typed event, such as `channel.reordered`) | `on_raw` | — |

TypeScript also has `interactionCreate`, `timer`, `voiceEvent` (and `trackStart`, `trackEnd`, …;
see [Voice and music](/docs/guide/bots/voice-and-music/)) and `error`.

## The event context

| TypeScript | Rust | Does |
|---|---|---|
| `ctx.send(channelId, reply)` | `ctx.send(channel_id, reply)` | posts a message |
| `ctx.reply(message, reply)` | `ctx.reply_to(&message, reply)` | posts a reply in the message's channel |
| `ctx.react(message, emoji)` | `ctx.react(&message, emoji)` | adds a reaction |
| `ctx.delete(message)` | `ctx.delete_message(&message)` | deletes it (the bot's own, or any with `MANAGE_MESSAGES`) |
| `ctx.dm(memberId, reply)` | `ctx.dm(member_id, reply)` | sends a [direct message](/docs/guide/bots/direct-messages/) |
| `ctx.isMe(memberId)` | `ctx.is_me(member_id)` | whether that is the bot itself |
| `ctx.setPresence(status, activity?)`, `ctx.setStatusText(text)` | `zaun_bot::presence::set(..)`, `presence::set_status_text(..)` | sets the bot's own [status and presence](/docs/guide/bots/status-and-presence/) |

Handlers run one at a time, so keep them short: long work blocks the bot's next events and
interactions. Every call is an ordinary command on the bot's member, checked by the host's
permission engine.

## Typing events and privacy

A channel's typing indicator can be `named`, `anonymous` or `off`
([Typing indicators](/docs/guide/concepts/typing-indicators/)). A bot subscribed to `typing` gets the
same shape a member's app would: names in a named channel, only a count in an anonymous one, and
nothing in a channel where typing is off.
