telegram_bot_api/
bot.rs

1use reqwest::header::HeaderMap;
2use reqwest::multipart;
3use serde::de::DeserializeOwned;
4use serde::{Deserialize, Serialize};
5use std::fmt::Display;
6use std::{collections::HashMap, fmt::Debug};
7
8use crate::{methods, types};
9
10/// APIResponse is a response from the Telegram API with the result
11/// stored raw.
12#[derive(Deserialize, Serialize, Debug)]
13pub struct APIResponse {
14    ok: bool,
15    error_code: Option<i32>,
16    result: Option<serde_json::Value>,
17    description: Option<String>,
18    parameters: Option<types::ResponseParameters>,
19}
20
21/// the APIResponseError is returned when send request failed.
22pub type APIResponseError = Box<dyn std::error::Error>;
23/// ReplyResult is returned when send a request
24pub type ReplyResult<T> = Result<T, APIResponseError>;
25
26impl APIResponse {
27    fn parse(self) -> Result<Self, APIResponseError> {
28        if self.ok {
29            return Ok(self);
30        }
31        Err(Error::new_option(self.error_code, self.description, self.parameters).into())
32    }
33}
34
35/// Error is an error containing extra information returned by the Telegram API.
36#[derive(Deserialize, Serialize, Debug)]
37pub struct Error {
38    pub code: i32,
39    pub message: String,
40    pub parameters: Option<types::ResponseParameters>,
41}
42
43impl Error {
44    pub fn new(code: i32, message: String) -> Self {
45        Self {
46            code,
47            message,
48            parameters: None,
49        }
50    }
51
52    pub fn new_option(
53        code: Option<i32>,
54        message: Option<String>,
55        parameters: Option<types::ResponseParameters>,
56    ) -> Self {
57        Self {
58            code: code.unwrap_or(400),
59            message: message.unwrap_or("server inter error.".to_string()),
60            parameters,
61        }
62    }
63
64    pub fn not_found() -> Self {
65        Self {
66            code: 404,
67            message: "not found".to_string(),
68            parameters: None,
69        }
70    }
71}
72
73impl std::error::Error for Error {
74    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
75        Some(self)
76    }
77}
78
79impl std::fmt::Display for Error {
80    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
81        Display::fmt(&self, f)
82    }
83}
84
85/// BotAPI allows you to interact with the Telegram Bot API.
86#[derive(Debug)]
87pub struct BotApi {
88    url: String,
89    token: String,
90    client: reqwest::Client,
91}
92
93impl BotApi {
94    /// NewBotAPI creates a new BotAPI instance.
95    /// It requires a token, provided by @BotFather on Telegram.
96    /// # Using a Custom Bot API Server
97    /// ```rust
98    /// new(String::from("token"),Some(String::from("http://127.0.0.1:8081/bot")));
99    /// ```
100    pub async fn new(token: String, url: Option<String>) -> ReplyResult<Self> {
101        let result = Self {
102            url: url.unwrap_or(String::from("https://api.telegram.org/bot")),
103            token,
104            client: reqwest::Client::builder().build().unwrap(),
105        };
106        match result.get_me().await {
107            Ok(_) => Ok(result),
108            Err(err) => Err(err),
109        }
110    }
111
112    /// send request
113    pub async fn send<T, R>(&self, request: T) -> ReplyResult<R>
114    where
115        T: methods::Methods,
116        R: DeserializeOwned,
117    {
118        if let Some(result) = self.request(&request).await?.result {
119            return Ok(serde_json::from_value(result)?);
120        }
121        Err(Error::not_found().into())
122    }
123
124    /// A simple method for testing your bot's authentication token. Requires no parameters. Returns basic information about the bot in form of a User object.
125    pub async fn get_me(&self) -> ReplyResult<types::User> {
126        Ok(self.send(methods::GetMe::new()).await?)
127    }
128
129    /// Use this method to log out from the cloud Bot API server before launching the bot locally. You must log out the bot before running it locally, otherwise there is no guarantee that the bot will receive updates. After a successful call, you can immediately log in on a local server, but will not be able to log in back to the cloud Bot API server for 10 minutes. Returns True on success. Requires no parameters.
130    pub async fn log_out(&self) -> ReplyResult<bool> {
131        Ok(self.send(methods::LogOut::new()).await?)
132    }
133
134    /// Use this method to close the bot instance before moving it from one local server to another. You need to delete the webhook before calling this method to ensure that the bot isn't launched again after server restart. The method will return error 429 in the first 10 minutes after the bot is launched. Returns True on success. Requires no parameters.
135    pub async fn close(&self) -> ReplyResult<bool> {
136        Ok(self.send(methods::Close::new()).await?)
137    }
138
139    /// Use this method to send text messages. On success, the sent Message is returned.
140    pub async fn send_message(&self, request: methods::SendMessage) -> ReplyResult<types::Message> {
141        Ok(self.send(request).await?)
142    }
143
144    /// Use this method to forward messages of any kind. Service messages can't be forwarded. On success, the sent Message is returned.
145    pub async fn forward_message(
146        &self,
147        request: methods::ForwardMessage,
148    ) -> ReplyResult<types::Message> {
149        Ok(self.send(request).await?)
150    }
151
152    /// Use this method to copy messages of any kind. Service messages and invoice messages can't be copied. A quiz poll can be copied only if the value of the field correct_option_id is known to the bot. The method is analogous to the method forwardMessage, but the copied message doesn't have a link to the original message. Returns the MessageId of the sent message on success.
153    pub async fn copy_message(
154        &self,
155        request: methods::CopyMessage,
156    ) -> ReplyResult<types::MessageId> {
157        Ok(self.send(request).await?)
158    }
159
160    /// Use this method to send photos. On success, the sent Message is returned.
161    pub async fn send_photo(&self, request: methods::SendPhoto) -> ReplyResult<types::Message> {
162        Ok(self.send(request).await?)
163    }
164
165    /// Use this method to send audio files, if you want Telegram clients to display them in the music player. Your audio must be in the .MP3 or .M4A format. On success, the sent Message is returned. Bots can currently send audio files of up to 50 MB in size, this limit may be changed in the future.
166    pub async fn send_audio(&self, request: methods::SendAudio) -> ReplyResult<types::Message> {
167        Ok(self.send(request).await?)
168    }
169
170    /// Use this method to send general files. On success, the sent Message is returned. Bots can currently send files of any type of up to 50 MB in size, this limit may be changed in the future.
171    pub async fn send_document(
172        &self,
173        request: methods::SendDocument,
174    ) -> ReplyResult<types::Message> {
175        Ok(self.send(request).await?)
176    }
177
178    /// Use this method to send video files, Telegram clients support MPEG4 videos (other formats may be sent as Document). On success, the sent Message is returned. Bots can currently send video files of up to 50 MB in size, this limit may be changed in the future.
179    pub async fn send_video(&self, request: methods::SendVideo) -> ReplyResult<types::Message> {
180        Ok(self.send(request).await?)
181    }
182
183    /// Use this method to send animation files (GIF or H.264/MPEG-4 AVC video without sound). On success, the sent Message is returned. Bots can currently send animation files of up to 50 MB in size, this limit may be changed in the future.
184    pub async fn send_animation(
185        &self,
186        request: methods::SendAnimation,
187    ) -> ReplyResult<types::Message> {
188        Ok(self.send(request).await?)
189    }
190
191    /// Use this method to send audio files, if you want Telegram clients to display the file as a playable voice message. For this to work, your audio must be in an .OGG file encoded with OPUS (other formats may be sent as Audio or Document). On success, the sent Message is returned. Bots can currently send voice messages of up to 50 MB in size, this limit may be changed in the future.
192    pub async fn send_voice(&self, request: methods::SendVoice) -> ReplyResult<types::Message> {
193        Ok(self.send(request).await?)
194    }
195
196    /// As of v.4.0, Telegram clients support rounded square MPEG4 videos of up to 1 minute long. Use this method to send video messages. On success, the sent Message is returned.
197    pub async fn send_video_note(
198        &self,
199        request: methods::SendVideoNote,
200    ) -> ReplyResult<types::Message> {
201        Ok(self.send(request).await?)
202    }
203
204    /// Use this method to send a group of photos, videos, documents or audios as an album. Documents and audio files can be only grouped in an album with messages of the same type. On success, an array of Messages that were sent is returned.
205    pub async fn send_media_group(
206        &self,
207        request: methods::SendMediaGroup,
208    ) -> ReplyResult<Vec<types::Message>> {
209        Ok(self.send(request).await?)
210    }
211
212    /// Use this method to send point on the map. On success, the sent Message is returned.
213    pub async fn send_location(
214        &self,
215        request: methods::SendLocation,
216    ) -> ReplyResult<types::Message> {
217        Ok(self.send(request).await?)
218    }
219
220    /// Use this method to edit live location messages. A location can be edited until its live_period expires or editing is explicitly disabled by a call to stopMessageLiveLocation. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned.
221    pub async fn edit_message_live_location(
222        &self,
223        request: methods::EditMessageLiveLocation,
224    ) -> ReplyResult<types::MayBeMessage> {
225        Ok(self.send(request).await?)
226    }
227
228    /// Use this method to stop updating a live location message before live_period expires. On success, if the message is not an inline message, the edited Message is returned, otherwise True is returned.
229    pub async fn stop_message_live_location(
230        &self,
231        request: methods::StopMessageLiveLocation,
232    ) -> ReplyResult<types::MayBeMessage> {
233        Ok(self.send(request).await?)
234    }
235
236    /// Use this method to send information about a venue. On success, the sent Message is returned.
237    pub async fn send_venue(&self, request: methods::SendVenue) -> ReplyResult<types::Message> {
238        Ok(self.send(request).await?)
239    }
240
241    /// Use this method to send phone contacts. On success, the sent Message is returned.
242    pub async fn send_contact(&self, request: methods::SendContact) -> ReplyResult<types::Message> {
243        Ok(self.send(request).await?)
244    }
245
246    /// Use this method to send a native poll. On success, the sent Message is returned.
247    pub async fn send_poll(&self, request: methods::SendPoll) -> ReplyResult<types::Message> {
248        Ok(self.send(request).await?)
249    }
250
251    /// Use this method to send an animated emoji that will display a random value. On success, the sent Message is returned.
252    pub async fn send_dice(&self, request: methods::SendDice) -> ReplyResult<types::Message> {
253        Ok(self.send(request).await?)
254    }
255
256    /// Use this method when you need to tell the user that something is happening on the bot's side. The status is set for 5 seconds or less (when a message arrives from your bot, Telegram clients clear its typing status). Returns True on success.
257    pub async fn send_chat_action(&self, request: methods::SendChatAction) -> ReplyResult<bool> {
258        Ok(self.send(request).await?)
259    }
260
261    /// Use this method to get a list of profile pictures for a user. Returns a UserProfilePhotos object.
262    pub async fn get_user_profile_photos(
263        &self,
264        request: methods::GetUserProfilePhotos,
265    ) -> ReplyResult<types::UserProfilePhotos> {
266        Ok(self.send(request).await?)
267    }
268
269    /// Use this method to get basic information about a file and prepare it for downloading. For the moment, bots can download files of up to 20MB in size. On success, a File object is returned. The file can then be downloaded via the link https://api.telegram.org/file/bot<token>/<file_path>, where <file_path> is taken from the response. It is guaranteed that the link will be valid for at least 1 hour. When the link expires, a new one can be requested by calling getFile again.
270    pub async fn get_file(&self, request: methods::GetFile) -> ReplyResult<types::File> {
271        Ok(self.send(request).await?)
272    }
273
274    /// Use this method to ban a user in a group, a supergroup or a channel. In the case of supergroups and channels, the user will not be able to return to the chat on their own using invite links, etc., unless unbanned first. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns True on success.
275    pub async fn ban_chat_member(&self, request: methods::BanChatMember) -> ReplyResult<bool> {
276        Ok(self.send(request).await?)
277    }
278
279    /// Use this method to unban a previously banned user in a supergroup or channel. The user will not return to the group or channel automatically, but will be able to join via link, etc. The bot must be an administrator for this to work. By default, this method guarantees that after the call the user is not a member of the chat, but will be able to join it. So if the user is a member of the chat they will also be removed from the chat. If you don't want this, use the parameter only_if_banned. Returns True on success.
280    pub async fn unban_chat_member(&self, request: methods::UnbanChatMember) -> ReplyResult<bool> {
281        Ok(self.send(request).await?)
282    }
283
284    /// Use this method to restrict a user in a supergroup. The bot must be an administrator in the supergroup for this to work and must have the appropriate administrator rights. Pass True for all permissions to lift restrictions from a user. Returns True on success.
285    pub async fn restrict_chat_member(
286        &self,
287        request: methods::RestrictChatMember,
288    ) -> ReplyResult<bool> {
289        Ok(self.send(request).await?)
290    }
291
292    /// Use this method to promote or demote a user in a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Pass False for all boolean parameters to demote a user. Returns True on success.
293    pub async fn promote_chat_member(
294        &self,
295        request: methods::PromoteChatMember,
296    ) -> ReplyResult<bool> {
297        Ok(self.send(request).await?)
298    }
299
300    /// Use this method to set a custom title for an administrator in a supergroup promoted by the bot. Returns True on success.
301    pub async fn set_chat_administrator_custom_title(
302        &self,
303        request: methods::SetChatAdministratorCustomTitle,
304    ) -> ReplyResult<bool> {
305        Ok(self.send(request).await?)
306    }
307
308    /// Use this method to ban a channel chat in a supergroup or a channel. Until the chat is unbanned, the owner of the banned chat won't be able to send messages on behalf of any of their channels. The bot must be an administrator in the supergroup or channel for this to work and must have the appropriate administrator rights. Returns True on success.
309    pub async fn ban_chat_sender_chat(
310        &self,
311        request: methods::BanChatSenderChat,
312    ) -> ReplyResult<bool> {
313        Ok(self.send(request).await?)
314    }
315
316    /// Use this method to unban a previously banned channel chat in a supergroup or channel. The bot must be an administrator for this to work and must have the appropriate administrator rights. Returns True on success.
317    pub async fn unban_chat_sender_chat(
318        &self,
319        request: methods::UnbanChatSenderChat,
320    ) -> ReplyResult<bool> {
321        Ok(self.send(request).await?)
322    }
323
324    /// Use this method to set default chat permissions for all members. The bot must be an administrator in the group or a supergroup for this to work and must have the can_restrict_members administrator rights. Returns True on success.
325    pub async fn set_chat_permissions(
326        &self,
327        request: methods::SetChatPermissions,
328    ) -> ReplyResult<bool> {
329        Ok(self.send(request).await?)
330    }
331
332    /// Use this method to generate a new primary invite link for a chat; any previously generated primary link is revoked. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns the new invite link as String on success.
333    pub async fn export_chat_invite_link(
334        &self,
335        request: methods::ExportChatInviteLink,
336    ) -> ReplyResult<String> {
337        Ok(self.send(request).await?)
338    }
339
340    /// Use this method to create an additional invite link for a chat. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. The link can be revoked using the method revokeChatInviteLink. Returns the new invite link as ChatInviteLink object.
341    pub async fn create_chat_invite_link(
342        &self,
343        request: methods::CreateChatInviteLink,
344    ) -> ReplyResult<types::ChatInviteLink> {
345        Ok(self.send(request).await?)
346    }
347
348    /// Use this method to edit a non-primary invite link created by the bot. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns the edited invite link as a ChatInviteLink object.
349    pub async fn edit_chat_invite_link(
350        &self,
351        request: methods::EditChatInviteLink,
352    ) -> ReplyResult<types::ChatInviteLink> {
353        Ok(self.send(request).await?)
354    }
355
356    /// Use this method to revoke an invite link created by the bot. If the primary link is revoked, a new link is automatically generated. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns the revoked invite link as ChatInviteLink object.
357    pub async fn revoke_chat_invite_link(
358        &self,
359        request: methods::RevokeChatInviteLink,
360    ) -> ReplyResult<types::ChatInviteLink> {
361        Ok(self.send(request).await?)
362    }
363
364    /// Use this method to approve a chat join request. The bot must be an administrator in the chat for this to work and must have the can_invite_users administrator right. Returns True on success.
365    pub async fn approve_chat_join_request(
366        &self,
367        request: methods::ApproveChatJoinRequest,
368    ) -> ReplyResult<bool> {
369        Ok(self.send(request).await?)
370    }
371
372    /// Use this method to decline a chat join request. The bot must be an administrator in the chat for this to work and must have the can_invite_users administrator right. Returns True on success.
373    pub async fn decline_chat_join_request(
374        &self,
375        request: methods::DeclineChatJoinRequest,
376    ) -> ReplyResult<bool> {
377        Ok(self.send(request).await?)
378    }
379
380    /// Use this method to set a new profile photo for the chat. Photos can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns True on success.
381    pub async fn set_chat_photo(&self, request: methods::SetChatPhoto) -> ReplyResult<bool> {
382        Ok(self.send(request).await?)
383    }
384
385    /// Use this method to delete a chat photo. Photos can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns True on success.
386    pub async fn delete_chat_photo(&self, request: methods::DeleteChatPhoto) -> ReplyResult<bool> {
387        Ok(self.send(request).await?)
388    }
389
390    /// Use this method to change the title of a chat. Titles can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns True on success.
391    pub async fn set_chat_title(&self, request: methods::SetChatTitle) -> ReplyResult<bool> {
392        Ok(self.send(request).await?)
393    }
394
395    /// Use this method to change the description of a group, a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns True on success.
396    pub async fn set_chat_description(
397        &self,
398        request: methods::SetChatDescription,
399    ) -> ReplyResult<bool> {
400        Ok(self.send(request).await?)
401    }
402
403    /// Use this method to add a message to the list of pinned messages in a chat. If the chat is not a private chat, the bot must be an administrator in the chat for this to work and must have the 'can_pin_messages' administrator right in a supergroup or 'can_edit_messages' administrator right in a channel. Returns True on success.
404    pub async fn pin_chat_message(&self, request: methods::PinChatMessage) -> ReplyResult<bool> {
405        Ok(self.send(request).await?)
406    }
407
408    /// Use this method to remove a message from the list of pinned messages in a chat. If the chat is not a private chat, the bot must be an administrator in the chat for this to work and must have the 'can_pin_messages' administrator right in a supergroup or 'can_edit_messages' administrator right in a channel. Returns True on success.
409    pub async fn unpin_chat_message(
410        &self,
411        request: methods::UnpinChatMessage,
412    ) -> ReplyResult<bool> {
413        Ok(self.send(request).await?)
414    }
415
416    /// Use this method to clear the list of pinned messages in a chat. If the chat is not a private chat, the bot must be an administrator in the chat for this to work and must have the 'can_pin_messages' administrator right in a supergroup or 'can_edit_messages' administrator right in a channel. Returns True on success.
417    pub async fn unpin_all_chat_messages(
418        &self,
419        request: methods::UnpinAllChatMessages,
420    ) -> ReplyResult<bool> {
421        Ok(self.send(request).await?)
422    }
423
424    /// Use this method for your bot to leave a group, supergroup or channel. Returns True on success.
425    pub async fn leave_chat(&self, request: methods::LeaveChat) -> ReplyResult<bool> {
426        Ok(self.send(request).await?)
427    }
428
429    /// Use this method to get up to date information about the chat (current name of the user for one-on-one conversations, current username of a user, group or channel, etc.). Returns a Chat object on success.
430    pub async fn get_chat(&self, request: methods::GetChat) -> ReplyResult<types::Chat> {
431        Ok(self.send(request).await?)
432    }
433
434    /// Use this method to get a list of administrators in a chat, which aren't bots. Returns an Array of ChatMember objects.
435    pub async fn get_chat_administrators(
436        &self,
437        request: methods::GetChatAdministrators,
438    ) -> ReplyResult<Vec<types::ChatMember>> {
439        Ok(self.send(request).await?)
440    }
441
442    /// Use this method to get the number of members in a chat. Returns Int on success.
443    pub async fn get_chat_member_count(
444        &self,
445        request: methods::GetChatMemberCount,
446    ) -> ReplyResult<i64> {
447        Ok(self.send(request).await?)
448    }
449
450    /// Use this method to get information about a member of a chat. Returns a ChatMember object on success.
451    pub async fn get_chat_member(
452        &self,
453        request: methods::GetChatMember,
454    ) -> ReplyResult<types::ChatMember> {
455        Ok(self.send(request).await?)
456    }
457
458    /// Use this method to set a new group sticker set for a supergroup. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Use the field can_set_sticker_set optionally returned in getChat requests to check if the bot can use this method. Returns True on success.
459    pub async fn set_chat_sticker_set(
460        &self,
461        request: methods::SetChatStickerSet,
462    ) -> ReplyResult<bool> {
463        Ok(self.send(request).await?)
464    }
465
466    /// Use this method to delete a group sticker set from a supergroup. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Use the field can_set_sticker_set optionally returned in getChat requests to check if the bot can use this method. Returns True on success.
467    pub async fn delete_chat_sticker_set(
468        &self,
469        request: methods::DeleteChatStickerSet,
470    ) -> ReplyResult<bool> {
471        Ok(self.send(request).await?)
472    }
473
474    /// Use this method to send answers to callback queries sent from inline keyboards. The answer will be displayed to the user as a notification at the top of the chat screen or as an alert. On success, True is returned.
475    pub async fn answer_callback_query(
476        &self,
477        request: methods::AnswerCallbackQuery,
478    ) -> ReplyResult<bool> {
479        Ok(self.send(request).await?)
480    }
481
482    /// Use this method to change the list of the bot's commands. See https://core.telegram.org/bots#commands for more details about bot commands. Returns True on success.
483    pub async fn set_my_commands(&self, request: methods::SetMyCommands) -> ReplyResult<bool> {
484        Ok(self.send(request).await?)
485    }
486
487    /// Use this method to delete the list of the bot's commands for the given scope and user language. After deletion, higher level commands will be shown to affected users. Returns True on success.
488    pub async fn delete_my_commands(
489        &self,
490        request: methods::DeleteMyCommands,
491    ) -> ReplyResult<bool> {
492        Ok(self.send(request).await?)
493    }
494
495    /// Use this method to get the current list of the bot's commands for the given scope and user language. Returns an Array of BotCommand objects. If commands aren't set, an empty list is returned.
496    pub async fn get_my_commands(
497        &self,
498        request: methods::GetMyCommands,
499    ) -> ReplyResult<Vec<types::BotCommand>> {
500        Ok(self.send(request).await?)
501    }
502
503    /// Use this method to change the bot's menu button in a private chat, or the default menu button. Returns True on success.
504    pub async fn set_chat_menu_button(
505        &self,
506        request: methods::SetChatMenuButton,
507    ) -> ReplyResult<bool> {
508        Ok(self.send(request).await?)
509    }
510
511    /// Use this method to get the current value of the bot's menu button in a private chat, or the default menu button. Returns MenuButton on success.
512    pub async fn get_chat_menu_button(
513        &self,
514        request: methods::GetChatMenuButton,
515    ) -> ReplyResult<types::MenuButton> {
516        Ok(self.send(request).await?)
517    }
518
519    /// Use this method to change the default administrator rights requested by the bot when it's added as an administrator to groups or channels. These rights will be suggested to users, but they are are free to modify the list before adding the bot. Returns True on success.
520    pub async fn set_my_default_administrator_rights(
521        &self,
522        request: methods::SetMyDefaultAdministratorRights,
523    ) -> ReplyResult<bool> {
524        Ok(self.send(request).await?)
525    }
526
527    /// Use this method to get the current default administrator rights of the bot. Returns ChatAdministratorRights on success.
528    pub async fn get_my_default_administrator_rights(
529        &self,
530        request: methods::GetMyDefaultAdministratorRights,
531    ) -> ReplyResult<bool> {
532        Ok(self.send(request).await?)
533    }
534
535    /// Use this method to receive incoming updates using long polling (wiki). Returns an Array of Update objects.
536    pub async fn get_updates(
537        &self,
538        request: methods::GetUpdates,
539    ) -> ReplyResult<Vec<types::Update>> {
540        Ok(self.send(request).await?)
541    }
542
543    /// Use this method to specify a URL and receive incoming updates via an outgoing webhook. Whenever there is an update for the bot, we will send an HTTPS POST request to the specified URL, containing a JSON-serialized Update. In case of an unsuccessful request, we will give up after a reasonable amount of attempts. Returns True on success.
544    pub async fn set_webhook(&self, request: methods::SetWebhook) -> ReplyResult<bool> {
545        Ok(self.send(request).await?)
546    }
547
548    /// Use this method to remove webhook integration if you decide to switch back to getUpdates. Returns True on success.
549    pub async fn delete_webhook(&self, request: methods::DeleteWebhook) -> ReplyResult<bool> {
550        Ok(self.send(request).await?)
551    }
552
553    /// Use this method to get current webhook status. Requires no parameters. On success, returns a WebhookInfo object. If the bot is using getUpdates, will return an object with the url field empty.
554    pub async fn get_webhook_info(&self) -> ReplyResult<types::WebhookInfo> {
555        Ok(self.send(methods::GetWebhookInfo::new()).await?)
556    }
557
558    /// Use this method to send static .WEBP, animated .TGS, or video .WEBM stickers. On success, the sent Message is returned.
559    pub async fn send_sticker(&self, request: methods::SendSticker) -> ReplyResult<types::Message> {
560        Ok(self.send(request).await?)
561    }
562
563    /// Use this method to get a sticker set. On success, a StickerSet object is returned.
564    pub async fn get_sticker_set(
565        &self,
566        request: methods::GetStickerSet,
567    ) -> ReplyResult<types::StickerSet> {
568        Ok(self.send(request).await?)
569    }
570
571    /// Use this method to get information about custom emoji stickers by their identifiers. Returns an Array of Sticker objects.
572    pub async fn get_custom_emoji_stickers(
573        &self,
574        request: methods::GetCustomEmojiStickers,
575    ) -> ReplyResult<Vec<types::Sticker>> {
576        Ok(self.send(request).await?)
577    }
578
579    /// Use this method to upload a .PNG file with a sticker for later use in createNewStickerSet and addStickerToSet methods (can be used multiple times). Returns the uploaded File on success.
580    pub async fn upload_sticker_file(
581        &self,
582        request: methods::UploadStickerFile,
583    ) -> ReplyResult<bool> {
584        Ok(self.send(request).await?)
585    }
586
587    /// Use this method to create a new sticker set owned by a user. The bot will be able to edit the sticker set thus created. You must use exactly one of the fields png_sticker, tgs_sticker, or webm_sticker. Returns True on success.
588    pub async fn create_new_sticker_set(
589        &self,
590        request: methods::CreateNewStickerSet,
591    ) -> ReplyResult<bool> {
592        Ok(self.send(request).await?)
593    }
594
595    /// Use this method to add a new sticker to a set created by the bot. You must use exactly one of the fields png_sticker, tgs_sticker, or webm_sticker. Animated stickers can be added to animated sticker sets and only to them. Animated sticker sets can have up to 50 stickers. Static sticker sets can have up to 120 stickers. Returns True on success.
596    pub async fn add_sticker_to_set(&self, request: methods::AddStickerToSet) -> ReplyResult<bool> {
597        Ok(self.send(request).await?)
598    }
599
600    /// Use this method to move a sticker in a set created by the bot to a specific position. Returns True on success.
601    pub async fn set_sticker_position_in_set(
602        &self,
603        request: methods::SetStickerPositionInSet,
604    ) -> ReplyResult<bool> {
605        Ok(self.send(request).await?)
606    }
607
608    /// Use this method to delete a sticker from a set created by the bot. Returns True on success.
609    pub async fn delete_sticker_from_set(
610        &self,
611        request: methods::DeleteStickerFromSet,
612    ) -> ReplyResult<bool> {
613        Ok(self.send(request).await?)
614    }
615
616    /// Use this method to set the thumbnail of a sticker set. Animated thumbnails can be set for animated sticker sets only. Video thumbnails can be set only for video sticker sets only. Returns True on success.
617    pub async fn set_sticker_set_thumb(
618        &self,
619        request: methods::SetStickerSetThumb,
620    ) -> ReplyResult<bool> {
621        Ok(self.send(request).await?)
622    }
623
624    /// Use this method to send answers to an inline query. On success, True is returned. No more than 50 results per query are allowed.
625    pub async fn answer_inline_query(
626        &self,
627        request: methods::AnswerInlineQuery,
628    ) -> ReplyResult<bool> {
629        Ok(self.send(request).await?)
630    }
631
632    /// Use this method to set the result of an interaction with a Web App and send a corresponding message on behalf of the user to the chat from which the query originated. On success, a SentWebAppMessage object is returned.
633    pub async fn answer_web_app_query(
634        &self,
635        request: methods::AnswerWebAppQuery,
636    ) -> ReplyResult<types::SentWebAppMessage> {
637        Ok(self.send(request).await?)
638    }
639
640    /// Use this method to send invoices. On success, the sent Message is returned.
641    pub async fn send_invoice(&self, request: methods::SendInvoice) -> ReplyResult<types::Message> {
642        Ok(self.send(request).await?)
643    }
644
645    /// Use this method to create a link for an invoice. Returns the created invoice link as String on success.
646    pub async fn create_invoice_link(
647        &self,
648        request: methods::CreateInvoiceLink,
649    ) -> ReplyResult<String> {
650        Ok(self.send(request).await?)
651    }
652
653    /// If you sent an invoice requesting a shipping address and the parameter is_flexible was specified, the Bot API will send an Update with a shipping_query field to the bot. Use this method to reply to shipping queries. On success, True is returned.
654    pub async fn answer_shipping_query(
655        &self,
656        request: methods::AnswerShippingQuery,
657    ) -> ReplyResult<bool> {
658        Ok(self.send(request).await?)
659    }
660
661    /// Once the user has confirmed their payment and shipping details, the Bot API sends the final confirmation in the form of an Update with the field pre_checkout_query. Use this method to respond to such pre-checkout queries. On success, True is returned. Note: The Bot API must receive an answer within 10 seconds after the pre-checkout query was sent.
662    pub async fn answer_pre_checkout_query(
663        &self,
664        request: methods::AnswerPreCheckoutQuery,
665    ) -> ReplyResult<bool> {
666        Ok(self.send(request).await?)
667    }
668
669    /// Informs a user that some of the Telegram Passport elements they provided contains errors. The user will not be able to re-submit their Passport to you until the errors are fixed (the contents of the field for which you returned the error must change). Returns True on success.
670    pub async fn set_passport_data_errors(
671        &self,
672        request: methods::SetPassportDataErrors,
673    ) -> ReplyResult<bool> {
674        Ok(self.send(request).await?)
675    }
676
677    /// Use this method to send a game. On success, the sent Message is returned.
678    pub async fn send_game(&self, request: methods::SendGame) -> ReplyResult<types::Message> {
679        Ok(self.send(request).await?)
680    }
681
682    /// Use this method to set the score of the specified user in a game message. On success, if the message is not an inline message, the Message is returned, otherwise True is returned. Returns an error, if the new score is not greater than the user's current score in the chat and force is False.
683    pub async fn set_game_score(
684        &self,
685        request: methods::SetGameScore,
686    ) -> ReplyResult<types::MayBeMessage> {
687        Ok(self.send(request).await?)
688    }
689
690    /// Use this method to get data for high score tables. Will return the score of the specified user and several of their neighbors in a game. Returns an Array of GameHighScore objects.
691    pub async fn get_game_high_scores(
692        &self,
693        request: methods::GetGameHighScores,
694    ) -> ReplyResult<Vec<types::GameHighScore>> {
695        Ok(self.send(request).await?)
696    }
697}
698
699impl BotApi {
700    /// specific url
701    fn method(&self, endpoint: String) -> String {
702        format!("{}{}/{}", self.url, self.token, endpoint)
703    }
704
705    /// make_request makes a request to a specific endpoint with our token.
706    async fn make_request(
707        &self,
708        endpoint: String,
709        params: types::Params,
710    ) -> ReplyResult<APIResponse> {
711        let mut headers = HeaderMap::new();
712        headers.insert("Content-Type", "application/json".parse().unwrap());
713        Ok(self
714            .client
715            .post(self.method(String::from(endpoint)))
716            .headers(headers)
717            .json(&params)
718            .send()
719            .await?
720            .json::<APIResponse>()
721            .await?
722            .parse()?)
723    }
724
725    /// upload_files makes a request to the API with files.
726    async fn upload_files(
727        &self,
728        endpoint: String,
729        params: types::Params,
730        files: HashMap<String, types::InputFile>,
731    ) -> ReplyResult<APIResponse> {
732        let mut form = reqwest::multipart::Form::new();
733        for (param_key, param_value) in params {
734            form = form.part(
735                param_key.to_string(),
736                multipart::Part::text(param_value.to_string()),
737            );
738        }
739        for (file_key, file_value) in files {
740            match file_value.data().await? {
741                types::InputFileResult::Text(text) => {
742                    form = form.part(
743                        file_key.to_string(),
744                        multipart::Part::text(text.to_string()),
745                    );
746                }
747                types::InputFileResult::Part(part) => {
748                    form = form.part(file_key.to_string(), part);
749                }
750            }
751        }
752        Ok(self
753            .client
754            .post(self.method(String::from(endpoint)))
755            .multipart(form)
756            .send()
757            .await?
758            .json::<APIResponse>()
759            .await?
760            .parse()?)
761    }
762
763    /// request sends a func to Telegram, and returns the APIResponse.
764    async fn request<T: methods::Methods>(&self, request: &T) -> ReplyResult<APIResponse> {
765        let mut params = request.params()?;
766        if || -> bool {
767            for (_, file) in request.files() {
768                if file.need_upload() {
769                    return true;
770                }
771            }
772            false
773        }() {
774            return Ok(self
775                .upload_files(request.endpoint(), params, request.files())
776                .await?);
777        }
778        for (key, file) in request.files() {
779            match file.data().await? {
780                types::InputFileResult::Text(text) => {
781                    params.insert(key, serde_json::json!(text));
782                }
783                _ => {}
784            }
785        }
786        Ok(self.make_request(request.endpoint(), params).await?)
787    }
788}