Conversations
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
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(())
}
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
});- /start
- Ada/startWhat's your name?
- Ada
- Ada/startHow old are you?
- 300
- 36
- Ada/startWelcome, Ada (36)!
What ran
enter_conversation("signup", msg.clone())The /start handler starts it and returns.conv.wait_for(filters::text())Waits for the next text.name = "Ada"conv.form().number()Waits for au8."300" is no u8The field drops it and waits on.age = 36Ok(())signup returns: the conversation ends.
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):
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?;
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:
/cancelis text like any other; callignore_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). otherwiseon a parallel conversation fails withOtherwiseInParallel(src/conversation/handle.rs:157); let the other conversation take the update instead.- Starting a listener inside a conversation: an
askorlistenstarted 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 for
Conversation,WaitandForm. - Dialogues for a flow that survives a restart.
- Testing for driving a conversation with the test kit.
- Receiving updates for handlers and
run.