Update the examples

This commit is contained in:
Hirrolot 2022-01-26 15:51:51 +06:00
parent 58311ef608
commit c017e59eb3
7 changed files with 151 additions and 157 deletions

View file

@ -122,12 +122,12 @@ async fn main() -> Result<(), Box<dyn Error>> {
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!");

View file

@ -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::<Message, Store, State>().dispatch_by::<State>())
.dispatch()
.await;
Dispatcher::new(
bot,
dptree::entry().add_dialogue::<Message, Store, State>().dispatch_by::<State>(),
)
.dependencies(dptree::deps![storage])
.dispatch()
.await;
}
async fn handle_start(bot: MyBot, mes: Message, dialogue: BotDialogue) -> anyhow::Result<()> {

View file

@ -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<Bot>| 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<Bot>| 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<Bot>| 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<Bot>| 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::<SimpleCommand>(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::<MaintainerCommands>(bot_username.clone())
.endpoint(
|mes: Message, bot: AutoSend<Bot>, 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::<SimpleCommand>(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::<MaintainerCommands>(bot_username.clone())
.endpoint(|mes: Message, bot: AutoSend<Bot>, 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;
}

View file

@ -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<Bot>| 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<Bot>| 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;
}

View file

@ -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::<Message, Store, BotDialogue>().branch(dptree::endpoint(handle_message))
})
.dispatch()
.await;
let handler = dptree::entry()
.add_dialogue::<Message, Store, BotDialogue>()
.branch(dptree::endpoint(handle_message));
Dispatcher::new(bot, handler).dependencies(dptree::deps![storage]).dispatch().await;
}

View file

@ -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<Bot>| 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<Bot>| 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;
}

View file

@ -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::<Message, Store, BotDialogue>().branch(dptree::endpoint(handle_message))
})
.dispatch()
.await;
let handler = dptree::entry()
.add_dialogue::<Message, Store, BotDialogue>()
.branch(dptree::endpoint(handle_message));
Dispatcher::new(bot, handler).dependencies(dptree::deps![storage]).dispatch().await;
}