From c017e59eb33655fedee97eb2ec5c4cc96d9e4f8b Mon Sep 17 00:00:00 2001 From: Hirrolot Date: Wed, 26 Jan 2022 15:51:51 +0600 Subject: [PATCH] Update the examples --- examples/buttons/src/main.rs | 12 +- examples/dialogue_bot/src/main.rs | 12 +- examples/dispatching2_features/src/main.rs | 144 +++++++++++---------- examples/inline_bot/src/main.rs | 93 +++++++------ examples/redis_remember_bot/src/main.rs | 12 +- examples/shared_state_bot/src/main.rs | 22 ++-- examples/sqlite_remember_bot/src/main.rs | 13 +- 7 files changed, 151 insertions(+), 157 deletions(-) diff --git a/examples/buttons/src/main.rs b/examples/buttons/src/main.rs index bcb5a1a2..9429ea63 100644 --- a/examples/buttons/src/main.rs +++ b/examples/buttons/src/main.rs @@ -122,12 +122,12 @@ async fn main() -> Result<(), Box> { let bot = Bot::from_env().auto_send(); - Dispatcher::new(bot) - .messages_handler(|h| h.branch(dptree::endpoint(message_handler))) - .callback_queries_handler(|h| h.branch(dptree::endpoint(callback_handler))) - .inline_queries_handler(|h| h.branch(dptree::endpoint(inline_query_handler))) - .dispatch() - .await; + let handler = dptree::entry() + .branch(Update::filter_message().endpoint(message_handler)) + .branch(Update::filter_callback_query().endpoint(callback_handler)) + .branch(Update::filter_inline_query().endpoint(inline_query_handler)); + + Dispatcher::new(bot, handler).dispatch().await; log::info!("Closing bot... Goodbye!"); diff --git a/examples/dialogue_bot/src/main.rs b/examples/dialogue_bot/src/main.rs index 8f211cbe..7f712fac 100644 --- a/examples/dialogue_bot/src/main.rs +++ b/examples/dialogue_bot/src/main.rs @@ -60,11 +60,13 @@ async fn main() { let bot = Bot::from_env().auto_send(); let storage = SqliteStorage::open("db.sqlite", Json).await.unwrap(); - Dispatcher::new(bot) - .dependencies(dptree::deps![storage]) - .messages_handler(|h| h.add_dialogue::().dispatch_by::()) - .dispatch() - .await; + Dispatcher::new( + bot, + dptree::entry().add_dialogue::().dispatch_by::(), + ) + .dependencies(dptree::deps![storage]) + .dispatch() + .await; } async fn handle_start(bot: MyBot, mes: Message, dialogue: BotDialogue) -> anyhow::Result<()> { diff --git a/examples/dispatching2_features/src/main.rs b/examples/dispatching2_features/src/main.rs index e38a2255..fc13535f 100644 --- a/examples/dispatching2_features/src/main.rs +++ b/examples/dispatching2_features/src/main.rs @@ -24,84 +24,86 @@ async fn main() { maintainer_username: None, }; - // Start create dispatcher. - Dispatcher::new(bot) - // You can specify dependencies to that you have access inside of handlers. It may be - // configs, connection to Database, or dialogue storage (see more in the dialogue_bot example). - // It is similar to the `actix_web::Extensions`. - .dependencies(dptree::deps![parameters]) - // Now handlers don't use streams. Instead handler is special constructs from `dptree` library. - // Any `*_handler` accepts function `Fn(UpdateHandler) -> UpdateHandler` which is builder - // for the handlers. Note that you _must_ use it instead of using `dptree` methods forward. - .messages_handler(|handler| { - // Branch is a special method that allow you to handle update several ways. - handler - .branch( - // Filter allow you to filter updates by some condition. - dptree::filter( - // Note that `async move` is obligatory. - |mes: Message| async move { mes.chat.is_group() || mes.chat.is_supergroup() } - ) - // Endpoint is a last message handler. - .endpoint(|mes: Message, bot: AutoSend| async move { - log::info!("Received message from the group chat."); - bot.send_message(mes.chat.id, "This is a group chat.").await?; - respond(()) - }) - ) - // Note that we cannot filter messages from public chats in the next branch, - // because they all is handled by previous branch. - .branch( - // There are some `filter` functions on message, that filters events. This - // filter will filter only messages with dices. - Message::filter_dice(|_dice| async { true }) - .endpoint(|mes: Message, bot: AutoSend| async move { - bot.send_message(mes.chat.id, "This is a dice!") - .reply_to_message_id(mes.id) - .await?; + let handler = Update::filter_message() + // Branch is a special method that allow you to handle update several ways. + .branch( + // Filter allow you to filter updates by some condition. + dptree::filter( + // Note that `async move` is obligatory. + |mes: Message| async move { mes.chat.is_group() || mes.chat.is_supergroup() }, + ) + // Endpoint is a last message handler. + .endpoint(|mes: Message, bot: AutoSend| async move { + log::info!("Received message from the group chat."); + bot.send_message(mes.chat.id, "This is a group chat.").await?; + respond(()) + }), + ) + // Note that we cannot filter messages from public chats in the next branch, + // because they all is handled by previous branch. + .branch( + // There are some `filter` functions on message, that filters events. This + // filter will filter only messages with dices. + Message::filter_dice().endpoint(|mes: Message, bot: AutoSend| async move { + bot.send_message(mes.chat.id, "This is a dice!") + .reply_to_message_id(mes.id) + .await?; + Ok(()) + }), + ) + .branch( + // If you do not like photos, you can break their handling like that. + Message::filter_photo().endpoint(|| async move { Ok(()) }), + ) + .branch( + dptree::entry() + // This method allows to parse text messages commands. + .add_command::(bot_username.clone()) + // Next we can add `SimpleCommand` in the argument of endpoint. If + // command parsing fails, this endpoint will not be called. + .endpoint(simple_commands_handler), + ) + .branch( + // Filter maintainer by used ID. + dptree::filter(|mes: Message, cfg: ConfigParameters| async move { + mes.from().map(|user| user.id == cfg.bot_maintainer).unwrap_or_default() + }) + .add_command::(bot_username.clone()) + .endpoint( + |mes: Message, bot: AutoSend, cmd: MaintainerCommands| async move { + match cmd { + MaintainerCommands::Rand { from, to } => { + let mut rng = rand::rngs::OsRng::default(); + let value: u64 = rng.gen_range(from..=to); + std::mem::drop(rng); + + bot.send_message(mes.chat.id, value.to_string()).await?; + Ok(()) - }) - ) - .branch( - // If you do not like photos, you can break their handling like that. - Message::filter_photo(|_photo| async { true }) - .endpoint(|| async move { Ok(()) }) - ) - .branch( - dptree::entry() - // This method allows to parse text messages commands. - .add_command::(bot_username.clone()) - // Next we can add `SimpleCommand` in the argument of endpoint. If - // command parsing fails, this endpoint will not be called. - .endpoint(simple_commands_handler) - ) - .branch( - // Filter maintainer by used ID. - dptree::filter(|mes: Message, cfg: ConfigParameters| async move { - mes.from().map(|user| user.id == cfg.bot_maintainer).unwrap_or_default() - }) - .add_command::(bot_username.clone()) - .endpoint(|mes: Message, bot: AutoSend, cmd: MaintainerCommands| async move { - match cmd { - MaintainerCommands::Rand { from, to } => { - let mut rng = rand::rngs::OsRng::default(); - let value: u64 = rng.gen_range(from..=to); - std::mem::drop(rng); + } + } + }, + ), + ); - bot.send_message(mes.chat.id, value.to_string()).await?; - - Ok(()) - } - } - }) - ) - }) + // Start create dispatcher. + Dispatcher::new(bot, handler) + // You can specify dependencies to that you have access inside of handlers. It may be + // configs, connection to Database, or dialogue storage (see more in the dialogue_bot + // example). It is similar to the `actix_web::Extensions`. + .dependencies(dptree::deps![parameters]) + // Now handlers don't use streams. Instead handler is special constructs from `dptree` + // library. Any `*_handler` accepts function `Fn(UpdateHandler) -> UpdateHandler` + // which is builder for the handlers. Note that you _must_ use it instead of using + // `dptree` methods forward. .default_handler(dptree::endpoint(|upd: Update| async move { // This handler handles updates that do not handled by other handlers. log::warn!("Unhandled update: {:?}", upd); })) // If `Result::Err` returns from the dispatcher, it goes here. - .error_handler(LoggingErrorHandler::with_custom_text("Error has occurred in the dispatcher")) + .error_handler(LoggingErrorHandler::with_custom_text( + "Error has occurred in the dispatcher", + )) .dispatch() .await; } diff --git a/examples/inline_bot/src/main.rs b/examples/inline_bot/src/main.rs index bae454b6..db8d6457 100644 --- a/examples/inline_bot/src/main.rs +++ b/examples/inline_bot/src/main.rs @@ -13,53 +13,52 @@ async fn main() { let bot = Bot::from_env().auto_send(); - Dispatcher::new(bot) - .inline_queries_handler(|b| { - b.branch(dptree::endpoint(|query: InlineQuery, bot: AutoSend| async move { - // First, create your actual response - let google_search = InlineQueryResultArticle::new( - // Each item needs a unique ID, as well as the response container for the - // items. These can be whatever, as long as they don't - // conflict. - "01".to_string(), - // What the user will actually see - "Google Search", - // What message will be sent when clicked/tapped - InputMessageContent::Text(InputMessageContentText::new(format!( - "https://www.google.com/search?q={}", - query.query, - ))), - ); - // While constructing them from the struct itself is possible, it is preferred - // to use the builder pattern if you wish to add more - // information to your result. Please refer to the documentation - // for more detailed information about each field. https://docs.rs/teloxide/latest/teloxide/types/struct.InlineQueryResultArticle.html - let ddg_search = InlineQueryResultArticle::new( - "02".to_string(), - "DuckDuckGo Search".to_string(), - InputMessageContent::Text(InputMessageContentText::new(format!( - "https://duckduckgo.com/?q={}", - query.query.to_string() - ))), - ) - .description("DuckDuckGo Search") - .thumb_url("https://duckduckgo.com/assets/logo_header.v108.png") - .url("https://duckduckgo.com/about"); // Note: This is the url that will open if they click the thumbnail + let handler = Update::filter_inline_query().branch(dptree::endpoint( + |query: InlineQuery, bot: AutoSend| async move { + // First, create your actual response + let google_search = InlineQueryResultArticle::new( + // Each item needs a unique ID, as well as the response container for the + // items. These can be whatever, as long as they don't + // conflict. + "01".to_string(), + // What the user will actually see + "Google Search", + // What message will be sent when clicked/tapped + InputMessageContent::Text(InputMessageContentText::new(format!( + "https://www.google.com/search?q={}", + query.query, + ))), + ); + // While constructing them from the struct itself is possible, it is preferred + // to use the builder pattern if you wish to add more + // information to your result. Please refer to the documentation + // for more detailed information about each field. https://docs.rs/teloxide/latest/teloxide/types/struct.InlineQueryResultArticle.html + let ddg_search = InlineQueryResultArticle::new( + "02".to_string(), + "DuckDuckGo Search".to_string(), + InputMessageContent::Text(InputMessageContentText::new(format!( + "https://duckduckgo.com/?q={}", + query.query.to_string() + ))), + ) + .description("DuckDuckGo Search") + .thumb_url("https://duckduckgo.com/assets/logo_header.v108.png") + .url("https://duckduckgo.com/about"); // Note: This is the url that will open if they click the thumbnail - let results = vec![ - InlineQueryResult::Article(google_search), - InlineQueryResult::Article(ddg_search), - ]; + let results = vec![ + InlineQueryResult::Article(google_search), + InlineQueryResult::Article(ddg_search), + ]; - // Send it off! One thing to note -- the ID we use here must be of the query - // we're responding to. - let response = bot.answer_inline_query(&query.id, results).send().await; - if let Err(err) = response { - log::error!("Error in handler: {:?}", err); - } - respond(()) - })) - }) - .dispatch() - .await; + // Send it off! One thing to note -- the ID we use here must be of the query + // we're responding to. + let response = bot.answer_inline_query(&query.id, results).send().await; + if let Err(err) = response { + log::error!("Error in handler: {:?}", err); + } + respond(()) + }, + )); + + Dispatcher::new(bot, handler).dispatch().await; } diff --git a/examples/redis_remember_bot/src/main.rs b/examples/redis_remember_bot/src/main.rs index 36629c46..fa67a71e 100644 --- a/examples/redis_remember_bot/src/main.rs +++ b/examples/redis_remember_bot/src/main.rs @@ -80,11 +80,9 @@ async fn main() { // or "serializer-bincode" let storage = RedisStorage::open("redis://127.0.0.1:6379", Bincode).await.unwrap(); - Dispatcher::new(bot) - .dependencies(dptree::deps![storage]) - .messages_handler(|h| { - h.add_dialogue::().branch(dptree::endpoint(handle_message)) - }) - .dispatch() - .await; + let handler = dptree::entry() + .add_dialogue::() + .branch(dptree::endpoint(handle_message)); + + Dispatcher::new(bot, handler).dependencies(dptree::deps![storage]).dispatch().await; } diff --git a/examples/shared_state_bot/src/main.rs b/examples/shared_state_bot/src/main.rs index b598b5a6..452b00d2 100644 --- a/examples/shared_state_bot/src/main.rs +++ b/examples/shared_state_bot/src/main.rs @@ -16,18 +16,14 @@ async fn main() { let bot = Bot::from_env().auto_send(); - Dispatcher::new(bot) - .messages_handler(|h| { - h.branch(dptree::endpoint(|mes: Message, bot: AutoSend| async move { - let previous = MESSAGES_TOTAL.fetch_add(1, Ordering::Relaxed); - bot.send_message( - mes.chat.id, - format!("I received {} messages in total.", previous), - ) + let handler = Update::filter_message().branch(dptree::endpoint( + |mes: Message, bot: AutoSend| async move { + let previous = MESSAGES_TOTAL.fetch_add(1, Ordering::Relaxed); + bot.send_message(mes.chat.id, format!("I received {} messages in total.", previous)) .await?; - respond(()) - })) - }) - .dispatch() - .await; + respond(()) + }, + )); + + Dispatcher::new(bot, handler).dispatch().await; } diff --git a/examples/sqlite_remember_bot/src/main.rs b/examples/sqlite_remember_bot/src/main.rs index 755ed828..f2a44c08 100644 --- a/examples/sqlite_remember_bot/src/main.rs +++ b/examples/sqlite_remember_bot/src/main.rs @@ -1,4 +1,3 @@ -use std::sync::Arc; use teloxide::{ dispatching2::dialogue::{serializer::Json, SqliteStorage, Storage}, prelude2::*, @@ -77,11 +76,9 @@ async fn main() { let bot = Bot::from_env().auto_send(); let storage = SqliteStorage::open("db.sqlite", Json).await.unwrap(); - Dispatcher::new(bot) - .dependencies(dptree::deps![storage]) - .messages_handler(|h| { - h.add_dialogue::().branch(dptree::endpoint(handle_message)) - }) - .dispatch() - .await; + let handler = dptree::entry() + .add_dialogue::() + .branch(dptree::endpoint(handle_message)); + + Dispatcher::new(bot, handler).dependencies(dptree::deps![storage]).dispatch().await; }