teloxide_core/errors.rs
1//! Possible error types.
2
3use std::{io, sync::Arc};
4
5use thiserror::Error;
6
7use crate::types::{ChatId, ResponseParameters, Seconds};
8
9/// An error caused by sending a request to Telegram.
10#[derive(Debug, Error, Clone)]
11pub enum RequestError {
12 /// A Telegram API error.
13 #[error("A Telegram's error: {0}")]
14 Api(#[from] ApiError),
15
16 /// The group has been migrated to a supergroup with the specified
17 /// identifier.
18 #[error("The group has been migrated to a supergroup with ID #{0}")]
19 MigrateToChatId(ChatId),
20
21 /// In case of exceeding flood control, the number of seconds left to wait
22 /// before the request can be repeated.
23 #[error("Retry after {0}")]
24 RetryAfter(Seconds),
25
26 /// Network error while sending a request to Telegram.
27 #[error("A network error: {0}")]
28 // NOTE: this variant must not be created by anything except the explicit From impl
29 Network(#[source] Arc<reqwest::Error>),
30
31 /// Error while parsing a response from Telegram.
32 ///
33 /// If you've received this error, please, [open an issue] with the
34 /// description of the error.
35 ///
36 /// [open an issue]: https://github.com/teloxide/teloxide/issues/new
37 #[error("An error while parsing JSON: {source} (raw: {raw:?})")]
38 InvalidJson {
39 #[source]
40 source: Arc<serde_json::Error>,
41 /// The raw string JSON that couldn't been parsed
42 raw: Box<str>,
43 },
44
45 /// Occurs when trying to send a file to Telegram.
46 #[error("An I/O error: {0}")]
47 Io(#[from] Arc<io::Error>),
48}
49
50/// An error caused by downloading a file.
51#[derive(Debug, Error, Clone)]
52pub enum DownloadError {
53 /// A network error while downloading a file from Telegram.
54 #[error("A network error: {0}")]
55 // NOTE: this variant must not be created by anything except the explicit From impl
56 Network(#[source] Arc<reqwest::Error>),
57
58 /// An I/O error while writing a file to destination.
59 #[error("An I/O error: {0}")]
60 Io(#[from] Arc<std::io::Error>),
61}
62
63pub trait AsResponseParameters {
64 fn response_parameters(&self) -> Option<ResponseParameters>;
65
66 fn retry_after(&self) -> Option<Seconds> {
67 self.response_parameters().and_then(|rp| match rp {
68 ResponseParameters::RetryAfter(n) => Some(n),
69 _ => None,
70 })
71 }
72
73 fn migrate_to_chat_id(&self) -> Option<ChatId> {
74 self.response_parameters().and_then(|rp| match rp {
75 ResponseParameters::MigrateToChatId(id) => Some(id),
76 _ => None,
77 })
78 }
79}
80
81impl AsResponseParameters for crate::RequestError {
82 fn response_parameters(&self) -> Option<ResponseParameters> {
83 match *self {
84 Self::RetryAfter(n) => Some(ResponseParameters::RetryAfter(n)),
85 Self::MigrateToChatId(id) => Some(ResponseParameters::MigrateToChatId(id)),
86 _ => None,
87 }
88 }
89}
90
91macro_rules! impl_api_error {
92 (
93 $( #[$meta:meta] )*
94 $vis:vis enum $ident:ident {
95 $(
96 $( #[$var_meta:meta] )*
97 $var_name:ident $( ($var_inner:ty) )? = $var_string:literal $(with $var_parser:expr)?
98 ),*
99 }
100 ) => {
101
102 $(#[$meta])*
103 #[derive(Error)]
104 $vis enum $ident {
105 $(
106 $(#[$var_meta])*
107 #[error($var_string)]
108 $var_name $(($var_inner))*,
109 )*
110 }
111
112 const _: () = {
113 struct Visitor;
114
115 impl<'de> ::serde::de::Visitor<'de> for Visitor {
116 type Value = $ident;
117
118 fn expecting(&self, formatter: &mut core::fmt::Formatter) -> core::fmt::Result {
119 formatter.write_str("telegram api error string")
120 }
121
122 fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
123 where
124 E: ::serde::de::Error,
125 {
126 $(impl_api_error!(@de v, $var_name $( ($var_inner) )?, $var_string $(, $var_parser)*);)*
127 Err(E::unknown_variant(v, &[]))
128 }
129 }
130
131 impl<'de> ::serde::de::Deserialize<'de> for $ident {
132 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
133 where
134 D: ::serde::de::Deserializer<'de>,
135 {
136 deserializer.deserialize_str(Visitor)
137 }
138 }
139 };
140 };
141 (@de $value:ident, $variant:ident, $val:literal) => {
142 if $value == $val {
143 return Ok(Self::Value::$variant)
144 }
145 };
146 (@de $value:ident, $variant:ident ($var_inner:ty), $val:literal, $block:expr) => {
147 #[allow(clippy::redundant_closure_call)]
148 match $block($value) {
149 Some(data) => return Ok(Self::Value::$variant(data)),
150 _ => {}
151 }
152 };
153 (@de $value:ident, $variant:ident, $val:literal, $block:expr) => {
154 #[allow(clippy::redundant_closure_call)]
155 if $block($value) {
156 return Ok(Self::Value::$variant);
157 }
158 };
159}
160
161impl_api_error! {
162 /// A kind of an API error.
163 #[derive(Debug, PartialEq, Hash, Eq, Clone)]
164 #[non_exhaustive]
165 pub enum ApiError {
166 /// Occurs when the bot tries to send message to user who blocked the bot.
167 BotBlocked = "Forbidden: bot was blocked by the user",
168
169 /// Occurs when the bot token is invalid.
170 // N.B. These errors are actually slightly different, "Unauthorized" is when the bot token
171 // is formatted mostly right, but is incorrect, whereas "Not Found" is when the url is
172 // not handled by TBA at all. From user POV both of those are "token is invalid", but
173 // there might be some cases where this is not right...
174 InvalidToken = "Invalid bot token" with |text: &str| text == "Unauthorized" || text == "Not Found",
175
176 /// Occurs when bot tries to modify a message without modification content.
177 ///
178 /// May happen in methods:
179 /// 1. [`EditMessageText`]
180 ///
181 /// [`EditMessageText`]: crate::payloads::EditMessageText
182 MessageNotModified = "Bad Request: message is not modified: specified new message content and reply markup are \
183 exactly the same as a current content and reply markup of the message",
184
185 /// Occurs when bot tries to forward or delete a message which was deleted.
186 ///
187 /// May happen in methods:
188 /// 1. [`ForwardMessage`]
189 /// 2. [`DeleteMessage`]
190 ///
191 /// [`ForwardMessage`]: crate::payloads::ForwardMessage
192 /// [`DeleteMessage`]: crate::payloads::DeleteMessage
193 MessageIdInvalid = "Bad Request: MESSAGE_ID_INVALID",
194
195 /// Occurs when bot tries to forward a message which does not exists.
196 ///
197 /// May happen in methods:
198 /// 1. [`ForwardMessage`]
199 ///
200 /// [`ForwardMessage`]: crate::payloads::ForwardMessage
201 MessageToForwardNotFound = "Bad Request: message to forward not found",
202
203 /// Occurs when bot tries to delete a message which does not exists.
204 ///
205 /// May happen in methods:
206 /// 1. [`DeleteMessage`]
207 ///
208 /// [`DeleteMessage`]: crate::payloads::DeleteMessage
209 MessageToDeleteNotFound = "Bad Request: message to delete not found",
210
211 /// Occurs when bot tries to copy a message which does not exists.
212 /// May happen in methods:
213 /// 1. [`CopyMessage`]
214 ///
215 /// [`CopyMessage`]: crate::payloads::CopyMessage
216 MessageToCopyNotFound = "Bad Request: message to copy not found",
217
218 /// Occurs when bot tries to send a text message without text.
219 ///
220 /// May happen in methods:
221 /// 1. [`SendMessage`]
222 ///
223 /// [`SendMessage`]: crate::payloads::SendMessage
224 MessageTextIsEmpty = "Bad Request: message text is empty",
225
226 /// Occurs when bot tries to edit a message after long time.
227 ///
228 /// May happen in methods:
229 /// 1. [`EditMessageText`]
230 ///
231 /// [`EditMessageText`]: crate::payloads::EditMessageText
232 MessageCantBeEdited = "Bad Request: message can't be edited",
233
234 /// Occurs when bot tries to delete a someone else's message in group where
235 /// it does not have enough rights.
236 ///
237 /// May happen in methods:
238 /// 1. [`DeleteMessage`]
239 ///
240 /// [`DeleteMessage`]: crate::payloads::DeleteMessage
241 MessageCantBeDeleted = "Bad Request: message can't be deleted",
242
243 /// Occurs when bot tries to edit a message which does not exists.
244 ///
245 /// May happen in methods:
246 /// 1. [`EditMessageText`]
247 ///
248 /// [`EditMessageText`]: crate::payloads::EditMessageText
249 MessageToEditNotFound = "Bad Request: message to edit not found",
250
251 /// Occurs when bot tries to edit a message which has no text.
252 ///
253 /// May happen in methods:
254 /// 1. [`EditMessageText`]
255 /// 2. [`EditMessageTextInline`]
256 ///
257 /// [`EditMessageText`]: crate::payloads::EditMessageText
258 /// [`EditMessageTextInline`]: crate::payloads::EditMessageTextInline
259 MessageToEditHasNoText = "Bad Request: there is no text in the message to edit",
260
261 /// Occurs when bot tries to reply to a message which does not exists.
262 ///
263 /// May happen in methods:
264 /// 1. [`SendMessage`]
265 ///
266 /// [`SendMessage`]: crate::payloads::SendMessage
267 MessageToReplyNotFound = "Bad Request: message to be replied not found",
268
269 /// Occurs when bot tries to
270 MessageIdentifierNotSpecified = "Bad Request: message identifier is not specified",
271
272 /// Occurs when bot tries to send a message with text size greater then
273 /// 4096 symbols.
274 ///
275 /// May happen in methods:
276 /// 1. [`SendMessage`]
277 ///
278 /// [`SendMessage`]: crate::payloads::SendMessage
279 MessageIsTooLong = "Bad Request: message is too long",
280
281 /// Occurs when bot tries to edit a message with text size greater then
282 /// 4096 symbols.
283 ///
284 /// May happen in methods:
285 /// 1. [`EditMessageText`]
286 /// 2. [`EditMessageTextInline`]
287 /// 3. [`EditMessageCaption`]
288 /// 4. [`EditMessageCaptionInline`]
289 ///
290 /// [`EditMessageText`]: crate::payloads::EditMessageText
291 /// [`EditMessageTextInline`]: crate::payloads::EditMessageTextInline
292 /// [`EditMessageCaption`]: crate::payloads::EditMessageCaption
293 /// [`EditMessageCaptionInline`]: crate::payloads::EditMessageCaptionInline
294 EditedMessageIsTooLong = "Bad Request: MESSAGE_TOO_LONG",
295
296 /// Occurs when bot tries to send media group with more than 10 items.
297 ///
298 /// May happen in methods:
299 /// 1. [`SendMediaGroup`]
300 ///
301 /// [`SendMediaGroup`]: crate::payloads::SendMediaGroup
302 TooMuchMessages = "Bad Request: Too much messages to send as an album",
303
304 /// Occurs when bot tries to answer an inline query with more than 50
305 /// results.
306 ///
307 /// Consider using offsets to paginate results.
308 ///
309 /// May happen in methods:
310 /// 1. [`AnswerInlineQuery`]
311 ///
312 /// [`AnswerInlineQuery`]: crate::payloads::AnswerInlineQuery
313 TooMuchInlineQueryResults = "Bad Request: RESULTS_TOO_MUCH",
314
315 /// Occurs when bot tries to stop poll that has already been stopped.
316 ///
317 /// May happen in methods:
318 /// 1. [`SendPoll`]
319 ///
320 /// [`SendPoll`]: crate::payloads::SendPoll
321 PollHasAlreadyClosed = "Bad Request: poll has already been closed",
322
323 /// Occurs when bot tries to send poll with less than 2 options.
324 ///
325 /// May happen in methods:
326 /// 1. [`SendPoll`]
327 ///
328 /// [`SendPoll`]: crate::payloads::SendPoll
329 PollMustHaveMoreOptions = "Bad Request: poll must have at least 2 option",
330
331 /// Occurs when bot tries to send poll with more than 12 options.
332 ///
333 /// May happen in methods:
334 /// 1. [`SendPoll`]
335 ///
336 /// [`SendPoll`]: crate::payloads::SendPoll
337 PollCantHaveMoreOptions = "Bad Request: poll can't have more than 12 options",
338
339 /// Occurs when bot tries to send poll with empty option (without text).
340 ///
341 /// May happen in methods:
342 /// 1. [`SendPoll`]
343 ///
344 /// [`SendPoll`]: crate::payloads::SendPoll
345 PollOptionsMustBeNonEmpty = "Bad Request: poll options must be non-empty",
346
347 /// Occurs when bot tries to send poll with empty question (without text).
348 ///
349 /// May happen in methods:
350 /// 1. [`SendPoll`]
351 ///
352 /// [`SendPoll`]: crate::payloads::SendPoll
353 PollQuestionMustBeNonEmpty = "Bad Request: poll question must be non-empty",
354
355 /// Occurs when bot tries to send poll with total size of options more than
356 /// 100 symbols.
357 ///
358 /// May happen in methods:
359 /// 1. [`SendPoll`]
360 ///
361 /// [`SendPoll`]: crate::payloads::SendPoll
362 PollOptionsLengthTooLong = "Bad Request: poll options length must not exceed 100",
363
364 /// Occurs when bot tries to send poll with question size more than 255
365 /// symbols.
366 ///
367 /// May happen in methods:
368 /// 1. [`SendPoll`]
369 ///
370 /// [`SendPoll`]: crate::payloads::SendPoll
371 PollQuestionLengthTooLong = "Bad Request: poll question length must not exceed 255",
372
373 /// Occurs when bot tries to stop poll with message without poll.
374 ///
375 /// May happen in methods:
376 /// 1. [`StopPoll`]
377 ///
378 /// [`StopPoll`]: crate::payloads::StopPoll
379 MessageWithPollNotFound = "Bad Request: message with poll to stop not found",
380
381 /// Occurs when bot tries to stop poll with message without poll.
382 ///
383 /// May happen in methods:
384 /// 1. [`StopPoll`]
385 ///
386 /// [`StopPoll`]: crate::payloads::StopPoll
387 MessageIsNotAPoll = "Bad Request: message is not a poll",
388
389 /// Occurs when bot tries to send a message to chat in which it is not a
390 /// member.
391 ///
392 /// May happen in methods:
393 /// 1. [`SendMessage`]
394 ///
395 /// [`SendMessage`]: crate::payloads::SendMessage
396 ChatNotFound = "Bad Request: chat not found",
397
398 /// Occurs when bot tries to send method with unknown user_id.
399 ///
400 /// May happen in methods:
401 /// 1. [`getUserProfilePhotos`]
402 ///
403 /// [`getUserProfilePhotos`]:
404 /// crate::payloads::GetUserProfilePhotos
405 UserNotFound = "Bad Request: user not found",
406
407 /// Occurs when bot tries to send [`SetChatDescription`] with same text as
408 /// in the current description.
409 ///
410 /// May happen in methods:
411 /// 1. [`SetChatDescription`]
412 ///
413 /// [`SetChatDescription`]: crate::payloads::SetChatDescription
414 ChatDescriptionIsNotModified = "Bad Request: chat description is not modified",
415
416 /// Occurs when bot tries to answer to query after timeout expire.
417 ///
418 /// May happen in methods:
419 /// 1. [`AnswerCallbackQuery`]
420 ///
421 /// [`AnswerCallbackQuery`]: crate::payloads::AnswerCallbackQuery
422 InvalidQueryId = "Bad Request: query is too old and response timeout expired or query id is invalid",
423
424 /// Occurs when bot tries to send InlineKeyboardMarkup with invalid button
425 /// url.
426 ///
427 /// May happen in methods:
428 /// 1. [`SendMessage`]
429 ///
430 /// [`SendMessage`]: crate::payloads::SendMessage
431 ButtonUrlInvalid = "Bad Request: BUTTON_URL_INVALID",
432
433 /// Occurs when bot tries to send button with data size more than 64 bytes.
434 ///
435 /// May happen in methods:
436 /// 1. [`SendMessage`]
437 ///
438 /// [`SendMessage`]: crate::payloads::SendMessage
439 ButtonDataInvalid = "Bad Request: BUTTON_DATA_INVALID",
440
441 /// Occurs when bot tries to send button with data size == 0.
442 ///
443 /// May happen in methods:
444 /// 1. [`SendMessage`]
445 ///
446 /// [`SendMessage`]: crate::payloads::SendMessage
447 TextButtonsAreUnallowed = "Bad Request: can't parse inline keyboard button: Text buttons are unallowed in the \
448 inline keyboard",
449
450 /// Occurs when bot tries to get file by wrong file id.
451 ///
452 /// May happen in methods:
453 /// 1. [`GetFile`]
454 ///
455 /// [`GetFile`]: crate::payloads::GetFile
456 WrongFileId = "Bad Request: wrong file id",
457
458 /// Occurs when bot tries to send files with wrong file identifier or HTTP
459 /// url
460 WrongFileIdOrUrl = "Bad Request: wrong file identifier/HTTP URL specified",
461
462 /// Occurs when When sending files with an url to a site that doesn't
463 /// respond.
464 FailedToGetUrlContent = "Bad Request: failed to get HTTP URL content",
465
466 /// Occurs when bot tries to do some with group which was deactivated.
467 GroupDeactivated = "Bad Request: group is deactivated",
468
469 /// Occurs when image processing fails on telegram's side.
470 ///
471 /// This is likely caused by an incorrectly encoded image, make sure that
472 /// the image is correctly encoded in a format telegram accepts.
473 ImageProcessFailed = "Bad Request: IMAGE_PROCESS_FAILED",
474
475 /// Occurs when bot tries to set chat photo from file ID
476 ///
477 /// May happen in methods:
478 /// 1. [`SetChatPhoto`]
479 ///
480 /// [`SetChatPhoto`]: crate::payloads::SetChatPhoto
481 PhotoAsInputFileRequired = "Bad Request: Photo should be uploaded as an InputFile",
482
483 /// Occurs when bot tries to add sticker to stickerset by invalid name.
484 ///
485 /// May happen in methods:
486 /// 1. [`AddStickerToSet`]
487 ///
488 /// [`AddStickerToSet`]: crate::payloads::AddStickerToSet
489 InvalidStickersSet = "Bad Request: STICKERSET_INVALID",
490
491 /// Occurs when bot tries to create a sticker set with a name that is
492 /// already used by another sticker set.
493 ///
494 /// May happen in methods:
495 /// 1. [`CreateNewStickerSet`]
496 ///
497 /// [`CreateNewStickerSet`]: crate::payloads::CreateNewStickerSet
498 StickerSetNameOccupied = "Bad Request: sticker set name is already occupied",
499
500 /// Occurs when bot tries to create a sticker set with user id of a bot.
501 ///
502 /// May happen in methods:
503 /// 1. [`CreateNewStickerSet`]
504 ///
505 /// [`CreateNewStickerSet`]: crate::payloads::CreateNewStickerSet
506 StickerSetOwnerIsBot = "Bad Request: USER_IS_BOT",
507
508 /// Occurs when bot tries to create a sticker set with invalid name.
509 ///
510 /// From documentation of [`CreateNewStickerSet`]:
511 /// > Short name of sticker set, to be used in `t.me/addstickers/` URLs
512 /// (e.g., _animals_). Can contain only english letters, digits and
513 /// underscores. Must begin with a letter, can't contain consecutive
514 /// underscores and must end in “\_by\_<bot\_username>”. <bot\_username>
515 /// is case insensitive. 1-64 characters.
516 ///
517 /// May happen in methods:
518 /// 1. [`CreateNewStickerSet`]
519 ///
520 /// [`CreateNewStickerSet`]: crate::payloads::CreateNewStickerSet
521 InvalidStickerName = "Bad Request: invalid sticker set name is specified",
522
523 /// Occurs when bot tries to pin a message without rights to pin in this
524 /// chat.
525 ///
526 /// May happen in methods:
527 /// 1. [`PinChatMessage`]
528 ///
529 /// [`PinChatMessage`]: crate::payloads::PinChatMessage
530 NotEnoughRightsToPinMessage = "Bad Request: not enough rights to pin a message",
531
532 /// Occurs when bot tries to pin or unpin a message without rights to pin
533 /// in this chat.
534 ///
535 /// May happen in methods:
536 /// 1. [`PinChatMessage`]
537 /// 2. [`UnpinChatMessage`]
538 ///
539 /// [`PinChatMessage`]: crate::payloads::PinChatMessage
540 /// [`UnpinChatMessage`]: crate::payloads::UnpinChatMessage
541 NotEnoughRightsToManagePins = "Bad Request: not enough rights to manage pinned messages in the chat",
542
543 /// Occurs when bot tries change default chat permissions without "Ban
544 /// Users" permission in this chat.
545 ///
546 /// May happen in methods:
547 /// 1. [`SetChatPermissions`]
548 ///
549 /// [`SetChatPermissions`]: crate::payloads::SetChatPermissions
550 NotEnoughRightsToChangeChatPermissions = "Bad Request: not enough rights to change chat permissions",
551
552 /// Occurs when bot tries to use method in group which is allowed only in a
553 /// supergroup or channel.
554 MethodNotAvailableInPrivateChats = "Bad Request: method is available only for supergroups and channel",
555
556 /// Occurs when bot tries to demote chat creator.
557 ///
558 /// May happen in methods:
559 /// 1. [`PromoteChatMember`]
560 ///
561 /// [`PromoteChatMember`]: crate::payloads::PromoteChatMember
562 CantDemoteChatCreator = "Bad Request: can't demote chat creator",
563
564 /// Occurs when bot tries to restrict self in group chats.
565 ///
566 /// May happen in methods:
567 /// 1. [`RestrictChatMember`]
568 ///
569 /// [`RestrictChatMember`]: crate::payloads::RestrictChatMember
570 CantRestrictSelf = "Bad Request: can't restrict self",
571
572 /// Occurs when bot tries to restrict chat member without rights to
573 /// restrict in this chat.
574 ///
575 /// May happen in methods:
576 /// 1. [`RestrictChatMember`]
577 ///
578 /// [`RestrictChatMember`]: crate::payloads::RestrictChatMember
579 NotEnoughRightsToRestrict = "Bad Request: not enough rights to restrict/unrestrict chat member",
580
581 /// Occurs when bot tries to post a message in a channel without "Post
582 /// Messages" admin right.
583 NotEnoughRightsToPostMessages = "Bad Request: need administrator rights in the channel chat",
584
585 /// Occurs when bot tries to get a chat member with an invalid
586 /// participant ID.
587 ///
588 /// May happen in methods:
589 /// 1. [`GetChatMember`]
590 ///
591 /// [`GetChatMember`]: crate::payloads::GetChatMember
592 ParticipantIdInvalid = "Bad Request: PARTICIPANT_ID_INVALID",
593
594 /// Occurs when bot tries to perform an action that requires admin
595 /// privileges in the chat.
596 ///
597 /// May happen in methods:
598 /// 1. [`GetChatMember`]
599 ///
600 /// [`GetChatMember`]: crate::payloads::GetChatMember
601 ChatAdminRequired = "Bad Request: CHAT_ADMIN_REQUIRED",
602
603 /// Occurs when bot tries set webhook to protocol other than HTTPS.
604 ///
605 /// May happen in methods:
606 /// 1. [`SetWebhook`]
607 ///
608 /// [`SetWebhook`]: crate::payloads::SetWebhook
609 WebhookRequireHttps = "Bad Request: bad webhook: HTTPS url must be provided for webhook",
610
611 /// Occurs when bot tries to set webhook to port other than 80, 88, 443 or
612 /// 8443.
613 ///
614 /// May happen in methods:
615 /// 1. [`SetWebhook`]
616 ///
617 /// [`SetWebhook`]: crate::payloads::SetWebhook
618 BadWebhookPort = "Bad Request: bad webhook: Webhook can be set up only on ports 80, 88, 443 or 8443",
619
620 /// Occurs when bot tries to set webhook to unknown host.
621 ///
622 /// May happen in methods:
623 /// 1. [`SetWebhook`]
624 ///
625 /// [`SetWebhook`]: crate::payloads::SetWebhook
626 UnknownHost = "Bad Request: bad webhook: Failed to resolve host: Name or service not known",
627
628 /// Occurs when bot tries to set webhook to invalid URL.
629 ///
630 /// May happen in methods:
631 /// 1. [`SetWebhook`]
632 ///
633 /// [`SetWebhook`]: crate::payloads::SetWebhook
634 CantParseUrl = "Bad Request: can't parse URL",
635
636 /// Occurs when bot tries to send message with unfinished entities.
637 ///
638 /// May happen in methods:
639 /// 1. [`SendMessage`]
640 ///
641 /// [`SendMessage`]: crate::payloads::SendMessage
642 CantParseEntities(String) = "{0}" with |text: &str| {
643 if text.starts_with("Bad Request: can't parse entities") {
644 Some(text.to_owned())
645 } else {
646 None
647 }
648 },
649
650 /// Occurs when bot tries to use getUpdates while webhook is active.
651 ///
652 /// May happen in methods:
653 /// 1. [`GetUpdates`]
654 ///
655 /// [`GetUpdates`]: crate::payloads::GetUpdates
656 CantGetUpdates = "can't use getUpdates method while webhook is active",
657
658 /// Occurs when bot tries to do some in group where bot was kicked.
659 ///
660 /// May happen in methods:
661 /// 1. [`SendMessage`]
662 ///
663 /// [`SendMessage`]: crate::payloads::SendMessage
664 BotKicked = "Unauthorized: bot was kicked from a chat",
665
666 /// Occurs when bot tries to do something in a supergroup the bot was
667 /// kicked from.
668 ///
669 /// May happen in methods:
670 /// 1. [`SendMessage`]
671 ///
672 /// [`SendMessage`]: crate::payloads::SendMessage
673 BotKickedFromSupergroup = "Forbidden: bot was kicked from the supergroup chat",
674
675 /// Occurs when bot tries to do something in a channel the bot was
676 /// kicked from.
677 ///
678 /// May happen in methods:
679 /// 1. [`SendMessage`]
680 ///
681 /// [`SendMessage`]: crate::payloads::SendMessage
682 BotKickedFromChannel = "Forbidden: bot was kicked from the channel chat",
683
684 /// Occurs when bot tries to send a message to a deactivated user (i.e. a
685 /// user that was banned by telegram).
686 ///
687 /// May happen in methods:
688 /// 1. [`SendMessage`]
689 ///
690 /// [`SendMessage`]: crate::payloads::SendMessage
691 UserDeactivated = "Forbidden: user is deactivated",
692
693 /// Occurs when you tries to initiate conversation with a user.
694 ///
695 /// May happen in methods:
696 /// 1. [`SendMessage`]
697 ///
698 /// [`SendMessage`]: crate::payloads::SendMessage
699 CantInitiateConversation = "Forbidden: bot can't initiate conversation with a user",
700
701 /// Occurs when you tries to send message to bot.
702 ///
703 /// May happen in methods:
704 /// 1. [`SendMessage`]
705 ///
706 /// [`SendMessage`]: crate::payloads::SendMessage
707 CantTalkWithBots = "Unauthorized: bot can't send messages to bots",
708
709 /// Occurs when bot tries to send button with invalid http url.
710 ///
711 /// May happen in methods:
712 /// 1. [`SendMessage`]
713 ///
714 /// [`SendMessage`]: crate::payloads::SendMessage
715 WrongHttpUrl = "Bad Request: wrong HTTP URL",
716
717 /// Occurs when multiple [`GetUpdates`] calls happen at the same time.
718 ///
719 /// This can happen if
720 /// 1. You are running multiple bot instances (including on different servers/hosting platforms)
721 /// 2. You are running multiple update consumers (like `Dispatcher` or `repl`)
722 /// 3. You are calling [`GetUpdates`] yourself and the second call is done before the first one finishes
723 ///
724 /// May happen in methods:
725 /// 1. [`GetUpdates`]
726 ///
727 /// [`GetUpdates`]: crate::payloads::GetUpdates
728 TerminatedByOtherGetUpdates = "Conflict: terminated by other getUpdates request; make sure that only one bot instance \
729 is running",
730
731 /// Occurs when bot tries to get file by invalid file id.
732 ///
733 /// May happen in methods:
734 /// 1. [`GetFile`]
735 ///
736 /// [`GetFile`]: crate::payloads::GetFile
737 FileIdInvalid = "Bad Request: invalid file id",
738
739 /// Occurs when bot tries to upload a file which is larger than 50 MB using
740 /// multipart/form-data.
741 ///
742 /// May happen in methods:
743 /// 1. [`SendVideo`]
744 /// 2. [`SendDocument`]
745 ///
746 /// [`SendVideo`]: crate::payloads::SendVideo
747 /// [`SendDocument`]: crate::payloads::SendDocument
748 RequestEntityTooLarge = "Request Entity Too Large",
749
750
751 /// Error which is not known to `teloxide`.
752 ///
753 /// If you've received this error, please [open an issue] with the
754 /// description of the error.
755 ///
756 /// [open an issue]: https://github.com/teloxide/teloxide/issues/new
757 Unknown(String) = "Unknown error: {0:?}" with |text: &str| Some(text.to_owned())
758 }
759}
760
761/// This impl allows to use `?` to propagate [`DownloadError`]s in function
762/// returning [`RequestError`]s. For example:
763///
764/// ```rust
765/// # use teloxide_core::errors::{DownloadError, RequestError};
766///
767/// async fn handler() -> Result<(), RequestError> {
768/// download_file().await?; // `?` just works
769///
770/// Ok(())
771/// }
772///
773/// async fn download_file() -> Result<(), DownloadError> {
774/// /* download file here */
775/// Ok(())
776/// }
777/// ```
778impl From<DownloadError> for RequestError {
779 fn from(download_err: DownloadError) -> Self {
780 match download_err {
781 DownloadError::Network(err) => RequestError::Network(err),
782 DownloadError::Io(err) => RequestError::Io(err),
783 }
784 }
785}
786
787impl From<reqwest::Error> for DownloadError {
788 fn from(error: reqwest::Error) -> Self {
789 DownloadError::Network(Arc::new(hide_token(error)))
790 }
791}
792
793impl From<std::io::Error> for DownloadError {
794 fn from(error: std::io::Error) -> Self {
795 DownloadError::Io(Arc::new(error))
796 }
797}
798
799impl From<reqwest::Error> for RequestError {
800 fn from(error: reqwest::Error) -> Self {
801 RequestError::Network(Arc::new(hide_token(error)))
802 }
803}
804
805/// Replaces token in the url in the error with `token:redacted` string.
806pub(crate) fn hide_token(mut error: reqwest::Error) -> reqwest::Error {
807 let url = match error.url_mut() {
808 Some(url) => url,
809 None => return error,
810 };
811
812 if let Some(mut segments) = url.path_segments() {
813 // Usually the url looks like "bot<token>/..." or "file/bot<token>/...".
814 let (beginning, segment) = match segments.next() {
815 Some("file") => ("file/", segments.next()),
816 segment => ("", segment),
817 };
818
819 if let Some(token) = segment.and_then(|s| s.strip_prefix("bot")) {
820 // make sure that what we are about to delete looks like a bot token
821 if let Some((id, secret)) = token.split_once(':') {
822 // The part before the : in the token is the id of the bot.
823 let id_character = |c: char| c.is_ascii_digit();
824
825 // The part after the : in the token is the secret.
826 //
827 // In all bot tokens we could find the secret is 35 characters long and is
828 // 0-9a-zA-Z_- only.
829 //
830 // It would be nice to research if TBA always has 35 character secrets or if it
831 // is just a coincidence.
832 const SECRET_LENGTH: usize = 35;
833 let secret_character = |c: char| c.is_ascii_alphanumeric() || c == '-' || c == '_';
834
835 if secret.len() >= SECRET_LENGTH
836 && id.chars().all(id_character)
837 && secret.chars().all(secret_character)
838 {
839 // found token, hide only the token
840 let without_token =
841 &url.path()[(beginning.len() + "/bot".len() + token.len())..];
842 let redacted = format!("{beginning}token:redacted{without_token}");
843
844 url.set_path(&redacted);
845 return error;
846 }
847 }
848 }
849 }
850
851 // couldn't find token in the url, hide the whole url
852 error.without_url()
853}
854
855#[cfg(test)]
856mod tests {
857 #[test]
858 fn custom_result() {
859 use super::ApiError;
860 use serde::Deserialize;
861
862 let cases = &[
863 ("{\"data\": \"Forbidden: bot was blocked by the user\"}", ApiError::BotBlocked),
864 ("{\"data\": \"Unauthorized\"}", ApiError::InvalidToken),
865 ("{\"data\": \"Not Found\"}", ApiError::InvalidToken),
866 (
867 "{\"data\": \"Bad Request: message is not modified: specified new message content \
868 and reply markup are exactly the same as a current content and reply markup of \
869 the message\"}",
870 ApiError::MessageNotModified,
871 ),
872 ("{\"data\": \"Bad Request: MESSAGE_ID_INVALID\"}", ApiError::MessageIdInvalid),
873 (
874 "{\"data\": \"Bad Request: message to forward not found\"}",
875 ApiError::MessageToForwardNotFound,
876 ),
877 (
878 "{\"data\": \"Bad Request: message to delete not found\"}",
879 ApiError::MessageToDeleteNotFound,
880 ),
881 (
882 "{\"data\": \"Bad Request: message to copy not found\"}",
883 ApiError::MessageToCopyNotFound,
884 ),
885 ("{\"data\": \"Bad Request: message text is empty\"}", ApiError::MessageTextIsEmpty),
886 ("{\"data\": \"Bad Request: message can't be edited\"}", ApiError::MessageCantBeEdited),
887 (
888 "{\"data\": \"Bad Request: message can't be deleted\"}",
889 ApiError::MessageCantBeDeleted,
890 ),
891 (
892 "{\"data\": \"Bad Request: message to edit not found\"}",
893 ApiError::MessageToEditNotFound,
894 ),
895 (
896 "{\"data\": \"Bad Request: there is no text in the message to edit\"}",
897 ApiError::MessageToEditHasNoText,
898 ),
899 (
900 "{\"data\": \"Bad Request: message to be replied not found\"}",
901 ApiError::MessageToReplyNotFound,
902 ),
903 (
904 "{\"data\": \"Bad Request: message identifier is not specified\"}",
905 ApiError::MessageIdentifierNotSpecified,
906 ),
907 ("{\"data\": \"Bad Request: message is too long\"}", ApiError::MessageIsTooLong),
908 ("{\"data\": \"Bad Request: MESSAGE_TOO_LONG\"}", ApiError::EditedMessageIsTooLong),
909 (
910 "{\"data\": \"Bad Request: Too much messages to send as an album\"}",
911 ApiError::TooMuchMessages,
912 ),
913 ("{\"data\": \"Bad Request: RESULTS_TOO_MUCH\"}", ApiError::TooMuchInlineQueryResults),
914 (
915 "{\"data\": \"Bad Request: poll has already been closed\"}",
916 ApiError::PollHasAlreadyClosed,
917 ),
918 (
919 "{\"data\": \"Bad Request: poll must have at least 2 option\"}",
920 ApiError::PollMustHaveMoreOptions,
921 ),
922 (
923 "{\"data\": \"Bad Request: poll can't have more than 12 options\"}",
924 ApiError::PollCantHaveMoreOptions,
925 ),
926 (
927 "{\"data\": \"Bad Request: poll options must be non-empty\"}",
928 ApiError::PollOptionsMustBeNonEmpty,
929 ),
930 (
931 "{\"data\": \"Bad Request: poll question must be non-empty\"}",
932 ApiError::PollQuestionMustBeNonEmpty,
933 ),
934 (
935 "{\"data\": \"Bad Request: poll options length must not exceed 100\"}",
936 ApiError::PollOptionsLengthTooLong,
937 ),
938 (
939 "{\"data\": \"Bad Request: poll question length must not exceed 255\"}",
940 ApiError::PollQuestionLengthTooLong,
941 ),
942 (
943 "{\"data\": \"Bad Request: message with poll to stop not found\"}",
944 ApiError::MessageWithPollNotFound,
945 ),
946 ("{\"data\": \"Bad Request: message is not a poll\"}", ApiError::MessageIsNotAPoll),
947 ("{\"data\": \"Bad Request: chat not found\"}", ApiError::ChatNotFound),
948 ("{\"data\": \"Bad Request: user not found\"}", ApiError::UserNotFound),
949 (
950 "{\"data\": \"Bad Request: chat description is not modified\"}",
951 ApiError::ChatDescriptionIsNotModified,
952 ),
953 (
954 "{\"data\": \"Bad Request: query is too old and response timeout expired or query \
955 id is invalid\"}",
956 ApiError::InvalidQueryId,
957 ),
958 ("{\"data\": \"Bad Request: BUTTON_URL_INVALID\"}", ApiError::ButtonUrlInvalid),
959 ("{\"data\": \"Bad Request: BUTTON_DATA_INVALID\"}", ApiError::ButtonDataInvalid),
960 (
961 "{\"data\": \"Bad Request: can't parse inline keyboard button: Text buttons are \
962 unallowed in the inline keyboard\"}",
963 ApiError::TextButtonsAreUnallowed,
964 ),
965 ("{\"data\": \"Bad Request: wrong file id\"}", ApiError::WrongFileId),
966 (
967 "{\"data\": \"Bad Request: wrong file identifier/HTTP URL specified\"}",
968 ApiError::WrongFileIdOrUrl,
969 ),
970 (
971 "{\"data\": \"Bad Request: failed to get HTTP URL content\"}",
972 ApiError::FailedToGetUrlContent,
973 ),
974 ("{\"data\": \"Bad Request: group is deactivated\"}", ApiError::GroupDeactivated),
975 ("{\"data\": \"Bad Request: IMAGE_PROCESS_FAILED\"}", ApiError::ImageProcessFailed),
976 (
977 "{\"data\": \"Bad Request: Photo should be uploaded as an InputFile\"}",
978 ApiError::PhotoAsInputFileRequired,
979 ),
980 ("{\"data\": \"Bad Request: STICKERSET_INVALID\"}", ApiError::InvalidStickersSet),
981 (
982 "{\"data\": \"Bad Request: sticker set name is already occupied\"}",
983 ApiError::StickerSetNameOccupied,
984 ),
985 ("{\"data\": \"Bad Request: USER_IS_BOT\"}", ApiError::StickerSetOwnerIsBot),
986 (
987 "{\"data\": \"Bad Request: invalid sticker set name is specified\"}",
988 ApiError::InvalidStickerName,
989 ),
990 (
991 "{\"data\": \"Bad Request: not enough rights to pin a message\"}",
992 ApiError::NotEnoughRightsToPinMessage,
993 ),
994 (
995 "{\"data\": \"Bad Request: not enough rights to manage pinned messages in the \
996 chat\"}",
997 ApiError::NotEnoughRightsToManagePins,
998 ),
999 (
1000 "{\"data\": \"Bad Request: not enough rights to change chat permissions\"}",
1001 ApiError::NotEnoughRightsToChangeChatPermissions,
1002 ),
1003 (
1004 "{\"data\": \"Bad Request: method is available only for supergroups and channel\"}",
1005 ApiError::MethodNotAvailableInPrivateChats,
1006 ),
1007 (
1008 "{\"data\": \"Bad Request: can't demote chat creator\"}",
1009 ApiError::CantDemoteChatCreator,
1010 ),
1011 ("{\"data\": \"Bad Request: can't restrict self\"}", ApiError::CantRestrictSelf),
1012 (
1013 "{\"data\": \"Bad Request: not enough rights to restrict/unrestrict chat member\"}",
1014 ApiError::NotEnoughRightsToRestrict,
1015 ),
1016 (
1017 "{\"data\": \"Bad Request: need administrator rights in the channel chat\"}",
1018 ApiError::NotEnoughRightsToPostMessages,
1019 ),
1020 ("{\"data\": \"Bad Request: PARTICIPANT_ID_INVALID\"}", ApiError::ParticipantIdInvalid),
1021 ("{\"data\": \"Bad Request: CHAT_ADMIN_REQUIRED\"}", ApiError::ChatAdminRequired),
1022 (
1023 "{\"data\": \"Bad Request: bad webhook: HTTPS url must be provided for webhook\"}",
1024 ApiError::WebhookRequireHttps,
1025 ),
1026 (
1027 "{\"data\": \"Bad Request: bad webhook: Webhook can be set up only on ports 80, \
1028 88, 443 or 8443\"}",
1029 ApiError::BadWebhookPort,
1030 ),
1031 (
1032 "{\"data\": \"Bad Request: bad webhook: Failed to resolve host: Name or service \
1033 not known\"}",
1034 ApiError::UnknownHost,
1035 ),
1036 ("{\"data\": \"Bad Request: can't parse URL\"}", ApiError::CantParseUrl),
1037 (
1038 "{\"data\": \"Bad Request: can't parse entities: SomeRandomString\"}",
1039 ApiError::CantParseEntities(
1040 "Bad Request: can't parse entities: SomeRandomString".to_owned(),
1041 ),
1042 ),
1043 (
1044 "{\"data\": \"can't use getUpdates method while webhook is active\"}",
1045 ApiError::CantGetUpdates,
1046 ),
1047 ("{\"data\": \"Unauthorized: bot was kicked from a chat\"}", ApiError::BotKicked),
1048 (
1049 "{\"data\": \"Forbidden: bot was kicked from the supergroup chat\"}",
1050 ApiError::BotKickedFromSupergroup,
1051 ),
1052 ("{\"data\": \"Forbidden: user is deactivated\"}", ApiError::UserDeactivated),
1053 (
1054 "{\"data\": \"Forbidden: bot can't initiate conversation with a user\"}",
1055 ApiError::CantInitiateConversation,
1056 ),
1057 (
1058 "{\"data\": \"Unauthorized: bot can't send messages to bots\"}",
1059 ApiError::CantTalkWithBots,
1060 ),
1061 ("{\"data\": \"Bad Request: wrong HTTP URL\"}", ApiError::WrongHttpUrl),
1062 (
1063 "{\"data\": \"Conflict: terminated by other getUpdates request; make sure that \
1064 only one bot instance is running\"}",
1065 ApiError::TerminatedByOtherGetUpdates,
1066 ),
1067 ("{\"data\": \"Bad Request: invalid file id\"}", ApiError::FileIdInvalid),
1068 ("{\"data\": \"Request Entity Too Large\"}", ApiError::RequestEntityTooLarge),
1069 ("{\"data\": \"RandomError\"}", ApiError::Unknown("RandomError".to_string())),
1070 ];
1071
1072 #[derive(Deserialize, Debug)]
1073 struct Res<T> {
1074 data: T,
1075 }
1076
1077 for (data, expected) in cases {
1078 let raw = serde_json::from_str::<Res<String>>(data).unwrap().data;
1079 let parsed = serde_json::from_str::<Res<ApiError>>(data).unwrap().data;
1080 assert_eq!(&parsed, expected);
1081
1082 let expected_error_message = match parsed {
1083 ApiError::Unknown(_) => {
1084 format!("Unknown error: \"{raw}\"")
1085 }
1086 ApiError::InvalidToken => "Invalid bot token".to_owned(),
1087 _ => raw,
1088 };
1089 assert_eq!(parsed.to_string(), expected_error_message);
1090 }
1091 }
1092}