# Dialogues

A dialogue is a multi-step flow, such as a form that asks for a name, then an age. Each step is a handler, and the
dialogue's state is kept in a storage, so with a persistent one the flow survives a restart.

## Example

```no_run
use std::time::Duration;

use vaegram::dialogue::{Dialogue, DialogueRouter, DialogueMemoryStorage};
use vaegram::prelude::*;

#[derive(Clone, PartialEq)]
enum Signup {
    Name,
    Age { name: String },
}

# fn setup(client: &Client) {
let mut signup = DialogueRouter::new("signup", DialogueMemoryStorage::new()).timeout(Duration::from_secs(600));

signup.on_message(filters::no_state(), filters::command("signup"), |msg, dlg: Dialogue<Signup>| async move {
    dlg.set(Signup::Name).await?;
    msg.reply("Your name?").await
});
let asked_name = filters::state_is(Signup::Name);
signup.on_message(asked_name, filters::text(), |msg, dlg| async move {
    dlg.set(Signup::Age { name: msg.text().to_owned() }).await?;
    msg.reply("Your age?").await
});
let asked_age = filters::state(|s: &Signup| matches!(s, Signup::Age { .. }));
signup.on_message(asked_age, filters::text(), |msg, dlg| async move {
    let Some(Signup::Age { name }) = dlg.state() else { return Ok(()) };
    let Ok(age) = msg.text().trim().parse::<u8>() else {
        msg.reply("Send your age as a number.").await?;
        return Ok(());
    };
    dlg.clear().await?;
    msg.reply(format!("Welcome, {name} ({age})!")).await?;
    Ok(())
});

client.include_router(signup.into_router());
# }
```

## How it works

### The state

The state is any `Clone + Send + Sync + 'static` type of yours, usually an enum with a variant per step carrying
what the earlier steps collected. `DialogueRouter<S>` and all its steps use the same type.

### Steps

`on_message(state_filter, update_filter, handler)` adds a step for messages, and `on_callback_query` for button
presses. A step runs when the update passes its `Filter` and the dialogue's state passes its state filter.
Steps are tried in order, only the first that matches runs, and an update no step takes goes on to the routes
after the dialogue (`src/dialogue/router.rs:255-272`).

Taking an update doesn't stop later groups: routes there still get it, so a catch-all would answer too.
`client.include_router(flow.into_router()).stop()` ends that, but only for updates a step took. A step that returns
an error goes to `on_error` and the later groups are skipped; a panic is reported as
`ClientEvent::HandlerPanicked` and leaves the dialogue usable.

The dialogue stays locked from loading its state until the step returns, so two quick messages from one user run
one after another. While an update waits for its turn it holds no handler slot, so other dialogues go on
(`src/dialogue/router.rs:267`).

### The `Dialogue` handle

The handler gets the update and a `Dialogue<S>`:

| Call | What it does |
|---|---|
| `state()` | The state (the getter), `None` when the dialogue has none. |
| `set(state)` | Moves to `state`, saved before the call returns. |
| `set_for(state, timeout)` | Like `set`, timing out after `timeout` whatever the dialogue's timeout. |
| `update(f)` | Changes the state with `f`, saved the same way; `false` when there is no state. |
| `clear()` | Ends the dialogue. |
| `is_active()`, `key()` | Whether there is a state, and the `DialogueKey` it is stored under. |

### State filters

`filters::state(|s| ...)` accepts a state the closure does, `filters::state_is(value)` a state equal to `value`
(the type needs `PartialEq`), `filters::any_state()` any state, and `filters::no_state()` none; combine them with
`&`, `|` and `!`. The state filter is separate from the update filter.

### Whose state

`Scope` picks what a dialogue's state is keyed by (`src/dialogue/key.rs:15-51`). The default, `Scope::UserInChat`,
keeps one state per user in each chat, so two members of a group each have their own. `Scope::Chat` shares one per
chat, `Scope::User` follows a user across chats, and `Scope::UserInTopic`/`ChatTopic` add the forum topic.
Conversations through a business connection are always separate, and a press on an inline message has no chat, so
only `Scope::User` gives it one. Under the topic scopes a press takes its topic from the message pressed, read from
the cache or Telegram; when that message can't be read, the press goes on to the later routes.

### Timeout

`timeout(d)` ends a conversation `d` after its state last changed: the next update finds no state, as after
`clear` (`src/dialogue/router.rs:128`). Without it, a state stays until it is cleared. An expired record is removed
on the next load.

### Storage

`DialogueMemoryStorage` keeps states in memory, gone when the process ends. `JsonFileStorage`, with the `dialogue-json`
feature, keeps them in one file, for a state type with serde's `Serialize` and `Deserialize`:

```rust
use std::sync::Arc;

use vaegram::dialogue::{DialogueRouter, JsonFileStorage};
use vaegram::prelude::*;

# fn build() {
// One storage, one file. Each dialogue keeps its records under its own namespace.
let storage = Arc::new(JsonFileStorage::new("dialogues.json"));
let mut count: DialogueRouter<u32> = DialogueRouter::new("count", Arc::clone(&storage));
count.on_message(filters::any_state(), filters::text(), |msg, dlg| async move {
    dlg.update(|n| *n += 1).await?;
    msg.reply(dlg.state().unwrap_or_default().to_string()).await
});
# }
```

A file of another version is refused, never overwritten (`src/dialogue/json_file.rs:15`), and a state the type can
no longer read reads as no state, so that conversation starts over. The storage caches the whole file: two of them
on one file overwrite each other's changes, so make one and share it, and never point two processes at it. For
another backend (Redis, SQL), implement `DialogueStorage<S>`: `get`, `set` and `remove`, with the key's `Display`
form as its key.

### Mounting, and routing by hand

`into_router()` returns a `Router` to include in a client or a router. Without the update loop, `handle_message`
and `handle_callback_query` return whether a step took the update. `dialogue(key)` gives the state outside a step,
to reset a user from an admin command; it takes no lock, so a step of the same dialogue may overwrite it.

### Dialogues, `ask` and conversations

`Client::ask` and `listen` wait inside one handler, keep its slot, and end with the process: fine for one quick
question. A dialogue keeps no task waiting between messages, and a persistent storage carries it past a restart. For
a flow written as one async function instead of one handler per step, use a `Conversation`.

## Common mistakes

- A catch-all later group answers too: taking an update doesn't stop later groups
  (`src/dialogue/router.rs:44-47`); call `.stop()` on the include.
- Order decides: only the first matching step runs, so put the `/cancel` step, with `any_state()`, first.
- Confusing the two filters: the first argument of `on_message` is the state filter, the second the update
  filter. Swapping them sends every message to the step.
- Expecting a group to share a form: the default scope is one state per user in each chat; pick `Scope::Chat`
  or `ChatTopic` to share it.
- Expecting `DialogueMemoryStorage` to survive a restart: use `JsonFileStorage`, or a storage of your own.
- Waiting for a reply inside a step with `ask`: the dialogue stays locked while it waits, so its next updates, a
  `/cancel` too, wait with it. Use a step per question.

## See also

- [API docs](https://docs.rs/vaegram/latest/vaegram/dialogue/index.html) for `DialogueRouter`, `Dialogue` and the storages.
- [Filters](/docs/filters.md) for `state`, `state_is`, `any_state` and `no_state`.
- [Routers](/docs/routers.md) for `include_router`, groups and `stop`.
- [Conversations](/docs/conversations.md) for the same flow written as one async function.
- [Testing](/docs/testing.md) for driving a dialogue with the test kit.