Skip to main content

Client

Struct Client 

Source
pub struct Client { /* private fields */ }
Expand description

The main Telegram client. Cheap to clone: internally Arc-wrapped.

Implementations§

Source§

impl Client

Source

pub async fn bot_sign_in(&self, token: &str) -> Result<String, InvocationError>

Sign in as a bot.

Source

pub async fn request_login_code( &self, phone: &str, ) -> Result<LoginToken, InvocationError>

Request a login code for a user account.

Source

pub async fn sign_in( &self, token: &LoginToken, code: &str, ) -> Result<String, SignInError>

Complete sign-in with the code sent to the phone.

Source

pub async fn check_password( &self, token: PasswordToken, password: impl AsRef<[u8]>, ) -> Result<String, InvocationError>

Complete 2FA login.

Source

pub async fn sign_out(&self) -> Result<bool, InvocationError>

Sign out and invalidate the current session.

Source

pub async fn get_users_by_id( &self, ids: &[i64], ) -> Result<Vec<Option<User>>, InvocationError>

Fetch user info by ID. Returns None for each ID that is not found.

Used internally by update::IncomingMessage::sender_user.

Source

pub async fn get_user_from_message( &self, peer: InputPeer, msg_id: i32, user_id: i64, ) -> Result<Option<User>, InvocationError>

Resolve a user by message context (no access_hash required). Returns None if Telegram returns no matching user.

Source

pub async fn get_me(&self) -> Result<User, InvocationError>

Fetch information about the logged-in user.

Source

pub async fn export_login_token( &self, ) -> Result<(Vec<u8>, i32), InvocationError>

Generate a QR-code login token.

Returns (token_bytes, expires_unix_ts). Encode token_bytes as a tg://login?token=<base64url> URL and present as a QR code.

Call [import_qr_token] once the user scans it, then poll until you receive Update::Raw with updateLoginToken (constructor 0x564fe691), or call [export_login_token] again to check.

§Example
let (token, expires) = client.export_login_token().await?;
// base64url-encode `token` and make a QR code
Source

pub async fn check_qr_login( &self, token: Vec<u8>, ) -> Result<Option<String>, InvocationError>

Check whether a QR-code token has been scanned.

Returns Some(username) if the user has scanned and confirmed the QR code, or None if still pending.

Source§

impl Client

Source

pub async fn delete_channel( &self, peer: impl Into<PeerRef>, ) -> Result<(), InvocationError>

Permanently delete a channel or supergroup.

Only the creator can delete a channel. This action is irreversible.

Source

pub async fn delete_chat(&self, chat_id: i64) -> Result<(), InvocationError>

Delete a legacy group chat (basic group).

Only the creator can delete the chat. For channels use [delete_channel].

Source

pub async fn leave_chat( &self, peer: impl Into<PeerRef>, ) -> Result<(), InvocationError>

Leave a channel or supergroup.

For basic groups, kick yourself with [kick_participant] or use [delete_dialog] to just hide it.

Source

pub async fn migrate_chat(&self, chat_id: i64) -> Result<Chat, InvocationError>

Upgrade a legacy group to a supergroup (megagroup).

Returns the new channel/supergroup peer. The original chat ID becomes invalid after migration.

Source§

impl Client

Source

pub async fn get_dialogs( &self, limit: i32, ) -> Result<Vec<Dialog>, InvocationError>

Fetch up to limit dialogs, most recent first. Populates entity/message.

Source

pub async fn delete_dialog( &self, peer: impl Into<PeerRef>, ) -> Result<(), InvocationError>

Source

pub async fn mark_as_read( &self, peer: impl Into<PeerRef>, ) -> Result<(), InvocationError>

Mark all messages in a chat as read.

Source

pub async fn clear_mentions( &self, peer: impl Into<PeerRef>, ) -> Result<(), InvocationError>

Clear unread mention markers.

Source

pub async fn join_chat( &self, peer: impl Into<PeerRef>, ) -> Result<(), InvocationError>

Join a public chat or channel by username/peer.

Accept and join via an invite link.

Source

pub fn parse_invite_hash(link: &str) -> Option<&str>

Extract hash from https://t.me/+HASH or https://t.me/joinchat/HASH.

Source

pub fn iter_dialogs(&self) -> DialogIter

Returns a DialogIter that can be advanced with DialogIter::next. Lets you page through all dialogs without loading them all at once.

§Example
let mut iter = client.iter_dialogs();
while let Some(dialog) = iter.next(&client).await? {
println!("{}", dialog.title());
}
Source

pub fn iter_messages(&self, peer: impl Into<PeerRef>) -> MessageIter

Fetch messages from a peer, page by page.

Returns a MessageIter that can be advanced with MessageIter::next.

§Example
let mut iter = client.iter_messages(peer);
while let Some(msg) = iter.next(&client).await? {
println!("{:?}", msg.text());
}
Source

pub async fn sync_drafts(&self) -> Result<(), InvocationError>

Fetch all saved drafts across all chats.

The server responds with an Updates containing updateDraftMessage entries; this method triggers that push and returns immediately.

Source

pub async fn clear_all_drafts(&self) -> Result<(), InvocationError>

Delete all saved drafts across all chats.

Source

pub async fn pin_dialog( &self, peer: impl Into<PeerRef>, ) -> Result<(), InvocationError>

Pin a dialog to the top of the dialog list.

Source

pub async fn unpin_dialog( &self, peer: impl Into<PeerRef>, ) -> Result<(), InvocationError>

Unpin a previously pinned dialog.

Source

pub async fn archive_chat( &self, peer: impl Into<PeerRef>, ) -> Result<(), InvocationError>

Archive a dialog (move it to folder 1).

Archived chats are hidden from the main dialog list.

§Example
client.archive_chat("@somebot").await?;
Source

pub async fn unarchive_chat( &self, peer: impl Into<PeerRef>, ) -> Result<(), InvocationError>

Unarchive a dialog (move it back to folder 0 - the main list).

§Example
client.unarchive_chat("@somebot").await?;
Source

pub async fn mark_dialog_read( &self, peer: impl Into<PeerRef>, ) -> Result<(), InvocationError>

Mark a dialog as read (clears the unread mark).

Source§

impl Client

Source

pub fn search(&self, peer: impl Into<PeerRef>, query: &str) -> SearchBuilder

Fluent search builder for in-chat message search.

Source

pub fn search_global(&self, query: &str) -> GlobalSearchBuilder

Fluent builder for global cross-chat search.

Source§

impl Client

Source

pub async fn read_reactions( &self, peer: impl Into<PeerRef>, ) -> Result<(), InvocationError>

Mark all unread reactions in a chat as read.

Source

pub async fn clear_recent_reactions(&self) -> Result<(), InvocationError>

Clear the recent reactions list shown in the reaction picker.

Source

pub async fn get_online_count( &self, peer: impl Into<PeerRef>, ) -> Result<i32, InvocationError>

Get the approximate number of online members in a group or channel.

Source§

impl Client

Source

pub async fn get_contacts(&self) -> Result<Vec<User>, InvocationError>

Fetch the full contact list of the current user.

Returns an empty list when the server reports no changes since the last fetch.

Source

pub async fn delete_contacts( &self, user_ids: &[i64], ) -> Result<(), InvocationError>

Remove one or more users from the contact list.

Source

pub async fn block_user( &self, peer: impl Into<PeerRef>, ) -> Result<(), InvocationError>

Block a user or peer so they can no longer send you messages.

Source

pub async fn unblock_user( &self, peer: impl Into<PeerRef>, ) -> Result<(), InvocationError>

Unblock a previously blocked user or peer.

Source

pub async fn set_online(&self) -> Result<(), InvocationError>

Appear online to other users.

Source

pub async fn set_offline(&self) -> Result<(), InvocationError>

Appear offline immediately.

Source

pub async fn terminate_session(&self, hash: i64) -> Result<(), InvocationError>

Terminate a specific session by its hash (obtained from [get_authorizations]).

Source§

impl Client

Source

pub fn builder() -> ClientBuilder

Return a fluent [ClientBuilder] for constructing and connecting a client.

§Example
let (client, _shutdown) = Client::builder()
.api_id(12345)
.api_hash("abc123")
.session("my.session")
.catch_up(true)
.connect().await?;
Source

pub async fn connect( config: Config, ) -> Result<(Self, ShutdownToken), InvocationError>

Source

pub async fn save_session(&self) -> Result<(), InvocationError>

Persist the current session to the configured [SessionBackend].

Source

pub async fn export_session_string(&self) -> Result<String, InvocationError>

Export the current session as a portable URL-safe base64 string.

The returned string encodes the auth key, DC, update state, and peer cache. Store it in an environment variable or secret manager and pass it back via Config::with_string_session to restore the session without re-authenticating.

Source

pub async fn media_dc_addr(&self, dc_id: i32) -> Option<String>

Return the media-only DC address for the given DC id, if known.

Media DCs (media_only = true in DcOption) are preferred for file uploads and downloads because they are not subject to the API rate limits applied to the main DC connection.

Source

pub async fn best_media_dc_addr(&self) -> Option<(i32, String)>

Return the best media DC address for the current home DC (falls back to any known media DC if no home-DC media entry exists).

Source

pub async fn is_authorized(&self) -> Result<bool, InvocationError>

Returns true if the client is already authorized.

Source

pub fn stream_updates(&self) -> UpdateStream

Return an UpdateStream that yields incoming [Update]s.

The reader task (started inside connect()) sends all updates to inner.update_tx. This method proxies those updates into a fresh caller-owned channel: typically called once per bot/app loop.

Source

pub fn signal_network_restored(&self)

Signal that network connectivity has been restored.

Call this from platform network-change callbacks: Android’s ConnectivityManager, iOS NWPathMonitor, or any other OS hook to make the client attempt an immediate reconnect instead of waiting for the exponential backoff timer to expire.

Safe to call at any time: if the connection is healthy the hint is silently ignored by the reader task; if it is in a backoff loop it wakes up and tries again right away.

Source

pub async fn send_message( &self, peer: impl Into<PeerRef>, msg: impl Into<InputMessage>, ) -> Result<IncomingMessage, InvocationError>

Source

pub async fn open_mini_app( &self, peer: impl Into<PeerRef>, app: MiniApp, ) -> Result<MiniAppSession, InvocationError>

Source

pub async fn send_to_self( &self, msg: impl Into<InputMessage>, ) -> Result<IncomingMessage, InvocationError>

Source

pub async fn edit_message( &self, peer: impl Into<PeerRef>, message_id: i32, new_text: impl Into<InputMessage>, ) -> Result<(), InvocationError>

Edit the text of an existing message.

Source

pub async fn forward_messages( &self, destination: impl Into<PeerRef>, message_ids: &[i32], source: impl Into<PeerRef>, opts: ForwardOptions, ) -> Result<Vec<IncomingMessage>, InvocationError>

Source

pub async fn delete_messages( &self, message_ids: &[i32], revoke: bool, ) -> Result<(), InvocationError>

Source

pub async fn get_message_by_id( &self, peer: impl Into<PeerRef>, id: i32, ) -> Result<Option<IncomingMessage>, InvocationError>

Fetch a single message by ID.

Source

pub async fn get_messages_by_id( &self, peer: impl Into<PeerRef>, ids: &[i32], ) -> Result<Vec<IncomingMessage>, InvocationError>

Source

pub async fn get_pinned_message( &self, peer: impl Into<PeerRef>, ) -> Result<Option<IncomingMessage>, InvocationError>

Source

pub async fn pin_message( &self, peer: impl Into<PeerRef>, message_id: i32, silent: bool, ) -> Result<(), InvocationError>

Source

pub async fn unpin_message( &self, peer: impl Into<PeerRef>, message_id: i32, ) -> Result<(), InvocationError>

Source

pub async fn unpin_all_messages( &self, peer: impl Into<PeerRef>, ) -> Result<(), InvocationError>

Source

pub async fn get_scheduled_messages( &self, peer: impl Into<PeerRef>, ) -> Result<Vec<IncomingMessage>, InvocationError>

Source

pub async fn delete_scheduled_messages( &self, peer: impl Into<PeerRef>, ids: &[i32], ) -> Result<(), InvocationError>

Source

pub async fn answer_callback_query( &self, query_id: i64, text: Option<&str>, alert: bool, ) -> Result<bool, InvocationError>

Source

pub async fn answer_inline_query( &self, query_id: i64, results: Vec<InputBotInlineResult>, cache_time: i32, is_personal: bool, next_offset: Option<String>, ) -> Result<bool, InvocationError>

Source

pub async fn get_dialogs_slice( &self, req: GetDialogs, ) -> Result<Vec<Dialog>, InvocationError>

Source

pub async fn get_dialogs_paginated( &self, req: GetDialogs, ) -> Result<(Vec<Dialog>, Option<i32>), InvocationError>

Source

pub async fn get_message_history( &self, peer: impl Into<PeerRef>, limit: i32, offset_id: i32, ) -> Result<Vec<IncomingMessage>, InvocationError>

Source

pub async fn download_file( &self, location: InputFileLocation, path: impl AsRef<Path>, ) -> Result<(), InvocationError>

Source

pub async fn download_file_to_path( &self, location: InputFileLocation, dc_id: i32, path: impl AsRef<Path>, ) -> Result<(), InvocationError>

Source

pub async fn send_chat_action( &self, peer: impl Into<PeerRef>, action: SendMessageAction, ) -> Result<(), InvocationError>

Source

pub async fn get_history_range( &self, peer: impl Into<PeerRef>, limit: i32, offset_id: i32, ) -> Result<Vec<IncomingMessage>, InvocationError>

Source

pub async fn resolve<P: Into<PeerRef>>( &self, peer: P, ) -> Result<Peer, InvocationError>

Resolve any peer reference to a tl::enums::Peer.

Accepts everything PeerRef accepts:

  • &str / String: "@username", "me", "self", numeric string, t.me/ URL, invite link, E.164 phone
  • i64 / i32: Bot-API encoded numeric ID
  • tl::enums::Peer: returned as-is (zero cost)
  • tl::enums::InputPeer: hash cached, then stripped to Peer

Resolution is cache-first; an RPC is only made on a genuine cache miss.

Source

pub async fn resolve_peer(&self, peer: &str) -> Result<Peer, InvocationError>

Resolve a peer string to a tl::enums::Peer.

Accepts: "me", "self", "@username", "username", numeric strings (Bot-API encoded), t.me/ URLs, E.164 phones (+digits), and invite links. Cache-first for usernames and phones; RPC only on miss.

Prefer Client::resolve when the input may not be a string.

Source

pub async fn join_by_invite( &self, link: &str, ) -> Result<InputPeer, InvocationError>

Join a chat by invite link and return its InputPeer.

Calls messages.importChatInvite, caches all returned entities, and returns the InputPeer of the joined chat.

Source

pub async fn check_invite( &self, link: &str, ) -> Result<ChatInvite, InvocationError>

Peek at an invite link without joining.

Returns the title and participant count of the chat the link points to.

Source

pub async fn invoke<R: RemoteCall>( &self, req: &R, ) -> Result<R::Return, InvocationError>

Source

pub fn disconnect(&self)

Gracefully shut down the client.

Signals the reader task to exit cleanly. Same as cancelling the ShutdownToken returned from Client::connect.

In-flight RPCs will receive a Dropped error. Call save_session() before this if you want to persist the current auth state.

Source

pub async fn warm_peer_cache_from_dialogs(&self) -> Result<(), InvocationError>

Warm the peer cache with access_hashes by fetching the first page of dialogs (messages.getDialogs).

§When to use

This is an explicit, opt-in cache-warming call. It is not called automatically during startup. Access hashes are resolved lazily:

  • Channels already seen in a previous session have their hash restored from the persisted peers list in the session file.
  • New channels receive their hash from the entities embedded in incoming updates, getDifference, or getChannelDifference responses.

Call this only when you know that a channel the client needs to interact with has never appeared in an update (e.g. the very first send_message to a channel before any update has been received).

§Why it is not called at startup

messages.getDialogs forces full deserialization of Dialog / DraftMessage / PollResults / PeerNotifySettings / Story. These are high-churn Telegram objects that change silently across beta layers, causing spurious parse failures that break startup even when the bot would otherwise work perfectly. Removing this from the startup path makes Ferogram resilient to Telegram schema drift - exactly the strategy

Source

pub async fn resolve_to_input_peer( &self, peer: &Peer, ) -> Result<InputPeer, InvocationError>

Try to resolve a peer to InputPeer, returning an error if the access_hash is unknown (i.e. the peer has not been seen in any prior API call).

Source

pub async fn invoke_on_dc<R: RemoteCall>( &self, dc_id: i32, req: &R, ) -> Result<R::Return, InvocationError>

Invoke a request on a specific DC, using the pool.

If the target DC has no auth key yet, one is acquired via DH and then authorized via auth.exportAuthorization / auth.importAuthorization so the worker DC can serve user-account requests too.

Source

pub async fn answer_precheckout_query( &self, query_id: i64, ok: bool, error_message: Option<String>, ) -> Result<(), InvocationError>

Source

pub async fn answer_shipping_query( &self, query_id: i64, error: Option<String>, shipping_options: Option<Vec<ShippingOption>>, ) -> Result<(), InvocationError>

Source

pub async fn start_bot( &self, bot_user_id: i64, peer: impl Into<PeerRef>, start_param: impl Into<String>, ) -> Result<(), InvocationError>

Source

pub async fn set_game_score( &self, peer: impl Into<PeerRef>, msg_id: i32, user_id: i64, score: i32, force: bool, edit_message: bool, ) -> Result<(), InvocationError>

Source

pub async fn get_game_high_scores( &self, peer: impl Into<PeerRef>, msg_id: i32, user_id: i64, ) -> Result<Vec<HighScore>, InvocationError>

Source

pub async fn edit_inline_message( &self, id: InputBotInlineMessageId, new_text: &str, reply_markup: Option<ReplyMarkup>, ) -> Result<bool, InvocationError>

Source

pub async fn send_dice( &self, peer: impl Into<PeerRef>, emoticon: impl Into<String>, ) -> Result<(), InvocationError>

Source

pub async fn send_poll( &self, peer: impl Into<PeerRef>, question: impl Into<String>, answers: &[impl AsRef<str>], quiz: bool, correct_index: Option<usize>, multiple_choice: bool, ) -> Result<(), InvocationError>

Source

pub async fn set_bot_commands( &self, commands: &[(&str, &str)], scope: Option<BotCommandScope>, lang_code: &str, ) -> Result<bool, InvocationError>

Source

pub async fn delete_bot_commands( &self, scope: Option<BotCommandScope>, lang_code: &str, ) -> Result<bool, InvocationError>

Source

pub async fn set_bot_info( &self, name: Option<&str>, about: Option<&str>, description: Option<&str>, lang_code: &str, ) -> Result<bool, InvocationError>

Source

pub async fn get_bot_info( &self, lang_code: &str, ) -> Result<BotInfo, InvocationError>

Source

pub async fn send_invoice( &self, peer: impl Into<PeerRef>, title: impl Into<String>, description: impl Into<String>, payload: impl Into<String>, options: InvoiceOptions, ) -> Result<IncomingMessage, InvocationError>

Source

pub async fn get_chat_full( &self, peer: impl Into<PeerRef>, ) -> Result<ChatFull, InvocationError>

Source

pub async fn delete_chat_history( &self, peer: impl Into<PeerRef>, max_id: i32, revoke: bool, ) -> Result<(), InvocationError>

Source

pub async fn save_draft( &self, peer: impl Into<PeerRef>, text: impl Into<String>, ) -> Result<(), InvocationError>

Source

pub async fn get_pinned_dialogs( &self, folder_id: i32, ) -> Result<Vec<Dialog>, InvocationError>

Source

pub async fn mark_dialog_unread( &self, peer: impl Into<PeerRef>, ) -> Result<(), InvocationError>

Source

pub async fn download_media_to_file( &self, location: InputFileLocation, path: impl AsRef<Path>, ) -> Result<(), InvocationError>

Source

pub async fn upload_media( &self, peer: impl Into<PeerRef>, media: InputMedia, ) -> Result<MessageMedia, InvocationError>

Source

pub async fn get_media_group( &self, peer: impl Into<PeerRef>, msg_id: i32, ) -> Result<Vec<IncomingMessage>, InvocationError>

Source

pub async fn create_group( &self, title: impl Into<String>, user_ids: Vec<i64>, ) -> Result<Chat, InvocationError>

Source

pub async fn create_channel( &self, title: impl Into<String>, about: impl Into<String>, broadcast: bool, ) -> Result<Chat, InvocationError>

Source

pub async fn edit_chat_title( &self, peer: impl Into<PeerRef>, title: impl Into<String>, ) -> Result<(), InvocationError>

Source

pub async fn edit_chat_about( &self, peer: impl Into<PeerRef>, about: impl Into<String>, ) -> Result<(), InvocationError>

Source

pub async fn edit_chat_photo( &self, peer: impl Into<PeerRef>, photo: InputChatPhoto, ) -> Result<(), InvocationError>

Source

pub async fn edit_chat_default_banned_rights( &self, peer: impl Into<PeerRef>, build: impl FnOnce(BannedRightsBuilder) -> BannedRightsBuilder, ) -> Result<(), InvocationError>

Source

pub async fn upload_profile_photo( &self, file: UploadedFile, ) -> Result<Photo, InvocationError>

Source

pub async fn invite_users( &self, peer: impl Into<PeerRef>, user_ids: &[i64], ) -> Result<(), InvocationError>

Source

pub async fn set_history_ttl( &self, peer: impl Into<PeerRef>, period: i32, ) -> Result<(), InvocationError>

Source

pub async fn get_common_chats( &self, user_id: i64, max_id: i64, limit: i32, ) -> Result<Vec<Chat>, InvocationError>

Source

pub async fn join_request( &self, peer: impl Into<PeerRef>, user_id: i64, approve: bool, ) -> Result<(), InvocationError>

Source

pub async fn all_join_requests( &self, peer: impl Into<PeerRef>, approve: bool, link: Option<String>, ) -> Result<(), InvocationError>

Source

pub async fn get_admins_with_invites( &self, peer: impl Into<PeerRef>, ) -> Result<ChatAdminsWithInvites, InvocationError>

Source

pub async fn get_chat_administrators( &self, peer: impl Into<PeerRef>, ) -> Result<Vec<Participant>, InvocationError>

Source

pub async fn get_forum_topics( &self, peer: impl Into<PeerRef>, query: Option<String>, limit: i32, offset_date: i32, offset_id: i32, offset_topic: i32, ) -> Result<Vec<ForumTopic>, InvocationError>

Source

pub async fn get_forum_topics_by_id( &self, peer: impl Into<PeerRef>, topic_ids: Vec<i32>, ) -> Result<Vec<ForumTopic>, InvocationError>

Source

pub async fn create_forum_topic( &self, peer: impl Into<PeerRef>, title: impl Into<String>, icon_color: Option<i32>, icon_emoji_id: Option<i64>, ) -> Result<(), InvocationError>

Source

pub async fn edit_forum_topic( &self, peer: impl Into<PeerRef>, topic_id: i32, title: Option<String>, icon_emoji_id: Option<i64>, closed: Option<bool>, hidden: Option<bool>, ) -> Result<(), InvocationError>

Source

pub async fn delete_forum_topic_history( &self, peer: impl Into<PeerRef>, top_msg_id: i32, ) -> Result<(), InvocationError>

Source

pub async fn toggle_forum( &self, peer: impl Into<PeerRef>, enabled: bool, ) -> Result<(), InvocationError>

Source

pub async fn transfer_chat_ownership( &self, peer: impl Into<PeerRef>, new_owner_id: i64, password: InputCheckPasswordSrp, ) -> Result<(), InvocationError>

Source

pub async fn get_linked_channel( &self, peer: impl Into<PeerRef>, ) -> Result<Option<i64>, InvocationError>

Source

pub async fn add_contact( &self, user_id: i64, first_name: impl Into<String>, last_name: impl Into<String>, phone: impl Into<String>, add_phone_privacy_exception: bool, ) -> Result<(), InvocationError>

Source

pub async fn import_contacts( &self, contacts: &[(&str, &str, &str)], ) -> Result<ImportedContacts, InvocationError>

Source

pub async fn get_blocked_users( &self, offset: i32, limit: i32, ) -> Result<Vec<Peer>, InvocationError>

Source

pub async fn search_contacts( &self, query: impl Into<String>, limit: i32, ) -> Result<Vec<Peer>, InvocationError>

Source

pub async fn set_profile_photo( &self, file: UploadedFile, ) -> Result<Photo, InvocationError>

Source

pub async fn delete_profile_photos( &self, photo_ids: Vec<(i64, i64, Vec<u8>)>, ) -> Result<Vec<i64>, InvocationError>

Source

pub async fn set_profile( &self, first_name: Option<String>, last_name: Option<String>, about: Option<String>, ) -> Result<User, InvocationError>

Source

pub async fn set_username( &self, username: impl Into<String>, ) -> Result<User, InvocationError>

Source

pub async fn get_authorizations( &self, ) -> Result<Vec<Authorization>, InvocationError>

Source

pub async fn get_user_full( &self, user_id: i64, ) -> Result<UserFull, InvocationError>

Source

pub async fn set_emoji_status( &self, document_id: Option<i64>, until: Option<i32>, ) -> Result<(), InvocationError>

Source

pub async fn get_broadcast_stats( &self, peer: impl Into<PeerRef>, ) -> Result<BroadcastStats, InvocationError>

Source

pub async fn get_megagroup_stats( &self, peer: impl Into<PeerRef>, ) -> Result<MegagroupStats, InvocationError>

Source

pub async fn send_scheduled_now( &self, peer: impl Into<PeerRef>, ids: &[i32], ) -> Result<(), InvocationError>

Source

pub async fn get_message_read_participants( &self, peer: impl Into<PeerRef>, msg_id: i32, ) -> Result<Vec<ReadParticipantDate>, InvocationError>

Source

pub async fn get_replies( &self, peer: impl Into<PeerRef>, msg_id: i32, limit: i32, offset_id: i32, ) -> Result<Vec<IncomingMessage>, InvocationError>

Source

pub async fn get_discussion_message( &self, peer: impl Into<PeerRef>, msg_id: i32, ) -> Result<DiscussionMessage, InvocationError>

Source

pub async fn read_discussion( &self, peer: impl Into<PeerRef>, msg_id: i32, read_max_id: i32, ) -> Result<(), InvocationError>

Source

pub async fn get_web_page_preview( &self, text: impl Into<String>, ) -> Result<MessageMedia, InvocationError>

Source

pub async fn get_reactions( &self, peer: impl Into<PeerRef>, msg_ids: Vec<i32>, ) -> Result<(), InvocationError>

Source

pub async fn iter_reaction_users( &self, peer: impl Into<PeerRef>, msg_id: i32, reaction: Option<Reaction>, limit: i32, offset: Option<String>, ) -> Result<MessageReactionsList, InvocationError>

Source

pub async fn send_paid_reaction( &self, peer: impl Into<PeerRef>, msg_id: i32, count: i32, ) -> Result<(), InvocationError>

Source

pub async fn translate_messages( &self, peer: impl Into<PeerRef>, msg_ids: Vec<i32>, to_lang: impl Into<String>, ) -> Result<Vec<TextWithEntities>, InvocationError>

Source

pub async fn transcribe_audio( &self, peer: impl Into<PeerRef>, msg_id: i32, ) -> Result<TranscribedAudio, InvocationError>

Source

pub async fn toggle_peer_translations( &self, peer: impl Into<PeerRef>, disabled: bool, ) -> Result<(), InvocationError>

Source

pub async fn get_admin_log( &self, peer: impl Into<PeerRef>, query: impl Into<String>, limit: i32, max_id: i64, min_id: i64, ) -> Result<Vec<ChannelAdminLogEvent>, InvocationError>

Source

pub async fn toggle_no_forwards( &self, peer: impl Into<PeerRef>, enabled: bool, ) -> Result<(), InvocationError>

Source

pub async fn set_chat_theme( &self, peer: impl Into<PeerRef>, emoticon: impl Into<String>, ) -> Result<(), InvocationError>

Source

pub async fn set_chat_reactions( &self, peer: impl Into<PeerRef>, reactions: ChatReactions, ) -> Result<(), InvocationError>

Source

pub async fn get_send_as_peers( &self, peer: impl Into<PeerRef>, ) -> Result<Vec<Peer>, InvocationError>

Source

pub async fn set_default_send_as( &self, peer: impl Into<PeerRef>, send_as_peer: impl Into<PeerRef>, ) -> Result<(), InvocationError>

Source

pub async fn send_vote( &self, peer: impl Into<PeerRef>, msg_id: i32, options: Vec<Vec<u8>>, ) -> Result<(), InvocationError>

Source

pub async fn get_poll_results( &self, peer: impl Into<PeerRef>, msg_id: i32, poll_hash: i64, ) -> Result<(), InvocationError>

Source

pub async fn get_poll_votes( &self, peer: impl Into<PeerRef>, msg_id: i32, option: Option<Vec<u8>>, limit: i32, offset: Option<String>, ) -> Result<VotesList, InvocationError>

Source

pub async fn get_sticker_set( &self, stickerset: InputStickerSet, ) -> Result<StickerSet, InvocationError>

Source

pub async fn install_sticker_set( &self, stickerset: InputStickerSet, archived: bool, ) -> Result<StickerSetInstallResult, InvocationError>

Source

pub async fn uninstall_sticker_set( &self, stickerset: InputStickerSet, ) -> Result<(), InvocationError>

Source

pub async fn get_all_stickers( &self, hash: i64, ) -> Result<Option<Vec<StickerSet>>, InvocationError>

Source

pub async fn get_custom_emoji_documents( &self, document_ids: Vec<i64>, ) -> Result<Vec<Document>, InvocationError>

Source

pub async fn get_privacy( &self, key: InputPrivacyKey, ) -> Result<Vec<PrivacyRule>, InvocationError>

Source

pub async fn set_privacy( &self, key: InputPrivacyKey, rules: Vec<InputPrivacyRule>, ) -> Result<Vec<PrivacyRule>, InvocationError>

Source

pub async fn get_notify_settings( &self, peer: impl Into<PeerRef>, ) -> Result<PeerNotifySettings, InvocationError>

Source

pub async fn update_notify_settings( &self, peer: impl Into<PeerRef>, settings: InputPeerNotifySettings, ) -> Result<(), InvocationError>

Source§

impl Client

Source

pub async fn upload_file( &self, data: &[u8], name: &str, mime_type: &str, ) -> Result<UploadedFile, InvocationError>

Upload bytes sequentially (single session).

Part size and big-file threshold:

  • Part size chosen by upload_part_size: < 1 MB → 32 KB, 1–32 MB → 64 KB, 32–512 MB → 128 KB, etc.
  • upload.saveBigFilePart used for files > 30 MB (kUseBigFilesFrom).

For files that benefit from parallelism use [upload_file_concurrent].

Source

pub async fn upload_file_concurrent( &self, data: Arc<Vec<u8>>, name: &str, mime_type: &str, ) -> Result<UploadedFile, InvocationError>

Upload bytes with parallel worker sessions.

Parallel upload using per-worker connections. Worker count scales with file size. Part size: 32 KB for tiny files, 512 KB otherwise.

  • Files < 10 MB -> upload.saveFilePart (small-file API)
  • Files >= 10 MB -> upload.saveBigFilePart (big-file API)
Source

pub async fn upload_stream<R: AsyncRead + Unpin>( &self, reader: &mut R, name: &str, mime_type: &str, ) -> Result<UploadedFile, InvocationError>

Upload from an AsyncRead. Reads fully into memory then uploads.

Source

pub async fn send_file( &self, peer: impl Into<PeerRef>, media: InputMedia, msg: &InputMessage, ) -> Result<IncomingMessage, InvocationError>

Send a file as a document or photo to a chat.

Source

pub async fn send_album( &self, peer: impl Into<PeerRef>, items: Vec<AlbumItem>, ) -> Result<Vec<IncomingMessage>, InvocationError>

Send multiple files as an album.

Each AlbumItem carries its own media, caption, entities (formatting), and optional reply_to message ID.

use ferogram::media::AlbumItem;

let msgs = client.send_album(peer.clone(), vec![
    AlbumItem::new(photo_media).caption_html("<b>First photo</b>"),
    AlbumItem::new(video_media).caption("Second item").reply_to(Some(42)),
]).await?;

// Shorthand: legacy tuple API still works via From impl
client.send_album(peer, vec![
    (photo_media2, "caption".to_string()).into(),
]).await?;
Source

pub fn iter_download(&self, location: InputFileLocation) -> DownloadIter

Create a sequential chunk download iterator.

dc_id must be the DC that stores the file (Document::dc_id() / Photo::dc_id()). Pass 0 to use the home DC (bots only).

Source

pub fn iter_download_on_dc( &self, location: InputFileLocation, dc_id: i32, ) -> DownloadIter

Like [iter_download] but routes to a specific DC.

Source

pub async fn download_media( &self, location: InputFileLocation, ) -> Result<Vec<u8>, InvocationError>

Download all bytes of a media attachment at once (sequential).

Source

pub async fn download_media_on_dc( &self, location: InputFileLocation, dc_id: i32, ) -> Result<Vec<u8>, InvocationError>

Like [download_media] but routes GetFile to dc_id.

Opens a dedicated DcConnection for this download so it never shares the idle transfer-pool connection (which the server silently closes after ~90 s of inactivity, causing early-eof on the next use).

Full AUTH_KEY_UNREGISTERED + FILE_MIGRATE recovery, the resilience of the concurrent worker path.

Source

pub async fn download_media_concurrent( &self, location: InputFileLocation, size: usize, ) -> Result<Vec<u8>, InvocationError>

Download a file using parallel sessions.

size must be the exact byte size of the file.

Returns the full file bytes in order.

Source

pub async fn download_media_concurrent_on_dc( &self, location: InputFileLocation, size: usize, dc_id: i32, ) -> Result<Vec<u8>, InvocationError>

Like [download_media_concurrent] but routes GetFile to dc_id.

Parallel download using per-worker connections. Worker count scales with file size.

Source

pub async fn download<D: Downloadable>( &self, item: &D, ) -> Result<Vec<u8>, InvocationError>

Download any Downloadable item.

Uses concurrent mode for files > 30 MB (kUseBigFilesFrom), sequential for smaller files.

Source§

impl Client

Source

pub async fn get_participants( &self, peer: impl Into<PeerRef>, limit: i32, ) -> Result<Vec<Participant>, InvocationError>

Fetch all participants of a chat, group or channel.

For channels this uses channels.getParticipants; for basic groups it uses messages.getFullChat.

Returns up to limit participants; pass 0 for the default (200 for channels).

Source

pub async fn kick_participant( &self, peer: impl Into<PeerRef>, user_id: i64, ) -> Result<(), InvocationError>

Kick a user from a group chat or channel.

For basic groups, this removes the user immediately. For channels and supergroups, it bans then unbans them (a Telegram kick).

Source

pub async fn ban_participant( &self, channel: impl Into<PeerRef>, user_id: i64, ) -> Result<(), InvocationError>

Permanently ban a user from a channel or supergroup.

Source

pub async fn ban_participant_until( &self, channel: impl Into<PeerRef>, user_id: i64, until_ts: i32, ) -> Result<(), InvocationError>

Ban a user from a channel or supergroup until until_ts (Unix timestamp).

Use [ban_participant] for a permanent ban.

Source

pub async fn promote_participant( &self, channel: impl Into<PeerRef>, user_id: i64, ) -> Result<(), InvocationError>

Promote a user to admin in a channel or supergroup with default admin rights.

Source

pub async fn demote_participant( &self, channel: impl Into<PeerRef>, user_id: i64, ) -> Result<(), InvocationError>

Remove admin rights from a user in a channel or supergroup.

Source

pub async fn get_profile_photos( &self, peer: impl Into<PeerRef>, limit: i32, ) -> Result<Vec<Photo>, InvocationError>

Iterate profile photos of a user or channel.

Returns a list of photo objects (up to limit).

Source

pub async fn iter_profile_photos( &self, peer: impl Into<PeerRef>, chunk_size: i32, ) -> Result<ProfilePhotoIter, InvocationError>

Stream profile photos of a user lazily, one page at a time.

Returns a ProfilePhotoIter that fetches photos in pages of chunk_size and exposes them one-by-one via .next().await. Set chunk_size to 0 to use the default (100).

Only works for users: channels use messages.search with a photo filter instead.

§Example
let mut iter = client.iter_profile_photos(peer, 0).await?;
while let Some(photo) = iter.next().await? {
println!("{photo:?}");
}
Source

pub async fn search_peer( &self, query: &str, ) -> Result<Vec<Peer>, InvocationError>

Search for a peer (user, group, or channel) by name prefix.

Searches contacts, dialogs, and globally. Returns combined results.

Source§

impl Client

Source

pub async fn set_banned_rights( &self, channel: impl Into<PeerRef>, user_id: i64, build: impl FnOnce(BannedRightsBuilder) -> BannedRightsBuilder, ) -> Result<(), InvocationError>

Apply granular ban rights to a user in a channel or supergroup.

Use BannedRightsBuilder to specify which rights to restrict.

Source

pub async fn set_admin_rights( &self, channel: impl Into<PeerRef>, user_id: i64, build: impl FnOnce(AdminRightsBuilder) -> AdminRightsBuilder, ) -> Result<(), InvocationError>

Apply granular admin rights to a user in a channel or supergroup.

Use AdminRightsBuilder to specify which rights to grant.

Source

pub async fn get_participants_filtered( &self, peer: impl Into<PeerRef>, filter: Option<ChannelParticipantsFilter>, limit: i32, ) -> Result<Vec<Participant>, InvocationError>

Fetch participants with an optional filter, paginated.

filter defaults to ChannelParticipantsRecent when None.

Source

pub async fn get_permissions( &self, channel: impl Into<PeerRef>, user_id: i64, ) -> Result<ParticipantPermissions, InvocationError>

Get the effective permissions of a specific user in a channel.

Source§

impl Client

Source

pub fn iter_inline_queries(&self) -> InlineQueryIter

Return an iterator that yields every incoming inline query (bot side).

The internal channel is bounded to [INLINE_QUERY_CHANNEL_CAP] entries. If the consumer stops calling InlineQueryIter::next and the backlog fills, the feed task exits and the stream ends rather than growing memory without bound.

Source

pub async fn inline_query( &self, bot: Peer, query: &str, ) -> Result<InlineResultIter, InvocationError>

Query a bot’s inline mode and return a paginated InlineResultIter.

Equivalent to typing @bot_username query in a Telegram app.

§Example
let mut iter = client.inline_query(bot, "hello").await?;
while let Some(r) = iter.next().await? {
println!("{}", r.title().unwrap_or("(no title)"));
}
Source§

impl Client

Source

pub async fn typing( &self, peer: impl Into<PeerRef>, ) -> Result<TypingGuard, InvocationError>

Start a scoped typing indicator that auto-cancels when dropped.

A convenience wrapper around TypingGuard::start.

Source

pub async fn typing_in_topic( &self, peer: impl Into<PeerRef>, topic_id: i32, ) -> Result<TypingGuard, InvocationError>

Start a scoped typing indicator in a forum topic thread.

topic_id is the top_msg_id of the forum topic.

Source

pub async fn uploading_document( &self, peer: impl Into<PeerRef>, ) -> Result<TypingGuard, InvocationError>

Start a scoped “uploading document” action that auto-cancels when dropped.

Source

pub async fn recording_video( &self, peer: impl Into<PeerRef>, ) -> Result<TypingGuard, InvocationError>

Start a scoped “recording video” action that auto-cancels when dropped.

Trait Implementations§

Source§

impl Clone for Client

Source§

fn clone(&self) -> Client

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more