# Status and presence

> Set the bot's status, activity and custom status text, at start or from a handler, and follow other members' presence.

Every member sees a bot's presence next to its name, as they see anyone's: a **status** (online,
idle, do not disturb) and an **activity**, what it is doing: "Playing chess", "Listening to lofi
radio", "Watching the queue". A bot can also set a **custom status text**: short text with an
emoji, kept by the host until the bot changes it or it expires.

Setting its own presence and status text needs no capability: it only describes the bot itself.
Receiving other members' presence needs the `presence` capability.

## Setting the status and activity

Set it when the instance starts: presence is not kept across restarts, and a bot starts `online`
without an activity.

**TypeScript:**

```ts

const bot = new Bot();

bot.on('init', () =>
  bot.presence.set('online', Activity.listening('lofi radio').setState('ChilledCow')),
);

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

**Rust:**

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

#[derive(Default)]
struct Dj;

impl Bot for Dj {
    fn on_start(&mut self, _: &Config) {
        presence::set(Status::Online, Activity::listening("lofi radio").state("ChilledCow"));
    }
}

export_bot!(Dj);
```

`init` (TypeScript) and `on_start` (Rust) run each time the instance starts, before its commands
register. The [ping example](/docs/examples/ping/) shows "Listening to /ping" this way.

### Statuses

| TypeScript | Rust | Members see |
|---|---|---|
| `'online'` | `Status::Online` | online |
| `'idle'` | `Status::Idle` | idle (away) |
| `'dnd'` | `Status::Dnd` | do not disturb |
| `'invisible'` | `Status::Invisible` | offline, with no activity |

A bot shows as offline when it stops, crashes or is disabled.

### Activities

**TypeScript:**

| Activity | Members see |
|---|---|
| `Activity.playing('chess')` | Playing chess |
| `Activity.streaming('speedrun', 'https://video.example.org/live')` | Streaming speedrun, with a link |
| `Activity.listening('lofi radio')` | Listening to lofi radio |
| `Activity.watching('the queue')` | Watching the queue |
| `Activity.competing('the cup')` | Competing in the cup |
| `Activity.custom('Taking requests').setEmoji('🎵')` | 🎵 Taking requests |

Add a second and third line with `setDetails(..)` and `setState(..)`, and an elapsed time with
`setStartedAt(ms)` (ms since the epoch). Each returns a new `Activity`.

**Rust:**

| Activity | Members see |
|---|---|
| `Activity::playing("chess")` | Playing chess |
| `Activity::streaming("speedrun", "https://video.example.org/live")` | Streaming speedrun, with a link |
| `Activity::listening("lofi radio")` | Listening to lofi radio |
| `Activity::watching("the queue")` | Watching the queue |
| `Activity::competing("the cup")` | Competing in the cup |
| `Activity::custom("Taking requests").emoji("🎵")` | 🎵 Taking requests |

Add a second and third line with `.details(..)` and `.state(..)`, and an elapsed time with
`.started_at(ms)` (ms since the epoch).

A streaming link is `https://` only, and a member's app opens it only after the member confirms.
Activities carry no pictures and no other links, so showing one never makes an app fetch anything.

To clear the activity, set the status alone: `bot.presence.set('online')` in TypeScript,
`presence::set(Status::Online, None)` in Rust.

## Changing it from a handler

A bot can change its presence at any time: when a command runs, when a track starts, on a timer.

**TypeScript:**

```ts

const bot = new Bot();

bot.command(
  new SlashCommandBuilder().setName('focus').setDescription('Do not disturb for a while'),
  (interaction) => {
    bot.presence.set('dnd', Activity.custom('Focusing').setEmoji('🎧'));
    interaction.reply('Do not disturb is on.');
  },
);

bot.on('trackStart', (title) => bot.presence.set('online', Activity.listening(title ?? 'music')));
bot.on('trackEnd', () => bot.presence.set('online'));

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

`bot.presence` works everywhere. In an event listener, `ctx.setPresence(status, activity?)` and
`ctx.setStatusText(text)` do the same.

**Rust:**

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

#[derive(Default)]
struct Focus;

impl Bot for Focus {
    fn commands(&mut self, _: &Config) -> Vec<ApplicationCommand> {
        vec![SlashCommand::new("focus", "Do not disturb for a while").build()]
    }

    fn on_command(&mut self, ctx: Context, command: CommandData) {
        if command.name == "focus" {
            ctx.set_presence(Status::Dnd, Activity::custom("Focusing").emoji("🎧"));
            let _ = ctx.reply("Do not disturb is on.");
        }
    }
}

export_bot!(Focus);
```

`zaun_bot::presence::set` works everywhere, including event handlers. In an interaction handler,
`ctx.set_presence(status, activity)` and `ctx.set_status_text(text)` do the same.

The [music example](/docs/examples/music/) shows "Listening to" the current track while it plays.

**Rate.** The host shows at most one change every 3 seconds. Set it as often as you like: a newer
call replaces one that has not gone out yet, so the latest always wins.

## Custom status text

**TypeScript:**

```ts
bot.presence.setStatusText('Type /play');          // kept until changed
bot.presence.setStatus('Back soon', '☕', until);   // text, emoji, and when the host clears it
bot.presence.clearStatus();
```

**Rust:**

```rust
use zaun_bot::presence;

presence::set_status_text("Type /play")?;                          // kept until changed
presence::set_status(Some("Back soon"), Some("☕"), Some(until))?;  // text, emoji, and when the host clears it
presence::clear_status()?;
```

`until` is a time in ms since the epoch; leave it out to keep the status until it changes. Unlike
presence, the host **keeps** a custom status: it survives restarts. These calls go to the host
and return its refusal (TypeScript throws a `ZaunError`; Rust returns a `HostError`), for example
for text that is too long.

## Other members' presence

Ask for the `presence` event group and the `presence` capability:

```toml title="zaun-bot.toml"
events = ["presence"]

[capabilities]
presence = true   # receive other members' status and activity
```

**TypeScript:**

```ts
bot.on('presenceUpdate', (p, ctx) => {
  // p: { memberId, status, activity? }
  if (ctx.isMe(p.memberId)) return;
  if (p.activity?.kind === 'listening') {
    bot.log.info(`${p.memberId} is listening to ${p.activity.name}`);
  }
});
```

**Rust:**

```rust
use zaun_bot::prelude::*;
use zaun_bot::presence::ActivityType;
use zaun_bot::types::Presence;

#[derive(Default)]
struct Watcher;

impl Bot for Watcher {
    fn on_presence_update(&mut self, ctx: EventContext, p: Presence) {
        if ctx.is_me(&p.member_id) {
            return;
        }
        if let Some(a) = p.activity.filter(|a| a.kind == ActivityType::Listening) {
            log_info!("{} is listening to {}", p.member_id, a.name);
        }
    }
}

export_bot!(Watcher);
```

`status` is `online`, `idle`, `dnd` or `offline`: invisible members arrive as `offline`, with no
activity. The activity has the same fields a bot sets: `kind` (`playing`, `streaming`,
`listening`, `watching`, `competing` or `custom`), `name`, and optionally `details`, `state`,
`url` (streaming), `startedAt` / `started_at` and `emoji` (custom).

Other members' custom status text is not part of what a bot receives.

## Limits

| Item | Limit |
|---|---|
| Activity name | 1–128 characters |
| Activity details, state | 0–128 characters each |
| Streaming link | `https://` only, streaming activities only |
| Activity emoji | one Unicode emoji (≤ 64 bytes), custom activities only |
| Custom status text | 1–128 characters of plain text, plus an optional emoji |
| Presence changes shown | one every 3 s; the latest wins |

An activity outside these limits is not shown.
