### Example: Sending a Document with Thumbnail Source: https://docs.rs/grammers-client/latest/grammers_client/media/struct.InputMedia.html Demonstrates how to create an `InputMedia` object for a document, including a thumbnail, and set an empty caption. This example requires uploading both the video and its thumbnail. ```rust async fn f(client: &mut grammers_client::Client) -> Result<(), Box> { use grammers_client::media::InputMedia; let video = client.upload_file("video.mp4").await?; let thumb = client.upload_file("thumb.png").await?; let media = InputMedia::new().caption("").document(video).thumbnail(thumb); Ok(()) } ``` -------------------------------- ### Bot Sign-in Example Source: https://docs.rs/grammers-client/latest/src/grammers_client/client/auth.rs.html Example demonstrating how to sign in as a bot using a provided token and API hash. Handles potential errors during the sign-in process and prints the user's first name upon success. ```rust # async fn f(client: grammers_client::Client) -> Result<(), Box> { # // Note: these values are obviously fake. # // Obtain your own with the developer's phone at https://my.telegram.org. # const API_HASH: &str = "514727c32270b9eb8cc16daf17e21e57"; # // Obtain your own by talking to @BotFather via a Telegram app. # const TOKEN: &str = "776609994:AAFXAy5-PawQlnYywUlZ_b_GOXgarR3ah_yq"; # let user = match client.bot_sign_in(TOKEN, API_HASH).await { Ok(user) => user, Err(err) => { println!("Failed to sign in as a bot :(\n{}", err); return Err(err.into()); } }; if let Some(first_name) = user.first_name() { println!("Signed in as {}!", first_name); } else { println!("Signed in!"); } # Ok(()) # } ``` -------------------------------- ### Get Pinned Message Example Source: https://docs.rs/grammers-client/latest/src/grammers_client/client/messages.rs.html Demonstrates how to retrieve the latest pinned message from a peer. It checks if a message is pinned and prints its content, or indicates if no messages are pinned. ```rust async fn f(peer: grammers_session::types::PeerRef, client: grammers_client::Client) -> Result<(), Box> { if let Some(message) = client.get_pinned_message(peer).await? { println!("There is a message pinned: {}", message.text()); } else { println!("There are no messages pinned"); } Ok(()) } ``` -------------------------------- ### Create New InputMedia Source: https://docs.rs/grammers-client/latest/src/grammers_client/media/input_media.rs.html Initializes a new, empty InputMedia struct. Use this as a starting point before configuring media and captions. ```rust pub fn new() -> Self { Self::default() } ``` -------------------------------- ### Pin Message Example Source: https://docs.rs/grammers-client/latest/src/grammers_client/client/messages.rs.html Shows how to pin a specific message in a peer. This action does not notify users. ```rust async fn f(peer: grammers_session::types::PeerRef, client: grammers_client::Client) -> Result<(), Box> { let message_id = 123; client.pin_message(peer, message_id).await?; Ok(()) } ``` -------------------------------- ### Create a new InputMedia Source: https://docs.rs/grammers-client/latest/grammers_client/media/struct.InputMedia.html Initializes a new, empty media message for input. This is the starting point for building an InputMedia object. ```rust pub struct InputMedia { /* private fields */ } ``` -------------------------------- ### Unpin Message Example Source: https://docs.rs/grammers-client/latest/src/grammers_client/client/messages.rs.html Demonstrates how to unpin a message from a peer. This is a simple call to the `unpin_message` method. ```rust async fn f(peer: grammers_session::types::PeerRef, client: grammers_client::Client) -> Result<(), Box> { let message_id = 123; client.unpin_message(peer, message_id).await?; Ok(()) } ``` -------------------------------- ### InputMessage::new Source: https://docs.rs/grammers-client/latest/grammers_client/message/struct.InputMessage.html Creates a new, empty message object ready for input. This is the starting point for building a message. ```APIDOC ## InputMessage::new ### Description Creates a new empty message for input. ### Method `new()` ### Returns - `Self`: A new instance of `InputMessage`. ``` -------------------------------- ### Get Password Hint Source: https://docs.rs/grammers-client/latest/grammers_client/client/struct.PasswordToken.html Retrieves an optional hint string associated with the PasswordToken. This can be useful for guiding the user during the authentication process. ```rust pub fn hint(&self) -> Option<&str> ``` -------------------------------- ### Get Total Poll Voters Source: https://docs.rs/grammers-client/latest/grammers_client/media/struct.Poll.html Returns the total number of unique voters who participated in the poll. This may be None if the poll has not yet started receiving votes. ```rust pub fn total_voters(&self) -> Option ``` -------------------------------- ### Create InputMedia with Document Source: https://docs.rs/grammers-client/latest/src/grammers_client/media/input_media.rs.html Use this to send videos, stickers, audios, or uncompressed photos as a document. The text will be the caption. ```rust pub fn document(mut self, file: Uploaded) -> Self { let mime_type = self.get_file_mime(&file); let file_name = file.name().to_string(); self.media = Some( (tl::types::InputMediaUploadedDocument { nosound_video: false, force_file: false, spoiler: false, file: file.raw, thumb: None, mime_type, attributes: vec![(tl::types::DocumentAttributeFilename { file_name }).into()], stickers: None, ttl_seconds: self.media_ttl, video_cover: None, video_timestamp: None, }) .into() ); self } ``` -------------------------------- ### Client::with_configuration Source: https://docs.rs/grammers-client/latest/grammers_client/client/struct.Client.html Creates a new client instance with a custom ClientConfiguration. ```APIDOC ## Client::with_configuration ### Description Like `Self::new` but with a custom `ClientConfiguration`. ### Method `with_configuration` ### Parameters - `sender_pool`: `SenderPoolFatHandle` - The sender pool handle for managing network connections. - `configuration`: `ClientConfiguration` - The custom client configuration to use. ``` -------------------------------- ### Get Messages by IDs Source: https://docs.rs/grammers-client/latest/src/grammers_client/client/messages.rs.html Retrieve up to 100 messages by their IDs using `get_messages_by_id`. The function returns a `Vec>` where `None` indicates a message could not be retrieved or doesn't belong to the peer. This example demonstrates how to count the number of successfully retrieved messages. ```rust # async fn f(peer: grammers_session::types::PeerRef, client: grammers_client::Client) -> Result<(), Box> { let message_ids = [123, 456, 789]; let messages = client.get_messages_by_id(peer, &message_ids).await?; let count = messages.into_iter().filter(Option::is_some).count(); println!("{} out of {} messages were deleted!", message_ids.len() - count, message_ids.len()); # Ok(()) # } ``` -------------------------------- ### Create InputMedia as a Force File Source: https://docs.rs/grammers-client/latest/src/grammers_client/media/input_media.rs.html Use this to send any type of media as a simple document file, overriding default media type interpretations. The text will be the caption. ```rust pub fn file(mut self, file: Uploaded) -> Self { let mime_type = self.get_file_mime(&file); let file_name = file.name().to_string(); self.media = Some( (tl::types::InputMediaUploadedDocument { nosound_video: false, force_file: true, spoiler: false, file: file.raw, thumb: None, mime_type, ``` -------------------------------- ### thumbs Source: https://docs.rs/grammers-client/latest/src/grammers_client/media/media.rs.html Get document thumbs. ```APIDOC ## thumbs ### Description Retrieves the thumbnails associated with the document. See . ### Method `thumbs(&self) -> Vec` ### Parameters None ### Returns - `Vec`: A vector of `PhotoSize` objects representing the thumbnails. Returns an empty vector if no thumbnails are available. ``` -------------------------------- ### Create New InputMessage Source: https://docs.rs/grammers-client/latest/src/grammers_client/message/input_message.rs.html Initializes a new, empty message for input. Use this as a starting point before setting other message properties. ```rust pub fn new() -> Self { Self::default() } ``` -------------------------------- ### type_id Source: https://docs.rs/grammers-client/latest/grammers_client/message/struct.Message.html Gets the TypeId of the Message. ```APIDOC ## fn type_id(&self) -> TypeId ### Description Gets the `TypeId` of `self`. ``` -------------------------------- ### Create Venue from Raw Media Source: https://docs.rs/grammers-client/latest/grammers_client/media/struct.Venue.html Constructs a Venue instance from raw media data. This is the primary way to create a Venue object. ```rust pub fn from_raw_media(venue: MessageMediaVenue) -> Self ``` -------------------------------- ### Example: Adding Audio Attributes to Media Source: https://docs.rs/grammers-client/latest/src/grammers_client/media/input_media.rs.html Shows how to add audio-specific attributes, such as duration, title, and performer, to a document media. Ensure necessary imports are present. ```rust # async fn f(client: &mut grammers_client::Client) -> Result<(), Box> { # let audio = client.upload_file("audio.flac").await?; # use std::time::Duration; use grammers_client::media::{Attribute, InputMedia}; let media = InputMedia::new().caption("").document(audio).attribute( Attribute::Audio { duration: Duration::new(123, 0), title: Some("Hello".to_string()), performer: Some("World".to_string()), } ); # Ok(()) # } ``` -------------------------------- ### Get Total Messages Count (Iterator) Source: https://docs.rs/grammers-client/latest/src/grammers_client/client/messages.rs.html Initiates a network call to determine the total number of messages available for the current iterator configuration. This method sets the request limit to 1 to efficiently get the total count. ```rust pub async fn total(&mut self) -> Result { self.request.limit = 1; self.get_total().await } ``` -------------------------------- ### Client Initialization Source: https://docs.rs/grammers-client/latest/src/grammers_client/client/net.rs.html Provides methods for creating a new Grammers client instance, either with default or custom configurations. ```APIDOC ## `Client::new` ### Description Creates and returns a new client instance upon successful connection to Telegram. If the session in the configuration did not have an authorization key, a new one will be created and the session will be saved with it. The connection will be initialized with the data from the input configuration. ### Signature ```rust pub fn new(sender_pool: SenderPoolFatHandle) -> Self ``` ### Examples ```rust use std::sync::Arc; use grammers_client::Client; use grammers_session::storages::MemorySession; // avoid this storage outside tests! use grammers_mtsender::SenderPool; // Note: these are example values and are not actually valid. // Obtain your own with the developer's phone at https://my.telegram.org. const API_ID: i32 = 932939; # async fn f() -> Result<(), Box> { let session = Arc::new(MemorySession::default()); let pool = SenderPool::new(Arc::clone(&session), API_ID); let client = Client::new(pool.handle); # Ok(()) # } ``` ``` ```APIDOC ## `Client::with_configuration` ### Description Similar to `Client::new`, but allows for a custom `ClientConfiguration` to be provided during initialization. This offers more control over the client's behavior and settings. ### Signature ```rust pub fn with_configuration( sender_pool: SenderPoolFatHandle, configuration: ClientConfiguration, ) -> Self ``` ``` -------------------------------- ### id Source: https://docs.rs/grammers-client/latest/grammers_client/peer/struct.User.html Gets the unique identifier for the user. ```APIDOC ## pub fn id(&self) -> PeerId ### Description Returns the unique identifier for this user, which is of type `PeerId`. ### Returns - `PeerId`: The unique identifier of the user. ``` -------------------------------- ### Create New Client Source: https://docs.rs/grammers-client/latest/grammers_client/client/struct.Client.html Creates a new client instance using a SenderPoolHandle. Initializes session and connection data. ```rust use std::sync::Arc; use grammers_client::Client; use grammers_session::storages::MemorySession; // avoid this storage outside tests! use grammers_mtsender::SenderPool; // Note: these are example values and are not actually valid. // Obtain your own with the developer's phone at https://my.telegram.org. const API_ID: i32 = 932939; let session = Arc::new(MemorySession::default()); let pool = SenderPool::new(Arc::clone(&session), API_ID); let client = Client::new(pool.handle); ``` -------------------------------- ### User ID Source: https://docs.rs/grammers-client/latest/src/grammers_client/peer/user.rs.html Gets the unique identifier for a user. ```APIDOC ## id ### Description Return the unique identifier for this user. ### Method `User::id()` ### Returns - `PeerId` - The unique identifier of the user. ``` -------------------------------- ### Example: Adding Audio Attributes to InputMedia Source: https://docs.rs/grammers-client/latest/grammers_client/media/struct.InputMedia.html Shows how to attach audio-specific attributes, including duration, title, and performer, to an `InputMedia` object. This is typically used when sending audio files. ```rust use std::time::Duration; use grammers_client::media::{Attribute, InputMedia}; let media = InputMedia::new().caption("").document(audio).attribute( Attribute::Audio { duration: Duration::new(123, 0), title: Some("Hello".to_string()), performer: Some("World".to_string()), } ); ``` -------------------------------- ### mime_type Source: https://docs.rs/grammers-client/latest/src/grammers_client/media/media.rs.html Get the file's MIME type, if any. ```APIDOC ## mime_type ### Description Retrieves the MIME type of the media file. ### Method `mime_type(&self) -> Option<&str>` ### Parameters None ### Returns - `Option<&str>`: The MIME type of the file if available, otherwise `None`. ``` -------------------------------- ### Sign In with Phone Number and Code Source: https://docs.rs/grammers-client/latest/grammers_client/client/struct.Client.html Handles the sign-in process by requesting a login code and then signing in with the provided code. Includes error handling for password and sign-up requirements. ```rust async fn f(client: grammers_client::Client) -> Result<(), Box> { fn ask_code_to_user() -> String { unimplemented!() } let token = client.request_login_code(PHONE, API_HASH).await?; let code = ask_code_to_user(); let user = match client.sign_in(&token, &code).await { Ok(user) => user, Err(SignInError::PasswordRequired(_token)) => panic!("Please provide a password"), Err(SignInError::SignUpRequired) => panic!("Sign up required"), Err(err) => { println!("Failed to sign in as a user :(\n{}", err); return Err(err.into()); } }; if let Some(first_name) = user.first_name() { println!("Signed in as {}!", first_name); } else { println!("Signed in!"); } } ``` -------------------------------- ### get_reply_to_message Source: https://docs.rs/grammers-client/latest/grammers_client/client/struct.Client.html Gets the Message to which the input message is replying to. ```APIDOC ## get_reply_to_message ### Description Gets the `Message` to which the input message is replying to. ### Method `async fn get_reply_to_message(&self, message: &Message) -> Result, InvocationError>` ### Parameters #### Path Parameters - `message` (&Message): The message to check for a reply. ### Request Example ```rust if let Some(reply) = client.get_reply_to_message(&message).await? { println!("The reply said: {}", reply.text()); } ``` ### Response #### Success Response (Result, InvocationError>) - `Option`: The message being replied to, or `None` if there is no reply. ``` -------------------------------- ### Get Venue Address Source: https://docs.rs/grammers-client/latest/grammers_client/media/struct.Venue.html Retrieves the address of the venue. ```rust pub fn address(&self) -> &str ``` -------------------------------- ### from_raw Constructor Source: https://docs.rs/grammers-client/latest/grammers_client/media/struct.Uploaded.html Creates a new `Uploaded` instance from a given `InputFile`. ```APIDOC ### impl Uploaded #### pub fn from_raw(input_file: InputFile) -> Self Creates a new `Uploaded` instance from a raw `InputFile`. ``` -------------------------------- ### Implement GlobalSearchIter next method Source: https://docs.rs/grammers-client/latest/src/grammers_client/client/messages.rs.html Handles fetching the next message from the buffer or filling it from the network. Updates request offsets if more data needs to be fetched. ```rust pub async fn next(&mut self) -> Result, InvocationError> { if let Some(result) = self.next_raw() { return result; } self.request.limit = self.determine_limit(MAX_LIMIT); let offset_rate = self.fill_buffer(self.request.limit, None).await?; // Don't bother updating offsets if this is the last time stuff has to be fetched. if !self.last_chunk && !self.buffer.is_empty() { let last = &self.buffer[self.buffer.len() - 1]; self.request.offset_rate = offset_rate.unwrap_or(0); self.request.offset_peer = last .peer_ref() .await .map(|peer| peer.into()) .unwrap_or(tl::enums::InputPeer::Empty); self.request.offset_id = last.id(); } Ok(self.pop_item()) } ``` -------------------------------- ### Get Venue Title Source: https://docs.rs/grammers-client/latest/grammers_client/media/struct.Venue.html Retrieves the title of the venue. ```rust pub fn title(&self) -> &str ``` -------------------------------- ### impl Any for T Source: https://docs.rs/grammers-client/latest/grammers_client/media/struct.InputMedia.html Provides the `type_id` method to get the `TypeId` of the type. ```APIDOC ## fn type_id(&self) -> TypeId ### Description Gets the `TypeId` of `self`. ### Method `type_id` ### Parameters None ### Response - **TypeId**: The unique identifier for the type of `self`. ``` -------------------------------- ### Client::new Source: https://docs.rs/grammers-client/latest/grammers_client/client/struct.Client.html Creates and returns a new client instance upon successful connection to Telegram. ```APIDOC ## Client::new ### Description Creates and returns a new client instance upon successful connection to Telegram. If the session in the configuration did not have an authorization key, a new one will be created and the session will be saved with it. The connection will be initialized with the data from the input configuration. ### Method `new` ### Parameters - `sender_pool`: `SenderPoolFatHandle` - The sender pool handle for managing network connections. ### Request Example ```rust use std::sync::Arc; use grammers_client::Client; use grammers_session::storages::MemorySession; // avoid this storage outside tests! use grammers_mtsender::SenderPool; // Note: these are example values and are not actually valid. // Obtain your own with the developer's phone at https://my.telegram.org. const API_ID: i32 = 932939; let session = Arc::new(MemorySession::default()); let pool = SenderPool::new(Arc::clone(&session), API_ID); let client = Client::new(pool.handle); ``` ``` -------------------------------- ### Get Venue ID Source: https://docs.rs/grammers-client/latest/grammers_client/media/struct.Venue.html Retrieves the unique identifier of the venue. ```rust pub fn venue_id(&self) -> &str ``` -------------------------------- ### InputMedia::new Source: https://docs.rs/grammers-client/latest/grammers_client/media/struct.InputMedia.html Creates a new empty media message for input. ```APIDOC ## InputMedia::new ### Description Creates a new empty media message for input. ### Method `new()` ### Returns `Self` - A new instance of InputMedia. ``` -------------------------------- ### Get Venue Provider Source: https://docs.rs/grammers-client/latest/grammers_client/media/struct.Venue.html Retrieves the provider of the venue location. ```rust pub fn provider(&self) -> &str ``` -------------------------------- ### Create InputMedia with External Document URL Source: https://docs.rs/grammers-client/latest/src/grammers_client/media/input_media.rs.html Use this to specify a document via a URL, allowing Telegram servers to download and include it. The text will be the caption. ```rust pub fn document_url(mut self, url: impl Into) -> Self { self.media = Some( (tl::types::InputMediaDocumentExternal { spoiler: false, url: url.into(), ttl_seconds: self.media_ttl, video_cover: None, video_timestamp: None, }) .into() ); self } ``` -------------------------------- ### Get Document Size Source: https://docs.rs/grammers-client/latest/grammers_client/media/struct.Document.html Returns the size of the file in bytes. ```rust pub fn size(&self) -> Option ``` -------------------------------- ### Create a Custom Keyboard Source: https://docs.rs/grammers-client/latest/grammers_client/message/struct.ReplyMarkup.html Use `from_keys` to define a custom keyboard that replaces the user's virtual keyboard. This is useful for bots to guide user input. Input is a matrix of `Key` objects. ```rust use grammers_client::message::{InputMessage, ReplyMarkup, Key}; let markup = ReplyMarkup::from_keys(&[ vec![Key::text("Accept")], vec![Key::text("Cancel"), Key::text("Try something else")], ]); client.send_message(peer, InputMessage::new().text("What do you want to do?").reply_markup(markup)).await?; ``` -------------------------------- ### Get Longitude from Geo Source: https://docs.rs/grammers-client/latest/grammers_client/media/struct.Geo.html Retrieves the longitude of the geographical location. ```rust pub fn longitude(&self) -> f64 ``` -------------------------------- ### Get Latitude from Geo Source: https://docs.rs/grammers-client/latest/grammers_client/media/struct.Geo.html Retrieves the latitude of the geographical location. ```rust pub fn latitue(&self) -> f64 ``` -------------------------------- ### Initialize GlobalSearchIter Source: https://docs.rs/grammers-client/latest/src/grammers_client/client/messages.rs.html Creates a new GlobalSearchIter with default parameters. Users can further configure the search request using methods like `offset_id`, `query`, and `filter`. ```rust fn new(client: &Client) -> Self { // TODO let users tweak all the options from the request Self::from_request( client, MAX_LIMIT, tl::functions::messages::SearchGlobal { folder_id: None, q: String::new(), filter: tl::enums::MessagesFilter::InputMessagesFilterEmpty, min_date: 0, max_date: 0, offset_rate: 0, offset_peer: tl::enums::InputPeer::Empty, offset_id: 0, limit: 0, broadcasts_only: false, groups_only: false, users_only: false, }, ) } ``` -------------------------------- ### ActionSender::repeat Example Source: https://docs.rs/grammers-client/latest/src/grammers_client/peer/action.rs.html Demonstrates how to use the `repeat` method to continuously send an action while a heavy task is running. The `repeat` method returns the output of the future and the result of the last action request. ```rust use std::time::Duration; # async fn f(peer: grammers_session::types::PeerRef, client: grammers_client::Client) -> Result<(), Box> { use grammers_tl_types as tl; let heavy_task = async { tokio::time::sleep(Duration::from_secs(10)).await; 42 }; tokio::pin!(heavy_task); let (task_result, _) = client .action(peer) .repeat( // most clients doesn't actually show progress of an action || tl::types::SendMessageUploadDocumentAction { progress: 0 }, heavy_task ) .await; // Note: repeat function does not cancel actions automatically, they will just fade away assert_eq!(task_result, 42); # Ok(()) # } ``` -------------------------------- ### Get replied message Source: https://docs.rs/grammers-client/latest/src/grammers_client/message/message.rs.html Fetches the actual message that this message is replying to. ```APIDOC ## GET /messages/{message_id}/get_reply ### Description Fetches the message that this message is replying to. ### Method GET ### Endpoint `/messages/{message_id}/get_reply` ### Parameters #### Path Parameters - **message_id** (int) - Required - The ID of the message to get the replied message for. ### Response #### Success Response (200) - **message** (object) - The message object that was replied to, or null if not a reply. #### Response Example ```json { "message": { "id": 98765, "text": "This is the original message." } } ``` ``` -------------------------------- ### Build InputMedia from HTML Source: https://docs.rs/grammers-client/latest/src/grammers_client/media/input_media.rs.html Constructs an InputMedia using an HTML-formatted string for the caption and its entities. Requires the 'html' feature to be enabled. ```rust #[cfg(feature = "html")] pub fn html(mut self, s: T) -> Self where T: AsRef, { let (caption, entities) = crate::parsers::parse_html_message(s.as_ref()); self.caption = caption; self.entities = entities; self } ``` -------------------------------- ### Get restriction reason Source: https://docs.rs/grammers-client/latest/src/grammers_client/message/message.rs.html Provides a list of reasons why a message is restricted, if any. ```APIDOC ## GET /messages/{message_id}/restriction_reason ### Description Returns a list of reasons why this message is restricted. ### Method GET ### Endpoint `/messages/{message_id}/restriction_reason` ### Parameters #### Path Parameters - **message_id** (int) - Required - The ID of the message to get the restriction reason for. ### Response #### Success Response (200) - **restriction_reason** (array) - A list of restriction reasons. Empty if the message is not restricted. #### Response Example ```json { "restriction_reason": [ "spam" ] } ``` ``` -------------------------------- ### Build InputMedia from Markdown Source: https://docs.rs/grammers-client/latest/src/grammers_client/media/input_media.rs.html Constructs an InputMedia using a markdown-formatted string for the caption and its entities. Requires the 'markdown' feature to be enabled. ```rust #[cfg(feature = "markdown")] pub fn markdown(mut self, s: T) -> Self where T: AsRef, { let (caption, entities) = crate::parsers::parse_markdown_message(s.as_ref()); self.caption = caption; self.entities = entities; self } ``` -------------------------------- ### Get Photo Source: https://docs.rs/grammers-client/latest/grammers_client/update/struct.Message.html Retrieves the photo attached to the message, if one exists. ```APIDOC ## pub fn photo(&self) -> Option ### Description Get photo attached to the message if any. ### Method `fn photo` ### Parameters None ### Returns `Option` - `Some(Photo)` if a photo is attached, `None` otherwise. ``` -------------------------------- ### Get Audio Title Source: https://docs.rs/grammers-client/latest/grammers_client/media/struct.Document.html Retrieves the title of the audio file, if available. ```rust pub fn audio_title(&self) -> Option<&str> ``` -------------------------------- ### Get InlineResult Title Source: https://docs.rs/grammers-client/latest/grammers_client/client/struct.InlineResult.html Retrieves the title of this inline result, if it exists. ```rust pub fn title(&self) -> Option<&String> ``` -------------------------------- ### Create GeoLive from Raw Media Source: https://docs.rs/grammers-client/latest/grammers_client/media/struct.GeoLive.html Constructs a GeoLive instance from raw media data. Use this when you receive live location data in its raw format. ```rust pub fn from_raw_media(geolive: MessageMediaGeoLive) -> Self ``` -------------------------------- ### Create Grammers Client Instance Source: https://docs.rs/grammers-client/latest/src/grammers_client/client/net.rs.html Initializes a new Grammers client instance with a provided sender pool handle. If the session lacks an authorization key, a new one is created and saved. ```rust use std::sync::Arc; use grammers_client::Client; use grammers_session::storages::MemorySession; // avoid this storage outside tests! use grammers_mtsender::SenderPool; // Note: these are example values and are not actually valid. // Obtain your own with the developer's phone at https://my.telegram.org. const API_ID: i32 = 932939; # async fn f() -> Result<(), Box> { let session = Arc::new(MemorySession::default()); let pool = SenderPool::new(Arc::clone(&session), API_ID); let client = Client::new(pool.handle); # Ok(()) # } ``` -------------------------------- ### Get InlineResult ID Source: https://docs.rs/grammers-client/latest/grammers_client/client/struct.InlineResult.html Retrieves the unique ID for this inline result. ```rust pub fn id(&self) -> &str ``` -------------------------------- ### Create Document from Raw Media Source: https://docs.rs/grammers-client/latest/grammers_client/media/struct.Document.html Constructs a `Document` instance from a raw `MessageMediaDocument`. This is the primary way to create a `Document` object. ```rust pub fn from_raw_media(document: MessageMediaDocument) -> Self ``` -------------------------------- ### Get action Source: https://docs.rs/grammers-client/latest/src/grammers_client/message/message.rs.html If the message is a service message, this returns the associated service action. ```APIDOC ## GET /messages/{message_id}/action ### Description If this message is a service message, return the service action that occurred. ### Method GET ### Endpoint `/messages/{message_id}/action` ### Parameters #### Path Parameters - **message_id** (int) - Required - The ID of the message to get the action for. ### Response #### Success Response (200) - **action** (object) - The service action associated with the message. #### Response Example ```json { "action": { "type": "user_joined", "user_id": 12345 } } ``` ``` -------------------------------- ### Get edit date Source: https://docs.rs/grammers-client/latest/src/grammers_client/message/message.rs.html Retrieves the date when the message was last edited, if it has been edited. ```APIDOC ## GET /messages/{message_id}/edit_date ### Description Retrieves the date when the message was last edited. ### Method GET ### Endpoint `/messages/{message_id}/edit_date` ### Parameters #### Path Parameters - **message_id** (int) - Required - The ID of the message to get the edit date for. ### Response #### Success Response (200) - **edit_date** (string) - The ISO 8601 formatted date and time of the last edit. #### Response Example ```json { "edit_date": "2023-10-27T10:30:00Z" } ``` ``` -------------------------------- ### ActionSender::new Source: https://docs.rs/grammers-client/latest/grammers_client/peer/struct.ActionSender.html Creates a new ActionSender instance. ```APIDOC ## ActionSender::new ### Description Creates a new ActionSender instance. ### Signature `pub fn new>(client: &Client, peer: C) -> Self` ``` -------------------------------- ### Get reaction count Source: https://docs.rs/grammers-client/latest/src/grammers_client/message/message.rs.html Retrieves the total count of reactions on a message, if applicable. ```APIDOC ## GET /messages/{message_id}/reactions/count ### Description Retrieves the total count of reactions on a message. ### Method GET ### Endpoint `/messages/{message_id}/reactions/count` ### Parameters #### Path Parameters - **message_id** (int) - Required - The ID of the message to get the reaction count for. ### Response #### Success Response (200) - **count** (int) - The total number of reactions on the message. #### Response Example ```json { "count": 5 } ``` ``` -------------------------------- ### Get Pinned Message Source: https://docs.rs/grammers-client/latest/grammers_client/client/struct.Client.html Retrieves the latest pinned message from a specified peer. ```rust client.get_pinned_message(peer).await?; ``` -------------------------------- ### InputMedia::attribute Source: https://docs.rs/grammers-client/latest/grammers_client/media/struct.InputMedia.html Add additional attributes to the media. This must be called _after_ setting a file. ```APIDOC ## InputMedia::attribute ### Description Add additional attributes to the media. This must be called _after_ setting a file. ### Method `attribute(self, attr: Attribute) -> Self` ### Parameters - **attr** (Attribute) - The attribute to add to the media. ``` -------------------------------- ### Get User Language Code Source: https://docs.rs/grammers-client/latest/grammers_client/peer/struct.User.html Retrieves the language code of the user, if available. ```rust pub fn lang_code(&self) -> Option<&str> ``` -------------------------------- ### Configure Reply Markup Options Source: https://docs.rs/grammers-client/latest/grammers_client/message/struct.ReplyMarkup.html Use `fit_size()` to request clients to resize the keyboard vertically for optimal fit, and `single_use()` to hide the keyboard after it's used. These methods modify the behavior of custom keyboards. ```rust pub fn fit_size(self) -> Self ``` ```rust pub fn single_use(self) -> Self ``` -------------------------------- ### Create CallbackQuery Answer Builder Source: https://docs.rs/grammers-client/latest/src/grammers_client/update/callback_query.rs.html Initiates the process of answering a callback query. This method returns an `Answer` builder, which can be configured before being executed. ```rust pub fn answer(&self) -> Answer<'_> { let query_id = match &self.raw { tl::enums::Update::BotCallbackQuery(update) => update.query_id, ``` -------------------------------- ### Get User Last Name Source: https://docs.rs/grammers-client/latest/grammers_client/peer/struct.User.html Retrieves the last name of the user, if available. ```rust pub fn last_name(&self) -> Option<&str> ``` -------------------------------- ### Get Ban Due Date Source: https://docs.rs/grammers-client/latest/grammers_client/peer/struct.Restrictions.html Returns the date and time until which the ban is effective. ```rust pub fn due(&self) -> DateTime ``` -------------------------------- ### Sign in as a Bot Source: https://docs.rs/grammers-client/latest/src/grammers_client/client/auth.rs.html Use this method to authenticate the client using a bot token and API hash. It's recommended to save the session after a successful login. If saving fails, consider signing out. ```rust pub async fn bot_sign_in(&self, token: &str, api_hash: &str) -> Result { let request = tl::functions::auth::ImportBotAuthorization { flags: 0, api_id: self.0.api_id, api_hash: api_hash.to_string(), bot_auth_token: token.to_string(), }; let result = match self.invoke(&request).await { Ok(x) => x, Err(InvocationError::Rpc(err)) if err.code == 303 => { let old_dc_id = self.0.session.home_dc_id(); let new_dc_id = err.value.unwrap() as i32; // Disconnect from current DC to cull the now-unused connection. // This also gives a chance for the new home DC to export its authorization // if there's a need to connect back to the old DC after having logged in. self.0.handle.disconnect_from_dc(old_dc_id); self.0.session.set_home_dc_id(new_dc_id).await; self.invoke(&request).await? } Err(e) => return Err(e.into()), }; match result { tl::enums::auth::Authorization::Authorization(x) => { self.complete_login(x).await.map_err(Into::into) } tl::enums::auth::Authorization::SignUpRequired(_) => { panic!("API returned SignUpRequired even though we're logging in as a bot"); } } } ``` -------------------------------- ### Get Channel Photo Source: https://docs.rs/grammers-client/latest/grammers_client/peer/struct.Channel.html Returns the photo associated with the channel, if one exists. ```rust pub fn photo(&self) -> Option<&ChatPhoto> ``` -------------------------------- ### Default InputMedia Implementation Source: https://docs.rs/grammers-client/latest/grammers_client/media/struct.InputMedia.html Provides the default value for `InputMedia`, which is an empty media message. ```rust fn default() -> InputMedia ``` -------------------------------- ### Upload and Send Document with Thumbnail Source: https://docs.rs/grammers-client/latest/grammers_client/message/struct.InputMessage.html Uploads a video and a thumbnail, then creates an InputMessage with the video as a document and the thumbnail attached. The message text is empty. ```rust async fn f(client: &mut grammers_client::Client) -> Result<(), Box> { use grammers_client::message::InputMessage; let video = client.upload_file("video.mp4").await?; let thumb = client.upload_file("thumb.png").await?; let message = InputMessage::new().text("").document(video).thumbnail(thumb); Ok(()) } ``` -------------------------------- ### Get Venue Type Source: https://docs.rs/grammers-client/latest/grammers_client/media/struct.Venue.html Retrieves the type of the venue (e.g., 'restaurant', 'cafe'). ```rust pub fn venue_type(&self) -> &str ``` -------------------------------- ### Get Audio Performer Source: https://docs.rs/grammers-client/latest/grammers_client/media/struct.Document.html Retrieves the performer (artist) of the audio file, if available. ```rust pub fn performer(&self) -> Option<&str> ``` -------------------------------- ### Create WebView Button Source: https://docs.rs/grammers-client/latest/src/grammers_client/message/button.rs.html Use this to create a button that opens a specified URL within an in-app browser. ```rust pub fn webview, U: Into>(text: T, url: U) -> Button { Button { raw: tl::types::KeyboardButtonWebView { style: None, text: text.into(), url: url.into(), } .into(), } } ``` -------------------------------- ### Upload a File using its Path Source: https://docs.rs/grammers-client/latest/src/grammers_client/client/files.rs.html Opens a local file, determines its size, and then uploads it using the `upload_stream` method. Requires the `fs` feature to be enabled. ```rust pub async fn upload_file>(&self, path: P) -> Result { let path = path.as_ref(); let mut file = fs::File::open(path).await?; let size = file.seek(SeekFrom::End(0)).await? as usize; file.seek(SeekFrom::Start(0)).await?; // File name will only be `None` for `..` path, and directories cannot be uploaded as // files, so it's fine to unwrap. let name = path.file_name().unwrap().to_string_lossy().to_string(); self.upload_stream(&mut file, size, name).await } ``` -------------------------------- ### Get Video/Audio Duration Source: https://docs.rs/grammers-client/latest/grammers_client/media/struct.Document.html Returns the duration of the video or audio in seconds, if applicable. ```rust pub fn duration(&self) -> Option ``` -------------------------------- ### Get Document ID Source: https://docs.rs/grammers-client/latest/grammers_client/media/struct.Document.html Retrieves the globally unique identifier for the media document. ```rust pub fn id(&self) -> i64 ``` -------------------------------- ### InputReactions From Implementations Source: https://docs.rs/grammers-client/latest/src/grammers_client/message/reactions.rs.html Provides convenient ways to create `InputReactions` from various types. ```APIDOC ## InputReactions From Implementations ### `impl From for InputReactions` #### Description Creates an `InputReactions` instance from a `String` representing an emoticon. #### Usage ```rust let reactions: InputReactions = "👍".to_string().into(); ``` ``` ```APIDOC ## InputReactions From Implementations ### `impl From<&str> for InputReactions` #### Description Creates an `InputReactions` instance from a string slice (`&str`) representing an emoticon. #### Usage ```rust let reactions: InputReactions = "❤️".into(); ``` ``` ```APIDOC ## InputReactions From Implementations ### `impl From> for InputReactions` #### Description Creates an `InputReactions` instance from a vector of `Reaction` types. #### Parameters - `reactions` (Vec) - The vector of reactions. #### Usage ```rust let reactions_vec: Vec = vec![...]; let input_reactions: InputReactions = reactions_vec.into(); ``` ``` ```APIDOC ## InputReactions From Implementations ### `impl From for Vec` #### Description Converts an `InputReactions` instance into a vector of `Reaction` types. #### Usage ```rust let input_reactions: InputReactions = InputReactions::emoticon("😂"); let reactions_vec: Vec = input_reactions.into(); ``` ``` -------------------------------- ### Get reply to message ID Source: https://docs.rs/grammers-client/latest/src/grammers_client/message/message.rs.html Returns the ID of the message that this message is replying to, if it is a reply. ```APIDOC ## GET /messages/{message_id}/reply_to_message_id ### Description Returns the ID of the message that this message is replying to. ### Method GET ### Endpoint `/messages/{message_id}/reply_to_message_id` ### Parameters #### Path Parameters - **message_id** (int) - Required - The ID of the message to get the reply-to message ID for. ### Response #### Success Response (200) - **reply_to_message_id** (int) - The ID of the message being replied to. #### Response Example ```json { "reply_to_message_id": 98765 } ``` ``` -------------------------------- ### Create Grammers Client with Custom Configuration Source: https://docs.rs/grammers-client/latest/src/grammers_client/client/net.rs.html Creates a new Grammers client instance using a custom `ClientConfiguration`. This allows for more specific setup of client behavior. ```rust pub fn with_configuration( sender_pool: SenderPoolFatHandle, configuration: ClientConfiguration, ) -> Self { // TODO Sender doesn't have a way to handle backpressure yet Self(Arc::new(ClientInner { session: sender_pool.session, api_id: sender_pool.api_id, handle: sender_pool.thin, configuration, auth_copied_to_dcs: Mutex::new(Vec::new()), })) } ``` -------------------------------- ### into_ok Source: https://docs.rs/grammers-client/latest/grammers_client/type.Result.html Returns the contained Ok value, but never panics. This is a nightly-only experimental API. ```APIDOC ## into_ok ### Description Returns the contained `Ok` value, but never panics. This method is known to never panic on the result types it is implemented for, making it a maintainability safeguard. ### Method `into_ok()` ### Parameters None ### Request Example ```rust fn only_good_news() -> Result { Ok("this is fine".into()) } let s: String = only_good_news().into_ok(); println!("{s}"); ``` ### Response #### Success Response (T) Returns the contained `Ok` value. #### Response Example ```rust "this is fine" ``` ### Constraints Requires `E` to implement `Into`. ### Note This is a nightly-only experimental API. ``` -------------------------------- ### Get grouped ID Source: https://docs.rs/grammers-client/latest/src/grammers_client/message/message.rs.html Returns the unique identifier for a group of messages, such as media albums. ```APIDOC ## GET /messages/{message_id}/grouped_id ### Description Returns the unique identifier for a group of messages, applicable to media albums. ### Method GET ### Endpoint `/messages/{message_id}/grouped_id` ### Parameters #### Path Parameters - **message_id** (int) - Required - The ID of the message to get the grouped ID for. ### Response #### Success Response (200) - **grouped_id** (long) - The unique identifier for the message group. #### Response Example ```json { "grouped_id": 1234567890 } ``` ``` -------------------------------- ### Create WebPage from Raw Media Source: https://docs.rs/grammers-client/latest/grammers_client/media/struct.WebPage.html Constructs a WebPage instance from raw message media data. This is the primary way to create a WebPage object. ```rust pub fn from_raw_media(webpage: MessageMediaWebPage) -> Self ``` -------------------------------- ### Get Message Forward Count Source: https://docs.rs/grammers-client/latest/src/grammers_client/message/message.rs.html Returns the number of times a message has been forwarded, if applicable. ```rust /// How many times has this message been forwarded, when applicable. pub fn forward_count(&self) -> Option { match &self.raw { tl::enums::Message::Empty(_) => None, tl::enums::Message::Message(message) => message.forwards, tl::enums::Message::Service(_) => None, } } ``` -------------------------------- ### WebPage::from_raw_media Source: https://docs.rs/grammers-client/latest/grammers_client/media/struct.WebPage.html Creates a new WebPage instance from raw media data. ```APIDOC ## impl WebPage ### pub fn from_raw_media(webpage: MessageMediaWebPage) -> Self Creates a new WebPage instance from raw media data. ``` -------------------------------- ### Get CachedSize Data Source: https://docs.rs/grammers-client/latest/src/grammers_client/media/photo_sizes.rs.html Returns the byte data stored within a CachedSize struct. ```rust fn data(&self) -> Vec { self.bytes.clone() } ``` -------------------------------- ### ActionSender::new Source: https://docs.rs/grammers-client/latest/src/grammers_client/peer/action.rs.html Creates a new ActionSender. It requires a client and a peer reference. The repeat delay defaults to 4 seconds. ```rust pub fn new>(client: &Client, peer: C) -> Self { Self { client: client.clone(), peer: peer.into(), topic_id: None, repeat_delay: DEFAULT_REPEAT_DELAY, } } ``` -------------------------------- ### Get Pinned Message Source: https://docs.rs/grammers-client/latest/grammers_client/client/struct.Client.html Checks if a message is pinned in a peer and prints its text if found. ```rust if let Some(message) = client.get_pinned_message(peer).await? { println!("There is a message pinned: {}", message.text()); } else { println!("There are no messages pinned"); } ``` -------------------------------- ### size Method Source: https://docs.rs/grammers-client/latest/grammers_client/media/trait.Downloadable.html Returns the file size in bytes for a downloadable item. This method provides the size without needing to download the entire file. ```rust fn size(&self) -> Option { ... } ``` -------------------------------- ### Get Deleted Message IDs Source: https://docs.rs/grammers-client/latest/grammers_client/update/struct.MessageDeletion.html Returns a slice containing the IDs of the messages that were deleted. ```rust pub fn messages(&self) -> &[i32] ``` -------------------------------- ### Create Webview Button Source: https://docs.rs/grammers-client/latest/grammers_client/message/struct.Button.html Creates a button that opens a specified URL within an in-app browser when clicked. ```rust pub fn webview, U: Into>(text: T, url: U) -> Button ``` -------------------------------- ### Get Channel Admin Rights Source: https://docs.rs/grammers-client/latest/grammers_client/peer/struct.Channel.html Returns the permissions of the logged-in user within this channel. ```rust pub fn admin_rights(&self) -> Option<&ChatAdminRights> ``` -------------------------------- ### Get Peer Reference from Dialog Source: https://docs.rs/grammers-client/latest/grammers_client/peer/struct.Dialog.html Obtains a cached reference to the peer object for the dialog. ```rust pub fn peer_ref(&self) -> PeerRef ``` -------------------------------- ### SenderPool::with_configuration Source: https://docs.rs/grammers-client/latest/grammers_client/struct.SenderPool.html Creates a new sender pool with non-default connection parameters. ```APIDOC ## SenderPool::with_configuration ### Description Creates a new sender pool with non-`ConnectionParams::default` configuration. ### Signature ```rust pub fn with_configuration( session: Arc, api_id: i32, connection_params: ConnectionParams, ) -> SenderPool where S: Session + 'static, ``` ``` -------------------------------- ### Get Peer ID from Dialog Source: https://docs.rs/grammers-client/latest/grammers_client/peer/struct.Dialog.html Retrieves the unique identifier for the peer associated with the dialog. ```rust pub fn peer_id(&self) -> PeerId ``` -------------------------------- ### Downloadable Implementation for Photo Source: https://docs.rs/grammers-client/latest/grammers_client/media/struct.Photo.html Provides methods for downloading and accessing photo media. ```APIDOC ### impl Downloadable for Photo #### `fn to_raw_input_location(&self) -> Option` Converts this downloadable into the input type that may be used by raw requests to download it. #### `fn to_data(&self) -> Option>` Returns `Some` if the media has a tiny thumbnail embedded within. #### `fn size(&self) -> Option` File size, in bytes. ``` -------------------------------- ### Create Callback Data Button Source: https://docs.rs/grammers-client/latest/src/grammers_client/message/button.rs.html Use this to create a button that triggers a `CallbackQuery` when clicked. The `callback_data` has a size limit, so consider using a database reference for larger data. ```rust pub fn data, B: Into>>(text: T, bytes: B) -> Button { Button { raw: tl::types::KeyboardButtonCallback { text: text.into(), data: bytes.into(), requires_password: false, style: None, } .into(), } } ``` -------------------------------- ### Get Video/Image Resolution Source: https://docs.rs/grammers-client/latest/grammers_client/media/struct.Document.html Returns the width and height of the video or image in pixels, if available. ```rust pub fn resolution(&self) -> Option<(i32, i32)> ``` -------------------------------- ### Get Document Creation Date Source: https://docs.rs/grammers-client/latest/grammers_client/media/struct.Document.html Returns the date on which the file was created, if this information is available. ```rust pub fn creation_date(&self) -> Option> ``` -------------------------------- ### Bot Sign In with Token and API Hash Source: https://docs.rs/grammers-client/latest/grammers_client/client/struct.Client.html Signs in to the bot account using a provided token and API hash. It's recommended to save the session after a successful login. ```rust // Note: these values are obviously fake. // Obtain your own with the developer's phone at https://my.telegram.org. const API_HASH: &str = "514727c32270b9eb8cc16daf17e21e57"; // Obtain your own by talking to @BotFather via a Telegram app. const TOKEN: &str = "776609994:AAFXAy5-PawQlnYywUlZ_b_GOXgarR3ah_yq"; let user = match client.bot_sign_in(TOKEN, API_HASH).await { Ok(user) => user, Err(err) => { println!("Failed to sign in as a bot :( {}", err); return Err(err.into()); } }; if let Some(first_name) = user.first_name() { println!("Signed in as {}!", first_name); } else { println!("Signed in!"); } ``` -------------------------------- ### Get Document MIME Type Source: https://docs.rs/grammers-client/latest/grammers_client/media/struct.Document.html Retrieves the file's MIME type, if available. ```rust pub fn mime_type(&self) -> Option<&str> ```