Skip to main content

BotClient

Struct BotClient 

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

The Telegram Bot API HTTP client.

BotClient is cheap to clone — all internal state is reference-counted. It is safe to share across tasks and threads without additional synchronisation.

§Creating a client

// From a token string (simplest)
let client = BotClient::from_token("123456:ABC...")?;

// From a ClientConfig for advanced options
let config = ClientConfig::new("123456:ABC...")?
    .api_base_url("http://localhost:8081")
    .timeout(Duration::from_secs(60));
let client = BotClient::new(config)?;

§Making API calls

Every Bot API method is available as a method on BotClient. Each method returns a builder — set optional parameters with chained calls, then .await to execute:

client
    .send_message(chat_id, "Hello!")
    .parse_mode(ParseMode::HTML)
    .disable_notification(true)
    .await?;

Implementations§

Source§

impl BotClient

Source

pub fn new(config: ClientConfig) -> Result<Self>

Creates a new BotClient from a ClientConfig.

§Errors

Returns an error if the underlying HTTP client cannot be initialised.

Source

pub fn from_token(token: impl Into<String>) -> Result<Self>

Creates a BotClient directly from a bot token string.

This is equivalent to BotClient::new(ClientConfig::new(token)?).

§Errors

Returns Error::InvalidToken if the token format is invalid.

Source

pub fn token(&self) -> &str

Returns the bot token used for authentication.

Source

pub fn api_base_url(&self) -> &str

Returns the base URL used for API requests, defaulting to https://api.telegram.org.

Source

pub async fn post_json<P, R>(&self, method: &str, params: &P) -> Result<R>

Sends a JSON POST request to a Bot API method and deserialises the result.

Automatically retries on HTTP 429 (flood control) up to max_retries times, waiting the retry_after duration between attempts.

§Errors

Returns an error on network failure, API error (ok: false), or deserialisation failure.

Source

pub async fn post_multipart<R>(&self, method: &str, form: Form) -> Result<R>

Sends a multipart/form-data POST request to a Bot API method and deserialises the result.

Source

pub async fn download_file(&self, file_path: &str) -> Result<Bytes>

Downloads a file by its path as returned by BotClient::get_file.

The file path must be obtained by calling get_file first:

let file = client.get_file(&document.file_id).await?;
let bytes = client.download_file(&file.file_path.unwrap()).await?;

Maximum file size via the Telegram cloud server is 20 MB. Use a local Bot API server to lift this restriction.

Source

pub fn get_updates(&self) -> GetUpdates

Calls getUpdates — fetches a batch of incoming updates via long polling.

Source

pub fn set_webhook(&self, url: impl Into<String>) -> SetWebhook

Calls setWebhook — registers a webhook URL with Telegram.

Source

pub fn delete_webhook(&self) -> DeleteWebhook

Calls deleteWebhook — removes the webhook integration.

Source

pub fn get_webhook_info(&self) -> GetWebhookInfo

Calls getWebhookInfo — returns the current webhook status.

Source

pub fn get_me(&self) -> GetMe

Calls getMe — returns basic information about the bot.

Source

pub fn get_chat(&self, chat_id: impl Into<ChatId>) -> GetChat

Calls getChat — returns detailed information about a chat.

Source

pub fn get_chat_administrators( &self, chat_id: impl Into<ChatId>, ) -> GetChatAdministrators

Calls getChatAdministrators — returns a list of all chat administrators.

Source

pub fn get_chat_member_count( &self, chat_id: impl Into<ChatId>, ) -> GetChatMemberCount

Calls getChatMemberCount — returns the number of members in a chat.

Source

pub fn get_chat_member( &self, chat_id: impl Into<ChatId>, user_id: i64, ) -> GetChatMember

Calls getChatMember — returns information about a specific chat member.

Source

pub fn get_file(&self, file_id: impl Into<String>) -> GetFile

Calls getFile — returns file metadata and a download path.

Source

pub fn get_user_profile_photos(&self, user_id: i64) -> GetUserProfilePhotos

Calls getUserProfilePhotos — returns a user’s profile pictures.

Source

pub fn send_message( &self, chat_id: impl Into<ChatId>, text: impl Into<String>, ) -> SendMessage

Calls sendMessage — sends a text message to a chat.

Source

pub fn forward_message( &self, chat_id: impl Into<ChatId>, from_chat_id: impl Into<ChatId>, message_id: i64, ) -> ForwardMessage

Calls forwardMessage — forwards a message from one chat to another.

Source

pub fn copy_message( &self, chat_id: impl Into<ChatId>, from_chat_id: impl Into<ChatId>, message_id: i64, ) -> CopyMessage

Calls copyMessage — copies a message without the forward header.

Source

pub fn send_chat_action( &self, chat_id: impl Into<ChatId>, action: ChatAction, ) -> SendChatAction

Calls sendChatAction — displays a typing or upload indicator.

Source

pub fn send_photo( &self, chat_id: impl Into<ChatId>, photo: InputFile, ) -> SendPhoto

Calls sendPhoto — sends a photo.

Source

pub fn send_audio( &self, chat_id: impl Into<ChatId>, audio: InputFile, ) -> SendAudio

Calls sendAudio — sends an audio file treated as music.

Source

pub fn send_document( &self, chat_id: impl Into<ChatId>, document: InputFile, ) -> SendDocument

Calls sendDocument — sends a general file.

Source

pub fn send_video( &self, chat_id: impl Into<ChatId>, video: InputFile, ) -> SendVideo

Calls sendVideo — sends a video file.

Source

pub fn send_animation( &self, chat_id: impl Into<ChatId>, animation: InputFile, ) -> SendAnimation

Calls sendAnimation — sends a GIF or silent H.264 video.

Source

pub fn send_voice( &self, chat_id: impl Into<ChatId>, voice: InputFile, ) -> SendVoice

Calls sendVoice — sends a voice note.

Source

pub fn send_video_note( &self, chat_id: impl Into<ChatId>, video_note: InputFile, ) -> SendVideoNote

Calls sendVideoNote — sends a rounded-square video.

Source

pub fn send_sticker( &self, chat_id: impl Into<ChatId>, sticker: InputFile, ) -> SendSticker

Calls sendSticker — sends a sticker.

Source

pub fn send_location( &self, chat_id: impl Into<ChatId>, latitude: f64, longitude: f64, ) -> SendLocation

Calls sendLocation — sends a geographic location, optionally live.

Source

pub fn send_contact( &self, chat_id: impl Into<ChatId>, phone_number: impl Into<String>, first_name: impl Into<String>, ) -> SendContact

Calls sendContact — sends a phone contact.

Source

pub fn send_poll( &self, chat_id: impl Into<ChatId>, question: impl Into<String>, options: Vec<InputPollOption>, ) -> SendPoll

Calls sendPoll — sends a native poll or quiz.

Source

pub fn send_dice(&self, chat_id: impl Into<ChatId>) -> SendDice

Calls sendDice — sends an animated random emoji.

Source

pub fn send_message_draft( &self, chat_id: impl Into<ChatId>, draft_id: i64, text: impl Into<String>, ) -> SendMessageDraft

Calls sendMessageDraft — streams a partial message (Bot API 9.5+).

Source

pub fn delete_message( &self, chat_id: impl Into<ChatId>, message_id: i64, ) -> DeleteMessage

Calls deleteMessage — deletes a message.

Source

pub fn delete_messages( &self, chat_id: impl Into<ChatId>, message_ids: Vec<i64>, ) -> DeleteMessages

Calls deleteMessages — deletes up to 100 messages at once.

Source

pub fn stop_poll(&self, chat_id: impl Into<ChatId>, message_id: i64) -> StopPoll

Calls stopPoll — stops an open poll.

Source

pub fn answer_callback_query( &self, callback_query_id: impl Into<String>, ) -> AnswerCallbackQuery

Calls answerCallbackQuery — acknowledges a callback button press.

Source

pub fn edit_message_text( &self, chat_id: impl Into<ChatId>, message_id: i64, text: impl Into<String>, ) -> EditMessageText

Calls editMessageText — edits the text of a sent message.

Source

pub fn edit_inline_message_text( &self, inline_message_id: impl Into<String>, text: impl Into<String>, ) -> EditMessageText

Calls editMessageText for an inline message sent via inline mode.

Source

pub fn edit_message_caption( &self, chat_id: impl Into<ChatId>, message_id: i64, ) -> EditMessageCaption

Calls editMessageCaption — edits the caption of a media message.

Source

pub fn edit_message_reply_markup( &self, chat_id: impl Into<ChatId>, message_id: i64, ) -> EditMessageReplyMarkup

Calls editMessageReplyMarkup — replaces the inline keyboard of a message.

Source

pub fn edit_message_live_location( &self, chat_id: impl Into<ChatId>, message_id: i64, latitude: f64, longitude: f64, ) -> EditMessageLiveLocation

Calls editMessageLiveLocation — updates the position of a live location.

Source

pub fn stop_message_live_location( &self, chat_id: impl Into<ChatId>, message_id: i64, ) -> StopMessageLiveLocation

Calls stopMessageLiveLocation — stops a live location from updating.

Source

pub fn ban_chat_member( &self, chat_id: impl Into<ChatId>, user_id: i64, ) -> BanChatMember

Calls banChatMember — bans a user from a chat.

Source

pub fn unban_chat_member( &self, chat_id: impl Into<ChatId>, user_id: i64, ) -> UnbanChatMember

Calls unbanChatMember — lifts a ban from a user.

Source

pub fn restrict_chat_member( &self, chat_id: impl Into<ChatId>, user_id: i64, permissions: ChatPermissions, ) -> RestrictChatMember

Calls restrictChatMember — restricts what a user can do in a chat.

Source

pub fn promote_chat_member( &self, chat_id: impl Into<ChatId>, user_id: i64, ) -> PromoteChatMember

Calls promoteChatMember — grants or revokes admin privileges.

Calls createChatInviteLink — generates a new invite link.

Source

pub fn pin_chat_message( &self, chat_id: impl Into<ChatId>, message_id: i64, ) -> PinChatMessage

Calls pinChatMessage — pins a message in a chat.

Source

pub fn unpin_chat_message(&self, chat_id: impl Into<ChatId>) -> UnpinChatMessage

Calls unpinChatMessage — unpins a message in a chat.

Source

pub fn set_my_commands(&self, commands: Vec<BotCommand>) -> SetMyCommands

Calls setMyCommands — sets the bot’s command list.

Source

pub fn get_my_commands(&self) -> GetMyCommands

Calls getMyCommands — returns the bot’s current command list.

Source

pub fn set_my_name(&self) -> SetMyName

Calls setMyName — changes the bot’s display name.

Source

pub fn set_my_description(&self) -> SetMyDescription

Calls setMyDescription — changes the bot’s profile description.

Source

pub fn get_chat_menu_button(&self) -> GetChatMenuButton

Calls getChatMenuButton — returns the current menu button for a private chat.

Source

pub fn get_managed_bot_token(&self, user_id: i64) -> GetManagedBotToken

Calls getManagedBotToken — returns the token of a managed bot (Bot API 9.6).

Source

pub fn set_message_reaction( &self, chat_id: impl Into<ChatId>, message_id: i64, ) -> SetMessageReaction

Calls setMessageReaction — sets a reaction on a message.

Source

pub fn answer_inline_query( &self, inline_query_id: impl Into<String>, results: Vec<InlineQueryResult>, ) -> AnswerInlineQuery

Calls answerInlineQuery — sends up to 50 results for an inline query.

Source

pub fn send_invoice( &self, chat_id: impl Into<ChatId>, title: impl Into<String>, description: impl Into<String>, payload: impl Into<String>, currency: impl Into<String>, prices: Vec<LabeledPrice>, ) -> SendInvoice

Calls sendInvoice — sends a payment invoice.

Source

pub fn get_my_star_balance(&self) -> GetMyStarBalance

Calls getMyStarBalance — returns the bot’s Telegram Star balance.

Source

pub fn get_star_transactions(&self) -> GetStarTransactions

Calls getStarTransactions — returns the bot’s Star transaction history.

Source

pub fn get_sticker_set(&self, name: impl Into<String>) -> GetStickerSet

Calls getStickerSet — returns a sticker set by name.

Source

pub fn get_custom_emoji_stickers( &self, ids: Vec<impl Into<String>>, ) -> GetCustomEmojiStickers

Calls getCustomEmojiStickers — returns stickers for the given custom emoji IDs.

Source

pub fn upload_sticker_file( &self, user_id: i64, sticker: InputFile, format: StickerFormat, ) -> UploadStickerFile

Calls uploadStickerFile — uploads a sticker file for later use in a set.

Source

pub fn create_new_sticker_set( &self, user_id: i64, name: impl Into<String>, title: impl Into<String>, stickers: Vec<InputSticker>, ) -> CreateNewStickerSet

Calls createNewStickerSet — creates a new sticker set owned by a user.

Source

pub fn add_sticker_to_set( &self, user_id: i64, name: impl Into<String>, sticker: InputSticker, ) -> AddStickerToSet

Calls addStickerToSet — adds a new sticker to an existing set.

Source

pub fn set_sticker_position_in_set( &self, sticker: impl Into<String>, position: u32, ) -> SetStickerPositionInSet

Calls setStickerPositionInSet — moves a sticker to a new position in its set.

Source

pub fn delete_sticker_from_set( &self, sticker: impl Into<String>, ) -> DeleteStickerFromSet

Calls deleteStickerFromSet — removes a sticker from its set.

Source

pub fn set_sticker_emoji_list( &self, sticker: impl Into<String>, emoji_list: Vec<impl Into<String>>, ) -> SetStickerEmojiList

Calls setStickerEmojiList — updates the emoji list for a sticker.

Source

pub fn set_sticker_keywords( &self, sticker: impl Into<String>, ) -> SetStickerKeywords

Calls setStickerKeywords — updates the search keywords for a sticker.

Source

pub fn set_sticker_mask_position( &self, sticker: impl Into<String>, ) -> SetStickerMaskPosition

Calls setStickerMaskPosition — updates the mask position for a mask sticker.

Source

pub fn set_sticker_set_title( &self, name: impl Into<String>, title: impl Into<String>, ) -> SetStickerSetTitle

Calls setStickerSetTitle — renames a sticker set.

Source

pub fn delete_sticker_set(&self, name: impl Into<String>) -> DeleteStickerSet

Calls deleteStickerSet — deletes a sticker set created by the bot.

Source

pub fn get_forum_topic_icon_stickers(&self) -> GetForumTopicIconStickers

Calls getForumTopicIconStickers — returns all available forum topic icon stickers.

Source

pub fn create_forum_topic( &self, chat_id: impl Into<ChatId>, name: impl Into<String>, ) -> CreateForumTopic

Calls createForumTopic — creates a new topic in a forum supergroup.

Source

pub fn edit_forum_topic( &self, chat_id: impl Into<ChatId>, thread_id: i64, ) -> EditForumTopic

Calls editForumTopic — edits the name or icon of a forum topic.

Source

pub fn close_forum_topic( &self, chat_id: impl Into<ChatId>, thread_id: i64, ) -> CloseForumTopic

Calls closeForumTopic — closes an open forum topic.

Source

pub fn reopen_forum_topic( &self, chat_id: impl Into<ChatId>, thread_id: i64, ) -> ReopenForumTopic

Calls reopenForumTopic — reopens a closed forum topic.

Source

pub fn delete_forum_topic( &self, chat_id: impl Into<ChatId>, thread_id: i64, ) -> DeleteForumTopic

Calls deleteForumTopic — deletes a forum topic and all its messages.

Source

pub fn edit_general_forum_topic( &self, chat_id: impl Into<ChatId>, name: impl Into<String>, ) -> EditGeneralForumTopic

Calls editGeneralForumTopic — renames the General topic.

Source

pub fn close_general_forum_topic( &self, chat_id: impl Into<ChatId>, ) -> CloseGeneralForumTopic

Calls closeGeneralForumTopic — closes the General topic.

Source

pub fn reopen_general_forum_topic( &self, chat_id: impl Into<ChatId>, ) -> ReopenGeneralForumTopic

Calls reopenGeneralForumTopic — reopens the General topic.

Source

pub fn hide_general_forum_topic( &self, chat_id: impl Into<ChatId>, ) -> HideGeneralForumTopic

Calls hideGeneralForumTopic — hides the General topic from the topic list.

Source

pub fn unhide_general_forum_topic( &self, chat_id: impl Into<ChatId>, ) -> UnhideGeneralForumTopic

Calls unhideGeneralForumTopic — makes the General topic visible again.

Source

pub fn verify_user(&self, user_id: i64) -> VerifyUser

Calls verifyUser — verifies a user on behalf of the organisation.

Source

pub fn verify_chat(&self, chat_id: impl Into<ChatId>) -> VerifyChat

Calls verifyChat — verifies a chat on behalf of the organisation.

Source

pub fn remove_user_verification(&self, user_id: i64) -> RemoveUserVerification

Calls removeUserVerification — removes verification from a user.

Source

pub fn remove_chat_verification( &self, chat_id: impl Into<ChatId>, ) -> RemoveChatVerification

Calls removeChatVerification — removes verification from a chat.

Source

pub fn get_business_connection( &self, id: impl Into<String>, ) -> GetBusinessConnection

Calls getBusinessConnection — returns business connection information.

Source

pub fn read_business_message( &self, business_connection_id: impl Into<String>, chat_id: impl Into<ChatId>, message_id: i64, ) -> ReadBusinessMessage

Calls readBusinessMessage — marks a business account message as read.

Source

pub fn delete_business_messages( &self, business_connection_id: impl Into<String>, message_ids: Vec<i64>, ) -> DeleteBusinessMessages

Calls deleteBusinessMessages — deletes messages from a business account.

Source

pub fn set_business_account_name( &self, business_connection_id: impl Into<String>, first_name: impl Into<String>, last_name: Option<String>, ) -> SetBusinessAccountName

Calls setBusinessAccountName — sets the name of a managed business account.

Source

pub fn set_business_account_username( &self, business_connection_id: impl Into<String>, username: Option<String>, ) -> SetBusinessAccountUsername

Calls setBusinessAccountUsername — sets the username of a managed business account.

Source

pub fn set_business_account_bio( &self, business_connection_id: impl Into<String>, bio: Option<String>, ) -> SetBusinessAccountBio

Calls setBusinessAccountBio — sets the bio of a managed business account.

Source

pub fn get_business_account_star_balance( &self, business_connection_id: impl Into<String>, ) -> GetBusinessAccountStarBalance

Calls getBusinessAccountStarBalance — returns a business account’s Star balance.

Source

pub fn transfer_business_account_stars( &self, business_connection_id: impl Into<String>, star_count: u64, ) -> TransferBusinessAccountStars

Calls transferBusinessAccountStars — transfers Stars from a business account to the bot.

Trait Implementations§

Source§

impl Clone for BotClient

Source§

fn clone(&self) -> BotClient

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