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 upload_file( &self, data: &[u8], name: &str, mime_type: &str, ) -> Result<UploadedFile, InvocationError>

Upload bytes sequentially. For big files (≥ 10 MB) prefer [upload_file_concurrent] which uses parallel workers.

Source

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

G-41 — Upload bytes using WORKER_COUNT (4) parallel workers.

Only beneficial for big files (≥ 10 MB). Falls through to sequential for small files automatically.

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: Peer, media: InputMedia, caption: &str, ) -> Result<(), InvocationError>

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

Source

pub async fn send_album( &self, peer: Peer, items: Vec<(InputMedia, String)>, ) -> Result<(), InvocationError>

Send multiple files as an album.

Source

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

Create a sequential chunk download iterator.

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_concurrent( &self, location: InputFileLocation, size: usize, ) -> Result<Vec<u8>, InvocationError>

G-42 — Download a file using WORKER_COUNT (4) parallel workers.

size must be the exact byte size of the file (obtained from the Downloadable::size accessor, or from the document’s size field).

Returns the full file bytes in order.

Source

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

Download any Downloadable item, automatically choosing concurrent mode for files ≥ 10 MB (G-42 / G-44 integration).

Source§

impl Client

Source

pub async fn get_participants( &self, peer: Peer, 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, chat_id: i64, user_id: i64, ) -> Result<(), InvocationError>

Kick a user from a basic group (chat). For channels, use [ban_participant].

Source

pub async fn ban_participant( &self, channel: Peer, user_id: i64, until_date: i32, ) -> Result<(), InvocationError>

Ban a user from a channel or supergroup.

Pass until_date = 0 for a permanent ban.

Source

pub async fn promote_participant( &self, channel: Peer, user_id: i64, promote: bool, ) -> Result<(), InvocationError>

Promote (or demote) a user to admin in a channel or supergroup.

Pass promote = true to grant admin rights, false to remove them.

Source

pub async fn get_profile_photos( &self, peer: Peer, 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 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

pub async fn send_reaction( &self, peer: Peer, message_id: i32, reaction: &str, ) -> Result<(), InvocationError>

Send a reaction to a message.

reaction should be an emoji string like "👍" or an empty string to remove.

Source§

impl Client

Source

pub async fn set_banned_rights( &self, channel: Peer, 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: Peer, 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 iter_participants( &self, peer: Peer, 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: Peer, user_id: i64, ) -> Result<ParticipantPermissions, InvocationError>

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

Source§

impl Client

Source

pub async fn get_difference(&self) -> Result<Vec<Update>, InvocationError>

Fetch and replay any updates missed since the persisted pts.

Source

pub async fn get_channel_difference( &self, channel_id: i64, ) -> Result<Vec<Update>, InvocationError>

Fetch missed updates for a single channel.

Source

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

Source

pub async fn check_and_fill_gap( &self, new_pts: i32, pts_count: i32, upd: Option<Update>, ) -> Result<Vec<Update>, InvocationError>

G-17: Check global pts, buffer during possible-gap window, fetch diff if real gap.

Source

pub async fn check_and_fill_qts_gap( &self, new_qts: i32, qts_count: i32, ) -> Result<Vec<Update>, InvocationError>

G-18: Check qts (secret chat updates) and fill gap if needed.

Source

pub async fn check_and_fill_seq_gap( &self, new_seq: i32, seq_start: i32, ) -> Result<Vec<Update>, InvocationError>

G-19: Check top-level seq and fill gap if needed.

Source

pub async fn check_and_fill_channel_gap( &self, channel_id: i64, new_pts: i32, pts_count: i32, upd: Option<Update>, ) -> Result<Vec<Update>, InvocationError>

G-15: Check a per-channel pts, fetch getChannelDifference if there is a gap.

Source

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

G-16: Called periodically (e.g. from keepalive) to fire getDifference if no update has been received for > 15 minutes.

Source§

impl Client

Source

pub fn iter_inline_queries(&self) -> InlineQueryIter

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

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 (G-25).

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: Peer) -> Result<TypingGuard, InvocationError>

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

This is a convenience wrapper around TypingGuard::start.

Source

pub async fn typing_in_topic( &self, peer: Peer, 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: Peer, ) -> Result<TypingGuard, InvocationError>

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

Source

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

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

Source§

impl Client

Source

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

Source

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

Source

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

Returns true if the client is already authorized.

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_me(&self) -> Result<User, InvocationError>

Fetch information about the logged-in user.

Source

pub fn stream_updates(&self) -> UpdateStream

Return an UpdateStream that yields incoming Updates.

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: &str, text: &str, ) -> Result<(), InvocationError>

Send a text message. Use "me" for Saved Messages.

Source

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

Send a message to an already-resolved peer (plain text shorthand).

Source

pub async fn send_message_to_peer_ex( &self, peer: Peer, msg: &InputMessage, ) -> Result<(), InvocationError>

Send a message with full InputMessage options.

Source

pub async fn send_to_self(&self, text: &str) -> Result<(), InvocationError>

Send directly to Saved Messages.

Source

pub async fn edit_message( &self, peer: Peer, message_id: i32, new_text: &str, ) -> Result<(), InvocationError>

Edit an existing message.

Source

pub async fn forward_messages( &self, destination: Peer, message_ids: &[i32], source: Peer, ) -> Result<(), InvocationError>

Forward messages from source to destination.

Source

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

Delete messages by ID.

Source

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

Get messages by their IDs from a peer.

Source

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

Get the pinned message in a chat.

Source

pub async fn pin_message( &self, peer: Peer, message_id: i32, silent: bool, unpin: bool, pm_oneside: bool, ) -> Result<(), InvocationError>

Pin a message in a chat.

Source

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

Unpin a specific message.

Source

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

Unpin all messages in a chat.

Source

pub async fn search_messages( &self, peer: Peer, query: &str, limit: i32, ) -> Result<Vec<IncomingMessage>, InvocationError>

Search messages in a chat (simple form). For advanced filtering use Client::searchSearchBuilder.

Source

pub fn search(&self, peer: Peer, query: &str) -> SearchBuilder

G-31: Fluent search builder for in-chat message search.

Source

pub async fn search_global( &self, query: &str, limit: i32, ) -> Result<Vec<IncomingMessage>, InvocationError>

Search globally (simple form). For filtering use Client::search_global_builder.

Source

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

G-32: Fluent builder for global cross-chat search.

Source

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

Retrieve all scheduled messages in a chat.

Scheduled messages are messages set to be sent at a future time using InputMessage::schedule_date. Returns them newest-first.

§Example
let scheduled = client.get_scheduled_messages(peer).await?;
for msg in &scheduled {
    println!("Scheduled: {:?} at {:?}", msg.text(), msg.date());
}
Source

pub async fn delete_scheduled_messages( &self, peer: Peer, ids: Vec<i32>, ) -> Result<(), InvocationError>

Delete one or more scheduled messages by their IDs.

Source

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

G-24: Edit an inline message by its [InputBotInlineMessageId].

Inline messages live on the bot’s home DC, not necessarily the current connection’s DC. This method sends the edit RPC on the correct DC by using the DC ID encoded in msg_id (high 20 bits of the dc_id field).

§Example
client.edit_inline_message(id, "new text", None).await?;
Source

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

Answer a callback query from an inline keyboard button press (bots only).

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( &self, limit: i32, ) -> Result<Vec<Dialog>, InvocationError>

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

Source

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

Download all bytes of a media attachment and save them to path.

§Example
if let Some(loc) = msg.download_location() {
    client.download_media_to_file(loc, "/tmp/file.jpg").await?;
}
Source

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

Source

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

Mark all messages in a chat as read.

Source

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

Clear unread mention markers.

Source

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

Send a chat action (typing indicator, uploading photo, etc).

For “typing” use tl::enums::SendMessageAction::Typing. For forum topic support use send_chat_action_ex or the typing_in_topic helper.

Source

pub async fn join_chat(&self, peer: Peer) -> 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 async fn get_messages( &self, peer: InputPeer, limit: i32, offset_id: i32, ) -> Result<Vec<IncomingMessage>, InvocationError>

Fetch a page of messages from a peer’s history.

Source

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

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

Source

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

Resolve a Telegram username to a tl::enums::Peer and cache the access hash.

Also accepts usernames without the leading @.

Source

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

Invoke any TL function directly, handling flood-wait retries.

Source

pub fn disconnect(&self)

Gracefully shut down the client.

Signals the reader task to exit cleanly. Equivalent to 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 sync_update_state(&self)

Sync the internal pts/qts/seq/date state with the Telegram server.

This is called automatically on connect(). Call it manually if you need to reset the update gap-detection counters, e.g. after resuming from a long hibernation.

Source

pub fn iter_dialogs(&self) -> DialogIter

Fetch dialogs page by page.

Returns a DialogIter that can be advanced with DialogIter::next. This 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: Peer) -> 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 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.

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, 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> 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.