Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Client Methods — Full Reference

All methods on Client. Every method is async and returns Result<T, InvocationError> unless noted.


Connection & Session

async Client::connect(config: Config) → Result<(Client, ShutdownToken), InvocationError>
Opens a TCP connection to Telegram, performs the full 3-step DH key exchange, and loads any existing session. Returns both the client handle and a ShutdownToken for graceful shutdown.
sync Client::with_string_session(session: &str, api_id: i32, api_hash: &str) → Result<(Client, ShutdownToken), InvocationError> New 0.4.5
Convenience constructor that connects using a StringSessionBackend. Pass the string exported by export_session_string().
async client.is_authorized() → Result<bool, InvocationError>
Returns true if the session has a logged-in user or bot. Use this to skip the login flow on subsequent runs.
async client.save_session() → Result<(), InvocationError>
Writes the current session (auth key + DC info + peer cache) to the backend. Call after a successful login.
async client.export_session_string() → Result<String, InvocationError> New 0.4.5
Serialises the current session to a portable base64 string. Store it in an env var, DB column, or CI secret. Restore with Client::with_string_session() or StringSessionBackend.
let s = client.export_session_string().await?;
std::env::set_var("TG_SESSION", &s);
async client.sign_out() → Result<bool, InvocationError>
Revokes the auth key on Telegram's servers and deletes the local session. The bool indicates whether teardown was confirmed server-side.
sync client.disconnect()
Immediately closes the TCP connection and stops the reader task without waiting for pending RPCs to drain. For graceful shutdown that waits for pending calls, use ShutdownToken::cancel() instead.
async client.sync_update_state() New 0.4.5
Forces an immediate updates.getState round-trip and reconciles local pts/seq/qts counters. Useful after a long disconnect or when you suspect a gap but don't want to wait for the gap-detection timer.
sync client.signal_network_restored()
Signals to the reconnect logic that the network is available. Skips the exponential backoff and triggers an immediate reconnect attempt. Call from Android ConnectivityManager or iOS NWPathMonitor callbacks.

Authentication

async client.request_login_code(phone: &str) → Result<LoginToken, InvocationError>
Sends a verification code to phone via SMS or Telegram app. Returns a LoginToken to pass to sign_in. Phone must be in E.164 format: "+12345678900".
async client.sign_in(token: &LoginToken, code: &str) → Result<String, SignInError>
Submits the verification code. Returns the user's full name on success, or SignInError::PasswordRequired(PasswordToken) when 2FA is enabled. The PasswordToken carries the hint set by the user.
async client.check_password(token: PasswordToken, password: &str) → Result<(), InvocationError>
Completes the SRP 2FA verification. The password is never transmitted in plain text — only a zero-knowledge cryptographic proof is sent.
async client.bot_sign_in(token: &str) → Result<String, InvocationError>
Logs in using a bot token from @BotFather. Returns the bot's username on success.
async client.get_me() → Result<tl::types::User, InvocationError>
Fetches the full User object for the logged-in account. Contains id, username, first_name, last_name, phone, bot flag, verified flag, and more.

Updates

sync client.stream_updates() → UpdateStream
Returns an UpdateStream — an async iterator that yields typed Update values. Call .next().await in a loop to process events. The stream runs until the connection is closed.
let mut updates = client.stream_updates();
while let Some(update) = updates.next().await {
    match update {
        Update::NewMessage(msg) => { /* … */ }
        _ => {}
    }
}

Messaging

async client.send_message(peer: &str, text: &str) → Result<(), InvocationError>
Send a plain-text message. peer can be "me", "@username", or a numeric ID string. For rich formatting, use send_message_to_peer_ex.
async client.send_to_self(text: &str) → Result<(), InvocationError>
Sends a message to your own Saved Messages. Shorthand for send_message("me", text).
async client.send_message_to_peer(peer: Peer, text: &str) → Result<(), InvocationError>
Send a plain text message to a resolved tl::enums::Peer.
async client.send_message_to_peer_ex(peer: Peer, msg: &InputMessage) → Result<(), InvocationError>
Full-featured send with the InputMessage builder — supports markdown entities, reply-to, inline keyboard, scheduled date, silent flag, and more.
async client.edit_message(peer: Peer, message_id: i32, new_text: &str) → Result<(), InvocationError>
Edit the text of a previously sent message. Only works on messages sent by the logged-in account (or bot).
async client.edit_inline_message(inline_msg_id: tl::enums::InputBotInlineMessageId, text: &str) → Result<(), InvocationError>
Edit the text of a message that was sent via inline mode. The inline_msg_id is provided in Update::InlineSend.
async client.forward_messages(from_peer: Peer, to_peer: Peer, ids: Vec<i32>) → Result<(), InvocationError>
Forward one or more messages from from_peer into to_peer.
async client.delete_messages(ids: Vec<i32>, revoke: bool) → Result<(), InvocationError>
revoke: true deletes for everyone; false deletes only for the current account.
async client.get_messages_by_id(peer: Peer, ids: &[i32]) → Result<Vec<tl::enums::Message>, InvocationError>
Fetch specific messages by their IDs from a peer. Returns messages in the same order as the input IDs.
async client.pin_message(peer: Peer, message_id: i32, silent: bool) → Result<(), InvocationError>
Pin a message. silent: true pins without notifying members.
async client.unpin_message(peer: Peer, message_id: i32) → Result<(), InvocationError>
Unpin a specific message.
async client.unpin_all_messages(peer: Peer) → Result<(), InvocationError>
Unpin all pinned messages in a chat.
async client.get_pinned_message(peer: Peer) → Result<Option<tl::enums::Message>, InvocationError>
Fetch the currently pinned message, or None if nothing is pinned.

Reactions

async client.send_reaction(peer: Peer, msg_id: i32, reaction: Reaction) → Result<(), InvocationError>
Send a reaction to a message. Build reactions using the Reaction helper:
use layer_client::reactions::Reaction;

client.send_reaction(peer, msg_id, Reaction::emoticon(“👍”)).await?; client.send_reaction(peer, msg_id, Reaction::remove()).await?; // remove all client.send_reaction(peer, msg_id, Reaction::emoticon(“🔥”).big()).await?; See Reactions for the full guide.


Sending chat actions

async client.send_chat_action(peer: Peer, action: SendMessageAction, top_msg_id: Option<i32>) → Result<(), InvocationError>
Send a one-shot typing / uploading / recording indicator. Expires after ~5 seconds. Use TypingGuard to keep it alive for longer operations. top_msg_id restricts the indicator to a forum topic.

sync client.search(peer: impl Into<PeerRef>, query: &str) → SearchBuilder
Returns a SearchBuilder for per-peer message search with date filters, sender filter, media type filter, and pagination.
sync client.search_global_builder(query: &str) → GlobalSearchBuilder
Returns a GlobalSearchBuilder for searching across all dialogs simultaneously.
async client.search_messages(peer: Peer, query: &str, limit: i32) → Result<Vec<tl::enums::Message>, InvocationError>
Simple one-shot search within a peer. For advanced options use client.search().
async client.search_global(query: &str, limit: i32) → Result<Vec<tl::enums::Message>, InvocationError>
Simple one-shot global search. For advanced options use client.search_global_builder().

Dialogs & History

async client.get_dialogs(limit: i32) → Result<Vec<Dialog>, InvocationError>
Fetch the most recent limit dialogs. Each Dialog has title(), peer(), unread_count(), and top_message().
sync client.iter_dialogs() → DialogIter
Lazy iterator that pages through all dialogs automatically. Call iter.next(&client).await?. iter.total() returns the server-reported count after the first page.
sync client.iter_messages(peer: impl Into<PeerRef>) → MessageIter
Lazy iterator over the full message history of a peer, newest first. Call iter.next(&client).await?.
async client.get_messages(peer: Peer, limit: i32, offset_id: i32) → Result<Vec<tl::enums::Message>, InvocationError>
Fetch a page of messages. Pass the lowest message ID from the previous page as offset_id to paginate.
async client.mark_as_read(peer: impl Into<PeerRef>) → Result<(), InvocationError>
Mark all messages in a dialog as read.
async client.clear_mentions(peer: impl Into<PeerRef>) → Result<(), InvocationError>
Clear unread @mention badges in a chat.
async client.delete_dialog(peer: impl Into<PeerRef>) → Result<(), InvocationError>
Delete a dialog from the account's dialog list (does not delete messages for others).

Scheduled messages

async client.get_scheduled_messages(peer: Peer) → Result<Vec<tl::enums::Message>, InvocationError>
Fetch all messages scheduled to be sent in a chat.
async client.delete_scheduled_messages(peer: Peer, ids: Vec<i32>) → Result<(), InvocationError>
Cancel and delete scheduled messages by ID.

Participants & Admin

async client.get_participants(peer: Peer, limit: i32) → Result<Vec<Participant>, InvocationError>
Fetch members of a chat or channel. Pass limit = 0 for the default server maximum per page. Use iter_participants to lazily page all members.
async client.iter_participants(peer: Peer) → ParticipantIter
Lazy async iterator that pages through all members, including beyond the 200-member limit. Fixed in v0.4.5 to paginate correctly for large channels.
async client.set_admin_rights(peer: Peer, user_id: i64, rights: AdminRightsBuilder) → Result<(), InvocationError>
Promote a user to admin with specified rights. See Admin & Ban Rights.
async client.set_banned_rights(peer: Peer, user_id: i64, rights: BanRightsBuilder) → Result<(), InvocationError>
Restrict or ban a user. Pass BanRightsBuilder::full_ban() to fully ban. See Admin & Ban Rights.
async client.get_profile_photos(peer: Peer, limit: i32) → Result<Vec<tl::enums::Photo>, InvocationError>
Fetch a user's profile photo list.
async client.get_permissions(peer: Peer, user_id: i64) → Result<Participant, InvocationError>
Fetch the effective permissions of a user in a chat. Check .is_admin(), .is_banned(), etc. on the returned Participant.

Media

async client.upload_file(path: &str) → Result<UploadedFile, InvocationError>
Upload a file from a local path. Returns an UploadedFile with .as_photo_media() and .as_document_media() methods.
async client.send_file(peer: Peer, media: InputMedia, caption: Option<&str>) → Result<(), InvocationError>
Send an uploaded file as a photo or document with an optional caption.
async client.send_album(peer: Peer, media: Vec<InputMedia>, caption: Option<&str>) → Result<(), InvocationError>
Send multiple media items as a grouped album (2–10 items).
async client.download_media_to_file(location: impl Downloadable, path: &str) → Result<(), InvocationError>
Download a media attachment and write it directly to a file path.

Callbacks & Inline

async client.answer_callback_query(query_id: i64, text: Option<&str>, alert: bool) → Result<(), InvocationError>
Acknowledge an inline button press. text shows a toast (or alert if alert=true). Must be called within 60 seconds of the button press.
async client.answer_inline_query(query_id: i64, results: Vec<InputBotInlineResult>, cache_time: i32, is_personal: bool, next_offset: Option<&str>) → Result<(), InvocationError>
Respond to an inline query with a list of results. cache_time in seconds. Empty result list now handled correctly (fixed in v0.4.5).

Peer resolution

async client.resolve_peer(peer: &str) → Result<tl::enums::Peer, InvocationError>
Resolve a string ("@username", "+phone", "me", numeric ID) to a Peer with cached access hash.
async client.resolve_username(username: &str) → Result<tl::enums::Peer, InvocationError>
Resolve a bare username (without @) to a Peer.

Raw API

async client.invoke<R: RemoteCall>(req: &R) → Result<R::Return, InvocationError>
Call any Layer 224 API method directly. See Raw API Access for the full guide.
use layer_tl_types::functions;
let state = client.invoke(&functions::updates::GetState {}).await?;
async client.invoke_on_dc<R: RemoteCall>(req: &R, dc_id: i32) → Result<R::Return, InvocationError>
Send a request to a specific Telegram data centre. Used for file downloads from CDN DCs.

Chat management

async client.join_chat(peer: impl Into<PeerRef>) → Result<(), InvocationError>
Join a group or channel by peer reference.
async client.accept_invite_link(link: &str) → Result<(), InvocationError>
Accept a t.me/+hash or t.me/joinchat/hash invite link.