diff --git a/CODE_STYLE.md b/CODE_STYLE.md new file mode 100644 index 00000000..384d7fa4 --- /dev/null +++ b/CODE_STYLE.md @@ -0,0 +1,124 @@ +# Code style +This is a description of a coding style that every contributor must follow. Please, read the whole document before you start pushing code. + +## Generics +Generics are always written with `where`. + +Bad: + +```rust + pub fn new, + T: Into, + P: Into, + E: Into> + (user_id: i32, name: N, title: T, png_sticker: P, emojis: E) -> Self { ... } +``` + +Good: + +```rust + pub fn new(user_id: i32, name: N, title: T, png_sticker: P, emojis: E) -> Self + where + N: Into, + T: Into, + P: Into, + E: Into { ... } +``` + +## Comments + 1. Comments must describe what your code does and mustn't describe how your code does it and bla-bla-bla. Be sure that your comments follow the grammar, including punctuation, the first capital letter and so on. + +Bad: + +```rust +/// this function make request to telegram +pub fn make_request(url: &str) -> String { ... } +``` + +Good: + +```rust +/// This function makes a request to Telegram. +pub fn make_request(url: &str) -> String { ... } +``` + + 2. Also, link resources in your comments when possible: + +```rust +/// Download a file from Telegram. +/// +/// `path` can be obtained from the [`Bot::get_file`]. +/// +/// To download into [`AsyncWrite`] (e.g. [`tokio::fs::File`]), see +/// [`Bot::download_file`]. +/// +/// [`Bot::get_file`]: crate::bot::Bot::get_file +/// [`AsyncWrite`]: tokio::io::AsyncWrite +/// [`tokio::fs::File`]: tokio::fs::File +/// [`Bot::download_file`]: crate::Bot::download_file +#[cfg(feature = "unstable-stream")] +pub async fn download_file_stream( + &self, + path: &str, +) -> Result>, reqwest::Error> +{ + download_file_stream(&self.client, &self.token, path).await +} +``` + +## Use Self where possible +Bad: + +```rust +impl ErrorKind { + fn print(&self) { + ErrorKind::Io => println!("Io"), + ErrorKind::Network => println!("Network"), + ErrorKind::Json => println!("Json"), + } +} +``` + +Good: +```rust +impl ErrorKind { + fn print(&self) { + Self::Io => println!("Io"), + Self::Network => println!("Network"), + Self::Json => println!("Json"), + } +} +``` + +
+ More examples + +Bad: + +```rust +impl<'a> AnswerCallbackQuery<'a> { + pub(crate) fn new(bot: &'a Bot, callback_query_id: C) -> AnswerCallbackQuery<'a> + where +C: Into, { ... } +``` + +Good: + +```rust +impl<'a> AnswerCallbackQuery<'a> { + pub(crate) fn new(bot: &'a Bot, callback_query_id: C) -> Self + where +C: Into, { ... } +``` +
+ +## Naming + 1. Avoid unnecessary duplication (`Message::message_id` -> `Message::id` using `#[serde(rename = "message_id")]`). + 2. Use a generic parameter name `S` for streams, `Fut` for futures, `F` for functions (where possible). + +## Deriving + 1. Derive `Copy`, `Eq`, `Hash`, `PartialEq`, `Clone`, `Debug` for public types when possible (note: if the default `Debug` implementation is weird, you should manually implement it by yourself). + 2. Derive `Default` when there is an algorithm to get a default value for your type. + +## Misc + 1. Use `Into<...>` only where there exists at least one conversion **and** it will be logically to use. diff --git a/Cargo.toml b/Cargo.toml index a30cfe19..23823539 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,16 +12,18 @@ serde = { version = "1.0.101", features = ["derive"] } tokio = { version = "0.2.6", features = ["full"] } tokio-util = { version = "0.2.0", features = ["full"] } -reqwest = { version = "0.10", features = ["json", "stream"] } +reqwest = { version = "0.10", features = ["json", "stream", "native-tls-vendored"] } log = "0.4.8" bytes = "0.5.3" +mime = "0.3.16" derive_more = "0.99.2" thiserror = "1.0.9" async-trait = "0.1.22" +duang = "0.1.2" futures = "0.3.1" pin-project = "0.4.6" serde_with_macros = "1.0.1" either = "1.5.3" -mime = "0.3.16" + teloxide-macros = { path = "teloxide-macros" } \ No newline at end of file diff --git a/examples/ping_pong_bot.rs b/examples/ping_pong_bot.rs new file mode 100644 index 00000000..8948dada --- /dev/null +++ b/examples/ping_pong_bot.rs @@ -0,0 +1,34 @@ +use futures::stream::StreamExt; +use teloxide::{ + dispatching::{ + chat::{ChatUpdate, ChatUpdateKind, Dispatcher}, + update_listeners::polling_default, + SessionState, + }, + requests::Request, + Bot, +}; + +#[tokio::main] +async fn main() { + let bot = &Bot::new("1061598315:AAErEDodTsrqD3UxA_EvFyEfXbKA6DT25G0"); + let mut updater = Box::pin(polling_default(bot)); + let handler = |_, upd: ChatUpdate| async move { + if let ChatUpdateKind::Message(m) = upd.kind { + let msg = bot.send_message(m.chat.id, "pong"); + msg.send().await.unwrap(); + } + SessionState::Continue(()) + }; + let mut dp = Dispatcher::<'_, (), _>::new(handler); + println!("Starting the message handler."); + loop { + let u = updater.next().await.unwrap(); + match u { + Err(e) => eprintln!("Error: {}", e), + Ok(u) => { + let _ = dp.dispatch(u).await; + } + } + } +} diff --git a/src/bot/api.rs b/src/bot/api.rs index 73a31753..ff3a8b88 100644 --- a/src/bot/api.rs +++ b/src/bot/api.rs @@ -27,10 +27,41 @@ use crate::{ }; impl Bot { + /// Use this method to receive incoming updates using long polling ([wiki]). + /// + /// **Notes:** + /// 1. This method will not work if an outgoing webhook is set up. + /// 2. In order to avoid getting duplicate updates, + /// recalculate offset after each server response. + /// + /// [The official docs](https://core.telegram.org/bots/api#getupdates). + /// + /// [wiki]: https://en.wikipedia.org/wiki/Push_technology#Long_polling pub fn get_updates(&self) -> GetUpdates { GetUpdates::new(self) } + /// Use this method to specify a url and receive incoming updates via an + /// outgoing webhook. + /// + /// Whenever there is an update for the bot, we will send an + /// HTTPS POST request to the specified url, containing a JSON-serialized + /// [`Update`]. In case of an unsuccessful request, we will give up after a + /// reasonable amount of attempts. + /// + /// If you'd like to make sure that the Webhook request comes from Telegram, + /// we recommend using a secret path in the URL, e.g. + /// `https://www.example.com/`. Since nobody else knows your bot‘s + /// token, you can be pretty sure it’s us. + /// + /// [The official docs](https://core.telegram.org/bots/api#setwebhook). + /// + /// # Params + /// - `url`: HTTPS url to send updates to. + /// + /// Use an empty string to remove webhook integration. + /// + /// [`Update`]: crate::types::Update pub fn set_webhook(&self, url: U) -> SetWebhook where U: Into, @@ -38,18 +69,44 @@ impl Bot { SetWebhook::new(self, url) } + /// Use this method to remove webhook integration if you decide to switch + /// back to [Bot::get_updates]. + /// + /// [The official docs](https://core.telegram.org/bots/api#deletewebhook). + /// + /// [Bot::get_updates]: crate::Bot::get_updates pub fn delete_webhook(&self) -> DeleteWebhook { DeleteWebhook::new(self) } + /// Use this method to get current webhook status. + /// + /// If the bot is using [`Bot::get_updates`], will return an object with the + /// url field empty. + /// + /// [The official docs](https://core.telegram.org/bots/api#getwebhookinfo). + /// + /// [`Bot::get_updates`]: crate::Bot::get_updates pub fn get_webhook_info(&self) -> GetWebhookInfo { GetWebhookInfo::new(self) } + /// A simple method for testing your bot's auth token. Requires no + /// parameters. + /// + /// [The official docs](https://core.telegram.org/bots/api#getme). pub fn get_me(&self) -> GetMe { GetMe::new(self) } + /// Use this method to send text messages. + /// + /// [The official docs](https://core.telegram.org/bots/api#sendmessage). + /// + /// # Params + /// - `chat_id`: Unique identifier for the target chat or username of the + /// target supergroup or channel (in the format `@channelusername`). + /// - `text`: Text of the message to be sent. pub fn send_message(&self, chat_id: C, text: T) -> SendMessage where C: Into, @@ -58,6 +115,20 @@ impl Bot { SendMessage::new(self, chat_id, text) } + /// Use this method to forward messages of any kind. + /// + /// [`The official docs`](https://core.telegram.org/bots/api#forwardmessage). + /// + /// # Params + /// - `chat_id`: Unique identifier for the target chat or username of the + /// target supergroup or channel (in the format `@channelusername`). + /// - `from_chat_id`: Unique identifier for the chat where the original + /// message was sent (or channel username in the format + /// `@channelusername`). + /// - `message_id`: Message identifier in the chat specified in + /// [`from_chat_id`]. + /// + /// [`from_chat_id`]: ForwardMessage::from_chat_id pub fn forward_message( &self, chat_id: C, @@ -71,6 +142,25 @@ impl Bot { ForwardMessage::new(self, chat_id, from_chat_id, message_id) } + /// Use this method to send photos. + /// + /// [The official docs](https://core.telegram.org/bots/api#sendphoto). + /// + /// # Params + /// - `chat_id`: Unique identifier for the target chat or username of the + /// target supergroup or channel (in the format `@channelusername`). + /// - `photo`: Photo to send. + /// + /// Pass [`InputFile::File`] to send a photo that exists on + /// the Telegram servers (recommended), pass an [`InputFile::Url`] for + /// Telegram to get a .webp file from the Internet, or upload a new one + /// using [`InputFile::FileId`]. [More info on Sending Files »]. + /// + /// [`InputFile::File`]: crate::types::InputFile::File + /// [`InputFile::Url`]: crate::types::InputFile::Url + /// [`InputFile::FileId`]: crate::types::InputFile::FileId + /// + /// [More info on Sending Files »]: https://core.telegram.org/bots/api#sending-files pub fn send_photo(&self, chat_id: C, photo: InputFile) -> SendPhoto where C: Into, @@ -78,6 +168,11 @@ impl Bot { SendPhoto::new(self, chat_id, photo) } + /// + /// + /// # Params + /// - `chat_id`: Unique identifier for the target chat or username of the + /// target supergroup or channel (in the format `@channelusername`). pub fn send_audio(&self, chat_id: C, audio: InputFile) -> SendAudio where C: Into, @@ -85,6 +180,24 @@ impl Bot { SendAudio::new(self, chat_id, audio) } + /// Use this method to send general files. + /// + /// Bots can currently send files of any type of up to 50 MB in size, this + /// limit may be changed in the future. + /// + /// [The official docs](https://core.telegram.org/bots/api#senddocument). + /// + /// # Params + /// - `chat_id`: Unique identifier for the target chat or username of the + /// target supergroup or channel (in the format `@channelusername`). + /// - `document`: File to send. + /// + /// Pass a file_id as String to send a file that exists on the + /// Telegram servers (recommended), pass an HTTP URL as a String for + /// Telegram to get a file from the Internet, or upload a new one using + /// `multipart/form-data`. [More info on Sending Files »]. + /// + /// [More info on Sending Files »]: https://core.telegram.org/bots/api#sending-files pub fn send_document( &self, chat_id: C, @@ -96,6 +209,27 @@ impl Bot { SendDocument::new(self, chat_id, document) } + /// Use this method to send video files, Telegram clients support mp4 videos + /// (other formats may be sent as Document). + /// + /// Bots can currently send video files of up to 50 MB in size, this + /// limit may be changed in the future. + /// + /// [The official docs](https://core.telegram.org/bots/api#sendvideo). + /// + /// # Params + /// - `chat_id`: Unique identifier for the target chat or username of the + /// target supergroup or channel (in the format `@channelusername`). + /// - `video`: Video to sent. + /// + /// Pass [`InputFile::File`] to send a file that exists on + /// the Telegram servers (recommended), pass an [`InputFile::Url`] for + /// Telegram to get a .webp file from the Internet, or upload a new one + /// using [`InputFile::FileId`]. [More info on Sending Files »]. + /// + /// [`InputFile::File`]: crate::types::InputFile::File + /// [`InputFile::Url`]: crate::types::InputFile::Url + /// [`InputFile::FileId`]: crate::types::InputFile::FileId pub fn send_video(&self, chat_id: C, video: InputFile) -> SendVideo where C: Into, @@ -103,6 +237,18 @@ impl Bot { SendVideo::new(self, chat_id, video) } + /// Use this method to send animation files (GIF or H.264/MPEG-4 AVC video + /// without sound). + /// + /// Bots can currently send animation files of up to 50 MB in size, this + /// limit may be changed in the future. + /// + /// [The official docs](https://core.telegram.org/bots/api#sendanimation). + /// + /// # Params + /// - `chat_id`: Unique identifier for the target chat or username of the + /// target supergroup or channel (in the format `@channelusername`). + /// - `animation`: Animation to send. pub fn send_animation( &self, chat_id: C, @@ -114,6 +260,33 @@ impl Bot { SendAnimation::new(self, chat_id, animation) } + /// Use this method to send audio files, if you want Telegram clients to + /// display the file as a playable voice message. + /// + /// For this to work, your audio must be in an .ogg file encoded with OPUS + /// (other formats may be sent as [`Audio`] or [`Document`]). Bots can + /// currently send voice messages of up to 50 MB in size, this limit may + /// be changed in the future. + /// + /// [The official docs](https://core.telegram.org/bots/api#sendvoice). + /// + /// [`Audio`]: crate::types::Audio + /// [`Document`]: crate::types::Document + /// + /// # Params + /// - `chat_id`: Unique identifier for the target chat or username of the + /// target supergroup or channel (in the format `@channelusername`). + /// - `voice`: Audio file to send. + /// + /// Pass [`InputFile::File`] to send a file that exists on + /// the Telegram servers (recommended), pass an [`InputFile::Url`] for + /// Telegram to get a .webp file from the Internet, or upload a new one + /// using [`InputFile::FileId`]. [More info on Sending Files »]. + /// + /// [`InputFile::File`]: crate::types::InputFile::File + /// [`InputFile::Url`]: crate::types::InputFile::Url + /// [`InputFile::FileId`]: crate::types::InputFile::FileId + /// [More info on Sending Files »]: https://core.telegram.org/bots/api#sending-files pub fn send_voice(&self, chat_id: C, voice: InputFile) -> SendVoice where C: Into, @@ -121,6 +294,26 @@ impl Bot { SendVoice::new(self, chat_id, voice) } + /// As of [v.4.0], Telegram clients support rounded square mp4 videos of up + /// to 1 minute long. Use this method to send video messages. + /// + /// [The official docs](https://core.telegram.org/bots/api#sendvideonote). + /// + /// # Params + /// - `chat_id`: Unique identifier for the target chat or username of the + /// target supergroup or channel (in the format `@channelusername`). + /// - `video_note`: Video note to send. + /// + /// Pass [`InputFile::File`] to send a file that exists on the Telegram + /// servers (recommended), pass an [`InputFile::Url`] for Telegram to get a + /// .webp file from the Internet, or upload a new one using + /// [`InputFile::FileId`]. [More info on Sending Files »]. + /// + /// [v.4.0]: https://telegram.org/blog/video-messages-and-telescope + /// [`InputFile::File`]: crate::types::InputFile::File + /// [`InputFile::Url`]: crate::types::InputFile::Url + /// [`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, @@ -132,6 +325,15 @@ impl Bot { SendVideoNote::new(self, chat_id, video_note) } + /// Use this method to send a group of photos or videos as an album. + /// + /// [The official docs](https://core.telegram.org/bots/api#sendmediagroup). + /// + /// # Params + /// - `chat_id`: Unique identifier for the target chat or username of the + /// target supergroup or channel (in the format `@channelusername`). + /// - `media`: A JSON-serialized array describing photos and videos to be + /// sent, must include 2–10 items. pub fn send_media_group(&self, chat_id: C, media: M) -> SendMediaGroup where C: Into, @@ -140,6 +342,15 @@ impl Bot { SendMediaGroup::new(self, chat_id, media) } + /// Use this method to send point on the map. + /// + /// [The official docs](https://core.telegram.org/bots/api#sendlocation). + /// + /// # Params + /// - `chat_id`: Unique identifier for the target chat or username of the + /// 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, @@ -152,6 +363,21 @@ impl Bot { SendLocation::new(self, chat_id, latitude, longitude) } + /// Use this method to edit live location messages. + /// + /// A location can be edited until its live_period expires or editing is + /// explicitly disabled by a call to stopMessageLiveLocation. On success, if + /// the edited message was sent by the bot, the edited [`Message`] is + /// returned, otherwise [`True`] is returned. + /// + /// [The official docs](https://core.telegram.org/bots/api#editmessagelivelocation). + /// + /// # Params + /// - `latitude`: Latitude of new location. + /// - `longitude`: Longitude of new location. + /// + /// [`Message`]: crate::types::Message + /// [`True`]: crate::types::True pub fn edit_message_live_location( &self, chat_or_inline_message: ChatOrInlineMessage, @@ -166,6 +392,16 @@ impl Bot { ) } + /// Use this method to stop updating a live location message before + /// `live_period` expires. + /// + /// On success, if the message was sent by the bot, the sent [`Message`] is + /// returned, otherwise [`True`] is returned. + /// + /// [The official docs](https://core.telegram.org/bots/api#stopmessagelivelocation). + /// + /// [`Message`]: crate::types::Message + /// [`True`]: crate::types::True pub fn stop_message_live_location( &self, chat_or_inline_message: ChatOrInlineMessage, @@ -173,6 +409,17 @@ impl Bot { StopMessageLiveLocation::new(self, chat_or_inline_message) } + /// Use this method to send information about a venue. + /// + /// [The official docs](https://core.telegram.org/bots/api#sendvenue). + /// + /// # Params + /// - `chat_id`: Unique identifier for the target chat or username of the + /// target supergroup or channel (in the format `@channelusername`). + /// - `latitude`: Latitude of the venue. + /// - `longitude`: Longitude of the venue. + /// - `title`: Name of the venue. + /// - `address`: Address of the venue. pub fn send_venue( &self, chat_id: C, @@ -189,6 +436,16 @@ impl Bot { SendVenue::new(self, chat_id, latitude, longitude, title, address) } + /// Use this method to send phone contacts. + /// + /// [The official docs](https://core.telegram.org/bots/api#sendcontact). + /// + /// + /// # Params + /// - `chat_id`: Unique identifier for the target chat or username of the + /// 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, @@ -203,6 +460,18 @@ impl Bot { SendContact::new(self, chat_id, phone_number, first_name) } + /// Use this method to send a native poll. A native poll can't be sent to a + /// private chat. + /// + /// [The official docs](https://core.telegram.org/bots/api#sendpoll). + /// + /// + /// # Params + /// - `chat_id`: Unique identifier for the target chat or username of the + /// target supergroup or channel (in the format `@channelusername`). + /// - `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, @@ -217,6 +486,28 @@ impl Bot { SendPoll::new(self, chat_id, question, options) } + /// Use this method when you need to tell the user that something is + /// happening on the bot's side. + /// + /// The status is set for 5 seconds or less (when a message arrives from + /// your bot, Telegram clients clear its typing status). + /// + /// ## Note + /// Example: The [ImageBot] needs some time to process a request and upload + /// the image. Instead of sending a text message along the lines of + /// “Retrieving image, please wait…”, the bot may use + /// [`Bot::send_chat_action`] with `action = upload_photo`. The user + /// will see a `sending photo` status for the bot. + /// + /// We only recommend using this method when a response from the bot will + /// take a **noticeable** amount of time to arrive. + /// + /// # Params + /// - `chat_id`: Unique identifier for the target chat or username of the + /// target supergroup or channel (in the format `@channelusername`). + /// + /// [ImageBot]: https://t.me/imagebot + /// [`Bot::send_chat_action`]: crate::Bot::send_chat_action pub fn send_chat_action( &self, chat_id: C, @@ -228,6 +519,12 @@ impl Bot { SendChatAction::new(self, chat_id, action) } + /// Use this method to get a list of profile pictures for a user. + /// + /// [The official docs](https://core.telegram.org/bots/api#getuserprofilephotos). + /// + /// # Params + /// - `user_id`: Unique identifier of the target user. pub fn get_user_profile_photos( &self, user_id: i32, @@ -235,6 +532,28 @@ impl Bot { GetUserProfilePhotos::new(self, user_id) } + /// Use this method to get basic info about a file and prepare it for + /// downloading. + /// + /// For the moment, bots can download files of up to `20MB` in size. + /// + /// The file can then be downloaded via the link + /// `https://api.telegram.org/file/bot/`, where `` + /// is taken from the response. It is guaranteed that the link will be valid + /// for at least `1` hour. When the link expires, a new one can be requested + /// by calling [`GetFile`] again. + /// + /// **Note**: This function may not preserve the original file name and MIME + /// type. You should save the file's MIME type and name (if available) when + /// the [`File`] object is received. + /// + /// [The official docs](https://core.telegram.org/bots/api#getfile). + /// + /// # Params + /// - `file_id`: File identifier to get info about. + /// + /// [`File`]: crate::types::file + /// [`GetFile`]: self::GetFile pub fn get_file(&self, file_id: F) -> GetFile where F: Into, @@ -242,6 +561,21 @@ impl Bot { GetFile::new(self, file_id) } + /// Use this method to kick a user from a group, a supergroup or a channel. + /// + /// In the case of supergroups and channels, the user will not be able to + /// return to the group on their own using invite links, etc., unless + /// [unbanned] first. The bot must be an administrator in the chat for + /// this to work and must have the appropriate admin rights. + /// + /// [The official docs](https://core.telegram.org/bots/api#kickchatmember). + /// + /// # Params + /// - `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. + /// + /// [unbanned]: crate::Bot::unban_chat_member pub fn kick_chat_member( &self, chat_id: C, @@ -253,6 +587,17 @@ impl Bot { KickChatMember::new(self, chat_id, user_id) } + /// Use this method to unban a previously kicked user in a supergroup or + /// channel. The user will **not** return to the group or channel + /// automatically, but will be able to join via link, etc. The bot must + /// be an administrator for this to work. + /// + /// [The official docs](https://core.telegram.org/bots/api#unbanchatmember). + /// + /// # Params + /// - `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, @@ -264,6 +609,19 @@ impl Bot { UnbanChatMember::new(self, chat_id, user_id) } + /// Use this method to restrict a user in a supergroup. + /// + /// The bot must be an administrator in the supergroup for this to work and + /// must have the appropriate admin rights. Pass `true` for all + /// permissions to lift restrictions from a user. + /// + /// [The official docs](https://core.telegram.org/bots/api#restrictchatmember). + /// + /// # Params + /// - `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. + /// - `permissions`: New user permissions. pub fn restrict_chat_member( &self, chat_id: C, @@ -276,6 +634,19 @@ impl Bot { RestrictChatMember::new(self, chat_id, user_id, permissions) } + /// Use this method to promote or demote a user in a supergroup or a + /// channel. + /// + /// The bot must be an administrator in the chat for this to work and must + /// have the appropriate admin rights. Pass False for all boolean + /// parameters to demote a user. + /// + /// [The official docs](https://core.telegram.org/bots/api#promotechatmember). + /// + /// # Params + /// - `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, @@ -287,6 +658,17 @@ impl Bot { PromoteChatMember::new(self, chat_id, user_id) } + /// Use this method to set default chat permissions for all members. + /// + /// The bot must be an administrator in the group or a supergroup for this + /// to work and must have the can_restrict_members admin rights. + /// + /// [The official docs](https://core.telegram.org/bots/api#setchatpermissions). + /// + /// # Params + /// - `chat_id`: Unique identifier for the target chat or username of the + /// target supergroup or channel (in the format `@channelusername`). + /// - `permissions`: New default chat permissions. pub fn set_chat_permissions( &self, chat_id: C, @@ -298,6 +680,29 @@ impl Bot { SetChatPermissions::new(self, chat_id, permissions) } + /// Use this method to generate a new invite link for a chat; any previously + /// generated link is revoked. + /// + /// The bot must be an administrator in the chat for this to work and must + /// have the appropriate admin rights. + /// + /// # Note + /// Each administrator in a chat generates their own invite links. Bots + /// can't use invite links generated by other administrators. If you + /// want your bot to work with invite links, it will need to generate + /// its own link using [`Bot::export_chat_invite_link`] – after this the + /// link will become available to the bot via the [`Bot::get_chat`] + /// method. If your bot needs to generate a new invite link replacing + /// its previous one, use [`Bot::export_chat_invite_link`] again. + /// + /// [The official docs](https://core.telegram.org/bots/api#exportchatinvitelink). + /// + /// # Params + /// - `chat_id`: Unique identifier for the target chat or username of the + /// target supergroup or channel (in the format `@channelusername`). + /// + /// [`Bot::export_chat_invite_link`]: crate::Bot::export_chat_invite_link + /// [`Bot::get_chat`]: crate::Bot::get_chat pub fn export_chat_invite_link(&self, chat_id: C) -> ExportChatInviteLink where C: Into, @@ -305,6 +710,18 @@ impl Bot { ExportChatInviteLink::new(self, chat_id) } + /// Use this method to set a new profile photo for the chat. + /// + /// Photos can't be changed for private chats. The bot must be an + /// administrator in the chat for this to work and must have the + /// appropriate admin rights. + /// + /// [The official docs](https://core.telegram.org/bots/api#setchatphoto). + /// + /// # Params + /// - `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, @@ -316,6 +733,15 @@ impl Bot { SetChatPhoto::new(self, chat_id, photo) } + /// Use this method to delete a chat photo. Photos can't be changed for + /// private chats. The bot must be an administrator in the chat for this + /// to work and must have the appropriate admin rights. + /// + /// [The official docs](https://core.telegram.org/bots/api#deletechatphoto). + /// + /// # Params + /// - `chat_id`: Unique identifier for the target chat or username of the + /// target supergroup or channel (in the format `@channelusername`). pub fn delete_chat_photo(&self, chat_id: C) -> DeleteChatPhoto where C: Into, @@ -323,6 +749,18 @@ impl Bot { DeleteChatPhoto::new(self, chat_id) } + /// Use this method to change the title of a chat. + /// + /// Titles can't be changed for private chats. The bot must be an + /// administrator in the chat for this to work and must have the + /// appropriate admin rights. + /// + /// [The official docs](https://core.telegram.org/bots/api#setchattitle). + /// + /// # Params + /// - `chat_id`: Unique identifier for the target chat or username of the + /// target supergroup or channel (in the format `@channelusername`). + /// - `title`: New chat title, 1-255 characters. pub fn set_chat_title(&self, chat_id: C, title: T) -> SetChatTitle where C: Into, @@ -331,6 +769,17 @@ impl Bot { SetChatTitle::new(self, chat_id, title) } + /// Use this method to change the description of a group, a supergroup or a + /// channel. + /// + /// The bot must be an administrator in the chat for this to work and must + /// have the appropriate admin rights. + /// + /// [The official docs](https://core.telegram.org/bots/api#setchatdescription). + /// + /// # Params + /// - `chat_id`: Unique identifier for the target chat or username of the + /// target supergroup or channel (in the format `@channelusername`). pub fn set_chat_description(&self, chat_id: C) -> SetChatDescription where C: Into, @@ -338,6 +787,18 @@ impl Bot { SetChatDescription::new(self, chat_id) } + /// Use this method to pin a message in a group, a supergroup, or a channel. + /// + /// The bot must be an administrator in the chat for this to work and must + /// have the `can_pin_messages` admin right in the supergroup or + /// `can_edit_messages` admin right in the channel. + /// + /// [The official docs](https://core.telegram.org/bots/api#pinchatmessage). + /// + /// # Params + /// - `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, @@ -349,6 +810,18 @@ impl Bot { PinChatMessage::new(self, chat_id, message_id) } + /// Use this method to unpin a message in a group, a supergroup, or a + /// channel. + /// + /// The bot must be an administrator in the chat for this to work and must + /// have the `can_pin_messages` admin right in the supergroup or + /// `can_edit_messages` admin right in the channel. + /// + /// [The official docs](https://core.telegram.org/bots/api#unpinchatmessage). + /// + /// # Params + /// - `chat_id`: Unique identifier for the target chat or username of the + /// target supergroup or channel (in the format `@channelusername`). pub fn unpin_chat_message(&self, chat_id: C) -> UnpinChatMessage where C: Into, @@ -356,6 +829,13 @@ impl Bot { UnpinChatMessage::new(self, chat_id) } + /// Use this method for your bot to leave a group, supergroup or channel. + /// + /// [The official docs](https://core.telegram.org/bots/api#leavechat). + /// + /// # Params + /// - `chat_id`: Unique identifier for the target chat or username of the + /// target supergroup or channel (in the format `@channelusername`). pub fn leave_chat(&self, chat_id: C) -> LeaveChat where C: Into, @@ -363,6 +843,15 @@ impl Bot { LeaveChat::new(self, chat_id) } + /// Use this method to get up to date information about the chat (current + /// name of the user for one-on-one conversations, current username of a + /// user, group or channel, etc.). + /// + /// [The official docs](https://core.telegram.org/bots/api#getchat). + /// + /// # 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(&self, chat_id: C) -> GetChat where C: Into, @@ -370,6 +859,16 @@ impl Bot { GetChat::new(self, chat_id) } + /// Use this method to get a list of administrators in a chat. + /// + /// If the chat is a group or a supergroup and no administrators were + /// appointed, only the creator will be returned. + /// + /// [The official docs](https://core.telegram.org/bots/api#getchatadministrators). + /// + /// # 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, @@ -380,6 +879,13 @@ impl Bot { GetChatAdministrators::new(self, chat_id) } + /// Use this method to get the number of members in a chat. + /// + /// [The official docs](https://core.telegram.org/bots/api#getchatmemberscount). + /// + /// # 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_members_count(&self, chat_id: C) -> GetChatMembersCount where C: Into, @@ -387,6 +893,14 @@ impl Bot { GetChatMembersCount::new(self, chat_id) } + /// Use this method to get information about a member of a chat. + /// + /// [The official docs](https://core.telegram.org/bots/api#getchatmember). + /// + /// # Params + /// - `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 get_chat_member(&self, chat_id: C, user_id: i32) -> GetChatMember where C: Into, @@ -394,6 +908,20 @@ impl Bot { GetChatMember::new(self, chat_id, user_id) } + /// Use this method to set a new group sticker set for a supergroup. + /// + /// The bot must be an administrator in the chat for this to work and must + /// have the appropriate admin rights. Use the field can_set_sticker_set + /// optionally returned in getChat requests to check if the bot can use + /// this method. + /// + /// [The official docs](https://core.telegram.org/bots/api#setchatstickerset). + /// + /// # Params + /// - `chat_id`: Unique identifier for the target chat or username of the + /// 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, @@ -406,6 +934,20 @@ impl Bot { SetChatStickerSet::new(self, chat_id, sticker_set_name) } + /// Use this method to delete a group sticker set from a supergroup. + /// + /// The bot must be an administrator in the chat for this to work and must + /// have the appropriate admin rights. Use the field + /// `can_set_sticker_set` optionally returned in [`Bot::get_chat`] + /// requests to check if the bot can use this method. + /// + /// [The official docs](https://core.telegram.org/bots/api#deletechatstickerset). + /// + /// # Params + /// - `chat_id`: Unique identifier for the target chat or username of the + /// target supergroup (in the format `@supergroupusername`). + /// + /// [`Bot::get_chat`]: crate::Bot::get_chat pub fn delete_chat_sticker_set(&self, chat_id: C) -> DeleteChatStickerSet where C: Into, @@ -413,6 +955,18 @@ impl Bot { DeleteChatStickerSet::new(self, chat_id) } + /// Use this method to send answers to callback queries sent from [inline + /// keyboards]. + /// + /// The answer will be displayed to the user as a notification at + /// the top of the chat screen or as an alert. + /// + /// [The official docs](https://core.telegram.org/bots/api#answercallbackquery). + /// + /// # Params + /// - `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, @@ -423,6 +977,18 @@ impl Bot { AnswerCallbackQuery::new(self, callback_query_id) } + /// Use this method to edit text and game messages. + /// + /// On success, if edited message is sent by the bot, the edited [`Message`] + /// is returned, otherwise [`True`] is returned. + /// + /// [The official docs](https://core.telegram.org/bots/api#editmessagetext). + /// + /// # Params + /// - New text of the message. + /// + /// [`Message`]: crate::types::Message + /// [`True`]: crate::types::True pub fn edit_message_text( &self, chat_or_inline_message: ChatOrInlineMessage, @@ -434,6 +1000,15 @@ impl Bot { EditMessageText::new(self, chat_or_inline_message, text) } + /// Use this method to edit captions of messages. + /// + /// On success, if edited message is sent by the bot, the edited [`Message`] + /// is returned, otherwise [`True`] is returned. + /// + /// [The official docs](https://core.telegram.org/bots/api#editmessagecaption). + /// + /// [`Message`]: crate::types::Message + /// [`True`]: crate::types::True pub fn edit_message_caption( &self, chat_or_inline_message: ChatOrInlineMessage, @@ -441,6 +1016,20 @@ impl Bot { EditMessageCaption::new(self, chat_or_inline_message) } + /// Use this method to edit animation, audio, document, photo, or video + /// messages. + /// + /// If a message is a part of a message album, then it can be edited only to + /// a photo or a video. Otherwise, message type can be changed + /// arbitrarily. When inline message is edited, new file can't be + /// uploaded. Use previously uploaded file via its `file_id` or specify + /// a URL. On success, if the edited message was sent by the bot, the + /// edited [`Message`] is returned, otherwise [`True`] is returned. + /// + /// [The official docs](https://core.telegram.org/bots/api#editmessagemedia). + /// + /// [`Message`]: crate::types::Message + /// [`True`]: crate::types::True pub fn edit_message_media( &self, chat_or_inline_message: ChatOrInlineMessage, @@ -449,6 +1038,15 @@ impl Bot { EditMessageMedia::new(self, chat_or_inline_message, media) } + /// Use this method to edit only the reply markup of messages. + /// + /// On success, if edited message is sent by the bot, the edited [`Message`] + /// is returned, otherwise [`True`] is returned. + /// + /// [The official docs](https://core.telegram.org/bots/api#editmessagereplymarkup). + /// + /// [`Message`]: crate::types::Message + /// [`True`]: crate::types::True pub fn edit_message_reply_markup( &self, chat_or_inline_message: ChatOrInlineMessage, @@ -456,6 +1054,15 @@ impl Bot { EditMessageReplyMarkup::new(self, chat_or_inline_message) } + /// Use this method to stop a poll which was sent by the bot. + /// + /// [The official docs](https://core.telegram.org/bots/api#stoppoll). + /// + /// + /// # Params + /// - `chat_id`: Unique identifier for the target chat or username of the + /// target channel (in the format `@channelusername`). + /// - `message_id`: Identifier of the original message with the poll. pub fn stop_poll(&self, chat_id: C, message_id: i32) -> StopPoll where C: Into, @@ -463,6 +1070,26 @@ impl Bot { StopPoll::new(self, chat_id, message_id) } + /// Use this method to delete a message, including service messages. + /// + /// The limitations are: + /// - A message can only be deleted if it was sent less than 48 hours ago. + /// - Bots can delete outgoing messages in private chats, groups, and + /// supergroups. + /// - Bots can delete incoming messages in private chats. + /// - Bots granted can_post_messages permissions can delete outgoing + /// messages in channels. + /// - If the bot is an administrator of a group, it can delete any message + /// there. + /// - If the bot has can_delete_messages permission in a supergroup or a + /// channel, it can delete any message there. + /// + /// [The official docs](https://core.telegram.org/bots/api#deletemessage). + /// + /// # Params + /// - `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, @@ -474,6 +1101,25 @@ impl Bot { DeleteMessage::new(self, chat_id, message_id) } + /// Use this method to send static .WEBP or [animated] .TGS stickers. + /// + /// [The official docs](https://core.telegram.org/bots/api#sendsticker). + /// + /// # Params + /// - `chat_id`: Unique identifier for the target chat or username of the + /// target channel (in the format `@channelusername`). + /// - `sticker`: Sticker to send. + /// + /// Pass [`InputFile::File`] to send a file that exists on the Telegram + /// servers (recommended), pass an [`InputFile::Url`] for Telegram to get a + /// .webp file from the Internet, or upload a new one using + /// [`InputFile::FileId`]. [More info on Sending Files »]. + /// + /// [animated]: https://telegram.org/blog/animated-stickers + /// [`InputFile::File`]: crate::types::InputFile::File + /// [`InputFile::Url`]: crate::types::InputFile::Url + /// [`InputFile::FileId`]: crate::types::InputFile::FileId + /// [More info on Sending Files »]: https://core.telegram.org/bots/api#sending-files pub fn send_sticker(&self, chat_id: C, sticker: InputFile) -> SendSticker where C: Into, @@ -481,6 +1127,12 @@ impl Bot { SendSticker::new(self, chat_id, sticker) } + /// Use this method to get a sticker set. + /// + /// [The official docs](https://core.telegram.org/bots/api#getstickerset). + /// + /// # Params + /// - `name`: Name of the sticker set. pub fn get_sticker_set(&self, name: N) -> GetStickerSet where N: Into, @@ -488,6 +1140,22 @@ impl Bot { GetStickerSet::new(self, name) } + /// Use this method to upload a .png file with a sticker for later use in + /// [`Bot::create_new_sticker_set`] and [`Bot::add_sticker_to_set`] methods + /// (can be used multiple times). + /// + /// [The official docs](https://core.telegram.org/bots/api#uploadstickerfile). + /// + /// # Params + /// - `user_id`: User identifier of sticker file owner. + /// - `png_sticker`: **Png** image with the sticker, must be up to 512 + /// kilobytes in size, dimensions must not exceed 512px, and either + /// width or height must be exactly 512px. [More info on Sending Files + /// »]. + /// + /// [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, @@ -496,6 +1164,34 @@ impl Bot { UploadStickerFile::new(self, user_id, png_sticker) } + /// Use this method to create new sticker set owned by a user. The bot will + /// be able to edit the created sticker set. + /// + /// [The official docs](https://core.telegram.org/bots/api#createnewstickerset). + /// + /// # Params + /// - `user_id`: User identifier of created sticker set owner. + /// - `name`: Short name of sticker set, to be used in `t.me/addstickers/` + /// URLs (e.g., animals). Can contain only english letters, digits and + /// underscores. + /// + /// Must begin with a letter, can't contain consecutive underscores and must + /// end in `_by_`. `` is case insensitive. 1-64 + /// characters. + /// - `title`: Sticker set title, 1-64 characters. + /// - `png_sticker`: **Png** image with the sticker, must be up to 512 + /// kilobytes in size, dimensions must not exceed 512px, and either + /// width or height must be exactly 512px. + /// + /// Pass [`InputFile::File`] to send a file that exists on the Telegram + /// servers (recommended), pass an [`InputFile::Url`] for Telegram to get a + /// .webp file from the Internet, or upload a new one using + /// [`InputFile::FileId`]. [More info on Sending Files »]. + /// - `emojis`: One or more emoji corresponding to the sticker. + /// + /// [`InputFile::File`]: crate::types::InputFile::File + /// [`InputFile::Url`]: crate::types::InputFile::Url + /// [`InputFile::FileId`]: crate::types::InputFile::FileId pub fn create_new_sticker_set( &self, user_id: i32, @@ -519,6 +1215,26 @@ impl Bot { ) } + /// Use this method to add a new sticker to a set created by the bot. + /// + /// [The official docs](https://core.telegram.org/bots/api#addstickertoset). + /// + /// # Params + /// - `user_id`: User identifier of sticker set owner. + /// - `name`: Sticker set name. + /// - `png_sticker`: **Png** image with the sticker, must be up to 512 + /// kilobytes in size, dimensions must not exceed 512px, and either + /// width or height must be exactly 512px. + /// + /// Pass [`InputFile::File`] to send a file that exists on the Telegram + /// servers (recommended), pass an [`InputFile::Url`] for Telegram to get a + /// .webp file from the Internet, or upload a new one using [`InputFile: + /// :FileId`]. [More info on Sending Files »]. + /// - `emojis`: One or more emoji corresponding to the sticker. + /// + /// [`InputFile::File`]: crate::types::InputFile::File + /// [`InputFile::Url`]: crate::types::InputFile::Url + /// [`InputFile::FileId`]: crate::types::InputFile::FileId pub fn add_sticker_to_set( &self, user_id: i32, @@ -533,6 +1249,14 @@ impl Bot { AddStickerToSet::new(self, user_id, name, png_sticker, emojis) } + /// Use this method to move a sticker in a set created by the bot to a + /// specific position. + /// + /// [The official docs](https://core.telegram.org/bots/api#setstickerpositioninset). + /// + /// # Params + /// - `sticker`: File identifier of the sticker. + /// - `position`: New sticker position in the set, zero-based. pub fn set_sticker_position_in_set( &self, sticker: S, @@ -544,6 +1268,12 @@ impl Bot { SetStickerPositionInSet::new(self, sticker, position) } + /// Use this method to delete a sticker from a set created by the bot. + /// + /// [The official docs](https://core.telegram.org/bots/api#deletestickerfromset). + /// + /// # Params + /// - `sticker`: File identifier of the sticker. pub fn delete_sticker_from_set(&self, sticker: S) -> DeleteStickerFromSet where S: Into, @@ -551,6 +1281,15 @@ impl Bot { DeleteStickerFromSet::new(self, sticker) } + /// Use this method to send answers to an inline query. + /// + /// No more than **50** results per query are allowed. + /// + /// [The official docs](https://core.telegram.org/bots/api#answerinlinequery). + /// + /// # 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, @@ -563,6 +1302,27 @@ impl Bot { AnswerInlineQuery::new(self, inline_query_id, results) } + /// Use this method to send invoices. + /// + /// [The official docs](https://core.telegram.org/bots/api#sendinvoice). + /// + /// # Params + /// - `chat_id`: Unique identifier for the target private chat. + /// - `title`: Product name, 1-32 characters. + /// - `description`: Product description, 1-255 characters. + /// - `payload`: Bot-defined invoice payload, 1-128 bytes. This will not + /// be displayed to the user, use for your internal processes. + /// - `provider_token`: Payments provider token, obtained via + /// [@Botfather]. + /// - `start_parameter`: Unique deep-linking parameter that can be used to + /// generate this invoice when used as a start parameter. + /// - `currency`: Three-letter ISO 4217 currency code, see [more on + /// currencies]. + /// - `prices`: Price breakdown, a list of components (e.g. product price, + /// tax, discount, delivery cost, delivery tax, bonus, etc.). + /// + /// [more on currencies]: https://core.telegram.org/bots/payments#supported-currencies + /// [@Botfather]: https://t.me/botfather #[allow(clippy::too_many_arguments)] pub fn send_invoice( &self, @@ -597,6 +1357,21 @@ impl Bot { ) } + /// Once the user has confirmed their payment and shipping details, the Bot + /// API sends the final confirmation in the form of an [`Update`] with + /// the field `pre_checkout_query`. Use this method to respond to such + /// pre-checkout queries. Note: The Bot API must receive an answer + /// within 10 seconds after the pre-checkout query was sent. + /// + /// [The official docs](https://core.telegram.org/bots/api#answerprecheckoutquery). + /// + /// # Params + /// - `shipping_query_id`: Unique identifier for the query to be answered. + /// - `ok`: Specify `true` if delivery to the specified address is + /// possible and `false` if there are any problems (for example, if + /// delivery to the specified address is not possible). + /// + /// [`Update`]: crate::types::Update pub fn answer_shipping_query( &self, shipping_query_id: S, @@ -608,6 +1383,21 @@ impl Bot { AnswerShippingQuery::new(self, shipping_query_id, ok) } + /// Once the user has confirmed their payment and shipping details, the Bot + /// API sends the final confirmation in the form of an [`Update`] with + /// the field `pre_checkout_query`. Use this method to respond to such + /// pre-checkout queries. Note: The Bot API must receive an answer + /// within 10 seconds after the pre-checkout query was sent. + /// + /// [The official docs](https://core.telegram.org/bots/api#answerprecheckoutquery). + /// + /// # Params + /// - `pre_checkout_query_id`: Unique identifier for the query to be + /// answered. + /// - `ok`: Specify `true` if everything is alright (goods are available, + /// etc.) and the bot is ready to proceed with the order. Use False if + /// there are any problems. + /// [`Update`]: crate::types::Update pub fn answer_pre_checkout_query

( &self, pre_checkout_query_id: P, @@ -619,6 +1409,16 @@ impl Bot { AnswerPreCheckoutQuery::new(self, pre_checkout_query_id, ok) } + /// Use this method to send a game. + /// + /// [The official docs](https://core.telegram.org/bots/api#sendgame). + /// + /// # Params + /// - `chat_id`: Unique identifier for the target chat. + /// - `game_short_name`: Short name of the game, serves as the unique + /// identifier for the game. Set up your games via [@Botfather]. + /// + /// [@Botfather]: https://t.me/botfather pub fn send_game(&self, chat_id: i32, game_short_name: G) -> SendGame where G: Into, @@ -626,6 +1426,21 @@ impl Bot { SendGame::new(self, chat_id, game_short_name) } + /// Use this method to set the score of the specified user in a game. + /// + /// On success, if the message was sent by the bot, returns the edited + /// [`Message`], otherwise returns [`True`]. Returns an error, if the new + /// score is not greater than the user's current score in the chat and + /// force is `false`. + /// + /// [The official docs](https://core.telegram.org/bots/api#setgamescore). + /// + /// # Params + /// - `user_id`: User identifier. + /// - `score`: New score, must be non-negative. + /// + /// [`Message`]: crate::types::Message + /// [`True`]: crate::types::True pub fn set_game_score( &self, chat_or_inline_message: ChatOrInlineMessage, @@ -635,6 +1450,21 @@ impl Bot { SetGameScore::new(self, chat_or_inline_message, user_id, score) } + /// Use this method to get data for high score tables. + /// + /// Will return the score of the specified user and several of his neighbors + /// in a game. + /// + /// # Note + /// This method will currently return scores for the target user, plus two + /// of his closest neighbors on each side. Will also return the top + /// three users if the user and his neighbors are not among them. Please + /// note that this behavior is subject to change. + /// + /// [The official docs](https://core.telegram.org/bots/api#getgamehighscores). + /// + /// # Params + /// - `user_id`: Target user id. pub fn get_game_high_scores( &self, chat_or_inline_message: ChatOrInlineMessage, @@ -643,6 +1473,17 @@ impl Bot { GetGameHighScores::new(self, chat_or_inline_message, user_id) } + /// Use this method to set a custom title for an administrator in a + /// supergroup promoted by the bot. + /// + /// [The official docs](https://core.telegram.org/bots/api#setchatadministratorcustomtitle). + /// + /// # Params + /// - `chat_id`: Unique identifier for the target chat or username of the + /// target channel (in the format `@channelusername`). + /// - `user_id`: Unique identifier of the target user. + /// - `custom_title`: New custom title for the administrator; 0-16 + /// characters, emoji are not allowed. pub fn set_chat_administrator_custom_title( &self, chat_id: C, diff --git a/src/bot/download.rs b/src/bot/download.rs index 12101032..985e36e4 100644 --- a/src/bot/download.rs +++ b/src/bot/download.rs @@ -4,14 +4,15 @@ use tokio::io::AsyncWrite; use ::{bytes::Bytes, tokio::stream::Stream}; #[cfg(feature = "unstable-stream")] -use crate::network::download_file_stream; -use crate::{bot::Bot, network::download_file, DownloadError}; +use crate::net::download_file_stream; +use crate::{bot::Bot, net::download_file, DownloadError}; impl Bot { /// Download a file from Telegram into `destination`. - /// `path` can be obtained from [`get_file`] method. /// - /// For downloading as Stream of Chunks see [`download_file_stream`]. + /// `path` can be obtained from [`Bot::get_file`]. + /// + /// To download as a stream of chunks, see [`Bot::download_file_stream`]. /// /// ## Examples /// @@ -30,8 +31,8 @@ impl Bot { /// # Ok(()) } /// ``` /// - /// [`get_file`]: crate::Bot::get_file - /// [`download_file_stream`]: crate::Bot::download_file_stream + /// [`Bot::get_file`]: crate::Bot::get_file + /// [`Bot::download_file_stream`]: crate::Bot::download_file_stream pub async fn download_file( &self, path: &str, @@ -45,15 +46,15 @@ impl Bot { /// Download a file from Telegram. /// - /// `path` can be obtained from the [`get_file`] method. + /// `path` can be obtained from the [`Bot::get_file`]. /// - /// For downloading into [`AsyncWrite`] (e.g. [`tokio::fs::File`]) - /// see [`download_file`]. + /// To download into [`AsyncWrite`] (e.g. [`tokio::fs::File`]), see + /// [`Bot::download_file`]. /// - /// [`get_file`]: crate::bot::Bot::get_file + /// [`Bot::get_file`]: crate::bot::Bot::get_file /// [`AsyncWrite`]: tokio::io::AsyncWrite /// [`tokio::fs::File`]: tokio::fs::File - /// [`download_file`]: crate::Bot::download_file + /// [`Bot::download_file`]: crate::Bot::download_file #[cfg(feature = "unstable-stream")] pub async fn download_file_stream( &self, diff --git a/src/dispatching/filters/command.rs b/src/dispatching/filters/command.rs deleted file mode 100644 index b807050a..00000000 --- a/src/dispatching/filters/command.rs +++ /dev/null @@ -1,110 +0,0 @@ -use crate::{dispatching::Filter, types::Message}; - -pub struct CommandFilter { - command: String, -} - -impl Filter for CommandFilter { - fn test(&self, value: &Message) -> bool { - match value.text() { - Some(text) => match text.split_whitespace().next() { - Some(command) => self.command == command, - None => false, - }, - None => false, - } - } -} - -impl CommandFilter { - pub fn new(command: T) -> Self - where - T: Into, - { - Self { - command: '/'.to_string() + &command.into(), - } - } - pub fn with_prefix(command: T, prefix: T) -> Self - where - T: Into, - { - Self { - command: prefix.into() + &command.into(), - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::types::{ - Chat, ChatKind, ForwardKind, MediaKind, MessageKind, Sender, User, - }; - - #[test] - fn commands_are_equal() { - let filter = CommandFilter::new("command".to_string()); - let message = create_message_with_text("/command".to_string()); - assert!(filter.test(&message)); - } - - #[test] - fn commands_are_not_equal() { - let filter = CommandFilter::new("command".to_string()); - let message = - create_message_with_text("/not_equal_command".to_string()); - assert_eq!(filter.test(&message), false); - } - - #[test] - fn command_have_args() { - let filter = CommandFilter::new("command".to_string()); - let message = - create_message_with_text("/command arg1 arg2".to_string()); - assert!(filter.test(&message)); - } - - #[test] - fn message_have_only_whitespace() { - let filter = CommandFilter::new("command".to_string()); - let message = create_message_with_text(" ".to_string()); - assert_eq!(filter.test(&message), false); - } - - fn create_message_with_text(text: String) -> Message { - Message { - id: 0, - date: 0, - chat: Chat { - id: 0, - kind: ChatKind::Private { - type_: (), - username: None, - first_name: None, - last_name: None, - }, - photo: None, - }, - kind: MessageKind::Common { - from: Sender::User(User { - id: 0, - is_bot: false, - first_name: "".to_string(), - last_name: None, - username: None, - language_code: None, - }), - forward_kind: ForwardKind::Origin { - reply_to_message: None, - }, - edit_date: None, - media_kind: MediaKind::Text { - text, - entities: vec![], - }, - reply_markup: None, - }, - } - } -} diff --git a/src/dispatching/filters/main.rs b/src/dispatching/filters/main.rs deleted file mode 100644 index 1a3b9b19..00000000 --- a/src/dispatching/filters/main.rs +++ /dev/null @@ -1,379 +0,0 @@ -/// Filter that determines that particular event -/// is suitable for particular handler. -pub trait Filter { - /// Passes (return true) if event is suitable (otherwise return false) - fn test(&self, value: &T) -> bool; -} - -/// ``` -/// use teloxide::dispatching::filters::Filter; -/// -/// let closure = |i: &i32| -> bool { *i >= 42 }; -/// assert!(closure.test(&42)); -/// assert!(closure.test(&100)); -/// -/// assert_eq!(closure.test(&41), false); -/// assert_eq!(closure.test(&0), false); -/// ``` -impl bool> Filter for F { - fn test(&self, value: &T) -> bool { - (self)(value) - } -} - -/// ``` -/// use teloxide::dispatching::filters::Filter; -/// -/// assert!(true.test(&())); -/// assert_eq!(false.test(&()), false); -/// ``` -impl Filter for bool { - fn test(&self, _: &T) -> bool { - *self - } -} - -/// And filter. -/// -/// Passes if both underlying filters pass. -/// -/// **NOTE**: if one of filters don't pass -/// it is **not** guaranteed that other will be executed. -/// -/// ## Examples -/// ``` -/// use teloxide::dispatching::filters::{And, Filter}; -/// -/// // Note: bool can be treated as `Filter` that always return self. -/// assert_eq!(And::new(true, false).test(&()), false); -/// assert_eq!(And::new(true, false).test(&()), false); -/// assert!(And::new(true, true).test(&())); -/// assert!(And::new(true, And::new(|_: &()| true, true)).test(&())); -/// ``` -#[derive(Debug, Clone, Copy)] -pub struct And(A, B); - -impl And { - pub fn new(a: A, b: B) -> Self { - And(a, b) - } -} - -impl Filter for And -where - A: Filter, - B: Filter, -{ - fn test(&self, value: &T) -> bool { - self.0.test(value) && self.1.test(value) - } -} - -/// Alias for [`And::new`] -/// -/// ## Examples -/// ``` -/// use teloxide::dispatching::filters::{and, Filter}; -/// -/// assert!(and(true, true).test(&())); -/// assert_eq!(and(true, false).test(&()), false); -/// ``` -/// -/// [`And::new`]: crate::dispatching::filters::And::new -pub fn and(a: A, b: B) -> And { - And::new(a, b) -} - -/// Or filter. -/// -/// Passes if at least one underlying filters passes. -/// -/// **NOTE**: if one of filters passes -/// it is **not** guaranteed that other will be executed. -/// -/// ## Examples -/// ``` -/// use teloxide::dispatching::filters::{Filter, Or}; -/// -/// // Note: bool can be treated as `Filter` that always return self. -/// assert!(Or::new(true, false).test(&())); -/// assert!(Or::new(false, true).test(&())); -/// assert!(Or::new(false, Or::new(|_: &()| true, false)).test(&())); -/// assert_eq!(Or::new(false, false).test(&()), false); -/// ``` -#[derive(Debug, Clone, Copy)] -pub struct Or(A, B); - -impl Or { - pub fn new(a: A, b: B) -> Self { - Or(a, b) - } -} - -impl Filter for Or -where - A: Filter, - B: Filter, -{ - fn test(&self, value: &T) -> bool { - self.0.test(value) || self.1.test(value) - } -} - -/// Alias for [`Or::new`] -/// -/// ## Examples -/// ``` -/// use teloxide::dispatching::filters::{or, Filter}; -/// -/// assert!(or(true, false).test(&())); -/// assert_eq!(or(false, false).test(&()), false); -/// ``` -/// -/// [`Or::new`]: crate::dispatching::filters::Or::new -pub fn or(a: A, b: B) -> Or { - Or::new(a, b) -} - -/// Not filter. -/// -/// Passes if underlying filter don't pass. -/// -/// ## Examples -/// ``` -/// use teloxide::dispatching::filters::{Filter, Not}; -/// -/// // Note: bool can be treated as `Filter` that always return self. -/// assert!(Not::new(false).test(&())); -/// assert_eq!(Not::new(true).test(&()), false); -/// ``` -#[derive(Debug, Clone, Copy)] -pub struct Not(A); - -impl Not { - pub fn new(a: A) -> Self { - Not(a) - } -} - -impl Filter for Not -where - A: Filter, -{ - fn test(&self, value: &T) -> bool { - !self.0.test(value) - } -} - -/// Alias for [`Not::new`] -/// -/// ## Examples -/// ``` -/// use teloxide::dispatching::filters::{not, Filter}; -/// -/// assert!(not(false).test(&())); -/// assert_eq!(not(true).test(&()), false); -/// ``` -/// -/// [`Not::new`]: crate::dispatching::filters::Not::new -pub fn not(a: A) -> Not { - Not::new(a) -} - -/// Return [filter] that passes if and only if all of the given filters passes. -/// -/// **NOTE**: if one of filters don't pass -/// it is **not** guaranteed that other will be executed. -/// -/// ## Examples -/// ``` -/// use teloxide::{all, dispatching::filters::Filter}; -/// -/// assert!(all![true].test(&())); -/// assert!(all![true, true].test(&())); -/// assert!(all![true, true, true].test(&())); -/// -/// assert_eq!(all![false].test(&()), false); -/// assert_eq!(all![true, false].test(&()), false); -/// assert_eq!(all![false, true].test(&()), false); -/// assert_eq!(all![false, false].test(&()), false); -/// ``` -/// -/// [filter]: crate::dispatching::filters::Filter -#[macro_export] -macro_rules! all { - ($one:expr) => { $one }; - ($head:expr, $($tail:tt)+) => { - $crate::dispatching::filters::And::new( - $head, - $crate::all!($($tail)+) - ) - }; -} - -/// Return [filter] that passes if any of the given filters passes. -/// -/// **NOTE**: if one of filters passes -/// it is **not** guaranteed that other will be executed. -/// -/// ## Examples -/// ``` -/// use teloxide::{any, dispatching::filters::Filter}; -/// -/// assert!(any![true].test(&())); -/// assert!(any![true, true].test(&())); -/// assert!(any![false, true].test(&())); -/// assert!(any![true, false, true].test(&())); -/// -/// assert_eq!(any![false].test(&()), false); -/// assert_eq!(any![false, false].test(&()), false); -/// assert_eq!(any![false, false, false].test(&()), false); -/// ``` -/// -/// [filter]: crate::dispatching::filters::Filter -#[macro_export] -macro_rules! any { - ($one:expr) => { $one }; - ($head:expr, $($tail:tt)+) => { - $crate::dispatching::filters::Or::new( - $head, - $crate::all!($($tail)+) - ) - }; -} - -/// Simple wrapper around `Filter` that adds `|` and `&` operators. -/// -/// ## Examples -/// ``` -/// use teloxide::dispatching::filters::{f, And, Filter, Or, F}; -/// -/// let flt1 = |i: &i32| -> bool { *i > 17 }; -/// let flt2 = |i: &i32| -> bool { *i < 42 }; -/// let flt3 = |i: &i32| -> bool { *i % 2 == 0 }; -/// -/// let and = f(flt1) & flt2; -/// assert!(and.test(&19)); // both filters pass -/// -/// assert_eq!(and.test(&50), false); // `flt2` doesn't pass -/// assert_eq!(and.test(&16), false); // `flt1` doesn't pass -/// -/// let or = f(flt1) | flt3; -/// assert!(or.test(&19)); // `flt1` passes -/// assert!(or.test(&16)); // `flt2` passes -/// assert!(or.test(&20)); // both pass -/// -/// assert_eq!(or.test(&17), false); // both don't pass -/// -/// // Note: only first filter in chain should be wrapped in `f(...)` -/// let complicated: F, _>> = f(flt1) & flt2 | flt3; -/// assert!(complicated.test(&2)); // `flt3` passes -/// assert!(complicated.test(&21)); // `flt1` and `flt2` pass -/// -/// assert_eq!(complicated.test(&15), false); // `flt1` and `flt3` don't pass -/// assert_eq!(complicated.test(&43), false); // `flt2` and `flt3` don't pass -/// ``` -pub struct F(A); - -/// Constructor fn for [F] -/// -/// [F]: crate::dispatching::filters::F; -pub fn f(a: A) -> F { - F(a) -} - -impl Filter for F -where - A: Filter, -{ - fn test(&self, value: &T) -> bool { - self.0.test(value) - } -} - -impl std::ops::BitAnd for F { - type Output = F>; - - fn bitand(self, other: B) -> Self::Output { - f(and(self.0, other)) - } -} - -impl std::ops::BitOr for F { - type Output = F>; - - fn bitor(self, other: B) -> Self::Output { - f(or(self.0, other)) - } -} - -/* workaround for `E0207` compiler error */ -/// Extensions for filters -pub trait FilterExt { - /// Alias for [`Not::new`] - /// - /// ## Examples - /// ``` - /// use teloxide::dispatching::filters::{Filter, FilterExt}; - /// - /// let flt = |i: &i32| -> bool { *i > 0 }; - /// let flt = flt.not(); - /// assert!(flt.test(&-1)); - /// assert_eq!(flt.test(&1), false); - /// ``` - /// - /// [`Not::new`]: crate::dispatching::filters::Not::new - fn not(self) -> Not - where - Self: Sized, - { - Not::new(self) - } - - /// Alias for [`And::new`] - /// - /// ## Examples - /// ``` - /// use teloxide::dispatching::filters::{Filter, FilterExt}; - /// - /// let flt = |i: &i32| -> bool { *i > 0 }; - /// let flt = flt.and(|i: &i32| *i < 42); - /// - /// assert!(flt.test(&1)); - /// assert_eq!(flt.test(&-1), false); - /// assert_eq!(flt.test(&43), false); - /// ``` - /// - /// [`Not::new`]: crate::dispatching::filters::And::new - fn and(self, other: B) -> And - where - Self: Sized, - { - And::new(self, other) - } - - /// Alias for [`Or::new`] - /// - /// ## Examples - /// ``` - /// use teloxide::dispatching::filters::{Filter, FilterExt}; - /// - /// let flt = |i: &i32| -> bool { *i < 0 }; - /// let flt = flt.or(|i: &i32| *i > 42); - /// - /// assert!(flt.test(&-1)); - /// assert!(flt.test(&43)); - /// assert_eq!(flt.test(&17), false); - /// ``` - /// - /// [`Not::new`]: crate::dispatching::filters::Or::new - fn or(self, other: B) -> Or - where - Self: Sized, - { - Or::new(self, other) - } -} - -// All methods implemented via defaults -impl FilterExt for F where F: Filter {} diff --git a/src/dispatching/filters/message_caption.rs b/src/dispatching/filters/message_caption.rs deleted file mode 100644 index 02255bc6..00000000 --- a/src/dispatching/filters/message_caption.rs +++ /dev/null @@ -1,100 +0,0 @@ -use crate::{dispatching::Filter, types::Message}; - -/// Filter which compare caption of media with another text. -/// Returns true if the caption of media is equal to another text, otherwise -/// false. -/// -/// NOTE: filter compares only caption of media, does not compare text of -/// message! -/// -/// If you want to compare text of message use -/// [MessageTextFilter] -/// -/// If you want to compare text and caption use -/// [MessageTextCaptionFilter] -/// -/// [MessageTextFilter]: crate::dispatching::filters::MessageTextFilter -/// [MessageTextCaptionFilter]: -/// crate::dispatching::filters::MessageTextCaptionFilter -pub struct MessageCaptionFilter { - text: String, -} - -impl Filter for MessageCaptionFilter { - fn test(&self, value: &Message) -> bool { - match value.caption() { - Some(caption) => self.text == caption, - None => false, - } - } -} - -impl MessageCaptionFilter { - pub fn new(text: T) -> Self - where - T: Into, - { - Self { text: text.into() } - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::types::{ - Chat, ChatKind, ForwardKind, MediaKind, MessageKind, Sender, User, - }; - - #[test] - fn captions_are_equal() { - let filter = MessageCaptionFilter::new("caption".to_string()); - let message = create_message_with_caption("caption".to_string()); - assert!(filter.test(&message)); - } - - #[test] - fn captions_are_not_equal() { - let filter = MessageCaptionFilter::new("caption".to_string()); - let message = - create_message_with_caption("not equal caption".to_string()); - assert_eq!(filter.test(&message), false); - } - - fn create_message_with_caption(caption: String) -> Message { - Message { - id: 0, - date: 0, - chat: Chat { - id: 0, - kind: ChatKind::Private { - type_: (), - username: None, - first_name: None, - last_name: None, - }, - photo: None, - }, - kind: MessageKind::Common { - from: Sender::User(User { - id: 0, - is_bot: false, - first_name: "".to_string(), - last_name: None, - username: None, - language_code: None, - }), - forward_kind: ForwardKind::Origin { - reply_to_message: None, - }, - edit_date: None, - media_kind: MediaKind::Photo { - photo: vec![], - caption: Some(caption), - caption_entities: vec![], - media_group_id: None, - }, - reply_markup: None, - }, - } - } -} diff --git a/src/dispatching/filters/message_text.rs b/src/dispatching/filters/message_text.rs deleted file mode 100644 index e713d9bc..00000000 --- a/src/dispatching/filters/message_text.rs +++ /dev/null @@ -1,95 +0,0 @@ -use crate::{dispatching::Filter, types::Message}; - -/// Filter which compare message text with another text. -/// Returns true if the message text is equal to another text, otherwise false. -/// -/// NOTE: filter compares only text message, does not compare caption of media! -/// -/// If you want to compare caption use -/// [MessageCaptionFilter] -/// -/// If you want to compare text and caption use -/// [MessageTextCaptionFilter] -/// -/// [MessageCaptionFilter]: crate::dispatching::filters::MessageCaptionFilter -/// [MessageTextCaptionFilter]: -/// crate::dispatching::filters::MessageTextCaptionFilter -pub struct MessageTextFilter { - text: String, -} - -impl Filter for MessageTextFilter { - fn test(&self, value: &Message) -> bool { - match value.text() { - Some(text) => self.text == text, - None => false, - } - } -} - -impl MessageTextFilter { - pub fn new(text: T) -> Self - where - T: Into, - { - Self { text: text.into() } - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::types::{ - Chat, ChatKind, ForwardKind, MediaKind, MessageKind, Sender, User, - }; - - #[test] - fn texts_are_equal() { - let filter = MessageTextFilter::new("text"); - let message = create_message_with_text("text".to_string()); - assert!(filter.test(&message)); - } - - #[test] - fn texts_are_not_equal() { - let filter = MessageTextFilter::new("text"); - let message = create_message_with_text("not equal text".to_string()); - assert_eq!(filter.test(&message), false); - } - - fn create_message_with_text(text: String) -> Message { - Message { - id: 0, - date: 0, - chat: Chat { - id: 0, - kind: ChatKind::Private { - type_: (), - username: None, - first_name: None, - last_name: None, - }, - photo: None, - }, - kind: MessageKind::Common { - from: Sender::User(User { - id: 0, - is_bot: false, - first_name: "".to_string(), - last_name: None, - username: None, - language_code: None, - }), - forward_kind: ForwardKind::Origin { - reply_to_message: None, - }, - edit_date: None, - media_kind: MediaKind::Text { - text, - entities: vec![], - }, - reply_markup: None, - }, - } - } -} diff --git a/src/dispatching/filters/message_text_caption.rs b/src/dispatching/filters/message_text_caption.rs deleted file mode 100644 index eabcfb71..00000000 --- a/src/dispatching/filters/message_text_caption.rs +++ /dev/null @@ -1,152 +0,0 @@ -use crate::{dispatching::Filter, types::Message}; - -/// Filter which compare message text or caption of media with another text. -/// Returns true if the message text or caption of media is equal to another -/// text, otherwise false. -/// -/// NOTE: filter compares text of message or if it is not exists, compares -/// caption of the message! -/// -/// If you want to compare only caption use -/// [MessageCaptionFilter] -/// -/// If you want to compare only text use -/// [MessageTextFilter] -/// -/// [MessageCaptionFilter]: crate::dispatching::filters::MessageCaptionFilter -/// [MessageTextFilter]: crate::dispatching::filters::MessageTextFilter -pub struct MessageTextCaptionFilter { - text: String, -} - -impl Filter for MessageTextCaptionFilter { - fn test(&self, value: &Message) -> bool { - match value.text() { - Some(text) => self.text == text, - None => match value.caption() { - Some(caption) => self.text == caption, - None => false, - }, - } - } -} - -impl MessageTextCaptionFilter { - pub fn new(text: T) -> Self - where - T: Into, - { - Self { text: text.into() } - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::types::{ - Chat, ChatKind, ForwardKind, MediaKind, MessageKind, Sender, User, - }; - - #[test] - fn texts_are_equal() { - let filter = MessageTextCaptionFilter::new("text"); - let message = create_message_with_text("text".to_string()); - assert!(filter.test(&message)); - } - - #[test] - fn texts_are_not_equal() { - let filter = MessageTextCaptionFilter::new("text"); - let message = create_message_with_text("not equal text".to_string()); - assert_eq!(filter.test(&message), false); - } - - fn create_message_with_text(text: String) -> Message { - Message { - id: 0, - date: 0, - chat: Chat { - id: 0, - kind: ChatKind::Private { - type_: (), - username: None, - first_name: None, - last_name: None, - }, - photo: None, - }, - kind: MessageKind::Common { - from: Sender::User(User { - id: 0, - is_bot: false, - first_name: "".to_string(), - last_name: None, - username: None, - language_code: None, - }), - forward_kind: ForwardKind::Origin { - reply_to_message: None, - }, - edit_date: None, - media_kind: MediaKind::Text { - text, - entities: vec![], - }, - reply_markup: None, - }, - } - } - - #[test] - fn captions_are_equal() { - let filter = MessageTextCaptionFilter::new("caption".to_string()); - let message = create_message_with_caption("caption".to_string()); - assert!(filter.test(&message)); - } - - #[test] - fn captions_are_not_equal() { - let filter = MessageTextCaptionFilter::new("caption".to_string()); - let message = - create_message_with_caption("not equal caption".to_string()); - assert_eq!(filter.test(&message), false); - } - - fn create_message_with_caption(caption: String) -> Message { - Message { - id: 0, - date: 0, - chat: Chat { - id: 0, - kind: ChatKind::Private { - type_: (), - username: None, - first_name: None, - last_name: None, - }, - photo: None, - }, - kind: MessageKind::Common { - from: Sender::User(User { - id: 0, - is_bot: false, - first_name: "".to_string(), - last_name: None, - username: None, - language_code: None, - }), - forward_kind: ForwardKind::Origin { - reply_to_message: None, - }, - edit_date: None, - media_kind: MediaKind::Photo { - photo: vec![], - caption: Some(caption), - caption_entities: vec![], - media_group_id: None, - }, - reply_markup: None, - }, - } - } -} diff --git a/src/dispatching/filters/mod.rs b/src/dispatching/filters/mod.rs deleted file mode 100644 index 4f8207a8..00000000 --- a/src/dispatching/filters/mod.rs +++ /dev/null @@ -1,15 +0,0 @@ -//! Filters of messages. - -pub use main::*; - -pub use command::*; -pub use message_caption::*; -pub use message_text::*; -pub use message_text_caption::*; - -mod main; - -mod command; -mod message_caption; -mod message_text; -mod message_text_caption; diff --git a/src/dispatching/mod.rs b/src/dispatching/mod.rs index 70d1e0c4..cfd4f87b 100644 --- a/src/dispatching/mod.rs +++ b/src/dispatching/mod.rs @@ -8,9 +8,7 @@ pub enum DispatchResult { } pub mod chat; -pub mod filters; mod handler; pub mod update_listeners; -pub use filters::Filter; pub use handler::*; diff --git a/src/lib.rs b/src/lib.rs index d3af8108..69cf82fe 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -8,7 +8,7 @@ pub use bot::Bot; pub use errors::{ApiErrorKind, DownloadError, RequestError}; mod errors; -mod network; +mod net; mod bot; pub mod dispatching; diff --git a/src/network/download.rs b/src/net/download.rs similarity index 100% rename from src/network/download.rs rename to src/net/download.rs diff --git a/src/network/mod.rs b/src/net/mod.rs similarity index 100% rename from src/network/mod.rs rename to src/net/mod.rs diff --git a/src/network/request.rs b/src/net/request.rs similarity index 100% rename from src/network/request.rs rename to src/net/request.rs diff --git a/src/network/telegram_response.rs b/src/net/telegram_response.rs similarity index 100% rename from src/network/telegram_response.rs rename to src/net/telegram_response.rs diff --git a/src/requests/all/add_sticker_to_set.rs b/src/requests/all/add_sticker_to_set.rs index 7dc37e50..760f4b54 100644 --- a/src/requests/all/add_sticker_to_set.rs +++ b/src/requests/all/add_sticker_to_set.rs @@ -1,33 +1,23 @@ use crate::{ - network, + net, requests::form_builder::FormBuilder, types::{InputFile, MaskPosition, True}, Bot, }; +use super::BotWrapper; use crate::requests::{Request, ResponseResult}; -/// Use this method to add a new sticker to a set created by the bot. Returns -/// True on success. -#[derive(Debug, Clone)] +/// Use this method to add a new sticker to a set created by the bot. +/// +/// [The official docs](https://core.telegram.org/bots/api#addstickertoset). +#[derive(PartialEq, Debug, Clone)] pub struct AddStickerToSet<'a> { - bot: &'a Bot, - - /// User identifier of sticker set owner + bot: BotWrapper<'a>, user_id: i32, - /// Sticker set name name: String, - /// Png image with the sticker, must be up to 512 kilobytes in size, - /// dimensions must not exceed 512px, and either width or height must be - /// exactly 512px. Pass a file_id as a String to send a file that already - /// exists on the Telegram servers, pass an HTTP URL as a String for - /// Telegram to get a file from the Internet, or upload a new one using - /// multipart/form-data. More info on Sending Files » png_sticker: InputFile, - /// One or more emoji corresponding to the sticker emojis: String, - /// A JSON-serialized object for position where the mask should be placed - /// on faces mask_position: Option, } @@ -36,7 +26,7 @@ impl Request for AddStickerToSet<'_> { type Output = True; async fn send(&self) -> ResponseResult { - network::request_multipart( + net::request_multipart( self.bot.client(), self.bot.token(), "addStickerToSet", @@ -70,7 +60,7 @@ impl<'a> AddStickerToSet<'a> { E: Into, { Self { - bot, + bot: BotWrapper(bot), user_id, name: name.into(), png_sticker, @@ -79,11 +69,13 @@ impl<'a> AddStickerToSet<'a> { } } + /// User identifier of sticker set owner. pub fn user_id(mut self, val: i32) -> Self { self.user_id = val; self } + /// Sticker set name. pub fn name(mut self, val: T) -> Self where T: Into, @@ -92,11 +84,24 @@ impl<'a> AddStickerToSet<'a> { self } + /// **Png** image with the sticker, must be up to 512 kilobytes in size, + /// dimensions must not exceed 512px, and either width or height must be + /// exactly 512px. + /// + /// Pass [`InputFile::File`] to send a file that exists on + /// the Telegram servers (recommended), pass an [`InputFile::Url`] for + /// Telegram to get a .webp file from the Internet, or upload a new one + /// using [`InputFile::FileId`]. [More info on Sending Files »]. + /// + /// [`InputFile::File`]: crate::types::InputFile::File + /// [`InputFile::Url`]: crate::types::InputFile::Url + /// [`InputFile::FileId`]: crate::types::InputFile::FileId pub fn png_sticker(mut self, val: InputFile) -> Self { self.png_sticker = val; self } + /// One or more emoji corresponding to the sticker. pub fn emojis(mut self, val: T) -> Self where T: Into, @@ -105,6 +110,8 @@ impl<'a> AddStickerToSet<'a> { self } + /// A JSON-serialized object for position where the mask should be placed on + /// faces. pub fn mask_position(mut self, val: MaskPosition) -> Self { self.mask_position = Some(val); self diff --git a/src/requests/all/answer_callback_query.rs b/src/requests/all/answer_callback_query.rs index 77b1b7f5..38f0c856 100644 --- a/src/requests/all/answer_callback_query.rs +++ b/src/requests/all/answer_callback_query.rs @@ -1,42 +1,31 @@ use serde::Serialize; +use super::BotWrapper; use crate::{ - network, + net, requests::{Request, ResponseResult}, types::True, Bot, }; -/// Use this method to send answers to callback queries sent from inline -/// keyboards. The answer will be displayed to the user as a notification at the -/// top of the chat screen or as an alert. On success, True is -/// returned.Alternatively, the user can be redirected to the specified Game -/// URL. For this option to work, you must first create a game for your bot via -/// @Botfather and accept the terms. Otherwise, you may use links like -/// t.me/your_bot?start=XXXX that open your bot with a parameter. +/// Use this method to send answers to callback queries sent from [inline +/// keyboards]. +/// +/// The answer will be displayed to the user as a notification at +/// the top of the chat screen or as an alert. +/// +/// [The official docs](https://core.telegram.org/bots/api#answercallbackquery). +/// +/// [inline keyboards]: https://core.telegram.org/bots#inline-keyboards-and-on-the-fly-updating #[serde_with_macros::skip_serializing_none] -#[derive(Debug, Clone, Serialize)] +#[derive(Eq, PartialEq, Debug, Clone, Serialize)] pub struct AnswerCallbackQuery<'a> { #[serde(skip_serializing)] - bot: &'a Bot, - - /// Unique identifier for the query to be answered + bot: BotWrapper<'a>, callback_query_id: String, - /// Text of the notification. If not specified, nothing will be shown to - /// the user, 0-200 characters text: Option, - /// If true, an alert will be shown by the client instead of a notification - /// at the top of the chat screen. Defaults to false. show_alert: Option, - /// URL that will be opened by the user's client. If you have created a - /// Game and accepted the conditions via @Botfather, specify the URL that - /// opens your game – note that this will only work if the query comes from - /// a callback_game button.Otherwise, you may use links like - /// t.me/your_bot?start=XXXX that open your bot with a parameter. url: Option, - /// The maximum amount of time in seconds that the result of the callback - /// query may be cached client-side. Telegram apps will support caching - /// starting in version 3.14. Defaults to 0. cache_time: Option, } @@ -45,7 +34,7 @@ impl Request for AnswerCallbackQuery<'_> { type Output = True; async fn send(&self) -> ResponseResult { - network::request_json( + net::request_json( self.bot.client(), self.bot.token(), "answerCallbackQuery", @@ -62,7 +51,7 @@ impl<'a> AnswerCallbackQuery<'a> { { let callback_query_id = callback_query_id.into(); Self { - bot, + bot: BotWrapper(bot), callback_query_id, text: None, show_alert: None, @@ -71,6 +60,7 @@ impl<'a> AnswerCallbackQuery<'a> { } } + /// Unique identifier for the query to be answered. pub fn callback_query_id(mut self, val: T) -> Self where T: Into, @@ -79,6 +69,8 @@ impl<'a> AnswerCallbackQuery<'a> { self } + /// Text of the notification. If not specified, nothing will be shown to the + /// user, 0-200 characters. pub fn text(mut self, val: T) -> Self where T: Into, @@ -87,11 +79,24 @@ impl<'a> AnswerCallbackQuery<'a> { self } + /// If `true`, an alert will be shown by the client instead of a + /// notification at the top of the chat screen. Defaults to `false`. pub fn show_alert(mut self, val: bool) -> Self { self.show_alert = Some(val); self } + /// URL that will be opened by the user's client. If you have created a + /// [`Game`] and accepted the conditions via [@Botfather], specify the + /// URL that opens your game – note that this will only work if the + /// query comes from a [`callback_game`] button. + /// + /// Otherwise, you may use links like `t.me/your_bot?start=XXXX` that open + /// your bot with a parameter. + /// + /// [@Botfather]: https://t.me/botfather + /// [`callback_game`]: crate::types::InlineKeyboardButton + /// [`Game`]: crate::types::Game pub fn url(mut self, val: T) -> Self where T: Into, @@ -100,6 +105,9 @@ impl<'a> AnswerCallbackQuery<'a> { self } + /// The maximum amount of time in seconds that the result of the callback + /// query may be cached client-side. Telegram apps will support caching + /// starting in version 3.14. Defaults to 0. pub fn cache_time(mut self, val: i32) -> Self { self.cache_time = Some(val); self diff --git a/src/requests/all/answer_inline_query.rs b/src/requests/all/answer_inline_query.rs index 5cd7bfdb..1236423a 100644 --- a/src/requests/all/answer_inline_query.rs +++ b/src/requests/all/answer_inline_query.rs @@ -1,51 +1,29 @@ use serde::Serialize; +use super::BotWrapper; use crate::{ - network, + net, requests::{Request, ResponseResult}, types::{InlineQueryResult, True}, Bot, }; -/// Use this method to send answers to an inline query. On success, True is -/// returned.No more than 50 results per query are allowed. +/// Use this method to send answers to an inline query. +/// +/// No more than **50** results per query are allowed. +/// +/// [The official docs](https://core.telegram.org/bots/api#answerinlinequery). #[serde_with_macros::skip_serializing_none] -#[derive(Debug, Clone, Serialize)] +#[derive(PartialEq, Debug, Clone, Serialize)] pub struct AnswerInlineQuery<'a> { #[serde(skip_serializing)] - bot: &'a Bot, - - /// Unique identifier for the answered query + bot: BotWrapper<'a>, inline_query_id: String, - /// A JSON-serialized array of results for the inline query results: Vec, - /// The maximum amount of time in seconds that the result of the inline - /// query may be cached on the server. Defaults to 300. cache_time: Option, - /// Pass True, if results may be cached on the server side only for the - /// user that sent the query. By default, results may be returned to any - /// user who sends the same query is_personal: Option, - /// Pass the offset that a client should send in the next query with the - /// same text to receive more results. Pass an empty string if there are no - /// more results or if you don‘t support pagination. Offset length can’t - /// exceed 64 bytes. next_offset: Option, - /// If passed, clients will display a button with specified text that - /// switches the user to a private chat with the bot and sends the bot a - /// start message with the parameter switch_pm_parameter switch_pm_text: Option, - /// Deep-linking parameter for the /start message sent to the bot when user - /// presses the switch button. 1-64 characters, only A-Z, a-z, 0-9, _ and - - /// are allowed.Example: An inline bot that sends YouTube videos can ask - /// the user to connect the bot to their YouTube account to adapt search - /// results accordingly. To do this, it displays a ‘Connect your YouTube - /// account’ button above the results, or even before showing any. The user - /// presses the button, switches to a private chat with the bot and, in - /// doing so, passes a start parameter that instructs the bot to return an - /// oauth link. Once done, the bot can offer a switch_inline button so that - /// the user can easily return to the chat where they wanted to use the - /// bot's inline capabilities. switch_pm_parameter: Option, } @@ -54,7 +32,7 @@ impl Request for AnswerInlineQuery<'_> { type Output = True; async fn send(&self) -> ResponseResult { - network::request_json( + net::request_json( self.bot.client(), self.bot.token(), "answerInlineQuery", @@ -77,7 +55,7 @@ impl<'a> AnswerInlineQuery<'a> { let inline_query_id = inline_query_id.into(); let results = results.into(); Self { - bot, + bot: BotWrapper(bot), inline_query_id, results, cache_time: None, @@ -88,6 +66,7 @@ impl<'a> AnswerInlineQuery<'a> { } } + /// Unique identifier for the answered query. pub fn inline_query_id(mut self, val: T) -> Self where T: Into, @@ -96,6 +75,7 @@ impl<'a> AnswerInlineQuery<'a> { self } + /// A JSON-serialized array of results for the inline query. pub fn results(mut self, val: T) -> Self where T: Into>, @@ -104,17 +84,31 @@ impl<'a> AnswerInlineQuery<'a> { self } + /// The maximum amount of time in seconds that the result of the inline + /// query may be cached on the server. + /// + /// Defaults to 300. pub fn cache_time(mut self, val: i32) -> Self { self.cache_time = Some(val); self } + /// Pass `true`, if results may be cached on the server side only for the + /// user that sent the query. + /// + /// By default, results may be returned to any user who sends the same + /// query. #[allow(clippy::wrong_self_convention)] pub fn is_personal(mut self, val: bool) -> Self { self.is_personal = Some(val); self } + /// Pass the offset that a client should send in the next query with the + /// same text to receive more results. + /// + /// Pass an empty string if there are no more results or if you don‘t + /// support pagination. Offset length can’t exceed 64 bytes. pub fn next_offset(mut self, val: T) -> Self where T: Into, @@ -123,6 +117,12 @@ impl<'a> AnswerInlineQuery<'a> { self } + /// If passed, clients will display a button with specified text that + /// switches the user to a private chat with the bot and sends the bot a + /// start message with the parameter [`switch_pm_parameter`]. + /// + /// [`switch_pm_parameter`]: + /// crate::requests::AnswerInlineQuery::switch_pm_parameter pub fn switch_pm_text(mut self, val: T) -> Self where T: Into, @@ -131,6 +131,22 @@ impl<'a> AnswerInlineQuery<'a> { self } + /// [Deep-linking] parameter for the /start message sent to the bot when + /// user presses the switch button. 1-64 characters, only `A-Z`, `a-z`, + /// `0-9`, `_` and `-` are allowed. + /// + /// Example: An inline bot that sends YouTube videos can ask the user to + /// connect the bot to their YouTube account to adapt search results + /// accordingly. To do this, it displays a ‘Connect your YouTube account’ + /// button above the results, or even before showing any. The user presses + /// the button, switches to a private chat with the bot and, in doing so, + /// passes a start parameter that instructs the bot to return an oauth link. + /// Once done, the bot can offer a [`switch_inline`] button so that the user + /// can easily return to the chat where they wanted to use the bot's + /// inline capabilities. + /// + /// [Deep-linking]: https://core.telegram.org/bots#deep-linking + /// [`switch_inline`]: crate::types::InlineKeyboardMarkup pub fn switch_pm_parameter(mut self, val: T) -> Self where T: Into, diff --git a/src/requests/all/answer_pre_checkout_query.rs b/src/requests/all/answer_pre_checkout_query.rs index d1760ebb..8d8dd0fb 100644 --- a/src/requests/all/answer_pre_checkout_query.rs +++ b/src/requests/all/answer_pre_checkout_query.rs @@ -1,35 +1,29 @@ use serde::Serialize; +use super::BotWrapper; use crate::{ - network, + net, requests::{Request, ResponseResult}, types::True, Bot, }; /// Once the user has confirmed their payment and shipping details, the Bot API -/// sends the final confirmation in the form of an Update with the field -/// pre_checkout_query. Use this method to respond to such pre-checkout queries. -/// On success, True is returned. Note: The Bot API must receive an answer -/// within 10 seconds after the pre-checkout query was sent. +/// sends the final confirmation in the form of an [`Update`] with the field +/// `pre_checkout_query`. Use this method to respond to such pre-checkout +/// queries. Note: The Bot API must receive an answer within 10 seconds after +/// the pre-checkout query was sent. +/// +/// [The official docs](https://core.telegram.org/bots/api#answerprecheckoutquery). +/// +/// [`Update`]: crate::types::Update #[serde_with_macros::skip_serializing_none] -#[derive(Debug, Clone, Serialize)] +#[derive(Eq, PartialEq, Debug, Clone, Serialize)] pub struct AnswerPreCheckoutQuery<'a> { #[serde(skip_serializing)] - bot: &'a Bot, - - /// Unique identifier for the query to be answered + bot: BotWrapper<'a>, pre_checkout_query_id: String, - /// Specify True if everything is alright (goods are available, etc.) and - /// the bot is ready to proceed with the order. Use False if there are any - /// problems. ok: bool, - /// Required if ok is False. Error message in human readable form that - /// explains the reason for failure to proceed with the checkout (e.g. - /// "Sorry, somebody just bought the last of our amazing black T-shirts - /// while you were busy filling out your payment details. Please choose a - /// different color or garment!"). Telegram will display this message to - /// the user. error_message: Option, } @@ -38,7 +32,7 @@ impl Request for AnswerPreCheckoutQuery<'_> { type Output = True; async fn send(&self) -> ResponseResult { - network::request_json( + net::request_json( self.bot.client(), self.bot.token(), "answerPreCheckoutQuery", @@ -59,13 +53,14 @@ impl<'a> AnswerPreCheckoutQuery<'a> { { let pre_checkout_query_id = pre_checkout_query_id.into(); Self { - bot, + bot: BotWrapper(bot), pre_checkout_query_id, ok, error_message: None, } } + /// Unique identifier for the query to be answered. pub fn pre_checkout_query_id(mut self, val: T) -> Self where T: Into, @@ -74,11 +69,21 @@ impl<'a> AnswerPreCheckoutQuery<'a> { self } + /// Specify `true` if everything is alright (goods are available, etc.) and + /// the bot is ready to proceed with the order. Use False if there are any + /// problems. pub fn ok(mut self, val: bool) -> Self { self.ok = val; self } + /// Required if ok is `false`. Error message in human readable form that + /// explains the reason for failure to proceed with the checkout (e.g. + /// "Sorry, somebody just bought the last of our amazing black T-shirts + /// while you were busy filling out your payment details. Please choose a + /// different color or garment!"). + /// + /// Telegram will display this message to the user. pub fn error_message(mut self, val: T) -> Self where T: Into, diff --git a/src/requests/all/answer_shipping_query.rs b/src/requests/all/answer_shipping_query.rs index efe55b4d..45435362 100644 --- a/src/requests/all/answer_shipping_query.rs +++ b/src/requests/all/answer_shipping_query.rs @@ -1,35 +1,28 @@ use serde::Serialize; +use super::BotWrapper; use crate::{ - network, + net, requests::{Request, ResponseResult}, types::{ShippingOption, True}, Bot, }; - /// If you sent an invoice requesting a shipping address and the parameter -/// is_flexible was specified, the Bot API will send an Update with a +/// `is_flexible` was specified, the Bot API will send an [`Update`] with a /// shipping_query field to the bot. Use this method to reply to shipping -/// queries. On success, True is returned. +/// queries. +/// +/// [The official docs](https://core.telegram.org/bots/api#answershippingquery). +/// +/// [`Update`]: crate::types::Update #[serde_with_macros::skip_serializing_none] -#[derive(Debug, Clone, Serialize)] +#[derive(Eq, PartialEq, Debug, Clone, Serialize)] pub struct AnswerShippingQuery<'a> { #[serde(skip_serializing)] - bot: &'a Bot, - - /// Unique identifier for the query to be answered + bot: BotWrapper<'a>, shipping_query_id: String, - /// Specify True if delivery to the specified address is possible and False - /// if there are any problems (for example, if delivery to the specified - /// address is not possible) ok: bool, - /// Required if ok is True. A JSON-serialized array of available shipping - /// options. shipping_options: Option>, - /// Required if ok is False. Error message in human readable form that - /// explains why it is impossible to complete the order (e.g. "Sorry, - /// delivery to your desired address is unavailable'). Telegram will - /// display this message to the user. error_message: Option, } @@ -38,7 +31,7 @@ impl Request for AnswerShippingQuery<'_> { type Output = True; async fn send(&self) -> ResponseResult { - network::request_json( + net::request_json( self.bot.client(), self.bot.token(), "answerShippingQuery", @@ -55,7 +48,7 @@ impl<'a> AnswerShippingQuery<'a> { { let shipping_query_id = shipping_query_id.into(); Self { - bot, + bot: BotWrapper(bot), shipping_query_id, ok, shipping_options: None, @@ -63,6 +56,7 @@ impl<'a> AnswerShippingQuery<'a> { } } + /// Unique identifier for the query to be answered. pub fn shipping_query_id(mut self, val: T) -> Self where T: Into, @@ -71,11 +65,16 @@ impl<'a> AnswerShippingQuery<'a> { self } + /// Specify `true` if delivery to the specified address is possible and + /// `false` if there are any problems (for example, if delivery to the + /// specified address is not possible). pub fn ok(mut self, val: bool) -> Self { self.ok = val; self } + /// Required if ok is `true`. A JSON-serialized array of available shipping + /// options. pub fn shipping_options(mut self, val: T) -> Self where T: Into>, @@ -84,6 +83,11 @@ impl<'a> AnswerShippingQuery<'a> { self } + /// Required if ok is `false`. Error message in human readable form that + /// explains why it is impossible to complete the order (e.g. "Sorry, + /// delivery to your desired address is unavailable'). + /// + /// Telegram will display this message to the user. pub fn error_message(mut self, val: T) -> Self where T: Into, diff --git a/src/requests/all/bot_wrapper.rs b/src/requests/all/bot_wrapper.rs new file mode 100644 index 00000000..87857725 --- /dev/null +++ b/src/requests/all/bot_wrapper.rs @@ -0,0 +1,33 @@ +use crate::Bot; +use std::ops::Deref; + +/// A wrapper that implements `Clone`, Copy, `PartialEq`, `Eq`, `Debug`, but +/// performs no copying, cloning and comparison. +/// +/// Used in the requests bodies. +#[derive(Debug)] +pub struct BotWrapper<'a>(pub &'a Bot); + +impl PartialEq for BotWrapper<'_> { + fn eq(&self, other: &BotWrapper<'_>) -> bool { + self.0.token() == other.0.token() + } +} + +impl Eq for BotWrapper<'_> {} + +impl<'a> Clone for BotWrapper<'a> { + fn clone(&self) -> BotWrapper<'a> { + Self(self.0) + } +} + +impl Copy for BotWrapper<'_> {} + +impl Deref for BotWrapper<'_> { + type Target = Bot; + + fn deref(&self) -> &Bot { + &self.0 + } +} diff --git a/src/requests/all/create_new_sticker_set.rs b/src/requests/all/create_new_sticker_set.rs index 08bd82af..a72556f4 100644 --- a/src/requests/all/create_new_sticker_set.rs +++ b/src/requests/all/create_new_sticker_set.rs @@ -1,39 +1,24 @@ +use super::BotWrapper; use crate::{ - network, + net, requests::{form_builder::FormBuilder, Request, ResponseResult}, types::{InputFile, MaskPosition, True}, Bot, }; /// Use this method to create new sticker set owned by a user. The bot will be -/// able to edit the created sticker set. Returns True on success. -#[derive(Debug, Clone)] +/// able to edit the created sticker set. +/// +/// [The official docs](https://core.telegram.org/bots/api#createnewstickerset). +#[derive(PartialEq, Debug, Clone)] pub struct CreateNewStickerSet<'a> { - bot: &'a Bot, - - /// User identifier of created sticker set owner + bot: BotWrapper<'a>, user_id: i32, - /// Short name of sticker set, to be used in t.me/addstickers/ URLs (e.g., - /// animals). Can contain only english letters, digits and underscores. - /// Must begin with a letter, can't contain consecutive underscores and - /// must end in “_by_”. is case insensitive. - /// 1-64 characters. name: String, - /// Sticker set title, 1-64 characters title: String, - /// Png image with the sticker, must be up to 512 kilobytes in size, - /// dimensions must not exceed 512px, and either width or height must be - /// exactly 512px. Pass a file_id as a String to send a file that already - /// exists on the Telegram servers, pass an HTTP URL as a String for - /// Telegram to get a file from the Internet, or upload a new one using - /// multipart/form-data. More info on Sending Files » png_sticker: InputFile, - /// One or more emoji corresponding to the sticker emojis: String, - /// Pass True, if a set of mask stickers should be created contains_masks: Option, - /// A JSON-serialized object for position where the mask should be placed - /// on faces mask_position: Option, } @@ -42,7 +27,7 @@ impl Request for CreateNewStickerSet<'_> { type Output = True; async fn send(&self) -> ResponseResult { - network::request_multipart( + net::request_multipart( self.bot.client(), self.bot.token(), "createNewStickerSet", @@ -82,7 +67,7 @@ impl<'a> CreateNewStickerSet<'a> { E: Into, { Self { - bot, + bot: BotWrapper(bot), user_id, name: name.into(), title: title.into(), @@ -93,11 +78,18 @@ impl<'a> CreateNewStickerSet<'a> { } } + /// User identifier of created sticker set owner. pub fn user_id(mut self, val: i32) -> Self { self.user_id = val; self } + /// Short name of sticker set, to be used in `t.me/addstickers/` URLs (e.g., + /// animals). Can contain only english letters, digits and underscores. + /// + /// Must begin with a letter, can't contain consecutive underscores and must + /// end in `_by_`. `` is case insensitive. + /// 1-64 characters. pub fn name(mut self, val: T) -> Self where T: Into, @@ -106,6 +98,7 @@ impl<'a> CreateNewStickerSet<'a> { self } + /// Sticker set title, 1-64 characters. pub fn title(mut self, val: T) -> Self where T: Into, @@ -114,11 +107,24 @@ impl<'a> CreateNewStickerSet<'a> { self } + /// **Png** image with the sticker, must be up to 512 kilobytes in size, + /// dimensions must not exceed 512px, and either width or height must be + /// exactly 512px. + /// + /// Pass [`InputFile::File`] to send a file that exists on + /// the Telegram servers (recommended), pass an [`InputFile::Url`] for + /// Telegram to get a .webp file from the Internet, or upload a new one + /// using [`InputFile::FileId`]. [More info on Sending Files »]. + /// + /// [`InputFile::File`]: crate::types::InputFile::File + /// [`InputFile::Url`]: crate::types::InputFile::Url + /// [`InputFile::FileId`]: crate::types::InputFile::FileId pub fn png_sticker(mut self, val: InputFile) -> Self { self.png_sticker = val; self } + /// One or more emoji corresponding to the sticker. pub fn emojis(mut self, val: T) -> Self where T: Into, @@ -127,11 +133,14 @@ impl<'a> CreateNewStickerSet<'a> { self } + /// Pass `true`, if a set of mask stickers should be created. pub fn contains_masks(mut self, val: bool) -> Self { self.contains_masks = Some(val); self } + /// A JSON-serialized object for position where the mask should be placed on + /// faces. pub fn mask_position(mut self, val: MaskPosition) -> Self { self.mask_position = Some(val); self diff --git a/src/requests/all/delete_chat_photo.rs b/src/requests/all/delete_chat_photo.rs index 0d2fe447..af1b330e 100644 --- a/src/requests/all/delete_chat_photo.rs +++ b/src/requests/all/delete_chat_photo.rs @@ -1,7 +1,8 @@ use serde::Serialize; +use super::BotWrapper; use crate::{ - network, + net, requests::{Request, ResponseResult}, types::{ChatId, True}, Bot, @@ -9,15 +10,14 @@ use crate::{ /// Use this method to delete a chat photo. Photos can't be changed for private /// chats. The bot must be an administrator in the chat for this to work and -/// must have the appropriate admin rights. Returns True on success. +/// must have the appropriate admin rights. +/// +/// [The official docs](https://core.telegram.org/bots/api#deletechatphoto). #[serde_with_macros::skip_serializing_none] -#[derive(Debug, Clone, Serialize)] +#[derive(Eq, PartialEq, Debug, Clone, Serialize)] pub struct DeleteChatPhoto<'a> { #[serde(skip_serializing)] - bot: &'a Bot, - - /// Unique identifier for the target chat or username of the target channel - /// (in the format @channelusername) + bot: BotWrapper<'a>, chat_id: ChatId, } @@ -26,7 +26,7 @@ impl Request for DeleteChatPhoto<'_> { type Output = True; async fn send(&self) -> ResponseResult { - network::request_json( + net::request_json( self.bot.client(), self.bot.token(), "deleteChatPhoto", @@ -42,9 +42,14 @@ impl<'a> DeleteChatPhoto<'a> { C: Into, { let chat_id = chat_id.into(); - Self { bot, chat_id } + Self { + bot: BotWrapper(bot), + chat_id, + } } + /// Unique identifier for the target chat or username of the target channel + /// (in the format `@channelusername`). pub fn chat_id(mut self, val: T) -> Self where T: Into, diff --git a/src/requests/all/delete_chat_sticker_set.rs b/src/requests/all/delete_chat_sticker_set.rs index 1e26eb1f..b10962dc 100644 --- a/src/requests/all/delete_chat_sticker_set.rs +++ b/src/requests/all/delete_chat_sticker_set.rs @@ -1,25 +1,28 @@ use serde::Serialize; +use super::BotWrapper; use crate::{ - network, + net, requests::{Request, ResponseResult}, types::{ChatId, True}, Bot, }; -/// Use this method to delete a group sticker set from a supergroup. The bot -/// must be an administrator in the chat for this to work and must have the -/// appropriate admin rights. Use the field can_set_sticker_set optionally -/// returned in getChat requests to check if the bot can use this method. -/// Returns True on success. +/// Use this method to delete a group sticker set from a supergroup. +/// +/// The bot must be an administrator in the chat for this to work and must have +/// the appropriate admin rights. Use the field `can_set_sticker_set` optionally +/// returned in [`Bot::get_chat`] requests to check if the bot can use this +/// method. +/// +/// [The official docs](https://core.telegram.org/bots/api#deletechatstickerset). +/// +/// [`Bot::get_chat`]: crate::Bot::get_chat #[serde_with_macros::skip_serializing_none] -#[derive(Debug, Clone, Serialize)] +#[derive(Eq, PartialEq, Debug, Clone, Serialize)] pub struct DeleteChatStickerSet<'a> { #[serde(skip_serializing)] - bot: &'a Bot, - - /// Unique identifier for the target chat or username of the target - /// supergroup (in the format @supergroupusername) + bot: BotWrapper<'a>, chat_id: ChatId, } @@ -28,7 +31,7 @@ impl Request for DeleteChatStickerSet<'_> { type Output = True; async fn send(&self) -> ResponseResult { - network::request_json( + net::request_json( self.bot.client(), self.bot.token(), "deleteChatStickerSet", @@ -44,9 +47,14 @@ impl<'a> DeleteChatStickerSet<'a> { C: Into, { let chat_id = chat_id.into(); - Self { bot, chat_id } + Self { + bot: BotWrapper(bot), + chat_id, + } } + /// Unique identifier for the target chat or username of the target + /// supergroup (in the format `@supergroupusername`). pub fn chat_id(mut self, val: T) -> Self where T: Into, diff --git a/src/requests/all/delete_message.rs b/src/requests/all/delete_message.rs index 97625805..0dbb88c8 100644 --- a/src/requests/all/delete_message.rs +++ b/src/requests/all/delete_message.rs @@ -1,31 +1,34 @@ use serde::Serialize; +use super::BotWrapper; use crate::{ - network, + net, requests::{Request, ResponseResult}, types::{ChatId, True}, Bot, }; -/// Use this method to delete a message, including service messages, with the -/// following limitations:- A message can only be deleted if it was sent less -/// than 48 hours ago.- Bots can delete outgoing messages in private chats, -/// groups, and supergroups.- Bots can delete incoming messages in private -/// chats.- Bots granted can_post_messages permissions can delete outgoing -/// messages in channels.- If the bot is an administrator of a group, it can -/// delete any message there.- If the bot has can_delete_messages permission in -/// a supergroup or a channel, it can delete any message there.Returns True on -/// success. +/// Use this method to delete a message, including service messages. +/// +/// The limitations are: +/// - A message can only be deleted if it was sent less than 48 hours ago. +/// - Bots can delete outgoing messages in private chats, groups, and +/// supergroups. +/// - Bots can delete incoming messages in private chats. +/// - Bots granted can_post_messages permissions can delete outgoing messages +/// in channels. +/// - If the bot is an administrator of a group, it can delete any message +/// there. +/// - If the bot has can_delete_messages permission in a supergroup or a +/// channel, it can delete any message there. +/// +/// [The official docs](https://core.telegram.org/bots/api#deletemessage). #[serde_with_macros::skip_serializing_none] -#[derive(Debug, Clone, Serialize)] +#[derive(Eq, PartialEq, Debug, Clone, Serialize)] pub struct DeleteMessage<'a> { #[serde(skip_serializing)] - bot: &'a Bot, - - /// Unique identifier for the target chat or username of the target channel - /// (in the format @channelusername) + bot: BotWrapper<'a>, chat_id: ChatId, - /// Identifier of the message to delete message_id: i32, } @@ -34,7 +37,7 @@ impl Request for DeleteMessage<'_> { type Output = True; async fn send(&self) -> ResponseResult { - network::request_json( + net::request_json( self.bot.client(), self.bot.token(), "deleteMessage", @@ -51,12 +54,14 @@ impl<'a> DeleteMessage<'a> { { let chat_id = chat_id.into(); Self { - bot, + bot: BotWrapper(bot), chat_id, message_id, } } + /// Unique identifier for the target chat or username of the target channel + /// (in the format `@channelusername`). pub fn chat_id(mut self, val: T) -> Self where T: Into, @@ -65,6 +70,7 @@ impl<'a> DeleteMessage<'a> { self } + /// Identifier of the message to delete. pub fn message_id(mut self, val: i32) -> Self { self.message_id = val; self diff --git a/src/requests/all/delete_sticker_from_set.rs b/src/requests/all/delete_sticker_from_set.rs index 0b8eb12b..111622f1 100644 --- a/src/requests/all/delete_sticker_from_set.rs +++ b/src/requests/all/delete_sticker_from_set.rs @@ -1,21 +1,21 @@ use serde::Serialize; +use super::BotWrapper; use crate::{ - network, + net, requests::{Request, ResponseResult}, types::True, Bot, }; -/// Use this method to delete a sticker from a set created by the bot. Returns -/// True on success. +/// Use this method to delete a sticker from a set created by the bot. +/// +/// [The official docs](https://core.telegram.org/bots/api#deletestickerfromset). #[serde_with_macros::skip_serializing_none] -#[derive(Debug, Clone, Serialize)] +#[derive(Eq, PartialEq, Debug, Clone, Serialize)] pub struct DeleteStickerFromSet<'a> { #[serde(skip_serializing)] - bot: &'a Bot, - - /// File identifier of the sticker + bot: BotWrapper<'a>, sticker: String, } @@ -24,7 +24,7 @@ impl Request for DeleteStickerFromSet<'_> { type Output = True; async fn send(&self) -> ResponseResult { - network::request_json( + net::request_json( self.bot.client(), self.bot.token(), "deleteStickerFromSet", @@ -40,9 +40,13 @@ impl<'a> DeleteStickerFromSet<'a> { S: Into, { let sticker = sticker.into(); - Self { bot, sticker } + Self { + bot: BotWrapper(bot), + sticker, + } } + /// File identifier of the sticker. pub fn sticker(mut self, val: T) -> Self where T: Into, diff --git a/src/requests/all/delete_webhook.rs b/src/requests/all/delete_webhook.rs index e0aebc83..10511a1b 100644 --- a/src/requests/all/delete_webhook.rs +++ b/src/requests/all/delete_webhook.rs @@ -1,27 +1,33 @@ use serde::Serialize; +use super::BotWrapper; use crate::{ - network, + net, requests::{Request, ResponseResult}, types::True, Bot, }; /// Use this method to remove webhook integration if you decide to switch back -/// to getUpdates. Returns True on success. Requires no parameters. +/// to [Bot::get_updates]. +/// +/// [The official docs](https://core.telegram.org/bots/api#deletewebhook). +/// +/// [Bot::get_updates]: crate::Bot::get_updates #[serde_with_macros::skip_serializing_none] -#[derive(Debug, Clone, Serialize)] +#[derive(Copy, Eq, PartialEq, Debug, Clone, Serialize)] pub struct DeleteWebhook<'a> { #[serde(skip_serializing)] - bot: &'a Bot, + bot: BotWrapper<'a>, } #[async_trait::async_trait] impl Request for DeleteWebhook<'_> { type Output = True; + #[allow(clippy::trivially_copy_pass_by_ref)] async fn send(&self) -> ResponseResult { - network::request_json( + net::request_json( self.bot.client(), self.bot.token(), "deleteWebhook", @@ -33,6 +39,8 @@ impl Request for DeleteWebhook<'_> { impl<'a> DeleteWebhook<'a> { pub(crate) fn new(bot: &'a Bot) -> Self { - Self { bot } + Self { + bot: BotWrapper(bot), + } } } diff --git a/src/requests/all/edit_message_caption.rs b/src/requests/all/edit_message_caption.rs index 7e0b6328..e873d2dc 100644 --- a/src/requests/all/edit_message_caption.rs +++ b/src/requests/all/edit_message_caption.rs @@ -1,30 +1,31 @@ use serde::Serialize; +use super::BotWrapper; use crate::{ - network, + net, requests::{Request, ResponseResult}, types::{ChatOrInlineMessage, InlineKeyboardMarkup, Message, ParseMode}, Bot, }; -/// Use this method to edit captions of messages. On success, if edited message -/// is sent by the bot, the edited Message is returned, otherwise True is -/// returned. +/// Use this method to edit captions of messages. +/// +/// On success, if edited message is sent by the bot, the edited [`Message`] is +/// returned, otherwise [`True`] is returned. +/// +/// [The official docs](https://core.telegram.org/bots/api#editmessagecaption). +/// +/// [`Message`]: crate::types::Message +/// [`True`]: crate::types::True #[serde_with_macros::skip_serializing_none] -#[derive(Debug, Clone, Serialize)] +#[derive(Eq, PartialEq, Debug, Clone, Serialize)] pub struct EditMessageCaption<'a> { #[serde(skip_serializing)] - bot: &'a Bot, - + bot: BotWrapper<'a>, #[serde(flatten)] chat_or_inline_message: ChatOrInlineMessage, - - /// New caption of the message caption: Option, - /// Send Markdown or HTML, if you want Telegram apps to show bold, italic, - /// fixed-width text or inline URLs in the media caption. parse_mode: Option, - /// A JSON-serialized object for an inline keyboard. reply_markup: Option, } @@ -33,7 +34,7 @@ impl Request for EditMessageCaption<'_> { type Output = Message; async fn send(&self) -> ResponseResult { - network::request_json( + net::request_json( self.bot.client(), self.bot.token(), "editMessageCaption", @@ -49,7 +50,7 @@ impl<'a> EditMessageCaption<'a> { chat_or_inline_message: ChatOrInlineMessage, ) -> Self { Self { - bot, + bot: BotWrapper(bot), chat_or_inline_message, caption: None, parse_mode: None, @@ -62,6 +63,7 @@ impl<'a> EditMessageCaption<'a> { self } + /// New caption of the message. pub fn caption(mut self, val: T) -> Self where T: Into, @@ -70,11 +72,21 @@ impl<'a> EditMessageCaption<'a> { self } + /// Send [Markdown] or [HTML], if you want Telegram apps to show + /// [bold, italic, fixed-width text or inline URLs] in the media caption. + /// + /// [Markdown]: crate::types::ParseMode::Markdown + /// [HTML]: crate::types::ParseMode::HTML + /// [bold, italic, fixed-width text or inline URLs]: + /// crate::types::ParseMode pub fn parse_mode(mut self, val: ParseMode) -> Self { self.parse_mode = Some(val); self } + /// A JSON-serialized object for an [inline keyboard]. + /// + /// [inline keyboard]: https://core.telegram.org/bots#inline-keyboards-and-on-the-fly-updating pub fn reply_markup(mut self, val: InlineKeyboardMarkup) -> Self { self.reply_markup = Some(val); self diff --git a/src/requests/all/edit_message_live_location.rs b/src/requests/all/edit_message_live_location.rs index 982c38de..1362366c 100644 --- a/src/requests/all/edit_message_live_location.rs +++ b/src/requests/all/edit_message_live_location.rs @@ -1,30 +1,33 @@ use serde::Serialize; +use super::BotWrapper; use crate::{ - network, + net, requests::{Request, ResponseResult}, types::{ChatOrInlineMessage, InlineKeyboardMarkup, Message}, Bot, }; -/// Use this method to edit live location messages. A location can be edited -/// until its live_period expires or editing is explicitly disabled by a call to -/// stopMessageLiveLocation. On success, if the edited message was sent by the -/// bot, the edited Message is returned, otherwise True is returned. +/// Use this method to edit live location messages. +/// +/// A location can be edited until its live_period expires or editing is +/// explicitly disabled by a call to stopMessageLiveLocation. On success, if the +/// edited message was sent by the bot, the edited [`Message`] is returned, +/// otherwise [`True`] is returned. +/// +/// [The official docs](https://core.telegram.org/bots/api#editmessagelivelocation). +/// +/// [`Message`]: crate::types::Message +/// [`True`]: crate::types::True #[serde_with_macros::skip_serializing_none] -#[derive(Debug, Clone, Serialize)] +#[derive(PartialEq, Debug, Clone, Serialize)] pub struct EditMessageLiveLocation<'a> { #[serde(skip_serializing)] - bot: &'a Bot, - + bot: BotWrapper<'a>, #[serde(flatten)] chat_or_inline_message: ChatOrInlineMessage, - - /// Latitude of new location latitude: f32, - /// Longitude of new location longitude: f32, - /// A JSON-serialized object for a new inline keyboard. reply_markup: Option, } @@ -33,7 +36,7 @@ impl Request for EditMessageLiveLocation<'_> { type Output = Message; async fn send(&self) -> ResponseResult { - network::request_json( + net::request_json( self.bot.client(), self.bot.token(), "editMessageLiveLocation", @@ -51,7 +54,7 @@ impl<'a> EditMessageLiveLocation<'a> { longitude: f32, ) -> Self { Self { - bot, + bot: BotWrapper(bot), chat_or_inline_message, latitude, longitude, @@ -64,16 +67,21 @@ impl<'a> EditMessageLiveLocation<'a> { self } + /// Latitude of new location. pub fn latitude(mut self, val: f32) -> Self { self.latitude = val; self } + /// Longitude of new location. pub fn longitude(mut self, val: f32) -> Self { self.longitude = val; self } + /// A JSON-serialized object for a new [inline keyboard]. + /// + /// [inline keyboard]: https://core.telegram.org/bots#inline-keyboards-and-on-the-fly-updating pub fn reply_markup(mut self, val: InlineKeyboardMarkup) -> Self { self.reply_markup = Some(val); self diff --git a/src/requests/all/edit_message_media.rs b/src/requests/all/edit_message_media.rs index 2c3cff90..685a0356 100644 --- a/src/requests/all/edit_message_media.rs +++ b/src/requests/all/edit_message_media.rs @@ -1,26 +1,30 @@ +use super::BotWrapper; use crate::{ - network, + net, requests::{form_builder::FormBuilder, Request, ResponseResult}, types::{ChatOrInlineMessage, InlineKeyboardMarkup, InputMedia, Message}, Bot, }; /// Use this method to edit animation, audio, document, photo, or video -/// messages. If a message is a part of a message album, then it can be edited -/// only to a photo or a video. Otherwise, message type can be changed -/// arbitrarily. When inline message is edited, new file can't be uploaded. Use -/// previously uploaded file via its file_id or specify a URL. On success, if -/// the edited message was sent by the bot, the edited Message is returned, -/// otherwise True is returned. -#[derive(Debug, Clone)] +/// messages. +/// +/// If a message is a part of a message album, then it can be edited only to a +/// photo or a video. Otherwise, message type can be changed arbitrarily. When +/// inline message is edited, new file can't be uploaded. Use previously +/// uploaded file via its `file_id` or specify a URL. On success, if the edited +/// message was sent by the bot, the edited [`Message`] is returned, +/// otherwise [`True`] is returned. +/// +/// [The official docs](https://core.telegram.org/bots/api#editmessagemedia). +/// +/// [`Message`]: crate::types::Message +/// [`True`]: crate::types::True +#[derive(Eq, PartialEq, Debug, Clone)] pub struct EditMessageMedia<'a> { - bot: &'a Bot, - + bot: BotWrapper<'a>, chat_or_inline_message: ChatOrInlineMessage, - - /// A JSON-serialized object for a new media content of the message media: InputMedia, - /// A JSON-serialized object for a new inline keyboard. reply_markup: Option, } @@ -48,7 +52,7 @@ impl Request for EditMessageMedia<'_> { } } - network::request_multipart( + net::request_multipart( self.bot.client(), self.bot.token(), "editMessageMedia", @@ -70,7 +74,7 @@ impl<'a> EditMessageMedia<'a> { media: InputMedia, ) -> Self { Self { - bot, + bot: BotWrapper(bot), chat_or_inline_message, media, reply_markup: None, @@ -82,11 +86,15 @@ impl<'a> EditMessageMedia<'a> { self } + /// A JSON-serialized object for a new media content of the message. pub fn media(mut self, val: InputMedia) -> Self { self.media = val; self } + /// A JSON-serialized object for a new [inline keyboard]. + /// + /// [inline keyboard]: https://core.telegram.org/bots#inline-keyboards-and-on-the-fly-updating pub fn reply_markup(mut self, val: InlineKeyboardMarkup) -> Self { self.reply_markup = Some(val); self diff --git a/src/requests/all/edit_message_reply_markup.rs b/src/requests/all/edit_message_reply_markup.rs index 3ad4dff1..7c7de32e 100644 --- a/src/requests/all/edit_message_reply_markup.rs +++ b/src/requests/all/edit_message_reply_markup.rs @@ -1,25 +1,29 @@ use serde::Serialize; +use super::BotWrapper; use crate::{ - network, + net, requests::{Request, ResponseResult}, types::{ChatOrInlineMessage, InlineKeyboardMarkup, Message}, Bot, }; -/// Use this method to edit only the reply markup of messages. On success, if -/// edited message is sent by the bot, the edited Message is returned, otherwise -/// True is returned. +/// Use this method to edit only the reply markup of messages. +/// +/// On success, if edited message is sent by the bot, the edited [`Message`] is +/// returned, otherwise [`True`] is returned. +/// +/// [The official docs](https://core.telegram.org/bots/api#editmessagereplymarkup). +/// +/// [`Message`]: crate::types::Message +/// [`True`]: crate::types::True #[serde_with_macros::skip_serializing_none] -#[derive(Debug, Clone, Serialize)] +#[derive(Eq, PartialEq, Debug, Clone, Serialize)] pub struct EditMessageReplyMarkup<'a> { #[serde(skip_serializing)] - bot: &'a Bot, - + bot: BotWrapper<'a>, #[serde(flatten)] chat_or_inline_message: ChatOrInlineMessage, - - /// A JSON-serialized object for an inline keyboard. reply_markup: Option, } @@ -28,7 +32,7 @@ impl Request for EditMessageReplyMarkup<'_> { type Output = Message; async fn send(&self) -> ResponseResult { - network::request_json( + net::request_json( self.bot.client(), self.bot.token(), "editMessageReplyMarkup", @@ -44,7 +48,7 @@ impl<'a> EditMessageReplyMarkup<'a> { chat_or_inline_message: ChatOrInlineMessage, ) -> Self { Self { - bot, + bot: BotWrapper(bot), chat_or_inline_message, reply_markup: None, } @@ -55,6 +59,9 @@ impl<'a> EditMessageReplyMarkup<'a> { self } + /// A JSON-serialized object for an [inline keyboard]. + /// + /// [inline keyboard]: https://core.telegram.org/bots#inline-keyboards-and-on-the-fly-updating pub fn reply_markup(mut self, val: InlineKeyboardMarkup) -> Self { self.reply_markup = Some(val); self diff --git a/src/requests/all/edit_message_text.rs b/src/requests/all/edit_message_text.rs index 4b88fd58..ffe71b4c 100644 --- a/src/requests/all/edit_message_text.rs +++ b/src/requests/all/edit_message_text.rs @@ -1,32 +1,32 @@ use serde::Serialize; +use super::BotWrapper; use crate::{ - network, + net, requests::{Request, ResponseResult}, types::{ChatOrInlineMessage, InlineKeyboardMarkup, Message, ParseMode}, Bot, }; -/// Use this method to edit text and game messages. On success, if edited -/// message is sent by the bot, the edited Message is returned, otherwise True -/// is returned. +/// Use this method to edit text and game messages. +/// +/// On success, if edited message is sent by the bot, the edited [`Message`] is +/// returned, otherwise [`True`] is returned. +/// +/// [The official docs](https://core.telegram.org/bots/api#editmessagetext). +/// +/// [`Message`]: crate::types::Message +/// [`True`]: crate::types::True #[serde_with_macros::skip_serializing_none] -#[derive(Debug, Clone, Serialize)] +#[derive(Eq, PartialEq, Debug, Clone, Serialize)] pub struct EditMessageText<'a> { #[serde(skip_serializing)] - bot: &'a Bot, - + bot: BotWrapper<'a>, #[serde(flatten)] chat_or_inline_message: ChatOrInlineMessage, - - /// New text of the message text: String, - /// Send Markdown or HTML, if you want Telegram apps to show bold, italic, - /// fixed-width text or inline URLs in your bot's message. parse_mode: Option, - /// Disables link previews for links in this message disable_web_page_preview: Option, - /// A JSON-serialized object for an inline keyboard. reply_markup: Option, } @@ -35,7 +35,7 @@ impl Request for EditMessageText<'_> { type Output = Message; async fn send(&self) -> ResponseResult { - network::request_json( + net::request_json( self.bot.client(), self.bot.token(), "editMessageText", @@ -55,7 +55,7 @@ impl<'a> EditMessageText<'a> { T: Into, { Self { - bot, + bot: BotWrapper(bot), chat_or_inline_message, text: text.into(), parse_mode: None, @@ -69,6 +69,7 @@ impl<'a> EditMessageText<'a> { self } + /// New text of the message. pub fn text(mut self, val: T) -> Self where T: Into, @@ -77,16 +78,26 @@ impl<'a> EditMessageText<'a> { self } + /// Send [Markdown] or [HTML], if you want Telegram apps to show [bold, + /// italic, fixed-width text or inline URLs] in your bot's message. + /// + /// [Markdown]: https://core.telegram.org/bots/api#markdown-style + /// [HTML]: https://core.telegram.org/bots/api#html-style + /// [bold, italic, fixed-width text or inline URLs]: https://core.telegram.org/bots/api#formatting-options pub fn parse_mode(mut self, val: ParseMode) -> Self { self.parse_mode = Some(val); self } + /// Disables link previews for links in this message. pub fn disable_web_page_preview(mut self, val: bool) -> Self { self.disable_web_page_preview = Some(val); self } + /// A JSON-serialized object for an [inline keyboard]. + /// + /// [inline keyboard]: https://core.telegram.org/bots#inline-keyboards-and-on-the-fly-updating pub fn reply_markup(mut self, val: InlineKeyboardMarkup) -> Self { self.reply_markup = Some(val); self diff --git a/src/requests/all/export_chat_invite_link.rs b/src/requests/all/export_chat_invite_link.rs index 3cb49728..ec2f93eb 100644 --- a/src/requests/all/export_chat_invite_link.rs +++ b/src/requests/all/export_chat_invite_link.rs @@ -1,30 +1,37 @@ use serde::Serialize; +use super::BotWrapper; use crate::{ - network, + net, requests::{Request, ResponseResult}, types::ChatId, Bot, }; /// Use this method to generate a new invite link for a chat; any previously -/// generated link is revoked. The bot must be an administrator in the chat for -/// this to work and must have the appropriate admin rights. Returns the new -/// invite link as String on success.Note: Each administrator in a chat -/// generates their own invite links. Bots can't use invite links generated by -/// other administrators. If you want your bot to work with invite links, it -/// will need to generate its own link using exportChatInviteLink – after this -/// the link will become available to the bot via the getChat method. If your -/// bot needs to generate a new invite link replacing its previous one, use -/// exportChatInviteLink again. +/// generated link is revoked. +/// +/// The bot must be an administrator in the chat for this to work and must have +/// the appropriate admin rights. +/// +/// ## Note +/// Each administrator in a chat generates their own invite links. Bots can't +/// use invite links generated by other administrators. If you want your bot to +/// work with invite links, it will need to generate its own link using +/// [`Bot::export_chat_invite_link`] – after this the link will become available +/// to the bot via the [`Bot::get_chat`] method. If your bot needs to generate a +/// new invite link replacing its previous one, use +/// [`Bot::export_chat_invite_link`] again. +/// +/// [The official docs](https://core.telegram.org/bots/api#exportchatinvitelink). +/// +/// [`Bot::export_chat_invite_link`]: crate::Bot::export_chat_invite_link +/// [`Bot::get_chat`]: crate::Bot::get_chat #[serde_with_macros::skip_serializing_none] -#[derive(Debug, Clone, Serialize)] +#[derive(Eq, PartialEq, Debug, Clone, Serialize)] pub struct ExportChatInviteLink<'a> { #[serde(skip_serializing)] - bot: &'a Bot, - - /// Unique identifier for the target chat or username of the target channel - /// (in the format @channelusername) + bot: BotWrapper<'a>, chat_id: ChatId, } @@ -32,8 +39,9 @@ pub struct ExportChatInviteLink<'a> { impl Request for ExportChatInviteLink<'_> { type Output = String; + /// Returns the new invite link as `String` on success. async fn send(&self) -> ResponseResult { - network::request_json( + net::request_json( self.bot.client(), self.bot.token(), "exportChatInviteLink", @@ -49,9 +57,14 @@ impl<'a> ExportChatInviteLink<'a> { C: Into, { let chat_id = chat_id.into(); - Self { bot, chat_id } + Self { + bot: BotWrapper(bot), + chat_id, + } } + /// Unique identifier for the target chat or username of the target channel + /// (in the format `@channelusername`). pub fn chat_id(mut self, val: T) -> Self where T: Into, diff --git a/src/requests/all/forward_message.rs b/src/requests/all/forward_message.rs index dd27d1f9..0b765f09 100644 --- a/src/requests/all/forward_message.rs +++ b/src/requests/all/forward_message.rs @@ -1,30 +1,24 @@ use serde::Serialize; +use super::BotWrapper; use crate::{ - network, + net, requests::{Request, ResponseResult}, types::{ChatId, Message}, Bot, }; -/// Use this method to forward messages of any kind. On success, the sent -/// Message is returned. +/// Use this method to forward messages of any kind. +/// +/// [`The official docs`](https://core.telegram.org/bots/api#forwardmessage). #[serde_with_macros::skip_serializing_none] -#[derive(Debug, Clone, Serialize)] +#[derive(Eq, PartialEq, Debug, Clone, Serialize)] pub struct ForwardMessage<'a> { #[serde(skip_serializing)] - bot: &'a Bot, - - /// Unique identifier for the target chat or username of the target channel - /// (in the format @channelusername) + bot: BotWrapper<'a>, chat_id: ChatId, - /// Unique identifier for the chat where the original message was sent (or - /// channel username in the format @channelusername) from_chat_id: ChatId, - /// Sends the message silently. Users will receive a notification with no - /// sound. disable_notification: Option, - /// Message identifier in the chat specified in from_chat_id message_id: i32, } @@ -33,7 +27,7 @@ impl Request for ForwardMessage<'_> { type Output = Message; async fn send(&self) -> ResponseResult { - network::request_json( + net::request_json( self.bot.client(), self.bot.token(), "forwardMessage", @@ -57,7 +51,7 @@ impl<'a> ForwardMessage<'a> { let chat_id = chat_id.into(); let from_chat_id = from_chat_id.into(); Self { - bot, + bot: BotWrapper(bot), chat_id, from_chat_id, message_id, @@ -65,6 +59,8 @@ impl<'a> ForwardMessage<'a> { } } + /// Unique identifier for the target chat or username of the target channel + /// (in the format `@channelusername`). pub fn chat_id(mut self, val: T) -> Self where T: Into, @@ -73,6 +69,8 @@ impl<'a> ForwardMessage<'a> { self } + /// Unique identifier for the chat where the original message was sent (or + /// channel username in the format `@channelusername`). #[allow(clippy::wrong_self_convention)] pub fn from_chat_id(mut self, val: T) -> Self where @@ -82,11 +80,18 @@ impl<'a> ForwardMessage<'a> { self } + /// Sends the message [silently]. Users will receive a notification with no + /// sound. + /// + /// [silently]: https://telegram.org/blog/channels-2-0#silent-messages pub fn disable_notification(mut self, val: bool) -> Self { self.disable_notification = Some(val); self } + /// Message identifier in the chat specified in [`from_chat_id`]. + /// + /// [`from_chat_id`]: ForwardMessage::from_chat_id pub fn message_id(mut self, val: i32) -> Self { self.message_id = val; self diff --git a/src/requests/all/get_chat.rs b/src/requests/all/get_chat.rs index a131e0b6..ce939041 100644 --- a/src/requests/all/get_chat.rs +++ b/src/requests/all/get_chat.rs @@ -1,7 +1,8 @@ use serde::Serialize; +use super::BotWrapper; use crate::{ - network, + net, requests::{Request, ResponseResult}, types::{Chat, ChatId}, Bot, @@ -9,15 +10,14 @@ use crate::{ /// Use this method to get up to date information about the chat (current name /// of the user for one-on-one conversations, current username of a user, group -/// or channel, etc.). Returns a Chat object on success. +/// or channel, etc.). +/// +/// [The official docs](https://core.telegram.org/bots/api#getchat). #[serde_with_macros::skip_serializing_none] -#[derive(Debug, Clone, Serialize)] +#[derive(Eq, PartialEq, Debug, Clone, Serialize)] pub struct GetChat<'a> { #[serde(skip_serializing)] - bot: &'a Bot, - - /// Unique identifier for the target chat or username of the target - /// supergroup or channel (in the format @channelusername) + bot: BotWrapper<'a>, chat_id: ChatId, } @@ -26,13 +26,8 @@ impl Request for GetChat<'_> { type Output = Chat; async fn send(&self) -> ResponseResult { - network::request_json( - self.bot.client(), - self.bot.token(), - "getChat", - &self, - ) - .await + net::request_json(self.bot.client(), self.bot.token(), "getChat", &self) + .await } } @@ -42,9 +37,14 @@ impl<'a> GetChat<'a> { C: Into, { let chat_id = chat_id.into(); - Self { bot, chat_id } + Self { + bot: BotWrapper(bot), + chat_id, + } } + /// Unique identifier for the target chat or username of the target + /// supergroup or channel (in the format `@channelusername`). pub fn chat_id(mut self, val: T) -> Self where T: Into, diff --git a/src/requests/all/get_chat_administrators.rs b/src/requests/all/get_chat_administrators.rs index f4012b91..bff1adb2 100644 --- a/src/requests/all/get_chat_administrators.rs +++ b/src/requests/all/get_chat_administrators.rs @@ -1,25 +1,24 @@ use serde::Serialize; +use super::BotWrapper; use crate::{ - network, + net, requests::{Request, ResponseResult}, types::{ChatId, ChatMember}, Bot, }; -/// Use this method to get a list of administrators in a chat. On success, -/// returns an Array of ChatMember objects that contains information about all -/// chat administrators except other bots. If the chat is a group or a -/// supergroup and no administrators were appointed, only the creator will be -/// returned. +/// Use this method to get a list of administrators in a chat. +/// +/// If the chat is a group or a supergroup and no administrators were appointed, +/// only the creator will be returned. +/// +/// [The official docs](https://core.telegram.org/bots/api#getchatadministrators). #[serde_with_macros::skip_serializing_none] -#[derive(Debug, Clone, Serialize)] +#[derive(Eq, PartialEq, Debug, Clone, Serialize)] pub struct GetChatAdministrators<'a> { #[serde(skip_serializing)] - bot: &'a Bot, - - /// Unique identifier for the target chat or username of the target - /// supergroup or channel (in the format @channelusername) + bot: BotWrapper<'a>, chat_id: ChatId, } @@ -27,8 +26,10 @@ pub struct GetChatAdministrators<'a> { impl Request for GetChatAdministrators<'_> { type Output = Vec; + /// On success, returns an array that contains information about all chat + /// administrators except other bots. async fn send(&self) -> ResponseResult> { - network::request_json( + net::request_json( self.bot.client(), self.bot.token(), "getChatAdministrators", @@ -44,9 +45,14 @@ impl<'a> GetChatAdministrators<'a> { C: Into, { let chat_id = chat_id.into(); - Self { bot, chat_id } + Self { + bot: BotWrapper(bot), + chat_id, + } } + /// Unique identifier for the target chat or username of the target + /// supergroup or channel (in the format `@channelusername`). pub fn chat_id(mut self, val: T) -> Self where T: Into, diff --git a/src/requests/all/get_chat_member.rs b/src/requests/all/get_chat_member.rs index 0f5d86c6..e3a4f190 100644 --- a/src/requests/all/get_chat_member.rs +++ b/src/requests/all/get_chat_member.rs @@ -1,24 +1,22 @@ use serde::Serialize; +use super::BotWrapper; use crate::{ - network, + net, requests::{Request, ResponseResult}, types::{ChatId, ChatMember}, Bot, }; -/// Use this method to get information about a member of a chat. Returns a -/// ChatMember object on success. +/// Use this method to get information about a member of a chat. +/// +/// [The official docs](https://core.telegram.org/bots/api#getchatmember). #[serde_with_macros::skip_serializing_none] -#[derive(Debug, Clone, Serialize)] +#[derive(Eq, PartialEq, Debug, Clone, Serialize)] pub struct GetChatMember<'a> { #[serde(skip_serializing)] - bot: &'a Bot, - - /// Unique identifier for the target chat or username of the target - /// supergroup or channel (in the format @channelusername) + bot: BotWrapper<'a>, chat_id: ChatId, - /// Unique identifier of the target user user_id: i32, } @@ -27,7 +25,7 @@ impl Request for GetChatMember<'_> { type Output = ChatMember; async fn send(&self) -> ResponseResult { - network::request_json( + net::request_json( self.bot.client(), self.bot.token(), "getChatMember", @@ -44,12 +42,14 @@ impl<'a> GetChatMember<'a> { { let chat_id = chat_id.into(); Self { - bot, + bot: BotWrapper(bot), chat_id, user_id, } } + /// Unique identifier for the target chat or username of the target + /// supergroup or channel (in the format `@channelusername`). pub fn chat_id(mut self, val: T) -> Self where T: Into, @@ -58,6 +58,7 @@ impl<'a> GetChatMember<'a> { self } + /// Unique identifier of the target user. pub fn user_id(mut self, val: i32) -> Self { self.user_id = val; self diff --git a/src/requests/all/get_chat_members_count.rs b/src/requests/all/get_chat_members_count.rs index 60c9789d..1d5e4c55 100644 --- a/src/requests/all/get_chat_members_count.rs +++ b/src/requests/all/get_chat_members_count.rs @@ -1,22 +1,21 @@ use serde::Serialize; +use super::BotWrapper; use crate::{ - network, + net, requests::{Request, ResponseResult}, types::ChatId, Bot, }; -/// Use this method to get the number of members in a chat. Returns Int on -/// success. +/// Use this method to get the number of members in a chat. +/// +/// [The official docs](https://core.telegram.org/bots/api#getchatmemberscount). #[serde_with_macros::skip_serializing_none] -#[derive(Debug, Clone, Serialize)] +#[derive(Eq, PartialEq, Debug, Clone, Serialize)] pub struct GetChatMembersCount<'a> { #[serde(skip_serializing)] - bot: &'a Bot, - - /// Unique identifier for the target chat or username of the target - /// supergroup or channel (in the format @channelusername) + bot: BotWrapper<'a>, chat_id: ChatId, } @@ -25,7 +24,7 @@ impl Request for GetChatMembersCount<'_> { type Output = i32; async fn send(&self) -> ResponseResult { - network::request_json( + net::request_json( self.bot.client(), self.bot.token(), "getChatMembersCount", @@ -41,9 +40,14 @@ impl<'a> GetChatMembersCount<'a> { C: Into, { let chat_id = chat_id.into(); - Self { bot, chat_id } + Self { + bot: BotWrapper(bot), + chat_id, + } } + /// Unique identifier for the target chat or username of the target + /// supergroup or channel (in the format `@channelusername`). pub fn chat_id(mut self, val: T) -> Self where T: Into, diff --git a/src/requests/all/get_file.rs b/src/requests/all/get_file.rs index 9fdde40a..4c470827 100644 --- a/src/requests/all/get_file.rs +++ b/src/requests/all/get_file.rs @@ -1,7 +1,8 @@ use serde::Serialize; +use super::BotWrapper; use crate::{ - network, + net, requests::{Request, ResponseResult}, types::File, Bot, @@ -12,8 +13,6 @@ use crate::{ /// /// For the moment, bots can download files of up to `20MB` in size. /// -/// On success, a [`File`] object is returned. -/// /// The file can then be downloaded via the link /// `https://api.telegram.org/file/bot/`, where `` /// is taken from the response. It is guaranteed that the link will be valid @@ -24,16 +23,16 @@ use crate::{ /// type. You should save the file's MIME type and name (if available) when the /// [`File`] object is received. /// +/// [The official docs](https://core.telegram.org/bots/api#getfile). +/// /// [`File`]: crate::types::file /// [`GetFile`]: self::GetFile #[serde_with_macros::skip_serializing_none] -#[derive(Debug, Clone, Serialize)] +#[derive(Eq, PartialEq, Debug, Clone, Serialize)] pub struct GetFile<'a> { #[serde(skip_serializing)] - bot: &'a Bot, - - /// File identifier to get info about - pub file_id: String, + bot: BotWrapper<'a>, + file_id: String, } #[async_trait::async_trait] @@ -41,13 +40,8 @@ impl Request for GetFile<'_> { type Output = File; async fn send(&self) -> ResponseResult { - network::request_json( - self.bot.client(), - self.bot.token(), - "getFile", - &self, - ) - .await + net::request_json(self.bot.client(), self.bot.token(), "getFile", &self) + .await } } @@ -57,11 +51,12 @@ impl<'a> GetFile<'a> { F: Into, { Self { - bot, + bot: BotWrapper(bot), file_id: file_id.into(), } } + /// File identifier to get info about. pub fn file_id(mut self, value: F) -> Self where F: Into, diff --git a/src/requests/all/get_game_high_scores.rs b/src/requests/all/get_game_high_scores.rs index aba2599a..04d43c5d 100644 --- a/src/requests/all/get_game_high_scores.rs +++ b/src/requests/all/get_game_high_scores.rs @@ -1,28 +1,32 @@ use serde::Serialize; +use super::BotWrapper; use crate::{ - network, + net, requests::{Request, ResponseResult}, types::{ChatOrInlineMessage, GameHighScore}, Bot, }; -/// Use this method to get data for high score tables. Will return the score of -/// the specified user and several of his neighbors in a game. On success, -/// returns an Array of GameHighScore objects.This method will currently return -/// scores for the target user, plus two of his closest neighbors on each side. -/// Will also return the top three users if the user and his neighbors are not -/// among them. Please note that this behavior is subject to change. +/// Use this method to get data for high score tables. +/// +/// Will return the score of the specified user and several of his neighbors in +/// a game. +/// +/// ## Note +/// This method will currently return scores for the target user, plus two of +/// his closest neighbors on each side. Will also return the top three users if +/// the user and his neighbors are not among them. Please note that this +/// behavior is subject to change. +/// +/// [The official docs](https://core.telegram.org/bots/api#getgamehighscores). #[serde_with_macros::skip_serializing_none] -#[derive(Debug, Clone, Serialize)] +#[derive(Eq, PartialEq, Debug, Clone, Serialize)] pub struct GetGameHighScores<'a> { #[serde(skip_serializing)] - bot: &'a Bot, - + bot: BotWrapper<'a>, #[serde(flatten)] chat_or_inline_message: ChatOrInlineMessage, - - /// Target user id user_id: i32, } @@ -31,7 +35,7 @@ impl Request for GetGameHighScores<'_> { type Output = Vec; async fn send(&self) -> ResponseResult> { - network::request_json( + net::request_json( self.bot.client(), self.bot.token(), "getGameHighScores", @@ -48,7 +52,7 @@ impl<'a> GetGameHighScores<'a> { user_id: i32, ) -> Self { Self { - bot, + bot: BotWrapper(bot), chat_or_inline_message, user_id, } @@ -59,6 +63,7 @@ impl<'a> GetGameHighScores<'a> { self } + /// Target user id. pub fn user_id(mut self, val: i32) -> Self { self.user_id = val; self diff --git a/src/requests/all/get_me.rs b/src/requests/all/get_me.rs index 9f9b4df4..78261693 100644 --- a/src/requests/all/get_me.rs +++ b/src/requests/all/get_me.rs @@ -1,39 +1,37 @@ +use super::BotWrapper; use crate::{ - network, + net, requests::{Request, ResponseResult}, types::User, Bot, }; use serde::Serialize; -/// A filter method for testing your bot's auth token. Requires no parameters. -/// Returns basic information about the bot in form of a [`User`] object. +/// A simple method for testing your bot's auth token. Requires no parameters. /// -/// [`User`]: crate::types::User -#[derive(Debug, Clone, Copy, Serialize)] +/// [The official docs](https://core.telegram.org/bots/api#getme). +#[derive(Eq, PartialEq, Debug, Clone, Copy, Serialize)] pub struct GetMe<'a> { #[serde(skip_serializing)] - bot: &'a Bot, + bot: BotWrapper<'a>, } #[async_trait::async_trait] impl Request for GetMe<'_> { type Output = User; + /// Returns basic information about the bot. #[allow(clippy::trivially_copy_pass_by_ref)] async fn send(&self) -> ResponseResult { - network::request_json( - self.bot.client(), - self.bot.token(), - "getMe", - &self, - ) - .await + net::request_json(self.bot.client(), self.bot.token(), "getMe", &self) + .await } } impl<'a> GetMe<'a> { pub(crate) fn new(bot: &'a Bot) -> Self { - Self { bot } + Self { + bot: BotWrapper(bot), + } } } diff --git a/src/requests/all/get_sticker_set.rs b/src/requests/all/get_sticker_set.rs index 2c181cd0..a63911f8 100644 --- a/src/requests/all/get_sticker_set.rs +++ b/src/requests/all/get_sticker_set.rs @@ -1,21 +1,21 @@ use serde::Serialize; +use super::BotWrapper; use crate::{ - network, + net, requests::{Request, ResponseResult}, types::StickerSet, Bot, }; -/// Use this method to get a sticker set. On success, a StickerSet object is -/// returned. +/// Use this method to get a sticker set. +/// +/// [The official docs](https://core.telegram.org/bots/api#getstickerset). #[serde_with_macros::skip_serializing_none] -#[derive(Debug, Clone, Serialize)] +#[derive(Eq, PartialEq, Debug, Clone, Serialize)] pub struct GetStickerSet<'a> { #[serde(skip_serializing)] - bot: &'a Bot, - - /// Name of the sticker set + bot: BotWrapper<'a>, name: String, } @@ -24,7 +24,7 @@ impl Request for GetStickerSet<'_> { type Output = StickerSet; async fn send(&self) -> ResponseResult { - network::request_json( + net::request_json( self.bot.client(), self.bot.token(), "getStickerSet", @@ -40,9 +40,13 @@ impl<'a> GetStickerSet<'a> { N: Into, { let name = name.into(); - Self { bot, name } + Self { + bot: BotWrapper(bot), + name, + } } + /// Name of the sticker set. pub fn name(mut self, val: T) -> Self where T: Into, diff --git a/src/requests/all/get_updates.rs b/src/requests/all/get_updates.rs index 8a42942b..c7311591 100644 --- a/src/requests/all/get_updates.rs +++ b/src/requests/all/get_updates.rs @@ -1,68 +1,32 @@ use serde::Serialize; +use super::BotWrapper; use crate::{ - network, + net, requests::{Request, ResponseResult}, types::{AllowedUpdate, Update}, Bot, }; /// Use this method to receive incoming updates using long polling ([wiki]). -/// An array ([`Vec`]) of [`Update`]s is returned. /// /// **Notes:** /// 1. This method will not work if an outgoing webhook is set up. /// 2. In order to avoid getting duplicate updates, /// recalculate offset after each server response. /// +/// [The official docs](https://core.telegram.org/bots/api#getupdates). +/// /// [wiki]: https://en.wikipedia.org/wiki/Push_technology#Long_polling -/// [Update]: crate::types::Update -/// [Vec]: std::alloc::Vec #[serde_with_macros::skip_serializing_none] -#[derive(Debug, Clone, Serialize)] +#[derive(Eq, PartialEq, Debug, Clone, Serialize)] pub struct GetUpdates<'a> { #[serde(skip_serializing)] - bot: &'a Bot, - - /// Identifier of the first update to be returned. Must be greater by one - /// than the highest among the identifiers of previously received updates. - /// By default, updates starting with the earliest unconfirmed update are - /// returned. An update is considered confirmed as soon as [`GetUpdates`] - /// is called with an [`offset`] higher than its [`id`]. The negative - /// offset can be specified to retrieve updates starting from `-offset` - /// update from the end of the updates queue. All previous updates will - /// forgotten. - /// - /// [`GetUpdates`]: self::GetUpdates - /// [`offset`]: self::GetUpdates::offset - /// [`id`]: crate::types::Update::id - pub offset: Option, - /// Limits the number of updates to be retrieved. - /// Values between `1`—`100` are accepted. Defaults to `100`. - pub limit: Option, - /// Timeout in seconds for long polling. Defaults to `0`, - /// i.e. usual short polling. Should be positive, short polling should be - /// used for testing purposes only. - pub timeout: Option, - /// List the types of updates you want your bot to receive. - /// For example, specify [[`Message`], [`EditedChannelPost`], - /// [`CallbackQuery`]] to only receive updates of these types. - /// See [`AllowedUpdate`] for a complete list of available update types. - /// - /// Specify an empty list to receive all updates regardless of type - /// (default). If not specified, the previous setting will be used. - /// - /// **Note:** - /// This parameter doesn't affect updates created before the call to the - /// [`GetUpdates`], so unwanted updates may be received for a short period - /// of time. - /// - /// [`Message`]: self::AllowedUpdate::Message - /// [`EditedChannelPost`]: self::AllowedUpdate::EditedChannelPost - /// [`CallbackQuery`]: self::AllowedUpdate::CallbackQuery - /// [`AllowedUpdate`]: self::AllowedUpdate - /// [`GetUpdates`]: self::GetUpdates - pub allowed_updates: Option>, + bot: BotWrapper<'a>, + pub(crate) offset: Option, + pub(crate) limit: Option, + pub(crate) timeout: Option, + pub(crate) allowed_updates: Option>, } #[async_trait::async_trait] @@ -70,7 +34,7 @@ impl Request for GetUpdates<'_> { type Output = Vec; async fn send(&self) -> ResponseResult> { - network::request_json( + net::request_json( self.bot.client(), self.bot.token(), "getUpdates", @@ -83,7 +47,7 @@ impl Request for GetUpdates<'_> { impl<'a> GetUpdates<'a> { pub(crate) fn new(bot: &'a Bot) -> Self { Self { - bot, + bot: BotWrapper(bot), offset: None, limit: None, timeout: None, @@ -91,24 +55,63 @@ impl<'a> GetUpdates<'a> { } } + /// Identifier of the first update to be returned. + /// + /// Must be greater by one than the highest among the identifiers of + /// previously received updates. By default, updates starting with the + /// earliest unconfirmed update are returned. An update is considered + /// confirmed as soon as [`GetUpdates`] is called with an [`offset`] + /// higher than its [`id`]. The negative offset can be specified to + /// retrieve updates starting from `-offset` update from the end of the + /// updates queue. All previous updates will forgotten. + /// + /// [`GetUpdates`]: self::GetUpdates + /// [`offset`]: self::GetUpdates::offset + /// [`id`]: crate::types::Update::id pub fn offset(mut self, value: i32) -> Self { self.offset = Some(value); self } + /// Limits the number of updates to be retrieved. + /// + /// Values between `1`—`100` are accepted. Defaults to `100`. pub fn limit(mut self, value: u8) -> Self { self.limit = Some(value); self } + /// Timeout in seconds for long polling. + /// + /// Defaults to `0`, i.e. usual short polling. Should be positive, short + /// polling should be used for testing purposes only. pub fn timeout(mut self, value: u32) -> Self { self.timeout = Some(value); self } + /// List the types of updates you want your bot to receive. + /// + /// For example, specify [[`Message`], [`EditedChannelPost`], + /// [`CallbackQuery`]] to only receive updates of these types. + /// See [`AllowedUpdate`] for a complete list of available update types. + /// + /// Specify an empty list to receive all updates regardless of type + /// (default). If not specified, the previous setting will be used. + /// + /// **Note:** + /// This parameter doesn't affect updates created before the call to the + /// [`Bot::get_updates`], so unwanted updates may be received for a short + /// period of time. + /// + /// [`Message`]: self::AllowedUpdate::Message + /// [`EditedChannelPost`]: self::AllowedUpdate::EditedChannelPost + /// [`CallbackQuery`]: self::AllowedUpdate::CallbackQuery + /// [`AllowedUpdate`]: self::AllowedUpdate + /// [`Bot::get_updates`]: crate::Bot::get_updates pub fn allowed_updates(mut self, value: T) -> Self where - T: Into>, // TODO: into or other trait? + T: Into>, { self.allowed_updates = Some(value.into()); self diff --git a/src/requests/all/get_user_profile_photos.rs b/src/requests/all/get_user_profile_photos.rs index 1a50e617..bc9b79c3 100644 --- a/src/requests/all/get_user_profile_photos.rs +++ b/src/requests/all/get_user_profile_photos.rs @@ -1,27 +1,23 @@ use serde::Serialize; +use super::BotWrapper; use crate::{ - network, + net, requests::{Request, ResponseResult}, types::UserProfilePhotos, Bot, }; -/// Use this method to get a list of profile pictures for a user. Returns a -/// UserProfilePhotos object. +/// Use this method to get a list of profile pictures for a user. +/// +/// [The official docs](https://core.telegram.org/bots/api#getuserprofilephotos). #[serde_with_macros::skip_serializing_none] -#[derive(Debug, Clone, Serialize)] +#[derive(Copy, Eq, PartialEq, Debug, Clone, Serialize)] pub struct GetUserProfilePhotos<'a> { #[serde(skip_serializing)] - bot: &'a Bot, - - /// Unique identifier of the target user + bot: BotWrapper<'a>, user_id: i32, - /// Sequential number of the first photo to be returned. By default, all - /// photos are returned. offset: Option, - /// Limits the number of photos to be retrieved. Values between 1—100 are - /// accepted. Defaults to 100. limit: Option, } @@ -30,7 +26,7 @@ impl Request for GetUserProfilePhotos<'_> { type Output = UserProfilePhotos; async fn send(&self) -> ResponseResult { - network::request_json( + net::request_json( self.bot.client(), self.bot.token(), "getUserProfilePhotos", @@ -43,23 +39,30 @@ impl Request for GetUserProfilePhotos<'_> { impl<'a> GetUserProfilePhotos<'a> { pub(crate) fn new(bot: &'a Bot, user_id: i32) -> Self { Self { - bot, + bot: BotWrapper(bot), user_id, offset: None, limit: None, } } + /// Unique identifier of the target user. pub fn user_id(mut self, val: i32) -> Self { self.user_id = val; self } + /// Sequential number of the first photo to be returned. By default, all + /// photos are returned. pub fn offset(mut self, val: i32) -> Self { self.offset = Some(val); self } + /// Limits the number of photos to be retrieved. Values between 1—100 are + /// accepted. + /// + /// Defaults to 100. pub fn limit(mut self, val: i32) -> Self { self.limit = Some(val); self diff --git a/src/requests/all/get_webhook_info.rs b/src/requests/all/get_webhook_info.rs index 8d5ef965..88fa92f5 100644 --- a/src/requests/all/get_webhook_info.rs +++ b/src/requests/all/get_webhook_info.rs @@ -1,27 +1,34 @@ use serde::Serialize; +use super::BotWrapper; use crate::{ - network, + net, requests::{Request, ResponseResult}, types::WebhookInfo, Bot, }; -/// Use this method to get current webhook status. Requires no parameters. On -/// success, returns a WebhookInfo object. If the bot is using getUpdates, will -/// return an object with the url field empty. -#[derive(Debug, Clone, Serialize)] +/// Use this method to get current webhook status. +/// +/// If the bot is using [`Bot::get_updates`], will return an object with the url +/// field empty. +/// +/// [The official docs](https://core.telegram.org/bots/api#getwebhookinfo). +/// +/// [`Bot::get_updates`]: crate::Bot::get_updates +#[derive(Copy, Eq, PartialEq, Debug, Clone, Serialize)] pub struct GetWebhookInfo<'a> { #[serde(skip_serializing)] - bot: &'a Bot, + bot: BotWrapper<'a>, } #[async_trait::async_trait] impl Request for GetWebhookInfo<'_> { type Output = WebhookInfo; + #[allow(clippy::trivially_copy_pass_by_ref)] async fn send(&self) -> ResponseResult { - network::request_json( + net::request_json( self.bot.client(), self.bot.token(), "getWebhookInfo", @@ -33,6 +40,8 @@ impl Request for GetWebhookInfo<'_> { impl<'a> GetWebhookInfo<'a> { pub(crate) fn new(bot: &'a Bot) -> Self { - Self { bot } + Self { + bot: BotWrapper(bot), + } } } diff --git a/src/requests/all/kick_chat_member.rs b/src/requests/all/kick_chat_member.rs index db99a1f1..c766071f 100644 --- a/src/requests/all/kick_chat_member.rs +++ b/src/requests/all/kick_chat_member.rs @@ -1,31 +1,30 @@ use serde::Serialize; +use super::BotWrapper; use crate::{ - network, + net, requests::{Request, ResponseResult}, types::{ChatId, True}, Bot, }; -/// Use this method to kick a user from a group, a supergroup or a channel. In -/// the case of supergroups and channels, the user will not be able to return to -/// the group on their own using invite links, etc., unless unbanned first. The -/// bot must be an administrator in the chat for this to work and must have the -/// appropriate admin rights. Returns True on success. +/// Use this method to kick a user from a group, a supergroup or a channel. +/// +/// In the case of supergroups and channels, the user will not be able to return +/// to the group on their own using invite links, etc., unless [unbanned] first. +/// The bot must be an administrator in the chat for this to work and must have +/// the appropriate admin rights. +/// +/// [The official docs](https://core.telegram.org/bots/api#kickchatmember). +/// +/// [unbanned]: crate::Bot::unban_chat_member #[serde_with_macros::skip_serializing_none] -#[derive(Debug, Clone, Serialize)] +#[derive(Eq, PartialEq, Debug, Clone, Serialize)] pub struct KickChatMember<'a> { #[serde(skip_serializing)] - bot: &'a Bot, - - /// Unique identifier for the target group or username of the target - /// supergroup or channel (in the format @channelusername) + bot: BotWrapper<'a>, chat_id: ChatId, - /// Unique identifier of the target user user_id: i32, - /// Date when the user will be unbanned, unix time. If user is banned for - /// more than 366 days or less than 30 seconds from the current time they - /// are considered to be banned forever until_date: Option, } @@ -34,7 +33,7 @@ impl Request for KickChatMember<'_> { type Output = True; async fn send(&self) -> ResponseResult { - network::request_json( + net::request_json( self.bot.client(), self.bot.token(), "kickChatMember", @@ -51,13 +50,15 @@ impl<'a> KickChatMember<'a> { { let chat_id = chat_id.into(); Self { - bot, + bot: BotWrapper(bot), chat_id, user_id, until_date: None, } } + /// Unique identifier for the target group or username of the target + /// supergroup or channel (in the format `@channelusername`). pub fn chat_id(mut self, val: T) -> Self where T: Into, @@ -66,11 +67,16 @@ impl<'a> KickChatMember<'a> { self } + /// Unique identifier of the target user. pub fn user_id(mut self, val: i32) -> Self { self.user_id = val; self } + /// Date when the user will be unbanned, unix time. + /// + /// If user is banned for more than 366 days or less than 30 seconds from + /// the current time they are considered to be banned forever. pub fn until_date(mut self, val: i32) -> Self { self.until_date = Some(val); self diff --git a/src/requests/all/leave_chat.rs b/src/requests/all/leave_chat.rs index ea8f1a56..a0ccd4b4 100644 --- a/src/requests/all/leave_chat.rs +++ b/src/requests/all/leave_chat.rs @@ -1,22 +1,21 @@ use serde::Serialize; +use super::BotWrapper; use crate::{ - network, + net, requests::{Request, ResponseResult}, types::{ChatId, True}, Bot, }; /// Use this method for your bot to leave a group, supergroup or channel. -/// Returns True on success. +/// +/// [The official docs](https://core.telegram.org/bots/api#leavechat). #[serde_with_macros::skip_serializing_none] -#[derive(Debug, Clone, Serialize)] +#[derive(Eq, PartialEq, Debug, Clone, Serialize)] pub struct LeaveChat<'a> { #[serde(skip_serializing)] - bot: &'a Bot, - - /// Unique identifier for the target chat or username of the target - /// supergroup or channel (in the format @channelusername) + bot: BotWrapper<'a>, chat_id: ChatId, } @@ -25,7 +24,7 @@ impl Request for LeaveChat<'_> { type Output = True; async fn send(&self) -> ResponseResult { - network::request_json( + net::request_json( self.bot.client(), self.bot.token(), "leaveChat", @@ -41,9 +40,14 @@ impl<'a> LeaveChat<'a> { C: Into, { let chat_id = chat_id.into(); - Self { bot, chat_id } + Self { + bot: BotWrapper(bot), + chat_id, + } } + /// Unique identifier for the target chat or username of the target + /// supergroup or channel (in the format `@channelusername`). pub fn chat_id(mut self, val: T) -> Self where T: Into, diff --git a/src/requests/all/mod.rs b/src/requests/all/mod.rs index 7d8e6845..84acc2e1 100644 --- a/src/requests/all/mod.rs +++ b/src/requests/all/mod.rs @@ -130,3 +130,6 @@ pub use stop_poll::*; pub use unban_chat_member::*; pub use unpin_chat_message::*; pub use upload_sticker_file::*; + +mod bot_wrapper; +use bot_wrapper::BotWrapper; diff --git a/src/requests/all/pin_chat_message.rs b/src/requests/all/pin_chat_message.rs index fe0ed246..6be8c7cf 100644 --- a/src/requests/all/pin_chat_message.rs +++ b/src/requests/all/pin_chat_message.rs @@ -1,30 +1,27 @@ use serde::Serialize; +use super::BotWrapper; use crate::{ - network, + net, requests::{Request, ResponseResult}, types::{ChatId, True}, Bot, }; -/// Use this method to pin a message in a group, a supergroup, or a channel. The -/// bot must be an administrator in the chat for this to work and must have the -/// ‘can_pin_messages’ admin right in the supergroup or ‘can_edit_messages’ -/// admin right in the channel. Returns True on success. +/// Use this method to pin a message in a group, a supergroup, or a channel. +/// +/// The bot must be an administrator in the chat for this to work and must have +/// the `can_pin_messages` admin right in the supergroup or `can_edit_messages` +/// admin right in the channel. +/// +/// [The official docs](https://core.telegram.org/bots/api#pinchatmessage). #[serde_with_macros::skip_serializing_none] -#[derive(Debug, Clone, Serialize)] +#[derive(Eq, PartialEq, Debug, Clone, Serialize)] pub struct PinChatMessage<'a> { #[serde(skip_serializing)] - bot: &'a Bot, - - /// Unique identifier for the target chat or username of the target channel - /// (in the format @channelusername) + bot: BotWrapper<'a>, chat_id: ChatId, - /// Identifier of a message to pin message_id: i32, - /// Pass True, if it is not necessary to send a notification to all chat - /// members about the new pinned message. Notifications are always disabled - /// in channels. disable_notification: Option, } @@ -33,7 +30,7 @@ impl Request for PinChatMessage<'_> { type Output = True; async fn send(&self) -> ResponseResult { - network::request_json( + net::request_json( self.bot.client(), self.bot.token(), "pinChatMessage", @@ -50,13 +47,15 @@ impl<'a> PinChatMessage<'a> { { let chat_id = chat_id.into(); Self { - bot, + bot: BotWrapper(bot), chat_id, message_id, disable_notification: None, } } + /// Unique identifier for the target chat or username of the target channel + /// (in the format `@channelusername`). pub fn chat_id(mut self, val: T) -> Self where T: Into, @@ -65,11 +64,16 @@ impl<'a> PinChatMessage<'a> { self } + /// Identifier of a message to pin. pub fn message_id(mut self, val: i32) -> Self { self.message_id = val; self } + /// Pass `true`, if it is not necessary to send a notification to all chat + /// members about the new pinned message. + /// + /// Notifications are always disabled in channels. pub fn disable_notification(mut self, val: bool) -> Self { self.disable_notification = Some(val); self diff --git a/src/requests/all/promote_chat_member.rs b/src/requests/all/promote_chat_member.rs index 49e497bb..ddd46e93 100644 --- a/src/requests/all/promote_chat_member.rs +++ b/src/requests/all/promote_chat_member.rs @@ -1,47 +1,34 @@ use serde::Serialize; +use super::BotWrapper; use crate::{ - network, + net, requests::{Request, ResponseResult}, types::{ChatId, True}, Bot, }; /// Use this method to promote or demote a user in a supergroup or a channel. +/// /// The bot must be an administrator in the chat for this to work and must have /// the appropriate admin rights. Pass False for all boolean parameters to -/// demote a user. Returns True on success. +/// demote a user. +/// +/// [The official docs](https://core.telegram.org/bots/api#promotechatmember). #[serde_with_macros::skip_serializing_none] -#[derive(Debug, Clone, Serialize)] +#[derive(Eq, PartialEq, Debug, Clone, Serialize)] pub struct PromoteChatMember<'a> { #[serde(skip_serializing)] - bot: &'a Bot, - - /// Unique identifier for the target chat or username of the target channel - /// (in the format @channelusername) + bot: BotWrapper<'a>, chat_id: ChatId, - /// Unique identifier of the target user user_id: i32, - /// Pass True, if the administrator can change chat title, photo and other - /// settings can_change_info: Option, - /// Pass True, if the administrator can create channel posts, channels only can_post_messages: Option, - /// Pass True, if the administrator can edit messages of other users and - /// can pin messages, channels only can_edit_messages: Option, - /// Pass True, if the administrator can delete messages of other users can_delete_messages: Option, - /// Pass True, if the administrator can invite new users to the chat can_invite_users: Option, - /// Pass True, if the administrator can restrict, ban or unban chat members can_restrict_members: Option, - /// Pass True, if the administrator can pin messages, supergroups only can_pin_messages: Option, - /// Pass True, if the administrator can add new administrators with a - /// subset of his own privileges or demote administrators that he has - /// promoted, directly or indirectly (promoted by administrators that were - /// appointed by him) can_promote_members: Option, } @@ -50,7 +37,7 @@ impl Request for PromoteChatMember<'_> { type Output = True; async fn send(&self) -> ResponseResult { - network::request_json( + net::request_json( self.bot.client(), self.bot.token(), "promoteChatMember", @@ -67,7 +54,7 @@ impl<'a> PromoteChatMember<'a> { { let chat_id = chat_id.into(); Self { - bot, + bot: BotWrapper(bot), chat_id, user_id, can_change_info: None, @@ -81,6 +68,8 @@ impl<'a> PromoteChatMember<'a> { } } + /// Unique identifier for the target chat or username of the target channel + /// (in the format `@channelusername`). pub fn chat_id(mut self, val: T) -> Self where T: Into, @@ -89,46 +78,62 @@ impl<'a> PromoteChatMember<'a> { self } + /// Unique identifier of the target user. pub fn user_id(mut self, val: i32) -> Self { self.user_id = val; self } + /// Pass `true`, if the administrator can change chat title, photo and other + /// settings. pub fn can_change_info(mut self, val: bool) -> Self { self.can_change_info = Some(val); self } + /// Pass `true`, if the administrator can create channel posts, channels + /// only. pub fn can_post_messages(mut self, val: bool) -> Self { self.can_post_messages = Some(val); self } + /// Pass `true`, if the administrator can edit messages of other users and + /// can pin messages, channels only. pub fn can_edit_messages(mut self, val: bool) -> Self { self.can_edit_messages = Some(val); self } + /// Pass `true`, if the administrator can delete messages of other users. pub fn can_delete_messages(mut self, val: bool) -> Self { self.can_delete_messages = Some(val); self } + /// Pass `true`, if the administrator can invite new users to the chat. pub fn can_invite_users(mut self, val: bool) -> Self { self.can_invite_users = Some(val); self } + /// Pass `true`, if the administrator can restrict, ban or unban chat + /// members. pub fn can_restrict_members(mut self, val: bool) -> Self { self.can_restrict_members = Some(val); self } + /// Pass `true`, if the administrator can pin messages, supergroups only. pub fn can_pin_messages(mut self, val: bool) -> Self { self.can_pin_messages = Some(val); self } + /// Pass `true`, if the administrator can add new administrators with a + /// subset of his own privileges or demote administrators that he has + /// promoted, directly or indirectly (promoted by administrators that were + /// appointed by him). pub fn can_promote_members(mut self, val: bool) -> Self { self.can_promote_members = Some(val); self diff --git a/src/requests/all/restrict_chat_member.rs b/src/requests/all/restrict_chat_member.rs index abcedb30..918571a6 100644 --- a/src/requests/all/restrict_chat_member.rs +++ b/src/requests/all/restrict_chat_member.rs @@ -1,32 +1,28 @@ use serde::Serialize; +use super::BotWrapper; use crate::{ - network, + net, requests::{Request, ResponseResult}, types::{ChatId, ChatPermissions, True}, Bot, }; -/// Use this method to restrict a user in a supergroup. The bot must be an -/// administrator in the supergroup for this to work and must have the -/// appropriate admin rights. Pass True for all permissions to lift restrictions -/// from a user. Returns True on success. +/// Use this method to restrict a user in a supergroup. +/// +/// The bot must be an administrator in the supergroup for this to work and must +/// have the appropriate admin rights. Pass `true` for all permissions to lift +/// restrictions from a user. +/// +/// [The official docs](https://core.telegram.org/bots/api#restrictchatmember). #[serde_with_macros::skip_serializing_none] -#[derive(Debug, Clone, Serialize)] +#[derive(Eq, PartialEq, Debug, Clone, Serialize)] pub struct RestrictChatMember<'a> { #[serde(skip_serializing)] - bot: &'a Bot, - - /// Unique identifier for the target chat or username of the target - /// supergroup (in the format @supergroupusername) + bot: BotWrapper<'a>, chat_id: ChatId, - /// Unique identifier of the target user user_id: i32, - /// New user permissions permissions: ChatPermissions, - /// Date when restrictions will be lifted for the user, unix time. If user - /// is restricted for more than 366 days or less than 30 seconds from the - /// current time, they are considered to be restricted forever until_date: Option, } @@ -35,7 +31,7 @@ impl Request for RestrictChatMember<'_> { type Output = True; async fn send(&self) -> ResponseResult { - network::request_json( + net::request_json( self.bot.client(), self.bot.token(), "restrictChatMember", @@ -57,7 +53,7 @@ impl<'a> RestrictChatMember<'a> { { let chat_id = chat_id.into(); Self { - bot, + bot: BotWrapper(bot), chat_id, user_id, permissions, @@ -65,6 +61,8 @@ impl<'a> RestrictChatMember<'a> { } } + /// Unique identifier for the target chat or username of the target + /// supergroup (in the format `@supergroupusername`). pub fn chat_id(mut self, val: T) -> Self where T: Into, @@ -73,16 +71,22 @@ impl<'a> RestrictChatMember<'a> { self } + /// Unique identifier of the target user. pub fn user_id(mut self, val: i32) -> Self { self.user_id = val; self } + /// New user permissions. pub fn permissions(mut self, val: ChatPermissions) -> Self { self.permissions = val; self } + /// Date when restrictions will be lifted for the user, unix time. + /// + /// If user is restricted for more than 366 days or less than 30 seconds + /// from the current time, they are considered to be restricted forever. pub fn until_date(mut self, val: i32) -> Self { self.until_date = Some(val); self diff --git a/src/requests/all/send_animation.rs b/src/requests/all/send_animation.rs index 9a9548f7..1584cc16 100644 --- a/src/requests/all/send_animation.rs +++ b/src/requests/all/send_animation.rs @@ -1,5 +1,6 @@ +use super::BotWrapper; use crate::{ - network, + net, requests::{form_builder::FormBuilder, Request, ResponseResult}, types::{ChatId, InputFile, Message, ParseMode, ReplyMarkup}, Bot, @@ -8,52 +9,23 @@ use crate::{ /// Use this method to send animation files (GIF or H.264/MPEG-4 AVC video /// without sound). /// -/// On success, the sent Message is returned. -/// /// Bots can currently send animation files of up to 50 MB in size, this limit /// may be changed in the future. -#[derive(Debug, Clone)] +/// +/// [The official docs](https://core.telegram.org/bots/api#sendanimation). +#[derive(Eq, PartialEq, Debug, Clone)] pub struct SendAnimation<'a> { - bot: &'a Bot, - - /// Unique identifier for the target chat or username of the target channel - /// (in the format `@channelusername`) + bot: BotWrapper<'a>, pub chat_id: ChatId, - /// Animation to send. pub animation: InputFile, - /// Duration of sent animation in seconds pub duration: Option, - /// Animation width pub width: Option, - /// Animation height pub height: Option, - /// Thumbnail of the file sent; can be ignored if thumbnail generation for - /// the file is supported server-side. The thumbnail should be in JPEG - /// format and less than 200 kB in size. A thumbnail‘s width and height - /// should not exceed 320. Ignored if the file is not uploaded using - /// [`InputFile::File`]. Thumbnails can’t be reused and can be only - /// uploaded as a new file, with [`InputFile::File`] - /// - /// [`InputFile::File`]: crate::types::InputFile::File pub thumb: Option, - /// Animation caption, `0`-`1024` characters pub caption: Option, - /// Send [Markdown] or [HTML], if you want Telegram apps to show - /// [bold, italic, fixed-width text or inline URLs] in the media caption. - /// - /// [Markdown]: crate::types::ParseMode::Markdown - /// [HTML]: crate::types::ParseMode::HTML - /// [bold, italic, fixed-width text or inline URLs]: - /// crate::types::ParseMode pub parse_mode: Option, - /// Sends the message silently. Users will receive a notification with no - /// sound. pub disable_notification: Option, - /// If the message is a reply, [id] of the original message - /// - /// [id]: crate::types::Message::id pub reply_to_message_id: Option, - /// Additional interface options pub reply_markup: Option, } @@ -62,7 +34,7 @@ impl Request for SendAnimation<'_> { type Output = Message; async fn send(&self) -> ResponseResult { - network::request_multipart( + net::request_multipart( self.bot.client(), self.bot.token(), "sendAnimation", @@ -101,7 +73,7 @@ impl<'a> SendAnimation<'a> { C: Into, { Self { - bot, + bot: BotWrapper(bot), chat_id: chat_id.into(), animation, duration: None, @@ -116,6 +88,8 @@ impl<'a> SendAnimation<'a> { } } + /// Unique identifier for the target chat or username of the target channel + /// (in the format `@channelusername`). pub fn chat_id(mut self, value: T) -> Self where T: Into, @@ -124,24 +98,46 @@ impl<'a> SendAnimation<'a> { self } + /// Animation to send. + pub fn animation(mut self, val: InputFile) -> Self { + self.animation = val; + self + } + + /// Duration of sent animation in seconds. pub fn duration(mut self, value: u32) -> Self { self.duration = Some(value); self } + /// Animation width. pub fn width(mut self, value: u32) -> Self { self.width = Some(value); self } + + /// Animation height. pub fn height(mut self, value: u32) -> Self { self.height = Some(value); self } + + /// Thumbnail of the file sent; can be ignored if thumbnail generation for + /// the file is supported server-side. + /// + /// The thumbnail should be in JPEG format and less than 200 kB in size. A + /// thumbnail‘s width and height should not exceed 320. Ignored if the + /// file is not uploaded using [`InputFile::File`]. Thumbnails can’t be + /// reused and can be only uploaded as a new file, with + /// [`InputFile::File`]. + /// + /// [`InputFile::File`]: crate::types::InputFile::File pub fn thumb(mut self, value: InputFile) -> Self { self.thumb = Some(value); self } + /// Animation caption, `0`-`1024` characters. pub fn caption(mut self, value: T) -> Self where T: Into, @@ -149,18 +145,35 @@ impl<'a> SendAnimation<'a> { self.caption = Some(value.into()); self } + + /// Send [Markdown] or [HTML], if you want Telegram apps to show + /// [bold, italic, fixed-width text or inline URLs] in the media caption. + /// + /// [Markdown]: crate::types::ParseMode::Markdown + /// [HTML]: crate::types::ParseMode::HTML + /// [bold, italic, fixed-width text or inline URLs]: + /// crate::types::ParseMode pub fn parse_mode(mut self, value: ParseMode) -> Self { self.parse_mode = Some(value); self } + + /// Sends the message silently. Users will receive a notification with no + /// sound. pub fn disable_notification(mut self, value: bool) -> Self { self.disable_notification = Some(value); self } + + /// If the message is a reply, [id] of the original message. + /// + /// [id]: crate::types::Message::id pub fn reply_to_message_id(mut self, value: i32) -> Self { self.reply_to_message_id = Some(value); self } + + /// Additional interface options. pub fn reply_markup(mut self, value: T) -> Self where T: Into, diff --git a/src/requests/all/send_audio.rs b/src/requests/all/send_audio.rs index 8ca739a2..9be59300 100644 --- a/src/requests/all/send_audio.rs +++ b/src/requests/all/send_audio.rs @@ -1,55 +1,35 @@ +use super::BotWrapper; use crate::{ - network, + net, requests::{form_builder::FormBuilder, Request, ResponseResult}, types::{ChatId, InputFile, Message, ParseMode, ReplyMarkup}, Bot, }; /// Use this method to send audio files, if you want Telegram clients to display -/// them in the music player. Your audio must be in the .MP3 or .M4A format. On -/// success, the sent Message is returned. Bots can currently send audio files -/// of up to 50 MB in size, this limit may be changed in the future.For sending -/// voice messages, use the sendVoice method instead. -#[derive(Debug, Clone)] +/// them in the music player. +/// +/// Your audio must be in the .MP3 or .M4A format. Bots can currently send audio +/// files of up to 50 MB in size, this limit may be changed in the future. +/// +/// For sending voice messages, use the [`Bot::send_voice`] method instead. +/// +/// [The official docs](https://core.telegram.org/bots/api#sendaudio). +/// +/// [`Bot::send_voice`]: crate::Bot::send_voice +#[derive(Eq, PartialEq, Debug, Clone)] pub struct SendAudio<'a> { - bot: &'a Bot, - - /// Unique identifier for the target chat or username of the target channel - /// (in the format @channelusername) + bot: BotWrapper<'a>, chat_id: ChatId, - /// Audio file to send. Pass a file_id as String to send an audio file that - /// exists on the Telegram servers (recommended), pass an HTTP URL as a - /// String for Telegram to get an audio file from the Internet, or upload a - /// new one using multipart/form-data. More info on Sending Files » audio: InputFile, - /// Audio caption, 0-1024 characters caption: Option, - /// Send Markdown or HTML, if you want Telegram apps to show bold, italic, - /// fixed-width text or inline URLs in the media caption. parse_mode: Option, - /// Duration of the audio in seconds duration: Option, - /// Performer performer: Option, - /// Track name title: Option, - /// Thumbnail of the file sent; can be ignored if thumbnail generation for - /// the file is supported server-side. The thumbnail should be in JPEG - /// format and less than 200 kB in size. A thumbnail‘s width and height - /// should not exceed 320. Ignored if the file is not uploaded using - /// multipart/form-data. Thumbnails can’t be reused and can be only - /// uploaded as a new file, so you can pass “attach://” - /// if the thumbnail was uploaded using multipart/form-data under - /// . More info on Sending Files » thumb: Option, - /// Sends the message silently. Users will receive a notification with no - /// sound. disable_notification: Option, - /// If the message is a reply, ID of the original message reply_to_message_id: Option, - /// Additional interface options. A JSON-serialized object for an inline - /// keyboard, custom reply keyboard, instructions to remove reply keyboard - /// or to force a reply from the user. reply_markup: Option, } @@ -58,7 +38,7 @@ impl Request for SendAudio<'_> { type Output = Message; async fn send(&self) -> ResponseResult { - network::request_multipart( + net::request_multipart( self.bot.client(), self.bot.token(), "sendAudio", @@ -97,7 +77,7 @@ impl<'a> SendAudio<'a> { C: Into, { Self { - bot, + bot: BotWrapper(bot), chat_id: chat_id.into(), audio, caption: None, @@ -112,6 +92,8 @@ impl<'a> SendAudio<'a> { } } + /// Unique identifier for the target chat or username of the target channel + /// (in the format `@channelusername`). pub fn chat_id(mut self, val: T) -> Self where T: Into, @@ -120,11 +102,24 @@ impl<'a> SendAudio<'a> { self } + /// Audio file to send. + /// + /// Pass [`InputFile::File`] to send a file that exists on + /// the Telegram servers (recommended), pass an [`InputFile::Url`] for + /// Telegram to get a .webp file from the Internet, or upload a new one + /// using [`InputFile::FileId`]. [More info on Sending Files »]. + /// + /// [`InputFile::File`]: crate::types::InputFile::File + /// [`InputFile::Url`]: crate::types::InputFile::Url + /// [`InputFile::FileId`]: crate::types::InputFile::FileId + /// + /// [More info on Sending Files »]: https://core.telegram.org/bots/api#sending-files pub fn audio(mut self, val: InputFile) -> Self { self.audio = val; self } + /// Audio caption, 0-1024 characters. pub fn caption(mut self, val: T) -> Self where T: Into, @@ -133,16 +128,25 @@ impl<'a> SendAudio<'a> { self } + /// Send [Markdown] or [HTML], if you want Telegram apps to show + /// [bold, italic, fixed-width text or inline URLs] in the media caption. + /// + /// [Markdown]: crate::types::ParseMode::Markdown + /// [HTML]: crate::types::ParseMode::HTML + /// [bold, italic, fixed-width text or inline URLs]: + /// crate::types::ParseMode pub fn parse_mode(mut self, val: ParseMode) -> Self { self.parse_mode = Some(val); self } + /// Duration of the audio in seconds. pub fn duration(mut self, val: i32) -> Self { self.duration = Some(val); self } + /// Performer. pub fn performer(mut self, val: T) -> Self where T: Into, @@ -151,6 +155,7 @@ impl<'a> SendAudio<'a> { self } + /// Track name. pub fn title(mut self, val: T) -> Self where T: Into, @@ -159,21 +164,44 @@ impl<'a> SendAudio<'a> { self } + /// Thumbnail of the file sent; can be ignored if thumbnail generation for + /// the file is supported server-side. + /// + /// The thumbnail should be in JPEG format and less than 200 kB in size. A + /// thumbnail‘s width and height should not exceed 320. Ignored if the + /// file is not uploaded using `multipart/form-data`. Thumbnails can’t + /// be reused and can be only uploaded as a new file, so you can pass + /// `attach://` if the thumbnail was uploaded using + /// `multipart/form-data` under ``. [More info on + /// Sending Files »]. + /// + /// [More info on Sending Files »]: https://core.telegram.org/bots/api#sending-files pub fn thumb(mut self, val: InputFile) -> Self { self.thumb = Some(val); self } + /// Sends the message [silently]. Users will receive a notification with no + /// sound. + /// + /// [silently]: https://telegram.org/blog/channels-2-0#silent-messages pub fn disable_notification(mut self, val: bool) -> Self { self.disable_notification = Some(val); self } + /// If the message is a reply, ID of the original message. pub fn reply_to_message_id(mut self, val: i32) -> Self { self.reply_to_message_id = Some(val); self } + /// Additional interface options. A JSON-serialized object for an [inline + /// keyboard], [custom reply keyboard], instructions to remove reply + /// keyboard or to force a reply from the user. + /// + /// [inline keyboard]: https://core.telegram.org/bots#inline-keyboards-and-on-the-fly-updating + /// [custom reply keyboard]: https://core.telegram.org/bots#keyboards pub fn reply_markup(mut self, val: ReplyMarkup) -> Self { self.reply_markup = Some(val); self diff --git a/src/requests/all/send_chat_action.rs b/src/requests/all/send_chat_action.rs index 9efc04cb..6718ae8f 100644 --- a/src/requests/all/send_chat_action.rs +++ b/src/requests/all/send_chat_action.rs @@ -1,39 +1,43 @@ use serde::{Deserialize, Serialize}; +use super::BotWrapper; use crate::{ - network, + net, requests::{Request, ResponseResult}, types::{ChatId, True}, Bot, }; /// Use this method when you need to tell the user that something is happening -/// on the bot's side. The status is set for 5 seconds or less (when a message -/// arrives from your bot, Telegram clients clear its typing status). Returns -/// True on success.Example: The ImageBot needs some time to process a request -/// and upload the image. Instead of sending a text message along the lines of -/// “Retrieving image, please wait…”, the bot may use sendChatAction with action -/// = upload_photo. The user will see a “sending photo” status for the bot.We -/// only recommend using this method when a response from the bot will take a -/// noticeable amount of time to arrive. +/// on the bot's side. +/// +/// The status is set for 5 seconds or less (when a message arrives from your +/// bot, Telegram clients clear its typing status). +/// +/// ## Note +/// Example: The [ImageBot] needs some time to process a request and upload the +/// image. Instead of sending a text message along the lines of “Retrieving +/// image, please wait…”, the bot may use [`Bot::send_chat_action`] with `action +/// = upload_photo`. The user will see a `sending photo` status for the bot. +/// +/// We only recommend using this method when a response from the bot will take a +/// **noticeable** amount of time to arrive. +/// +/// [ImageBot]: https://t.me/imagebot +/// [`Bot::send_chat_action`]: crate::Bot::send_chat_action #[serde_with_macros::skip_serializing_none] -#[derive(Debug, Clone, Serialize)] +#[derive(Eq, PartialEq, Debug, Clone, Serialize)] pub struct SendChatAction<'a> { #[serde(skip_serializing)] - bot: &'a Bot, - - /// Unique identifier for the target chat or username of the target channel - /// (in the format @channelusername) + bot: BotWrapper<'a>, chat_id: ChatId, - - /// Type of action to broadcast. action: SendChatActionKind, } /// A type of action used in [`SendChatAction`]. /// /// [`SendChatAction`]: crate::requests::SendChatAction -#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq, Serialize, Deserialize)] +#[derive(PartialEq, Copy, Clone, Debug, Eq, Hash, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum SendChatActionKind { /// For [text messages](crate::Bot::send_message). @@ -72,7 +76,7 @@ impl Request for SendChatAction<'_> { type Output = True; async fn send(&self) -> ResponseResult { - network::request_json( + net::request_json( self.bot.client(), self.bot.token(), "sendChatAction", @@ -92,12 +96,14 @@ impl<'a> SendChatAction<'a> { C: Into, { Self { - bot, + bot: BotWrapper(bot), chat_id: chat_id.into(), action, } } + /// Unique identifier for the target chat or username of the target channel + /// (in the format `@channelusername`). pub fn chat_id(mut self, val: T) -> Self where T: Into, @@ -106,6 +112,7 @@ impl<'a> SendChatAction<'a> { self } + /// Type of action to broadcast. pub fn action(mut self, val: SendChatActionKind) -> Self { self.action = val; self diff --git a/src/requests/all/send_contact.rs b/src/requests/all/send_contact.rs index 326c656b..97cda878 100644 --- a/src/requests/all/send_contact.rs +++ b/src/requests/all/send_contact.rs @@ -1,39 +1,28 @@ use serde::Serialize; +use super::BotWrapper; use crate::{ - network, + net, requests::{Request, ResponseResult}, types::{ChatId, Message, ReplyMarkup}, Bot, }; -/// Use this method to send phone contacts. On success, the sent Message is -/// returned. +/// Use this method to send phone contacts. +/// +/// [The official docs](https://core.telegram.org/bots/api#sendcontact). #[serde_with_macros::skip_serializing_none] -#[derive(Debug, Clone, Serialize)] +#[derive(Eq, PartialEq, Debug, Clone, Serialize)] pub struct SendContact<'a> { #[serde(skip_serializing)] - bot: &'a Bot, - - /// Unique identifier for the target chat or username of the target channel - /// (in the format @channelusername) + bot: BotWrapper<'a>, chat_id: ChatId, - /// Contact's phone number phone_number: String, - /// Contact's first name first_name: String, - /// Contact's last name last_name: Option, - /// Additional data about the contact in the form of a vCard, 0-2048 bytes vcard: Option, - /// Sends the message silently. Users will receive a notification with no - /// sound. disable_notification: Option, - /// If the message is a reply, ID of the original message reply_to_message_id: Option, - /// Additional interface options. A JSON-serialized object for an inline - /// keyboard, custom reply keyboard, instructions to remove keyboard or to - /// force a reply from the user. reply_markup: Option, } @@ -42,7 +31,7 @@ impl Request for SendContact<'_> { type Output = Message; async fn send(&self) -> ResponseResult { - network::request_json( + net::request_json( self.bot.client(), self.bot.token(), "sendContact", @@ -68,7 +57,7 @@ impl<'a> SendContact<'a> { let phone_number = phone_number.into(); let first_name = first_name.into(); Self { - bot, + bot: BotWrapper(bot), chat_id, phone_number, first_name, @@ -80,6 +69,8 @@ impl<'a> SendContact<'a> { } } + /// Unique identifier for the target chat or username of the target channel + /// (in the format `@channelusername`). pub fn chat_id(mut self, val: T) -> Self where T: Into, @@ -88,6 +79,7 @@ impl<'a> SendContact<'a> { self } + /// Contact's phone number. pub fn phone_number(mut self, val: T) -> Self where T: Into, @@ -96,6 +88,7 @@ impl<'a> SendContact<'a> { self } + /// Contact's first name. pub fn first_name(mut self, val: T) -> Self where T: Into, @@ -104,6 +97,7 @@ impl<'a> SendContact<'a> { self } + /// Contact's last name. pub fn last_name(mut self, val: T) -> Self where T: Into, @@ -112,6 +106,10 @@ impl<'a> SendContact<'a> { self } + /// Additional data about the contact in the form of a [vCard], 0-2048 + /// bytes. + /// + /// [vCard]: https://en.wikipedia.org/wiki/VCard pub fn vcard(mut self, val: T) -> Self where T: Into, @@ -120,16 +118,22 @@ impl<'a> SendContact<'a> { self } + /// Sends the message [silently]. Users will receive a notification with no + /// sound. + /// + /// [silently]: https://telegram.org/blog/channels-2-0#silent-messages pub fn disable_notification(mut self, val: bool) -> Self { self.disable_notification = Some(val); self } + /// If the message is a reply, ID of the original message. pub fn reply_to_message_id(mut self, val: i32) -> Self { self.reply_to_message_id = Some(val); self } + /// Additional interface options. pub fn reply_markup(mut self, val: ReplyMarkup) -> Self { self.reply_markup = Some(val); self diff --git a/src/requests/all/send_document.rs b/src/requests/all/send_document.rs index d3e6cc36..a2175156 100644 --- a/src/requests/all/send_document.rs +++ b/src/requests/all/send_document.rs @@ -1,48 +1,27 @@ +use super::BotWrapper; use crate::{ - network, + net, requests::{form_builder::FormBuilder, Request, ResponseResult}, types::{ChatId, InputFile, Message, ParseMode, ReplyMarkup}, Bot, }; -/// Use this method to send general files. On success, the sent Message is -/// returned. Bots can currently send files of any type of up to 50 MB in size, -/// this limit may be changed in the future. -#[derive(Debug, Clone)] +/// Use this method to send general files. +/// +/// Bots can currently send files of any type of up to 50 MB in size, this limit +/// may be changed in the future. +/// +/// [The official docs](https://core.telegram.org/bots/api#senddocument). +#[derive(Eq, PartialEq, Debug, Clone)] pub struct SendDocument<'a> { - bot: &'a Bot, - - /// Unique identifier for the target chat or username of the target channel - /// (in the format @channelusername) + bot: BotWrapper<'a>, chat_id: ChatId, - /// File to send. Pass a file_id as String to send a file that exists on - /// the Telegram servers (recommended), pass an HTTP URL as a String for - /// Telegram to get a file from the Internet, or upload a new one using - /// multipart/form-data. More info on Sending Files » document: InputFile, - /// Thumbnail of the file sent; can be ignored if thumbnail generation for - /// the file is supported server-side. The thumbnail should be in JPEG - /// format and less than 200 kB in size. A thumbnail‘s width and height - /// should not exceed 320. Ignored if the file is not uploaded using - /// multipart/form-data. Thumbnails can’t be reused and can be only - /// uploaded as a new file, so you can pass “attach://” - /// if the thumbnail was uploaded using multipart/form-data under - /// . More info on Sending Files » thumb: Option, - /// Document caption (may also be used when resending documents by - /// file_id), 0-1024 characters caption: Option, - /// Send Markdown or HTML, if you want Telegram apps to show bold, italic, - /// fixed-width text or inline URLs in the media caption. parse_mode: Option, - /// Sends the message silently. Users will receive a notification with no - /// sound. disable_notification: Option, - /// If the message is a reply, ID of the original message reply_to_message_id: Option, - /// Additional interface options. A JSON-serialized object for an inline - /// keyboard, custom reply keyboard, instructions to remove reply keyboard - /// or to force a reply from the user. reply_markup: Option, } @@ -51,7 +30,7 @@ impl Request for SendDocument<'_> { type Output = Message; async fn send(&self) -> ResponseResult { - network::request_multipart( + net::request_multipart( self.bot.client(), self.bot.token(), "sendDocument", @@ -84,7 +63,7 @@ impl<'a> SendDocument<'a> { C: Into, { Self { - bot, + bot: BotWrapper(bot), chat_id: chat_id.into(), document, thumb: None, @@ -96,6 +75,8 @@ impl<'a> SendDocument<'a> { } } + /// Unique identifier for the target chat or username of the target channel + /// (in the format `@channelusername`). pub fn chat_id(mut self, val: T) -> Self where T: Into, @@ -104,16 +85,38 @@ impl<'a> SendDocument<'a> { self } + /// File to send. + /// + /// Pass a file_id as String to send a file that exists on the + /// Telegram servers (recommended), pass an HTTP URL as a String for + /// Telegram to get a file from the Internet, or upload a new one using + /// `multipart/form-data`. [More info on Sending Files »]. + /// + /// [More info on Sending Files »]: https://core.telegram.org/bots/api#sending-files pub fn document(mut self, val: InputFile) -> Self { self.document = val; self } + /// Thumbnail of the file sent; can be ignored if thumbnail generation for + /// the file is supported server-side. + /// + /// The thumbnail should be in JPEG format and less than 200 kB in size. A + /// thumbnail‘s width and height should not exceed 320. Ignored if the + /// file is not uploaded using `multipart/form-data`. Thumbnails can’t + /// be reused and can be only uploaded as a new file, so you can pass + /// “attach://” if the thumbnail was uploaded using + /// `multipart/form-data` under ``. [More info on + /// Sending Files »]. + /// + /// [More info on Sending Files »]: https://core.telegram.org/bots/api#sending-files pub fn thumb(mut self, val: InputFile) -> Self { self.thumb = Some(val); self } + /// Document caption (may also be used when resending documents by + /// `file_id`), 0-1024 characters. pub fn caption(mut self, val: T) -> Self where T: Into, @@ -122,21 +125,34 @@ impl<'a> SendDocument<'a> { self } + /// Send [Markdown] or [HTML], if you want Telegram apps to show + /// [bold, italic, fixed-width text or inline URLs] in the media caption. + /// + /// [Markdown]: crate::types::ParseMode::Markdown + /// [HTML]: crate::types::ParseMode::HTML + /// [bold, italic, fixed-width text or inline URLs]: + /// crate::types::ParseMode pub fn parse_mode(mut self, val: ParseMode) -> Self { self.parse_mode = Some(val); self } + /// Sends the message [silently]. Users will receive a notification with no + /// sound. + /// + /// [silently]: https://telegram.org/blog/channels-2-0#silent-messages pub fn disable_notification(mut self, val: bool) -> Self { self.disable_notification = Some(val); self } + /// If the message is a reply, ID of the original message. pub fn reply_to_message_id(mut self, val: i32) -> Self { self.reply_to_message_id = Some(val); self } + /// Additional interface options. pub fn reply_markup(mut self, val: ReplyMarkup) -> Self { self.reply_markup = Some(val); self diff --git a/src/requests/all/send_game.rs b/src/requests/all/send_game.rs index 0480791f..bc3056aa 100644 --- a/src/requests/all/send_game.rs +++ b/src/requests/all/send_game.rs @@ -1,32 +1,25 @@ use serde::Serialize; +use super::BotWrapper; use crate::{ - network, + net, requests::{Request, ResponseResult}, types::{InlineKeyboardMarkup, Message}, Bot, }; -/// Use this method to send a game. On success, the sent Message is returned. +/// Use this method to send a game. +/// +/// [The official docs](https://core.telegram.org/bots/api#sendgame). #[serde_with_macros::skip_serializing_none] -#[derive(Debug, Clone, Serialize)] +#[derive(Eq, PartialEq, Debug, Clone, Serialize)] pub struct SendGame<'a> { #[serde(skip_serializing)] - bot: &'a Bot, - - /// Unique identifier for the target chat + bot: BotWrapper<'a>, chat_id: i32, - /// Short name of the game, serves as the unique identifier for the game. - /// Set up your games via Botfather. game_short_name: String, - /// Sends the message silently. Users will receive a notification with no - /// sound. disable_notification: Option, - /// If the message is a reply, ID of the original message reply_to_message_id: Option, - /// A JSON-serialized object for an inline keyboard. If empty, one ‘Play - /// game_title’ button will be shown. If not empty, the first button must - /// launch the game. reply_markup: Option, } @@ -35,7 +28,7 @@ impl Request for SendGame<'_> { type Output = Message; async fn send(&self) -> ResponseResult { - network::request_json( + net::request_json( self.bot.client(), self.bot.token(), "sendGame", @@ -52,7 +45,7 @@ impl<'a> SendGame<'a> { { let game_short_name = game_short_name.into(); Self { - bot, + bot: BotWrapper(bot), chat_id, game_short_name, disable_notification: None, @@ -61,11 +54,16 @@ impl<'a> SendGame<'a> { } } + /// Unique identifier for the target chat. pub fn chat_id(mut self, val: i32) -> Self { self.chat_id = val; self } + /// Short name of the game, serves as the unique identifier for the game. + /// Set up your games via [@Botfather]. + /// + /// [@Botfather]: https://t.me/botfather pub fn game_short_name(mut self, val: T) -> Self where T: Into, @@ -74,16 +72,26 @@ impl<'a> SendGame<'a> { self } + /// Sends the message [silently]. Users will receive a notification with no + /// sound. + /// + /// [silently]: https://telegram.org/blog/channels-2-0#silent-messages pub fn disable_notification(mut self, val: bool) -> Self { self.disable_notification = Some(val); self } + /// If the message is a reply, ID of the original message. pub fn reply_to_message_id(mut self, val: i32) -> Self { self.reply_to_message_id = Some(val); self } + /// A JSON-serialized object for an [inline keyboard]. If empty, one `Play + /// game_title` button will be shown. If not empty, the first button must + /// launch the game. + /// + /// [inline keyboard]: https://core.telegram.org/bots#inline-keyboards-and-on-the-fly-updating pub fn reply_markup(mut self, val: InlineKeyboardMarkup) -> Self { self.reply_markup = Some(val); self diff --git a/src/requests/all/send_invoice.rs b/src/requests/all/send_invoice.rs index 5d0bbcf4..99fbab15 100644 --- a/src/requests/all/send_invoice.rs +++ b/src/requests/all/send_invoice.rs @@ -1,76 +1,43 @@ use serde::Serialize; +use super::BotWrapper; use crate::{ - network, + net, requests::{Request, ResponseResult}, types::{InlineKeyboardMarkup, LabeledPrice, Message}, Bot, }; -/// Use this method to send invoices. On success, the sent Message is returned. +/// Use this method to send invoices. +/// +/// [The official docs](https://core.telegram.org/bots/api#sendinvoice). #[serde_with_macros::skip_serializing_none] -#[derive(Debug, Clone, Serialize)] +#[derive(Eq, PartialEq, Debug, Clone, Serialize)] pub struct SendInvoice<'a> { #[serde(skip_serializing)] - bot: &'a Bot, - - /// Unique identifier for the target private chat + bot: BotWrapper<'a>, chat_id: i32, - /// Product name, 1-32 characters title: String, - /// Product description, 1-255 characters description: String, - /// Bot-defined invoice payload, 1-128 bytes. This will not be displayed to - /// the user, use for your internal processes. payload: String, - /// Payments provider token, obtained via Botfather provider_token: String, - /// Unique deep-linking parameter that can be used to generate this invoice - /// when used as a start parameter start_parameter: String, - /// Three-letter ISO 4217 currency code, see more on currencies currency: String, - /// Price breakdown, a list of components (e.g. product price, tax, - /// discount, delivery cost, delivery tax, bonus, etc.) prices: Vec, - /// JSON-encoded data about the invoice, which will be shared with the - /// payment provider. A detailed description of required fields should be - /// provided by the payment provider. provider_data: Option, - /// URL of the product photo for the invoice. Can be a photo of the goods - /// or a marketing image for a service. People like it better when they see - /// what they are paying for. photo_url: Option, - /// Photo size photo_size: Option, - /// Photo width photo_width: Option, - /// Photo height photo_height: Option, - /// Pass True, if you require the user's full name to complete the order need_name: Option, - /// Pass True, if you require the user's phone number to complete the order need_phone_number: Option, - /// Pass True, if you require the user's email address to complete the - /// order need_email: Option, - /// Pass True, if you require the user's shipping address to complete the - /// order need_shipping_address: Option, - /// Pass True, if user's phone number should be sent to provider send_phone_number_to_provider: Option, - /// Pass True, if user's email address should be sent to provider send_email_to_provider: Option, - /// Pass True, if the final price depends on the shipping method is_flexible: Option, - /// Sends the message silently. Users will receive a notification with no - /// sound. disable_notification: Option, - /// If the message is a reply, ID of the original message reply_to_message_id: Option, - /// A JSON-serialized object for an inline keyboard. If empty, one 'Pay - /// total price' button will be shown. If not empty, the first button must - /// be a Pay button. reply_markup: Option, } @@ -79,7 +46,7 @@ impl Request for SendInvoice<'_> { type Output = Message; async fn send(&self) -> ResponseResult { - network::request_json( + net::request_json( self.bot.client(), self.bot.token(), "sendInvoice", @@ -119,7 +86,7 @@ impl<'a> SendInvoice<'a> { let currency = currency.into(); let prices = prices.into(); Self { - bot, + bot: BotWrapper(bot), chat_id, title, description, @@ -146,11 +113,13 @@ impl<'a> SendInvoice<'a> { } } + /// Unique identifier for the target private chat. pub fn chat_id(mut self, val: i32) -> Self { self.chat_id = val; self } + /// Product name, 1-32 characters. pub fn title(mut self, val: T) -> Self where T: Into, @@ -159,6 +128,7 @@ impl<'a> SendInvoice<'a> { self } + /// Product description, 1-255 characters. pub fn description(mut self, val: T) -> Self where T: Into, @@ -167,6 +137,8 @@ impl<'a> SendInvoice<'a> { self } + /// Bot-defined invoice payload, 1-128 bytes. This will not be displayed to + /// the user, use for your internal processes. pub fn payload(mut self, val: T) -> Self where T: Into, @@ -175,6 +147,9 @@ impl<'a> SendInvoice<'a> { self } + /// Payments provider token, obtained via [@Botfather]. + /// + /// [@Botfather]: https://t.me/botfather pub fn provider_token(mut self, val: T) -> Self where T: Into, @@ -183,6 +158,8 @@ impl<'a> SendInvoice<'a> { self } + /// Unique deep-linking parameter that can be used to generate this invoice + /// when used as a start parameter. pub fn start_parameter(mut self, val: T) -> Self where T: Into, @@ -191,6 +168,9 @@ impl<'a> SendInvoice<'a> { self } + /// Three-letter ISO 4217 currency code, see [more on currencies]. + /// + /// [more on currencies]: https://core.telegram.org/bots/payments#supported-currencies pub fn currency(mut self, val: T) -> Self where T: Into, @@ -199,6 +179,8 @@ impl<'a> SendInvoice<'a> { self } + /// Price breakdown, a list of components (e.g. product price, tax, + /// discount, delivery cost, delivery tax, bonus, etc.). pub fn prices(mut self, val: T) -> Self where T: Into>, @@ -207,6 +189,11 @@ impl<'a> SendInvoice<'a> { self } + /// JSON-encoded data about the invoice, which will be shared with the + /// payment provider. + /// + /// A detailed description of required fields should be provided by the + /// payment provider. pub fn provider_data(mut self, val: T) -> Self where T: Into, @@ -215,6 +202,10 @@ impl<'a> SendInvoice<'a> { self } + /// URL of the product photo for the invoice. + /// + /// Can be a photo of the goods or a marketing image for a service. People + /// like it better when they see what they are paying for. pub fn photo_url(mut self, val: T) -> Self where T: Into, @@ -223,67 +214,91 @@ impl<'a> SendInvoice<'a> { self } + /// Photo size. pub fn photo_size(mut self, val: i32) -> Self { self.photo_size = Some(val); self } + /// Photo width. pub fn photo_width(mut self, val: i32) -> Self { self.photo_width = Some(val); self } + /// Photo height. pub fn photo_height(mut self, val: i32) -> Self { self.photo_height = Some(val); self } + /// Pass `true`, if you require the user's full name to complete the order. pub fn need_name(mut self, val: bool) -> Self { self.need_name = Some(val); self } + /// Pass `true`, if you require the user's phone number to complete the + /// order. pub fn need_phone_number(mut self, val: bool) -> Self { self.need_phone_number = Some(val); self } + /// Pass `true`, if you require the user's email address to complete the + /// order. pub fn need_email(mut self, val: bool) -> Self { self.need_email = Some(val); self } + /// Pass `true`, if you require the user's shipping address to complete the + /// order. pub fn need_shipping_address(mut self, val: bool) -> Self { self.need_shipping_address = Some(val); self } + /// Pass `true`, if user's phone number should be sent to provider. pub fn send_phone_number_to_provider(mut self, val: bool) -> Self { self.send_phone_number_to_provider = Some(val); self } + /// Pass `true`, if user's email address should be sent to provider. pub fn send_email_to_provider(mut self, val: bool) -> Self { self.send_email_to_provider = Some(val); self } + /// Pass `true`, if the final price depends on the shipping method. #[allow(clippy::wrong_self_convention)] pub fn is_flexible(mut self, val: bool) -> Self { self.is_flexible = Some(val); self } + /// Sends the message [silently]. Users will receive a notification with no + /// sound. + /// + /// [silently]: https://telegram.org/blog/channels-2-0#silent-messages pub fn disable_notification(mut self, val: bool) -> Self { self.disable_notification = Some(val); self } + /// If the message is a reply, ID of the original message. pub fn reply_to_message_id(mut self, val: i32) -> Self { self.reply_to_message_id = Some(val); self } + /// A JSON-serialized object for an [inline keyboard]. + /// + /// If empty, one 'Pay `total price`' button will be shown. If not empty, + /// the first button must be a Pay button. + /// + /// [inlint keyboard]: https://core.telegram.org/bots#inline-keyboards-and-on-the-fly-updating pub fn reply_markup(mut self, val: InlineKeyboardMarkup) -> Self { self.reply_markup = Some(val); self diff --git a/src/requests/all/send_location.rs b/src/requests/all/send_location.rs index e29582db..6ce4060e 100644 --- a/src/requests/all/send_location.rs +++ b/src/requests/all/send_location.rs @@ -1,38 +1,27 @@ use serde::Serialize; +use super::BotWrapper; use crate::{ - network, + net, requests::{Request, ResponseResult}, types::{ChatId, Message, ReplyMarkup}, Bot, }; -/// Use this method to send point on the map. On success, the sent Message is -/// returned. +/// Use this method to send point on the map. +/// +/// [The official docs](https://core.telegram.org/bots/api#sendlocation). #[serde_with_macros::skip_serializing_none] -#[derive(Debug, Clone, Serialize)] +#[derive(PartialEq, Debug, Clone, Serialize)] pub struct SendLocation<'a> { #[serde(skip_serializing)] - bot: &'a Bot, - - /// Unique identifier for the target chat or username of the target channel - /// (in the format @channelusername) + bot: BotWrapper<'a>, chat_id: ChatId, - /// Latitude of the location latitude: f32, - /// Longitude of the location longitude: f32, - /// Period in seconds for which the location will be updated (see Live - /// Locations, should be between 60 and 86400. live_period: Option, - /// Sends the message silently. Users will receive a notification with no - /// sound. disable_notification: Option, - /// If the message is a reply, ID of the original message reply_to_message_id: Option, - /// Additional interface options. A JSON-serialized object for an inline - /// keyboard, custom reply keyboard, instructions to remove reply keyboard - /// or to force a reply from the user. reply_markup: Option, } @@ -41,7 +30,7 @@ impl Request for SendLocation<'_> { type Output = Message; async fn send(&self) -> ResponseResult { - network::request_json( + net::request_json( self.bot.client(), self.bot.token(), "sendLocation", @@ -63,7 +52,7 @@ impl<'a> SendLocation<'a> { { let chat_id = chat_id.into(); Self { - bot, + bot: BotWrapper(bot), chat_id, latitude, longitude, @@ -74,6 +63,8 @@ impl<'a> SendLocation<'a> { } } + /// Unique identifier for the target chat or username of the target channel + /// (in the format `@channelusername`). pub fn chat_id(mut self, val: T) -> Self where T: Into, @@ -82,31 +73,48 @@ impl<'a> SendLocation<'a> { self } + /// Latitude of the location. pub fn latitude(mut self, val: f32) -> Self { self.latitude = val; self } + /// Longitude of the location. pub fn longitude(mut self, val: f32) -> Self { self.longitude = val; self } + /// Period in seconds for which the location will be updated (see [Live + /// Locations], should be between 60 and 86400). + /// + /// [Live Locations]: https://telegram.org/blog/live-locations pub fn live_period(mut self, val: i64) -> Self { self.live_period = Some(val); self } + /// Sends the message [silently]. Users will receive a notification with no + /// sound. + /// + /// [silently]: https://telegram.org/blog/channels-2-0#silent-messages pub fn disable_notification(mut self, val: bool) -> Self { self.disable_notification = Some(val); self } + /// If the message is a reply, ID of the original message. pub fn reply_to_message_id(mut self, val: i32) -> Self { self.reply_to_message_id = Some(val); self } + /// A JSON-serialized object for an [inline keyboard]. + /// + /// If empty, one 'Pay `total price`' button will be shown. If not empty, + /// the first button must be a Pay button. + /// + /// [inlint keyboard]: https://core.telegram.org/bots#inline-keyboards-and-on-the-fly-updating pub fn reply_markup(mut self, val: ReplyMarkup) -> Self { self.reply_markup = Some(val); self diff --git a/src/requests/all/send_media_group.rs b/src/requests/all/send_media_group.rs index e7bd331d..6576da97 100644 --- a/src/requests/all/send_media_group.rs +++ b/src/requests/all/send_media_group.rs @@ -1,26 +1,20 @@ +use super::BotWrapper; use crate::{ - network, + net, requests::{form_builder::FormBuilder, Request, ResponseResult}, types::{ChatId, InputMedia, Message}, Bot, }; -/// Use this method to send a group of photos or videos as an album. On success, -/// an array of the sent Messages is returned. -#[derive(Debug, Clone)] +/// Use this method to send a group of photos or videos as an album. +/// +/// [The official docs](https://core.telegram.org/bots/api#sendmediagroup). +#[derive(Eq, PartialEq, Debug, Clone)] pub struct SendMediaGroup<'a> { - bot: &'a Bot, - - /// Unique identifier for the target chat or username of the target channel - /// (in the format @channelusername) + bot: BotWrapper<'a>, chat_id: ChatId, - /// A JSON-serialized array describing photos and videos to be sent, must - /// include 2–10 items media: Vec, // TODO: InputMediaPhoto and InputMediaVideo - /// Sends the messages silently. Users will receive a notification with no - /// sound. disable_notification: Option, - /// If the messages are a reply, ID of the original message reply_to_message_id: Option, } @@ -29,7 +23,7 @@ impl Request for SendMediaGroup<'_> { type Output = Vec; async fn send(&self) -> ResponseResult> { - network::request_multipart( + net::request_multipart( self.bot.client(), self.bot.token(), "sendMediaGroup", @@ -57,7 +51,7 @@ impl<'a> SendMediaGroup<'a> { let chat_id = chat_id.into(); let media = media.into(); Self { - bot, + bot: BotWrapper(bot), chat_id, media, disable_notification: None, @@ -65,6 +59,8 @@ impl<'a> SendMediaGroup<'a> { } } + /// Unique identifier for the target chat or username of the target channel + /// (in the format `@channelusername`). pub fn chat_id(mut self, val: T) -> Self where T: Into, @@ -73,6 +69,8 @@ impl<'a> SendMediaGroup<'a> { self } + /// A JSON-serialized array describing photos and videos to be sent, must + /// include 2–10 items. pub fn media(mut self, val: T) -> Self where T: Into>, @@ -81,11 +79,16 @@ impl<'a> SendMediaGroup<'a> { self } + /// Sends the message [silently]. Users will receive a notification with no + /// sound. + /// + /// [silently]: https://telegram.org/blog/channels-2-0#silent-messages pub fn disable_notification(mut self, val: bool) -> Self { self.disable_notification = Some(val); self } + /// If the messages are a reply, ID of the original message. pub fn reply_to_message_id(mut self, val: i32) -> Self { self.reply_to_message_id = Some(val); self diff --git a/src/requests/all/send_message.rs b/src/requests/all/send_message.rs index 3b4ff715..f19792fe 100644 --- a/src/requests/all/send_message.rs +++ b/src/requests/all/send_message.rs @@ -1,7 +1,8 @@ use serde::Serialize; +use super::BotWrapper; use crate::{ - network, + net, requests::{Request, ResponseResult}, types::{ChatId, Message, ParseMode, ReplyMarkup}, Bot, @@ -9,38 +10,18 @@ use crate::{ /// Use this method to send text messages. /// -/// On success, the sent [`Message`] is returned. -/// -/// [`Message`]: crate::types::Message +/// [The official docs](https://core.telegram.org/bots/api#sendmessage). #[serde_with_macros::skip_serializing_none] -#[derive(Debug, Clone, Serialize)] +#[derive(Eq, PartialEq, Debug, Clone, Serialize)] pub struct SendMessage<'a> { #[serde(skip_serializing)] - bot: &'a Bot, - - /// Unique identifier for the target chat or username of the target channel - /// (in the format `@channelusername`) + bot: BotWrapper<'a>, pub chat_id: ChatId, - /// Text of the message to be sent pub text: String, - /// Send [Markdown] or [HTML], if you want Telegram apps to show - /// [bold, italic, fixed-width text or inline URLs] in your bot's message. - /// - /// [Markdown]: crate::types::ParseMode::Markdown - /// [HTML]: crate::types::ParseMode::HTML - /// [bold, italic, fixed-width text or inline URLs]: - /// crate::types::ParseMode pub parse_mode: Option, - /// Disables link previews for links in this message pub disable_web_page_preview: Option, - /// Sends the message silently. - /// Users will receive a notification with no sound. pub disable_notification: Option, - /// If the message is a reply, [id] of the original message - /// - /// [id]: crate::types::Message::id pub reply_to_message_id: Option, - /// Additional interface options. pub reply_markup: Option, } @@ -49,7 +30,7 @@ impl Request for SendMessage<'_> { type Output = Message; async fn send(&self) -> ResponseResult { - network::request_json( + net::request_json( self.bot.client(), self.bot.token(), "sendMessage", @@ -66,7 +47,7 @@ impl<'a> SendMessage<'a> { T: Into, { Self { - bot, + bot: BotWrapper(bot), chat_id: chat_id.into(), text: text.into(), parse_mode: None, @@ -77,6 +58,8 @@ impl<'a> SendMessage<'a> { } } + /// Unique identifier for the target chat or username of the target channel + /// (in the format `@channelusername`). pub fn chat_id(mut self, value: T) -> Self where T: Into, @@ -85,6 +68,7 @@ impl<'a> SendMessage<'a> { self } + /// Text of the message to be sent. pub fn text(mut self, value: T) -> Self where T: Into, @@ -93,26 +77,47 @@ impl<'a> SendMessage<'a> { self } + /// Send [Markdown] or [HTML], if you want Telegram apps to show + /// [bold, italic, fixed-width text or inline URLs] in the media caption. + /// + /// [Markdown]: crate::types::ParseMode::Markdown + /// [HTML]: crate::types::ParseMode::HTML + /// [bold, italic, fixed-width text or inline URLs]: + /// crate::types::ParseMode pub fn parse_mode(mut self, value: ParseMode) -> Self { self.parse_mode = Some(value); self } + /// Disables link previews for links in this message. pub fn disable_web_page_preview(mut self, value: bool) -> Self { self.disable_web_page_preview = Some(value); self } + /// Sends the message [silently]. Users will receive a notification with no + /// sound. + /// + /// [silently]: https://telegram.org/blog/channels-2-0#silent-messages pub fn disable_notification(mut self, value: bool) -> Self { self.disable_notification = Some(value); self } + /// If the message is a reply, ID of the original message. pub fn reply_to_message_id(mut self, value: i32) -> Self { self.reply_to_message_id = Some(value); self } + /// Additional interface options. + /// + /// A JSON-serialized object for an [inline keyboard], [custom reply + /// keyboard], instructions to remove reply keyboard or to force a reply + /// from the user. + /// + /// [inline keyboard]: https://core.telegram.org/bots#inline-keyboards-and-on-the-fly-updating + /// [custom reply keyboard]: https://core.telegram.org/bots#keyboards pub fn reply_markup(mut self, value: T) -> Self where T: Into, diff --git a/src/requests/all/send_photo.rs b/src/requests/all/send_photo.rs index 92524d65..e75580a3 100644 --- a/src/requests/all/send_photo.rs +++ b/src/requests/all/send_photo.rs @@ -1,37 +1,23 @@ +use super::BotWrapper; use crate::{ - network, + net, requests::{form_builder::FormBuilder, Request, ResponseResult}, types::{ChatId, InputFile, Message, ParseMode, ReplyMarkup}, Bot, }; -/// Use this method to send photos. On success, the sent Message is returned. -#[derive(Debug, Clone)] +/// Use this method to send photos. +/// +/// [The official docs](https://core.telegram.org/bots/api#sendphoto). +#[derive(Eq, PartialEq, Debug, Clone)] pub struct SendPhoto<'a> { - bot: &'a Bot, - - /// Unique identifier for the target chat or username of the target channel - /// (in the format @channelusername) + bot: BotWrapper<'a>, chat_id: ChatId, - /// Photo to send. Pass a file_id as String to send a photo that exists on - /// the Telegram servers (recommended), pass an HTTP URL as a String for - /// Telegram to get a photo from the Internet, or upload a new photo using - /// multipart/form-data. More info on Sending Files » photo: InputFile, - /// Photo caption (may also be used when resending photos by file_id), - /// 0-1024 characters caption: Option, - /// Send Markdown or HTML, if you want Telegram apps to show bold, italic, - /// fixed-width text or inline URLs in the media caption. parse_mode: Option, - /// Sends the message silently. Users will receive a notification with no - /// sound. disable_notification: Option, - /// If the message is a reply, ID of the original message reply_to_message_id: Option, - /// Additional interface options. A JSON-serialized object for an inline - /// keyboard, custom reply keyboard, instructions to remove reply keyboard - /// or to force a reply from the user. reply_markup: Option, } @@ -40,7 +26,7 @@ impl Request for SendPhoto<'_> { type Output = Message; async fn send(&self) -> ResponseResult { - network::request_multipart( + net::request_multipart( self.bot.client(), self.bot.token(), "sendPhoto", @@ -71,7 +57,7 @@ impl<'a> SendPhoto<'a> { C: Into, { Self { - bot, + bot: BotWrapper(bot), chat_id: chat_id.into(), photo, caption: None, @@ -82,6 +68,8 @@ impl<'a> SendPhoto<'a> { } } + /// Unique identifier for the target chat or username of the target channel + /// (in the format `@channelusername`). pub fn chat_id(mut self, val: T) -> Self where T: Into, @@ -90,11 +78,25 @@ impl<'a> SendPhoto<'a> { self } + /// Photo to send. + /// + /// Pass [`InputFile::File`] to send a photo that exists on + /// the Telegram servers (recommended), pass an [`InputFile::Url`] for + /// Telegram to get a .webp file from the Internet, or upload a new one + /// using [`InputFile::FileId`]. [More info on Sending Files »]. + /// + /// [`InputFile::File`]: crate::types::InputFile::File + /// [`InputFile::Url`]: crate::types::InputFile::Url + /// [`InputFile::FileId`]: crate::types::InputFile::FileId + /// + /// [More info on Sending Files »]: https://core.telegram.org/bots/api#sending-files pub fn photo(mut self, val: InputFile) -> Self { self.photo = val; self } + ///Photo caption (may also be used when resending photos by file_id), + /// 0-1024 characters. pub fn caption(mut self, val: T) -> Self where T: Into, @@ -103,21 +105,39 @@ impl<'a> SendPhoto<'a> { self } + /// Send [Markdown] or [HTML], if you want Telegram apps to show + /// [bold, italic, fixed-width text or inline URLs] in the media caption. + /// + /// [Markdown]: crate::types::ParseMode::Markdown + /// [HTML]: crate::types::ParseMode::HTML + /// [bold, italic, fixed-width text or inline URLs]: + /// crate::types::ParseMode pub fn parse_mode(mut self, val: ParseMode) -> Self { self.parse_mode = Some(val); self } + /// Sends the message [silently]. Users will receive a notification with no + /// sound. + /// + /// [silently]: https://telegram.org/blog/channels-2-0#silent-messages pub fn disable_notification(mut self, val: bool) -> Self { self.disable_notification = Some(val); self } + /// If the message is a reply, ID of the original message. pub fn reply_to_message_id(mut self, val: i32) -> Self { self.reply_to_message_id = Some(val); self } + /// Additional interface options. A JSON-serialized object for an [inline + /// keyboard], [custom reply keyboard], instructions to remove reply + /// keyboard or to force a reply from the user. + /// + /// [inline keyboard]: https://core.telegram.org/bots#inline-keyboards-and-on-the-fly-updating + /// [custom reply keyboard]: https://core.telegram.org/bots#keyboards pub fn reply_markup(mut self, val: ReplyMarkup) -> Self { self.reply_markup = Some(val); self diff --git a/src/requests/all/send_poll.rs b/src/requests/all/send_poll.rs index 0bd8e6ba..940ade12 100644 --- a/src/requests/all/send_poll.rs +++ b/src/requests/all/send_poll.rs @@ -1,36 +1,27 @@ use serde::Serialize; +use super::BotWrapper; use crate::{ - network, + net, requests::{Request, ResponseResult}, types::{ChatId, Message, ReplyMarkup}, Bot, }; /// Use this method to send a native poll. A native poll can't be sent to a -/// private chat. On success, the sent Message is returned. +/// private chat. +/// +/// [The official docs](https://core.telegram.org/bots/api#sendpoll). #[serde_with_macros::skip_serializing_none] -#[derive(Debug, Clone, Serialize)] +#[derive(Eq, PartialEq, Debug, Clone, Serialize)] pub struct SendPoll<'a> { #[serde(skip_serializing)] - bot: &'a Bot, - - /// Unique identifier for the target chat or username of the target channel - /// (in the format @channelusername). A native poll can't be sent to a - /// private chat. + bot: BotWrapper<'a>, chat_id: ChatId, - /// Poll question, 1-255 characters question: String, - /// List of answer options, 2-10 strings 1-100 characters each options: Vec, - /// Sends the message silently. Users will receive a notification with no - /// sound. disable_notification: Option, - /// If the message is a reply, ID of the original message reply_to_message_id: Option, - /// Additional interface options. A JSON-serialized object for an inline - /// keyboard, custom reply keyboard, instructions to remove reply keyboard - /// or to force a reply from the user. reply_markup: Option, } @@ -39,7 +30,7 @@ impl Request for SendPoll<'_> { type Output = Message; async fn send(&self) -> ResponseResult { - network::request_json( + net::request_json( self.bot.client(), self.bot.token(), "sendPoll", @@ -65,7 +56,7 @@ impl<'a> SendPoll<'a> { let question = question.into(); let options = options.into(); Self { - bot, + bot: BotWrapper(bot), chat_id, question, options, @@ -75,6 +66,10 @@ impl<'a> SendPoll<'a> { } } + /// Unique identifier for the target chat or username of the target channel + /// (in the format `@channelusername`). + /// + /// A native poll can't be sent to a private chat. pub fn chat_id(mut self, val: T) -> Self where T: Into, @@ -83,6 +78,7 @@ impl<'a> SendPoll<'a> { self } + /// Poll question, 1-255 characters. pub fn question(mut self, val: T) -> Self where T: Into, @@ -91,6 +87,7 @@ impl<'a> SendPoll<'a> { self } + /// List of answer options, 2-10 strings 1-100 characters each. pub fn options(mut self, val: T) -> Self where T: Into>, @@ -99,16 +96,29 @@ impl<'a> SendPoll<'a> { self } + /// Sends the message [silently]. Users will receive a notification with no + /// sound. + /// + /// [silently]: https://telegram.org/blog/channels-2-0#silent-messages pub fn disable_notification(mut self, val: bool) -> Self { self.disable_notification = Some(val); self } + /// If the message is a reply, ID of the original message. pub fn reply_to_message_id(mut self, val: i32) -> Self { self.reply_to_message_id = Some(val); self } + /// Additional interface options. + /// + /// A JSON-serialized object for an [inline keyboard], [custom reply + /// keyboard], instructions to remove reply keyboard or to force a reply + /// from the user. + /// + /// [inline keyboard]: https://core.telegram.org/bots#inline-keyboards-and-on-the-fly-updating + /// [custom reply keyboard]: https://core.telegram.org/bots#keyboards pub fn reply_markup(mut self, val: ReplyMarkup) -> Self { self.reply_markup = Some(val); self diff --git a/src/requests/all/send_sticker.rs b/src/requests/all/send_sticker.rs index 865fe744..1cf07e23 100644 --- a/src/requests/all/send_sticker.rs +++ b/src/requests/all/send_sticker.rs @@ -1,32 +1,23 @@ +use super::BotWrapper; use crate::{ - network, + net, requests::{form_builder::FormBuilder, Request, ResponseResult}, types::{ChatId, InputFile, Message, ReplyMarkup}, Bot, }; -/// Use this method to send static .WEBP or animated .TGS stickers. On success, -/// the sent Message is returned. -#[derive(Debug, Clone)] +/// Use this method to send static .WEBP or [animated] .TGS stickers. +/// +/// [The official docs](https://core.telegram.org/bots/api#sendsticker). +/// +/// [animated]: https://telegram.org/blog/animated-stickers +#[derive(Eq, PartialEq, Debug, Clone)] pub struct SendSticker<'a> { - bot: &'a Bot, - - /// Unique identifier for the target chat or username of the target channel - /// (in the format @channelusername) + bot: BotWrapper<'a>, chat_id: ChatId, - /// Sticker to send. Pass a file_id as String to send a file that exists on - /// the Telegram servers (recommended), pass an HTTP URL as a String for - /// Telegram to get a .webp file from the Internet, or upload a new one - /// using multipart/form-data. More info on Sending Files » sticker: InputFile, - /// Sends the message silently. Users will receive a notification with no - /// sound. disable_notification: Option, - /// If the message is a reply, ID of the original message reply_to_message_id: Option, - /// Additional interface options. A JSON-serialized object for an inline - /// keyboard, custom reply keyboard, instructions to remove reply keyboard - /// or to force a reply from the user. reply_markup: Option, } @@ -35,7 +26,7 @@ impl Request for SendSticker<'_> { type Output = Message; async fn send(&self) -> ResponseResult { - network::request_multipart( + net::request_multipart( self.bot.client(), self.bot.token(), "sendSticker", @@ -62,7 +53,7 @@ impl<'a> SendSticker<'a> { C: Into, { Self { - bot, + bot: BotWrapper(bot), chat_id: chat_id.into(), sticker, disable_notification: None, @@ -71,6 +62,8 @@ impl<'a> SendSticker<'a> { } } + /// Unique identifier for the target chat or username of the target channel + /// (in the format `@channelusername`). pub fn chat_id(mut self, val: T) -> Self where T: Into, @@ -79,21 +72,45 @@ impl<'a> SendSticker<'a> { self } + /// Sticker to send. + /// + /// Pass [`InputFile::File`] to send a file that exists on + /// the Telegram servers (recommended), pass an [`InputFile::Url`] for + /// Telegram to get a .webp file from the Internet, or upload a new one + /// using [`InputFile::FileId`]. [More info on Sending Files »]. + /// + /// [`InputFile::File`]: crate::types::InputFile::File + /// [`InputFile::Url`]: crate::types::InputFile::Url + /// [`InputFile::FileId`]: crate::types::InputFile::FileId + /// [More info on Sending Files »]: https://core.telegram.org/bots/api#sending-files pub fn sticker(mut self, val: InputFile) -> Self { self.sticker = val; self } + /// Sends the message [silently]. Users will receive a notification with no + /// sound. + /// + /// [silently]: https://telegram.org/blog/channels-2-0#silent-messages pub fn disable_notification(mut self, val: bool) -> Self { self.disable_notification = Some(val); self } + /// If the message is a reply, ID of the original message. pub fn reply_to_message_id(mut self, val: i32) -> Self { self.reply_to_message_id = Some(val); self } + /// Additional interface options. + /// + /// A JSON-serialized object for an [inline keyboard], [custom reply + /// keyboard], instructions to remove reply keyboard or to force a reply + /// from the user. + /// + /// [inline keyboard]: https://core.telegram.org/bots#inline-keyboards-and-on-the-fly-updating + /// [custom reply keyboard]: https://core.telegram.org/bots#keyboards pub fn reply_markup(mut self, val: ReplyMarkup) -> Self { self.reply_markup = Some(val); self diff --git a/src/requests/all/send_venue.rs b/src/requests/all/send_venue.rs index e6ac22a7..c0d06765 100644 --- a/src/requests/all/send_venue.rs +++ b/src/requests/all/send_venue.rs @@ -1,45 +1,30 @@ use serde::Serialize; +use super::BotWrapper; use crate::{ - network, + net, requests::{Request, ResponseResult}, types::{ChatId, Message, ReplyMarkup}, Bot, }; -/// Use this method to send information about a venue. On success, the sent -/// Message is returned. +/// Use this method to send information about a venue. +/// +/// [The official docs](https://core.telegram.org/bots/api#sendvenue). #[serde_with_macros::skip_serializing_none] -#[derive(Debug, Clone, Serialize)] +#[derive(PartialEq, Debug, Clone, Serialize)] pub struct SendVenue<'a> { #[serde(skip_serializing)] - bot: &'a Bot, - - /// Unique identifier for the target chat or username of the target channel - /// (in the format @channelusername) + bot: BotWrapper<'a>, chat_id: ChatId, - /// Latitude of the venue latitude: f32, - /// Longitude of the venue longitude: f32, - /// Name of the venue title: String, - /// Address of the venue address: String, - /// Foursquare identifier of the venue foursquare_id: Option, - /// Foursquare type of the venue, if known. (For example, - /// “arts_entertainment/default”, “arts_entertainment/aquarium” or - /// “food/icecream”.) foursquare_type: Option, - /// Sends the message silently. Users will receive a notification with no - /// sound. disable_notification: Option, - /// If the message is a reply, ID of the original message reply_to_message_id: Option, - /// Additional interface options. A JSON-serialized object for an inline - /// keyboard, custom reply keyboard, instructions to remove reply keyboard - /// or to force a reply from the user. reply_markup: Option, } @@ -48,7 +33,7 @@ impl Request for SendVenue<'_> { type Output = Message; async fn send(&self) -> ResponseResult { - network::request_json( + net::request_json( self.bot.client(), self.bot.token(), "sendVenue", @@ -76,7 +61,7 @@ impl<'a> SendVenue<'a> { let title = title.into(); let address = address.into(); Self { - bot, + bot: BotWrapper(bot), chat_id, latitude, longitude, @@ -90,6 +75,8 @@ impl<'a> SendVenue<'a> { } } + /// Unique identifier for the target chat or username of the target channel + /// (in the format `@channelusername`). pub fn chat_id(mut self, val: T) -> Self where T: Into, @@ -98,16 +85,19 @@ impl<'a> SendVenue<'a> { self } + /// Latitude of the venue. pub fn latitude(mut self, val: f32) -> Self { self.latitude = val; self } + /// Longitude of the venue. pub fn longitude(mut self, val: f32) -> Self { self.longitude = val; self } + /// Name of the venue. pub fn title(mut self, val: T) -> Self where T: Into, @@ -116,6 +106,7 @@ impl<'a> SendVenue<'a> { self } + /// Address of the venue. pub fn address(mut self, val: T) -> Self where T: Into, @@ -124,6 +115,7 @@ impl<'a> SendVenue<'a> { self } + /// Foursquare identifier of the venue. pub fn foursquare_id(mut self, val: T) -> Self where T: Into, @@ -132,6 +124,10 @@ impl<'a> SendVenue<'a> { self } + /// Foursquare type of the venue, if known. + /// + /// For example, `arts_entertainment/default`, `arts_entertainment/aquarium` + /// or `food/icecream`. pub fn foursquare_type(mut self, val: T) -> Self where T: Into, @@ -140,16 +136,29 @@ impl<'a> SendVenue<'a> { self } + /// Sends the message [silently]. Users will receive a notification with no + /// sound. + /// + /// [silently]: https://telegram.org/blog/channels-2-0#silent-messages pub fn disable_notification(mut self, val: bool) -> Self { self.disable_notification = Some(val); self } + /// If the message is a reply, ID of the original message. pub fn reply_to_message_id(mut self, val: i32) -> Self { self.reply_to_message_id = Some(val); self } + /// Additional interface options. + /// + /// A JSON-serialized object for an [inline keyboard], [custom reply + /// keyboard], instructions to remove reply keyboard or to force a reply + /// from the user. + /// + /// [inline keyboard]: https://core.telegram.org/bots#inline-keyboards-and-on-the-fly-updating + /// [custom reply keyboard]: https://core.telegram.org/bots#keyboards pub fn reply_markup(mut self, val: ReplyMarkup) -> Self { self.reply_markup = Some(val); self diff --git a/src/requests/all/send_video.rs b/src/requests/all/send_video.rs index ac5d44ba..1671ad7c 100644 --- a/src/requests/all/send_video.rs +++ b/src/requests/all/send_video.rs @@ -1,57 +1,32 @@ +use super::BotWrapper; use crate::{ - network, + net, requests::{form_builder::FormBuilder, Request, ResponseResult}, types::{ChatId, InputFile, Message, ParseMode, ReplyMarkup}, Bot, }; /// Use this method to send video files, Telegram clients support mp4 videos -/// (other formats may be sent as Document). On success, the sent Message is -/// returned. Bots can currently send video files of up to 50 MB in size, this +/// (other formats may be sent as Document). +/// +/// Bots can currently send video files of up to 50 MB in size, this /// limit may be changed in the future. -#[derive(Debug, Clone)] +/// +/// [The official docs](https://core.telegram.org/bots/api#sendvideo). +#[derive(Eq, PartialEq, Debug, Clone)] pub struct SendVideo<'a> { - bot: &'a Bot, - - /// Unique identifier for the target chat or username of the target channel - /// (in the format @channelusername) + bot: BotWrapper<'a>, chat_id: ChatId, - /// Video to send. Pass a file_id as String to send a video that exists on - /// the Telegram servers (recommended), pass an HTTP URL as a String for - /// Telegram to get a video from the Internet, or upload a new video using - /// multipart/form-data. More info on Sending Files » video: InputFile, - /// Duration of sent video in seconds duration: Option, - /// Video width width: Option, - /// Video height height: Option, - /// Thumbnail of the file sent; can be ignored if thumbnail generation for - /// the file is supported server-side. The thumbnail should be in JPEG - /// format and less than 200 kB in size. A thumbnail‘s width and height - /// should not exceed 320. Ignored if the file is not uploaded using - /// multipart/form-data. Thumbnails can’t be reused and can be only - /// uploaded as a new file, so you can pass “attach://” - /// if the thumbnail was uploaded using multipart/form-data under - /// . More info on Sending Files » thumb: Option, - /// Video caption (may also be used when resending videos by file_id), - /// 0-1024 characters caption: Option, - /// Send Markdown or HTML, if you want Telegram apps to show bold, italic, - /// fixed-width text or inline URLs in the media caption. parse_mode: Option, - /// Pass True, if the uploaded video is suitable for streaming supports_streaming: Option, - /// Sends the message silently. Users will receive a notification with no - /// sound. disable_notification: Option, - /// If the message is a reply, ID of the original message reply_to_message_id: Option, - /// Additional interface options. A JSON-serialized object for an inline - /// keyboard, custom reply keyboard, instructions to remove reply keyboard - /// or to force a reply from the user. reply_markup: Option, } @@ -60,7 +35,7 @@ impl Request for SendVideo<'_> { type Output = Message; async fn send(&self) -> ResponseResult { - network::request_multipart( + net::request_multipart( self.bot.client(), self.bot.token(), "sendVideo", @@ -101,7 +76,7 @@ impl<'a> SendVideo<'a> { C: Into, { Self { - bot, + bot: BotWrapper(bot), chat_id: chat_id.into(), video, duration: None, @@ -117,6 +92,8 @@ impl<'a> SendVideo<'a> { } } + /// Unique identifier for the target chat or username of the target channel + /// (in the format `@channelusername`). pub fn chat_id(mut self, val: T) -> Self where T: Into, @@ -125,31 +102,58 @@ impl<'a> SendVideo<'a> { self } + /// Video to sent. + /// + /// Pass [`InputFile::File`] to send a file that exists on + /// the Telegram servers (recommended), pass an [`InputFile::Url`] for + /// Telegram to get a .webp file from the Internet, or upload a new one + /// using [`InputFile::FileId`]. [More info on Sending Files »]. + /// + /// [`InputFile::File`]: crate::types::InputFile::File + /// [`InputFile::Url`]: crate::types::InputFile::Url + /// [`InputFile::FileId`]: crate::types::InputFile::FileId pub fn video(mut self, val: InputFile) -> Self { self.video = val; self } + /// Duration of sent video in seconds. pub fn duration(mut self, val: i32) -> Self { self.duration = Some(val); self } + /// Video width. pub fn width(mut self, val: i32) -> Self { self.width = Some(val); self } + /// Video height. pub fn height(mut self, val: i32) -> Self { self.height = Some(val); self } + /// Thumbnail of the file sent; can be ignored if thumbnail generation for + /// the file is supported server-side. + /// + /// The thumbnail should be in JPEG format and less than 200 kB in size. A + /// thumbnail‘s width and height should not exceed 320. Ignored if the + /// file is not uploaded using `multipart/form-data`. Thumbnails can’t be + /// reused and can be only uploaded as a new file, so you can pass + /// `attach://` if the thumbnail was uploaded using + /// `multipart/form-data` under ``. [More info on Sending + /// Files »]. + /// + /// [More info on Sending Files »]: https://core.telegram.org/bots/api#sending-files pub fn thumb(mut self, val: InputFile) -> Self { self.thumb = Some(val); self } + /// Video caption (may also be used when resending videos by file_id), + /// 0-1024 characters. pub fn caption(mut self, val: T) -> Self where T: Into, @@ -158,26 +162,47 @@ impl<'a> SendVideo<'a> { self } + /// Send [Markdown] or [HTML], if you want Telegram apps to show + /// [bold, italic, fixed-width text or inline URLs] in the media caption. + /// + /// [Markdown]: crate::types::ParseMode::Markdown + /// [HTML]: crate::types::ParseMode::HTML + /// [bold, italic, fixed-width text or inline URLs]: + /// crate::types::ParseMode pub fn parse_mode(mut self, val: ParseMode) -> Self { self.parse_mode = Some(val); self } + /// Pass `true`, if the uploaded video is suitable for streaming. pub fn supports_streaming(mut self, val: bool) -> Self { self.supports_streaming = Some(val); self } + /// Sends the message [silently]. Users will receive a notification with no + /// sound. + /// + /// [silently]: https://telegram.org/blog/channels-2-0#silent-messages pub fn disable_notification(mut self, val: bool) -> Self { self.disable_notification = Some(val); self } + /// If the message is a reply, ID of the original message. pub fn reply_to_message_id(mut self, val: i32) -> Self { self.reply_to_message_id = Some(val); self } + /// Additional interface options. + /// + /// A JSON-serialized object for an [inline keyboard], [custom reply + /// keyboard], instructions to remove reply keyboard or to force a reply + /// from the user. + /// + /// [inline keyboard]: https://core.telegram.org/bots#inline-keyboards-and-on-the-fly-updating + /// [custom reply keyboard]: https://core.telegram.org/bots#keyboards pub fn reply_markup(mut self, val: ReplyMarkup) -> Self { self.reply_markup = Some(val); self diff --git a/src/requests/all/send_video_note.rs b/src/requests/all/send_video_note.rs index cb4229a5..fbed9bbb 100644 --- a/src/requests/all/send_video_note.rs +++ b/src/requests/all/send_video_note.rs @@ -1,46 +1,27 @@ +use super::BotWrapper; use crate::{ - network, + net, requests::{form_builder::FormBuilder, Request, ResponseResult}, types::{ChatId, InputFile, Message, ReplyMarkup}, Bot, }; -/// As of v.4.0, Telegram clients support rounded square mp4 videos of up to 1 -/// minute long. Use this method to send video messages. On success, the sent -/// Message is returned. -#[derive(Debug, Clone)] +/// As of [v.4.0], Telegram clients support rounded square mp4 videos of up to 1 +/// minute long. Use this method to send video messages. +/// +/// [The official docs](https://core.telegram.org/bots/api#sendvideonote). +/// +/// [v.4.0]: https://telegram.org/blog/video-messages-and-telescope +#[derive(Eq, PartialEq, Debug, Clone)] pub struct SendVideoNote<'a> { - bot: &'a Bot, - - /// Unique identifier for the target chat or username of the target channel - /// (in the format @channelusername) + bot: BotWrapper<'a>, chat_id: ChatId, - /// Video note to send. Pass a file_id as String to send a video note that - /// exists on the Telegram servers (recommended) or upload a new video - /// using multipart/form-data. More info on Sending Files ». Sending video - /// notes by a URL is currently unsupported video_note: InputFile, - /// Duration of sent video in seconds duration: Option, - /// Video width and height, i.e. diameter of the video message length: Option, - /// Thumbnail of the file sent; can be ignored if thumbnail generation for - /// the file is supported server-side. The thumbnail should be in JPEG - /// format and less than 200 kB in size. A thumbnail‘s width and height - /// should not exceed 320. Ignored if the file is not uploaded using - /// multipart/form-data. Thumbnails can’t be reused and can be only - /// uploaded as a new file, so you can pass “attach://” - /// if the thumbnail was uploaded using multipart/form-data under - /// . More info on Sending Files » thumb: Option, - /// Sends the message silently. Users will receive a notification with no - /// sound. disable_notification: Option, - /// If the message is a reply, ID of the original message reply_to_message_id: Option, - /// Additional interface options. A JSON-serialized object for an inline - /// keyboard, custom reply keyboard, instructions to remove reply keyboard - /// or to force a reply from the user. reply_markup: Option, } @@ -49,7 +30,7 @@ impl Request for SendVideoNote<'_> { type Output = Message; async fn send(&self) -> ResponseResult { - network::request_multipart( + net::request_multipart( self.bot.client(), self.bot.token(), "sendVideoNote", @@ -86,7 +67,7 @@ impl<'a> SendVideoNote<'a> { C: Into, { Self { - bot, + bot: BotWrapper(bot), chat_id: chat_id.into(), video_note, duration: None, @@ -98,6 +79,8 @@ impl<'a> SendVideoNote<'a> { } } + /// Unique identifier for the target chat or username of the target channel + /// (in the format `@channelusername`). pub fn chat_id(mut self, val: T) -> Self where T: Into, @@ -106,36 +89,72 @@ impl<'a> SendVideoNote<'a> { self } + /// Video note to send. + /// + /// Pass [`InputFile::File`] to send a file that exists on + /// the Telegram servers (recommended), pass an [`InputFile::Url`] for + /// Telegram to get a .webp file from the Internet, or upload a new one + /// using [`InputFile::FileId`]. [More info on Sending Files »]. + /// + /// [`InputFile::File`]: crate::types::InputFile::File + /// [`InputFile::Url`]: crate::types::InputFile::Url + /// [`InputFile::FileId`]: crate::types::InputFile::FileId + /// [More info on Sending Files »]: https://core.telegram.org/bots/api#sending-files pub fn video_note(mut self, val: InputFile) -> Self { self.video_note = val; self } + /// Duration of sent video in seconds. pub fn duration(mut self, val: i32) -> Self { self.duration = Some(val); self } + /// Video width and height, i.e. diameter of the video message. pub fn length(mut self, val: i32) -> Self { self.length = Some(val); self } + /// Thumbnail of the file sent; can be ignored if thumbnail generation for + /// the file is supported server-side. + /// + /// The thumbnail should be in JPEG format and less than 200 kB in size. A + /// thumbnail‘s width and height should not exceed 320. Ignored if the + /// file is not uploaded using `multipart/form-data`. Thumbnails can’t + /// be reused and can be only uploaded as a new file, so you can pass + /// `attach://` if the thumbnail was uploaded using + /// `multipart/form-data` under ``. [More info on + /// Sending Files »]. pub fn thumb(mut self, val: InputFile) -> Self { self.thumb = Some(val); self } + /// Sends the message [silently]. Users will receive a notification with no + /// sound. + /// + /// [silently]: https://telegram.org/blog/channels-2-0#silent-messages pub fn disable_notification(mut self, val: bool) -> Self { self.disable_notification = Some(val); self } + /// If the message is a reply, ID of the original message. pub fn reply_to_message_id(mut self, val: i32) -> Self { self.reply_to_message_id = Some(val); self } + /// Additional interface options. + /// + /// A JSON-serialized object for an [inline keyboard], [custom reply + /// keyboard], instructions to remove reply keyboard or to force a reply + /// from the user. + /// + /// [inline keyboard]: https://core.telegram.org/bots#inline-keyboards-and-on-the-fly-updating + /// [custom reply keyboard]: https://core.telegram.org/bots#keyboards pub fn reply_markup(mut self, val: ReplyMarkup) -> Self { self.reply_markup = Some(val); self diff --git a/src/requests/all/send_voice.rs b/src/requests/all/send_voice.rs index 49bc29bc..00df1764 100644 --- a/src/requests/all/send_voice.rs +++ b/src/requests/all/send_voice.rs @@ -1,43 +1,33 @@ +use super::BotWrapper; use crate::{ - network, + net, requests::{form_builder::FormBuilder, Request, ResponseResult}, types::{ChatId, InputFile, Message, ParseMode, ReplyMarkup}, Bot, }; /// Use this method to send audio files, if you want Telegram clients to display -/// the file as a playable voice message. For this to work, your audio must be -/// in an .ogg file encoded with OPUS (other formats may be sent as Audio or -/// Document). On success, the sent Message is returned. Bots can currently send -/// voice messages of up to 50 MB in size, this limit may be changed in the +/// the file as a playable voice message. +/// +/// For this to work, your audio must be in an .ogg file encoded with OPUS +/// (other formats may be sent as [`Audio`] or [`Document`]). Bots can currently +/// send voice messages of up to 50 MB in size, this limit may be changed in the /// future. -#[derive(Debug, Clone)] +/// +/// [The official docs](https://core.telegram.org/bots/api#sendvoice). +/// +/// [`Audio`]: crate::types::Audio +/// [`Document`]: crate::types::Document +#[derive(Eq, PartialEq, Debug, Clone)] pub struct SendVoice<'a> { - bot: &'a Bot, - - /// Unique identifier for the target chat or username of the target channel - /// (in the format @channelusername) + bot: BotWrapper<'a>, chat_id: ChatId, - /// Audio file to send. Pass a file_id as String to send a file that exists - /// on the Telegram servers (recommended), pass an HTTP URL as a String for - /// Telegram to get a file from the Internet, or upload a new one using - /// multipart/form-data. More info on Sending Files » voice: InputFile, - /// Voice message caption, 0-1024 characters caption: Option, - /// Send Markdown or HTML, if you want Telegram apps to show bold, italic, - /// fixed-width text or inline URLs in the media caption. parse_mode: Option, - /// Duration of the voice message in seconds duration: Option, - /// Sends the message silently. Users will receive a notification with no - /// sound. disable_notification: Option, - /// If the message is a reply, ID of the original message reply_to_message_id: Option, - /// Additional interface options. A JSON-serialized object for an inline - /// keyboard, custom reply keyboard, instructions to remove reply keyboard - /// or to force a reply from the user. reply_markup: Option, } @@ -46,7 +36,7 @@ impl Request for SendVoice<'_> { type Output = Message; async fn send(&self) -> ResponseResult { - network::request_multipart( + net::request_multipart( self.bot.client(), self.bot.token(), "sendVoice", @@ -79,7 +69,7 @@ impl<'a> SendVoice<'a> { C: Into, { Self { - bot, + bot: BotWrapper(bot), chat_id: chat_id.into(), voice, caption: None, @@ -91,6 +81,8 @@ impl<'a> SendVoice<'a> { } } + /// Unique identifier for the target chat or username of the target channel + /// (in the format `@channelusername`). pub fn chat_id(mut self, val: T) -> Self where T: Into, @@ -99,11 +91,23 @@ impl<'a> SendVoice<'a> { self } + /// Audio file to send. + /// + /// Pass [`InputFile::File`] to send a file that exists on + /// the Telegram servers (recommended), pass an [`InputFile::Url`] for + /// Telegram to get a .webp file from the Internet, or upload a new one + /// using [`InputFile::FileId`]. [More info on Sending Files »]. + /// + /// [`InputFile::File`]: crate::types::InputFile::File + /// [`InputFile::Url`]: crate::types::InputFile::Url + /// [`InputFile::FileId`]: crate::types::InputFile::FileId + /// [More info on Sending Files »]: https://core.telegram.org/bots/api#sending-files pub fn voice(mut self, val: InputFile) -> Self { self.voice = val; self } + /// Voice message caption, 0-1024 characters. pub fn caption(mut self, val: T) -> Self where T: Into, @@ -112,26 +116,47 @@ impl<'a> SendVoice<'a> { self } + /// Send [Markdown] or [HTML], if you want Telegram apps to show + /// [bold, italic, fixed-width text or inline URLs] in the media caption. + /// + /// [Markdown]: crate::types::ParseMode::Markdown + /// [HTML]: crate::types::ParseMode::HTML + /// [bold, italic, fixed-width text or inline URLs]: + /// crate::types::ParseMode pub fn parse_mode(mut self, val: ParseMode) -> Self { self.parse_mode = Some(val); self } + /// Duration of the voice message in seconds. pub fn duration(mut self, val: i32) -> Self { self.duration = Some(val); self } + /// Sends the message [silently]. Users will receive a notification with no + /// sound. + /// + /// [silently]: https://telegram.org/blog/channels-2-0#silent-messages pub fn disable_notification(mut self, val: bool) -> Self { self.disable_notification = Some(val); self } + /// If the message is a reply, ID of the original message. pub fn reply_to_message_id(mut self, val: i32) -> Self { self.reply_to_message_id = Some(val); self } + /// Additional interface options. + /// + /// A JSON-serialized object for an [inline keyboard], [custom reply + /// keyboard], instructions to remove reply keyboard or to force a reply + /// from the user. + /// + /// [inline keyboard]: https://core.telegram.org/bots#inline-keyboards-and-on-the-fly-updating + /// [custom reply keyboard]: https://core.telegram.org/bots#keyboards pub fn reply_markup(mut self, val: ReplyMarkup) -> Self { self.reply_markup = Some(val); self diff --git a/src/requests/all/set_chat_administrator_custom_title.rs b/src/requests/all/set_chat_administrator_custom_title.rs index 4f90f266..94370bef 100644 --- a/src/requests/all/set_chat_administrator_custom_title.rs +++ b/src/requests/all/set_chat_administrator_custom_title.rs @@ -1,7 +1,8 @@ use serde::Serialize; +use super::BotWrapper; use crate::{ - network, + net, requests::{Request, ResponseResult}, types::{ChatId, True}, Bot, @@ -9,22 +10,16 @@ use crate::{ /// Use this method to set a custom title for an administrator in a supergroup /// promoted by the bot. +/// +/// [The official docs](https://core.telegram.org/bots/api#setchatadministratorcustomtitle). #[serde_with_macros::skip_serializing_none] -#[derive(Debug, Clone, Serialize)] +#[derive(Eq, PartialEq, Debug, Clone, Serialize)] pub struct SetChatAdministratorCustomTitle<'a> { #[serde(skip_serializing)] - bot: &'a Bot, - - /// Unique identifier for the target chat or username of the target - /// supergroup (in the format `@supergroupusername`) - pub chat_id: ChatId, - - /// Unique identifier of the target user - pub user_id: i32, - - /// New custom title for the administrator; 0-16 characters, emoji are not - /// allowed - pub custom_title: String, + bot: BotWrapper<'a>, + chat_id: ChatId, + user_id: i32, + custom_title: String, } #[async_trait::async_trait] @@ -32,7 +27,7 @@ impl Request for SetChatAdministratorCustomTitle<'_> { type Output = True; async fn send(&self) -> ResponseResult { - network::request_json( + net::request_json( self.bot.client(), self.bot.token(), "setChatAdministratorCustomTitle", @@ -56,13 +51,15 @@ impl<'a> SetChatAdministratorCustomTitle<'a> { let chat_id = chat_id.into(); let custom_title = custom_title.into(); Self { - bot, + bot: BotWrapper(bot), chat_id, user_id, custom_title, } } + /// Unique identifier for the target chat or username of the target channel + /// (in the format `@channelusername`). pub fn chat_id(mut self, val: T) -> Self where T: Into, @@ -71,11 +68,14 @@ impl<'a> SetChatAdministratorCustomTitle<'a> { self } + /// Unique identifier of the target user. pub fn user_id(mut self, val: i32) -> Self { self.user_id = val; self } + /// New custom title for the administrator; 0-16 characters, emoji are not + /// allowed. pub fn custom_title(mut self, val: T) -> Self where T: Into, diff --git a/src/requests/all/set_chat_description.rs b/src/requests/all/set_chat_description.rs index a3acb225..2c731483 100644 --- a/src/requests/all/set_chat_description.rs +++ b/src/requests/all/set_chat_description.rs @@ -1,25 +1,26 @@ use serde::Serialize; +use super::BotWrapper; use crate::{ - network, + net, requests::{Request, ResponseResult}, types::{ChatId, True}, Bot, }; /// Use this method to change the description of a group, a supergroup or a -/// channel. The bot must be an administrator in the chat for this to work and -/// must have the appropriate admin rights. Returns True on success. +/// channel. +/// +/// The bot must be an administrator in the chat for this to work and must have +/// the appropriate admin rights. +/// +/// [The official docs](https://core.telegram.org/bots/api#setchatdescription). #[serde_with_macros::skip_serializing_none] -#[derive(Debug, Clone, Serialize)] +#[derive(Eq, PartialEq, Debug, Clone, Serialize)] pub struct SetChatDescription<'a> { #[serde(skip_serializing)] - bot: &'a Bot, - - /// Unique identifier for the target chat or username of the target channel - /// (in the format @channelusername) + bot: BotWrapper<'a>, chat_id: ChatId, - /// New chat description, 0-255 characters description: Option, } @@ -28,7 +29,7 @@ impl Request for SetChatDescription<'_> { type Output = True; async fn send(&self) -> ResponseResult { - network::request_json( + net::request_json( self.bot.client(), self.bot.token(), "setChatDescription", @@ -45,12 +46,14 @@ impl<'a> SetChatDescription<'a> { { let chat_id = chat_id.into(); Self { - bot, + bot: BotWrapper(bot), chat_id, description: None, } } + /// Unique identifier for the target chat or username of the target channel + /// (in the format `@channelusername`). pub fn chat_id(mut self, val: T) -> Self where T: Into, @@ -59,6 +62,7 @@ impl<'a> SetChatDescription<'a> { self } + /// New chat description, 0-255 characters. pub fn description(mut self, val: T) -> Self where T: Into, diff --git a/src/requests/all/set_chat_permissions.rs b/src/requests/all/set_chat_permissions.rs index 2ea69ed3..2a16f863 100644 --- a/src/requests/all/set_chat_permissions.rs +++ b/src/requests/all/set_chat_permissions.rs @@ -1,25 +1,25 @@ use serde::Serialize; +use super::BotWrapper; use crate::{ - network, + net, requests::{Request, ResponseResult}, types::{ChatId, ChatPermissions, True}, Bot, }; -/// Use this method to set default chat permissions for all members. The bot -/// must be an administrator in the group or a supergroup for this to work and -/// must have the can_restrict_members admin rights. Returns True on success. +/// Use this method to set default chat permissions for all members. +/// +/// The bot must be an administrator in the group or a supergroup for this to +/// work and must have the can_restrict_members admin rights. +/// +/// [The official docs](https://core.telegram.org/bots/api#setchatpermissions). #[serde_with_macros::skip_serializing_none] -#[derive(Debug, Clone, Serialize)] +#[derive(Eq, PartialEq, Debug, Clone, Serialize)] pub struct SetChatPermissions<'a> { #[serde(skip_serializing)] - bot: &'a Bot, - - /// Unique identifier for the target chat or username of the target - /// supergroup (in the format @supergroupusername) + bot: BotWrapper<'a>, chat_id: ChatId, - /// New default chat permissions permissions: ChatPermissions, } @@ -28,7 +28,7 @@ impl Request for SetChatPermissions<'_> { type Output = True; async fn send(&self) -> ResponseResult { - network::request_json( + net::request_json( self.bot.client(), self.bot.token(), "sendChatPermissions", @@ -49,12 +49,14 @@ impl<'a> SetChatPermissions<'a> { { let chat_id = chat_id.into(); Self { - bot, + bot: BotWrapper(bot), chat_id, permissions, } } + /// Unique identifier for the target chat or username of the target + /// supergroup (in the format `@supergroupusername`). pub fn chat_id(mut self, val: T) -> Self where T: Into, @@ -63,6 +65,7 @@ impl<'a> SetChatPermissions<'a> { self } + /// New default chat permissions. pub fn permissions(mut self, val: ChatPermissions) -> Self { self.permissions = val; self diff --git a/src/requests/all/set_chat_photo.rs b/src/requests/all/set_chat_photo.rs index 991b52cc..4279c7b1 100644 --- a/src/requests/all/set_chat_photo.rs +++ b/src/requests/all/set_chat_photo.rs @@ -1,26 +1,25 @@ use serde::Serialize; +use super::BotWrapper; use crate::{ - network, + net, requests::{Request, ResponseResult}, types::{ChatId, InputFile, True}, Bot, }; -/// Use this method to set a new profile photo for the chat. Photos can't be -/// changed for private chats. The bot must be an administrator in the chat for -/// this to work and must have the appropriate admin rights. Returns True on -/// success. +/// Use this method to set a new profile photo for the chat. +/// +/// Photos can't be changed for private chats. The bot must be an administrator +/// in the chat for this to work and must have the appropriate admin rights. +/// +/// [The official docs](https://core.telegram.org/bots/api#setchatphoto). #[serde_with_macros::skip_serializing_none] -#[derive(Debug, Clone, Serialize)] +#[derive(Eq, PartialEq, Debug, Clone, Serialize)] pub struct SetChatPhoto<'a> { #[serde(skip_serializing)] - bot: &'a Bot, - - /// Unique identifier for the target chat or username of the target channel - /// (in the format @channelusername) + bot: BotWrapper<'a>, chat_id: ChatId, - /// New chat photo, uploaded using multipart/form-data photo: InputFile, } @@ -29,7 +28,7 @@ impl Request for SetChatPhoto<'_> { type Output = True; async fn send(&self) -> ResponseResult { - network::request_json( + net::request_json( self.bot.client(), self.bot.token(), "setChatPhoto", @@ -46,12 +45,14 @@ impl<'a> SetChatPhoto<'a> { { let chat_id = chat_id.into(); Self { - bot, + bot: BotWrapper(bot), chat_id, photo, } } + /// Unique identifier for the target chat or username of the target channel + /// (in the format `@channelusername`). pub fn chat_id(mut self, val: T) -> Self where T: Into, @@ -60,6 +61,7 @@ impl<'a> SetChatPhoto<'a> { self } + /// New chat photo, uploaded using `multipart/form-data`. pub fn photo(mut self, val: InputFile) -> Self { self.photo = val; self diff --git a/src/requests/all/set_chat_sticker_set.rs b/src/requests/all/set_chat_sticker_set.rs index 5f83dc2a..1b2874e4 100644 --- a/src/requests/all/set_chat_sticker_set.rs +++ b/src/requests/all/set_chat_sticker_set.rs @@ -1,27 +1,26 @@ use serde::Serialize; +use super::BotWrapper; use crate::{ - network, + net, requests::{Request, ResponseResult}, types::{ChatId, True}, Bot, }; -/// Use this method to set a new group sticker set for a supergroup. The bot -/// must be an administrator in the chat for this to work and must have the -/// appropriate admin rights. Use the field can_set_sticker_set optionally +/// Use this method to set a new group sticker set for a supergroup. +/// +/// The bot must be an administrator in the chat for this to work and must have +/// the appropriate admin rights. Use the field can_set_sticker_set optionally /// returned in getChat requests to check if the bot can use this method. -/// Returns True on success. +/// +/// [The official docs](https://core.telegram.org/bots/api#setchatstickerset). #[serde_with_macros::skip_serializing_none] -#[derive(Debug, Clone, Serialize)] +#[derive(Eq, PartialEq, Debug, Clone, Serialize)] pub struct SetChatStickerSet<'a> { #[serde(skip_serializing)] - bot: &'a Bot, - - /// Unique identifier for the target chat or username of the target - /// supergroup (in the format @supergroupusername) + bot: BotWrapper<'a>, chat_id: ChatId, - /// Name of the sticker set to be set as the group sticker set sticker_set_name: String, } @@ -30,7 +29,7 @@ impl Request for SetChatStickerSet<'_> { type Output = True; async fn send(&self) -> ResponseResult { - network::request_json( + net::request_json( self.bot.client(), self.bot.token(), "setChatStickerSet", @@ -53,12 +52,14 @@ impl<'a> SetChatStickerSet<'a> { let chat_id = chat_id.into(); let sticker_set_name = sticker_set_name.into(); Self { - bot, + bot: BotWrapper(bot), chat_id, sticker_set_name, } } + /// Unique identifier for the target chat or username of the target + /// supergroup (in the format `@supergroupusername`). pub fn chat_id(mut self, val: T) -> Self where T: Into, @@ -67,6 +68,7 @@ impl<'a> SetChatStickerSet<'a> { self } + /// Name of the sticker set to be set as the group sticker set. pub fn sticker_set_name(mut self, val: T) -> Self where T: Into, diff --git a/src/requests/all/set_chat_title.rs b/src/requests/all/set_chat_title.rs index ee50d428..7b5349fa 100644 --- a/src/requests/all/set_chat_title.rs +++ b/src/requests/all/set_chat_title.rs @@ -1,25 +1,25 @@ use serde::Serialize; +use super::BotWrapper; use crate::{ - network, + net, requests::{Request, ResponseResult}, types::{ChatId, True}, Bot, }; -/// Use this method to change the title of a chat. Titles can't be changed for -/// private chats. The bot must be an administrator in the chat for this to work -/// and must have the appropriate admin rights. Returns True on success. +/// Use this method to change the title of a chat. +/// +/// Titles can't be changed for private chats. The bot must be an administrator +/// in the chat for this to work and must have the appropriate admin rights. +/// +/// [The official docs](https://core.telegram.org/bots/api#setchattitle). #[serde_with_macros::skip_serializing_none] -#[derive(Debug, Clone, Serialize)] +#[derive(Eq, PartialEq, Debug, Clone, Serialize)] pub struct SetChatTitle<'a> { #[serde(skip_serializing)] - bot: &'a Bot, - - /// Unique identifier for the target chat or username of the target channel - /// (in the format @channelusername) + bot: BotWrapper<'a>, chat_id: ChatId, - /// New chat title, 1-255 characters title: String, } @@ -28,7 +28,7 @@ impl Request for SetChatTitle<'_> { type Output = True; async fn send(&self) -> ResponseResult { - network::request_json( + net::request_json( self.bot.client(), self.bot.token(), "setChatTitle", @@ -47,12 +47,14 @@ impl<'a> SetChatTitle<'a> { let chat_id = chat_id.into(); let title = title.into(); Self { - bot, + bot: BotWrapper(bot), chat_id, title, } } + /// Unique identifier for the target chat or username of the target channel + /// (in the format `@channelusername`). pub fn chat_id(mut self, val: T) -> Self where T: Into, @@ -61,6 +63,7 @@ impl<'a> SetChatTitle<'a> { self } + /// New chat title, 1-255 characters. pub fn title(mut self, val: T) -> Self where T: Into, diff --git a/src/requests/all/set_game_score.rs b/src/requests/all/set_game_score.rs index 08eba77a..e21152d6 100644 --- a/src/requests/all/set_game_score.rs +++ b/src/requests/all/set_game_score.rs @@ -1,34 +1,34 @@ use serde::Serialize; +use super::BotWrapper; use crate::{ - network, + net, requests::{Request, ResponseResult}, types::{ChatOrInlineMessage, Message}, Bot, }; -/// Use this method to set the score of the specified user in a game. On -/// success, if the message was sent by the bot, returns the edited Message, -/// otherwise returns True. Returns an error, if the new score is not greater -/// than the user's current score in the chat and force is False. +/// Use this method to set the score of the specified user in a game. +/// +/// On success, if the message was sent by the bot, returns the edited +/// [`Message`], otherwise returns [`True`]. Returns an error, if the new score +/// is not greater than the user's current score in the chat and force is +/// `false`. +/// +/// [The official docs](https://core.telegram.org/bots/api#setgamescore). +/// +/// [`Message`]: crate::types::Message +/// [`True`]: crate::types::True #[serde_with_macros::skip_serializing_none] -#[derive(Debug, Clone, Serialize)] +#[derive(Eq, PartialEq, Debug, Clone, Serialize)] pub struct SetGameScore<'a> { #[serde(skip_serializing)] - bot: &'a Bot, - + bot: BotWrapper<'a>, #[serde(flatten)] chat_or_inline_message: ChatOrInlineMessage, - - /// User identifier user_id: i32, - /// New score, must be non-negative score: i32, - /// Pass True, if the high score is allowed to decrease. This can be useful - /// when fixing mistakes or banning cheaters force: Option, - /// Pass True, if the game message should not be automatically edited to - /// include the current scoreboard disable_edit_message: Option, } @@ -37,7 +37,7 @@ impl Request for SetGameScore<'_> { type Output = Message; async fn send(&self) -> ResponseResult { - network::request_json( + net::request_json( self.bot.client(), self.bot.token(), "setGameScore", @@ -55,7 +55,7 @@ impl<'a> SetGameScore<'a> { score: i32, ) -> Self { Self { - bot, + bot: BotWrapper(bot), chat_or_inline_message, user_id, score, @@ -69,21 +69,30 @@ impl<'a> SetGameScore<'a> { self } + /// User identifier. pub fn user_id(mut self, val: i32) -> Self { self.user_id = val; self } + /// New score, must be non-negative. pub fn score(mut self, val: i32) -> Self { self.score = val; self } + /// Pass `true`, if the high score is allowed to decrease. + /// + /// This can be useful when fixing mistakes or banning cheaters. pub fn force(mut self, val: bool) -> Self { self.force = Some(val); self } + /// Sends the message [silently]. Users will receive a notification with no + /// sound. + /// + /// [silently]: https://telegram.org/blog/channels-2-0#silent-messages pub fn disable_edit_message(mut self, val: bool) -> Self { self.disable_edit_message = Some(val); self diff --git a/src/requests/all/set_sticker_position_in_set.rs b/src/requests/all/set_sticker_position_in_set.rs index b1d4f0e5..11dfeceb 100644 --- a/src/requests/all/set_sticker_position_in_set.rs +++ b/src/requests/all/set_sticker_position_in_set.rs @@ -1,23 +1,23 @@ use serde::Serialize; +use super::BotWrapper; use crate::{ - network, + net, requests::{Request, ResponseResult}, types::True, Bot, }; /// Use this method to move a sticker in a set created by the bot to a specific -/// position . Returns True on success. +/// position. +/// +/// [The official docs](https://core.telegram.org/bots/api#setstickerpositioninset). #[serde_with_macros::skip_serializing_none] -#[derive(Debug, Clone, Serialize)] +#[derive(Eq, PartialEq, Debug, Clone, Serialize)] pub struct SetStickerPositionInSet<'a> { #[serde(skip_serializing)] - bot: &'a Bot, - - /// File identifier of the sticker + bot: BotWrapper<'a>, sticker: String, - /// New sticker position in the set, zero-based position: i32, } @@ -26,7 +26,7 @@ impl Request for SetStickerPositionInSet<'_> { type Output = True; async fn send(&self) -> ResponseResult { - network::request_json( + net::request_json( self.bot.client(), self.bot.token(), "setStickerPositionInSet", @@ -43,12 +43,13 @@ impl<'a> SetStickerPositionInSet<'a> { { let sticker = sticker.into(); Self { - bot, + bot: BotWrapper(bot), sticker, position, } } + /// File identifier of the sticker. pub fn sticker(mut self, val: T) -> Self where T: Into, @@ -57,6 +58,7 @@ impl<'a> SetStickerPositionInSet<'a> { self } + /// New sticker position in the set, zero-based. pub fn position(mut self, val: i32) -> Self { self.position = val; self diff --git a/src/requests/all/set_webhook.rs b/src/requests/all/set_webhook.rs index 4dcbb396..1233e0cf 100644 --- a/src/requests/all/set_webhook.rs +++ b/src/requests/all/set_webhook.rs @@ -1,51 +1,38 @@ use serde::Serialize; +use super::BotWrapper; use crate::{ - network, + net, requests::{Request, ResponseResult}, - types::{InputFile, True}, + types::{AllowedUpdate, InputFile, True}, Bot, }; /// Use this method to specify a url and receive incoming updates via an -/// outgoing webhook. Whenever there is an update for the bot, we will send an +/// outgoing webhook. +/// +/// Whenever there is an update for the bot, we will send an /// HTTPS POST request to the specified url, containing a JSON-serialized -/// Update. In case of an unsuccessful request, we will give up after a -/// reasonable amount of attempts. Returns True on success. If you'd like to -/// make sure that the Webhook request comes from Telegram, we recommend using a secret path in the URL, e.g. https://www.example.com/. Since nobody else -/// knows your bot‘s token, you can be pretty sure it’s us.Notes1. You will not -/// be able to receive updates using getUpdates for as long as an outgoing -/// webhook is set up.2. To use a self-signed certificate, you need to upload -/// your public key certificate using certificate parameter. Please upload as -/// InputFile, sending a String will not work.3. Ports currently supported for -/// Webhooks: 443, 80, 88, 8443.NEW! If you're having any trouble setting up -/// webhooks, please check out this amazing guide to Webhooks. +/// [`Update`]. In case of an unsuccessful request, we will give up after a +/// reasonable amount of attempts. +/// +/// If you'd like to make sure that the Webhook request comes from Telegram, +/// we recommend using a secret path in the URL, e.g. +/// `https://www.example.com/`. Since nobody else knows your bot‘s +/// token, you can be pretty sure it’s us. +/// +/// [The official docs](https://core.telegram.org/bots/api#setwebhook). +/// +/// [`Update`]: crate::types::Update #[serde_with_macros::skip_serializing_none] -#[derive(Debug, Clone, Serialize)] +#[derive(Eq, PartialEq, Debug, Clone, Serialize)] pub struct SetWebhook<'a> { #[serde(skip_serializing)] - bot: &'a Bot, - - /// HTTPS url to send updates to. Use an empty string to remove webhook - /// integration + bot: BotWrapper<'a>, url: String, - /// Upload your public key certificate so that the root certificate in use - /// can be checked. See our self-signed guide for details. certificate: Option, - /// Maximum allowed number of simultaneous HTTPS connections to the webhook - /// for update delivery, 1-100. Defaults to 40. Use lower values to limit - /// the load on your bot‘s server, and higher values to increase your bot’s - /// throughput. max_connections: Option, - /// List the types of updates you want your bot to receive. For example, - /// specify [“message”, “edited_channel_post”, “callback_query”] to only - /// receive updates of these types. See Update for a complete list of - /// available update types. Specify an empty list to receive all updates - /// regardless of type (default). If not specified, the previous setting - /// will be used.Please note that this parameter doesn't affect updates - /// created before the call to the setWebhook, so unwanted updates may be - /// received for a short period of time. - allowed_updates: Option>, + allowed_updates: Option>, } #[async_trait::async_trait] @@ -53,7 +40,7 @@ impl Request for SetWebhook<'_> { type Output = True; async fn send(&self) -> ResponseResult { - network::request_json( + net::request_json( self.bot.client(), self.bot.token(), "setWebhook", @@ -70,7 +57,7 @@ impl<'a> SetWebhook<'a> { { let url = url.into(); Self { - bot, + bot: BotWrapper(bot), url, certificate: None, max_connections: None, @@ -78,6 +65,9 @@ impl<'a> SetWebhook<'a> { } } + /// HTTPS url to send updates to. + /// + /// Use an empty string to remove webhook integration. pub fn url(mut self, val: T) -> Self where T: Into, @@ -86,19 +76,50 @@ impl<'a> SetWebhook<'a> { self } + /// Upload your public key certificate so that the root certificate in use + /// can be checked. + /// + /// See our [self-signed guide] for details. + /// + /// [self-signed guide]: https://core.telegram.org/bots/self-signed pub fn certificate(mut self, val: InputFile) -> Self { self.certificate = Some(val); self } + /// Maximum allowed number of simultaneous HTTPS connections to the webhook + /// for update delivery, 1-100. + /// + /// Defaults to 40. Use lower values to limit the load on your bot‘s server, + /// and higher values to increase your bot’s throughput. pub fn max_connections(mut self, val: i32) -> Self { self.max_connections = Some(val); self } + /// List the types of updates you want your bot to receive. + /// + /// For example, specify [`AllowedUpdate::Message`], + /// [`AllowedUpdate::EditedChannelPost`], [`AllowedUpdate::CallbackQuery`] + /// to only receive updates of these types. Specify an empty list to receive + /// all updates regardless of type (default). If not specified, the + /// previous setting will be used. See [`AllowedUpdate`] for a complete list + /// of available update types. + /// + /// Please note that this parameter doesn't affect updates created before + /// the call to the [`Bot::set_webhook`], so unwanted updates may be + /// received for a short period of time. + /// + /// [`Bot::set_webhook`]: crate::Bot::set_webhook + /// [`AllowedUpdate::Message`]: crate::types::AllowedUpdate::Message + /// [`AllowedUpdate::EditedChannelPost`]: + /// crate::types::AllowedUpdate::EditedChannelPost + /// [`AllowedUpdate::CallbackQuery`]: + /// crate::types::AllowedUpdate::CallbackQuery + /// [`AllowedUpdate`]: crate::types::AllowedUpdate pub fn allowed_updates(mut self, val: T) -> Self where - T: Into>, + T: Into>, { self.allowed_updates = Some(val.into()); self diff --git a/src/requests/all/stop_message_live_location.rs b/src/requests/all/stop_message_live_location.rs index ea2c544b..859a3a84 100644 --- a/src/requests/all/stop_message_live_location.rs +++ b/src/requests/all/stop_message_live_location.rs @@ -1,25 +1,30 @@ use serde::Serialize; +use super::BotWrapper; use crate::{ - network, + net, requests::{Request, ResponseResult}, types::{ChatOrInlineMessage, InlineKeyboardMarkup, Message}, Bot, }; -/// Use this method to stop updating a live location message before live_period -/// expires. On success, if the message was sent by the bot, the sent Message is -/// returned, otherwise True is returned. +/// Use this method to stop updating a live location message before +/// `live_period` expires. +/// +/// On success, if the message was sent by the bot, the sent [`Message`] is +/// returned, otherwise [`True`] is returned. +/// +/// [The official docs](https://core.telegram.org/bots/api#stopmessagelivelocation). +/// +/// [`Message`]: crate::types::Message +/// [`True`]: crate::types::True #[serde_with_macros::skip_serializing_none] -#[derive(Debug, Clone, Serialize)] +#[derive(Eq, PartialEq, Debug, Clone, Serialize)] pub struct StopMessageLiveLocation<'a> { #[serde(skip_serializing)] - bot: &'a Bot, - + bot: BotWrapper<'a>, #[serde(flatten)] chat_or_inline_message: ChatOrInlineMessage, - - /// A JSON-serialized object for a new inline keyboard. reply_markup: Option, } @@ -28,7 +33,7 @@ impl Request for StopMessageLiveLocation<'_> { type Output = Message; async fn send(&self) -> ResponseResult { - network::request_json( + net::request_json( self.bot.client(), self.bot.token(), "stopMessageLiveLocation", @@ -44,7 +49,7 @@ impl<'a> StopMessageLiveLocation<'a> { chat_or_inline_message: ChatOrInlineMessage, ) -> Self { Self { - bot, + bot: BotWrapper(bot), chat_or_inline_message, reply_markup: None, } @@ -55,6 +60,9 @@ impl<'a> StopMessageLiveLocation<'a> { self } + /// A JSON-serialized object for a new [inline keyboard]. + /// + /// [inline keyboard]: https://core.telegram.org/bots#inline-keyboards-and-on-the-fly-updating pub fn reply_markup(mut self, val: InlineKeyboardMarkup) -> Self { self.reply_markup = Some(val); self diff --git a/src/requests/all/stop_poll.rs b/src/requests/all/stop_poll.rs index 9590f142..6e99b6c5 100644 --- a/src/requests/all/stop_poll.rs +++ b/src/requests/all/stop_poll.rs @@ -1,26 +1,23 @@ use serde::Serialize; +use super::BotWrapper; use crate::{ - network, + net, requests::{Request, ResponseResult}, types::{ChatId, InlineKeyboardMarkup, Poll}, Bot, }; -/// Use this method to stop a poll which was sent by the bot. On success, the -/// stopped Poll with the final results is returned. +/// Use this method to stop a poll which was sent by the bot. +/// +/// [The official docs](https://core.telegram.org/bots/api#stoppoll). #[serde_with_macros::skip_serializing_none] -#[derive(Debug, Clone, Serialize)] +#[derive(Eq, PartialEq, Debug, Clone, Serialize)] pub struct StopPoll<'a> { #[serde(skip_serializing)] - bot: &'a Bot, - - /// Unique identifier for the target chat or username of the target channel - /// (in the format @channelusername) + bot: BotWrapper<'a>, chat_id: ChatId, - /// Identifier of the original message with the poll message_id: i32, - /// A JSON-serialized object for a new message inline keyboard. reply_markup: Option, } @@ -28,8 +25,11 @@ pub struct StopPoll<'a> { impl Request for StopPoll<'_> { type Output = Poll; + /// On success, the stopped [`Poll`] with the final results is returned. + /// + /// [`Poll`]: crate::types::Poll async fn send(&self) -> ResponseResult { - network::request_json( + net::request_json( self.bot.client(), self.bot.token(), "stopPoll", @@ -45,13 +45,15 @@ impl<'a> StopPoll<'a> { { let chat_id = chat_id.into(); Self { - bot, + bot: BotWrapper(bot), chat_id, message_id, reply_markup: None, } } + /// Unique identifier for the target chat or username of the target channel + /// (in the format `@channelusername`). pub fn chat_id(mut self, val: T) -> Self where T: Into, @@ -60,11 +62,15 @@ impl<'a> StopPoll<'a> { self } + /// Identifier of the original message with the poll. pub fn message_id(mut self, val: i32) -> Self { self.message_id = val; self } + /// A JSON-serialized object for a new [inline keyboard]. + /// + /// [inline keyboard]: https://core.telegram.org/bots#inline-keyboards-and-on-the-fly-updating pub fn reply_markup(mut self, val: InlineKeyboardMarkup) -> Self { self.reply_markup = Some(val); self diff --git a/src/requests/all/unban_chat_member.rs b/src/requests/all/unban_chat_member.rs index 9b3ccb7f..749f31cc 100644 --- a/src/requests/all/unban_chat_member.rs +++ b/src/requests/all/unban_chat_member.rs @@ -1,26 +1,25 @@ use serde::Serialize; +use super::BotWrapper; use crate::{ - network, + net, requests::{Request, ResponseResult}, types::{ChatId, True}, Bot, }; /// Use this method to unban a previously kicked user in a supergroup or -/// channel. The user will not return to the group or channel automatically, but -/// will be able to join via link, etc. The bot must be an administrator for -/// this to work. Returns True on success. +/// channel. The user will **not** return to the group or channel automatically, +/// but will be able to join via link, etc. The bot must be an administrator for +/// this to work. +/// +/// [The official docs](https://core.telegram.org/bots/api#unbanchatmember). #[serde_with_macros::skip_serializing_none] -#[derive(Debug, Clone, Serialize)] +#[derive(Eq, PartialEq, Debug, Clone, Serialize)] pub struct UnbanChatMember<'a> { #[serde(skip_serializing)] - bot: &'a Bot, - - /// Unique identifier for the target group or username of the target - /// supergroup or channel (in the format @username) + bot: BotWrapper<'a>, chat_id: ChatId, - /// Unique identifier of the target user user_id: i32, } @@ -29,7 +28,7 @@ impl Request for UnbanChatMember<'_> { type Output = True; async fn send(&self) -> ResponseResult { - network::request_json( + net::request_json( self.bot.client(), self.bot.token(), "unbanChatMember", @@ -46,12 +45,14 @@ impl<'a> UnbanChatMember<'a> { { let chat_id = chat_id.into(); Self { - bot, + bot: BotWrapper(bot), chat_id, user_id, } } + /// Unique identifier for the target group or username of the target + /// supergroup or channel (in the format `@username`). pub fn chat_id(mut self, val: T) -> Self where T: Into, @@ -60,6 +61,7 @@ impl<'a> UnbanChatMember<'a> { self } + /// Unique identifier of the target user. pub fn user_id(mut self, val: i32) -> Self { self.user_id = val; self diff --git a/src/requests/all/unpin_chat_message.rs b/src/requests/all/unpin_chat_message.rs index 7a93c890..b4b42921 100644 --- a/src/requests/all/unpin_chat_message.rs +++ b/src/requests/all/unpin_chat_message.rs @@ -1,24 +1,25 @@ use serde::Serialize; +use super::BotWrapper; use crate::{ - network, + net, requests::{Request, ResponseResult}, types::{ChatId, True}, Bot, }; /// Use this method to unpin a message in a group, a supergroup, or a channel. +/// /// The bot must be an administrator in the chat for this to work and must have -/// the ‘can_pin_messages’ admin right in the supergroup or ‘can_edit_messages’ -/// admin right in the channel. Returns True on success. +/// the `can_pin_messages` admin right in the supergroup or `can_edit_messages` +/// admin right in the channel. +/// +/// [The official docs](https://core.telegram.org/bots/api#unpinchatmessage). #[serde_with_macros::skip_serializing_none] -#[derive(Debug, Clone, Serialize)] +#[derive(Eq, PartialEq, Debug, Clone, Serialize)] pub struct UnpinChatMessage<'a> { #[serde(skip_serializing)] - bot: &'a Bot, - - /// Unique identifier for the target chat or username of the target channel - /// (in the format @channelusername) + bot: BotWrapper<'a>, chat_id: ChatId, } @@ -27,7 +28,7 @@ impl Request for UnpinChatMessage<'_> { type Output = True; async fn send(&self) -> ResponseResult { - network::request_json( + net::request_json( self.bot.client(), self.bot.token(), "unpinChatMessage", @@ -43,9 +44,14 @@ impl<'a> UnpinChatMessage<'a> { C: Into, { let chat_id = chat_id.into(); - Self { bot, chat_id } + Self { + bot: BotWrapper(bot), + chat_id, + } } + /// Unique identifier for the target chat or username of the target channel + /// (in the format `@channelusername`). pub fn chat_id(mut self, val: T) -> Self where T: Into, diff --git a/src/requests/all/upload_sticker_file.rs b/src/requests/all/upload_sticker_file.rs index ba34abd5..6183e2de 100644 --- a/src/requests/all/upload_sticker_file.rs +++ b/src/requests/all/upload_sticker_file.rs @@ -1,26 +1,27 @@ use serde::Serialize; +use super::BotWrapper; use crate::{ - network, + net, requests::{Request, ResponseResult}, types::{File, InputFile}, Bot, }; /// Use this method to upload a .png file with a sticker for later use in -/// createNewStickerSet and addStickerToSet methods (can be used multiple -/// times). Returns the uploaded File on success. +/// [`Bot::create_new_sticker_set`] and [`Bot::add_sticker_to_set`] methods (can +/// be used multiple times). +/// +/// [The official docs](https://core.telegram.org/bots/api#uploadstickerfile). +/// +/// [`Bot::create_new_sticker_set`]: crate::Bot::create_new_sticker_set +/// [`Bot::add_sticker_to_set`]: crate::Bot::add_sticker_to_set #[serde_with_macros::skip_serializing_none] -#[derive(Debug, Clone, Serialize)] +#[derive(Eq, PartialEq, Debug, Clone, Serialize)] pub struct UploadStickerFile<'a> { #[serde(skip_serializing)] - bot: &'a Bot, - - /// User identifier of sticker file owner + bot: BotWrapper<'a>, user_id: i32, - /// Png image with the sticker, must be up to 512 kilobytes in size, - /// dimensions must not exceed 512px, and either width or height must be - /// exactly 512px. More info on Sending Files » png_sticker: InputFile, } #[async_trait::async_trait] @@ -28,7 +29,7 @@ impl Request for UploadStickerFile<'_> { type Output = File; async fn send(&self) -> ResponseResult { - network::request_json( + net::request_json( self.bot.client(), self.bot.token(), "uploadStickerFile", @@ -45,17 +46,23 @@ impl<'a> UploadStickerFile<'a> { png_sticker: InputFile, ) -> Self { Self { - bot, + bot: BotWrapper(bot), user_id, png_sticker, } } + /// User identifier of sticker file owner. pub fn user_id(mut self, val: i32) -> Self { self.user_id = val; self } + /// **Png** image with the sticker, must be up to 512 kilobytes in size, + /// dimensions must not exceed 512px, and either width or height must be + /// exactly 512px. [More info on Sending Files »]. + /// + /// [More info on Sending Files »]: https://core.telegram.org/bots/api#sending-files pub fn png_sticker(mut self, val: InputFile) -> Self { self.png_sticker = val; self diff --git a/src/types/encrypted_passport_element.rs b/src/types/encrypted_passport_element.rs index e4ad20ec..6b52f67b 100644 --- a/src/types/encrypted_passport_element.rs +++ b/src/types/encrypted_passport_element.rs @@ -9,10 +9,10 @@ use super::PassportFile; #[derive(Clone, Debug, Eq, Hash, PartialEq, Serialize, Deserialize)] pub struct EncryptedPassportElement { /// Base64-encoded element hash for using in - /// [`PassportElementErrorUnspecified`]. + /// [`PassportElementErrorKind::Unspecified`]. /// - /// [`PassportElementErrorUnspecified`]: - /// crate::types::PassportElementErrorUnspecified + /// [`PassportElementErrorKind::Unspecified`]: + /// crate::types::PassportElementErrorKind::Unspecified pub hash: String, #[serde(flatten)]