# Bot API mode vs MTProto

`Client` reaches Telegram two ways: MTProto, with an `api_id`/`api_hash` session, or the HTTP
[Bot API](https://core.telegram.org/bots/api) with only a bot token. Methods, types, filters and handlers stay the
same; coverage and updates differ.

## Example

The Bot API: a token, HTTPS, no session file.

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

#[tokio::main]
async fn main() -> Result<()> {
    let app = Client::builder("hello_bot", 0, "") // api_id and api_hash are unused in Bot API mode
        .bot_api(std::env::var("BOT_TOKEN").unwrap())
        .start()
        .await?;

    app.on_message(filters::command("start"), |msg| async move {
        msg.reply("Hello over the Bot API.").await?;
        Ok(())
    });

    app.run().await
}
```

The same bot over MTProto; only the builder line changes.

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

#[tokio::main]
async fn main() -> Result<()> {
    let app = Client::builder("hello_bot", 12345, std::env::var("API_HASH").unwrap())
        .bot_token(std::env::var("BOT_TOKEN").unwrap())
        .start()
        .await?;

    app.on_message(filters::command("start"), |msg| async move {
        msg.reply("Hello over MTProto.").await?;
        Ok(())
    });

    app.run().await
}
```

## The builder decides

`Client::builder(name, api_id, api_hash)` is the only constructor; `.bot_api(token)` switches the transport. In Bot
API mode `api_id` and `api_hash` are not used, so `0` and `""` are fine, and `bot_token` is ignored (`src/client.rs:113`).
`start` calls `getMe` over HTTPS and opens no MTProto connection; nothing is stored, so peers live in memory
whatever storage is set. `.bot_api_url("http://127.0.0.1:8081")` points at a local Bot API server.

## What a friendly method sends

A friendly method builds its TL request as usual; in Bot API mode the session hands it to the bridge, which sends
the Bot API method that does the same job and converts the answer back (`src/bot_api/bridge.rs:1-5`). The bridge
covers messages (send, edit, delete, forward and copy, reactions, polls, checklists, ephemeral messages, games),
chats (members, admins, permissions, invite links, join requests, topics, boosts) and the bot itself (settings,
business, gifts, Stars and payments, stickers, stories, inline answers, Passport).

A request with no counterpart fails with `Unsupported` inside `Error::Other`; `downcast_ref::<Unsupported>()` on the
error and its `what()` tell you which method was missing.

Scheduled messages, sends as another chat, quick replies, rich messages, paid messages and suggested posts are
refused that way (`src/bot_api/bridge.rs:399-402`), and so are deletions of messages this client never saw outside
channels (`src/bot_api/bridge.rs:505-510`).

Fields the Bot API does not send are approximated: users and chats come as `min` with access hash `0`, a message's
raw TL holds only what the Bot API sent, and a user looked up by id reads back as a person (`src/client.rs:104-112`).

## How updates arrive

`run` drives a `getUpdates` long poll, 50 seconds per request (`src/bot_api/polling.rs:23`). For a webhook, register
it and run the receiver instead of `Client::run`:

```no_run
# async fn f(client: vaegram::Client) -> vaegram::Result<()> {
let webhook = client.webhook(std::env::var("WEBHOOK_SECRET").unwrap())?;
webhook.register("https://bot.example.com/telegram").await?;
webhook.run().await?; // or webhook.serve("127.0.0.1:8080") with the `webhook-server` feature
# Ok(()) }
```

In Bot API mode only nine kinds of update arrive: `message`, `edited_message`, `channel_post`,
`edited_channel_post`, `callback_query`, `inline_query`, `business_connection`, `business_message` and
`edited_business_message` (`src/bot_api/polling.rs:27-37`). Handlers for anything else, such as
`on_chat_member_updated`, `on_chat_join_request`, `on_poll`, `on_shipping_query` or `on_chosen_inline_result`, never
fire there, even though sending inline results with `answer_inline_query` does work. MTProto delivers every kind.

## Limits

- Text is 1 to 4096 characters after entities parsing (`src/bot_api/raw/methods.rs:135`); split longer text yourself.
- Downloads through `api.telegram.org` stop at 20 MB; a local Bot API server or MTProto has no such cap
  (`src/bot_api/media.rs:27`).
- Uploads travel inside the request as `multipart/form-data`, so no resumable upload runs; the server's upload limit
  applies. `Upload::Bytes` and `Upload::Path` both work, and `InputFile` does the same for the raw client.

## The raw Bot API client

`bot_api::BotApi` is the transport on its own, with one struct per method of the generated spec (194 methods in
`bot_api::raw::methods`, Bot API 10.5):

```no_run
use vaegram::bot_api::raw::{ChatId, methods::SendMessage};
use vaegram::bot_api::BotApi;

# async fn f() -> vaegram::Result<()> {
let api = BotApi::new(std::env::var("BOT_TOKEN").unwrap())?;
let sent = api.invoke(&SendMessage {
    chat_id: Some(ChatId::Id(42)),
    text: "Straight from the Bot API.".into(),
    ..Default::default()
}).await?;
println!("sent message {}", sent.message_id);
# Ok(()) }
```

`BotApi::builder(token).url(..).timeout(..).build()?` sets a local server and a request timeout. Errors are
`Error::Rpc` with MTProto-style names, a `retry_after` becomes `420 FLOOD_WAIT_<n>`, and a migrated group arrives as
`Error::ChatMigrated { chat_id }`; `file_url` holds the token, so never log it (`src/bot_api/client.rs:122-124`).

`bot_api::raw` mirrors the Bot API's published spec and is exempt from semver: a Bot API update may add or change a
type, field or method in any 0.4.x release. Pin `vaegram` if a raw type must stay exactly as it is.

## Which transport to pick

| You need | Use |
|---|---|
| A user account, or anything only a user can do | MTProto |
| A bot that needs no real `api_id`/`api_hash`, only outbound HTTPS, or a webhook | Bot API |
| Message history, member lists, files over 20 MB, every update kind | MTProto |
| A Bot API method the bridge lacks, sent through the raw client | Bot API |

Bot API mode is experimental in the 0.4.0 nightlies and may change between them.

## Common mistakes

- Passing a `BotApi` to `bot_api()`: it takes the token string, `BotApi::new(token)` is the raw client.
- Expecting `on_chat_member_updated` or `on_poll` to fire: only the nine kinds above are delivered.
- Calling `Client::run` while a webhook is registered: `getUpdates` fails with 409 and the run ends. Use
  `webhook.run()`.
- Downloading a 50 MB file through `api.telegram.org`: it stops at 20 MB; use MTProto or a local server.
- Setting a big `api_id` and assuming it matters: in Bot API mode it is unused.

## See also

- [API docs](https://docs.rs/vaegram/latest/vaegram/bot_api/index.html) for `BotApi`, `Webhook` and the raw methods.
- [Files and media](/docs/files-and-media.md).
- [Deployment](/docs/deployment.md) for webhooks and graceful shutdown.
- [Flood limits](/docs/flood-limits.md).