# vaegram > vaegram is a Rust client library for Telegram, speaking MTProto directly as a user account or as a > bot, with an optional Bot API mode. This is the guide. API reference: . ## Introduction and setup - [Introduction](/docs/introduction.md): what vaegram is, MTProto vs the Bot API, and which pages to read first. - [Installation](/docs/installation.md): add the crate, pick features, get an api_id and api_hash. - [Your first bot](/docs/first-bot.md): a bot that answers /start, built from an empty project. - [Your first user account](/docs/first-user-account.md): log in as a person and send a message to yourself. ## Basics - [Sending messages](/docs/sending-messages.md): text, formatting, replies, edits, and the return value of a send. - [Receiving updates](/docs/receiving-updates.md): handlers, `run`, the update loop, and filtering what you get. - [Filters](/docs/filters.md): pick updates with `filters::`, and combine them with `&`, `|` and `!`. - [Commands](/docs/commands.md): parse `/command` text, and derive an enum from it with `#[derive(BotCommands)]`. - [Keyboards](/docs/keyboards.md): inline and reply keyboards with the chained builder, callbacks and answer handlers. - [Files and media](/docs/files-and-media.md): send photos, documents and albums from a path, bytes or an id. - [Errors](/docs/errors.md): `Result`, `Error`, Telegram's `RpcError`, and how to retry. ## Bot API and routers - [Bot API mode vs MTProto](/docs/bot-api-vs-mtproto.md): the two transports in one client, what each can and cannot do. - [Routers](/docs/routers.md): group handlers into modules, nest them, and share values and errors. - [Middleware](/docs/middleware.md): run code before filters (outer) and around handlers (inner), and stop an update. ## Dialogues, conversations and testing - [Dialogues](/docs/dialogues.md): multi-step forms that survive a restart, with typed state and storage. - [Conversations](/docs/conversations.md): ask several questions in one async function with `Conversation`. - [Testing](/docs/testing.md): drive the handlers with the test kit and assert on what the bot sent. ## Deployment and migration - [Deployment](/docs/deployment.md): polling, webhooks, graceful shutdown and running more than one instance. - [Flood limits](/docs/flood-limits.md): vaegram's per-chat limit, Telegram's flood waits, and how to stay under both. - [Sessions and storage](/docs/sessions-and-storage.md): the session file, session strings, and the storage engines. - [Migration 0.3 to 0.4](/docs/migration-03-to-04.md): every breaking change from 0.3.0, with the fix for each. --- # Introduction vaegram is a Rust client for Telegram that speaks MTProto, the protocol the official apps use. You can run a bot with it, or a normal person's account. ## Example ```no_run use vaegram::prelude::*; #[tokio::main] async fn main() -> Result<()> { let app = Client::builder("my_bot", 12345, "0123456789abcdef0123456789abcdef") .bot_token("123456:ABC-DEF") .start() .await?; app.on_message(filters::command("start"), |msg| async move { msg.answer("Hello from vaegram!").await?; Ok(()) }); app.run().await } ``` ## MTProto, and the Bot API Telegram has two APIs. MTProto is the one its own apps use: a binary protocol over TCP with an encrypted session and a login key exchange, and the API on top of it has every method Telegram offers. vaegram implements it in Rust, generates a type for every function in Telegram's schema, and puts a friendly API of methods, handlers and filters on top. The Bot API is Telegram's HTTPS wrapper around a smaller part of that. If you want it, the `bot-api` cargo feature runs the same `Client` over it: `Client::builder(..).bot_api(token)` keeps your handlers, filters and method calls and sends them as Bot API calls. Requests with no Bot API counterpart fail with `Unsupported`. The feature is experimental in the 0.4.0 nightlies, and a client uses one transport or the other; [Bot API mode vs MTProto](/docs/bot-api-vs-mtproto.md) compares them. ## User accounts and bots Both use the same `Client`. A bot logs in with a token from [@BotFather](https://t.me/BotFather), set with `.bot_token(..)`, and acts as a bot: it can reach most users who have talked to it, and it works from the updates Telegram sends it rather than from an account's chats. A user account logs in with a phone number, the code Telegram sends, and the two-step verification password if the account has one; leave out `.bot_token(..)` and `start` asks for them on stdin. It is a full client of that account: its chats and history, and any peer it has met, whether a chat it joined, a username it looked up, or a person who wrote to it. ## Features The crate has no default features: add the ones you use. | Feature | What it enables | |---|---| | `serde` | `Serialize` for the types you receive (`Message`, `User`, `Chat`, events, …). | | `json` | `ToJson` for every TL type and function, and JSON for raw updates and recordings. | | `bot-api` | The HTTP Bot API as a raw client, and as a transport for the whole `Client`. | | `webhook-server` | `bot_api::Webhook::serve`, an HTTP server that receives a bot's webhook. | | `macros` | `#[derive(BotCommands)]`, which writes `commands::BotCommands` for an enum. | | `sqlite`, `redb`, `redis`, `mongodb`, `postgres`, `s3`, `vault` | A storage engine for the session and update state. | | `dialogue-json` | Dialogue states kept in a JSON file. | | `regex` | `filters::regex` and `filters::matches`. | | `websocket` | `ClientBuilder::websocket`, MTProto over TLS on `*.web.telegram.org`. | | `dns-config` | `ClientBuilder::dns_fallback`, addresses from Telegram's DNS config. | | `web-proxy` | `Proxy::Web`, an MTProxy behind an HTTPS relay. | | `metrics`, `opentelemetry` | Request observers in the `observe` module. | | `unstable-raw` | The TL objects behind raw updates, and the session plumbing below `Client`. May change in any release. | ## Where to go next Read [Installation](/docs/installation.md) first: it adds the crate and gets the `api_id` and `api_hash` that every login needs. After that, [Your first bot](/docs/first-bot.md) if the account is a bot, or [Your first user account](/docs/first-user-account.md) if it is a person. ## Common mistakes - Mixing up the two credentials. `api_id` and `api_hash` belong to the application and come from my.telegram.org; a bot token belongs to one bot and comes from @BotFather. Both are needed for a bot. - Planning a user account on the Bot API. Bot API mode logs in as a bot with a token, so a person's account always uses MTProto. ## See also - [API docs](https://docs.rs/vaegram/latest/vaegram/index.html) for the crate, its modules and the prelude. - [Bot API mode vs MTProto](/docs/bot-api-vs-mtproto.md) for choosing the transport. - [Installation](/docs/installation.md) for the crate, its Rust version and its features. --- # Installation vaegram is a normal cargo dependency. An MTProto login needs an `api_id` and an `api_hash` from Telegram, and a bot needs a token from [@BotFather](https://t.me/BotFather) as well. ## Example This guide teaches 0.4, which is not on crates.io yet (crates.io has 0.3.0). Until it is, install it from the `nightly` branch on GitHub, which carries 0.4.0-nightly.2: ```bash cargo add vaegram --git https://github.com/rjriajul/vaegram --branch nightly cargo add tokio --features macros,rt-multi-thread ``` ```toml [dependencies] vaegram = { git = "https://github.com/rjriajul/vaegram", branch = "nightly" } tokio = { version = "1", features = ["macros", "rt-multi-thread"] } ``` ```no_run use vaegram::prelude::*; #[tokio::main] async fn main() -> Result<()> { let app = Client::builder("my_bot", 12345, "0123456789abcdef0123456789abcdef") .bot_token("123456:ABC-DEF") .start() .await?; println!("logged in as {}", app.get_me().await?.first_name); Ok(()) } ``` ## Rust version The crate needs Rust 1.85 or newer and is an edition 2024 crate. `#[tokio::main]` needs tokio's `macros` and `rt-multi-thread` features, as above. ## Features No feature is on by default, so a build pulls only what you name. Add them where you add the crate: ```bash cargo add vaegram --git https://github.com/rjriajul/vaegram --branch nightly --features serde,bot-api ``` The list of features with what each turns on is in the [introduction](/docs/introduction.md#features). Two worth knowing before you start: - `serde` makes the types you receive serializable, which most logging and storage code wants. - A storage feature (`sqlite`, `redb`, `postgres`, `redis`, `mongodb`, `s3`, `vault`) replaces the session file with that engine. Without one, the client writes a file. ## api_id and api_hash Both come from : log in, open "API development tools", create an application, and copy its `api_id` (a number) and `api_hash` (32 hex characters). They belong to the application, not to an account, so one pair serves every bot and every user login that app makes. Bot API mode ignores them, since it has no session with Telegram's servers, but the builder still takes them. Pass them to `Client::builder(name, api_id, api_hash)`. The first argument is the client's name, and it decides the session file's path: `"my_bot"` gives `my_bot.session` in the working directory, `"bots/echo"` gives `bots/echo.session`. `ClientBuilder::workdir` picks the directory instead. ## The session file The first run logs in and saves the login to `.session`. Later runs read it and skip the login, so a bot does not need its token in the code once the file exists, and a user account does not get a new code on every restart. The file is created readable only by you (0600 on Unix). Bot API mode is the exception: it keeps peers in memory and writes no session. Two things follow from that: - One client at a time can open a session file. While it is open the file has a `.session.lock` next to it, and a second client on the same file, in this process or another, fails with `ResourceBusy`. A crash releases the lock; the empty `.lock` file stays. - The session file is the login. Anyone with a copy is logged in as that account, so keep it out of git and out of logs. `ClientBuilder::in_memory()` writes nothing at all, and `export_session_string()` puts the login in one line for an environment variable. ## The short name The `vae` crate is the same library under a shorter name: `vae = { git = "https://github.com/rjriajul/vaegram", branch = "nightly" }` for now (same branch as below), then `use vae::Client;`. Everything is re-exported, `prelude` included. Only the `macros` feature needs a word: give a `#[derive(BotCommands)]` enum `#[command(crate = "vae")]`, or the generated code names `vaegram`. ## Installing a nightly 0.4 is not on crates.io yet. The `nightly` branch moves as new nightlies land, and cargo records the exact commit in `Cargo.lock`, so a build stays the same until you run `cargo update`. To pin one commit, use `rev` instead of `branch`: ```toml vaegram = { git = "https://github.com/rjriajul/vaegram", rev = "f4479fd" } ``` Once a nightly is on crates.io, cargo still skips it under `vaegram = "0.4"`, since pre-releases need asking for: pin it with `=`, as in `vaegram = "=0.4.0-nightly.2"`. When 0.4 is stable, a plain `vaegram = "0.4"` follows the releases. ## Common mistakes - Calling `.bot_api(..)` or `#[derive(BotCommands)]` without the matching feature: the method does not exist and the compiler says so. Add `bot-api` or `macros`. - Expecting `serde` to be on. Nothing is: a type that is not `Serialize` means the feature is missing. - Running the program twice at once on one session file. Give each process its own name, or run one process. - Committing `*.session`. It is the account's login. ## See also - [API docs](https://docs.rs/vaegram/latest/vaegram/client/struct.ClientBuilder.html) for `ClientBuilder` and every setting. - [Introduction](/docs/introduction.md) for the feature table and what vaegram is. - [Sessions and storage](/docs/sessions-and-storage.md) for session strings, the engines and where the state lives. - [Your first bot](/docs/first-bot.md) once the crate is in. --- # Your first bot A bot logs in with the token @BotFather gives you. This page builds one that answers `/start`, replies to it, and has a second command. ## Example ```bash cargo new my_bot && cd my_bot cargo add vaegram --git https://github.com/rjriajul/vaegram --branch nightly cargo add tokio --features macros,rt-multi-thread ``` Put this in `src/main.rs`, set the three variables, and run it: ```no_run use vaegram::prelude::*; #[tokio::main] async fn main() -> Result<()> { let api_id = std::env::var("VAEGRAM_API_ID").expect("set VAEGRAM_API_ID"); let api_hash = std::env::var("VAEGRAM_API_HASH").expect("set VAEGRAM_API_HASH"); let token = std::env::var("VAEGRAM_BOT_TOKEN").expect("set VAEGRAM_BOT_TOKEN"); let app = Client::builder("my_bot", api_id.parse().expect("api_id is a number"), api_hash) .bot_token(token) .start() .await?; app.on_message(filters::command("start"), |msg| async move { let name = msg.from_user.as_ref().map_or("there", |u| u.first_name.as_str()); msg.reply(format!("Hi {name}! Send /help for the commands.")).await?; Ok(()) }); app.run().await } ``` Send `/start` to the bot and it answers. The first run writes `my_bot.session`; later runs log in from it. ## How it works `Client::builder(name, api_id, api_hash)` holds the settings and connects nothing. `.bot_token(token)` says who the client is. `.start()` opens the connection and logs in: with a token it never asks anything, and without a saved login it signs in as the bot straight away. `app.on_message(filter, handler)` registers a handler for new messages that pass `filter`. Filters are values you combine with `&` (both), `|` (either) and `!` (not); `filters::command("start")` matches `/start` and `/start@YourBot` in any chat. The handler receives the `Message`, returns a future, and ends with a `Result`: `Ok(())` on success, or the error from a call that failed. A handler's `Err` goes to `Client::on_error`; with no error handler registered, it arrives as `ClientEvent::HandlerFailed`. `app.run()` is the loop. It takes updates from Telegram and runs the handlers until `Client::stop`, then returns: no handler fires until it is awaited, so register handlers before it. ## Replying Inside a handler, `msg.answer(text)` sends a text message to the same chat, and `msg.reply(text)` does the same with a quote of the message being handled. Both return the sent `Message` when awaited, so you can edit or delete it later: ```no_run # use vaegram::prelude::*; # async fn demo(msg: Message) -> Result<()> { let sent = msg.reply("Got it").await?; println!("sent message {}", sent.id); # Ok(()) } ``` Both send plain text by default: the client's parse mode starts off, so `**bold**` arrives with the asterisks. `.html()` and `.markdown()` on the returned request turn parsing on for that one message, and `Text::from_html("..")` builds formatting without a parse mode. ## A second command Handlers are independent; add another one for each command. This one answers `/help` with a bold first line: ```no_run # use vaegram::prelude::*; # fn register(app: &Client) { app.on_message(filters::command("help"), |msg| async move { let list = Text::new().bold("Commands").plain("\n/start - say hello\n/help - this list"); msg.answer(list).await?; Ok(()) }); # } ``` `filters::command` takes one name or a list: `filters::command(["start", "help"])`. Two handlers in the same group do not both run: the first one whose filter matches handles the update. `.group(n)` puts a handler in a later group, and every group gets its turn, so a group 1 handler still runs after a group 0 match. ## Common mistakes - No updates arrive because the bot ran on the cloud Bot API before. Call `logOut` there once; until then Telegram keeps sending the bot's updates to the Bot API, and an MTProto login gets none. - Two copies of the program on the same session file. The second one fails with `ResourceBusy`: give each its own name, or one process. - Registering handlers after `run`, or never awaiting it. `.start()` alone only logs in, so no handler runs. - Putting the token in the source. Read it from the environment, and keep the `.session` file out of git too. - Assuming a parse mode. Formatting sent as a plain string stays literal; use `.html()`, `.markdown()` or `Text`. ## See also - [API docs](https://docs.rs/vaegram/latest/vaegram/client/struct.Client.html) for `Client` and its methods. - [Receiving updates](/docs/receiving-updates.md) for `run`, update state and catching up after a restart. - [Filters](/docs/filters.md) and [Commands](/docs/commands.md) for picking updates. - [Your first user account](/docs/first-user-account.md) when the login is a phone number instead. --- # Your first user account A user account is a logged-in session of a real Telegram account. It logs in with a phone number instead of a bot token, and then it can read its chats, send messages and run handlers like any other client. ## Example ```no_run use vaegram::prelude::*; #[tokio::main] async fn main() -> Result<()> { let app = Client::builder("my_account", 12345, "0123456789abcdef0123456789abcdef") .start() .await?; let me = app.get_me().await?; println!("logged in as {} (id {})", me.first_name, me.id); app.send_message("me", "Hello from vaegram").await?; Ok(()) } ``` Run it once. It asks for the phone number, the code Telegram sends, and the two-step verification password if the account has one. The next run reads `my_account.session` and asks nothing. ## The login `start` with no bot token on the builder asks on stdin, in this order: 1. "Enter phone number or bot token": the phone number in international format, `+` optional. A value with a colon in it is read as a bot token, so pasting a token logs in as that bot. 2. The confirmation code, after "The confirmation code has been sent via …". A wrong code is asked for again. 3. Only when the number has no account yet: a first name, a last name, and whether to accept the terms. 4. Only with two-step verification on: the password, after Telegram's hint if it has one, read without echo when stdin is a terminal. A wrong password is asked for again too. The answers come from stdin line by line, with the prompts written to stdout, so they can be piped in as well as typed. Every step can also be answered from the builder: `.phone_number(..)`, `.phone_code(..)` and `.password(..)` are tried first, and whatever is missing is still asked. ## Sending and reading `get_me()` returns the account as a `User`: its `id`, `first_name`, `username`. `"me"` and `"self"` name the account itself wherever a chat id is taken, which is why `send_message("me", ..)` is the quickest way to check that a login works. To read what arrives, register handlers and `run`: ```no_run # use vaegram::prelude::*; # async fn run(app: Client) -> Result<()> { app.on_message(filters::text(), |msg| async move { let from = msg.from_user.as_ref().map_or("unknown", |u| u.first_name.as_str()); println!("{from} in chat {}: {}", msg.chat.id, msg.text()); Ok(()) }); app.run().await # } ``` A user account gets messages from every chat it is in, so check `msg.chat.id` before acting. Messages this client sends do not come back to its own handlers; the same account's messages from another session or device do. ## Logging in without stdin For a server, drive the login yourself: `connect` opens the connection without asking anything, then `send_code`, `sign_in` and, when the account has two-step verification, `check_password`: ```no_run use vaegram::prelude::*; #[tokio::main] async fn main() -> Result<()> { let app = Client::builder("my_account", 12345, "0123456789abcdef0123456789abcdef") .connect() .await?; let sent = app.send_code("+15551234567").await?; let me = match app.sign_in("+15551234567", &sent.phone_code_hash, "12345").await { Ok(me) => me, Err(e) if e.is_session_password_needed() => app.check_password("the password").await?, Err(e) => return Err(e), }; println!("logged in as {}", me.first_name); Ok(()) } ``` `send_code` returns a `SentCode`; `phone_code_hash` must come back with the code, which is why an interactive login does these in two steps. `sign_in` fails with `Error::SignUpRequired` on a number without an account, and with `SESSION_PASSWORD_NEEDED`, as above, when a password is still missing. ## Common mistakes - Messaging a peer the account has never seen. A user account can use a username it resolves, a chat it is in, or someone who wrote to it; a bare id of a stranger fails with `PeerNotFound`, where a bot could reach the user. - Running the program twice on one session file: the second fails with `ResourceBusy`, as with a bot. - Sharing or committing `my_account.session`. It is the login, and anyone with it is that account. - Expecting a conversation to survive a restart. A listener belongs to the client that registered it: `run` stopping ends the ones waiting, and one started outside a run fails with `ListenerStopped`. - Assuming one client is alone. Telegram sends every update to every session of the account, so another client on the same account also gets it and runs its own handlers. ## See also - [API docs](https://docs.rs/vaegram/latest/vaegram/client/struct.Client.html#method.send_code) for `send_code`, `sign_in` and `check_password` on `Client`. - [Sessions and storage](/docs/sessions-and-storage.md) for session strings and the other storage engines. - [Flood limits](/docs/flood-limits.md) for the per-chat limit a user account starts with. - [Your first bot](/docs/first-bot.md) for the token login. --- # Sending messages `Client::send_message` sends text to a chat and returns the message Telegram stored. Any `Message` can then answer, edit or delete itself. ## Example ```no_run use vaegram::prelude::*; # async fn send(client: &Client) -> Result<()> { let sent = client.send_message("me", "Deploy finished in 42s").await?; println!("message {} in chat {}", sent.id, sent.chat.id); # Ok(()) } ``` The request is only sent when it is awaited; the awaited value is the new `Message`. ## How it works ### Text with formatting A plain string is sent as it is, with no formatting. Build styled text with `Text`: ```rust use vaegram::prelude::*; let text = Text::new().bold("Deploy").plain(" finished in ").code("42s"); assert_eq!(text.as_str(), "Deploy finished in 42s"); assert_eq!(text.entities().len(), 2); ``` `bold`, `italic`, `underline`, `strike`, `spoiler` and `code` take just the text. `link` also takes its URL, `mention` the user id, `custom_emoji` the emoji's document id, and `pre` the language for highlighting. `date_time` and `blockquote` take more: ```rust use vaegram::prelude::*; let text = Text::new() .date_time("in two hours", 1_700_000_000, "r") .plain(" ") .blockquote("moved to Friday", false); ``` `date_time` takes the text, a `unix_time: i32`, and a `&str` whose letters pick the styles: `r` relative, `t` short time, `T` long time, `d` short date, `D` long date and `w` weekday. `blockquote` takes the text and an `expandable` flag, which hides the quote behind an expand button. `Text` keeps the plain string plus entities, and its offsets count UTF-16 units, as Telegram does. Every send takes `impl Into`, and every edit `impl Into`; a `&str`, a `String` and a built `Text` all convert. ### Parse modes Instead of building a `Text`, you can send markup and let it be parsed: ```no_run # use vaegram::prelude::*; # async fn send(client: &Client) -> Result<()> { client.send_message(123456789, "bold").html().await?; client.send_message(123456789, "**bold**").markdown().await?; client.send_message(123456789, "**bold**").parse_mode(ParseMode::Default).await?; # Ok(()) } ``` `ParseMode` is one of `Disabled` (send as is), `Html`, `Markdown`, or `Default` (both, with a backslash escaping). A send uses its own mode if set, else the client's default from `Client::builder(..).parse_mode(..)`, which is `Disabled` unless you change it. A mode only applies to a `Text` made straight from a string. A built `Text` or one from `Text::from_html` / `Text::from_markdown` is already parsed and goes out unchanged. `Text::parse(text, mode)` does the same work and never fails: `Disabled` leaves the text plain, and nesting deeper than 64 levels is dropped. Text parsed from user input must be escaped first, or a `<` in it breaks the markup: ```rust use vaegram::escape_html; let name = "Tom & Jerry <3"; let message = format!("{}", escape_html(name)); assert_eq!(message, "Tom & Jerry <3"); ``` `escape_markdown` does the same for Markdown and `Default`. ### Replies ```no_run # use vaegram::prelude::*; # async fn reply(message: &Message) -> Result<()> { message.reply("Got it").await?; message.answer("Same chat and topic, without the quote").await?; # Ok(()) } ``` `reply` is `answer().reply_to(this message)`. `answer` sends to the same chat, topic and business connection without pointing at a message. To reply to a message in another chat, or to quote part of it, build `ReplyParameters`: ```no_run # use vaegram::prelude::*; # async fn reply(message: &Message) -> Result<()> { message .client() .send_message(-1001234567890, "look at this") .reply_to(ReplyParameters::new(7).chat_id(-1001234567890).quote("the part I mean")) .await?; # Ok(()) } ``` `reply_to` accepts a bare `i32` message id too. `quote_position` places the quote by UTF-16 offset; Telegram rejects a quote whose text is not in the replied message. ### Editing and deleting ```no_run # use vaegram::prelude::*; # async fn edit(message: &Message) -> Result<()> { let edited = message.edit_text("new text").await?; message.edit_caption("new caption").await?; message.edit_reply_markup(None).await?; message.delete().await?; message.client().delete_messages(message.chat.id, &[10, 11]).await?; # Ok(()) } ``` Edits return the edited `Message`. `client.delete_messages` takes 1 to 100 ids and deletes for everyone unless `.revoke(false)` says only for this account. ### What a send returns A `Message` with `id`, `chat`, `date`, the sender, and `text()` (or `caption()` for media) plus `entities()`. Media sends return a `Message` the same way. ### Options `.disable_notification()`, `.protect_content()`, `.reply_to(..)`, `.message_thread_id(..)`, `.schedule_date(..)` and `.reply_markup(..)` chain on the request before awaiting. Keyboards are on [Keyboards](/docs/keyboards.md). ## Common mistakes - Sending `hi` without `.html()` shows the tags. A mode is needed for markup, and `Disabled` is the default. - Formatting user text with HTML tags but not escaping it: one `&` breaks every tag after it. Run it through `escape_html`. - Using `reply` where a plain message belongs: it points at the previous message, which groups show as a quote. - Quoting text that differs from the replied message by one character: Telegram answers with an error, not a trimmed quote. - Reading `text()` on a photo message: media keeps its text in `caption()`, and `text()` is empty there. - Deleting an empty list or more than 100 ids: awaiting fails with `Error::InvalidArgument`. ## See also - [API docs](https://docs.rs/vaegram/latest/vaegram/struct.Client.html) for `send_message` and `edit_message_text`. - [API docs](https://docs.rs/vaegram/latest/vaegram/types/struct.Text.html) for `Text`. - [Receiving updates](/docs/receiving-updates.md), [Filters](/docs/filters.md), [Files and media](/docs/files-and-media.md). --- # Receiving updates A handler is a function you register for one kind of update; `run` is the loop that receives updates and calls the matching handlers. ## Example ```no_run use vaegram::prelude::*; #[tokio::main] async fn main() -> Result<()> { let app = Client::builder("my_bot", 12345, "0123456789abcdef0123456789abcdef") .bot_token("123456:ABC-DEF") .start() .await?; app.on_message(filters::command("start"), |msg| async move { msg.answer("Hello!").await?; Ok(()) }); app.run().await } ``` ## How it works ### Handlers ```no_run # use vaegram::prelude::*; # async fn setup(app: &Client) -> Result<()> { app.on_message(filters::all(), |msg: Message| async move { if msg.text().is_empty() { return Ok(()); } msg.answer("seen").await?; Ok(()) }); # Ok(()) } ``` A handler is a closure `Fn(update) -> Future>`; `T` is anything, so `Ok(())` is the usual end. The closure must be `Send + Sync + 'static`: clone what it needs. Each `on_*` method takes one update type and handles that type only: | Method | Gets | |---|---| | `on_message`, `on_edited_message` | `Message` | | `on_callback_query` | `CallbackQuery` (button presses) | | `on_inline_query`, `on_chosen_inline_result` | `InlineQuery`, `ChosenInlineResult` | | `on_chat_member_updated`, `on_my_chat_member` | `ChatMemberUpdated` | | `on_chat_join_request`, `on_poll_answer` | `ChatJoinRequest`, `PollAnswer` | | `on_chat_action`, `on_poll` | `ChatActionUpdated`, `PollUpdated` | | `on_deleted_messages`, `on_pinned_messages` | `DeletedMessages`, `PinnedMessagesUpdated` | | `on_message_reaction`, `on_reactions` | `MessageReactionUpdated`, `ReactionsUpdated` | | `on_business_message`, `on_edited_business_message`, `on_business_connection` | business chats | There are more, one per update Telegram sends: `on_widget_query`, `on_guest_message`, `on_story`, `on_draft`, `on_user_status`, `on_new_login`, `on_read_history`, `on_transcription` and the rest. The lifecycle hooks take no filter: `on_start`, `on_stop`, `on_connect`, `on_disconnect`. Separately, `on_raw_update` and `on_unhandled_update` take a filter over the raw or unhandled update, and `on_event` and `on_error` take a callback. Messages this client sends itself never reach `on_message`, and its own edits never reach `on_edited_message`. ### `run` `run` takes updates until `stop` is called, then returns `Ok(())`. It returns `Error::Disconnected` if the connection ends first. It runs on a connected client, so build it with `start()` (or `connect()` after logging in yourself). While it runs it saves the update state, so a restart continues where the last run left off; `Client::builder(..).catch_up(false)` starts from now instead. Only one `run` per client: a second one fails at once with `Error::InvalidArgument`. For Ctrl-C, await `run_until_ctrl_c()` in place of `run()`; for a service that also gets SIGTERM, `run_until_signal()`. ### Order and concurrency By default every update that matches gets its own task, so two handlers for different updates can run at the same time and interleave. Two settings change that: - `.ordered(true)` runs one chat's updates one at a time, in arrival order (by user for inline queries). Off by default, because in a big group one slow handler would then hold up every member. - `.max_concurrent_handlers(n)` caps how many handlers run at once; the rest wait for a slot. Both go on the builder, next to `bot_token` and `parse_mode`. ### Groups and stopping A handler's group is `0` unless `group(..)` says otherwise, and groups run in ascending order. Inside one group only the first matching handler runs; every group still gets its turn, which is why a fallback needs the earlier handler to `stop()`. ```no_run # use vaegram::prelude::*; # async fn setup(app: &Client) -> Result<()> { app.on_message(filters::command("start"), |msg| async move { msg.answer("hi").await?; Ok(()) }) .group(10) .stop(); let fallback = app.on_message(filters::all(), |msg: Message| async move { msg.answer("I don't know that command").await?; Ok(()) }); fallback.group(20); # Ok(()) } ``` `stop()` ends the walk, so no later group sees that update; without it the group-20 handler would answer `/start` too. The returned `HandlerRef` only borrows the client. Dropping it keeps the handler registered; keep `.id()` to remove it later with `remove_handler`. ### Errors A handler that returns `Err`, or panics, stops the later groups for its update. The error goes to the callback set with `on_error`; without one it arrives as `ClientEvent::HandlerFailed` on `on_event`, and without that it is printed to stderr. A panic never reaches `on_error` and instead arrives as `ClientEvent::HandlerPanicked`. ### A handler and `listen` `listen` waits inside your own code for one update instead of registering a handler: ```no_run use std::time::Duration; # use vaegram::prelude::*; # async fn ask(message: &Message) -> Result<()> { let next = message.client().wait_for_message(message.chat.id).timeout(Duration::from_secs(60)).await?; next.answer("thanks").await?; # Ok(()) } ``` The update a listener takes skips every handler group, so no handler answers it twice; raw handlers still see it. It waits 5 minutes by default (`listener_timeout` on the builder) and then fails with `Error::ListenerTimeout`. `listen::()` is the default kind; name another type for the rest. Use a handler when every matching update needs an answer, and a listener when one place in the code needs the next one. ## Common mistakes - Registering handlers but never awaiting `run`: nothing is received until the loop runs. - Assuming handlers run in registration order for one update: only the group decides, and within a group the first match wins. - Relying on `ordered(true)` to order work across chats: it orders one chat only. - Forgetting that `Err` from a handler skips the later groups and needs `on_error` to be seen. - Expecting `on_message` to see the bot's own messages: they never arrive. - Waiting with `listen` and then also expecting handlers for that reply: a listener's update skips all groups. ## See also - [API docs](https://docs.rs/vaegram/latest/vaegram/handlers/index.html) for `HandlerRef`, `HandlerInfo` and `HandlerError`. - [API docs](https://docs.rs/vaegram/latest/vaegram/struct.Client.html) for `run`, `stop` and `listen`. - [Filters](/docs/filters.md), [Routers](/docs/routers.md), [Deployment](/docs/deployment.md). --- # Filters A filter is a test that decides whether a handler runs for one update. Every `on_*` handler method takes one, and the `filters::` module builds them. ## Example ```no_run use vaegram::prelude::*; # async fn setup(app: &Client) -> Result<()> { app.on_message(filters::command("start") & filters::private(), |msg| async move { msg.answer("Welcome to the private chat").await?; Ok(()) }); # Ok(()) } ``` ## How it works ### The `Filter` type `Filter` is a value, not a trait: `filters::command("start")` returns a `Filter`, which `on_message` accepts. On messages and callback queries, built-in filters are checked against the raw update before it is parsed, so a miss costs no parsing. `Filter::check(&update)` runs the same test by hand, which is handy for a message you fetched. ```rust use vaegram::prelude::*; let start_in_private: Filter = filters::command("start") & filters::private(); let from_admins: Filter = filters::user([42, 43]); let not_a_service: Filter = !filters::service(); let text_or_photo: Filter = filters::text() | filters::photo(); ``` `&` binds tighter than `|`; parenthesise when you mix them. ### Every filter | Group | Functions | |---|---| | Any update | `all()` | | Chat type | `private()`, `direct()` (people, not bots), `group()`, `supergroup()`, `channel()` | | Ids | `chat(ids)`, `user(ids)`: one `i64`, `[i64; N]`, `&[i64]` or `Vec` | | Text | `text()`, `caption()`, `text_starts_with(prefix)` | | Commands | `command(names)`, `command_with(prefixes, names)`, `command_with_prefixes(prefixes, names)`, `command_case_sensitive(prefixes, names)`, `command_with_prefixes_case_sensitive(prefixes, names)` | | Media | `media()`, `photo()`, `video()`, `animation()`, `audio()`, `voice()`, `video_note()`, `document()`, `sticker()`, `live_photo()`, `contact()`, `location()`, `venue()`, `dice()`, `poll()`, `game()`, `invoice()`, `checklist()`, `story()`, `giveaway()`, `giveaway_winners()`, `paid_media()`, `widget()`, `web_page()` | | Message facts | `reply()`, `forwarded()`, `via_bot()`, `mentioned()`, `quote()`, `from_scheduled()`, `scheduled()`, `protected()`, `media_group()`, `service()`, `media_spoiler()`, `linked_channel()`, `live_location()`, `self_destruction()`, `paid_message()`, `business()`, `reacted()`, `inline_keyboard()`, `reply_keyboard()` | | Direction and sender | `outgoing()`, `incoming()`, `me()`, `bot()`, `sender_chat()` | | Chat facts | `forum()`, `admin()` | | Topics | `topic(id)` | | Service kinds | `service_kind(kinds)`, plus `new_chat_members()`, `left_chat_member()`, `new_chat_title()`, `new_chat_photo()`, `delete_chat_photo()`, `group_chat_created()`, `supergroup_chat_created()`, `channel_chat_created()`, `migrate_to_chat_id()`, `migrate_from_chat_id()`, `pinned_message()`, `game_high_score()`, `video_chat_started()`, `video_chat_ended()`, `video_chat_members_invited()`, `successful_payment()`, `users_shared()`, `chat_shared()`, `gift_code()`, `gift()` | | Gift offers | `gift_offer()`, `gift_offer_accepted()`, `gift_offer_rejected()` | | Button data | `data(bytes)`, `data_prefix(bytes)` | | Your own test | `create(closure)` | Each filter only applies to update kinds that carry what it tests: `filters::user` needs a sender, `filters::text` needs text, `filters::data` needs callback data. A filter that does not apply is a compile error, not a filter that never matches. Ids are Bot-API style: users positive, basic groups negative, channels and supergroups `-100…`. With the `regex` feature, `filters::regex(re)` takes an owned `Regex` and returns a filter that matches an update whose text, caption, callback data or payload the pattern finds. `filters::matches(&re, &item)` is not a filter: it returns every match's capture groups for one item, for reading them inside a `create(..)` closure or a handler. ### A filter from a closure ```rust use vaegram::prelude::*; let long: Filter = filters::create(|msg: &Message| msg.text().len() > 40); let long_from_admin = filters::user(42) & long; ``` A closure sees the parsed update, so it is the one filter that always needs parsing. Put the cheap filters first with `&`: `filters::private() & filters::create(..)` skips parsing every group message. ### State Dialogue steps take a second kind of filter, `StateFilter`, built by `state(f)`, `state_is(value)`, `any_state()` and `no_state()`. It tests the dialogue's stored state instead of the update, and only `DialogueRouter` takes it. See [Dialogues](/docs/dialogues.md). ## Common mistakes - Matching commands with `text_starts_with("/start")`: it also takes `/starter` and `/start@another_bot`. `filters::command("start")` reads the name and the mention instead. - Putting `create(..)` first in a chain: every update of that kind then gets parsed. Put it last. - Combining filters of different update types with `&`: both sides must be `Filter` for the same `T`, so a mismatch fails to compile. - Expecting `filters::text()` to match a photo's caption: that is `filters::caption()`. - Expecting `filters::media()` to match a text with a link preview: a preview is not media; `filters::web_page()` matches it alone. ## See also - [API docs](https://docs.rs/vaegram/latest/vaegram/filters/index.html) for the whole module. - [Receiving updates](/docs/receiving-updates.md), [Commands](/docs/commands.md), [Dialogues](/docs/dialogues.md). --- # Commands A command is message text that starts with `/`; `#[derive(BotCommands)]` turns an enum into a parser, a filter, a help text and the bot's command menu. ## Example ```rust use vaegram::prelude::*; #[derive(BotCommands, Debug, PartialEq)] enum Cmd { /// Start the bot Start(Option), /// Ban a user, with an optional reason #[command(alias = "b")] Ban { user_id: i64, #[command(rest)] reason: Option }, } let ban = Cmd::parse("/ban@MyBot 42 spam bot", Some("mybot")).unwrap(); assert_eq!(ban, Cmd::Ban { user_id: 42, reason: Some("spam bot".into()) }); assert_eq!(Cmd::descriptions().to_string(), "/start - Start the bot\n/ban, /b - Ban a user, with an optional reason"); ``` ## How it works ### Reading a command from a message Text like `/ban@MyBot 42 spam` is read as the name `ban`, the bot `MyBot` and the rest `42 spam`: ```no_run # use vaegram::prelude::*; # async fn read(msg: &Message) -> Result<()> { if let Some(command) = msg.command() { let _name = command.name; let _first_argument = command.arg(0); let _everything_after = command.rest(); } # Ok(()) } ``` `command()` returns `None` for text that is no command, and for a command that names another bot once the client knows its own username. A name is 1 to 32 letters, digits or underscores. `command_with("/!")` accepts any character of the given set as the prefix, and `command_with_prefixes(&[".", "!x"])` any of several strings. ### Command filters `filters::command("start")` matches `/start` and `/start@this_bot`, in any letter case. `filters::command(["ban", "kick"])` takes several names. `filters::command_with("/!", names)` lets any character of the first argument start the command, and `filters::command_case_sensitive(prefixes, names)` requires the typed case. There is no `command_with_args`: arguments are read from the `Message` with `command()`, never from the filter. The filter only decides whether the handler runs. ### The enum `#[derive(BotCommands)]` writes the `BotCommands` trait for the enum: - A variant's command is its name in `snake_case`: `SetAge` is `/set_age`. - Doc comment lines become its description. Only the first paragraph is used. - `#[command(alias = "b")]` adds another name; `rename = "name"` replaces it. - With one field, all the text after the command goes into it. With several, the text splits on spaces, one word per field; a last field marked `#[command(rest)]` takes everything left. An `Option` field may be missing. ```no_run use vaegram::prelude::*; #[derive(BotCommands, Debug)] enum Cmd { /// Start the bot Start(Option), /// Ban a user, with an optional reason #[command(alias = "b")] Ban { user_id: i64, #[command(rest)] reason: Option }, /// Show this help #[command(allow_extra)] Help, } # async fn setup(app: &Client) -> Result<()> { app.set_bot_commands(Cmd::bot_commands()).await?; app.on_message(Cmd::filter::(), |msg: Message| async move { match msg.parse_command::()? { Cmd::Start(_) => { msg.answer("Hello!").await?; } Cmd::Ban { user_id, .. } => { msg.answer(format!("banning {user_id}")).await?; } Cmd::Help => { msg.answer(Cmd::descriptions().to_string()).await?; } } Ok(()) }); # Ok(()) } ``` `Cmd::filter()` builds the filter from the enum's names and aliases, so an update that cannot be one of its commands is dropped before parsing. `msg.parse_command::()` parses and checks the `@mention` against this bot's username. ### Help text and the menu `Cmd::descriptions()` prints one line per command: `/name, /alias - description`. `#[command(description = "Commands:")]` on the enum puts a header above the list, and `hide` leaves a command out of both the help text and the menu while still parsing it. A command set built at run time implements `BotCommands` by hand: `CommandDescription::owned(prefix, command, description)` and `CommandDescriptions::owned(commands)` take owned strings, so the help text needn't be `'static`. The derive keeps its literals static, with no allocation. `Cmd::bot_commands()` is the menu for `set_bot_commands`. Telegram refuses the whole menu over one bad entry, so a name in it must be lowercase letters, digits or underscores and a description 3 to 256 characters long; the derive checks that when it builds. ### Errors `parse` returns `CommandParseError`: `NotACommand`, `UnknownCommand`, `WrongBot`, `TooFewArguments`, `TooManyArguments`, `InvalidArgument`, and `Custom` for a `parse_with` parser. An argument that doesn't parse names the field and its position, as in `invalid argument 1: invalid digit found in string`. The error converts into `Error`, so `?` works in a handler that returns `Result`. ## Common mistakes - Reading arguments in the filter: use `msg.command()` or `parse_command` after the handler runs. - Leaving out `allow_extra` on a command with no fields that users may add words to: extra words are `TooManyArguments`. - Naming a menu command in uppercase or giving it a two-letter description: the derive refuses to build. - Comparing `command.name` case-sensitively: filters match any case, so `/START` arrives with `"START"` and must be compared without case. - Expecting `filter()` to keep hidden commands out: `hide` only affects the help text and the menu, not parsing. ## See also - [API docs](https://docs.rs/vaegram/latest/vaegram/commands/index.html) for the trait, the helpers and `CommandParseError`. - [API docs](https://docs.rs/vaegram/latest/vaegram/types/struct.Command.html) for `Command`. - [Filters](/docs/filters.md), [Receiving updates](/docs/receiving-updates.md). --- # Keyboards Buttons under a message (inline) or in place of the user's keyboard (reply), and the callback query a button sends back when it is pressed. ## Example ```rust use vaegram::prelude::*; let menu = InlineKeyboardMarkup::default() .callback("Yes", "yes") .callback("No", "no") .row() .button(InlineKeyboardButton::callback("Delete", "delete").style(ButtonStyle::Danger)) .url("Docs", "https://docs.rs/vaegram"); assert_eq!(menu.rows.len(), 2); // Yes, No / Delete, Docs let keyboard = ReplyKeyboardMarkup::default() .text("Yes") .text("No") .row() .button(KeyboardButton::new("Share my number").request_contact(true)) .one_time(true) .placeholder("Pick one"); assert_eq!(keyboard.rows.len(), 2); assert!(keyboard.resize); // on unless turned off ``` ## How it works Both keyboards are built the same way: each button joins the last row, and `.row()` starts the next one. `.row()` does nothing while the last row is empty, so a keyboard is never written with an empty row, though the empty row still counts in `rows`. ### Inline keyboards `InlineKeyboardMarkup::default()` is an empty keyboard. Add buttons with `.callback(text, data)`, `.url(text, url)`, `.button(InlineKeyboardButton)` and `.buttons(iter)`. The button constructors cover what a callback cannot: `InlineKeyboardButton::copy_text`, `::web_app`, `::login_url`, `::switch_inline_query_current_chat`, `::disabled`, and more; each has a short description in the API docs. `.style(ButtonStyle::Primary)` colors a button; a plain button is the default. For a list whose length you don't know, build the rows yourself; `new` takes them: ```rust # use vaegram::prelude::*; let buttons = vec![InlineKeyboardButton::callback("A", "a"), InlineKeyboardButton::callback("B", "b")]; let keyboard = InlineKeyboardMarkup::new(buttons.chunks(2).map(<[_]>::to_vec)); assert_eq!(keyboard.rows.len(), 1); ``` Attach it with `.reply_markup(..)` on any send, and on `edit_message_text`. A keyboard with no buttons is still sent as an empty keyboard; to remove one, pass `None` to `edit_reply_markup`. ### Reply keyboards `ReplyKeyboardMarkup::default()` starts with `resize` on, which fits the keyboard to its buttons. `.text(..)` adds a plain button; `.button(KeyboardButton::new(..).request_contact(true))` adds one that asks for a phone number, location, user, chat or poll instead of sending text. A button sends one request kind, so the `with_*` constructors build it directly: `KeyboardButton::with_contact("Share my number")`, `with_location`, `with_users`, `with_chat`, `with_poll`, `with_managed_bot` and `with_web_app`. `.one_time(true)` hides the keyboard after one press, `.placeholder(..)` sets the hint in the input field, `persistent` and `selective` behave as Telegram documents them. Take a reply keyboard away with `ReplyKeyboardRemove::new()`, and ask for a reply with `ForceReply::new()`. ```rust,no_run use vaegram::prelude::*; async fn ask(msg: &Message) -> Result<()> { let keyboard = ReplyKeyboardMarkup::default().text("Yes").text("No").resize(true); msg.answer("Use the keyboard below.").reply_markup(keyboard).await?; msg.answer("Keyboard removed.").reply_markup(ReplyKeyboardRemove::new()).await?; Ok(()) } ``` ### Handling a press A pressed button arrives as a `CallbackQuery` carrying `data` and the chat and message it is on. Register a handler with `on_callback_query` and a filter; `filters::data("yes")` matches one button, `filters::all()` every press. Answer the query with `query.answer()`, then edit the message the button was on: ```rust,no_run use vaegram::prelude::*; async fn setup(app: &Client) -> Result<()> { app.on_message(filters::command("menu"), |msg| async move { let keyboard = InlineKeyboardMarkup::default().callback("Yes", "yes").callback("No", "no"); msg.answer("Pick one:").reply_markup(keyboard).await?; Ok(()) }); app.on_callback_query(filters::data("yes"), |query| async move { query.answer().text("Saved").alert().await?; query.edit_message_text("You picked Yes.").html().await?; Ok(()) }); app.run().await } ``` `query.edit_message_text(..)` works on regular, inline and ephemeral messages; awaiting it gives `()`. `query.answer().text(..)` shows a toast, `.alert()` makes it a modal alert, `.url(..)` opens a link. Answer every query: the answer is all the user sees from the press. For the message itself, `query.message().await?` returns it (`None` if it was deleted), and then the usual methods work on it: `message.edit_text(..)`, `message.edit_caption(..)` and `message.edit_reply_markup(None)` to remove the keyboard. `message.wait_for_click()` waits for the next press on that message's buttons. ```rust,no_run use vaegram::prelude::*; async fn edit(msg: &Message) -> Result<()> { let edited = msg.edit_text("Updated").await?; edited.edit_reply_markup(None).await?; Ok(()) } ``` ## Common mistakes - Expecting `.row()` to make a row of its own: it only opens one, and buttons land in the last row, so a trailing `.row()` leaves an empty row in `rows`. - Removing a keyboard with an empty markup. Send `ReplyKeyboardRemove` for a reply keyboard, and `None` to `edit_reply_markup` for an inline one. - A callback button whose data no filter matches: `filters::all()` takes every press, while a wrong `filters::data(..)` ignores it silently. - Reading `query.data` as the pressed message: it is the button's payload, set by you. The message is `query.message().await?`. - Long callback data: Telegram caps it (64 bytes in the Bot API, https://core.telegram.org/bots/api#inlinekeyboardbutton). Keep an id or a short code there, not a whole state. ## See also - [API docs](https://docs.rs/vaegram/latest/vaegram/types/struct.InlineKeyboardMarkup.html) for `InlineKeyboardMarkup` and `InlineKeyboardButton`. - [API docs](https://docs.rs/vaegram/latest/vaegram/types/struct.CallbackQuery.html) for `CallbackQuery`. - [Receiving updates](/docs/receiving-updates.md), for how handlers and `run` work. - [Filters](/docs/filters.md), for combining callback filters. --- # Files and media Sending photos, documents and albums from a path, from bytes or from a file id, and getting the files back out of messages. ## Example ```rust,no_run use vaegram::prelude::*; use vaegram::types::{FileSource, Upload}; async fn send(client: &Client) -> Result<()> { // From a path on disk: &str, &Path and &PathBuf all convert. client.send_photo("me", "/tmp/cat.jpg").caption("My cat").await?; // From bytes in memory. The name's extension picks the MIME type. client.send_document("me", Upload::bytes("chart.png", b"\x89PNG\r\n\x1a\n")).await?; // From a file id, to send what Telegram already holds. let id = "AgACAgIAAxkBAAIENGfeY4AfRquwTL2LpDrzqvFMVNt_AAIG9DEbXX3wSq3oI7t_PqQGAQADAgADbQADNgQ"; client.send_photo("me", FileSource::file_id(id)?).await?; // Or let Telegram fetch it from a URL; only photos and plain documents take one. client.send_document("me", FileSource::url("https://example.com/report.pdf")?).await?; Ok(()) } ``` ## How it works Every media sender takes a `FileSource`, which converts from: - `&str`, `&Path`, `&PathBuf`: a file on disk, uploaded. - `Upload::bytes(name, data)`: bytes in memory, uploaded under `name`; its extension picks the MIME type. - `FileSource::file_id(id)?`: a file Telegram already stores. - `FileSource::url(url)?`: a link Telegram downloads itself; photos and plain documents only. - `&UploadedFile`, `&Photo`, `&Document` and the other media types: something already uploaded or received. There is one sender per kind: `send_photo`, `send_document`, `send_video`, `send_animation`, `send_audio`, `send_voice`, `send_video_note`, `send_sticker`, `send_live_photo`. Awaiting one uploads the file if needed and returns the sent `Message`; `.caption(..)`, `.file_name(..)`, `.has_spoiler()` and the rest are in the API docs. On a `Message`, `answer_photo(..)` and `reply_photo(..)` send into the same chat, and every kind has the same pair. ### Upload once, send many `upload_file(..)` and `upload_stream(..)` upload without sending and give an `UploadedFile`, which any sender takes as `&file`; it exposes `name()`, the name given at upload time. Telegram keeps the uploaded parts "between several minutes and several hours" (https://core.telegram.org/api/files#uploading-files); after that a send fails with `Error::Rpc` and a name such as `FILE_PART_1_MISSING`. To resend later, keep the sent message's `file_id`. ```rust,no_run use vaegram::prelude::*; use vaegram::types::Upload; async fn once(client: &Client) -> Result<()> { let file = client.upload_file(Upload::bytes("report.pdf", b"%PDF-1.7")).await?; client.send_document("me", &file).caption("The report").await?; client.send_document("@some_channel", &file).await?; Ok(()) } ``` ### Albums `send_media_group` takes 2 to 10 items and returns the sent `Message`s sorted by id. An album is photos and videos, only audio, or only documents; any other mix or count fails with `Error::InvalidArgument`. ```rust,no_run use vaegram::prelude::*; use vaegram::types::Upload; async fn album(client: &Client) -> Result<()> { let sent = client .send_media_group("me", [ InputMedia::photo("/tmp/a.jpg").caption("First"), InputMedia::photo(Upload::bytes("b.jpg", b"\xff\xd8\xff")).caption("Second"), InputMedia::video("/tmp/c.mp4").caption("Clip").duration(12), ]) .await?; println!("{} messages", sent.len()); Ok(()) } ``` ### What comes back The returned `Message` holds the media as `message.media`, read through `message.photo()`, `message.document()`, `message.video()` and the rest. A `Photo` carries `file_id`, `file_unique_id`, `width`, `height` and `file_size`; a `Document` carries `file_id`, `file_unique_id`, `file_name`, `mime_type` and `file_size`. `file_id` is what you send again and can change between sessions; compare `file_unique_id` to tell whether two values are the same file. A received `&Photo` or `&Document` goes back into any sender, as in the list above, so `message.answer_photo(photo)` resends a photo the user sent. ### Downloading `message.download()` returns a `DownloadMedia`: awaiting it gives the whole file as `Vec`, `.save(path)` writes it to disk (creating missing parent directories, replacing the target only on success), and `.stream()` yields chunks. `.progress(|done, total| ..)`, `.offset(..)` and `.limit(..)` are available on all three. `client.download_media(..)` does the same for anything that is a `Photo`, a `Document`, a `FileLocation` or a `file_id` string. ```rust,no_run use vaegram::prelude::*; async fn download(message: &Message) -> Result<()> { let bytes = message.download().await?; println!("{} bytes", bytes.len()); message.download().save("downloads/file.jpg").await?; Ok(()) } ``` A `FILE_REFERENCE_*` error means the file reference is stale: `message.download()` fetches the message again and retries once. A download of a business connection's message can't do that, so download it while handling it. ### Over the Bot API A client in Bot API mode sends and downloads through the HTTP API. Two limits sit there: `getFile` serves files of up to 20 MB, so a larger download fails with `Error::InvalidArgument` pointing at MTProto or a local server, and a file uploaded with `upload_file` can't be sent, only a path, bytes or a file id can. Uploads from a path or bytes travel inside the request that sends them. ## Common mistakes - Using a `file_id` from another bot or account, or comparing `file_id`s to deduplicate. An id is per account; compare `file_unique_id`, and keep one id per account. - Keeping an `UploadedFile` for a day. Telegram drops the parts after minutes to hours; resend the message's media. - Sending a photo id to `send_document` (or the reverse) through `FileSource::file_id`, which fails with `Error::InvalidArgument`; check the kind first when it isn't known. - Passing a name taken from an incoming message straight to `.save(..)`: the sender chose it and it can contain `..` or an absolute path. ## See also - [API docs](https://docs.rs/vaegram/latest/vaegram/types/struct.FileSource.html) for `FileSource`. - [API docs](https://docs.rs/vaegram/latest/vaegram/types/struct.InputMedia.html) for `InputMedia`. - [API docs](https://docs.rs/vaegram/latest/vaegram/methods/struct.DownloadMedia.html) for `DownloadMedia`. - [Sending messages](/docs/sending-messages.md), for captions, replies and what a send returns. - [Errors](/docs/errors.md), for `FILE_REFERENCE_*` and the other Telegram errors here. --- # Errors Every call returns `Result<_, Error>`. This page is about telling a Telegram error from a network one, reading a flood wait, and retrying without sending anything twice. ## Example ```rust use std::time::Duration; use vaegram::errors::{Error, RpcError}; let error = Error::Rpc(RpcError::new(420, "FLOOD_WAIT", Some(30))); assert_eq!(error.flood_wait(), Some(Duration::from_secs(30))); assert!(error.is_flood_wait()); if let Error::Rpc(rpc) = &error { assert_eq!((rpc.code, rpc.name.as_str(), rpc.value), (420, "FLOOD_WAIT", Some(30))); } let refused = Error::Rpc(RpcError::new(400, "PEER_ID_INVALID", None)); assert!(refused.is_peer_id_invalid()); assert!(!refused.is_flood_wait()); ``` ## How it works `vaegram::Result` is `std::result::Result`, so `?` works the same everywhere. ### Telegram's errors A request Telegram answered with an error is `Error::Rpc(RpcError { code, name, value })`. `code` works like an HTTP status (400 bad request, 401 not logged in, 420 flood limit, 500 server side), `name` is Telegram's name without the trailing number, so a match checks the name and reads the number from `value`: ```rust # use vaegram::prelude::*; # fn f(error: &Error) { if let Error::Rpc(rpc) = error { match (rpc.code, rpc.name.as_str(), rpc.value) { (420, "FLOOD_WAIT", Some(seconds)) => println!("wait {seconds} s"), (400, "PEER_ID_INVALID", _) => println!("this account can't reach that chat"), _ => println!("{rpc}"), } } # } ``` `Error::is("FLOOD_WAIT")` compares the name and ignores the number; `Error::rpc()` gives the `RpcError` back. There are named helpers for the errors you are likely to branch on: `is_peer_id_invalid`, `is_message_not_modified`, `is_chat_admin_required`, `is_user_is_blocked`, `is_query_id_invalid`, `is_auth_key_unregistered`, `is_peer_flood` and more, each documented in the API docs. `is_unauthorized()` covers every 401: the login is gone, or the two-step password is still needed. `is_file_reference_error()` covers the stale-file cases. ### Network errors The other variants mean the call didn't get a usable answer: - `Error::Io`: a socket, DNS or file read/write failed. - `Error::Timeout`: no answer within `request_timeout` (30 seconds by default), so the request was abandoned. - `Error::Disconnected`: the connection closed before the answer came. - `Error::Transport(404)`: the data center doesn't know the stored login; delete the session file and start again. A lost connection is reconnected and its waiting requests go out again without any setting. An `Io`, `Timeout` or `Disconnected` that reaches you was given up on, so retrying it is your decision. A `Timeout` doesn't say whether Telegram ran the request: a send carries a `random_id` and is recognised on a retry, a call without one may run twice. The remaining variants are local: `InvalidArgument` (the call can't work as built), `PeerNotFound` and `ChatNotJoined` (the chat needs meeting or joining first), `FileSize { size, limit }` (too big, or empty, for this account), `Unexpected` (an answer vaegram can't use), `Security` (a check failed, so the data was refused), `MissingDependency` (a handler asks for a `Dep` nobody provided), `Conversation` (a conversation didn't start or go on; the `ConversationError` says why), `ChatMigrated { chat_id }` (a group became that supergroup in Bot API mode), and `Other`, which carries an error of yours so a handler can return it. `Error::other(e)` builds one and `downcast_ref::()` reads it back; it looks only inside `Other`, so match the typed variants directly. ### Retrying safely By default the client sleeps off a `FLOOD_WAIT` of up to 60 seconds, five times per call, and hands longer ones to you as `Error::Rpc`. Raise, lower or turn that off when building: ```rust,no_run # use std::time::Duration; # use vaegram::prelude::*; async fn client() -> Result { Client::builder("my_bot", 1, "api-hash") .flood_sleep_threshold(Duration::from_secs(120)) .max_flood_sleeps(3) .start() .await } ``` `retry_policy(..)` replaces both with your own `RetryPolicy`; `NoRetries` hands every failure over. When a flood wait reaches you, sleep `error.flood_wait()` before the same call: sending again at once draws a longer one. ### Errors in handlers A handler returns `Result`; with `on_error` registered, every `Err` comes there with the route, the chat, the message and the error: ```rust,no_run use vaegram::prelude::*; async fn setup(app: &Client) -> Result<()> { app.on_error(|e| async move { eprintln!("{:?} failed: {}", e.kind, e.error); }); app.on_message(filters::text(), |msg| async move { match msg.answer("Hi").await { Ok(_) => Ok(()), // Waits of up to a minute were already slept off; this one is longer. Err(e) if e.is_flood_wait() => { let wait = e.flood_wait().expect("a flood wait has a duration"); eprintln!("flood wait of {} s, sending later", wait.as_secs()); Ok(()) } Err(e) => Err(e), } }); app.run().await } ``` Without `on_error`, the error goes to `on_event` as `HandlerFailed`, and with neither it is printed to stderr. An error stops the later handler groups for that update. ## Common mistakes - Matching on `"FLOOD_WAIT_30"`: the number is in `value`, so the name is `"FLOOD_WAIT"`. Use `is(..)` or `flood_wait()`. - Treating `Error::Rpc` like a network error and retrying at once. A flood wait needs its sleep; a 400 won't change. - Retrying a `Timeout` without checking what the call does: the request may have run already. - Catching every error in a handler and returning `Ok(())`. The failure disappears from `on_error` and from the event stream. - Logging `error.to_string()` only. `error.rpc()`, `flood_wait()` and the `is_*` helpers say what to do next. ## See also - [API docs](https://docs.rs/vaegram/latest/vaegram/errors/enum.Error.html) for `Error`. - [API docs](https://docs.rs/vaegram/latest/vaegram/errors/struct.RpcError.html) for `RpcError`. - [Telegram's error list](https://core.telegram.org/api/errors), for what an error name means. - [Flood limits](/docs/flood-limits.md), for the per-chat limit and the waits together. --- # 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::()` 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_`, 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). --- # 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, } async fn ban(msg: Message, Dep(config): Dep) -> 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`; - `.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`. 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>` 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). --- # Middleware Middleware runs your code around a router's filters and handlers. Outer middleware runs once per update, before anything in the router; inner middleware runs around each handler that matched. Both get a `Next` to pass the update on. ## Example An admin guard that stops the update for everyone else, and times the handler: ```no_run use vaegram::handlers::{Next, UpdateContext}; use vaegram::prelude::*; /// Provided to the handlers behind the guard. #[derive(Clone)] struct Admin(i64); async fn ban(msg: Message, Dep(admin): Dep) -> Result<()> { msg.reply(format!("Banned on behalf of {}.", admin.0)).await?; Ok(()) } #[tokio::main] async fn main() -> Result<()> { let app = Client::builder("guard_bot", 12345, std::env::var("API_HASH").unwrap()) .bot_token(std::env::var("BOT_TOKEN").unwrap()) .start() .await?; let mut admin = Router::new(); admin.outer_middleware(|mut ctx: UpdateContext, next: Next| async move { match ctx.user_id() { Some(id) if id == 42 => { ctx.provide(Admin(id)); next.run(ctx).await } // Returning without `next.run` keeps the update: later routes in this group don't see it. _ => Ok(()), } }); admin.inner_middleware(|ctx: UpdateContext, next: Next| async move { let started = std::time::Instant::now(); let result = next.run(ctx).await; eprintln!("handled in {:?}", started.elapsed()); result }); admin.message().handle(filters::command("ban"), ban); app.include_router(admin); app.run().await } ``` ## How it works ### Outer middleware `router.outer_middleware(f)` runs on every update that reaches the router, for the kinds it has handlers for; `router.message().outer_middleware(f)` adds one for a single kind, and makes the router take part in that kind even without a handler. What the middleware does with `Next` decides who sees the update (`src/handlers/router.rs:68-80`): 1. `next.run(ctx).await` hands it to the router's filters and handlers and gives back their result. 2. Returning without running `next` keeps the update: the routes after this router in its group never get it. 3. Running `next` and having nothing match passes the update on unchanged: the routes after this router in its group get it as it arrived, without this middleware's `provide` or `event_mut` changes. ### Inner middleware `router.inner_middleware(f)` wraps each handler of the router and of the routers inside it whose filter matched, after the outer middleware. Returning without `next.run` skips just that handler, which still takes its group's turn. A parent's inner middleware runs outside its children's (`src/handlers/router.rs:82-86`). The built-in `chat_action` is one: ```rust # use vaegram::enums::ChatAction; # use vaegram::handlers::{Router, chat_action}; # let mut router = Router::new(); router.inner_middleware(chat_action(ChatAction::Typing)); ``` ### The context `UpdateContext` carries the event, the client and the values provided so far: - `client()`, `kind()`, `chat_id()`, `user_id()`; - `event::()`, `event_mut::()`, and the shortcuts `message()` and `callback_query()`; - `data()`, `provide(value)` for handlers after this middleware (taken as `Dep`). `ctx.provide` replaces a value of the same type; `event_mut` changes stay inside the router when nothing matches. ### Order Filters decide before the update is parsed where they can, so a router whose filters miss costs nothing. Then the outer middleware in the order it was added (the first outermost, a parent's before its children's), the inner middleware around the matched handler, and the handler. An `Err` from any of them goes to the router's `on_error`, and one that reaches the client stops the later groups for that update. ## Common mistakes - Ending an outer middleware with `Ok(())` while wanting the update to continue: that is the "keep" outcome. Call `next.run(ctx).await` and return its result. - Changing `ctx` and expecting later routers to see it when nothing matched: they get the update as it arrived. - Using outer middleware for per-handler work: it runs even when no handler matches. Use inner middleware. - Dropping the result of `next.run`: errors stop at the middleware, and `on_error` never sees them. - Adding middleware to a router that is never included: it never runs. ## See also - [API docs](https://docs.rs/vaegram/latest/vaegram/handlers/index.html) for `Next`, `UpdateContext` and `chat_action`. - [Routers](/docs/routers.md). - [Filters](/docs/filters.md). - [Errors](/docs/errors.md). --- # 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| 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::() 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` 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`: | 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 = 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`: `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. --- # Conversations A conversation is a multi-step flow written as one async function that waits for each answer in place. The function runs on its own task while it waits, so it holds no handler slot. ## Example ```no_run use std::time::Duration; use vaegram::prelude::*; async fn signup(mut conv: Conversation, msg: Message) -> Result<()> { msg.reply("What's your name?").await?; let name = conv.wait_for(filters::text()).await?.text().to_owned(); msg.reply("How old are you?").await?; let age: u8 = conv.form().number().await?; msg.reply(format!("Welcome, {name} ({age})!")).await?; Ok(()) } # fn setup(client: &Client) { client.conversation("signup", signup).timeout(Duration::from_secs(600)).ignore_commands(); client.on_message(filters::command("start"), |msg| async move { msg.client().enter_conversation("signup", msg.clone()) }); client.on_message(filters::command("cancel"), |msg| async move { let ended = msg.client().exit_conversation("signup", &msg); msg.reply(if ended > 0 { "Cancelled." } else { "Nothing to cancel." }).await }); # } ``` ## How it works ### Register and enter `client.conversation(name, f)` registers `f` under `name`. `enter_conversation(name, update)` starts it with the update a handler got, usually `msg.clone()`, and returns at once: the function runs on its own task, so the handler frees its slot. Its second argument can be a `Message` or a `CallbackQuery`; the other kind fails with `ConversationError::WrongUpdate`. A second start under the same key fails with `ConversationError::Busy`. Re-registering a name replaces the function and its settings; the conversations already running go on. ### What it sees A conversation sees the new messages and button presses of its chat and user, as its `Scope` keys them; never edits, never updates through a business connection. It lives in memory only, and a return, an error or a panic ends it. While its code runs between two waits it keeps incoming updates, up to 64 (`src/conversation/inbox.rs:18`), for the next wait, so an answer that arrives before the question's `send_message` returns still counts. Updates a wait doesn't want go on to the handlers, as if the conversation weren't there. To send, reply to the update that started it with `msg.reply`, or use `conv.client()`; `Conversation` has no `send` of its own. `conv.name()`, `conv.chat_id()` and `conv.user_id()` say which conversation it is. ### Waiting | Call | Returns the next | |---|---| | `wait()` | new message. | | `wait_for(filter)` | message that passes `filter`, such as `filters::text()`. | | `wait_from(user_id)` | message from that user, for a conversation shared by a chat. | | `wait_for_command(names)` | of these commands. | | `wait_for_callback_query(filter)` | button press that passes `filter`, such as `filters::data("yes")`. | | `wait_either(messages, presses)` | message or press, whichever comes first, as an `Answer`. | These are defined at `src/conversation/handle.rs:95-131`. Awaiting one pauses the function until the update arrives. A wait has `.and(filter)`, `.otherwise(f)`, `.timeout(d)` and `.no_timeout()`; waits for presses also have `.message_id(id)` for one message's keyboard. `Answer` is `#[non_exhaustive]`: match `Answer::Message` and `Answer::CallbackQuery`, plus a `_` arm for variants a later release may add. A command is an ordinary text answer: `/cancel` sent while the conversation waits for a name becomes the name, unless the conversation ignores commands or the wait's filter leaves them out, as in `filters::text() & !filters::command("cancel")`. ### Typed answers `form()` reads one typed value and keeps the messages it can't read, so a typo never reaches an unrelated handler (fields at `src/conversation/form.rs:22-58`): ```rust # use vaegram::prelude::*; # async fn pick(mut conv: Conversation, msg: Message) -> Result<()> { let plan = conv .form() .select(["free", "pro"]) .otherwise(|m: Message| async move { m.reply("Pick free or pro.").await }) .await?; msg.reply(format!("{plan} it is.")).await?; # Ok(()) # } ``` The fields are `text()` for a string, `number()` for any `FromStr` type (`300` for a `u8` does not parse), `select(options)` for one of several, `photo()` for a `Photo`, and `field(read)` for your own. Messages a field can't read run its `otherwise`, or are dropped without one; in a parallel conversation they go to the handlers. ### Leaving Returning from the function ends the conversation. `conv.halt()` ends it without an error report; from any handler, `client.exit_conversation(name, &update)` ends it and returns how many it ended. A wait that times out fails with `Error::ListenerTimeout`, one cut short by the client with `Error::ListenerStopped`, and returning either with `?` ends the conversation quietly (`src/conversation/registry.rs:298`). Updates the conversation took and never read go to the handlers, never to another conversation. ### Timeouts and cancelling `ConversationRef::timeout(d)` sets how long each wait waits; without it a wait uses the client's `listener_timeout` (5 minutes unless set), and `no_timeout()` lets it wait as long as it takes (`src/conversation/handle.rs:60`). A single wait overrides both. A wait that times out fails with `Error::ListenerTimeout`; returning it with `?` ends the conversation without a report. Catch that variant to reply first, and let any other error through. To let the user cancel by command, keep the command out of the conversation with `ignore_commands()` or `ignore(filters::command("cancel"))`, then let the command's handler call `exit_conversation`. ### One at a time, and in parallel By default one conversation runs per user in each chat, and a second `enter_conversation` there fails with `Busy` (`src/conversation/registry.rs:167`). `parallel()` lets conversations of the same name, and one conversation with itself, run under one key when they are all parallel. The oldest gets each update first, and one it doesn't want goes on to the next. A parallel conversation keeps nothing for later between its waits, and `otherwise` on one makes that wait fail with `ConversationError::OtherwiseInParallel`. ### Topics, and splitting a flow `scope(Scope::UserInTopic)` (or `ChatTopic`) keys a conversation by forum topic. Start it from a message, and give every wait for presses a `.message_id(id)`: a press doesn't say its topic, so a wait without one fails with `ConversationError::UnpinnedPress`. There is no API to nest one conversation inside another: `enter_conversation` under the same key while one runs fails with `Busy` unless both are parallel. Split a flow into plain async helpers that take `&mut Conversation` instead. ## Common mistakes - A command is taken as the answer: `/cancel` is text like any other; call `ignore_commands()` and handle it in a normal handler. - A wait never gets its press: under the topic scopes, pin it with `.message_id(id)` (`src/conversation/handle.rs:161`). - `otherwise` on a parallel conversation fails with `OtherwiseInParallel` (`src/conversation/handle.rs:157`); let the other conversation take the update instead. - Starting a listener inside a conversation: an `ask` or `listen` started after it never gets what the conversation takes; use the conversation's own waits. - Expecting the flow to survive a restart: it doesn't; use a dialogue with a persistent storage. ## See also - [API docs](https://docs.rs/vaegram/latest/vaegram/conversation/index.html) for `Conversation`, `Wait` and `Form`. - [Dialogues](/docs/dialogues.md) for a flow that survives a restart. - [Testing](/docs/testing.md) for driving a conversation with the test kit. - [Receiving updates](/docs/receiving-updates.md) for handlers and `run`. --- # Testing A test client answers requests inside the process and records every one it sends, so a bot's tests need no token and no network. The test kit is `vaegram::test`. ## Example ```rust use vaegram::filters; use vaegram::test::{CallKind, TestMessage}; use vaegram::Client; #[tokio::main] async fn main() { let (client, recorder) = Client::recording(); client.on_message(filters::command("start"), |msg| async move { msg.reply("Welcome!").await }); recorder.feed(TestMessage::private(42, "/start")).await; assert_eq!(recorder.sent_texts(42), ["Welcome!"]); assert!(recorder.calls().iter().any(|call| matches!( &call.kind, CallKind::SendMessage { reply_to_message_id: Some(_), .. } ))); } ``` ## How it works ### A client that never connects `Client::recording()` returns a bot client, id 1000, and a `CallRecorder`. The client answers the requests bots send most with what Telegram would answer, numbering messages from 1 up (`src/test/mod.rs:27-46`), and the recorder keeps each request it sent. `Client::scripted()` returns a `Script` instead: strict, so a request it has no answer for fails, until `auto_reply(true)` turns the same defaults on. Both keep their login and peers in memory and never retry (`src/test/mod.rs:144`). Make them inside a Tokio runtime, such as the one `#[tokio::test]` starts. `TestBuilder` sets the account and the client's settings first (`src/test/mod.rs:135-205`): `bot(id, Some("username"))` or `user(id, premium)`, then `ordered(true)`, `max_concurrent_handlers(n)`, `parse_mode(mode)` and `auto_sleep(policy)`; `recording()` or `scripted()` finishes. ### Feeding updates `recorder.feed(update)` hands an update to the handlers and waits for them to finish. `dispatch(update)` returns once they start, and `settle()` waits for everything running; `feed` is the two together (`src/test/harness.rs:86-107`). `recv()` waits for the next request the client sends, for a handler running on its own task. Build updates with `TestMessage::private(user_id, text)` or `TestMessage::in_chat(chat, user, text)`, which take `.reply_to(id)`, `.thread_id(topic)`, `.id(id)` and `.outgoing(true)`, and with `TestCallbackQuery::new(user_id, chat_id, message_id, data)`. `TestChat::private`, `group`, `supergroup` and `channel` build the chat, and `TestChat::supergroup(id).forum(true)` adds topics; `TestUser::new(id)` is the sender. The users and chats an update names land in the client's peer cache, so `client.send_message(42, ..)` works afterwards; `know_user` and `know_chat` add peers no update named. `TestUpdate::EditedMessage(msg)` feeds an edit. A handler that waits for a second update, in `ask` or `listen`, would keep `feed` waiting for it. Dispatch the first update, await the question with `recv`, feed the answer, then settle: ```rust use vaegram::filters; use vaegram::test::TestMessage; use vaegram::Client; # async fn f() { let (client, recorder) = Client::recording(); client.on_message(filters::command("name"), |msg| async move { let answer = msg.client().ask(msg.chat.id, "What's your name?").await?; msg.reply(format!("Hi, {}", answer.text())).await }); recorder.dispatch(TestMessage::private(42, "/name")).await; assert!(recorder.recv().await.is_some(), "the question was sent"); recorder.feed(TestMessage::private(42, "Ann")).await; recorder.settle().await; assert_eq!(recorder.sent_texts(42), ["What's your name?", "Hi, Ann"]); # } ``` ### What the bot sent `calls()` returns every `RecordedCall` since the last `take_calls()`: its `method` is the TL name, such as `"messages.sendMessage"`, and its `kind` is a `CallKind` for the requests bots send most. Match with `..`, since a variant may gain fields. `sent_texts(chat_id)` is the shortcut for the texts of the text messages sent there; media sends and edits are not in it. ### Choosing answers A `Script` answers in this order: the next reply queued for the method with `reply_next` or `fail_next`, the method's `on_call` responder, the default answer when `auto_reply` is on (`src/test/mod.rs:294-297`). A queued `Reply` is `OkDefault`, `Bool(b)`, `SentMessage { id }`, or `Error(error)`: ```rust use std::time::Duration; use vaegram::test::Reply; use vaegram::{Client, RpcError}; # async fn f() { let (client, script) = Client::scripted(); script.auto_reply(true); script.fail_next("messages.sendMessage", RpcError::new(420, "FLOOD_WAIT", Some(30))); // A test client never retries: the flood wait comes straight back. let error = client.send_message(42, "hi").await.unwrap_err(); assert_eq!(error.flood_wait(), Some(Duration::from_secs(30))); script.on_call("messages.sendMessage", |_call| Reply::SentMessage { id: 7 }); assert_eq!(client.send_message(42, "hi").await.unwrap().id, 7); # } ``` A request the script has no answer for fails with `TestError::Unscripted` inside `Error::Other`; read it back with `error.downcast_ref::()`. ### The update loop `recorder.push_stream(update)` feeds `run` the way the connection does, through the tracker that holds updates on a `pts` gap, and `close_stream()` ends it. Start `run` on a task of its own first. Use it only to test that layer: `feed` and `dispatch` skip it. ### What a test client does not do It never dials Telegram, and a file transfer to another data center fails at once. On a recording client, and on a script with `auto_reply` on, a request without a default answer, such as fetching old messages, fails with `TestError::NoDefaultAnswer`; answer it with `on_call`. A strict script, with `auto_reply` off, answers nothing it was not given, so every request without a queued reply or an `on_call` responder fails with `TestError::Unscripted`. ## Common mistakes - `feed` hangs in a handler that waits in `ask`: dispatch the first update, take the question with `recv`, feed the answer, then settle (`src/test/harness.rs:88-107`). - Asserting too early: a conversation or a spawned task runs on its own task; settle before you assert. - Matching a `CallKind` without `..`: each variant may gain fields (`src/test/calls.rs:36-39`). - Creating a test client outside a runtime: `Client::recording` panics; call it inside `#[tokio::test]`. - Expecting media in `sent_texts`: it lists `SendMessage` only (`src/test/mod.rs:279-289`); match `CallKind::SendMedia` in `calls`. - Expecting a peer to be known: only users and chats an update named, or `know_user`/`know_chat`, are cached. ## See also - [API docs](https://docs.rs/vaegram/latest/vaegram/test/index.html) for `TestBuilder`, `CallRecorder` and `Script`. - [Receiving updates](/docs/receiving-updates.md) for the handlers and `run` the kit drives. - [Filters](/docs/filters.md) for picking the updates to feed. - [Dialogues](/docs/dialogues.md) and [Conversations](/docs/conversations.md) for the flows a test usually drives. --- # Deployment How a vaegram client takes updates in production, stops cleanly, and avoids fighting a second copy of itself. A deployed bot is a process that stays connected for weeks. What keeps it that way is how it gets updates, how it shuts down, and how many copies run. ## Example ```no_run use vaegram::prelude::*; #[tokio::main] async fn main() -> Result<()> { let bot = Client::builder("my_bot", 12345, "0123456789abcdef0123456789abcdef") .bot_token("123456:ABC-DEF") .start() .await?; bot.on_message(filters::command("start"), |msg| async move { msg.answer("Hello!").await?; Ok(()) }); bot.run().await } ``` `run` returns `Ok(())` after `stop`, and `Error::Disconnected` when the connection ends first. ## How updates arrive | Mode | How updates reach the handlers | When to use it | |---|---|---| | MTProto (default) | Telegram pushes updates on the connection; `run` dispatches them | user accounts, MTProto bots | | Bot API polling | `run` long-polls `getUpdates` | a Bot API bot that can reach `api.telegram.org` | | Bot API webhook | Telegram POSTs to your HTTPS URL; a `Webhook` dispatches them | a Bot API bot behind a public HTTPS proxy | The first two are the same call, `run`. In Bot API mode a webhook replaces the poll: while one is set, `Client::run` gets Telegram's 409 error instead of updates. ## Webhooks Webhook mode needs the `bot-api` feature, and the built-in server needs `webhook-server`. The flow is always: make a receiver with a secret, register the public URL, then feed it requests. ```no_run use vaegram::prelude::*; #[tokio::main] async fn main() -> Result<()> { let bot = Client::builder("my_bot", 12345, "0123456789abcdef0123456789abcdef") .bot_api(std::env::var("BOT_TOKEN").expect("BOT_TOKEN")) .start() .await?; let secret = std::env::var("WEBHOOK_SECRET").expect("WEBHOOK_SECRET"); let webhook = bot.webhook(secret)?; webhook.register("https://bot.example.com/telegram").await?; webhook.serve("127.0.0.1:8080").await } ``` The API id and hash are not used in Bot API mode, but `Client::builder` still takes them. - **The secret** is 1 to 256 characters of `A-Z`, `a-z`, `0-9`, `_` and `-`. Keep it in the environment or a secret store. The receiver compares it in constant time; `serve` rejects a request before reading its body. - **The URL** must be HTTPS, on port 443, 80, 88 or 8443. `serve` speaks plain HTTP, so it belongs behind a reverse proxy that terminates TLS: bind it where only the proxy reaches it and register the proxy's public URL. - **A self-signed certificate** is uploaded with the webhook: `.certificate(pem_bytes)` on the request `register` returns. `.ip_address("203.0.113.10")` pins where Telegram sends requests, and `.max_connections(40)` sets how many it sends at once (1 to 100). - **`get_webhook_info`** reports the URL, `pending_update_count` and `last_error_message`, which is the first thing to read when deliveries stop. ### Your own HTTP server `Webhook::handle` takes one request's body and headers and returns a `WebhookResponse`; answer the request with its `status()`. Drive the handlers with `webhook.run().await` (it is `Client::run`, fed by the webhook) and mount `handle` in whatever server you already run. ```no_run # async fn f(webhook: vaegram::bot_api::Webhook, body: Vec, token: Option<&str>) -> vaegram::Result<()> { let headers = token.into_iter().map(|value| ("X-Telegram-Bot-Api-Secret-Token", value)); let answer = webhook.handle(&body, headers).await; match answer.status() { 200 => {} // queued for the handlers, or already taken 401 => {} // wrong or missing secret; nothing was queued _ => {} // 503: no run is taking updates, or the queue stayed full } # Ok(()) } ``` `serve` is a small HTTP/1.1 server around the same path: it accepts POST only (405 otherwise), checks the secret before reading the body (401), caps a body at 4 MiB (413), serves 256 connections at once, and answers 200 as soon as an update is queued, so a slow handler never causes a redelivery. To go back to polling, `bot.delete_webhook().await?;` and then `run`. ## Graceful shutdown `run_until_signal` stops on Ctrl-C or, on Unix, SIGTERM, which is what containers and service managers send. It calls `stop`, so `run` finishes the handlers already running and returns `Ok(())`. ```no_run # async fn f(bot: vaegram::Client) -> vaegram::Result<()> { bot.run_until_signal().await?; // Ctrl-C or SIGTERM calls stop() bot.close().await; // waits for the final save before the process exits # Ok(()) } ``` - `stop_with_timeout(d)` bounds that wait: handlers still running at the deadline are cancelled and reported as `Error::Timeout`. - `run` saves the update state as it returns; `close().await` is what flushes and closes the storage. Await it before `std::process::exit` or `Runtime::shutdown_background`, which do not wait for a save a plain drop starts in the background. - Returning from `main`, `#[tokio::main]` included, waits for that save. ## One instance per session The default `FileStorage` keeps `.session` and holds `.session.lock` while the client is open. A second client on the same file, in this process or another, fails with `ResourceBusy` instead of writing interleaved records. That lock does not protect you from running the same login on two machines: copying the session file and starting both gets the auth key revoked by Telegram (`Error::is_auth_key_duplicated`), and both clients must log in again. One process per login, or log in separately on each. In Bot API mode Telegram allows one consumer of a bot's updates: a second poller, or a poll while a webhook is set, gets 409. ## Behind a proxy `ClientBuilder::proxy` takes a parsed `Proxy`. Any address or link `Proxy` understands works, including `tg://proxy`, `tg://socks` and `t.me/proxy` links. ```no_run use vaegram::connection::Proxy; # async fn f() -> vaegram::Result<()> { let proxy: Proxy = "tg://socks?server=127.0.0.1&port=1080".parse()?; let _bot = vaegram::Client::builder("my_bot", 12345, "0123456789abcdef0123456789abcdef") .bot_token("123456:ABC-DEF") .proxy(proxy); # Ok(()) } ``` - SOCKS5, SOCKS4 and HTTP CONNECT are built in; HTTP CONNECT sends Basic credentials in the clear. - An MTProxy goes through `.proxy(Proxy::MtProxy { .. })`; the secret picks padding or fake TLS. - On a network that only lets HTTPS out, the `web-proxy` feature adds `Proxy::Web`, an MTProxy stream carried in HTTPS requests to a relay (`tg://webproxy` links). The `websocket` feature is the other way out: `.websocket()` connects over TLS to `web.telegram.org`. ## Common mistakes - Registering `http://` or a non-standard port. Telegram only posts to HTTPS on 443, 80, 88 and 8443. - Calling `webhook.serve` before `register`, or without a running `run`: every request is answered 503. - Using `run_until_ctrl_c` in a container. SIGTERM ends the process without a clean stop; use `run_until_signal`. - Skipping `close().await` before `std::process::exit`, and losing the last update state. ## See also - [API docs](https://docs.rs/vaegram/latest/vaegram/bot_api/struct.Webhook.html) for `Webhook` and `WebhookResponse`. - [Receiving updates](/docs/receiving-updates.md) for handlers and the update loop. - [Bot API mode vs MTProto](/docs/bot-api-vs-mtproto.md) for what each transport supports. - [Sessions and storage](/docs/sessions-and-storage.md) for the session file and its lock. --- # Flood limits The two limits every sender meets: vaegram's own pacing, and Telegram's `FLOOD_WAIT`. Both exist so a busy client slows down instead of getting an account-limited `PEER_FLOOD` or a ban. The client paces itself; Telegram answers with a wait when something still goes too fast. ## Example ```rust use vaegram::prelude::*; use vaegram::session::{ChatRateLimits, RateCategory, RateLimits}; let limits = RateLimits::default() .limit(RateCategory::Message, 20.0, 30.0) .per_chat(ChatRateLimits::default()); let _bot = Client::builder("my_bot", 12345, "0123456789abcdef0123456789abcdef") .rate_limits(limits); ``` ## vaegram's limiter A call that goes through the limiter counts against one category bucket and the `Global` bucket. Categories are `Message`, `Media`, `Query`, `Admin`, `Bulk` and `Account`, chosen from the TL method name; `Client::invoke_for_chat` (and the client's own sends, edits, forwards and copies) also counts against that chat's bucket. File parts are not paced here. Defaults: - **A bot gets no limiter** unless `rate_limits` is set, so it goes at network speed. - **A user account gets `RateLimits::user_account()`**: a message a second, a file every two seconds, a chat change a second, reads in bursts, and the per-chat limits below. Sending like a bot from a user account risks a ban, not just a wait. - **Before login** the default limiter stands aside. It starts holding a user account back once `getMe` says the account is a user, and stays aside for a bot. `RateLimits::default()` is the bots' pace: 20 messages a second, 30 in a burst, with no per-chat limits. It is not an unlimited preset, and `limit` refuses a rate that is not finite and above 0. A user account always gets a limiter; the closest to 0.3's none is a high finite rate per category with `no_per_chat()`. ### Per-chat limits `ChatRateLimits::default()` gives a private chat one message a second with no burst, and a group, supergroup or channel the same plus at most 20 messages in any 60 seconds. Telegram answers `FLOOD_WAIT` above roughly those numbers, which is why they are the defaults. - `private(rate, burst)`, `group(rate, burst)` and `group_per_minute(Option)` change them. - The limiter keeps a bucket per chat by id, up to 10 000 chats; `max_tracked_chats` and `idle_ttl` control eviction. - `no_per_chat()` takes chat limits off, and `per_chat(..)` puts them on a bot: `RateLimits::default().per_chat(ChatRateLimits::default())`. ```no_run use vaegram::prelude::*; # async fn f(bot: &Client) -> Result<()> { if let Some(limiter) = bot.rate_limiter() { println!("global bucket {:.0}% used", limiter.congestion() * 100.0); } bot.send_message(7, "one").await?; // waits for chat 7's bucket bot.send_message(7, "two").await?; // waits about a second more # Ok(()) } ``` `Client::rate_limiter()` is `None` for an unlimited bot. `RateLimiter::available`, `try_acquire`, `try_acquire_chat`, `tracked_chats` and `update_limits` read or change it while the client runs. ## Telegram's flood waits A flood wait is a `420` error whose name ends in a number of seconds: `FLOOD_WAIT_30`, `FLOOD_PREMIUM_WAIT_30`, `SLOWMODE_WAIT_30`. It arrives as `Error::Rpc`, and `Error::flood_wait()` reads the duration. By default (`AutoSleep`) the session sleeps off waits of up to 60 seconds, at most 5 per call, and retries. A longer wait, or the sixth one, goes to the caller as `Error::Rpc`. ```no_run use std::time::Duration; use vaegram::prelude::*; # async fn f(bot: &Client) -> Result<()> { match bot.send_message(7, "hi").await { Ok(_) => {} Err(e) if e.is_flood_wait() => { let wait = e.flood_wait().unwrap_or(Duration::from_secs(1)); eprintln!("Telegram says wait {wait:?}"); } Err(e) => return Err(e), } # Ok(()) } ``` - `flood_sleep_threshold(d)` sets the longest wait slept off; `Duration::ZERO` surfaces every one. - `max_flood_sleeps(n)` sets how many a call sleeps off; `0` surfaces every one. - `retry_policy(NoRetries)` hands every failure to the caller, file parts included. - A waited-off `FLOOD_WAIT` or `SLOWMODE_WAIT` also holds that chat's next message back by the wait, and no other chat's. The client does this itself for the calls it sends to one chat; raw calls can use `client.rate_limiter().unwrap().penalize_chat(id, wait)`. - A file part gets four times the tries, since one part stands for a whole transfer. `FLOOD_WAIT` is not the only account limit: `PEER_FLOOD` (code 400, no number) means the account messaged too many strangers. It is not a wait; `Error::is_peer_flood()` recognizes it, and retrying makes it worse. A hard cap on volume is separate: `RateLimits::daily_limit(category, max)` allows `max` requests in any 24 hours. The count lives with the client, so a restart forgets it. ## Practical batching - **Await each send to one chat.** The limiter queues waiters in order; firing a thousand sends at one chat with `join_all` does not go faster, it just parks a thousand tasks in memory. - **Fan out across chats, not within one.** The per-chat buckets are independent; the global bucket is the ceiling. - **Do not sleep before every send yourself.** The limiter already does it, and a manual sleep stacks on top. Sleep only where you must react to a surfaced `FLOOD_WAIT`. - **A repeated update is not a reason to resend.** Redeliveries and catch-up can hand a handler an update twice; make the send idempotent or check the message cache instead of retrying blindly. - **Keep the default retry settings for long-running bots.** They absorb normal waits; lower the threshold only when a scheduler must reschedule the work itself. - **Watch `congestion()`.** A global bucket near 100% means the client is at its own ceiling, so more parallelism will not help. ## Common mistakes - Expecting a bot to be paced by default. It is not; call `rate_limits(..)`. - Setting `RateLimits::default()` on a user account to "remove limits". That is 20 messages a second from a person and is a ban risk. - Matching on `Error::Rpc` and comparing `name == "FLOOD_WAIT_30"`. Use `is_flood_wait()` and `flood_wait()`; the number is split into `RpcError::value`. - Retrying `PEER_FLOOD` on a timer. It is lifted by Telegram, not by waiting out a number. ## See also - [API docs](https://docs.rs/vaegram/latest/vaegram/session/struct.RateLimits.html) for `RateLimits`, `ChatRateLimits` and `RateLimiter`. - [Errors](/docs/errors.md) for `Error`, `RpcError` and retry policy. - [Sending messages](/docs/sending-messages.md) for the calls that count against the limits. --- # Sessions and storage Where a client keeps its login, its update position and the peers it has met, and how to move that from one process to another. "Session" means the saved auth key and where updates resume. vaegram stores it in a file by default; any `Storage` engine can replace the file. ## Example ```no_run use vaegram::prelude::*; #[tokio::main] async fn main() -> Result<()> { let bot = Client::builder("echo", 12345, "0123456789abcdef0123456789abcdef") .bot_token("123456:ABC-DEF") .workdir("/var/lib/mybot") .start() .await?; bot.on_message(filters::command("start"), |msg| async move { msg.answer("Ready.").await?; Ok(()) }); bot.run().await } ``` The first run logs in and writes `/var/lib/mybot/echo.session`; later runs log in from it. `Client::is_signed_in()` answers whether the client already holds a login, without a request to Telegram: false before a login, true once one is cached. ## What a session holds - **The login**: the data center id, the 256-byte auth key, the api id, the account's user id, and the bot and test-server flags. - **The update state**: the account's `pts`, `qts`, `date` and `seq`, plus each channel's `pts`. `run` resumes from it, which is how a restart does not miss or repeat updates. - **Peers**: the id, access hash, known usernames and phone number of every user and chat the client met, so it can address them again without a lookup. ## The session file `FileStorage`, the default, keeps all three in one `.session` file. The name comes from `Client::builder` and may contain a directory: `"bots/echo"` keeps `bots/echo.session` under `workdir` (the working directory if unset). - The file is created private to the user (0600 on Unix). - Each save appends a record; the file is rewritten whole once the appended bytes outgrow what it holds. - A torn last record from a crash is ignored; the records before it stand. - While a client has the file open it holds `.session.lock` in the same directory. A second client on the same file fails with `ResourceBusy`, even in another process. The lock goes with the process, so a crash leaves no stale lock, only the empty `.lock` file. ## Session strings `Client::export_session_string` renders the login as one `VAE_…` line. It is the auth key: anyone who has it is logged in as the account. ```no_run use vaegram::prelude::*; # async fn f(bot: &Client) -> Result<()> { let line = bot.export_session_string(); let other = Client::builder("copy", 12345, "0123456789abcdef0123456789abcdef") .session_string(line) .bot_token("123456:ABC-DEF") .start() .await?; # let _ = other; Ok(()) } ``` `vaegram::storage::session_string::parse` reads one back without a client, and fails with a message meant for the user: ```rust use vaegram::storage::session_string; fn main() { match session_string::parse("VAE_not-a-real-string") { Ok(data) => println!("data center {}", data.dc_id), Err(why) => eprintln!("{why}"), } } ``` The parser also accepts a few layouts other tools write: `WZ_`-prefixed strings, unprefixed fixed-size strings, and the address-first form. The exporter never writes those, only reads them. A string in a layout it cannot use fails with a message meant for the user, such as an old fixed layout whose generation byte it does not know. ## Choosing storage Three builder methods choose where the session lives, and the last of them called wins. `workdir` only moves the default file. ```rust use vaegram::prelude::*; use vaegram::storage::MemoryStorage; let _bot = Client::builder("my_bot", 12345, "0123456789abcdef0123456789abcdef") .storage_engine(MemoryStorage::new()); // the same as .in_memory() ``` - `storage_engine(engine)` keeps the login, state and peers in any `Storage`; it runs on a thread of the client's own, so an engine may block. - `session_string(s)` keeps them in memory and starts from `s`. The login is then never written, so the next run needs the string again. - `in_memory()` keeps everything in memory and writes nothing; without an exported session string the next run logs in again. - `workdir(dir)` only moves the default file; it is ignored once another storage is chosen. The `Storage` trait itself is small: `open`, `close`, `delete`, `load_session`, `save_session`, `load_state`, `save_state`, `update_peers`, `get_peer_by_id`, `get_peer_by_username`, `get_peer_by_phone_number`, `export_peers`, `clear_peers`. Implement it to keep a session anywhere. ### Engines | Engine | Feature | Constructor | Keeps it in | |---|---|---|---| | `FileStorage` | none (default) | `FileStorage::new(name)` | the `.session` file above | | `MemoryStorage` | none | `MemoryStorage::new()` | memory only | | `SqliteStorage` | `sqlite` | `SqliteStorage::new(path)` | a SQLite database, WAL mode, schema version 8 | | `RedbStorage` | `redb` | `RedbStorage::new(path)` | a redb file, one process per file | | `RedisStorage` | `redis` | `RedisStorage::new(url, name)` | Redis keys under `vaegram:` | | `MongoStorage` | `mongodb` | `MongoStorage::new(uri, name)` | a Mongo database named after the session | | `PostgresStorage` | `postgres` | `PostgresStorage::new(config, tls, name)` | a schema `name` in that database | | `S3Storage` | `s3` | `S3Storage::from_env(bucket, key)` | one S3-compatible object | | `VaultStorage` | `vault` | `VaultStorage::new(addr, token, mount, path)` | a HashiCorp Vault secret | Details that bite: - **SQLite** opens databases in the schema other MTProto tools use (version 8), so an existing `.session` database opens here; it is migrated in place, so keep a copy. - **Redis** needs `maxmemory-policy noeviction`; an evicted session key is a lost login. On a cluster, give the prefix a hash tag so its keys share a slot. - **Postgres** creates its schema and holds a lock on it: one client per schema, a second gets `ResourceBusy` until the first closes. - **S3** uploads conditionally (`If-Match`) and refuses to overwrite an object another client wrote. State and peers upload at most every 30 seconds and on close. - **Vault** stores one session string in a secret; every write names the version it read. The token is not renewed, so it must outlive the client. ## Closing The update state is saved when `run` returns or its future is dropped, and while it runs within about 10 seconds of moving. The storage closes on `close().await`, on `disconnect()`, or when the last clone of the client is dropped (in the background, without blocking the runtime). `close` waits for the final save once no `run` owns the client; `disconnect()` does the same work but blocks the thread it runs on for up to 10 seconds. Await `close` after `run` returns and before opening the same session again in the same process, or before `std::process::exit`. ## Common mistakes - Copying a `.session` file to a second machine and running both. Telegram revokes the duplicated auth key (`AUTH_KEY_DUPLICATED`); log in separately instead. - Committing a `.session` file or a session string. Both are the login. - Using `in_memory()` and expecting peers or the login after a restart. - Setting `workdir` while another storage is chosen. - Running two clients on one Postgres schema, or two processes on one redb file. - Passing a SQLite path without an extension expecting one to be added; `SqliteStorage::new` takes the path as given. ## See also - [API docs](https://docs.rs/vaegram/latest/vaegram/storage/index.html) for `Storage`, `FileStorage` and `SessionData`. - [Your first bot](/docs/first-bot.md) for the login flow this page shortens. - [Deployment](/docs/deployment.md) for the lock and one-instance rules in a running service. - [Migration 0.3 to 0.4](/docs/migration-03-to-04.md) for what changed in storage. --- # Migration 0.3 to 0.4 Every user-visible change from vaegram 0.3.0 to 0.4.0-nightly.2, with the old code and its replacement. Most 0.3.0 code compiles unchanged. What follows is what does not compile, plus the defaults and behaviour that changed under code that still does. ## Example The shutdown every 0.4.0 service needs. Only the `close` line is new. ```no_run # async fn f(bot: vaegram::Client) -> vaegram::Result<()> { bot.run_until_signal().await?; // stop on Ctrl-C or SIGTERM bot.close().await; // wait for the final save # Ok(()) } ``` ## Handlers did not change `on_message` and the rest still take `Fn(T)`, and the client rides inside the update: `msg.answer(..)`, `query.answer()`. The first nightly (0.4.0-nightly.1) passed the client as a first argument; nightly.2 reverted that. ```text // 0.4.0-nightly.1 only: app.on_message(filter, |client, msg| async move { ... }); // 0.3.0 and 0.4.0-nightly.2: app.on_message(filter, |msg| async move { msg.answer("hi").await?; Ok(()) }); ``` If you wrote against nightly.1, drop the extra parameter; nothing else changes. `Client::builder(name, api_id, api_hash)` is unchanged, and `.bot_api(token)` is the new way to switch that client to the HTTP Bot API. ## Client lifecycle `close().await` is new: it stops the client and waits for the final save without blocking a runtime thread, once `run` has returned (called during `run`, it leaves the save and close to `run` as it returns). `disconnect()` still blocks the thread it runs on for up to 10 seconds. Dropping the last clone now saves in the background. ```text // 0.3.0, on a runtime thread: disconnect() blocked that thread for the final save client.disconnect(); ``` ```rust # async fn f(client: vaegram::Client) -> vaegram::Result<()> { client.run_until_signal().await?; // stop on Ctrl-C or SIGTERM client.close().await; // wait for the final save # Ok(()) } ``` Returning from `main` waits for a save a drop started; `std::process::exit` and `Runtime::shutdown_background` do not, so await `close` before either. ## User accounts are rate-limited by default A 0.3.0 user account had no client-side limits. 0.4.0 has no unlimited preset. A bot that leaves `rate_limits` unset gets no limiter; an account that is not a bot gets `RateLimits::user_account()`, about a person's pace, a message a second per chat and 20 a minute in a group, and nothing switches that off. `RateLimits::default()` is no way back either: it is the bots' pace, 20 messages a second. The closest to 0.3.0 is a high finite rate in the categories you care about, since `limit` refuses a rate that is not finite and above 0, with the per-chat limits off: ```rust use vaegram::prelude::*; use vaegram::session::{RateCategory, RateLimits}; let _app = Client::builder("me", 12345, "0123456789abcdef0123456789abcdef") .rate_limits( RateLimits::user_account() .no_per_chat() .limit(RateCategory::Message, 1000.0, 1000.0), ); ``` That pace from a person risks a ban. Prefer `RateLimits::user_account()` with the few categories you need loosened; see [Flood limits](/docs/flood-limits.md). ## Behaviour that changed without breaking the build - **A command name is 1 to 32 letters, digits or underscores.** `/usr/bin/python3:` or `/start:` no longer counts as a command. - **`send_reaction` adds the reaction to recent by default.** `.add_to_recent(false)` restores the 0.3.0 behaviour. - **The update state is saved within about 15 seconds of moving** (10 seconds, then the storage's flush within 5), so a hard kill replays about the last 15 seconds of updates on the next `run`. A handler that must not act twice should check. ## Changed signatures `delete_messages` is a request builder, and `revoke(false)` is new: ```rust # async fn f(client: &vaegram::Client, chat: i64) -> vaegram::Result<()> { client.delete_messages(chat, &[10, 11]).await?; // for everyone, as before client.delete_messages(chat, &[10, 11]).revoke(false).await?; // only for this account # Ok(()) } ``` `CallbackQuery::answer_ephemeral` returns the builder, not `Result`: drop the `?`. ```text // 0.3.0 query.answer_ephemeral("Only you see this")?.await?; ``` ```rust # async fn f(query: &vaegram::types::CallbackQuery) -> vaegram::Result<()> { query.answer_ephemeral("Only you see this").await?; # Ok(()) } ``` `get_app_config` returns `AppConfig` instead of raw `Json`; `get(key)` and `json()` read it, and `get_config` is new and typed. ```rust # async fn f(client: &vaegram::Client) -> vaegram::Result<()> { let config = client.get_app_config().await?; let _limit = config.get("reactions_user_max"); # Ok(()) } ``` `transcribe_audio` returns `Transcription`: it derefs to the old `TranscribedAudio`, and `wait(timeout)` gets the final text. ```rust use std::time::Duration; # async fn f(client: &vaegram::Client, chat: i64) -> vaegram::Result<()> { let mut transcription = client.transcribe_audio(chat, 9).await?; let text = transcription.wait(Duration::from_secs(30)).await?; # println!("{text}"); Ok(()) } ``` `get_sticker_set`, `reply_sticker` and `answer_sticker` take a reference, not only a short name; a `&str` still works. ```rust # async fn f(client: &vaegram::Client) -> vaegram::Result<()> { let set = client.get_sticker_set("cats_by_bot").await?; let again = client.get_sticker_set(set.set_ref()).await?; # let _ = again; Ok(()) } ``` `RichBlock::expandable_blockquote` takes the blocks the quote contains, not one `RichText`, and the `RichBlockKind::ExpandableBlockQuote` variant it reads back now carries `blocks` where it carried `text`. ```text // 0.3.0 RichBlock::expandable_blockquote("one line") // 0.4.0 RichBlock::expandable_blockquote([RichBlock::paragraph("one line")]) ``` ## Types that changed traits - **`ChatAction` is no longer `Copy`**: its emoji-interaction variants carry text. Clone it when it is used twice: `client.send_chat_action(chat, action.clone()).await?;` - **`Sticker` is `#[non_exhaustive]`**: a struct literal or an exhaustive match no longer compiles; read its fields. ## Renamed and retyped fields Two `User` fields take their Bot API names: `has_topics_sidebar` is now `has_topic_sidebar`, and `inline_needs_location` is now `needs_inline_query_location`. The values are unchanged, as are the Bot API fields they mirror. ```text // 0.3.0 let sidebar = user.has_topics_sidebar; let location = user.inline_needs_location; // 0.4.0 let sidebar = user.has_topic_sidebar; let location = user.needs_inline_query_location; ``` `TransactionPartner::AffiliateProgram`'s `sponsor_user` is `Option`, not `User`: an affiliate commission can arrive with no sponsoring bot named, and 0.3.0 had no way to say so. Match or `unwrap` it like any other optional field. ## Sessions and storage need no action The `.session` file format and the `VAE_` session-string format are unchanged from 0.3.0, so both load as they are. Two operational differences: - `PostgresStorage` now holds a lock on its schema: a second client on the same schema gets `ResourceBusy` until the first closes. - In Bot API mode (`bot_api`) nothing is stored: peers stay in memory, and `api_id` and `api_hash` are unused. ## New Cargo features, all off by default ```toml vaegram = { git = "https://github.com/rjriajul/vaegram", branch = "nightly", features = [ "bot-api", # talk to the HTTP Bot API through the same client "webhook-server", # the built-in webhook receiver "macros", # #[derive(BotCommands)] "dialogue-json", # dialogue states in a JSON file "serde", # Serialize on received types ] } ``` None changes code that does not use it; `macros` pulls in the new `vaegram-macros` crate. ## Additions that need no change `Router`, middleware and `Dep`; `DialogueRouter`; `Conversation`; `#[derive(BotCommands)]`; the test kit (`Client::offline`, `recording`, `scripted`); `Client::webhook` with `set_webhook`, `delete_webhook` and `get_webhook_info`; seven new `Error::is_*` helpers and `From for Error`. `Error` and `ClientEvent` were already `#[non_exhaustive]`, so new variants break no match. ## Common mistakes - Copying a nightly.1 handler signature (`|client, msg|`) into nightly.2, where it takes `|msg|`. - Leaving the `?` on `answer_ephemeral`, which now returns a builder. - Calling `disconnect()` and exiting at once, then losing the final save; await `close()` instead. - Upgrading a user account and finding sends suddenly paced. That is the new default. - Running an MTProto bot that ran on the cloud Bot API before. Call `logOut` there once; until then Telegram keeps its updates on the Bot API server and the MTProto login receives none. ## See also - [Deployment](/docs/deployment.md) for the shutdown sequence in full. - [Flood limits](/docs/flood-limits.md) for the new default limits. - [Sessions and storage](/docs/sessions-and-storage.md) for the file and string formats.