How can I use a dptree on a CallbackQuery handler? #964
-
I started writing a handler for CallbackQuery, and it has become a complicated mess of match cases. I thought to reuse the BotCommands enum and filter_command, is it a thing? How can I implement it? This would allow to set the CallbackQuery data to a command-like message, e.g. /delete 1, and use the filters to neatly match the right command parser, and get the arguments. Minimal example: #[derive(BotCommands, Clone)]
#[command(
rename_rule = "lowercase",
description = "commands from the feed CRUD callback query interface"
)]
enum FeedCommand {
#[command(description = "delete this feed")]
Delete { feed_id: i64 },
#[command(description = "Exit from the keyboard")]
Exit,
}
async fn handle_callback(
bot: Bot,
q: CallbackQuery,
db: &DatabaseConnection,
) -> Result<(), Box<dyn Error + Send + Sync>> {
match q.data {
Some(data) => {
if let Some(command) = FeedCommand::parse(data) {
match command {
FeedCommand::Delete(feed_id) => {
bot.send_message(q.chat_id(), format!("Deleted {feed_id}.")).await?;
}
FeedCommand::Exit => {
bot.send_message(q.chat_id(), format!("All done thanks.")).await?;
}
}
}
else {
}
}
Err(err) => {
bot.send_message(q.chat_id(), format!("Error {}", err)).await?;
}
}
Ok(())
} |
Beta Was this translation helpful? Give feedback.
Answered by
WaffleLapkin
Nov 7, 2023
Replies: 1 comment
-
You can use Update::filter_callback_query()
.filter_map(|q: CallbackQuery| q.data.and_then(FeedCommand::parse))
.branch(case![FeedCommand::Delete { feed_id }].endpoint(delete))
.branch(case![FeedCommand::Exit].endpoint(delete)) |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
Enucatl
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You can use
filter_map
withFeedCommand::parse
the same way you dofilter_command
. So something like