diff --git a/README.md b/README.md index d44b6be9..47854d69 100644 --- a/README.md +++ b/README.md @@ -100,7 +100,7 @@ async fn main() { Dispatcher::new(bot) .messages_handler(|rx: DispatcherHandlerRx| { rx.for_each(|message| async move { - message.answer("pong").send().await.log_on_error().await; + message.answer_str("pong").await.log_on_error().await; }) }) .dispatch() @@ -136,28 +136,18 @@ enum Command { Help, #[command(description = "handle a username.")] Username(String), - #[command( - description = "handle a username and an age.", - parse_with = "split" - )] + #[command(description = "handle a username and an age.", parse_with = "split")] UsernameAndAge { username: String, age: u8 }, } -async fn answer( - cx: UpdateWithCx, - command: Command, -) -> ResponseResult<()> { +async fn answer(cx: UpdateWithCx, command: Command) -> ResponseResult<()> { match command { Command::Help => cx.answer(Command::descriptions()).send().await?, Command::Username(username) => { cx.answer_str(format!("Your username is @{}.", username)).await? } Command::UsernameAndAge { username, age } => { - cx.answer_str(format!( - "Your username is @{} and age is {}.", - username, age - )) - .await? + cx.answer_str(format!("Your username is @{} and age is {}.", username, age)).await? } }; @@ -176,6 +166,7 @@ async fn handle_commands(rx: DispatcherHandlerRx) { async fn main() { // Setup is omitted... } + ```
@@ -195,9 +186,8 @@ Below is a bot, which asks you three questions and then sends the answers back t ```rust // Imports are omitted... -#[derive(Transition, SmartDefault, From)] +#[derive(Transition, From)] pub enum Dialogue { - #[default] Start(StartState), ReceiveFullName(ReceiveFullNameState), ReceiveAge(ReceiveAgeState), @@ -219,11 +209,7 @@ impl Default for Dialogue { pub struct StartState; #[teloxide(transition)] -async fn start( - _state: StartState, - cx: TransitionIn, - _ans: String, -) -> TransitionOut { +async fn start(_state: StartState, cx: TransitionIn, _ans: String) -> TransitionOut { cx.answer_str("Let's start! What's your full name?").await?; next(ReceiveFullNameState) } @@ -291,11 +277,8 @@ async fn receive_location( cx: TransitionIn, ans: String, ) -> TransitionOut { - cx.answer_str(format!( - "Full name: {}\nAge: {}\nLocation: {}", - state.full_name, state.age, ans - )) - .await?; + cx.answer_str(format!("Full name: {}\nAge: {}\nLocation: {}", state.full_name, state.age, ans)) + .await?; exit() } ``` @@ -320,19 +303,14 @@ async fn main() { |DialogueWithCx { cx, dialogue }: In| async move { // No panic because of std::convert::Infallible. let dialogue = dialogue.unwrap(); - handle_message(cx, dialogue) - .await - .expect("Something wrong with the bot!") + handle_message(cx, dialogue).await.expect("Something wrong with the bot!") }, )) .dispatch() .await; } -async fn handle_message( - cx: UpdateWithCx, - dialogue: Dialogue, -) -> TransitionOut { +async fn handle_message(cx: UpdateWithCx, dialogue: Dialogue) -> TransitionOut { match cx.update.text_owned() { None => { cx.answer_str("Send me a text message.").await?; @@ -341,6 +319,7 @@ async fn handle_message( Some(ans) => dialogue.react(cx, ans).await, } } + ```
diff --git a/examples/admin_bot/src/main.rs b/examples/admin_bot/src/main.rs index cdeab9e3..78c51cb4 100644 --- a/examples/admin_bot/src/main.rs +++ b/examples/admin_bot/src/main.rs @@ -1,8 +1,6 @@ use std::str::FromStr; -use teloxide::{ - prelude::*, types::ChatPermissions, utils::command::BotCommand -}; +use teloxide::{prelude::*, types::ChatPermissions, utils::command::BotCommand}; use futures::future; @@ -81,9 +79,7 @@ async fn mute_user(cx: &Cx, time: u32) -> ResponseResult<()> { .await?; } None => { - cx.reply_to("Use this command in reply to another message") - .send() - .await?; + cx.reply_to("Use this command in reply to another message").send().await?; } } Ok(()) @@ -94,15 +90,10 @@ async fn kick_user(cx: &Cx) -> ResponseResult<()> { match cx.update.reply_to_message() { Some(mes) => { // bot.unban_chat_member can also kicks a user from a group chat. - cx.bot - .unban_chat_member(cx.update.chat_id(), mes.from().unwrap().id) - .send() - .await?; + cx.bot.unban_chat_member(cx.update.chat_id(), mes.from().unwrap().id).send().await?; } None => { - cx.reply_to("Use this command in reply to another message") - .send() - .await?; + cx.reply_to("Use this command in reply to another message").send().await?; } } Ok(()) @@ -122,29 +113,18 @@ async fn ban_user(cx: &Cx, time: u32) -> ResponseResult<()> { .await?; } None => { - cx.reply_to("Use this command in a reply to another message!") - .send() - .await?; + cx.reply_to("Use this command in a reply to another message!").send().await?; } } Ok(()) } -async fn action( - cx: UpdateWithCx, - command: Command, -) -> ResponseResult<()> { +async fn action(cx: UpdateWithCx, command: Command) -> ResponseResult<()> { match command { - Command::Help => { - cx.answer(Command::descriptions()).send().await.map(|_| ())? - } + Command::Help => cx.answer(Command::descriptions()).send().await.map(|_| ())?, Command::Kick => kick_user(&cx).await?, - Command::Ban { time, unit } => { - ban_user(&cx, calc_restrict_time(time, unit)).await? - } - Command::Mute { time, unit } => { - mute_user(&cx, calc_restrict_time(time, unit)).await? - } + Command::Ban { time, unit } => ban_user(&cx, calc_restrict_time(time, unit)).await?, + Command::Mute { time, unit } => mute_user(&cx, calc_restrict_time(time, unit)).await?, }; Ok(()) diff --git a/examples/dialogue_bot/src/dialogue/states/receive_age.rs b/examples/dialogue_bot/src/dialogue/states/receive_age.rs index 404258c9..71b31371 100644 --- a/examples/dialogue_bot/src/dialogue/states/receive_age.rs +++ b/examples/dialogue_bot/src/dialogue/states/receive_age.rs @@ -1,6 +1,4 @@ -use crate::dialogue::{ - states::receive_location::ReceiveLocationState, Dialogue, -}; +use crate::dialogue::{states::receive_location::ReceiveLocationState, Dialogue}; use teloxide::prelude::*; use teloxide_macros::teloxide; diff --git a/examples/dialogue_bot/src/dialogue/states/receive_location.rs b/examples/dialogue_bot/src/dialogue/states/receive_location.rs index 7db8b851..041219a2 100644 --- a/examples/dialogue_bot/src/dialogue/states/receive_location.rs +++ b/examples/dialogue_bot/src/dialogue/states/receive_location.rs @@ -14,10 +14,7 @@ async fn receive_location( cx: TransitionIn, ans: String, ) -> TransitionOut { - cx.answer_str(format!( - "Full name: {}\nAge: {}\nLocation: {}", - state.full_name, state.age, ans - )) - .await?; + cx.answer_str(format!("Full name: {}\nAge: {}\nLocation: {}", state.full_name, state.age, ans)) + .await?; exit() } diff --git a/examples/dialogue_bot/src/dialogue/states/start.rs b/examples/dialogue_bot/src/dialogue/states/start.rs index 2f448f72..60240b59 100644 --- a/examples/dialogue_bot/src/dialogue/states/start.rs +++ b/examples/dialogue_bot/src/dialogue/states/start.rs @@ -6,11 +6,7 @@ use teloxide_macros::teloxide; pub struct StartState; #[teloxide(transition)] -async fn start( - _state: StartState, - cx: TransitionIn, - _ans: String, -) -> TransitionOut { +async fn start(_state: StartState, cx: TransitionIn, _ans: String) -> TransitionOut { cx.answer_str("Let's start! What's your full name?").await?; next(ReceiveFullNameState) } diff --git a/examples/dialogue_bot/src/main.rs b/examples/dialogue_bot/src/main.rs index 66a5f63a..042c7e77 100644 --- a/examples/dialogue_bot/src/main.rs +++ b/examples/dialogue_bot/src/main.rs @@ -44,19 +44,14 @@ async fn run() { |DialogueWithCx { cx, dialogue }: In| async move { // No panic because of std::convert::Infallible. let dialogue = dialogue.unwrap(); - handle_message(cx, dialogue) - .await - .expect("Something wrong with the bot!") + handle_message(cx, dialogue).await.expect("Something wrong with the bot!") }, )) .dispatch() .await; } -async fn handle_message( - cx: UpdateWithCx, - dialogue: Dialogue, -) -> TransitionOut { +async fn handle_message(cx: UpdateWithCx, dialogue: Dialogue) -> TransitionOut { match cx.update.text_owned() { None => { cx.answer_str("Send me a text message.").await?; diff --git a/examples/heroku_ping_pong_bot/src/main.rs b/examples/heroku_ping_pong_bot/src/main.rs index 974ed89c..daec468a 100644 --- a/examples/heroku_ping_pong_bot/src/main.rs +++ b/examples/heroku_ping_pong_bot/src/main.rs @@ -14,19 +14,14 @@ async fn main() { run().await; } -async fn handle_rejection( - error: warp::Rejection, -) -> Result { +async fn handle_rejection(error: warp::Rejection) -> Result { log::error!("Cannot process the request due to: {:?}", error); Ok(StatusCode::INTERNAL_SERVER_ERROR) } -pub async fn webhook<'a>( - bot: Bot, -) -> impl update_listeners::UpdateListener { +pub async fn webhook<'a>(bot: Bot) -> impl update_listeners::UpdateListener { // Heroku defines auto defines a port value - let teloxide_token = env::var("TELOXIDE_TOKEN") - .expect("TELOXIDE_TOKEN env variable missing"); + let teloxide_token = env::var("TELOXIDE_TOKEN").expect("TELOXIDE_TOKEN env variable missing"); let port: u16 = env::var("PORT") .expect("PORT env variable missing") .parse() @@ -58,8 +53,7 @@ pub async fn webhook<'a>( } }; if let Ok(update) = try_parse { - tx.send(Ok(update)) - .expect("Cannot send an incoming update from the webhook") + tx.send(Ok(update)).expect("Cannot send an incoming update from the webhook") } StatusCode::OK @@ -87,9 +81,7 @@ async fn run() { }) .dispatch_with_listener( webhook(bot).await, - LoggingErrorHandler::with_custom_text( - "An error from the update listener", - ), + LoggingErrorHandler::with_custom_text("An error from the update listener"), ) .await; } diff --git a/examples/ngrok_ping_pong_bot/src/main.rs b/examples/ngrok_ping_pong_bot/src/main.rs index af31f297..0c9b278b 100644 --- a/examples/ngrok_ping_pong_bot/src/main.rs +++ b/examples/ngrok_ping_pong_bot/src/main.rs @@ -1,5 +1,5 @@ -// The version of ngrok ping-pong-bot, which uses a webhook to receive updates from -// Telegram, instead of long polling. +// The version of ngrok ping-pong-bot, which uses a webhook to receive updates +// from Telegram, instead of long polling. use teloxide::{dispatching::update_listeners, prelude::*}; @@ -14,16 +14,12 @@ async fn main() { run().await; } -async fn handle_rejection( - error: warp::Rejection, -) -> Result { +async fn handle_rejection(error: warp::Rejection) -> Result { log::error!("Cannot process the request due to: {:?}", error); Ok(StatusCode::INTERNAL_SERVER_ERROR) } -pub async fn webhook<'a>( - bot: Bot, -) -> impl update_listeners::UpdateListener { +pub async fn webhook<'a>(bot: Bot) -> impl update_listeners::UpdateListener { // You might want to specify a self-signed certificate via .certificate // method on SetWebhook. bot.set_webhook("Your HTTPS ngrok URL here. Get it by 'ngrok http 80'") @@ -37,8 +33,7 @@ pub async fn webhook<'a>( .and(warp::body::json()) .map(move |json: serde_json::Value| { if let Ok(update) = Update::try_parse(&json) { - tx.send(Ok(update)) - .expect("Cannot send an incoming update from the webhook") + tx.send(Ok(update)).expect("Cannot send an incoming update from the webhook") } StatusCode::OK @@ -68,9 +63,7 @@ async fn run() { }) .dispatch_with_listener( webhook(bot).await, - LoggingErrorHandler::with_custom_text( - "An error from the update listener", - ), + LoggingErrorHandler::with_custom_text("An error from the update listener"), ) .await; } diff --git a/examples/redis_remember_bot/src/main.rs b/examples/redis_remember_bot/src/main.rs index 283061cf..a95e6363 100644 --- a/examples/redis_remember_bot/src/main.rs +++ b/examples/redis_remember_bot/src/main.rs @@ -38,26 +38,19 @@ async fn run() { |DialogueWithCx { cx, dialogue }: In| async move { // No panic because of std::convert::Infallible. let dialogue = dialogue.unwrap(); - handle_message(cx, dialogue) - .await - .expect("Something wrong with the bot!") + handle_message(cx, dialogue).await.expect("Something wrong with the bot!") }, // You can also choose serializer::JSON or serializer::CBOR // All serializers but JSON require enabling feature // "serializer-", e. g. "serializer-cbor" // or "serializer-bincode" - RedisStorage::open("redis://127.0.0.1:6379", Bincode) - .await - .unwrap(), + RedisStorage::open("redis://127.0.0.1:6379", Bincode).await.unwrap(), )) .dispatch() .await; } -async fn handle_message( - cx: UpdateWithCx, - dialogue: Dialogue, -) -> TransitionOut { +async fn handle_message(cx: UpdateWithCx, dialogue: Dialogue) -> TransitionOut { match cx.update.text_owned() { None => { cx.answer_str("Send me a text message.").await?; diff --git a/examples/redis_remember_bot/src/transitions.rs b/examples/redis_remember_bot/src/transitions.rs index 7bc8fab3..a35c94e8 100644 --- a/examples/redis_remember_bot/src/transitions.rs +++ b/examples/redis_remember_bot/src/transitions.rs @@ -4,17 +4,9 @@ use teloxide_macros::teloxide; use super::states::*; #[teloxide(transition)] -async fn start( - state: StartState, - cx: TransitionIn, - ans: String, -) -> TransitionOut { +async fn start(state: StartState, cx: TransitionIn, ans: String) -> TransitionOut { if let Ok(number) = ans.parse() { - cx.answer_str(format!( - "Remembered number {}. Now use /get or /reset", - number - )) - .await?; + cx.answer_str(format!("Remembered number {}. Now use /get or /reset", number)).await?; next(HaveNumberState { number }) } else { cx.answer_str("Please, send me a number").await?; diff --git a/examples/shared_state_bot/src/main.rs b/examples/shared_state_bot/src/main.rs index e98d18d5..164f5a7a 100644 --- a/examples/shared_state_bot/src/main.rs +++ b/examples/shared_state_bot/src/main.rs @@ -26,10 +26,7 @@ async fn run() { let previous = MESSAGES_TOTAL.fetch_add(1, Ordering::Relaxed); message - .answer_str(format!( - "I received {} messages in total.", - previous - )) + .answer_str(format!("I received {} messages in total.", previous)) .await .log_on_error() .await; diff --git a/examples/simple_commands_bot/src/main.rs b/examples/simple_commands_bot/src/main.rs index 2803ff15..1bdf7d5e 100644 --- a/examples/simple_commands_bot/src/main.rs +++ b/examples/simple_commands_bot/src/main.rs @@ -7,28 +7,18 @@ enum Command { Help, #[command(description = "handle a username.")] Username(String), - #[command( - description = "handle a username and an age.", - parse_with = "split" - )] + #[command(description = "handle a username and an age.", parse_with = "split")] UsernameAndAge { username: String, age: u8 }, } -async fn answer( - cx: UpdateWithCx, - command: Command, -) -> ResponseResult<()> { +async fn answer(cx: UpdateWithCx, command: Command) -> ResponseResult<()> { match command { Command::Help => cx.answer(Command::descriptions()).send().await?, Command::Username(username) => { cx.answer_str(format!("Your username is @{}.", username)).await? } Command::UsernameAndAge { username, age } => { - cx.answer_str(format!( - "Your username is @{} and age is {}.", - username, age - )) - .await? + cx.answer_str(format!("Your username is @{} and age is {}.", username, age)).await? } }; diff --git a/rustfmt.toml b/rustfmt.toml index 1907f64f..c61c5a92 100644 --- a/rustfmt.toml +++ b/rustfmt.toml @@ -1,7 +1,6 @@ format_code_in_doc_comments = true wrap_comments = true format_strings = true -max_width = 80 merge_imports = true use_small_heuristics = "Max" use_field_init_shorthand = true diff --git a/src/bot/api.rs b/src/bot/api.rs index 98baa665..bfb85e92 100644 --- a/src/bot/api.rs +++ b/src/bot/api.rs @@ -1,27 +1,23 @@ use crate::{ requests::{ - AddStickerToSet, AnswerCallbackQuery, AnswerInlineQuery, - AnswerPreCheckoutQuery, AnswerShippingQuery, CreateNewStickerSet, - DeleteChatPhoto, DeleteChatStickerSet, DeleteMessage, - DeleteStickerFromSet, DeleteWebhook, EditMessageCaption, - EditMessageLiveLocation, EditMessageMedia, EditMessageReplyMarkup, - EditMessageText, ExportChatInviteLink, ForwardMessage, GetChat, - GetChatAdministrators, GetChatMember, GetChatMembersCount, GetFile, - GetGameHighScores, GetMe, GetStickerSet, GetUpdates, - GetUserProfilePhotos, GetWebhookInfo, KickChatMember, LeaveChat, - PinChatMessage, PromoteChatMember, RestrictChatMember, SendAnimation, - SendAudio, SendChatAction, SendChatActionKind, SendContact, - SendDocument, SendGame, SendInvoice, SendLocation, SendMediaGroup, - SendMessage, SendPhoto, SendPoll, SendSticker, SendVenue, SendVideo, - SendVideoNote, SendVoice, SetChatAdministratorCustomTitle, - SetChatDescription, SetChatPermissions, SetChatPhoto, - SetChatStickerSet, SetChatTitle, SetGameScore, SetStickerPositionInSet, - SetWebhook, StopMessageLiveLocation, StopPoll, UnbanChatMember, + AddStickerToSet, AnswerCallbackQuery, AnswerInlineQuery, AnswerPreCheckoutQuery, + AnswerShippingQuery, CreateNewStickerSet, DeleteChatPhoto, DeleteChatStickerSet, + DeleteMessage, DeleteStickerFromSet, DeleteWebhook, EditMessageCaption, + EditMessageLiveLocation, EditMessageMedia, EditMessageReplyMarkup, EditMessageText, + ExportChatInviteLink, ForwardMessage, GetChat, GetChatAdministrators, GetChatMember, + GetChatMembersCount, GetFile, GetGameHighScores, GetMe, GetStickerSet, GetUpdates, + GetUserProfilePhotos, GetWebhookInfo, KickChatMember, LeaveChat, PinChatMessage, + PromoteChatMember, RestrictChatMember, SendAnimation, SendAudio, SendChatAction, + SendChatActionKind, SendContact, SendDocument, SendGame, SendInvoice, SendLocation, + SendMediaGroup, SendMessage, SendPhoto, SendPoll, SendSticker, SendVenue, SendVideo, + SendVideoNote, SendVoice, SetChatAdministratorCustomTitle, SetChatDescription, + SetChatPermissions, SetChatPhoto, SetChatStickerSet, SetChatTitle, SetGameScore, + SetStickerPositionInSet, SetWebhook, StopMessageLiveLocation, StopPoll, UnbanChatMember, UnpinChatMessage, UploadStickerFile, }, types::{ - ChatId, ChatOrInlineMessage, ChatPermissions, InlineQueryResult, - InputFile, InputMedia, LabeledPrice, + ChatId, ChatOrInlineMessage, ChatPermissions, InlineQueryResult, InputFile, InputMedia, + LabeledPrice, }, Bot, }; @@ -121,8 +117,9 @@ impl Bot { { match self.parse_mode.deref() { None => SendMessage::new(self.clone(), chat_id, text), - Some(parse_mode) => SendMessage::new(self.clone(), chat_id, text) - .parse_mode(*parse_mode.deref()), + Some(parse_mode) => { + SendMessage::new(self.clone(), chat_id, text).parse_mode(*parse_mode.deref()) + } } } @@ -184,8 +181,9 @@ impl Bot { { match self.parse_mode.deref() { None => SendPhoto::new(self.clone(), chat_id, photo), - Some(parse_mode) => SendPhoto::new(self.clone(), chat_id, photo) - .parse_mode(*parse_mode.deref()), + Some(parse_mode) => { + SendPhoto::new(self.clone(), chat_id, photo).parse_mode(*parse_mode.deref()) + } } } @@ -206,8 +204,9 @@ impl Bot { { match self.parse_mode.deref() { None => SendAudio::new(self.clone(), chat_id, audio), - Some(parse_mode) => SendAudio::new(self.clone(), chat_id, audio) - .parse_mode(*parse_mode.deref()), + Some(parse_mode) => { + SendAudio::new(self.clone(), chat_id, audio).parse_mode(*parse_mode.deref()) + } } } @@ -235,19 +234,14 @@ impl Bot { /// /// [a default parse mode]: crate::BotBuilder::parse_mode /// [`BotBuilder`]: crate::BotBuilder - pub fn send_document( - &self, - chat_id: C, - document: InputFile, - ) -> SendDocument + pub fn send_document(&self, chat_id: C, document: InputFile) -> SendDocument where C: Into, { match self.parse_mode.deref() { None => SendDocument::new(self.clone(), chat_id, document), Some(parse_mode) => { - SendDocument::new(self.clone(), chat_id, document) - .parse_mode(*parse_mode.deref()) + SendDocument::new(self.clone(), chat_id, document).parse_mode(*parse_mode.deref()) } } } @@ -285,8 +279,9 @@ impl Bot { { match self.parse_mode.deref() { None => SendVideo::new(self.clone(), chat_id, video), - Some(parse_mode) => SendVideo::new(self.clone(), chat_id, video) - .parse_mode(*parse_mode.deref()), + Some(parse_mode) => { + SendVideo::new(self.clone(), chat_id, video).parse_mode(*parse_mode.deref()) + } } } @@ -308,19 +303,14 @@ impl Bot { /// /// [a default parse mode]: crate::BotBuilder::parse_mode /// [`BotBuilder`]: crate::BotBuilder - pub fn send_animation( - &self, - chat_id: C, - animation: InputFile, - ) -> SendAnimation + pub fn send_animation(&self, chat_id: C, animation: InputFile) -> SendAnimation where C: Into, { match self.parse_mode.deref() { None => SendAnimation::new(self.clone(), chat_id, animation), Some(parse_mode) => { - SendAnimation::new(self.clone(), chat_id, animation) - .parse_mode(*parse_mode.deref()) + SendAnimation::new(self.clone(), chat_id, animation).parse_mode(*parse_mode.deref()) } } } @@ -364,8 +354,9 @@ impl Bot { { match self.parse_mode.deref() { None => SendVoice::new(self.clone(), chat_id, voice), - Some(parse_mode) => SendVoice::new(self.clone(), chat_id, voice) - .parse_mode(*parse_mode.deref()), + Some(parse_mode) => { + SendVoice::new(self.clone(), chat_id, voice).parse_mode(*parse_mode.deref()) + } } } @@ -390,11 +381,7 @@ impl Bot { /// [`InputFile::FileId`]: crate::types::InputFile::FileId /// [More info on Sending Files »]: https://core.telegram.org/bots/api#sending-files - pub fn send_video_note( - &self, - chat_id: C, - video_note: InputFile, - ) -> SendVideoNote + pub fn send_video_note(&self, chat_id: C, video_note: InputFile) -> SendVideoNote where C: Into, { @@ -427,12 +414,7 @@ impl Bot { /// target supergroup or channel (in the format `@channelusername`). /// - `latitude`: Latitude of the location. /// - `longitude`: Latitude of the location. - pub fn send_location( - &self, - chat_id: C, - latitude: f32, - longitude: f32, - ) -> SendLocation + pub fn send_location(&self, chat_id: C, latitude: f32, longitude: f32) -> SendLocation where C: Into, { @@ -460,12 +442,7 @@ impl Bot { latitude: f32, longitude: f32, ) -> EditMessageLiveLocation { - EditMessageLiveLocation::new( - self.clone(), - chat_or_inline_message, - latitude, - longitude, - ) + EditMessageLiveLocation::new(self.clone(), chat_or_inline_message, latitude, longitude) } /// Use this method to stop updating a live location message before @@ -509,14 +486,7 @@ impl Bot { T: Into, A: Into, { - SendVenue::new( - self.clone(), - chat_id, - latitude, - longitude, - title, - address, - ) + SendVenue::new(self.clone(), chat_id, latitude, longitude, title, address) } /// Use this method to send phone contacts. @@ -529,12 +499,7 @@ impl Bot { /// target supergroup or channel (in the format `@channelusername`). /// - `phone_number`: Contact's phone number. /// - `first_name`: Contact's first name. - pub fn send_contact( - &self, - chat_id: C, - phone_number: P, - first_name: F, - ) -> SendContact + pub fn send_contact(&self, chat_id: C, phone_number: P, first_name: F) -> SendContact where C: Into, P: Into, @@ -555,12 +520,7 @@ impl Bot { /// - `question`: Poll question, 1-255 characters. /// - `options`: List of answer options, 2-10 strings 1-100 characters /// each. - pub fn send_poll( - &self, - chat_id: C, - question: Q, - options: O, - ) -> SendPoll + pub fn send_poll(&self, chat_id: C, question: Q, options: O) -> SendPoll where C: Into, Q: Into, @@ -592,11 +552,7 @@ impl Bot { /// /// [ImageBot]: https://t.me/imagebot /// [`Bot::send_chat_action`]: crate::Bot::send_chat_action - pub fn send_chat_action( - &self, - chat_id: C, - action: SendChatActionKind, - ) -> SendChatAction + pub fn send_chat_action(&self, chat_id: C, action: SendChatActionKind) -> SendChatAction where C: Into, { @@ -609,10 +565,7 @@ impl Bot { /// /// # Params /// - `user_id`: Unique identifier of the target user. - pub fn get_user_profile_photos( - &self, - user_id: i32, - ) -> GetUserProfilePhotos { + pub fn get_user_profile_photos(&self, user_id: i32) -> GetUserProfilePhotos { GetUserProfilePhotos::new(self.clone(), user_id) } @@ -660,11 +613,7 @@ impl Bot { /// - `user_id`: Unique identifier of the target user. /// /// [unbanned]: crate::Bot::unban_chat_member - pub fn kick_chat_member( - &self, - chat_id: C, - user_id: i32, - ) -> KickChatMember + pub fn kick_chat_member(&self, chat_id: C, user_id: i32) -> KickChatMember where C: Into, { @@ -682,11 +631,7 @@ impl Bot { /// - `chat_id`: Unique identifier for the target chat or username of the /// target supergroup or channel (in the format `@channelusername`). /// - `user_id`: Unique identifier of the target user. - pub fn unban_chat_member( - &self, - chat_id: C, - user_id: i32, - ) -> UnbanChatMember + pub fn unban_chat_member(&self, chat_id: C, user_id: i32) -> UnbanChatMember where C: Into, { @@ -731,11 +676,7 @@ impl Bot { /// - `chat_id`: Unique identifier for the target chat or username of the /// target supergroup or channel (in the format `@channelusername`). /// - `user_id`: Unique identifier of the target user. - pub fn promote_chat_member( - &self, - chat_id: C, - user_id: i32, - ) -> PromoteChatMember + pub fn promote_chat_member(&self, chat_id: C, user_id: i32) -> PromoteChatMember where C: Into, { @@ -806,11 +747,7 @@ impl Bot { /// - `chat_id`: Unique identifier for the target chat or username of the /// target supergroup or channel (in the format `@channelusername`). /// - `photo`: New chat photo, uploaded using `multipart/form-data`. - pub fn set_chat_photo( - &self, - chat_id: C, - photo: InputFile, - ) -> SetChatPhoto + pub fn set_chat_photo(&self, chat_id: C, photo: InputFile) -> SetChatPhoto where C: Into, { @@ -883,11 +820,7 @@ impl Bot { /// - `chat_id`: Unique identifier for the target chat or username of the /// target supergroup or channel (in the format `@channelusername`). /// - `message_id`: Identifier of a message to pin. - pub fn pin_chat_message( - &self, - chat_id: C, - message_id: i32, - ) -> PinChatMessage + pub fn pin_chat_message(&self, chat_id: C, message_id: i32) -> PinChatMessage where C: Into, { @@ -953,10 +886,7 @@ impl Bot { /// # Params /// - `chat_id`: Unique identifier for the target chat or username of the /// target supergroup or channel (in the format `@channelusername`). - pub fn get_chat_administrators( - &self, - chat_id: C, - ) -> GetChatAdministrators + pub fn get_chat_administrators(&self, chat_id: C) -> GetChatAdministrators where C: Into, { @@ -1006,11 +936,7 @@ impl Bot { /// target supergroup (in the format `@supergroupusername`). /// - `sticker_set_name`: Name of the sticker set to be set as the group /// sticker set. - pub fn set_chat_sticker_set( - &self, - chat_id: C, - sticker_set_name: S, - ) -> SetChatStickerSet + pub fn set_chat_sticker_set(&self, chat_id: C, sticker_set_name: S) -> SetChatStickerSet where C: Into, S: Into, @@ -1051,10 +977,7 @@ impl Bot { /// - `callback_query_id`: Unique identifier for the query to be answered. /// /// [inline keyboards]: https://core.telegram.org/bots#inline-keyboards-and-on-the-fly-updating - pub fn answer_callback_query( - &self, - callback_query_id: C, - ) -> AnswerCallbackQuery + pub fn answer_callback_query(&self, callback_query_id: C) -> AnswerCallbackQuery where C: Into, { @@ -1088,13 +1011,9 @@ impl Bot { T: Into, { match self.parse_mode.deref() { - None => { - EditMessageText::new(self.clone(), chat_or_inline_message, text) - } - Some(parse_mode) => { - EditMessageText::new(self.clone(), chat_or_inline_message, text) - .parse_mode(*parse_mode.deref()) - } + None => EditMessageText::new(self.clone(), chat_or_inline_message, text), + Some(parse_mode) => EditMessageText::new(self.clone(), chat_or_inline_message, text) + .parse_mode(*parse_mode.deref()), } } @@ -1118,13 +1037,9 @@ impl Bot { chat_or_inline_message: ChatOrInlineMessage, ) -> EditMessageCaption { match self.parse_mode.deref() { - None => { - EditMessageCaption::new(self.clone(), chat_or_inline_message) - } - Some(parse_mode) => { - EditMessageCaption::new(self.clone(), chat_or_inline_message) - .parse_mode(*parse_mode.deref()) - } + None => EditMessageCaption::new(self.clone(), chat_or_inline_message), + Some(parse_mode) => EditMessageCaption::new(self.clone(), chat_or_inline_message) + .parse_mode(*parse_mode.deref()), } } @@ -1202,11 +1117,7 @@ impl Bot { /// - `chat_id`: Unique identifier for the target chat or username of the /// target channel (in the format `@channelusername`). /// - `message_id`: Identifier of the message to delete. - pub fn delete_message( - &self, - chat_id: C, - message_id: i32, - ) -> DeleteMessage + pub fn delete_message(&self, chat_id: C, message_id: i32) -> DeleteMessage where C: Into, { @@ -1268,11 +1179,7 @@ impl Bot { /// [More info on Sending Files »]: https://core.telegram.org/bots/api#sending-files /// [`Bot::create_new_sticker_set`]: crate::Bot::create_new_sticker_set /// [`Bot::add_sticker_to_set`]: crate::Bot::add_sticker_to_set - pub fn upload_sticker_file( - &self, - user_id: i32, - png_sticker: InputFile, - ) -> UploadStickerFile { + pub fn upload_sticker_file(&self, user_id: i32, png_sticker: InputFile) -> UploadStickerFile { UploadStickerFile::new(self.clone(), user_id, png_sticker) } @@ -1317,14 +1224,7 @@ impl Bot { T: Into, E: Into, { - CreateNewStickerSet::new( - self.clone(), - user_id, - name, - title, - png_sticker, - emojis, - ) + CreateNewStickerSet::new(self.clone(), user_id, name, title, png_sticker, emojis) } /// Use this method to add a new sticker to a set created by the bot. @@ -1402,11 +1302,7 @@ impl Bot { /// # Params /// - `inline_query_id`: Unique identifier for the answered query. /// - `results`: A JSON-serialized array of results for the inline query. - pub fn answer_inline_query( - &self, - inline_query_id: I, - results: R, - ) -> AnswerInlineQuery + pub fn answer_inline_query(&self, inline_query_id: I, results: R) -> AnswerInlineQuery where I: Into, R: Into>, @@ -1484,11 +1380,7 @@ impl Bot { /// delivery to the specified address is not possible). /// /// [`Update`]: crate::types::Update - pub fn answer_shipping_query( - &self, - shipping_query_id: S, - ok: bool, - ) -> AnswerShippingQuery + pub fn answer_shipping_query(&self, shipping_query_id: S, ok: bool) -> AnswerShippingQuery where S: Into, { @@ -1607,11 +1499,6 @@ impl Bot { C: Into, CT: Into, { - SetChatAdministratorCustomTitle::new( - self.clone(), - chat_id, - user_id, - custom_title, - ) + SetChatAdministratorCustomTitle::new(self.clone(), chat_id, user_id, custom_title) } } diff --git a/src/bot/download.rs b/src/bot/download.rs index 985e36e4..7035cfe7 100644 --- a/src/bot/download.rs +++ b/src/bot/download.rs @@ -59,8 +59,7 @@ impl Bot { pub async fn download_file_stream( &self, path: &str, - ) -> Result>, reqwest::Error> - { + ) -> Result>, reqwest::Error> { download_file_stream(&self.client, &self.token, path).await } } diff --git a/src/bot/mod.rs b/src/bot/mod.rs index fd840461..10454a32 100644 --- a/src/bot/mod.rs +++ b/src/bot/mod.rs @@ -116,8 +116,7 @@ pub(crate) fn build_sound_bot() -> Client { } fn get_token_from_env() -> String { - std::env::var("TELOXIDE_TOKEN") - .expect("Cannot get the TELOXIDE_TOKEN env variable") + std::env::var("TELOXIDE_TOKEN").expect("Cannot get the TELOXIDE_TOKEN env variable") } impl Bot { diff --git a/src/dispatching/dialogue/dialogue_dispatcher.rs b/src/dispatching/dialogue/dialogue_dispatcher.rs index a9c7e4d1..18565824 100644 --- a/src/dispatching/dialogue/dialogue_dispatcher.rs +++ b/src/dispatching/dialogue/dialogue_dispatcher.rs @@ -1,7 +1,6 @@ use crate::dispatching::{ dialogue::{ - DialogueDispatcherHandler, DialogueStage, DialogueWithCx, GetChatId, - InMemStorage, Storage, + DialogueDispatcherHandler, DialogueStage, DialogueWithCx, GetChatId, InMemStorage, Storage, }, DispatcherHandler, UpdateWithCx, }; @@ -100,13 +99,10 @@ where match handler.handle(DialogueWithCx { cx, dialogue }).await { DialogueStage::Next(new_dialogue) => { - if let Ok(Some(_)) = - storage.update_dialogue(chat_id, new_dialogue).await - { + if let Ok(Some(_)) = storage.update_dialogue(chat_id, new_dialogue).await { panic!( - "Oops, you have an bug in your Storage: \ - update_dialogue returns Some after \ - remove_dialogue" + "Oops, you have an bug in your Storage: update_dialogue returns \ + Some after remove_dialogue" ); } } @@ -135,10 +131,7 @@ where S: Storage + Send + Sync + 'static, S::Error: Send + 'static, { - fn handle( - self, - updates: mpsc::UnboundedReceiver>, - ) -> BoxFuture<'static, ()> + fn handle(self, updates: mpsc::UnboundedReceiver>) -> BoxFuture<'static, ()> where UpdateWithCx: 'static, { @@ -152,19 +145,13 @@ where // An old dialogue Some(tx) => { if tx.1.send(cx).is_err() { - panic!( - "We are not dropping a receiver or call .close() \ - on it", - ); + panic!("We are not dropping a receiver or call .close() on it",); } } None => { let tx = this.new_tx(); if tx.send(cx).is_err() { - panic!( - "We are not dropping a receiver or call .close() \ - on it", - ); + panic!("We are not dropping a receiver or call .close() on it",); } this.senders.insert(chat_id, tx); } @@ -214,8 +201,8 @@ mod tests { static ref SEQ3: Mutex> = Mutex::new(Vec::new()); } - let dispatcher = DialogueDispatcher::new( - |cx: DialogueWithCx| async move { + let dispatcher = + DialogueDispatcher::new(|cx: DialogueWithCx| async move { delay_for(Duration::from_millis(300)).await; match cx.cx.update { @@ -232,8 +219,7 @@ mod tests { } DialogueStage::Next(()) - }, - ); + }); let updates = stream::iter( vec![ @@ -260,10 +246,7 @@ mod tests { MyUpdate::new(3, 1611), ] .into_iter() - .map(|update| UpdateWithCx { - update, - bot: Bot::new("Doesn't matter here"), - }) + .map(|update| UpdateWithCx { update, bot: Bot::new("Doesn't matter here") }) .collect::>>(), ); @@ -287,13 +270,7 @@ mod tests { delay_for(Duration::from_millis(3000)).await; assert_eq!(*SEQ1.lock().await, vec![174, 125, 2, 193, 104, 7, 7778]); - assert_eq!( - *SEQ2.lock().await, - vec![411, 515, 623, 2222, 737, 10, 55456] - ); - assert_eq!( - *SEQ3.lock().await, - vec![72782, 2737, 5475, 1096, 872, 5665, 1611] - ); + assert_eq!(*SEQ2.lock().await, vec![411, 515, 623, 2222, 737, 10, 55456]); + assert_eq!(*SEQ3.lock().await, vec![72782, 2737, 5475, 1096, 872, 5665, 1611]); } } diff --git a/src/dispatching/dialogue/dialogue_dispatcher_handler.rs b/src/dispatching/dialogue/dialogue_dispatcher_handler.rs index 111febcd..1a596bcc 100644 --- a/src/dispatching/dialogue/dialogue_dispatcher_handler.rs +++ b/src/dispatching/dialogue/dialogue_dispatcher_handler.rs @@ -23,10 +23,7 @@ where F: Fn(DialogueWithCx) -> Fut + Send + Sync + 'static, Fut: Future> + Send + 'static, { - fn handle( - self: Arc, - cx: DialogueWithCx, - ) -> BoxFuture<'static, Fut::Output> + fn handle(self: Arc, cx: DialogueWithCx) -> BoxFuture<'static, Fut::Output> where DialogueWithCx: Send + 'static, { diff --git a/src/dispatching/dialogue/mod.rs b/src/dispatching/dialogue/mod.rs index c179c667..521fd144 100644 --- a/src/dispatching/dialogue/mod.rs +++ b/src/dispatching/dialogue/mod.rs @@ -153,8 +153,7 @@ pub use dialogue_stage::{exit, next, DialogueStage}; pub use dialogue_with_cx::DialogueWithCx; pub use get_chat_id::GetChatId; pub use transition::{ - SubTransition, SubTransitionOutputType, Transition, TransitionIn, - TransitionOut, + SubTransition, SubTransitionOutputType, Transition, TransitionIn, TransitionOut, }; #[cfg(feature = "redis-storage")] diff --git a/src/dispatching/dialogue/storage/in_mem_storage.rs b/src/dispatching/dialogue/storage/in_mem_storage.rs index 55c8f345..78fc842f 100644 --- a/src/dispatching/dialogue/storage/in_mem_storage.rs +++ b/src/dispatching/dialogue/storage/in_mem_storage.rs @@ -43,8 +43,6 @@ impl Storage for InMemStorage { where D: Send + 'static, { - Box::pin( - async move { Ok(self.map.lock().await.insert(chat_id, dialogue)) }, - ) + Box::pin(async move { Ok(self.map.lock().await.insert(chat_id, dialogue)) }) } } diff --git a/src/dispatching/dialogue/storage/redis_storage.rs b/src/dispatching/dialogue/storage/redis_storage.rs index 37c5fd07..a8514355 100644 --- a/src/dispatching/dialogue/storage/redis_storage.rs +++ b/src/dispatching/dialogue/storage/redis_storage.rs @@ -37,9 +37,7 @@ impl RedisStorage { serializer: S, ) -> Result, RedisStorageError> { Ok(Arc::new(Self { - conn: Mutex::new( - redis::Client::open(url)?.get_async_connection().await?, - ), + conn: Mutex::new(redis::Client::open(url)?.get_async_connection().await?), serializer, })) } @@ -91,21 +89,15 @@ where dialogue: D, ) -> BoxFuture<'static, Result, Self::Error>> { Box::pin(async move { - let dialogue = self - .serializer - .serialize(&dialogue) - .map_err(RedisStorageError::SerdeError)?; + let dialogue = + self.serializer.serialize(&dialogue).map_err(RedisStorageError::SerdeError)?; Ok(self .conn .lock() .await .getset::<_, Vec, Option>>(chat_id, dialogue) .await? - .map(|d| { - self.serializer - .deserialize(&d) - .map_err(RedisStorageError::SerdeError) - }) + .map(|d| self.serializer.deserialize(&d).map_err(RedisStorageError::SerdeError)) .transpose()?) }) } diff --git a/src/dispatching/dialogue/transition.rs b/src/dispatching/dialogue/transition.rs index d53e990e..e1881a2e 100644 --- a/src/dispatching/dialogue/transition.rs +++ b/src/dispatching/dialogue/transition.rs @@ -10,11 +10,7 @@ pub trait Transition: Sized { /// Turns itself into another state, depending on the input message. /// /// `aux` will be passed to each subtransition function. - fn react( - self, - cx: TransitionIn, - aux: T, - ) -> BoxFuture<'static, TransitionOut>; + fn react(self, cx: TransitionIn, aux: T) -> BoxFuture<'static, TransitionOut>; } /// Like [`Transition`], but from `StateN` -> `Dialogue`. diff --git a/src/dispatching/dispatcher.rs b/src/dispatching/dispatcher.rs index 822e9011..95b067c2 100644 --- a/src/dispatching/dispatcher.rs +++ b/src/dispatching/dispatcher.rs @@ -1,12 +1,11 @@ use crate::{ dispatching::{ - update_listeners, update_listeners::UpdateListener, DispatcherHandler, - UpdateWithCx, + update_listeners, update_listeners::UpdateListener, DispatcherHandler, UpdateWithCx, }, error_handlers::{ErrorHandler, LoggingErrorHandler}, types::{ - CallbackQuery, ChosenInlineResult, InlineQuery, Message, Poll, - PollAnswer, PreCheckoutQuery, ShippingQuery, UpdateKind, + CallbackQuery, ChosenInlineResult, InlineQuery, Message, Poll, PollAnswer, + PreCheckoutQuery, ShippingQuery, UpdateKind, }, Bot, }; @@ -26,19 +25,14 @@ mod macros { } } -fn send<'a, Upd>( - bot: &'a Bot, - tx: &'a Tx, - update: Upd, - variant: &'static str, -) where +fn send<'a, Upd>(bot: &'a Bot, tx: &'a Tx, update: Upd, variant: &'static str) +where Upd: Debug, { if let Some(tx) = tx { if let Err(error) = tx.send(UpdateWithCx { bot: bot.clone(), update }) { log::error!( - "The RX part of the {} channel is closed, but an update is \ - received.\nError:{}\n", + "The RX part of the {} channel is closed, but an update is received.\nError:{}\n", variant, error ); @@ -206,9 +200,7 @@ impl Dispatcher { pub async fn dispatch(&self) { self.dispatch_with_listener( update_listeners::polling_default(self.bot.clone()), - LoggingErrorHandler::with_custom_text( - "An error from the update listener", - ), + LoggingErrorHandler::with_custom_text("An error from the update listener"), ) .await; } @@ -228,8 +220,7 @@ impl Dispatcher { update_listener .for_each(move |update| { - let update_listener_error_handler = - Arc::clone(&update_listener_error_handler); + let update_listener_error_handler = Arc::clone(&update_listener_error_handler); async move { log::trace!("Dispatcher received an update: {:?}", update); @@ -237,21 +228,14 @@ impl Dispatcher { let update = match update { Ok(update) => update, Err(error) => { - Arc::clone(&update_listener_error_handler) - .handle_error(error) - .await; + Arc::clone(&update_listener_error_handler).handle_error(error).await; return; } }; match update.kind { UpdateKind::Message(message) => { - send!( - &self.bot, - &self.messages_queue, - message, - UpdateKind::Message - ); + send!(&self.bot, &self.messages_queue, message, UpdateKind::Message); } UpdateKind::EditedMessage(message) => { send!( @@ -318,12 +302,7 @@ impl Dispatcher { ); } UpdateKind::Poll(poll) => { - send!( - &self.bot, - &self.polls_queue, - poll, - UpdateKind::Poll - ); + send!(&self.bot, &self.polls_queue, poll, UpdateKind::Poll); } UpdateKind::PollAnswer(answer) => { send!( diff --git a/src/dispatching/dispatcher_handler.rs b/src/dispatching/dispatcher_handler.rs index 60b3840b..94ec6dbd 100644 --- a/src/dispatching/dispatcher_handler.rs +++ b/src/dispatching/dispatcher_handler.rs @@ -11,10 +11,7 @@ use futures::future::BoxFuture; /// [`Dispatcher`]: crate::dispatching::Dispatcher pub trait DispatcherHandler { #[must_use] - fn handle( - self, - updates: DispatcherHandlerRx, - ) -> BoxFuture<'static, ()> + fn handle(self, updates: DispatcherHandlerRx) -> BoxFuture<'static, ()> where UpdateWithCx: Send + 'static; } diff --git a/src/dispatching/dispatcher_handler_rx_ext.rs b/src/dispatching/dispatcher_handler_rx_ext.rs index 48e37556..12e26146 100644 --- a/src/dispatching/dispatcher_handler_rx_ext.rs +++ b/src/dispatching/dispatcher_handler_rx_ext.rs @@ -1,6 +1,4 @@ -use crate::{ - prelude::UpdateWithCx, types::Message, utils::command::BotCommand, -}; +use crate::{prelude::UpdateWithCx, types::Message, utils::command::BotCommand}; use futures::{stream::BoxStream, Stream, StreamExt}; /// An extension trait to be used with [`DispatcherHandlerRx`]. @@ -11,18 +9,13 @@ use futures::{stream::BoxStream, Stream, StreamExt}; /// [`DispatcherHandlerRx`]: crate::dispatching::DispatcherHandlerRx pub trait DispatcherHandlerRxExt { /// Extracts only text messages from this stream of arbitrary messages. - fn text_messages( - self, - ) -> BoxStream<'static, (UpdateWithCx, String)> + fn text_messages(self) -> BoxStream<'static, (UpdateWithCx, String)> where Self: Stream>; /// Extracts only commands with their arguments from this stream of /// arbitrary messages. - fn commands( - self, - bot_name: N, - ) -> BoxStream<'static, (UpdateWithCx, C)> + fn commands(self, bot_name: N) -> BoxStream<'static, (UpdateWithCx, C)> where Self: Stream>, C: BotCommand, @@ -33,21 +26,14 @@ impl DispatcherHandlerRxExt for T where T: Send + 'static, { - fn text_messages( - self, - ) -> BoxStream<'static, (UpdateWithCx, String)> + fn text_messages(self) -> BoxStream<'static, (UpdateWithCx, String)> where Self: Stream>, { - Box::pin(self.filter_map(|cx| async move { - cx.update.text_owned().map(|text| (cx, text)) - })) + Box::pin(self.filter_map(|cx| async move { cx.update.text_owned().map(|text| (cx, text)) })) } - fn commands( - self, - bot_name: N, - ) -> BoxStream<'static, (UpdateWithCx, C)> + fn commands(self, bot_name: N) -> BoxStream<'static, (UpdateWithCx, C)> where Self: Stream>, C: BotCommand, @@ -58,9 +44,7 @@ where Box::pin(self.text_messages().filter_map(move |(cx, text)| { let bot_name = bot_name.clone(); - async move { - C::parse(&text, &bot_name).map(|command| (cx, command)).ok() - } + async move { C::parse(&text, &bot_name).map(|command| (cx, command)).ok() } })) } } diff --git a/src/dispatching/update_listeners.rs b/src/dispatching/update_listeners.rs index cd0cd454..05b30cc7 100644 --- a/src/dispatching/update_listeners.rs +++ b/src/dispatching/update_listeners.rs @@ -145,8 +145,7 @@ pub fn polling( limit: Option, allowed_updates: Option>, ) -> impl UpdateListener { - let timeout = - timeout.map(|t| t.as_secs().try_into().expect("timeout is too big")); + let timeout = timeout.map(|t| t.as_secs().try_into().expect("timeout is too big")); stream::unfold( (allowed_updates, bot, 0), @@ -165,10 +164,7 @@ pub fn polling( Ok(ok) => ok.id, Err((value, _)) => value["update_id"] .as_i64() - .expect( - "The 'update_id' field must always exist \ - in Update", - ) + .expect("The 'update_id' field must always exist in Update") .try_into() .expect("update_id must be i32"), }; @@ -176,10 +172,8 @@ pub fn polling( offset = id + 1; } - let updates = updates - .into_iter() - .filter_map(Result::ok) - .collect::>(); + let updates = + updates.into_iter().filter_map(Result::ok).collect::>(); updates.into_iter().map(Ok).collect::>() } diff --git a/src/dispatching/update_with_cx.rs b/src/dispatching/update_with_cx.rs index f095bfda..abd72e31 100644 --- a/src/dispatching/update_with_cx.rs +++ b/src/dispatching/update_with_cx.rs @@ -1,10 +1,10 @@ use crate::{ dispatching::dialogue::GetChatId, requests::{ - DeleteMessage, EditMessageCaption, EditMessageText, ForwardMessage, - PinChatMessage, Request, ResponseResult, SendAnimation, SendAudio, - SendContact, SendDocument, SendLocation, SendMediaGroup, SendMessage, - SendPhoto, SendSticker, SendVenue, SendVideo, SendVideoNote, SendVoice, + DeleteMessage, EditMessageCaption, EditMessageText, ForwardMessage, PinChatMessage, + Request, ResponseResult, SendAnimation, SendAudio, SendContact, SendDocument, SendLocation, + SendMediaGroup, SendMessage, SendPhoto, SendSticker, SendVenue, SendVideo, SendVideoNote, + SendVoice, }, types::{ChatId, ChatOrInlineMessage, InputFile, InputMedia, Message}, Bot, @@ -51,9 +51,7 @@ impl UpdateWithCx { where T: Into, { - self.bot - .send_message(self.chat_id(), text) - .reply_to_message_id(self.update.id) + self.bot.send_message(self.chat_id(), text).reply_to_message_id(self.update.id) } pub fn answer_photo(&self, photo: InputFile) -> SendPhoto { @@ -87,11 +85,7 @@ impl UpdateWithCx { self.bot.send_media_group(self.update.chat.id, media_group) } - pub fn answer_location( - &self, - latitude: f32, - longitude: f32, - ) -> SendLocation { + pub fn answer_location(&self, latitude: f32, longitude: f32) -> SendLocation { self.bot.send_location(self.update.chat.id, latitude, longitude) } @@ -106,24 +100,14 @@ impl UpdateWithCx { T: Into, U: Into, { - self.bot.send_venue( - self.update.chat.id, - latitude, - longitude, - title, - address, - ) + self.bot.send_venue(self.update.chat.id, latitude, longitude, title, address) } pub fn answer_video_note(&self, video_note: InputFile) -> SendVideoNote { self.bot.send_video_note(self.update.chat.id, video_note) } - pub fn answer_contact( - &self, - phone_number: T, - first_name: U, - ) -> SendContact + pub fn answer_contact(&self, phone_number: T, first_name: U) -> SendContact where T: Into, U: Into, diff --git a/src/error_handlers.rs b/src/error_handlers.rs index dc3d1ba2..740ae427 100644 --- a/src/error_handlers.rs +++ b/src/error_handlers.rs @@ -174,9 +174,7 @@ impl ErrorHandler for IgnoringErrorHandlerSafe { /// /// LoggingErrorHandler::new().handle_error(()).await; /// LoggingErrorHandler::with_custom_text("Omg1").handle_error(404).await; -/// LoggingErrorHandler::with_custom_text("Omg2") -/// .handle_error("Invalid data type!") -/// .await; +/// LoggingErrorHandler::with_custom_text("Omg2").handle_error("Invalid data type!").await; /// # } /// ``` pub struct LoggingErrorHandler { diff --git a/src/errors.rs b/src/errors.rs index acca11f8..466cc501 100644 --- a/src/errors.rs +++ b/src/errors.rs @@ -63,9 +63,9 @@ pub enum KnownApiErrorKind { /// 1. [`EditMessageText`] /// /// [`EditMessageText`]: crate::requests::EditMessageText - #[serde(rename = "Bad Request: message is not modified: specified new \ - message content and reply markup are exactly the same \ - as a current content and reply markup of the message")] + #[serde(rename = "Bad Request: message is not modified: specified new message content and \ + reply markup are exactly the same as a current content and reply markup \ + of the message")] MessageNotModified, /// Occurs when bot tries to forward or delete a message which was deleted. @@ -285,8 +285,8 @@ pub enum KnownApiErrorKind { /// 1. [`AnswerCallbackQuery`] /// /// [`AnswerCallbackQuery`]: crate::requests::AnswerCallbackQuery - #[serde(rename = "Bad Request: query is too old and response timeout \ - expired or query id is invalid")] + #[serde(rename = "Bad Request: query is too old and response timeout expired or query id is \ + invalid")] InvalidQueryID, /// Occurs when bot tries to send InlineKeyboardMarkup with invalid button @@ -314,8 +314,8 @@ pub enum KnownApiErrorKind { /// 1. [`SendMessage`] /// /// [`SendMessage`]: crate::requests::SendMessage - #[serde(rename = "Bad Request: can't parse inline keyboard button: Text \ - buttons are unallowed in the inline keyboard")] + #[serde(rename = "Bad Request: can't parse inline keyboard button: Text buttons are \ + unallowed in the inline keyboard")] TextButtonsAreUnallowed, /// Occurs when bot tries to get file by wrong file id. @@ -361,8 +361,7 @@ pub enum KnownApiErrorKind { /// Occurs when bot tries to use method in group which is allowed only in a /// supergroup or channel. - #[serde(rename = "Bad Request: method is available only for supergroups \ - and channel")] + #[serde(rename = "Bad Request: method is available only for supergroups and channel")] MethodNotAvailableInPrivateChats, /// Occurs when bot tries to demote chat creator. @@ -390,8 +389,7 @@ pub enum KnownApiErrorKind { /// 1. [`RestrictChatMember`] /// /// [`RestrictChatMember`]: crate::requests::RestrictChatMember - #[serde(rename = "Bad Request: not enough rights to restrict/unrestrict \ - chat member")] + #[serde(rename = "Bad Request: not enough rights to restrict/unrestrict chat member")] NotEnoughRightsToRestrict, /// Occurs when bot tries set webhook to protocol other than HTTPS. @@ -400,8 +398,7 @@ pub enum KnownApiErrorKind { /// 1. [`SetWebhook`] /// /// [`SetWebhook`]: crate::requests::SetWebhook - #[serde(rename = "Bad Request: bad webhook: HTTPS url must be provided \ - for webhook")] + #[serde(rename = "Bad Request: bad webhook: HTTPS url must be provided for webhook")] WebhookRequireHTTPS, /// Occurs when bot tries to set webhook to port other than 80, 88, 443 or @@ -411,8 +408,8 @@ pub enum KnownApiErrorKind { /// 1. [`SetWebhook`] /// /// [`SetWebhook`]: crate::requests::SetWebhook - #[serde(rename = "Bad Request: bad webhook: Webhook can be set up only \ - on ports 80, 88, 443 or 8443")] + #[serde(rename = "Bad Request: bad webhook: Webhook can be set up only on ports 80, 88, 443 \ + or 8443")] BadWebhookPort, /// Occurs when bot tries to set webhook to unknown host. @@ -421,8 +418,7 @@ pub enum KnownApiErrorKind { /// 1. [`SetWebhook`] /// /// [`SetWebhook`]: crate::requests::SetWebhook - #[serde(rename = "Bad Request: bad webhook: Failed to resolve host: \ - Name or service not known")] + #[serde(rename = "Bad Request: bad webhook: Failed to resolve host: Name or service not known")] UnknownHost, /// Occurs when bot tries to set webhook to invalid URL. @@ -476,9 +472,7 @@ pub enum KnownApiErrorKind { /// 1. [`SendMessage`] /// /// [`SendMessage`]: crate::requests::SendMessage - #[serde( - rename = "Unauthorized: bot can't initiate conversation with a user" - )] + #[serde(rename = "Unauthorized: bot can't initiate conversation with a user")] CantInitiateConversation, /// Occurs when you tries to send message to bot. @@ -506,8 +500,8 @@ pub enum KnownApiErrorKind { /// 1. [`GetUpdates`] /// /// [`GetUpdates`]: crate::requests::GetUpdates - #[serde(rename = "Conflict: terminated by other getUpdates request; \ - make sure that only one bot instance is running")] + #[serde(rename = "Conflict: terminated by other getUpdates request; make sure that only one \ + bot instance is running")] TerminatedByOtherGetUpdates, /// Occurs when bot tries to get file by invalid file id. diff --git a/src/lib.rs b/src/lib.rs index d30a19c8..59775c94 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -17,9 +17,7 @@ #![forbid(unsafe_code)] pub use bot::{Bot, BotBuilder}; -pub use errors::{ - ApiErrorKind, DownloadError, KnownApiErrorKind, RequestError, -}; +pub use errors::{ApiErrorKind, DownloadError, KnownApiErrorKind, RequestError}; mod errors; mod net; diff --git a/src/net/mod.rs b/src/net/mod.rs index 1461304f..b4944959 100644 --- a/src/net/mod.rs +++ b/src/net/mod.rs @@ -17,24 +17,14 @@ const TELEGRAM_API_URL: &str = "https://api.telegram.org"; /// /// [Telegram documentation]: https://core.telegram.org/bots/api#making-requests fn method_url(base: &str, token: &str, method_name: &str) -> String { - format!( - "{url}/bot{token}/{method}", - url = base, - token = token, - method = method_name, - ) + format!("{url}/bot{token}/{method}", url = base, token = token, method = method_name,) } /// Creates URL for downloading a file. See the [Telegram documentation]. /// /// [Telegram documentation]: https://core.telegram.org/bots/api#file fn file_url(base: &str, token: &str, file_path: &str) -> String { - format!( - "{url}/file/bot{token}/{file}", - url = base, - token = token, - file = file_path, - ) + format!("{url}/file/bot{token}/{file}", url = base, token = token, file = file_path,) } #[cfg(test)] diff --git a/src/net/telegram_response.rs b/src/net/telegram_response.rs index 4be974eb..d5062e8f 100644 --- a/src/net/telegram_response.rs +++ b/src/net/telegram_response.rs @@ -33,17 +33,10 @@ impl Into> for TelegramResponse { fn into(self) -> Result { match self { TelegramResponse::Ok { result, .. } => Ok(result), - TelegramResponse::Err { - kind, - error_code, - response_parameters, - .. - } => { + TelegramResponse::Err { kind, error_code, response_parameters, .. } => { if let Some(params) = response_parameters { match params { - ResponseParameters::RetryAfter(i) => { - Err(RequestError::RetryAfter(i)) - } + ResponseParameters::RetryAfter(i) => Err(RequestError::RetryAfter(i)), ResponseParameters::MigrateToChatId(to) => { Err(RequestError::MigrateToChatId(to)) } @@ -66,8 +59,7 @@ mod tests { #[test] fn terminated_by_other_get_updates() { - let expected = - ApiErrorKind::Known(KnownApiErrorKind::TerminatedByOtherGetUpdates); + let expected = ApiErrorKind::Known(KnownApiErrorKind::TerminatedByOtherGetUpdates); if let TelegramResponse::Err{ kind, .. } = serde_json::from_str::>(r#"{"ok":false,"error_code":409,"description":"Conflict: terminated by other getUpdates request; make sure that only one bot instance is running"}"#).unwrap() { assert_eq!(expected, kind); } diff --git a/src/prelude.rs b/src/prelude.rs index 12ab10c0..4c5730ed 100644 --- a/src/prelude.rs +++ b/src/prelude.rs @@ -3,8 +3,8 @@ pub use crate::{ dispatching::{ dialogue::{ - exit, next, DialogueDispatcher, DialogueStage, DialogueWithCx, - GetChatId, Transition, TransitionIn, TransitionOut, + exit, next, DialogueDispatcher, DialogueStage, DialogueWithCx, GetChatId, Transition, + TransitionIn, TransitionOut, }, Dispatcher, DispatcherHandlerRx, DispatcherHandlerRxExt, UpdateWithCx, }, diff --git a/src/requests/all/answer_callback_query.rs b/src/requests/all/answer_callback_query.rs index 447b50d2..c74b1e88 100644 --- a/src/requests/all/answer_callback_query.rs +++ b/src/requests/all/answer_callback_query.rs @@ -33,13 +33,7 @@ impl Request for AnswerCallbackQuery { type Output = True; async fn send(&self) -> ResponseResult { - net::request_json( - self.bot.client(), - self.bot.token(), - "answerCallbackQuery", - &self, - ) - .await + net::request_json(self.bot.client(), self.bot.token(), "answerCallbackQuery", &self).await } } @@ -49,14 +43,7 @@ impl AnswerCallbackQuery { C: Into, { let callback_query_id = callback_query_id.into(); - Self { - bot, - callback_query_id, - text: None, - show_alert: None, - url: None, - cache_time: None, - } + Self { bot, callback_query_id, text: None, show_alert: None, url: None, cache_time: None } } /// Unique identifier for the query to be answered. diff --git a/src/requests/all/answer_inline_query.rs b/src/requests/all/answer_inline_query.rs index 0382af65..dd1b6a38 100644 --- a/src/requests/all/answer_inline_query.rs +++ b/src/requests/all/answer_inline_query.rs @@ -31,13 +31,7 @@ impl Request for AnswerInlineQuery { type Output = True; async fn send(&self) -> ResponseResult { - net::request_json( - self.bot.client(), - self.bot.token(), - "answerInlineQuery", - &self, - ) - .await + net::request_json(self.bot.client(), self.bot.token(), "answerInlineQuery", &self).await } } diff --git a/src/requests/all/answer_pre_checkout_query.rs b/src/requests/all/answer_pre_checkout_query.rs index 710019b9..2ac4df42 100644 --- a/src/requests/all/answer_pre_checkout_query.rs +++ b/src/requests/all/answer_pre_checkout_query.rs @@ -34,13 +34,8 @@ impl Request for AnswerPreCheckoutQuery { type Output = True; async fn send(&self) -> ResponseResult { - net::request_json( - self.bot.client(), - self.bot.token(), - "answerPreCheckoutQuery", - &self, - ) - .await + net::request_json(self.bot.client(), self.bot.token(), "answerPreCheckoutQuery", &self) + .await } } diff --git a/src/requests/all/answer_shipping_query.rs b/src/requests/all/answer_shipping_query.rs index b3c177e1..be4d6662 100644 --- a/src/requests/all/answer_shipping_query.rs +++ b/src/requests/all/answer_shipping_query.rs @@ -31,13 +31,7 @@ impl Request for AnswerShippingQuery { type Output = True; async fn send(&self) -> ResponseResult { - net::request_json( - self.bot.client(), - self.bot.token(), - "answerShippingQuery", - &self, - ) - .await + net::request_json(self.bot.client(), self.bot.token(), "answerShippingQuery", &self).await } } @@ -47,13 +41,7 @@ impl AnswerShippingQuery { S: Into, { let shipping_query_id = shipping_query_id.into(); - Self { - bot, - shipping_query_id, - ok, - shipping_options: None, - error_message: None, - } + Self { bot, shipping_query_id, ok, shipping_options: None, error_message: None } } /// Unique identifier for the query to be answered. diff --git a/src/requests/all/delete_chat_photo.rs b/src/requests/all/delete_chat_photo.rs index b54a6a4c..01439bfa 100644 --- a/src/requests/all/delete_chat_photo.rs +++ b/src/requests/all/delete_chat_photo.rs @@ -25,13 +25,7 @@ impl Request for DeleteChatPhoto { type Output = True; async fn send(&self) -> ResponseResult { - net::request_json( - self.bot.client(), - self.bot.token(), - "deleteChatPhoto", - &self, - ) - .await + net::request_json(self.bot.client(), self.bot.token(), "deleteChatPhoto", &self).await } } diff --git a/src/requests/all/delete_chat_sticker_set.rs b/src/requests/all/delete_chat_sticker_set.rs index d4ca16d4..9fe228c5 100644 --- a/src/requests/all/delete_chat_sticker_set.rs +++ b/src/requests/all/delete_chat_sticker_set.rs @@ -30,13 +30,7 @@ impl Request for DeleteChatStickerSet { type Output = True; async fn send(&self) -> ResponseResult { - net::request_json( - self.bot.client(), - self.bot.token(), - "deleteChatStickerSet", - &self, - ) - .await + net::request_json(self.bot.client(), self.bot.token(), "deleteChatStickerSet", &self).await } } diff --git a/src/requests/all/delete_message.rs b/src/requests/all/delete_message.rs index efcfa270..35ead60a 100644 --- a/src/requests/all/delete_message.rs +++ b/src/requests/all/delete_message.rs @@ -36,13 +36,7 @@ impl Request for DeleteMessage { type Output = True; async fn send(&self) -> ResponseResult { - net::request_json( - self.bot.client(), - self.bot.token(), - "deleteMessage", - &self, - ) - .await + net::request_json(self.bot.client(), self.bot.token(), "deleteMessage", &self).await } } diff --git a/src/requests/all/delete_sticker_from_set.rs b/src/requests/all/delete_sticker_from_set.rs index 09846d2e..59269f7a 100644 --- a/src/requests/all/delete_sticker_from_set.rs +++ b/src/requests/all/delete_sticker_from_set.rs @@ -23,13 +23,7 @@ impl Request for DeleteStickerFromSet { type Output = True; async fn send(&self) -> ResponseResult { - net::request_json( - self.bot.client(), - self.bot.token(), - "deleteStickerFromSet", - &self, - ) - .await + net::request_json(self.bot.client(), self.bot.token(), "deleteStickerFromSet", &self).await } } diff --git a/src/requests/all/delete_webhook.rs b/src/requests/all/delete_webhook.rs index 5ab071ab..fd3bd3ba 100644 --- a/src/requests/all/delete_webhook.rs +++ b/src/requests/all/delete_webhook.rs @@ -26,13 +26,7 @@ impl Request for DeleteWebhook { #[allow(clippy::trivially_copy_pass_by_ref)] async fn send(&self) -> ResponseResult { - net::request_json( - self.bot.client(), - self.bot.token(), - "deleteWebhook", - &self, - ) - .await + net::request_json(self.bot.client(), self.bot.token(), "deleteWebhook", &self).await } } diff --git a/src/requests/all/edit_message_caption.rs b/src/requests/all/edit_message_caption.rs index 4b56a909..2b9f2839 100644 --- a/src/requests/all/edit_message_caption.rs +++ b/src/requests/all/edit_message_caption.rs @@ -33,28 +33,13 @@ impl Request for EditMessageCaption { type Output = Message; async fn send(&self) -> ResponseResult { - net::request_json( - self.bot.client(), - self.bot.token(), - "editMessageCaption", - &self, - ) - .await + net::request_json(self.bot.client(), self.bot.token(), "editMessageCaption", &self).await } } impl EditMessageCaption { - pub(crate) fn new( - bot: Bot, - chat_or_inline_message: ChatOrInlineMessage, - ) -> Self { - Self { - bot, - chat_or_inline_message, - caption: None, - parse_mode: None, - reply_markup: None, - } + pub(crate) fn new(bot: Bot, chat_or_inline_message: ChatOrInlineMessage) -> Self { + Self { bot, chat_or_inline_message, caption: None, parse_mode: None, reply_markup: None } } pub fn chat_or_inline_message(mut self, val: ChatOrInlineMessage) -> Self { diff --git a/src/requests/all/edit_message_live_location.rs b/src/requests/all/edit_message_live_location.rs index dda18546..78fd163e 100644 --- a/src/requests/all/edit_message_live_location.rs +++ b/src/requests/all/edit_message_live_location.rs @@ -35,13 +35,8 @@ impl Request for EditMessageLiveLocation { type Output = Message; async fn send(&self) -> ResponseResult { - net::request_json( - self.bot.client(), - self.bot.token(), - "editMessageLiveLocation", - &self, - ) - .await + net::request_json(self.bot.client(), self.bot.token(), "editMessageLiveLocation", &self) + .await } } @@ -52,13 +47,7 @@ impl EditMessageLiveLocation { latitude: f32, longitude: f32, ) -> Self { - Self { - bot, - chat_or_inline_message, - latitude, - longitude, - reply_markup: None, - } + Self { bot, chat_or_inline_message, latitude, longitude, reply_markup: None } } pub fn chat_or_inline_message(mut self, val: ChatOrInlineMessage) -> Self { diff --git a/src/requests/all/edit_message_media.rs b/src/requests/all/edit_message_media.rs index 4e498abb..fd49c5c0 100644 --- a/src/requests/all/edit_message_media.rs +++ b/src/requests/all/edit_message_media.rs @@ -36,13 +36,10 @@ impl Request for EditMessageMedia { match &self.chat_or_inline_message { ChatOrInlineMessage::Chat { chat_id, message_id } => { - params = params - .add_text("chat_id", chat_id) - .add_text("message_id", message_id); + params = params.add_text("chat_id", chat_id).add_text("message_id", message_id); } ChatOrInlineMessage::Inline { inline_message_id } => { - params = - params.add_text("inline_message_id", inline_message_id); + params = params.add_text("inline_message_id", inline_message_id); } } diff --git a/src/requests/all/edit_message_reply_markup.rs b/src/requests/all/edit_message_reply_markup.rs index cef2eec8..cdfd9e67 100644 --- a/src/requests/all/edit_message_reply_markup.rs +++ b/src/requests/all/edit_message_reply_markup.rs @@ -31,21 +31,13 @@ impl Request for EditMessageReplyMarkup { type Output = Message; async fn send(&self) -> ResponseResult { - net::request_json( - self.bot.client(), - self.bot.token(), - "editMessageReplyMarkup", - &self, - ) - .await + net::request_json(self.bot.client(), self.bot.token(), "editMessageReplyMarkup", &self) + .await } } impl EditMessageReplyMarkup { - pub(crate) fn new( - bot: Bot, - chat_or_inline_message: ChatOrInlineMessage, - ) -> Self { + pub(crate) fn new(bot: Bot, chat_or_inline_message: ChatOrInlineMessage) -> Self { Self { bot, chat_or_inline_message, reply_markup: None } } diff --git a/src/requests/all/edit_message_text.rs b/src/requests/all/edit_message_text.rs index 8d87f86e..71c7aeed 100644 --- a/src/requests/all/edit_message_text.rs +++ b/src/requests/all/edit_message_text.rs @@ -34,22 +34,12 @@ impl Request for EditMessageText { type Output = Message; async fn send(&self) -> ResponseResult { - net::request_json( - self.bot.client(), - self.bot.token(), - "editMessageText", - &self, - ) - .await + net::request_json(self.bot.client(), self.bot.token(), "editMessageText", &self).await } } impl EditMessageText { - pub(crate) fn new( - bot: Bot, - chat_or_inline_message: ChatOrInlineMessage, - text: T, - ) -> Self + pub(crate) fn new(bot: Bot, chat_or_inline_message: ChatOrInlineMessage, text: T) -> Self where T: Into, { diff --git a/src/requests/all/export_chat_invite_link.rs b/src/requests/all/export_chat_invite_link.rs index 622099d4..51a26437 100644 --- a/src/requests/all/export_chat_invite_link.rs +++ b/src/requests/all/export_chat_invite_link.rs @@ -40,13 +40,7 @@ impl Request for ExportChatInviteLink { /// Returns the new invite link as `String` on success. async fn send(&self) -> ResponseResult { - net::request_json( - self.bot.client(), - self.bot.token(), - "exportChatInviteLink", - &self, - ) - .await + net::request_json(self.bot.client(), self.bot.token(), "exportChatInviteLink", &self).await } } diff --git a/src/requests/all/forward_message.rs b/src/requests/all/forward_message.rs index ad921401..feb9ec02 100644 --- a/src/requests/all/forward_message.rs +++ b/src/requests/all/forward_message.rs @@ -26,36 +26,19 @@ impl Request for ForwardMessage { type Output = Message; async fn send(&self) -> ResponseResult { - net::request_json( - self.bot.client(), - self.bot.token(), - "forwardMessage", - &self, - ) - .await + net::request_json(self.bot.client(), self.bot.token(), "forwardMessage", &self).await } } impl ForwardMessage { - pub(crate) fn new( - bot: Bot, - chat_id: C, - from_chat_id: F, - message_id: i32, - ) -> Self + pub(crate) fn new(bot: Bot, chat_id: C, from_chat_id: F, message_id: i32) -> Self where C: Into, F: Into, { let chat_id = chat_id.into(); let from_chat_id = from_chat_id.into(); - Self { - bot, - chat_id, - from_chat_id, - message_id, - disable_notification: None, - } + Self { bot, chat_id, from_chat_id, message_id, disable_notification: None } } /// Unique identifier for the target chat or username of the target channel diff --git a/src/requests/all/get_chat.rs b/src/requests/all/get_chat.rs index 9a884ec6..11406776 100644 --- a/src/requests/all/get_chat.rs +++ b/src/requests/all/get_chat.rs @@ -25,8 +25,7 @@ impl Request for GetChat { type Output = Chat; async fn send(&self) -> ResponseResult { - net::request_json(self.bot.client(), self.bot.token(), "getChat", &self) - .await + net::request_json(self.bot.client(), self.bot.token(), "getChat", &self).await } } diff --git a/src/requests/all/get_chat_administrators.rs b/src/requests/all/get_chat_administrators.rs index d3c55a31..06657ec5 100644 --- a/src/requests/all/get_chat_administrators.rs +++ b/src/requests/all/get_chat_administrators.rs @@ -28,13 +28,7 @@ impl Request for GetChatAdministrators { /// On success, returns an array that contains information about all chat /// administrators except other bots. async fn send(&self) -> ResponseResult> { - net::request_json( - self.bot.client(), - self.bot.token(), - "getChatAdministrators", - &self, - ) - .await + net::request_json(self.bot.client(), self.bot.token(), "getChatAdministrators", &self).await } } diff --git a/src/requests/all/get_chat_member.rs b/src/requests/all/get_chat_member.rs index a6c54002..4ebe3f56 100644 --- a/src/requests/all/get_chat_member.rs +++ b/src/requests/all/get_chat_member.rs @@ -24,13 +24,7 @@ impl Request for GetChatMember { type Output = ChatMember; async fn send(&self) -> ResponseResult { - net::request_json( - self.bot.client(), - self.bot.token(), - "getChatMember", - &self, - ) - .await + net::request_json(self.bot.client(), self.bot.token(), "getChatMember", &self).await } } diff --git a/src/requests/all/get_chat_members_count.rs b/src/requests/all/get_chat_members_count.rs index a7062d57..5c78596b 100644 --- a/src/requests/all/get_chat_members_count.rs +++ b/src/requests/all/get_chat_members_count.rs @@ -23,13 +23,7 @@ impl Request for GetChatMembersCount { type Output = i32; async fn send(&self) -> ResponseResult { - net::request_json( - self.bot.client(), - self.bot.token(), - "getChatMembersCount", - &self, - ) - .await + net::request_json(self.bot.client(), self.bot.token(), "getChatMembersCount", &self).await } } diff --git a/src/requests/all/get_file.rs b/src/requests/all/get_file.rs index 00d0a37e..7017f420 100644 --- a/src/requests/all/get_file.rs +++ b/src/requests/all/get_file.rs @@ -39,8 +39,7 @@ impl Request for GetFile { type Output = File; async fn send(&self) -> ResponseResult { - net::request_json(self.bot.client(), self.bot.token(), "getFile", &self) - .await + net::request_json(self.bot.client(), self.bot.token(), "getFile", &self).await } } diff --git a/src/requests/all/get_game_high_scores.rs b/src/requests/all/get_game_high_scores.rs index eb52517a..260098c7 100644 --- a/src/requests/all/get_game_high_scores.rs +++ b/src/requests/all/get_game_high_scores.rs @@ -34,22 +34,12 @@ impl Request for GetGameHighScores { type Output = Vec; async fn send(&self) -> ResponseResult> { - net::request_json( - self.bot.client(), - self.bot.token(), - "getGameHighScores", - &self, - ) - .await + net::request_json(self.bot.client(), self.bot.token(), "getGameHighScores", &self).await } } impl GetGameHighScores { - pub(crate) fn new( - bot: Bot, - chat_or_inline_message: ChatOrInlineMessage, - user_id: i32, - ) -> Self { + pub(crate) fn new(bot: Bot, chat_or_inline_message: ChatOrInlineMessage, user_id: i32) -> Self { Self { bot, chat_or_inline_message, user_id } } diff --git a/src/requests/all/get_me.rs b/src/requests/all/get_me.rs index 83168769..567b4375 100644 --- a/src/requests/all/get_me.rs +++ b/src/requests/all/get_me.rs @@ -22,8 +22,7 @@ impl Request for GetMe { /// Returns basic information about the bot. #[allow(clippy::trivially_copy_pass_by_ref)] async fn send(&self) -> ResponseResult { - net::request_json(self.bot.client(), self.bot.token(), "getMe", &self) - .await + net::request_json(self.bot.client(), self.bot.token(), "getMe", &self).await } } diff --git a/src/requests/all/get_sticker_set.rs b/src/requests/all/get_sticker_set.rs index 0186b9a0..a8a83bea 100644 --- a/src/requests/all/get_sticker_set.rs +++ b/src/requests/all/get_sticker_set.rs @@ -23,13 +23,7 @@ impl Request for GetStickerSet { type Output = StickerSet; async fn send(&self) -> ResponseResult { - net::request_json( - self.bot.client(), - self.bot.token(), - "getStickerSet", - &self, - ) - .await + net::request_json(self.bot.client(), self.bot.token(), "getStickerSet", &self).await } } diff --git a/src/requests/all/get_updates.rs b/src/requests/all/get_updates.rs index d331c677..8bc2db59 100644 --- a/src/requests/all/get_updates.rs +++ b/src/requests/all/get_updates.rs @@ -36,23 +36,14 @@ impl Request for GetUpdates { /// Deserialize to `Vec>` instead of /// `Vec`, because we want to parse the rest of updates even if our /// library hasn't parsed one. - async fn send( - &self, - ) -> ResponseResult>> { - let value: Value = net::request_json( - self.bot.client(), - self.bot.token(), - "getUpdates", - &self, - ) - .await?; + async fn send(&self) -> ResponseResult>> { + let value: Value = + net::request_json(self.bot.client(), self.bot.token(), "getUpdates", &self).await?; match value { Value::Array(array) => Ok(array .into_iter() - .map(|value| { - Update::try_parse(&value).map_err(|error| (value, error)) - }) + .map(|value| Update::try_parse(&value).map_err(|error| (value, error))) .collect()), _ => Err(RequestError::InvalidJson( serde_json::from_value::>(value) @@ -64,13 +55,7 @@ impl Request for GetUpdates { impl GetUpdates { pub(crate) fn new(bot: Bot) -> Self { - Self { - bot, - offset: None, - limit: None, - timeout: None, - allowed_updates: None, - } + Self { bot, offset: None, limit: None, timeout: None, allowed_updates: None } } /// Identifier of the first update to be returned. diff --git a/src/requests/all/get_user_profile_photos.rs b/src/requests/all/get_user_profile_photos.rs index f1dd1a26..663a07a4 100644 --- a/src/requests/all/get_user_profile_photos.rs +++ b/src/requests/all/get_user_profile_photos.rs @@ -25,13 +25,7 @@ impl Request for GetUserProfilePhotos { type Output = UserProfilePhotos; async fn send(&self) -> ResponseResult { - net::request_json( - self.bot.client(), - self.bot.token(), - "getUserProfilePhotos", - &self, - ) - .await + net::request_json(self.bot.client(), self.bot.token(), "getUserProfilePhotos", &self).await } } diff --git a/src/requests/all/get_webhook_info.rs b/src/requests/all/get_webhook_info.rs index 18e6b0fe..51424471 100644 --- a/src/requests/all/get_webhook_info.rs +++ b/src/requests/all/get_webhook_info.rs @@ -27,13 +27,7 @@ impl Request for GetWebhookInfo { #[allow(clippy::trivially_copy_pass_by_ref)] async fn send(&self) -> ResponseResult { - net::request_json( - self.bot.client(), - self.bot.token(), - "getWebhookInfo", - &self, - ) - .await + net::request_json(self.bot.client(), self.bot.token(), "getWebhookInfo", &self).await } } diff --git a/src/requests/all/kick_chat_member.rs b/src/requests/all/kick_chat_member.rs index 85e09946..31953949 100644 --- a/src/requests/all/kick_chat_member.rs +++ b/src/requests/all/kick_chat_member.rs @@ -32,13 +32,7 @@ impl Request for KickChatMember { type Output = True; async fn send(&self) -> ResponseResult { - net::request_json( - self.bot.client(), - self.bot.token(), - "kickChatMember", - &self, - ) - .await + net::request_json(self.bot.client(), self.bot.token(), "kickChatMember", &self).await } } diff --git a/src/requests/all/leave_chat.rs b/src/requests/all/leave_chat.rs index 3bcf7c3d..d0411efb 100644 --- a/src/requests/all/leave_chat.rs +++ b/src/requests/all/leave_chat.rs @@ -23,13 +23,7 @@ impl Request for LeaveChat { type Output = True; async fn send(&self) -> ResponseResult { - net::request_json( - self.bot.client(), - self.bot.token(), - "leaveChat", - &self, - ) - .await + net::request_json(self.bot.client(), self.bot.token(), "leaveChat", &self).await } } diff --git a/src/requests/all/pin_chat_message.rs b/src/requests/all/pin_chat_message.rs index 2fb906da..ae1f3227 100644 --- a/src/requests/all/pin_chat_message.rs +++ b/src/requests/all/pin_chat_message.rs @@ -29,13 +29,7 @@ impl Request for PinChatMessage { type Output = True; async fn send(&self) -> ResponseResult { - net::request_json( - self.bot.client(), - self.bot.token(), - "pinChatMessage", - &self, - ) - .await + net::request_json(self.bot.client(), self.bot.token(), "pinChatMessage", &self).await } } diff --git a/src/requests/all/promote_chat_member.rs b/src/requests/all/promote_chat_member.rs index fa9ad1a0..468b3c48 100644 --- a/src/requests/all/promote_chat_member.rs +++ b/src/requests/all/promote_chat_member.rs @@ -36,13 +36,7 @@ impl Request for PromoteChatMember { type Output = True; async fn send(&self) -> ResponseResult { - net::request_json( - self.bot.client(), - self.bot.token(), - "promoteChatMember", - &self, - ) - .await + net::request_json(self.bot.client(), self.bot.token(), "promoteChatMember", &self).await } } diff --git a/src/requests/all/restrict_chat_member.rs b/src/requests/all/restrict_chat_member.rs index d019d837..6b825b91 100644 --- a/src/requests/all/restrict_chat_member.rs +++ b/src/requests/all/restrict_chat_member.rs @@ -30,23 +30,12 @@ impl Request for RestrictChatMember { type Output = True; async fn send(&self) -> ResponseResult { - net::request_json( - self.bot.client(), - self.bot.token(), - "restrictChatMember", - &self, - ) - .await + net::request_json(self.bot.client(), self.bot.token(), "restrictChatMember", &self).await } } impl RestrictChatMember { - pub(crate) fn new( - bot: Bot, - chat_id: C, - user_id: i32, - permissions: ChatPermissions, - ) -> Self + pub(crate) fn new(bot: Bot, chat_id: C, user_id: i32, permissions: ChatPermissions) -> Self where C: Into, { diff --git a/src/requests/all/send_chat_action.rs b/src/requests/all/send_chat_action.rs index 299bcb12..5fe853b2 100644 --- a/src/requests/all/send_chat_action.rs +++ b/src/requests/all/send_chat_action.rs @@ -75,22 +75,12 @@ impl Request for SendChatAction { type Output = True; async fn send(&self) -> ResponseResult { - net::request_json( - self.bot.client(), - self.bot.token(), - "sendChatAction", - &self, - ) - .await + net::request_json(self.bot.client(), self.bot.token(), "sendChatAction", &self).await } } impl SendChatAction { - pub(crate) fn new( - bot: Bot, - chat_id: C, - action: SendChatActionKind, - ) -> Self + pub(crate) fn new(bot: Bot, chat_id: C, action: SendChatActionKind) -> Self where C: Into, { diff --git a/src/requests/all/send_contact.rs b/src/requests/all/send_contact.rs index 4b8e0aa9..ef3ff034 100644 --- a/src/requests/all/send_contact.rs +++ b/src/requests/all/send_contact.rs @@ -30,23 +30,12 @@ impl Request for SendContact { type Output = Message; async fn send(&self) -> ResponseResult { - net::request_json( - self.bot.client(), - self.bot.token(), - "sendContact", - &self, - ) - .await + net::request_json(self.bot.client(), self.bot.token(), "sendContact", &self).await } } impl SendContact { - pub(crate) fn new( - bot: Bot, - chat_id: C, - phone_number: P, - first_name: F, - ) -> Self + pub(crate) fn new(bot: Bot, chat_id: C, phone_number: P, first_name: F) -> Self where C: Into, P: Into, diff --git a/src/requests/all/send_game.rs b/src/requests/all/send_game.rs index da42e2f6..03a0b0e2 100644 --- a/src/requests/all/send_game.rs +++ b/src/requests/all/send_game.rs @@ -27,13 +27,7 @@ impl Request for SendGame { type Output = Message; async fn send(&self) -> ResponseResult { - net::request_json( - self.bot.client(), - self.bot.token(), - "sendGame", - &self, - ) - .await + net::request_json(self.bot.client(), self.bot.token(), "sendGame", &self).await } } diff --git a/src/requests/all/send_invoice.rs b/src/requests/all/send_invoice.rs index f00b0dc7..8466cdba 100644 --- a/src/requests/all/send_invoice.rs +++ b/src/requests/all/send_invoice.rs @@ -45,13 +45,7 @@ impl Request for SendInvoice { type Output = Message; async fn send(&self) -> ResponseResult { - net::request_json( - self.bot.client(), - self.bot.token(), - "sendInvoice", - &self, - ) - .await + net::request_json(self.bot.client(), self.bot.token(), "sendInvoice", &self).await } } diff --git a/src/requests/all/send_location.rs b/src/requests/all/send_location.rs index b91c4531..20201ad1 100644 --- a/src/requests/all/send_location.rs +++ b/src/requests/all/send_location.rs @@ -29,23 +29,12 @@ impl Request for SendLocation { type Output = Message; async fn send(&self) -> ResponseResult { - net::request_json( - self.bot.client(), - self.bot.token(), - "sendLocation", - &self, - ) - .await + net::request_json(self.bot.client(), self.bot.token(), "sendLocation", &self).await } } impl SendLocation { - pub(crate) fn new( - bot: Bot, - chat_id: C, - latitude: f32, - longitude: f32, - ) -> Self + pub(crate) fn new(bot: Bot, chat_id: C, latitude: f32, longitude: f32) -> Self where C: Into, { diff --git a/src/requests/all/send_media_group.rs b/src/requests/all/send_media_group.rs index 5dfad7e0..7484fc62 100644 --- a/src/requests/all/send_media_group.rs +++ b/src/requests/all/send_media_group.rs @@ -45,13 +45,7 @@ impl SendMediaGroup { { let chat_id = chat_id.into(); let media = media.into(); - Self { - bot, - chat_id, - media, - disable_notification: None, - reply_to_message_id: None, - } + Self { bot, chat_id, media, disable_notification: None, reply_to_message_id: None } } /// Unique identifier for the target chat or username of the target channel diff --git a/src/requests/all/send_message.rs b/src/requests/all/send_message.rs index 2020fed7..29525cb9 100644 --- a/src/requests/all/send_message.rs +++ b/src/requests/all/send_message.rs @@ -29,13 +29,7 @@ impl Request for SendMessage { type Output = Message; async fn send(&self) -> ResponseResult { - net::request_json( - self.bot.client(), - self.bot.token(), - "sendMessage", - &self, - ) - .await + net::request_json(self.bot.client(), self.bot.token(), "sendMessage", &self).await } } diff --git a/src/requests/all/send_poll.rs b/src/requests/all/send_poll.rs index 0e736f75..40d07875 100644 --- a/src/requests/all/send_poll.rs +++ b/src/requests/all/send_poll.rs @@ -33,23 +33,12 @@ impl Request for SendPoll { type Output = Message; async fn send(&self) -> ResponseResult { - net::request_json( - self.bot.client(), - self.bot.token(), - "sendPoll", - &self, - ) - .await + net::request_json(self.bot.client(), self.bot.token(), "sendPoll", &self).await } } impl SendPoll { - pub(crate) fn new( - bot: Bot, - chat_id: C, - question: Q, - options: O, - ) -> Self + pub(crate) fn new(bot: Bot, chat_id: C, question: Q, options: O) -> Self where C: Into, Q: Into, diff --git a/src/requests/all/send_venue.rs b/src/requests/all/send_venue.rs index 0567ba67..513ece7d 100644 --- a/src/requests/all/send_venue.rs +++ b/src/requests/all/send_venue.rs @@ -32,13 +32,7 @@ impl Request for SendVenue { type Output = Message; async fn send(&self) -> ResponseResult { - net::request_json( - self.bot.client(), - self.bot.token(), - "sendVenue", - &self, - ) - .await + net::request_json(self.bot.client(), self.bot.token(), "sendVenue", &self).await } } diff --git a/src/requests/all/set_chat_administrator_custom_title.rs b/src/requests/all/set_chat_administrator_custom_title.rs index 2d85ad06..a3211811 100644 --- a/src/requests/all/set_chat_administrator_custom_title.rs +++ b/src/requests/all/set_chat_administrator_custom_title.rs @@ -37,12 +37,7 @@ impl Request for SetChatAdministratorCustomTitle { } impl SetChatAdministratorCustomTitle { - pub(crate) fn new( - bot: Bot, - chat_id: C, - user_id: i32, - custom_title: CT, - ) -> Self + pub(crate) fn new(bot: Bot, chat_id: C, user_id: i32, custom_title: CT) -> Self where C: Into, CT: Into, diff --git a/src/requests/all/set_chat_description.rs b/src/requests/all/set_chat_description.rs index 006325d0..092c495b 100644 --- a/src/requests/all/set_chat_description.rs +++ b/src/requests/all/set_chat_description.rs @@ -28,13 +28,7 @@ impl Request for SetChatDescription { type Output = True; async fn send(&self) -> ResponseResult { - net::request_json( - self.bot.client(), - self.bot.token(), - "setChatDescription", - &self, - ) - .await + net::request_json(self.bot.client(), self.bot.token(), "setChatDescription", &self).await } } diff --git a/src/requests/all/set_chat_permissions.rs b/src/requests/all/set_chat_permissions.rs index 754cd565..aaa1881b 100644 --- a/src/requests/all/set_chat_permissions.rs +++ b/src/requests/all/set_chat_permissions.rs @@ -27,22 +27,12 @@ impl Request for SetChatPermissions { type Output = True; async fn send(&self) -> ResponseResult { - net::request_json( - self.bot.client(), - self.bot.token(), - "sendChatPermissions", - &self, - ) - .await + net::request_json(self.bot.client(), self.bot.token(), "sendChatPermissions", &self).await } } impl SetChatPermissions { - pub(crate) fn new( - bot: Bot, - chat_id: C, - permissions: ChatPermissions, - ) -> Self + pub(crate) fn new(bot: Bot, chat_id: C, permissions: ChatPermissions) -> Self where C: Into, { diff --git a/src/requests/all/set_chat_photo.rs b/src/requests/all/set_chat_photo.rs index f49ec12a..dcc5febc 100644 --- a/src/requests/all/set_chat_photo.rs +++ b/src/requests/all/set_chat_photo.rs @@ -27,13 +27,7 @@ impl Request for SetChatPhoto { type Output = True; async fn send(&self) -> ResponseResult { - net::request_json( - self.bot.client(), - self.bot.token(), - "setChatPhoto", - &self, - ) - .await + net::request_json(self.bot.client(), self.bot.token(), "setChatPhoto", &self).await } } diff --git a/src/requests/all/set_chat_sticker_set.rs b/src/requests/all/set_chat_sticker_set.rs index 2d59199e..010a10f5 100644 --- a/src/requests/all/set_chat_sticker_set.rs +++ b/src/requests/all/set_chat_sticker_set.rs @@ -28,13 +28,7 @@ impl Request for SetChatStickerSet { type Output = True; async fn send(&self) -> ResponseResult { - net::request_json( - self.bot.client(), - self.bot.token(), - "setChatStickerSet", - &self, - ) - .await + net::request_json(self.bot.client(), self.bot.token(), "setChatStickerSet", &self).await } } diff --git a/src/requests/all/set_chat_title.rs b/src/requests/all/set_chat_title.rs index 447d7eef..7d6ae6d1 100644 --- a/src/requests/all/set_chat_title.rs +++ b/src/requests/all/set_chat_title.rs @@ -27,13 +27,7 @@ impl Request for SetChatTitle { type Output = True; async fn send(&self) -> ResponseResult { - net::request_json( - self.bot.client(), - self.bot.token(), - "setChatTitle", - &self, - ) - .await + net::request_json(self.bot.client(), self.bot.token(), "setChatTitle", &self).await } } diff --git a/src/requests/all/set_game_score.rs b/src/requests/all/set_game_score.rs index c7ea8853..e3271a77 100644 --- a/src/requests/all/set_game_score.rs +++ b/src/requests/all/set_game_score.rs @@ -36,13 +36,7 @@ impl Request for SetGameScore { type Output = Message; async fn send(&self) -> ResponseResult { - net::request_json( - self.bot.client(), - self.bot.token(), - "setGameScore", - &self, - ) - .await + net::request_json(self.bot.client(), self.bot.token(), "setGameScore", &self).await } } diff --git a/src/requests/all/set_sticker_position_in_set.rs b/src/requests/all/set_sticker_position_in_set.rs index 325efbb7..4ed78551 100644 --- a/src/requests/all/set_sticker_position_in_set.rs +++ b/src/requests/all/set_sticker_position_in_set.rs @@ -25,13 +25,8 @@ impl Request for SetStickerPositionInSet { type Output = True; async fn send(&self) -> ResponseResult { - net::request_json( - self.bot.client(), - self.bot.token(), - "setStickerPositionInSet", - &self, - ) - .await + net::request_json(self.bot.client(), self.bot.token(), "setStickerPositionInSet", &self) + .await } } diff --git a/src/requests/all/set_webhook.rs b/src/requests/all/set_webhook.rs index 45ef9fd6..c2aff792 100644 --- a/src/requests/all/set_webhook.rs +++ b/src/requests/all/set_webhook.rs @@ -39,13 +39,7 @@ impl Request for SetWebhook { type Output = True; async fn send(&self) -> ResponseResult { - net::request_json( - self.bot.client(), - self.bot.token(), - "setWebhook", - &self, - ) - .await + net::request_json(self.bot.client(), self.bot.token(), "setWebhook", &self).await } } @@ -55,13 +49,7 @@ impl SetWebhook { U: Into, { let url = url.into(); - Self { - bot, - url, - certificate: None, - max_connections: None, - allowed_updates: None, - } + Self { bot, url, certificate: None, max_connections: None, allowed_updates: None } } /// HTTPS url to send updates to. diff --git a/src/requests/all/stop_message_live_location.rs b/src/requests/all/stop_message_live_location.rs index 08c625a9..a0692ec8 100644 --- a/src/requests/all/stop_message_live_location.rs +++ b/src/requests/all/stop_message_live_location.rs @@ -32,21 +32,13 @@ impl Request for StopMessageLiveLocation { type Output = Message; async fn send(&self) -> ResponseResult { - net::request_json( - self.bot.client(), - self.bot.token(), - "stopMessageLiveLocation", - &self, - ) - .await + net::request_json(self.bot.client(), self.bot.token(), "stopMessageLiveLocation", &self) + .await } } impl StopMessageLiveLocation { - pub(crate) fn new( - bot: Bot, - chat_or_inline_message: ChatOrInlineMessage, - ) -> Self { + pub(crate) fn new(bot: Bot, chat_or_inline_message: ChatOrInlineMessage) -> Self { Self { bot, chat_or_inline_message, reply_markup: None } } diff --git a/src/requests/all/stop_poll.rs b/src/requests/all/stop_poll.rs index b513bd86..946b4760 100644 --- a/src/requests/all/stop_poll.rs +++ b/src/requests/all/stop_poll.rs @@ -28,13 +28,7 @@ impl Request for StopPoll { /// /// [`Poll`]: crate::types::Poll async fn send(&self) -> ResponseResult { - net::request_json( - self.bot.client(), - self.bot.token(), - "stopPoll", - &self, - ) - .await + net::request_json(self.bot.client(), self.bot.token(), "stopPoll", &self).await } } impl StopPoll { diff --git a/src/requests/all/unban_chat_member.rs b/src/requests/all/unban_chat_member.rs index 955c5ba9..5aee625c 100644 --- a/src/requests/all/unban_chat_member.rs +++ b/src/requests/all/unban_chat_member.rs @@ -27,13 +27,7 @@ impl Request for UnbanChatMember { type Output = True; async fn send(&self) -> ResponseResult { - net::request_json( - self.bot.client(), - self.bot.token(), - "unbanChatMember", - &self, - ) - .await + net::request_json(self.bot.client(), self.bot.token(), "unbanChatMember", &self).await } } diff --git a/src/requests/all/unpin_chat_message.rs b/src/requests/all/unpin_chat_message.rs index 4d4a0775..15e76a99 100644 --- a/src/requests/all/unpin_chat_message.rs +++ b/src/requests/all/unpin_chat_message.rs @@ -27,13 +27,7 @@ impl Request for UnpinChatMessage { type Output = True; async fn send(&self) -> ResponseResult { - net::request_json( - self.bot.client(), - self.bot.token(), - "unpinChatMessage", - &self, - ) - .await + net::request_json(self.bot.client(), self.bot.token(), "unpinChatMessage", &self).await } } diff --git a/src/requests/all/upload_sticker_file.rs b/src/requests/all/upload_sticker_file.rs index 3e8b0ea4..b09b143f 100644 --- a/src/requests/all/upload_sticker_file.rs +++ b/src/requests/all/upload_sticker_file.rs @@ -28,13 +28,7 @@ impl Request for UploadStickerFile { type Output = File; async fn send(&self) -> ResponseResult { - net::request_json( - self.bot.client(), - self.bot.token(), - "uploadStickerFile", - &self, - ) - .await + net::request_json(self.bot.client(), self.bot.token(), "uploadStickerFile", &self).await } } diff --git a/src/requests/form_builder.rs b/src/requests/form_builder.rs index e94edaaa..3c7f70b9 100644 --- a/src/requests/form_builder.rs +++ b/src/requests/form_builder.rs @@ -5,8 +5,7 @@ use reqwest::multipart::Form; use crate::{ requests::utils::{file_from_memory_to_part, file_to_part}, types::{ - ChatId, InlineKeyboardMarkup, InputFile, InputMedia, MaskPosition, - ParseMode, ReplyMarkup, + ChatId, InlineKeyboardMarkup, InputFile, InputMedia, MaskPosition, ParseMode, ReplyMarkup, }, }; @@ -27,18 +26,12 @@ impl FormBuilder { T: IntoFormText, { match value.into_form_text() { - Some(val) => { - Self { form: self.form.text(name.into().into_owned(), val) } - } + Some(val) => Self { form: self.form.text(name.into().into_owned(), val) }, None => self, } } - pub async fn add_input_file<'a, N>( - self, - name: N, - value: &InputFile, - ) -> tokio::io::Result + pub async fn add_input_file<'a, N>(self, name: N, value: &InputFile) -> tokio::io::Result where N: Into>, { @@ -53,19 +46,12 @@ impl FormBuilder { } // used in SendMediaGroup - pub async fn add_file<'a, N>( - self, - name: N, - path_to_file: PathBuf, - ) -> tokio::io::Result + pub async fn add_file<'a, N>(self, name: N, path_to_file: PathBuf) -> tokio::io::Result where N: Into>, { Ok(Self { - form: self.form.part( - name.into().into_owned(), - file_to_part(path_to_file).await?, - ), + form: self.form.part(name.into().into_owned(), file_to_part(path_to_file).await?), }) } @@ -79,10 +65,9 @@ impl FormBuilder { N: Into>, { Self { - form: self.form.part( - name.into().into_owned(), - file_from_memory_to_part(data, file_name), - ), + form: self + .form + .part(name.into().into_owned(), file_from_memory_to_part(data, file_name)), } } @@ -109,15 +94,7 @@ macro_rules! impl_for_struct { }; } -impl_for_struct!( - bool, - i32, - i64, - u32, - ReplyMarkup, - InlineKeyboardMarkup, - MaskPosition -); +impl_for_struct!(bool, i32, i64, u32, ReplyMarkup, InlineKeyboardMarkup, MaskPosition); impl IntoFormText for Option where @@ -132,16 +109,14 @@ where // encode files :|) impl IntoFormText for Vec { fn into_form_text(&self) -> Option { - let json = - serde_json::to_string(self).expect("serde_json::to_string failed"); + let json = serde_json::to_string(self).expect("serde_json::to_string failed"); Some(json) } } impl IntoFormText for InputMedia { fn into_form_text(&self) -> Option { - let json = - serde_json::to_string(self).expect("serde_json::to_string failed"); + let json = serde_json::to_string(self).expect("serde_json::to_string failed"); Some(json) } } diff --git a/src/requests/utils.rs b/src/requests/utils.rs index 399c8cd1..f10c9dc5 100644 --- a/src/requests/utils.rs +++ b/src/requests/utils.rs @@ -10,10 +10,7 @@ impl Decoder for FileDecoder { type Item = Bytes; type Error = std::io::Error; - fn decode( - &mut self, - src: &mut BytesMut, - ) -> Result, Self::Error> { + fn decode(&mut self, src: &mut BytesMut) -> Result, Self::Error> { if src.is_empty() { return Ok(None); } @@ -22,20 +19,13 @@ impl Decoder for FileDecoder { } pub async fn file_to_part(path_to_file: PathBuf) -> std::io::Result { - let file_name = - path_to_file.file_name().unwrap().to_string_lossy().into_owned(); + let file_name = path_to_file.file_name().unwrap().to_string_lossy().into_owned(); - let file = FramedRead::new( - tokio::fs::File::open(path_to_file).await?, - FileDecoder, - ); + let file = FramedRead::new(tokio::fs::File::open(path_to_file).await?, FileDecoder); Ok(Part::stream(Body::wrap_stream(file)).file_name(file_name)) } -pub fn file_from_memory_to_part( - data: Cow<'static, [u8]>, - name: String, -) -> Part { +pub fn file_from_memory_to_part(data: Cow<'static, [u8]>, name: String) -> Part { Part::bytes(data).file_name(name) } diff --git a/src/types/audio.rs b/src/types/audio.rs index 68326310..b34d8a62 100644 --- a/src/types/audio.rs +++ b/src/types/audio.rs @@ -64,9 +64,7 @@ mod tests { duration: 60, performer: Some("Performer".to_string()), title: Some("Title".to_string()), - mime_type: Some( - serde_json::from_str("\"application/zip\"").unwrap(), - ), + mime_type: Some(serde_json::from_str("\"application/zip\"").unwrap()), file_size: Some(123_456), thumb: Some(PhotoSize { file_id: "id".to_string(), diff --git a/src/types/chat.rs b/src/types/chat.rs index 082866bc..cf7645e2 100644 --- a/src/types/chat.rs +++ b/src/types/chat.rs @@ -154,16 +154,10 @@ impl<'de> serde::de::Visitor<'de> for PrivateChatKindVisitor { write!(f, r#"field equal to "private""#) } - fn visit_borrowed_str( - self, - v: &'de str, - ) -> Result { + fn visit_borrowed_str(self, v: &'de str) -> Result { match v { "private" => Ok(()), - _ => Err(E::invalid_value( - serde::de::Unexpected::Str(v), - &r#""private""#, - )), + _ => Err(E::invalid_value(serde::de::Unexpected::Str(v), &r#""private""#)), } } } @@ -180,30 +174,16 @@ impl Chat { matches!(self.kind, ChatKind::Private(_)) } pub fn is_group(&self) -> bool { - matches!( - self.kind, - ChatKind::Public(ChatPublic { - kind: PublicChatKind::Group(_), .. - }) - ) + matches!(self.kind, ChatKind::Public(ChatPublic { kind: PublicChatKind::Group(_), .. })) } pub fn is_supergroup(&self) -> bool { matches!( self.kind, - ChatKind::Public(ChatPublic { - kind: PublicChatKind::Supergroup(_), - .. - }) + ChatKind::Public(ChatPublic { kind: PublicChatKind::Supergroup(_), .. }) ) } pub fn is_channel(&self) -> bool { - matches!( - self.kind, - ChatKind::Public(ChatPublic { - kind: PublicChatKind::Channel(_), - .. - }) - ) + matches!(self.kind, ChatKind::Public(ChatPublic { kind: PublicChatKind::Channel(_), .. })) } pub fn is_chat(&self) -> bool { @@ -232,9 +212,7 @@ mod tests { }), photo: None, }; - let actual = - from_str(r#"{"id":-1,"type":"channel","username":"channelname"}"#) - .unwrap(); + let actual = from_str(r#"{"id":-1,"type":"channel","username":"channelname"}"#).unwrap(); assert_eq!(expected, actual); } @@ -251,9 +229,9 @@ mod tests { }), photo: None, }, - from_str( - r#"{"id":0,"type":"private","username":"username","first_name":"Anon"}"# - ).unwrap()); + from_str(r#"{"id":0,"type":"private","username":"username","first_name":"Anon"}"#) + .unwrap() + ); } #[test] diff --git a/src/types/chat_id.rs b/src/types/chat_id.rs index ecb2ebd9..f4e57e98 100644 --- a/src/types/chat_id.rs +++ b/src/types/chat_id.rs @@ -3,9 +3,7 @@ use serde::{Deserialize, Serialize}; /// A unique identifier for the target chat or username of the target channel /// (in the format `@channelusername`). -#[derive( - Clone, Debug, Eq, Hash, PartialEq, Serialize, Deserialize, Display, From, -)] +#[derive(Clone, Debug, Eq, Hash, PartialEq, Serialize, Deserialize, Display, From)] #[serde(untagged)] pub enum ChatId { /// A chat identifier. @@ -32,10 +30,8 @@ mod tests { #[test] fn chat_id_channel_username_serialization() { let expected_json = String::from(r#""@username""#); - let actual_json = serde_json::to_string(&ChatId::ChannelUsername( - String::from("@username"), - )) - .unwrap(); + let actual_json = + serde_json::to_string(&ChatId::ChannelUsername(String::from("@username"))).unwrap(); assert_eq!(expected_json, actual_json) } diff --git a/src/types/encrypted_credentials.rs b/src/types/encrypted_credentials.rs index 7e467192..583821e7 100644 --- a/src/types/encrypted_credentials.rs +++ b/src/types/encrypted_credentials.rs @@ -51,8 +51,7 @@ mod tests { secret: "secret".to_string(), }; // when - let actual_json = - serde_json::to_string(&encrypted_credentials).unwrap(); + let actual_json = serde_json::to_string(&encrypted_credentials).unwrap(); //then assert_eq!(actual_json, expected_json) } diff --git a/src/types/inline_keyboard_button.rs b/src/types/inline_keyboard_button.rs index c6b3b039..296c07cd 100644 --- a/src/types/inline_keyboard_button.rs +++ b/src/types/inline_keyboard_button.rs @@ -79,35 +79,21 @@ pub enum InlineKeyboardButtonKind { /// ``` /// use teloxide::types::InlineKeyboardButton; /// -/// let url_button = InlineKeyboardButton::url( -/// "Text".to_string(), -/// "http://url.com".to_string(), -/// ); +/// let url_button = InlineKeyboardButton::url("Text".to_string(), "http://url.com".to_string()); /// ``` impl InlineKeyboardButton { pub fn url(text: String, url: String) -> InlineKeyboardButton { InlineKeyboardButton { text, kind: InlineKeyboardButtonKind::Url(url) } } - pub fn callback( - text: String, - callback_data: String, - ) -> InlineKeyboardButton { - InlineKeyboardButton { - text, - kind: InlineKeyboardButtonKind::CallbackData(callback_data), - } + pub fn callback(text: String, callback_data: String) -> InlineKeyboardButton { + InlineKeyboardButton { text, kind: InlineKeyboardButtonKind::CallbackData(callback_data) } } - pub fn switch_inline_query( - text: String, - switch_inline_query: String, - ) -> InlineKeyboardButton { + pub fn switch_inline_query(text: String, switch_inline_query: String) -> InlineKeyboardButton { InlineKeyboardButton { text, - kind: InlineKeyboardButtonKind::SwitchInlineQuery( - switch_inline_query, - ), + kind: InlineKeyboardButtonKind::SwitchInlineQuery(switch_inline_query), } } diff --git a/src/types/inline_keyboard_markup.rs b/src/types/inline_keyboard_markup.rs index 9511bc66..eeb73046 100644 --- a/src/types/inline_keyboard_markup.rs +++ b/src/types/inline_keyboard_markup.rs @@ -26,10 +26,7 @@ pub struct InlineKeyboardMarkup { /// ``` /// use teloxide::types::{InlineKeyboardButton, InlineKeyboardMarkup}; /// -/// let url_button = InlineKeyboardButton::url( -/// "text".to_string(), -/// "http://url.com".to_string(), -/// ); +/// let url_button = InlineKeyboardButton::url("text".to_string(), "http://url.com".to_string()); /// let keyboard = InlineKeyboardMarkup::default().append_row(vec![url_button]); /// ``` impl InlineKeyboardMarkup { @@ -38,11 +35,7 @@ impl InlineKeyboardMarkup { self } - pub fn append_to_row( - mut self, - button: InlineKeyboardButton, - index: usize, - ) -> Self { + pub fn append_to_row(mut self, button: InlineKeyboardButton, index: usize) -> Self { match self.inline_keyboard.get_mut(index) { Some(buttons) => buttons.push(button), None => self.inline_keyboard.push(vec![button]), @@ -57,65 +50,41 @@ mod tests { #[test] fn append_row() { - let button1 = InlineKeyboardButton::url( - "text 1".to_string(), - "url 1".to_string(), - ); - let button2 = InlineKeyboardButton::url( - "text 2".to_string(), - "url 2".to_string(), - ); + let button1 = InlineKeyboardButton::url("text 1".to_string(), "url 1".to_string()); + let button2 = InlineKeyboardButton::url("text 2".to_string(), "url 2".to_string()); - let markup = InlineKeyboardMarkup::default() - .append_row(vec![button1.clone(), button2.clone()]); + let markup = + InlineKeyboardMarkup::default().append_row(vec![button1.clone(), button2.clone()]); - let expected = InlineKeyboardMarkup { - inline_keyboard: vec![vec![button1, button2]], - }; + let expected = InlineKeyboardMarkup { inline_keyboard: vec![vec![button1, button2]] }; assert_eq!(markup, expected); } #[test] fn append_to_row_existent_row() { - let button1 = InlineKeyboardButton::url( - "text 1".to_string(), - "url 1".to_string(), - ); - let button2 = InlineKeyboardButton::url( - "text 2".to_string(), - "url 2".to_string(), - ); + let button1 = InlineKeyboardButton::url("text 1".to_string(), "url 1".to_string()); + let button2 = InlineKeyboardButton::url("text 2".to_string(), "url 2".to_string()); let markup = InlineKeyboardMarkup::default() .append_row(vec![button1.clone()]) .append_to_row(button2.clone(), 0); - let expected = InlineKeyboardMarkup { - inline_keyboard: vec![vec![button1, button2]], - }; + let expected = InlineKeyboardMarkup { inline_keyboard: vec![vec![button1, button2]] }; assert_eq!(markup, expected); } #[test] fn append_to_row_nonexistent_row() { - let button1 = InlineKeyboardButton::url( - "text 1".to_string(), - "url 1".to_string(), - ); - let button2 = InlineKeyboardButton::url( - "text 2".to_string(), - "url 2".to_string(), - ); + let button1 = InlineKeyboardButton::url("text 1".to_string(), "url 1".to_string()); + let button2 = InlineKeyboardButton::url("text 2".to_string(), "url 2".to_string()); let markup = InlineKeyboardMarkup::default() .append_row(vec![button1.clone()]) .append_to_row(button2.clone(), 1); - let expected = InlineKeyboardMarkup { - inline_keyboard: vec![vec![button1], vec![button2]], - }; + let expected = InlineKeyboardMarkup { inline_keyboard: vec![vec![button1], vec![button2]] }; assert_eq!(markup, expected); } diff --git a/src/types/inline_query_result.rs b/src/types/inline_query_result.rs index de3b28e8..e295bd15 100644 --- a/src/types/inline_query_result.rs +++ b/src/types/inline_query_result.rs @@ -4,15 +4,13 @@ use derive_more::From; use serde::{Deserialize, Serialize}; use crate::types::{ - InlineQueryResultArticle, InlineQueryResultAudio, - InlineQueryResultCachedAudio, InlineQueryResultCachedDocument, - InlineQueryResultCachedGif, InlineQueryResultCachedMpeg4Gif, - InlineQueryResultCachedPhoto, InlineQueryResultCachedSticker, - InlineQueryResultCachedVideo, InlineQueryResultCachedVoice, - InlineQueryResultContact, InlineQueryResultDocument, InlineQueryResultGame, - InlineQueryResultGif, InlineQueryResultLocation, InlineQueryResultMpeg4Gif, - InlineQueryResultPhoto, InlineQueryResultVenue, InlineQueryResultVideo, - InlineQueryResultVoice, + InlineQueryResultArticle, InlineQueryResultAudio, InlineQueryResultCachedAudio, + InlineQueryResultCachedDocument, InlineQueryResultCachedGif, InlineQueryResultCachedMpeg4Gif, + InlineQueryResultCachedPhoto, InlineQueryResultCachedSticker, InlineQueryResultCachedVideo, + InlineQueryResultCachedVoice, InlineQueryResultContact, InlineQueryResultDocument, + InlineQueryResultGame, InlineQueryResultGif, InlineQueryResultLocation, + InlineQueryResultMpeg4Gif, InlineQueryResultPhoto, InlineQueryResultVenue, + InlineQueryResultVideo, InlineQueryResultVoice, }; /// This object represents one result of an inline query. @@ -57,25 +55,22 @@ pub enum InlineQueryResult { #[cfg(test)] mod tests { use crate::types::{ - inline_keyboard_markup::InlineKeyboardMarkup, parse_mode::ParseMode, - InlineQueryResult, InlineQueryResultCachedAudio, InputMessageContent, - InputMessageContentText, + inline_keyboard_markup::InlineKeyboardMarkup, parse_mode::ParseMode, InlineQueryResult, + InlineQueryResultCachedAudio, InputMessageContent, InputMessageContentText, }; #[test] fn cached_audio_min_serialize() { - let structure = - InlineQueryResult::CachedAudio(InlineQueryResultCachedAudio { - id: String::from("id"), - audio_file_id: String::from("audio_file_id"), - caption: None, - parse_mode: None, - reply_markup: None, - input_message_content: None, - }); + let structure = InlineQueryResult::CachedAudio(InlineQueryResultCachedAudio { + id: String::from("id"), + audio_file_id: String::from("audio_file_id"), + caption: None, + parse_mode: None, + reply_markup: None, + input_message_content: None, + }); - let expected_json = - r#"{"type":"audio","id":"id","audio_file_id":"audio_file_id"}"#; + let expected_json = r#"{"type":"audio","id":"id","audio_file_id":"audio_file_id"}"#; let actual_json = serde_json::to_string(&structure).unwrap(); assert_eq!(expected_json, actual_json); @@ -83,21 +78,18 @@ mod tests { #[test] fn cached_audio_full_serialize() { - let structure = - InlineQueryResult::CachedAudio(InlineQueryResultCachedAudio { - id: String::from("id"), - audio_file_id: String::from("audio_file_id"), - caption: Some(String::from("caption")), - parse_mode: Some(ParseMode::HTML), - reply_markup: Some(InlineKeyboardMarkup::default()), - input_message_content: Some(InputMessageContent::Text( - InputMessageContentText { - message_text: String::from("message_text"), - parse_mode: Some(ParseMode::MarkdownV2), - disable_web_page_preview: Some(true), - }, - )), - }); + let structure = InlineQueryResult::CachedAudio(InlineQueryResultCachedAudio { + id: String::from("id"), + audio_file_id: String::from("audio_file_id"), + caption: Some(String::from("caption")), + parse_mode: Some(ParseMode::HTML), + reply_markup: Some(InlineKeyboardMarkup::default()), + input_message_content: Some(InputMessageContent::Text(InputMessageContentText { + message_text: String::from("message_text"), + parse_mode: Some(ParseMode::MarkdownV2), + disable_web_page_preview: Some(true), + })), + }); let expected_json = r#"{"type":"audio","id":"id","audio_file_id":"audio_file_id","caption":"caption","parse_mode":"HTML","reply_markup":{"inline_keyboard":[]},"input_message_content":{"message_text":"message_text","parse_mode":"MarkdownV2","disable_web_page_preview":true}}"#; let actual_json = serde_json::to_string(&structure).unwrap(); diff --git a/src/types/inline_query_result_document.rs b/src/types/inline_query_result_document.rs index f5a328b7..d4a4462d 100644 --- a/src/types/inline_query_result_document.rs +++ b/src/types/inline_query_result_document.rs @@ -1,8 +1,6 @@ use serde::{Deserialize, Serialize}; -use crate::types::{ - InlineKeyboardMarkup, InputMessageContent, MimeWrapper, ParseMode, -}; +use crate::types::{InlineKeyboardMarkup, InputMessageContent, MimeWrapper, ParseMode}; /// Represents a link to a file. /// diff --git a/src/types/inline_query_result_video.rs b/src/types/inline_query_result_video.rs index 6550df89..28d443c9 100644 --- a/src/types/inline_query_result_video.rs +++ b/src/types/inline_query_result_video.rs @@ -1,8 +1,6 @@ use serde::{Deserialize, Serialize}; -use crate::types::{ - InlineKeyboardMarkup, InputMessageContent, MimeWrapper, ParseMode, -}; +use crate::types::{InlineKeyboardMarkup, InputMessageContent, MimeWrapper, ParseMode}; /// Represents a link to a page containing an embedded video player or a video /// file. diff --git a/src/types/input_file.rs b/src/types/input_file.rs index 83b7fe9c..6c948f4b 100644 --- a/src/types/input_file.rs +++ b/src/types/input_file.rs @@ -85,19 +85,13 @@ impl Serialize for InputFile { // multipart/form-data serializer.serialize_str( // TODO: remove unwrap (?) - &format!( - "attach://{}", - path.file_name().unwrap().to_string_lossy() - ), + &format!("attach://{}", path.file_name().unwrap().to_string_lossy()), ) } InputFile::Memory { data, .. } => { // NOTE: file should be actually attached with // multipart/form-data - serializer.serialize_str(&format!( - "attach://{}", - String::from_utf8_lossy(data) - )) + serializer.serialize_str(&format!("attach://{}", String::from_utf8_lossy(data))) } InputFile::Url(url) => serializer.serialize_str(url), InputFile::FileId(id) => serializer.serialize_str(id), diff --git a/src/types/input_message_content.rs b/src/types/input_message_content.rs index 79444de4..633beb9c 100644 --- a/src/types/input_message_content.rs +++ b/src/types/input_message_content.rs @@ -118,12 +118,11 @@ mod tests { #[test] fn location_serialize() { let expected_json = r#"{"latitude":59.08,"longitude":38.4326}"#; - let location_content = - InputMessageContent::Location(InputMessageContentLocation { - latitude: 59.08, - longitude: 38.4326, - live_period: None, - }); + let location_content = InputMessageContent::Location(InputMessageContentLocation { + latitude: 59.08, + longitude: 38.4326, + live_period: None, + }); let actual_json = serde_json::to_string(&location_content).unwrap(); assert_eq!(expected_json, actual_json); @@ -132,15 +131,14 @@ mod tests { #[test] fn venue_serialize() { let expected_json = r#"{"latitude":59.08,"longitude":38.4326,"title":"some title","address":"some address"}"#; - let venue_content = - InputMessageContent::Venue(InputMessageContentVenue { - latitude: 59.08, - longitude: 38.4326, - title: String::from("some title"), - address: String::from("some address"), - foursquare_id: None, - foursquare_type: None, - }); + let venue_content = InputMessageContent::Venue(InputMessageContentVenue { + latitude: 59.08, + longitude: 38.4326, + title: String::from("some title"), + address: String::from("some address"), + foursquare_id: None, + foursquare_type: None, + }); let actual_json = serde_json::to_string(&venue_content).unwrap(); assert_eq!(expected_json, actual_json); @@ -148,15 +146,13 @@ mod tests { #[test] fn contact_serialize() { - let expected_json = - r#"{"phone_number":"+3800000000","first_name":"jhon"}"#; - let contact_content = - InputMessageContent::Contact(InputMessageContentContact { - phone_number: String::from("+3800000000"), - first_name: String::from("jhon"), - last_name: None, - vcard: None, - }); + let expected_json = r#"{"phone_number":"+3800000000","first_name":"jhon"}"#; + let contact_content = InputMessageContent::Contact(InputMessageContentContact { + phone_number: String::from("+3800000000"), + first_name: String::from("jhon"), + last_name: None, + vcard: None, + }); let actual_json = serde_json::to_string(&contact_content).unwrap(); assert_eq!(expected_json, actual_json); diff --git a/src/types/keyboard_button.rs b/src/types/keyboard_button.rs index 240a36c5..4c964bdd 100644 --- a/src/types/keyboard_button.rs +++ b/src/types/keyboard_button.rs @@ -18,8 +18,8 @@ pub struct KeyboardButton { /// Request something from user. /// - If `Some(Contact)`, the user's phone number will be sent as a contact /// when the button is pressed. Available in private chats only - /// - If `Some(Location)`, the user's current location will be sent when - /// the button is pressed. Available in private chats only + /// - If `Some(Location)`, the user's current location will be sent when the + /// button is pressed. Available in private chats only #[serde(flatten)] pub request: Option, } @@ -79,22 +79,17 @@ impl<'de> Deserialize<'de> for ButtonRequest { { let raw = RawRequest::deserialize(deserializer)?; match raw { - RawRequest { - contact: Some(_), - location: Some(_), - poll: Some(_), - } => Err(D::Error::custom( - "`request_contact` and `request_location` fields are mutually \ - exclusive, but both were provided", - )), + RawRequest { contact: Some(_), location: Some(_), poll: Some(_) } => { + Err(D::Error::custom( + "`request_contact` and `request_location` fields are mutually exclusive, but \ + both were provided", + )) + } RawRequest { contact: Some(_), .. } => Ok(Self::Contact), RawRequest { location: Some(_), .. } => Ok(Self::Location), - RawRequest { poll: Some(poll_type), .. } => { - Ok(Self::KeyboardButtonPollType(poll_type)) - } + RawRequest { poll: Some(poll_type), .. } => Ok(Self::KeyboardButtonPollType(poll_type)), _ => Err(D::Error::custom( - "Either one of `request_contact` and `request_location` \ - fields is required", + "Either one of `request_contact` and `request_location` fields is required", )), } } @@ -107,19 +102,15 @@ impl Serialize for ButtonRequest { { match self { Self::Contact => { - RawRequest { contact: Some(True), location: None, poll: None } - .serialize(serializer) + RawRequest { contact: Some(True), location: None, poll: None }.serialize(serializer) } Self::Location => { - RawRequest { contact: None, location: Some(True), poll: None } + RawRequest { contact: None, location: Some(True), poll: None }.serialize(serializer) + } + Self::KeyboardButtonPollType(poll_type) => { + RawRequest { contact: None, location: None, poll: Some(poll_type.clone()) } .serialize(serializer) } - Self::KeyboardButtonPollType(poll_type) => RawRequest { - contact: None, - location: None, - poll: Some(poll_type.clone()), - } - .serialize(serializer), } } } @@ -138,10 +129,8 @@ mod tests { #[test] fn serialize_request_contact() { - let button = KeyboardButton { - text: String::from(""), - request: Some(ButtonRequest::Contact), - }; + let button = + KeyboardButton { text: String::from(""), request: Some(ButtonRequest::Contact) }; let expected = r#"{"text":"","request_contact":true}"#; let actual = serde_json::to_string(&button).unwrap(); assert_eq!(expected, actual); @@ -158,10 +147,8 @@ mod tests { #[test] fn deserialize_request_contact() { let json = r#"{"text":"","request_contact":true}"#; - let expected = KeyboardButton { - text: String::from(""), - request: Some(ButtonRequest::Contact), - }; + let expected = + KeyboardButton { text: String::from(""), request: Some(ButtonRequest::Contact) }; let actual = serde_json::from_str(json).unwrap(); assert_eq!(expected, actual); } diff --git a/src/types/label_price.rs b/src/types/label_price.rs index 0a418cf6..da2fa5f2 100644 --- a/src/types/label_price.rs +++ b/src/types/label_price.rs @@ -25,8 +25,7 @@ mod tests { #[test] fn serialize() { - let labeled_price = - LabeledPrice { label: "Label".to_string(), amount: 60 }; + let labeled_price = LabeledPrice { label: "Label".to_string(), amount: 60 }; let expected = r#"{"label":"Label","amount":60}"#; let actual = serde_json::to_string(&labeled_price).unwrap(); assert_eq!(actual, expected); diff --git a/src/types/message.rs b/src/types/message.rs index 774f2784..bed3ef8d 100644 --- a/src/types/message.rs +++ b/src/types/message.rs @@ -4,10 +4,9 @@ use serde::{Deserialize, Serialize}; use crate::types::{ chat::{ChatKind, PublicChatKind}, - Animation, Audio, Chat, ChatPublic, Contact, Document, Game, - InlineKeyboardMarkup, Invoice, Location, MessageEntity, PassportData, - PhotoSize, Poll, PublicChatChannel, PublicChatSupergroup, Sticker, - SuccessfulPayment, True, User, Venue, Video, VideoNote, Voice, + Animation, Audio, Chat, ChatPublic, Contact, Document, Game, InlineKeyboardMarkup, Invoice, + Location, MessageEntity, PassportData, PhotoSize, Poll, PublicChatChannel, + PublicChatSupergroup, Sticker, SuccessfulPayment, True, User, Venue, Video, VideoNote, Voice, }; /// This object represents a message. @@ -425,23 +424,19 @@ mod getters { message::{ ForwardKind::NonChannel, MessageKind::{ - ChannelChatCreated, Common, ConnectedWebsite, DeleteChatPhoto, - GroupChatCreated, Invoice, LeftChatMember, Migrate, - NewChatMembers, NewChatPhoto, NewChatTitle, PassportData, - Pinned, SuccessfulPayment, SupergroupChatCreated, + ChannelChatCreated, Common, ConnectedWebsite, DeleteChatPhoto, GroupChatCreated, + Invoice, LeftChatMember, Migrate, NewChatMembers, NewChatPhoto, NewChatTitle, + PassportData, Pinned, SuccessfulPayment, SupergroupChatCreated, }, }, - Chat, ForwardChannel, ForwardKind, ForwardNonChannel, ForwardOrigin, - ForwardedFrom, MediaAnimation, MediaAudio, MediaContact, MediaDocument, - MediaGame, MediaKind, MediaLocation, MediaPhoto, MediaPoll, - MediaSticker, MediaText, MediaVenue, MediaVideo, MediaVideoNote, - MediaVoice, Message, MessageChannelChatCreated, MessageCommon, - MessageConnectedWebsite, MessageDeleteChatPhoto, MessageEntity, - MessageGroupChatCreated, MessageInvoice, MessageLeftChatMember, - MessageMigrate, MessageNewChatMembers, MessageNewChatPhoto, - MessageNewChatTitle, MessagePassportData, MessagePinned, - MessageSuccessfulPayment, MessageSupergroupChatCreated, PhotoSize, - True, User, + Chat, ForwardChannel, ForwardKind, ForwardNonChannel, ForwardOrigin, ForwardedFrom, + MediaAnimation, MediaAudio, MediaContact, MediaDocument, MediaGame, MediaKind, + MediaLocation, MediaPhoto, MediaPoll, MediaSticker, MediaText, MediaVenue, MediaVideo, + MediaVideoNote, MediaVoice, Message, MessageChannelChatCreated, MessageCommon, + MessageConnectedWebsite, MessageDeleteChatPhoto, MessageEntity, MessageGroupChatCreated, + MessageInvoice, MessageLeftChatMember, MessageMigrate, MessageNewChatMembers, + MessageNewChatPhoto, MessageNewChatTitle, MessagePassportData, MessagePinned, + MessageSuccessfulPayment, MessageSupergroupChatCreated, PhotoSize, True, User, }; /// Getters for [Message] fields from [telegram docs]. @@ -476,8 +471,7 @@ mod getters { pub fn forward_from_chat(&self) -> Option<&Chat> { match &self.kind { Common(MessageCommon { - forward_kind: - ForwardKind::Channel(ForwardChannel { chat, .. }), + forward_kind: ForwardKind::Channel(ForwardChannel { chat, .. }), .. }) => Some(chat), _ => None, @@ -487,8 +481,7 @@ mod getters { pub fn forward_from_message_id(&self) -> Option<&i32> { match &self.kind { Common(MessageCommon { - forward_kind: - ForwardKind::Channel(ForwardChannel { message_id, .. }), + forward_kind: ForwardKind::Channel(ForwardChannel { message_id, .. }), .. }) => Some(message_id), _ => None, @@ -498,8 +491,7 @@ mod getters { pub fn forward_signature(&self) -> Option<&str> { match &self.kind { Common(MessageCommon { - forward_kind: - ForwardKind::Channel(ForwardChannel { signature, .. }), + forward_kind: ForwardKind::Channel(ForwardChannel { signature, .. }), .. }) => signature.as_ref().map(Deref::deref), _ => None, @@ -509,13 +501,11 @@ mod getters { pub fn forward_date(&self) -> Option<&i32> { match &self.kind { Common(MessageCommon { - forward_kind: - ForwardKind::Channel(ForwardChannel { date, .. }), + forward_kind: ForwardKind::Channel(ForwardChannel { date, .. }), .. }) | Common(MessageCommon { - forward_kind: - ForwardKind::NonChannel(ForwardNonChannel { date, .. }), + forward_kind: ForwardKind::NonChannel(ForwardNonChannel { date, .. }), .. }) => Some(date), _ => None, @@ -525,10 +515,7 @@ mod getters { pub fn reply_to_message(&self) -> Option<&Message> { match &self.kind { Common(MessageCommon { - forward_kind: - ForwardKind::Origin(ForwardOrigin { - reply_to_message, .. - }), + forward_kind: ForwardKind::Origin(ForwardOrigin { reply_to_message, .. }), .. }) => reply_to_message.as_ref().map(Deref::deref), _ => None, @@ -545,13 +532,11 @@ mod getters { pub fn media_group_id(&self) -> Option<&str> { match &self.kind { Common(MessageCommon { - media_kind: - MediaKind::Video(MediaVideo { media_group_id, .. }), + media_kind: MediaKind::Video(MediaVideo { media_group_id, .. }), .. }) | Common(MessageCommon { - media_kind: - MediaKind::Photo(MediaPhoto { media_group_id, .. }), + media_kind: MediaKind::Photo(MediaPhoto { media_group_id, .. }), .. }) => media_group_id.as_ref().map(Deref::deref), _ => None, @@ -585,38 +570,27 @@ mod getters { pub fn caption_entities(&self) -> Option<&[MessageEntity]> { match &self.kind { Common(MessageCommon { - media_kind: - MediaKind::Animation(MediaAnimation { - caption_entities, - .. - }), + media_kind: MediaKind::Animation(MediaAnimation { caption_entities, .. }), .. }) | Common(MessageCommon { - media_kind: - MediaKind::Audio(MediaAudio { caption_entities, .. }), + media_kind: MediaKind::Audio(MediaAudio { caption_entities, .. }), .. }) | Common(MessageCommon { - media_kind: - MediaKind::Document(MediaDocument { - caption_entities, .. - }), + media_kind: MediaKind::Document(MediaDocument { caption_entities, .. }), .. }) | Common(MessageCommon { - media_kind: - MediaKind::Photo(MediaPhoto { caption_entities, .. }), + media_kind: MediaKind::Photo(MediaPhoto { caption_entities, .. }), .. }) | Common(MessageCommon { - media_kind: - MediaKind::Video(MediaVideo { caption_entities, .. }), + media_kind: MediaKind::Video(MediaVideo { caption_entities, .. }), .. }) | Common(MessageCommon { - media_kind: - MediaKind::Voice(MediaVoice { caption_entities, .. }), + media_kind: MediaKind::Voice(MediaVoice { caption_entities, .. }), .. }) => Some(caption_entities), _ => None, @@ -636,8 +610,7 @@ mod getters { pub fn document(&self) -> Option<&types::Document> { match &self.kind { Common(MessageCommon { - media_kind: - MediaKind::Document(MediaDocument { document, .. }), + media_kind: MediaKind::Document(MediaDocument { document, .. }), .. }) => Some(document), _ => None, @@ -647,8 +620,7 @@ mod getters { pub fn animation(&self) -> Option<&types::Animation> { match &self.kind { Common(MessageCommon { - media_kind: - MediaKind::Animation(MediaAnimation { animation, .. }), + media_kind: MediaKind::Animation(MediaAnimation { animation, .. }), .. }) => Some(animation), _ => None, @@ -708,8 +680,7 @@ mod getters { pub fn video_note(&self) -> Option<&types::VideoNote> { match &self.kind { Common(MessageCommon { - media_kind: - MediaKind::VideoNote(MediaVideoNote { video_note, .. }), + media_kind: MediaKind::VideoNote(MediaVideoNote { video_note, .. }), .. }) => Some(video_note), _ => None, @@ -719,9 +690,7 @@ mod getters { pub fn caption(&self) -> Option<&str> { match &self.kind { Common(MessageCommon { media_kind, .. }) => match media_kind { - MediaKind::Animation(MediaAnimation { - caption, .. - }) + MediaKind::Animation(MediaAnimation { caption, .. }) | MediaKind::Audio(MediaAudio { caption, .. }) | MediaKind::Document(MediaDocument { caption, .. }) | MediaKind::Photo(MediaPhoto { caption, .. }) @@ -748,8 +717,7 @@ mod getters { pub fn location(&self) -> Option<&types::Location> { match &self.kind { Common(MessageCommon { - media_kind: - MediaKind::Location(MediaLocation { location, .. }), + media_kind: MediaKind::Location(MediaLocation { location, .. }), .. }) => Some(location), _ => None, @@ -796,18 +764,14 @@ mod getters { pub fn new_chat_title(&self) -> Option<&str> { match &self.kind { - NewChatTitle(MessageNewChatTitle { new_chat_title }) => { - Some(new_chat_title) - } + NewChatTitle(MessageNewChatTitle { new_chat_title }) => Some(new_chat_title), _ => None, } } pub fn new_chat_photo(&self) -> Option<&[PhotoSize]> { match &self.kind { - NewChatPhoto(MessageNewChatPhoto { new_chat_photo }) => { - Some(new_chat_photo) - } + NewChatPhoto(MessageNewChatPhoto { new_chat_photo }) => Some(new_chat_photo), _ => None, } } @@ -816,54 +780,50 @@ mod getters { // mb smt like `is_delete_chat_photo(&self) -> bool`? pub fn delete_chat_photo(&self) -> Option { match &self.kind { - DeleteChatPhoto(MessageDeleteChatPhoto { - delete_chat_photo, - }) => Some(*delete_chat_photo), + DeleteChatPhoto(MessageDeleteChatPhoto { delete_chat_photo }) => { + Some(*delete_chat_photo) + } _ => None, } } pub fn group_chat_created(&self) -> Option { match &self.kind { - GroupChatCreated(MessageGroupChatCreated { - group_chat_created, - }) => Some(*group_chat_created), + GroupChatCreated(MessageGroupChatCreated { group_chat_created }) => { + Some(*group_chat_created) + } _ => None, } } pub fn super_group_chat_created(&self) -> Option { match &self.kind { - SupergroupChatCreated(MessageSupergroupChatCreated { - supergroup_chat_created, - }) => Some(*supergroup_chat_created), + SupergroupChatCreated(MessageSupergroupChatCreated { supergroup_chat_created }) => { + Some(*supergroup_chat_created) + } _ => None, } } pub fn channel_chat_created(&self) -> Option { match &self.kind { - ChannelChatCreated(MessageChannelChatCreated { - channel_chat_created, - }) => Some(*channel_chat_created), + ChannelChatCreated(MessageChannelChatCreated { channel_chat_created }) => { + Some(*channel_chat_created) + } _ => None, } } pub fn migrate_to_chat_id(&self) -> Option { match &self.kind { - Migrate(MessageMigrate { migrate_to_chat_id, .. }) => { - Some(*migrate_to_chat_id) - } + Migrate(MessageMigrate { migrate_to_chat_id, .. }) => Some(*migrate_to_chat_id), _ => None, } } pub fn migrate_from_chat_id(&self) -> Option { match &self.kind { - Migrate(MessageMigrate { migrate_from_chat_id, .. }) => { - Some(*migrate_from_chat_id) - } + Migrate(MessageMigrate { migrate_from_chat_id, .. }) => Some(*migrate_from_chat_id), _ => None, } } @@ -884,36 +844,32 @@ mod getters { pub fn successful_payment(&self) -> Option<&types::SuccessfulPayment> { match &self.kind { - SuccessfulPayment(MessageSuccessfulPayment { - successful_payment, - }) => Some(successful_payment), + SuccessfulPayment(MessageSuccessfulPayment { successful_payment }) => { + Some(successful_payment) + } _ => None, } } pub fn connected_website(&self) -> Option<&str> { match &self.kind { - ConnectedWebsite(MessageConnectedWebsite { - connected_website, - }) => Some(connected_website), + ConnectedWebsite(MessageConnectedWebsite { connected_website }) => { + Some(connected_website) + } _ => None, } } pub fn passport_data(&self) -> Option<&types::PassportData> { match &self.kind { - PassportData(MessagePassportData { passport_data }) => { - Some(passport_data) - } + PassportData(MessagePassportData { passport_data }) => Some(passport_data), _ => None, } } pub fn reply_markup(&self) -> Option<&types::InlineKeyboardMarkup> { match &self.kind { - Common(MessageCommon { reply_markup, .. }) => { - reply_markup.as_ref() - } + Common(MessageCommon { reply_markup, .. }) => reply_markup.as_ref(), _ => None, } } @@ -924,25 +880,18 @@ impl Message { pub fn url(&self) -> Option { match &self.chat.kind { ChatKind::Public(ChatPublic { - kind: - PublicChatKind::Channel(PublicChatChannel { - username: Some(username), - }), + kind: PublicChatKind::Channel(PublicChatChannel { username: Some(username) }), .. }) | ChatKind::Public(ChatPublic { kind: PublicChatKind::Supergroup(PublicChatSupergroup { - username: Some(username), - .. + username: Some(username), .. }), .. }) => Some( - reqwest::Url::parse( - format!("https://t.me/{0}/{1}/", username, self.id) - .as_str(), - ) - .unwrap(), + reqwest::Url::parse(format!("https://t.me/{0}/{1}/", username, self.id).as_str()) + .unwrap(), ), _ => None, } diff --git a/src/types/message_entity.rs b/src/types/message_entity.rs index 39cc32b9..7d8458fd 100644 --- a/src/types/message_entity.rs +++ b/src/types/message_entity.rs @@ -51,8 +51,8 @@ impl MessageEntity { mod tests { use super::*; use crate::types::{ - Chat, ChatKind, ChatPrivate, ForwardKind, ForwardOrigin, MediaKind, - MediaText, MessageCommon, MessageKind, + Chat, ChatKind, ChatPrivate, ForwardKind, ForwardOrigin, MediaKind, MediaText, + MessageCommon, MessageKind, }; #[test] @@ -78,9 +78,7 @@ mod tests { assert_eq!( MessageEntity { - kind: MessageEntityKind::Pre { - language: Some("rust".to_string()), - }, + kind: MessageEntityKind::Pre { language: Some("rust".to_string()) }, offset: 1, length: 2, }, @@ -123,9 +121,7 @@ mod tests { username: None, language_code: None, }), - forward_kind: ForwardKind::Origin(ForwardOrigin { - reply_to_message: None, - }), + forward_kind: ForwardKind::Origin(ForwardOrigin { reply_to_message: None }), edit_date: None, media_kind: MediaKind::Text(MediaText { text: "no yes no".to_string(), diff --git a/src/types/non_telegram_types/mime_wrapper.rs b/src/types/non_telegram_types/mime_wrapper.rs index d45a2dfb..43326de6 100644 --- a/src/types/non_telegram_types/mime_wrapper.rs +++ b/src/types/non_telegram_types/mime_wrapper.rs @@ -1,19 +1,13 @@ use derive_more::From; use mime::Mime; -use serde::{ - de::Visitor, export::Formatter, Deserialize, Deserializer, Serialize, - Serializer, -}; +use serde::{de::Visitor, export::Formatter, Deserialize, Deserializer, Serialize, Serializer}; /// Serializable & deserializable `MIME` wrapper. #[derive(Clone, Debug, Eq, Hash, PartialEq, From)] pub struct MimeWrapper(pub Mime); impl Serialize for MimeWrapper { - fn serialize( - &self, - serializer: S, - ) -> Result<::Ok, ::Error> + fn serialize(&self, serializer: S) -> Result<::Ok, ::Error> where S: Serializer, { @@ -25,10 +19,7 @@ struct MimeVisitor; impl<'a> Visitor<'a> for MimeVisitor { type Value = MimeWrapper; - fn expecting( - &self, - formatter: &mut Formatter<'_>, - ) -> Result<(), serde::export::fmt::Error> { + fn expecting(&self, formatter: &mut Formatter<'_>) -> Result<(), serde::export::fmt::Error> { formatter.write_str("mime type") } @@ -44,9 +35,7 @@ impl<'a> Visitor<'a> for MimeVisitor { } impl<'de> Deserialize<'de> for MimeWrapper { - fn deserialize( - deserializer: D, - ) -> Result>::Error> + fn deserialize(deserializer: D) -> Result>::Error> where D: Deserializer<'de>, { diff --git a/src/types/parse_mode.rs b/src/types/parse_mode.rs index 862c7c02..989b2f24 100644 --- a/src/types/parse_mode.rs +++ b/src/types/parse_mode.rs @@ -129,8 +129,8 @@ use serde::{Deserialize, Serialize}; pub enum ParseMode { MarkdownV2, HTML, - #[deprecated = "This is a legacy mode, retained for backward \ - compatibility. Use `MarkdownV2` instead."] + #[deprecated = "This is a legacy mode, retained for backward compatibility. Use `MarkdownV2` \ + instead."] Markdown, } diff --git a/src/types/passport_element_error.rs b/src/types/passport_element_error.rs index dde19903..ed453eb1 100644 --- a/src/types/passport_element_error.rs +++ b/src/types/passport_element_error.rs @@ -291,13 +291,11 @@ mod tests { fn serialize_data_field() { let data = PassportElementError { message: "This is an error message!".to_owned(), - kind: PassportElementErrorKind::DataField( - PassportElementErrorDataField { - r#type: PassportElementErrorDataFieldType::InternalPassport, - field_name: "The field name".to_owned(), - data_hash: "This is a data hash".to_owned(), - }, - ), + kind: PassportElementErrorKind::DataField(PassportElementErrorDataField { + r#type: PassportElementErrorDataFieldType::InternalPassport, + field_name: "The field name".to_owned(), + data_hash: "This is a data hash".to_owned(), + }), }; assert_eq!( diff --git a/src/types/reply_keyboard_markup.rs b/src/types/reply_keyboard_markup.rs index 59707764..aea63b73 100644 --- a/src/types/reply_keyboard_markup.rs +++ b/src/types/reply_keyboard_markup.rs @@ -50,11 +50,7 @@ impl ReplyKeyboardMarkup { self } - pub fn append_to_row( - mut self, - button: KeyboardButton, - index: usize, - ) -> Self { + pub fn append_to_row(mut self, button: KeyboardButton, index: usize) -> Self { match self.keyboard.get_mut(index) { Some(buttons) => buttons.push(button), None => self.keyboard.push(vec![button]), diff --git a/src/types/reply_markup.rs b/src/types/reply_markup.rs index f69245e6..5f0afbbe 100644 --- a/src/types/reply_markup.rs +++ b/src/types/reply_markup.rs @@ -1,9 +1,7 @@ use derive_more::From; use serde::{Deserialize, Serialize}; -use crate::types::{ - ForceReply, InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, -}; +use crate::types::{ForceReply, InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove}; #[derive(Clone, Debug, Eq, Hash, PartialEq, Serialize, Deserialize, From)] #[serde(untagged)] diff --git a/src/types/response_parameters.rs b/src/types/response_parameters.rs index ee8cc2d7..c69ce9e0 100644 --- a/src/types/response_parameters.rs +++ b/src/types/response_parameters.rs @@ -35,8 +35,7 @@ mod tests { #[test] fn retry_after_deserialization() { let expected = ResponseParameters::RetryAfter(123_456); - let actual: ResponseParameters = - serde_json::from_str(r#"{"retry_after":123456}"#).unwrap(); + let actual: ResponseParameters = serde_json::from_str(r#"{"retry_after":123456}"#).unwrap(); assert_eq!(expected, actual); } diff --git a/src/types/shipping_option.rs b/src/types/shipping_option.rs index aa5115dd..a915522b 100644 --- a/src/types/shipping_option.rs +++ b/src/types/shipping_option.rs @@ -26,10 +26,7 @@ mod tests { let shipping_option = ShippingOption { id: "0".to_string(), title: "Option".to_string(), - prices: vec![LabeledPrice { - label: "Label".to_string(), - amount: 60, - }], + prices: vec![LabeledPrice { label: "Label".to_string(), amount: 60 }], }; let expected = r#"{"id":"0","title":"Option","prices":[{"label":"Label","amount":60}]}"#; let actual = serde_json::to_string(&shipping_option).unwrap(); diff --git a/src/types/unit_false.rs b/src/types/unit_false.rs index 058758f9..bde6410b 100644 --- a/src/types/unit_false.rs +++ b/src/types/unit_false.rs @@ -29,10 +29,7 @@ struct FalseVisitor; impl<'de> Visitor<'de> for FalseVisitor { type Value = False; - fn expecting( - &self, - formatter: &mut std::fmt::Formatter, - ) -> std::fmt::Result { + fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { write!(formatter, "bool, equal to `false`") } diff --git a/src/types/update.rs b/src/types/update.rs index 9f0b0f5f..e992c216 100644 --- a/src/types/update.rs +++ b/src/types/update.rs @@ -3,8 +3,8 @@ use serde::{Deserialize, Serialize}; use crate::types::{ - CallbackQuery, Chat, ChosenInlineResult, InlineQuery, Message, Poll, - PollAnswer, PreCheckoutQuery, ShippingQuery, User, + CallbackQuery, Chat, ChosenInlineResult, InlineQuery, Message, Poll, PollAnswer, + PreCheckoutQuery, ShippingQuery, User, }; use serde_json::Value; @@ -129,9 +129,8 @@ impl Update { #[cfg(test)] mod test { use crate::types::{ - Chat, ChatKind, ChatPrivate, ForwardKind, ForwardOrigin, MediaKind, - MediaText, Message, MessageCommon, MessageKind, Update, UpdateKind, - User, + Chat, ChatKind, ChatPrivate, ForwardKind, ForwardOrigin, MediaKind, MediaText, Message, + MessageCommon, MessageKind, Update, UpdateKind, User, }; // TODO: more tests for deserialization @@ -183,9 +182,7 @@ mod test { username: Some(String::from("WaffleLapkin")), language_code: Some(String::from("en")), }), - forward_kind: ForwardKind::Origin(ForwardOrigin { - reply_to_message: None, - }), + forward_kind: ForwardKind::Origin(ForwardOrigin { reply_to_message: None }), edit_date: None, media_kind: MediaKind::Text(MediaText { text: String::from("hello there"), diff --git a/src/types/user.rs b/src/types/user.rs index 1ebac900..55d2eb48 100644 --- a/src/types/user.rs +++ b/src/types/user.rs @@ -40,8 +40,7 @@ impl User { } pub fn url(&self) -> reqwest::Url { - reqwest::Url::parse(format!("tg://user/?id={}", self.id).as_str()) - .unwrap() + reqwest::Url::parse(format!("tg://user/?id={}", self.id).as_str()).unwrap() } } diff --git a/src/utils/client_from_env.rs b/src/utils/client_from_env.rs index 373b9979..7c5c7b06 100644 --- a/src/utils/client_from_env.rs +++ b/src/utils/client_from_env.rs @@ -16,8 +16,9 @@ pub fn client_from_env() -> reqwest::Client { use reqwest::{Client, Proxy}; match std::env::var("TELOXIDE_PROXY").ok() { - Some(proxy) => Client::builder() - .proxy(Proxy::all(&proxy).expect("creating reqwest::Proxy")), + Some(proxy) => { + Client::builder().proxy(Proxy::all(&proxy).expect("creating reqwest::Proxy")) + } None => sound_bot(), } .build() diff --git a/src/utils/command.rs b/src/utils/command.rs index 1519185c..ff5c9023 100644 --- a/src/utils/command.rs +++ b/src/utils/command.rs @@ -25,8 +25,7 @@ //! ``` //! use teloxide::utils::command::parse_command; //! -//! let (command, args) = -//! parse_command("/ban@MyBotName 3 hours", "MyBotName").unwrap(); +//! let (command, args) = parse_command("/ban@MyBotName 3 hours", "MyBotName").unwrap(); //! assert_eq!(command, "ban"); //! assert_eq!(args, vec!["3", "hours"]); //! ``` @@ -155,14 +154,10 @@ pub use teloxide_macros::BotCommand; /// fn accept_two_digits(input: String) -> Result<(u8,), ParseError> { /// match input.len() { /// 2 => { -/// let num = input -/// .parse::() -/// .map_err(|e| ParseError::IncorrectFormat(e.into()))?; +/// let num = input.parse::().map_err(|e| ParseError::IncorrectFormat(e.into()))?; /// Ok((num,)) /// } -/// len => Err(ParseError::Custom( -/// format!("Only 2 digits allowed, not {}", len).into(), -/// )), +/// len => Err(ParseError::Custom(format!("Only 2 digits allowed, not {}", len).into())), /// } /// } /// @@ -233,20 +228,13 @@ impl Display for ParseError { "Too few arguments (expected {}, found {}, message = '{}')", expected, found, message ), - ParseError::TooManyArguments { expected, found, message } => { - write!( - f, - "Too many arguments (expected {}, found {}, message = \ - '{}')", - expected, found, message - ) - } - ParseError::IncorrectFormat(e) => { - write!(f, "Incorrect format of command args: {}", e) - } - ParseError::UnknownCommand(e) => { - write!(f, "Unknown command: {}", e) - } + ParseError::TooManyArguments { expected, found, message } => write!( + f, + "Too many arguments (expected {}, found {}, message = '{}')", + expected, found, message + ), + ParseError::IncorrectFormat(e) => write!(f, "Incorrect format of command args: {}", e), + ParseError::UnknownCommand(e) => write!(f, "Unknown command: {}", e), ParseError::WrongBotName(n) => write!(f, "Wrong bot name: {}", n), ParseError::Custom(e) => write!(f, "{}", e), } @@ -305,8 +293,7 @@ where /// ``` /// use teloxide::utils::command::parse_command_with_prefix; /// -/// let result = -/// parse_command_with_prefix("!", "!ban@MyNameBot1 3 hours", "MyNameBot2"); +/// let result = parse_command_with_prefix("!", "!ban@MyNameBot1 3 hours", "MyNameBot2"); /// assert!(result.is_none()); /// ``` pub fn parse_command_with_prefix<'a, N>( diff --git a/src/utils/html.rs b/src/utils/html.rs index 61391900..71c7bec9 100644 --- a/src/utils/html.rs +++ b/src/utils/html.rs @@ -127,8 +127,7 @@ mod tests { fn test_link() { assert_eq!( link("https://www.google.com/?q=foo&l=ru", ""), - "<google>\ - ", + "<google>", ); } @@ -144,8 +143,7 @@ mod tests { fn test_code_block() { assert_eq!( code_block("

pre-'formatted'\n & fixed-width \\code `block`

"), - "
<p>pre-'formatted'\n & fixed-width \\code \
-             `block`</p>
" + "
<p>pre-'formatted'\n & fixed-width \\code `block`</p>
" ); } @@ -158,8 +156,7 @@ mod tests { ), concat!( "
",
-                "<p>pre-'formatted'\n & fixed-width \\code \
-                 `block`</p>",
+                "<p>pre-'formatted'\n & fixed-width \\code `block`</p>",
                 "
", ) ); @@ -179,10 +176,7 @@ mod tests { escape(" Foo & Bar "), " <title>Foo & Bar</title> " ); - assert_eq!( - escape("

你好 & 再見

"), - "<p>你好 & 再見</p>" - ); + assert_eq!(escape("

你好 & 再見

"), "<p>你好 & 再見</p>"); assert_eq!(escape("'foo\""), "'foo\""); } diff --git a/src/utils/markdown.rs b/src/utils/markdown.rs index 5e194988..f96236d6 100644 --- a/src/utils/markdown.rs +++ b/src/utils/markdown.rs @@ -176,10 +176,7 @@ mod tests { #[test] fn test_user_mention() { - assert_eq!( - user_mention(123_456_789, "pwner666"), - "[pwner666](tg://user?id=123456789)" - ); + assert_eq!(user_mention(123_456_789, "pwner666"), "[pwner666](tg://user?id=123456789)"); } #[test] @@ -193,26 +190,16 @@ mod tests { #[test] fn test_code_block_with_lang() { assert_eq!( - code_block_with_lang( - "pre-'formatted'\nfixed-width \\code `block`", - "[python]" - ), - "```\\[python\\]\npre-'formatted'\nfixed-width \\\\code \ - \\`block\\`\n```" + code_block_with_lang("pre-'formatted'\nfixed-width \\code `block`", "[python]"), + "```\\[python\\]\npre-'formatted'\nfixed-width \\\\code \\`block\\`\n```" ); } #[test] fn test_code_inline() { - assert_eq!( - code_inline(" let x = (1, 2, 3); "), - "` let x = (1, 2, 3); `" - ); + assert_eq!(code_inline(" let x = (1, 2, 3); "), "` let x = (1, 2, 3); `"); assert_eq!(code_inline("foo"), "`foo`"); - assert_eq!( - code_inline(r" `(code inside code \ )` "), - r"` \`(code inside code \\ )\` `" - ); + assert_eq!(code_inline(r" `(code inside code \ )` "), r"` \`(code inside code \\ )\` `"); } #[test] @@ -227,27 +214,19 @@ mod tests { #[test] fn test_escape_link_url() { assert_eq!( - escape_link_url( - r"https://en.wikipedia.org/wiki/Development+(Software)" - ), + escape_link_url(r"https://en.wikipedia.org/wiki/Development+(Software)"), r"https://en.wikipedia.org/wiki/Development+(Software\)" ); assert_eq!( escape_link_url(r"https://en.wikipedia.org/wiki/`"), r"https://en.wikipedia.org/wiki/\`" ); - assert_eq!( - escape_link_url(r"_*[]()~`#+-=|{}.!\"), - r"_*[](\)~\`#+-=|{}.!\" - ); + assert_eq!(escape_link_url(r"_*[]()~`#+-=|{}.!\"), r"_*[](\)~\`#+-=|{}.!\"); } #[test] fn test_escape_code() { - assert_eq!( - escape_code(r"` \code inside the code\ `"), - r"\` \\code inside the code\\ \`" - ); + assert_eq!(escape_code(r"` \code inside the code\ `"), r"\` \\code inside the code\\ \`"); assert_eq!(escape_code(r"_*[]()~`#+-=|{}.!\"), r"_*[]()~\`#+-=|{}.!\\"); } diff --git a/tests/command.rs b/tests/command.rs index fd474c2a..82bba9aa 100644 --- a/tests/command.rs +++ b/tests/command.rs @@ -44,10 +44,7 @@ fn many_attributes() { Help, } - assert_eq!( - DefaultCommands::Start, - DefaultCommands::parse("!start", "").unwrap() - ); + assert_eq!(DefaultCommands::Start, DefaultCommands::parse("!start", "").unwrap()); assert_eq!(DefaultCommands::descriptions(), "!start - desc\n/help\n"); } @@ -61,18 +58,9 @@ fn global_attributes() { Help, } - assert_eq!( - DefaultCommands::Start, - DefaultCommands::parse("/start", "MyNameBot").unwrap() - ); - assert_eq!( - DefaultCommands::Help, - DefaultCommands::parse("!help", "MyNameBot").unwrap() - ); - assert_eq!( - DefaultCommands::descriptions(), - "Bot commands\n/start\n!help\n" - ); + assert_eq!(DefaultCommands::Start, DefaultCommands::parse("/start", "MyNameBot").unwrap()); + assert_eq!(DefaultCommands::Help, DefaultCommands::parse("!help", "MyNameBot").unwrap()); + assert_eq!(DefaultCommands::descriptions(), "Bot commands\n/start\n!help\n"); } #[test] @@ -129,19 +117,11 @@ fn parse_custom_parser() { let vec = s.split_whitespace().collect::>(); let (left, right) = match vec.as_slice() { [l, r] => (l, r), - _ => { - return Err(ParseError::IncorrectFormat( - "might be 2 arguments!".into(), - )) - } + _ => return Err(ParseError::IncorrectFormat("might be 2 arguments!".into())), }; - left.parse::().map(|res| (res, (*right).to_string())).map_err( - |_| { - ParseError::Custom( - "First argument must be a integer!".to_owned().into(), - ) - }, - ) + left.parse::() + .map(|res| (res, (*right).to_string())) + .map_err(|_| ParseError::Custom("First argument must be a integer!".to_owned().into())) } #[command(rename = "lowercase")] diff --git a/tests/redis.rs b/tests/redis.rs index 61dd6ad1..41e21a73 100644 --- a/tests/redis.rs +++ b/tests/redis.rs @@ -10,22 +10,19 @@ use teloxide::dispatching::dialogue::{ #[tokio::test] async fn test_redis_json() { - let storage = - RedisStorage::open("redis://127.0.0.1:7777", JSON).await.unwrap(); + let storage = RedisStorage::open("redis://127.0.0.1:7777", JSON).await.unwrap(); test_redis(storage).await; } #[tokio::test] async fn test_redis_bincode() { - let storage = - RedisStorage::open("redis://127.0.0.1:7778", Bincode).await.unwrap(); + let storage = RedisStorage::open("redis://127.0.0.1:7778", Bincode).await.unwrap(); test_redis(storage).await; } #[tokio::test] async fn test_redis_cbor() { - let storage = - RedisStorage::open("redis://127.0.0.1:7779", CBOR).await.unwrap(); + let storage = RedisStorage::open("redis://127.0.0.1:7779", CBOR).await.unwrap(); test_redis(storage).await; } @@ -36,34 +33,14 @@ where S: Send + Sync + Serializer + 'static, >::Error: Debug + Display, { - check_dialogue( - None, - Arc::clone(&storage).update_dialogue(1, "ABC".to_owned()), - ) - .await; - check_dialogue( - None, - Arc::clone(&storage).update_dialogue(11, "DEF".to_owned()), - ) - .await; - check_dialogue( - None, - Arc::clone(&storage).update_dialogue(256, "GHI".to_owned()), - ) - .await; + check_dialogue(None, Arc::clone(&storage).update_dialogue(1, "ABC".to_owned())).await; + check_dialogue(None, Arc::clone(&storage).update_dialogue(11, "DEF".to_owned())).await; + check_dialogue(None, Arc::clone(&storage).update_dialogue(256, "GHI".to_owned())).await; // 1 - ABC, 11 - DEF, 256 - GHI - check_dialogue( - "ABC", - Arc::clone(&storage).update_dialogue(1, "JKL".to_owned()), - ) - .await; - check_dialogue( - "GHI", - Arc::clone(&storage).update_dialogue(256, "MNO".to_owned()), - ) - .await; + check_dialogue("ABC", Arc::clone(&storage).update_dialogue(1, "JKL".to_owned())).await; + check_dialogue("GHI", Arc::clone(&storage).update_dialogue(256, "MNO".to_owned())).await; // 1 - GKL, 11 - DEF, 256 - MNO