Refactor the composite state example a bit

This commit is contained in:
Hirrolot 2024-09-23 01:58:49 -04:00
parent de34970e70
commit 782ec00f32
No known key found for this signature in database
GPG key ID: F0C33B48BD883C81

View file

@ -96,26 +96,20 @@ fn schema() -> UpdateHandler {
teloxide::filter_command::<Command, _>() teloxide::filter_command::<Command, _>()
.branch(dptree::case![Command::Start].endpoint(ask_full_name)), .branch(dptree::case![Command::Start].endpoint(ask_full_name)),
) )
.branch(dptree::case![GlobalState::Idle].endpoint(handle_configured_user_message)) .branch(dptree::case![GlobalState::Idle].endpoint(on_idle))
.branch( .branch(
// Its essential not to use // This macro passes the `state` variable further. In order to pattern-match on it,
// `dptree::case![GlobalState::UserSetup(UserSetup::ReceiveFullName)]` directly, // we need to use `dptree::case!` two times again.
// this won't work. Each nested enum requires it's own `branch` dptree::case![GlobalState::UserSetup(state)]
// scope. Actually, each `dptree::case![..]` introduces the inner
// enum value to the `DependencyMap`, so there is an option
// to branch on the inner values freely.
dptree::case![GlobalState::UserSetup(_state)]
.branch( .branch(
dptree::case![UserSetup::ReceiveFullName] dptree::case![UserSetup::ReceiveFullName].map(FullName).endpoint(ask_age),
.map(|text: String| FullName(text))
.endpoint(ask_age),
) )
.branch( .branch(
dptree::case![UserSetup::ReceiveAge { full_name }] dptree::case![UserSetup::ReceiveAge { full_name }]
.endpoint(finish_user_setup), .endpoint(finish_user_setup),
), ),
) )
.branch(dptree::endpoint(handle_unconfigured_user_message)), .branch(dptree::endpoint(fallback)),
) )
} }
@ -145,22 +139,22 @@ async fn finish_user_setup(
let _age = match age.parse::<u8>() { let _age = match age.parse::<u8>() {
Ok(age) => age, Ok(age) => age,
Err(_err) => { Err(_err) => {
bot.send_message(message.chat.id, "Please, enter your age").await?; bot.send_message(message.chat.id, "Please, enter your real age.").await?;
return Ok(()); return Ok(());
} }
}; };
bot.send_message(message.chat.id, "You've successfully passed setup").await?; bot.send_message(message.chat.id, "Your accout is set up!").await?;
dialogue.update(GlobalState::Idle).await?; dialogue.update(GlobalState::Idle).await?;
Ok(()) Ok(())
} }
async fn handle_configured_user_message(bot: Bot, message: Message) -> HandlerResult { async fn on_idle(bot: Bot, message: Message) -> HandlerResult {
bot.send_message(message.chat.id, "Hi, configured user!").await?; bot.send_message(message.chat.id, "You are all set.").await?;
Ok(()) Ok(())
} }
async fn handle_unconfigured_user_message(bot: Bot, message: Message) -> HandlerResult { async fn fallback(bot: Bot, message: Message) -> HandlerResult {
bot.send_message(message.chat.id, "Use /start to setup your account").await?; bot.send_message(message.chat.id, "Use /start to setup your account.").await?;
Ok(()) Ok(())
} }