Merge pull request #725 from teloxide/refactor-examples-style

Refactor examples style
This commit is contained in:
Hirrolot 2022-10-03 18:29:31 +06:00 committed by GitHub
commit a461061c26
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
16 changed files with 70 additions and 76 deletions

View file

@ -94,8 +94,8 @@ async fn main() {
let bot = Bot::from_env(); let bot = Bot::from_env();
teloxide::repl(bot, |message: Message, bot: Bot| async move { teloxide::repl(bot, |bot: Bot, msg: Message| async move {
bot.send_dice(message.chat.id).await?; bot.send_dice(msg.chat.id).await?;
Ok(()) Ok(())
}) })
.await; .await;
@ -143,20 +143,15 @@ enum Command {
UsernameAndAge { username: String, age: u8 }, UsernameAndAge { username: String, age: u8 },
} }
async fn answer(bot: Bot, message: Message, command: Command) -> ResponseResult<()> { async fn answer(bot: Bot, msg: Message, cmd: Command) -> ResponseResult<()> {
match command { match cmd {
Command::Help => { Command::Help => bot.send_message(msg.chat.id, Command::descriptions().to_string()).await?,
bot.send_message(message.chat.id, Command::descriptions().to_string()).await?
}
Command::Username(username) => { Command::Username(username) => {
bot.send_message(message.chat.id, format!("Your username is @{username}.")).await? bot.send_message(msg.chat.id, format!("Your username is @{username}.")).await?
} }
Command::UsernameAndAge { username, age } => { Command::UsernameAndAge { username, age } => {
bot.send_message( bot.send_message(msg.chat.id, format!("Your username is @{username} and age is {age}."))
message.chat.id, .await?
format!("Your username is @{username} and age is {age}."),
)
.await?
} }
}; };
@ -223,13 +218,13 @@ async fn main() {
.await; .await;
} }
async fn start(bot: Bot, msg: Message, dialogue: MyDialogue) -> HandlerResult { async fn start(bot: Bot, dialogue: MyDialogue, msg: Message) -> HandlerResult {
bot.send_message(msg.chat.id, "Let's start! What's your full name?").await?; bot.send_message(msg.chat.id, "Let's start! What's your full name?").await?;
dialogue.update(State::ReceiveFullName).await?; dialogue.update(State::ReceiveFullName).await?;
Ok(()) Ok(())
} }
async fn receive_full_name(bot: Bot, msg: Message, dialogue: MyDialogue) -> HandlerResult { async fn receive_full_name(bot: Bot, dialogue: MyDialogue, msg: Message) -> HandlerResult {
match msg.text() { match msg.text() {
Some(text) => { Some(text) => {
bot.send_message(msg.chat.id, "How old are you?").await?; bot.send_message(msg.chat.id, "How old are you?").await?;
@ -245,9 +240,9 @@ async fn receive_full_name(bot: Bot, msg: Message, dialogue: MyDialogue) -> Hand
async fn receive_age( async fn receive_age(
bot: Bot, bot: Bot,
msg: Message,
dialogue: MyDialogue, dialogue: MyDialogue,
full_name: String, // Available from `State::ReceiveAge`. full_name: String, // Available from `State::ReceiveAge`.
msg: Message,
) -> HandlerResult { ) -> HandlerResult {
match msg.text().map(|text| text.parse::<u8>()) { match msg.text().map(|text| text.parse::<u8>()) {
Some(Ok(age)) => { Some(Ok(age)) => {
@ -264,14 +259,14 @@ async fn receive_age(
async fn receive_location( async fn receive_location(
bot: Bot, bot: Bot,
msg: Message,
dialogue: MyDialogue, dialogue: MyDialogue,
(full_name, age): (String, u8), // Available from `State::ReceiveLocation`. (full_name, age): (String, u8), // Available from `State::ReceiveLocation`.
msg: Message,
) -> HandlerResult { ) -> HandlerResult {
match msg.text() { match msg.text() {
Some(location) => { Some(location) => {
let message = format!("Full name: {full_name}\nAge: {age}\nLocation: {location}"); let report = format!("Full name: {full_name}\nAge: {age}\nLocation: {location}");
bot.send_message(msg.chat.id, message).await?; bot.send_message(msg.chat.id, report).await?;
dialogue.exit().await?; dialogue.exit().await?;
} }
None => { None => {

View file

@ -63,8 +63,8 @@ async fn main() {
teloxide::commands_repl(bot, action, Command::ty()).await; teloxide::commands_repl(bot, action, Command::ty()).await;
} }
async fn action(bot: Bot, msg: Message, command: Command) -> ResponseResult<()> { async fn action(bot: Bot, msg: Message, cmd: Command) -> ResponseResult<()> {
match command { match cmd {
Command::Help => { Command::Help => {
bot.send_message(msg.chat.id, Command::descriptions().to_string()).await?; bot.send_message(msg.chat.id, Command::descriptions().to_string()).await?;
} }

View file

@ -58,21 +58,25 @@ fn make_keyboard() -> InlineKeyboardMarkup {
/// Parse the text wrote on Telegram and check if that text is a valid command /// Parse the text wrote on Telegram and check if that text is a valid command
/// or not, then match the command. If the command is `/start` it writes a /// or not, then match the command. If the command is `/start` it writes a
/// markup with the `InlineKeyboardMarkup`. /// markup with the `InlineKeyboardMarkup`.
async fn message_handler(m: Message, bot: Bot, me: Me) -> Result<(), Box<dyn Error + Send + Sync>> { async fn message_handler(
if let Some(text) = m.text() { bot: Bot,
msg: Message,
me: Me,
) -> Result<(), Box<dyn Error + Send + Sync>> {
if let Some(text) = msg.text() {
match BotCommands::parse(text, me.username()) { match BotCommands::parse(text, me.username()) {
Ok(Command::Help) => { Ok(Command::Help) => {
// Just send the description of all commands. // Just send the description of all commands.
bot.send_message(m.chat.id, Command::descriptions().to_string()).await?; bot.send_message(msg.chat.id, Command::descriptions().to_string()).await?;
} }
Ok(Command::Start) => { Ok(Command::Start) => {
// Create a list of buttons and send them. // Create a list of buttons and send them.
let keyboard = make_keyboard(); let keyboard = make_keyboard();
bot.send_message(m.chat.id, "Debian versions:").reply_markup(keyboard).await?; bot.send_message(msg.chat.id, "Debian versions:").reply_markup(keyboard).await?;
} }
Err(_) => { Err(_) => {
bot.send_message(m.chat.id, "Command not found!").await?; bot.send_message(msg.chat.id, "Command not found!").await?;
} }
} }
} }
@ -81,8 +85,8 @@ async fn message_handler(m: Message, bot: Bot, me: Me) -> Result<(), Box<dyn Err
} }
async fn inline_query_handler( async fn inline_query_handler(
q: InlineQuery,
bot: Bot, bot: Bot,
q: InlineQuery,
) -> Result<(), Box<dyn Error + Send + Sync>> { ) -> Result<(), Box<dyn Error + Send + Sync>> {
let choose_debian_version = InlineQueryResultArticle::new( let choose_debian_version = InlineQueryResultArticle::new(
"0", "0",
@ -101,7 +105,7 @@ async fn inline_query_handler(
/// ///
/// **IMPORTANT**: do not send privacy-sensitive data this way!!! /// **IMPORTANT**: do not send privacy-sensitive data this way!!!
/// Anyone can read data stored in the callback button. /// Anyone can read data stored in the callback button.
async fn callback_handler(q: CallbackQuery, bot: Bot) -> Result<(), Box<dyn Error + Send + Sync>> { async fn callback_handler(bot: Bot, q: CallbackQuery) -> Result<(), Box<dyn Error + Send + Sync>> {
if let Some(version) = q.data { if let Some(version) = q.data {
let text = format!("You chose: {version}"); let text = format!("You chose: {version}");

View file

@ -21,20 +21,15 @@ enum Command {
UsernameAndAge { username: String, age: u8 }, UsernameAndAge { username: String, age: u8 },
} }
async fn answer(bot: Bot, message: Message, command: Command) -> ResponseResult<()> { async fn answer(bot: Bot, msg: Message, cmd: Command) -> ResponseResult<()> {
match command { match cmd {
Command::Help => { Command::Help => bot.send_message(msg.chat.id, Command::descriptions().to_string()).await?,
bot.send_message(message.chat.id, Command::descriptions().to_string()).await?
}
Command::Username(username) => { Command::Username(username) => {
bot.send_message(message.chat.id, format!("Your username is @{username}.")).await? bot.send_message(msg.chat.id, format!("Your username is @{username}.")).await?
} }
Command::UsernameAndAge { username, age } => { Command::UsernameAndAge { username, age } => {
bot.send_message( bot.send_message(msg.chat.id, format!("Your username is @{username} and age is {age}."))
message.chat.id, .await?
format!("Your username is @{username} and age is {age}."),
)
.await?
} }
}; };

View file

@ -60,7 +60,7 @@ async fn main() {
.await; .await;
} }
async fn start(bot: Bot, msg: Message, dialogue: MyDialogue) -> HandlerResult { async fn start(bot: Bot, dialogue: MyDialogue, msg: Message) -> HandlerResult {
match msg.text().map(|text| text.parse::<i32>()) { match msg.text().map(|text| text.parse::<i32>()) {
Some(Ok(n)) => { Some(Ok(n)) => {
dialogue.update(State::GotNumber(n)).await?; dialogue.update(State::GotNumber(n)).await?;
@ -80,9 +80,9 @@ async fn start(bot: Bot, msg: Message, dialogue: MyDialogue) -> HandlerResult {
async fn got_number( async fn got_number(
bot: Bot, bot: Bot,
msg: Message,
dialogue: MyDialogue, dialogue: MyDialogue,
num: i32, num: i32, // Available from `State::GotNumber`.
msg: Message,
cmd: Command, cmd: Command,
) -> HandlerResult { ) -> HandlerResult {
match cmd { match cmd {

View file

@ -57,13 +57,13 @@ async fn main() {
.await; .await;
} }
async fn start(bot: Bot, msg: Message, dialogue: MyDialogue) -> HandlerResult { async fn start(bot: Bot, dialogue: MyDialogue, msg: Message) -> HandlerResult {
bot.send_message(msg.chat.id, "Let's start! What's your full name?").await?; bot.send_message(msg.chat.id, "Let's start! What's your full name?").await?;
dialogue.update(State::ReceiveFullName).await?; dialogue.update(State::ReceiveFullName).await?;
Ok(()) Ok(())
} }
async fn receive_full_name(bot: Bot, msg: Message, dialogue: MyDialogue) -> HandlerResult { async fn receive_full_name(bot: Bot, dialogue: MyDialogue, msg: Message) -> HandlerResult {
match msg.text() { match msg.text() {
Some(text) => { Some(text) => {
bot.send_message(msg.chat.id, "How old are you?").await?; bot.send_message(msg.chat.id, "How old are you?").await?;
@ -79,9 +79,9 @@ async fn receive_full_name(bot: Bot, msg: Message, dialogue: MyDialogue) -> Hand
async fn receive_age( async fn receive_age(
bot: Bot, bot: Bot,
msg: Message,
dialogue: MyDialogue, dialogue: MyDialogue,
full_name: String, // Available from `State::ReceiveAge`. full_name: String, // Available from `State::ReceiveAge`.
msg: Message,
) -> HandlerResult { ) -> HandlerResult {
match msg.text().map(|text| text.parse::<u8>()) { match msg.text().map(|text| text.parse::<u8>()) {
Some(Ok(age)) => { Some(Ok(age)) => {
@ -98,14 +98,14 @@ async fn receive_age(
async fn receive_location( async fn receive_location(
bot: Bot, bot: Bot,
msg: Message,
dialogue: MyDialogue, dialogue: MyDialogue,
(full_name, age): (String, u8), // Available from `State::ReceiveLocation`. (full_name, age): (String, u8), // Available from `State::ReceiveLocation`.
msg: Message,
) -> HandlerResult { ) -> HandlerResult {
match msg.text() { match msg.text() {
Some(location) => { Some(location) => {
let message = format!("Full name: {full_name}\nAge: {age}\nLocation: {location}"); let report = format!("Full name: {full_name}\nAge: {age}\nLocation: {location}");
bot.send_message(msg.chat.id, message).await?; bot.send_message(msg.chat.id, report).await?;
dialogue.exit().await?; dialogue.exit().await?;
} }
None => { None => {

View file

@ -33,7 +33,7 @@ async fn main() {
) )
.branch( .branch(
// Filter a maintainer by a used ID. // Filter a maintainer by a used ID.
dptree::filter(|msg: Message, cfg: ConfigParameters| { dptree::filter(|cfg: ConfigParameters, msg: Message| {
msg.from().map(|user| user.id == cfg.bot_maintainer).unwrap_or_default() msg.from().map(|user| user.id == cfg.bot_maintainer).unwrap_or_default()
}) })
.filter_command::<MaintainerCommands>() .filter_command::<MaintainerCommands>()
@ -62,7 +62,7 @@ async fn main() {
.branch( .branch(
// There are some extension filtering functions on `Message`. The following filter will // There are some extension filtering functions on `Message`. The following filter will
// filter only messages with dices. // filter only messages with dices.
Message::filter_dice().endpoint(|msg: Message, dice: Dice, bot: Bot| async move { Message::filter_dice().endpoint(|bot: Bot, msg: Message, dice: Dice| async move {
bot.send_message(msg.chat.id, format!("Dice value: {}", dice.value)) bot.send_message(msg.chat.id, format!("Dice value: {}", dice.value))
.reply_to_message_id(msg.id) .reply_to_message_id(msg.id)
.await?; .await?;
@ -114,11 +114,11 @@ enum MaintainerCommands {
} }
async fn simple_commands_handler( async fn simple_commands_handler(
msg: Message,
bot: Bot,
cmd: SimpleCommand,
cfg: ConfigParameters, cfg: ConfigParameters,
bot: Bot,
me: teloxide::types::Me, me: teloxide::types::Me,
msg: Message,
cmd: SimpleCommand,
) -> Result<(), teloxide::RequestError> { ) -> Result<(), teloxide::RequestError> {
let text = match cmd { let text = match cmd {
SimpleCommand::Help => { SimpleCommand::Help => {

View file

@ -47,7 +47,7 @@ async fn main() {
teloxide::repl_with_listener( teloxide::repl_with_listener(
bot, bot,
|msg: Message, bot: Bot| async move { |bot: Bot, msg: Message| async move {
bot.send_message(msg.chat.id, "pong").await?; bot.send_message(msg.chat.id, "pong").await?;
Ok(()) Ok(())
}, },

View file

@ -14,7 +14,7 @@ async fn main() {
let bot = Bot::from_env(); let bot = Bot::from_env();
let handler = Update::filter_inline_query().branch(dptree::endpoint( let handler = Update::filter_inline_query().branch(dptree::endpoint(
|query: InlineQuery, bot: Bot| async move { |bot: Bot, q: InlineQuery| async move {
// First, create your actual response // First, create your actual response
let google_search = InlineQueryResultArticle::new( let google_search = InlineQueryResultArticle::new(
// Each item needs a unique ID, as well as the response container for the // Each item needs a unique ID, as well as the response container for the
@ -26,7 +26,7 @@ async fn main() {
// What message will be sent when clicked/tapped // What message will be sent when clicked/tapped
InputMessageContent::Text(InputMessageContentText::new(format!( InputMessageContent::Text(InputMessageContentText::new(format!(
"https://www.google.com/search?q={}", "https://www.google.com/search?q={}",
query.query, q.query,
))), ))),
); );
// While constructing them from the struct itself is possible, it is preferred // While constructing them from the struct itself is possible, it is preferred
@ -38,7 +38,7 @@ async fn main() {
"DuckDuckGo Search".to_string(), "DuckDuckGo Search".to_string(),
InputMessageContent::Text(InputMessageContentText::new(format!( InputMessageContent::Text(InputMessageContentText::new(format!(
"https://duckduckgo.com/?q={}", "https://duckduckgo.com/?q={}",
query.query q.query
))), ))),
) )
.description("DuckDuckGo Search") .description("DuckDuckGo Search")
@ -52,7 +52,7 @@ async fn main() {
// Send it off! One thing to note -- the ID we use here must be of the query // Send it off! One thing to note -- the ID we use here must be of the query
// we're responding to. // we're responding to.
let response = bot.answer_inline_query(&query.id, results).send().await; let response = bot.answer_inline_query(&q.id, results).send().await;
if let Err(err) = response { if let Err(err) = response {
log::error!("Error in handler: {:?}", err); log::error!("Error in handler: {:?}", err);
} }

View file

@ -18,7 +18,7 @@ async fn main() {
teloxide::repl_with_listener( teloxide::repl_with_listener(
bot, bot,
|msg: Message, bot: Bot| async move { |bot: Bot, msg: Message| async move {
bot.send_message(msg.chat.id, "pong").await?; bot.send_message(msg.chat.id, "pong").await?;
Ok(()) Ok(())
}, },

View file

@ -83,7 +83,7 @@ fn schema() -> UpdateHandler<Box<dyn std::error::Error + Send + Sync + 'static>>
.branch(callback_query_handler) .branch(callback_query_handler)
} }
async fn start(bot: Bot, msg: Message, dialogue: MyDialogue) -> HandlerResult { async fn start(bot: Bot, dialogue: MyDialogue, msg: Message) -> HandlerResult {
bot.send_message(msg.chat.id, "Let's start! What's your full name?").await?; bot.send_message(msg.chat.id, "Let's start! What's your full name?").await?;
dialogue.update(State::ReceiveFullName).await?; dialogue.update(State::ReceiveFullName).await?;
Ok(()) Ok(())
@ -94,7 +94,7 @@ async fn help(bot: Bot, msg: Message) -> HandlerResult {
Ok(()) Ok(())
} }
async fn cancel(bot: Bot, msg: Message, dialogue: MyDialogue) -> HandlerResult { async fn cancel(bot: Bot, dialogue: MyDialogue, msg: Message) -> HandlerResult {
bot.send_message(msg.chat.id, "Cancelling the dialogue.").await?; bot.send_message(msg.chat.id, "Cancelling the dialogue.").await?;
dialogue.exit().await?; dialogue.exit().await?;
Ok(()) Ok(())
@ -106,7 +106,7 @@ async fn invalid_state(bot: Bot, msg: Message) -> HandlerResult {
Ok(()) Ok(())
} }
async fn receive_full_name(bot: Bot, msg: Message, dialogue: MyDialogue) -> HandlerResult { async fn receive_full_name(bot: Bot, dialogue: MyDialogue, msg: Message) -> HandlerResult {
match msg.text().map(ToOwned::to_owned) { match msg.text().map(ToOwned::to_owned) {
Some(full_name) => { Some(full_name) => {
let products = ["Apple", "Banana", "Orange", "Potato"] let products = ["Apple", "Banana", "Orange", "Potato"]
@ -127,9 +127,9 @@ async fn receive_full_name(bot: Bot, msg: Message, dialogue: MyDialogue) -> Hand
async fn receive_product_selection( async fn receive_product_selection(
bot: Bot, bot: Bot,
q: CallbackQuery,
dialogue: MyDialogue, dialogue: MyDialogue,
full_name: String, full_name: String, // Available from `State::ReceiveProductChoice`.
q: CallbackQuery,
) -> HandlerResult { ) -> HandlerResult {
if let Some(product) = &q.data { if let Some(product) = &q.data {
bot.send_message( bot.send_message(

View file

@ -16,7 +16,7 @@ async fn main() {
let messages_total = Arc::new(AtomicU64::new(0)); let messages_total = Arc::new(AtomicU64::new(0));
let handler = Update::filter_message().endpoint( let handler = Update::filter_message().endpoint(
|msg: Message, bot: Bot, messages_total: Arc<AtomicU64>| async move { |bot: Bot, messages_total: Arc<AtomicU64>, msg: Message| async move {
let previous = messages_total.fetch_add(1, Ordering::Relaxed); let previous = messages_total.fetch_add(1, Ordering::Relaxed);
bot.send_message(msg.chat.id, format!("I received {previous} messages in total.")) bot.send_message(msg.chat.id, format!("I received {previous} messages in total."))
.await?; .await?;

View file

@ -9,8 +9,8 @@ async fn main() {
let bot = Bot::from_env(); let bot = Bot::from_env();
teloxide::repl(bot, |message: Message, bot: Bot| async move { teloxide::repl(bot, |bot: Bot, msg: Message| async move {
bot.send_dice(message.chat.id).await?; bot.send_dice(msg.chat.id).await?;
Ok(()) Ok(())
}) })
.await; .await;

View file

@ -113,26 +113,26 @@
//! type MyDialogue = Dialogue<State, InMemStorage<State>>; //! type MyDialogue = Dialogue<State, InMemStorage<State>>;
//! type HandlerResult = Result<(), Box<dyn std::error::Error + Send + Sync>>; //! type HandlerResult = Result<(), Box<dyn std::error::Error + Send + Sync>>;
//! //!
//! async fn start(bot: Bot, msg: Message, dialogue: MyDialogue) -> HandlerResult { //! async fn start(bot: Bot, dialogue: MyDialogue, msg: Message) -> HandlerResult {
//! todo!() //! todo!()
//! } //! }
//! async fn help(bot: Bot, msg: Message) -> HandlerResult { //! async fn help(bot: Bot, msg: Message) -> HandlerResult {
//! todo!() //! todo!()
//! } //! }
//! async fn cancel(bot: Bot, msg: Message, dialogue: MyDialogue) -> HandlerResult { //! async fn cancel(bot: Bot, dialogue: MyDialogue, msg: Message) -> HandlerResult {
//! todo!() //! todo!()
//! } //! }
//! async fn invalid_state(bot: Bot, msg: Message) -> HandlerResult { //! async fn invalid_state(bot: Bot, msg: Message) -> HandlerResult {
//! todo!() //! todo!()
//! } //! }
//! async fn receive_full_name(bot: Bot, msg: Message, dialogue: MyDialogue) -> HandlerResult { //! async fn receive_full_name(bot: Bot, dialogue: MyDialogue, msg: Message) -> HandlerResult {
//! todo!() //! todo!()
//! } //! }
//! async fn receive_product_selection( //! async fn receive_product_selection(
//! bot: Bot, //! bot: Bot,
//! q: CallbackQuery,
//! dialogue: MyDialogue, //! dialogue: MyDialogue,
//! full_name: String, //! full_name: String, // Available from `State::ReceiveProductChoice`.
//! q: CallbackQuery,
//! ) -> HandlerResult { //! ) -> HandlerResult {
//! todo!() //! todo!()
//! } //! }

View file

@ -39,9 +39,9 @@
//! # #[derive(Clone, Debug)] enum State { ReceiveLocation { full_name: String, age: u8 } } //! # #[derive(Clone, Debug)] enum State { ReceiveLocation { full_name: String, age: u8 } }
//! async fn receive_age( //! async fn receive_age(
//! bot: Bot, //! bot: Bot,
//! msg: Message,
//! dialogue: MyDialogue, //! dialogue: MyDialogue,
//! full_name: String, // Available from `State::ReceiveAge`. //! full_name: String, // Available from `State::ReceiveAge`.
//! msg: Message,
//! ) -> HandlerResult { //! ) -> HandlerResult {
//! match msg.text().map(|text| text.parse::<u8>()) { //! match msg.text().map(|text| text.parse::<u8>()) {
//! Some(Ok(age)) => { //! Some(Ok(age)) => {
@ -71,9 +71,9 @@
//! # #[derive(Clone, Debug)] enum State {} //! # #[derive(Clone, Debug)] enum State {}
//! async fn receive_location( //! async fn receive_location(
//! bot: Bot, //! bot: Bot,
//! msg: Message,
//! dialogue: MyDialogue, //! dialogue: MyDialogue,
//! (full_name, age): (String, u8), // Available from `State::ReceiveLocation`. //! (full_name, age): (String, u8), // Available from `State::ReceiveLocation`.
//! msg: Message,
//! ) -> HandlerResult { //! ) -> HandlerResult {
//! match msg.text() { //! match msg.text() {
//! Some(location) => { //! Some(location) => {

View file

@ -15,8 +15,8 @@
//! //!
//! let bot = Bot::from_env(); //! let bot = Bot::from_env();
//! //!
//! teloxide::repl(bot, |message: Message, bot: Bot| async move { //! teloxide::repl(bot, |bot: Bot, msg: Message| async move {
//! bot.send_dice(message.chat.id).await?; //! bot.send_dice(msg.chat.id).await?;
//! Ok(()) //! Ok(())
//! }) //! })
//! .await; //! .await;