Receiving updates
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
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
app.on_message(filters::all(), |msg: Message| async move {
if msg.text().is_empty() {
return Ok(());
}
msg.answer("seen").await?;
Ok(())
});
A handler is a closure Fn(update) -> Future<Output = Result<T>>; 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().
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);
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:
use std::time::Duration;
let next = message.client().wait_for_message(message.chat.id).timeout(Duration::from_secs(60)).await?;
next.answer("thanks").await?;
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::<Message>() 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
Errfrom a handler skips the later groups and needson_errorto be seen. - Expecting
on_messageto see the bot’s own messages: they never arrive. - Waiting with
listenand then also expecting handlers for that reply: a listener’s update skips all groups.
See also
- API docs for
HandlerRef,HandlerInfoandHandlerError. - API docs for
run,stopandlisten. - Filters, Routers, Deployment.