# Routers

A `Router` is a set of handlers with its own middleware, provided values and error handler, written like a small
module and included in the client (or in another router). Use one per feature so a growing bot stays readable.

## Example

A bot split in two routers, moderation nested in admin:

```no_run
use vaegram::prelude::*;

#[derive(Clone)]
struct Config {
    admins: Vec<i64>,
}

async fn ban(msg: Message, Dep(config): Dep<Config>) -> Result<()> {
    msg.reply(format!("Banned. {} admins are configured.", config.admins.len())).await?;
    Ok(())
}

#[tokio::main]
async fn main() -> Result<()> {
    let app = Client::builder("modular_bot", 12345, std::env::var("API_HASH").unwrap())
        .bot_token(std::env::var("BOT_TOKEN").unwrap())
        .start()
        .await?;
    app.provide(Config { admins: vec![42] });

    let mut moderation = Router::new();
    moderation.message().handle(filters::command("ban"), ban);
    moderation.on_error(|e| async move { eprintln!("moderation failed: {}", e.error) });

    let mut admin = Router::new();
    admin.message().filter(filters::private());
    admin.include_router(moderation);

    app.include_router(admin).group(-1);
    app.on_message(filters::command("start"), |msg| async move { msg.reply("Welcome!").await });
    app.run().await
}
```

## How it works

### The same `on_*` methods as the client

A router has every `Client::on_*` method under the same name: `on_message`, `on_callback_query`, `on_inline_query`
and the rest, generated from one list of update kinds (`src/dispatcher/router.rs:693`). They take the same filters
and closures and return a `RouteRef` instead of a `HandlerRef`.

For a single kind, `router.message()` gives an `Observer` with three extras:

- `.handle(filter, handler)` takes a named async function and extra arguments from the context, such as `Dep<V>`;
- `.filter(filter)` adds a filter every update of that kind must pass before the router's handlers see it;
- `.outer_middleware(..)` / `.inner_middleware(..)` add middleware for that kind alone.

`on_message(filter, |msg| ..)` only ever passes the update, so a handler that wants a `Dep` uses `handle`, as the
example's `ban` does.

### Including and nesting

`client.include_router(router)` adds the router as one entry in the client's groups. An included router is one entry
in its parent's groups too: when one of its handlers matches, it has taken its group's turn; its own handlers run by
their groups inside it, and a parent's middleware and values reach it (`src/handlers/router.rs:7-16`).

Handler ids are process-wide, so a `RouteRef::id` taken before including still removes the handler afterwards:

```rust
# use vaegram::prelude::*;
# fn f(app: &Client) {
let mut router = Router::new();
let help = router.on_message(filters::command("help"), |msg| async move { msg.reply("Help!").await }).id();
app.include_router(router);
app.remove_handler(help); // also works once the router is included
# }
```

Removing the id returned by `include_router` removes the whole router.

### Groups and `stop`

Groups run in ascending order, default `0`. Within a group the first matching handler registered wins, and a match
in group `0` does not stop group `1` (`src/handlers/mod.rs:108-114`). `stop()` ends the walk for that update:

```rust
# use vaegram::prelude::*;
# fn f(mut router: Router) {
router.on_message(filters::command("admin"), |msg| async move {
    msg.reply("Admins only.").await?;
    Ok(())
}).group(-10).stop();
# }
```

`client.include_router(router).group(-1)` puts a whole module before the client's own group `0`.

### Values with `Dep`

`client.provide(value)` and `router.provide(value)` hand a value to handlers that ask for `Dep<V>`. A router's value
wins over the client's, and a middleware's `ctx.provide(..)` wins over both (`src/handlers/di.rs:10-15`,
`src/handlers/router.rs:87-92`):

```rust
# use std::sync::Arc;
# use vaegram::prelude::*;
# struct Db;
# fn f(app: &Client) {
app.provide(Arc::new(Db));
let mut router = Router::new();
router.provide(Arc::new(Db)); // handlers in this router take this one
# }
```

A handler that asks for a value nobody provided does not run; the error is `Error::MissingDependency`.
Take `Option<Dep<V>>` when the value may be absent. Values are cloned per update, so provide shared state as an
`Arc`.

### Per-router errors

`router.on_error(f)` receives every `Err` from this router's handlers and middleware and from the routers inside it
that have no `on_error` of their own (`src/handlers/router.rs:96-100`). Without it, the error goes to the outer
router's `on_error`, then to `Client::on_error`, and stops the later groups for that update. Registering again
replaces the handler.

## Common mistakes

- Building a router and never including it: nothing runs. `Client::include_router` or `Router::include_router`.
- Expecting a match in group `0` to hide group `1`: every group gets a turn; use `.stop()`.
- Registering a `Dep` handler with `on_message`: it takes only the update. Use `message().handle(..)`.
- Forgetting `provide`: the handler silently never runs and `on_error` gets a `MissingDependency`.
- Putting shared state in a `Dep` without `Arc`: it is cloned for every update.
- A child's `on_error` also takes the errors of routers nested in it, unless they have their own; the parent's does
  not see them.

## See also

- [API docs](https://docs.rs/vaegram/latest/vaegram/handlers/index.html) for `Router`, `RouteRef` and `Dep`.
- [Middleware](/docs/middleware.md).
- [Filters](/docs/filters.md).
- [Commands](/docs/commands.md).