telbot_types/markup.rs
1use serde::{Deserialize, Serialize};
2
3use crate::user::User;
4
5/// This object represents a [custom keyboard](https://core.telegram.org/bots#keyboards) with reply options
6/// (see [Introduction to bots](https://core.telegram.org/bots#keyboards) for details and examples).
7#[derive(Debug, Clone, Serialize, Deserialize)]
8pub struct ReplyKeyboardMarkup {
9 /// Array of button rows, each represented by an Array of [KeyboardButton](https://core.telegram.org/bots/api#keyboardbutton) objects
10 pub keyboard: Vec<Vec<KeyboardButton>>,
11 /// Requests clients to resize the keyboard vertically for optimal fit
12 // (e.g., make the keyboard smaller if there are just two rows of buttons).
13 /// Defaults to false, in which case the custom keyboard is always of the same height as the app's standard keyboard.
14 #[serde(skip_serializing_if = "Option::is_none")]
15 pub reisze_keyboard: Option<bool>,
16 /// Requests clients to hide the keyboard as soon as it's been used.
17 /// The keyboard will still be available, but clients will automatically display the usual letter-keyboard in the chat
18 /// – the user can press a special button in the input field to see the custom keyboard again.
19 /// Defaults to _false_.
20 #[serde(skip_serializing_if = "Option::is_none")]
21 pub one_time_keyboard: Option<bool>,
22 /// The placeholder to be shown in the input field when the keyboard is active; 1-64 characters
23 #[serde(skip_serializing_if = "Option::is_none")]
24 pub input_field_placeholder: Option<String>,
25 /// Use this parameter if you want to show the keyboard to specific users only.
26 ///
27 /// Targets:
28 /// 1) users that are @mentioned in the text of the [Message](https://core.telegram.org/bots/api#message) object;
29 /// 2) if the bot's message is a reply (has *reply_to_message_id*), sender of the original message.
30 ///
31 /// Example: A user requests to change the bot's language, bot replies to the request with a keyboard to select the new language.
32 /// Other users in the group don't see the keyboard.
33 #[serde(skip_serializing_if = "Option::is_none")]
34 pub selective: Option<bool>,
35}
36
37/// This object represents one button of the reply keyboard.
38/// For simple text buttons *String* can be used instead of this object to specify text of the button.
39/// Optional fields *request_contact*, *request_location*, and *request_poll* are mutually exclusive.
40///
41/// # Note
42/// - *request_contact* and *request_location* options will only work in Telegram versions released after 9 April, 2016.
43/// Older clients will display *unsupported message*.
44/// - *request_poll* option will only work in Telegram versions released after 23 January, 2020.
45/// Older clients will display *unsupported message*.
46#[derive(Debug, Clone, Serialize, Deserialize)]
47pub struct KeyboardButton {
48 /// Text of the button. If none of the optional fields are used,
49 /// it will be sent as a message when the button is pressed
50 pub text: String,
51 /// If True, the user's phone number will be sent as a contact when the button is pressed.
52 /// Available in private chats only
53 #[serde(skip_serializing_if = "Option::is_none")]
54 request_contact: Option<bool>,
55 /// If True, the user's current location will be sent when the button is pressed.
56 /// Available in private chats only
57 #[serde(skip_serializing_if = "Option::is_none")]
58 request_location: Option<bool>,
59 /// If specified, the user will be asked to create a poll and send it to the bot when the button is pressed.
60 /// Available in private chats only
61 #[serde(skip_serializing_if = "Option::is_none")]
62 request_poll: Option<KeyboardButtonPollType>,
63}
64
65/// This object represents type of a poll, which is allowed to be created and sent when the corresponding button is pressed.
66#[derive(Debug, Clone, Serialize, Deserialize)]
67pub struct KeyboardButtonPollType {
68 /// If *quiz* is passed, the user will be allowed to create only polls in the quiz mode.
69 /// If *regular* is passed, only regular polls will be allowed.
70 /// Otherwise, the user will be allowed to create a poll of any type.
71 #[serde(rename = "type")]
72 #[serde(skip_serializing_if = "Option::is_none")]
73 kind: Option<String>,
74}
75
76/// Upon receiving a message with this object, Telegram clients will remove the current custom keyboard and display the default letter-keyboard.
77///
78/// By default, custom keyboards are displayed until a new keyboard is sent by a bot.
79/// An exception is made for one-time keyboards that are hidden immediately after the user presses a button (see ReplyKeyboardMarkup).
80#[derive(Debug, Clone, Serialize, Deserialize)]
81pub struct ReplyKeyboardRemove {
82 /// Requests clients to remove the custom keyboard
83 /// (user will not be able to summon this keyboard;
84 /// if you want to hide the keyboard from sight but keep it accessible, use *one_time_keyboard* in
85 /// [ReplyKeyboardMarkup](https://core.telegram.org/bots/api#replykeyboardmarkup))
86 remove_keyboard: bool,
87 /// Use this parameter if you want to show the keyboard to specific users only.
88 ///
89 /// Targets:
90 /// 1) users that are @mentioned in the text of the [Message](https://core.telegram.org/bots/api#message) object;
91 /// 2) if the bot's message is a reply (has *reply_to_message_id*), sender of the original message.
92 ///
93 /// Example: A user requests to change the bot's language, bot replies to the request with a keyboard to select the new language.
94 /// Other users in the group don't see the keyboard.
95 #[serde(skip_serializing_if = "Option::is_none")]
96 pub selective: Option<bool>,
97}
98
99/// This object represents an [inline keyboard](https://core.telegram.org/bots#inline-keyboards-and-on-the-fly-updating)
100/// that appears right next to the message it belongs to.
101#[derive(Debug, Clone, Serialize, Deserialize)]
102pub struct InlineKeyboardMarkup {
103 /// Array of button rows, each represented by an Array of [InlineKeyboardButton](https://core.telegram.org/bots/api#inlinekeyboardbutton) objects
104 pub inline_keyboard: Vec<Vec<InlineKeyboardButton>>,
105}
106
107impl InlineKeyboardMarkup {
108 /// Create a new InlineKeyboardMarkup with a row.
109 pub fn new_with_row(row: InlineKeyboardRow) -> Self {
110 Self {
111 inline_keyboard: vec![row.buttons],
112 }
113 }
114
115 /// Add a row
116 pub fn with_row(mut self, row: InlineKeyboardRow) -> Self {
117 self.inline_keyboard.push(row.buttons);
118 self
119 }
120}
121
122#[derive(Clone)]
123pub struct InlineKeyboardRow {
124 pub buttons: Vec<InlineKeyboardButton>,
125}
126
127impl InlineKeyboardRow {
128 /// Create a new InlineKeyboardRow
129 pub fn new_with(button: InlineKeyboardButton) -> Self {
130 Self {
131 buttons: vec![button],
132 }
133 }
134 /// Create a new InlineKeyboardRow, emplacing a new button
135 pub fn new_emplace(text: impl Into<String>, kind: InlineKeyboardButtonKind) -> Self {
136 Self {
137 buttons: vec![InlineKeyboardButton {
138 text: text.into(),
139 kind,
140 }],
141 }
142 }
143 /// Add a InlineKeyboardButton to the row
144 pub fn with(mut self, button: InlineKeyboardButton) -> Self {
145 self.buttons.push(button);
146 self
147 }
148 /// Create and add a InlineKeyboardButton to the row
149 pub fn emplace(mut self, text: impl Into<String>, kind: InlineKeyboardButtonKind) -> Self {
150 self.buttons.push(InlineKeyboardButton {
151 text: text.into(),
152 kind,
153 });
154 self
155 }
156}
157
158/// This object represents one button of an inline keyboard.
159#[derive(Debug, Clone, Serialize, Deserialize)]
160pub struct InlineKeyboardButton {
161 /// Label text on the button
162 pub text: String,
163 /// Button type
164 #[serde(flatten)]
165 pub kind: InlineKeyboardButtonKind,
166}
167
168/// Inline keyboard button type
169#[derive(Debug, Clone, Serialize, Deserialize)]
170#[serde(untagged)]
171pub enum InlineKeyboardButtonKind {
172 Url {
173 /// HTTP or tg:// url to be opened when button is pressed
174 url: String,
175 },
176 Login {
177 /// An HTTP URL used to automatically authorize the user.
178 /// Can be used as a replacement for the [Telegram Login Widget](https://core.telegram.org/widgets/login).
179 login_url: LoginUrl,
180 },
181 Callback {
182 /// Data to be sent in a [callback query](https://core.telegram.org/bots/api#callbackquery) to the bot when button is pressed, 1-64 bytes
183 callback_data: String,
184 },
185 SwitchInlineQuery {
186 /// If set, pressing the button will prompt the user to select one of their chats, open that chat and insert the bot's username and the specified inline query in the input field. Can be empty, in which case just the bot's username will be inserted.
187 ///
188 /// **Note:** This offers an easy way for users to start using your bot in [inline mode](https://core.telegram.org/bots/inline)
189 /// when they are currently in a private chat with it.
190 /// Especially useful when combined with [*switch_pm…*](https://core.telegram.org/bots/api#answerinlinequery) actions
191 /// – in this case the user will be automatically returned to the chat they switched from, skipping the chat selection screen.
192 switch_inline_query: String,
193 },
194 SwitchInlineQueryCurrentChat {
195 /// If set, pressing the button will insert the bot's username and the specified inline query in the current chat's input field.
196 /// Can be empty, in which case only the bot's username will be inserted.
197 ///
198 /// This offers a quick way for the user to open your bot in inline mode in the same chat
199 /// – good for selecting something from multiple options.
200 switch_inline_query_current_chat: String,
201 },
202 CallbackGame {
203 /// Description of the game that will be launched when the user presses the button.
204 ///
205 /// **NOTE:** This type of button **must** always be the first button in the first row.
206 callback_game: CallbackGame,
207 },
208 Pay {
209 /// Specify True, to send a Pay button.
210 ///
211 /// **NOTE:** This type of button **must** always be the first button in the first row.
212 pay: bool,
213 },
214}
215
216impl InlineKeyboardButtonKind {
217 pub fn url(&self) -> Option<&str> {
218 match self {
219 Self::Url { url } => Some(url),
220 _ => None,
221 }
222 }
223
224 pub fn login_url(&self) -> Option<&LoginUrl> {
225 match self {
226 Self::Login { login_url } => Some(login_url),
227 _ => None,
228 }
229 }
230
231 pub fn callback_data(&self) -> Option<&str> {
232 match self {
233 Self::Callback { callback_data } => Some(&callback_data),
234 _ => None,
235 }
236 }
237
238 pub fn inline_query_prompt(&self) -> Option<&str> {
239 match self {
240 Self::SwitchInlineQuery {
241 switch_inline_query,
242 } => Some(switch_inline_query),
243 _ => None,
244 }
245 }
246
247 pub fn inline_query_current_chat_prompt(&self) -> Option<&str> {
248 match self {
249 Self::SwitchInlineQueryCurrentChat {
250 switch_inline_query_current_chat,
251 } => Some(switch_inline_query_current_chat),
252 _ => None,
253 }
254 }
255
256 pub fn is_url(&self) -> bool {
257 matches!(self, Self::Url { .. })
258 }
259
260 pub fn is_login(&self) -> bool {
261 matches!(self, Self::Login { .. })
262 }
263
264 pub fn is_callback(&self) -> bool {
265 matches!(self, Self::Callback { .. })
266 }
267
268 pub fn is_switch_inline_query(&self) -> bool {
269 matches!(self, Self::SwitchInlineQuery { .. })
270 }
271
272 pub fn is_switch_inline_query_current_chat(&self) -> bool {
273 matches!(self, Self::SwitchInlineQueryCurrentChat { .. })
274 }
275
276 pub fn is_callback_game(&self) -> bool {
277 matches!(self, Self::CallbackGame { .. })
278 }
279
280 pub fn is_pay(&self) -> bool {
281 match self {
282 Self::Pay { pay } => *pay,
283 _ => false,
284 }
285 }
286}
287
288/// A placeholder, currently holds no information. Use [BotFather](https://t.me/botfather) to set up your game.
289#[derive(Debug, Clone, Serialize, Deserialize)]
290pub struct CallbackGame;
291
292/// This object represents a parameter of the inline keyboard button used to automatically authorize a user.
293///
294/// Serves as a great replacement for the [Telegram Login Widget](https://core.telegram.org/widgets/login)
295/// when the user is coming from Telegram.
296/// All the user needs to do is tap/click a button and confirm that they want to log in:
297/// 
298/// Telegram apps support buttons as of [version 5.7](https://telegram.org/blog/privacy-discussions-web-bots#meet-seamless-web-bots)
299/// > Sample bot: [@discussbot](https://t.me/discussbot)
300#[derive(Debug, Clone, Serialize, Deserialize)]
301pub struct LoginUrl {
302 /// An HTTP URL to be opened with user authorization data added to the query string when the button is pressed.
303 ///
304 /// If the user refuses to provide authorization data, the original URL without information about the user will be opened.
305 /// The data added is the same as described in [Receiving authorization data](https://core.telegram.org/widgets/login#receiving-authorization-data).
306 ///
307 /// **NOTE:** You **must** always check the hash of the received data to verify the authentication
308 /// and the integrity of the data as described in [Checking authorization](https://core.telegram.org/widgets/login#checking-authorization).
309 pub url: String,
310 /// New text of the button in forwarded messages.
311 #[serde(skip_serializing_if = "Option::is_none")]
312 pub forward_text: Option<String>,
313 /// Username of a bot, which will be used for user authorization.
314 /// See Setting up a bot for more details.
315 /// If not specified, the current bot's username will be assumed.
316 /// The url's domain must be the same as the domain linked with the bot.
317 /// See Linking your domain to the bot for more details.
318 #[serde(skip_serializing_if = "Option::is_none")]
319 pub bot_username: Option<String>,
320 /// Pass True to request the permission for your bot to send messages to the user.
321 #[serde(skip_serializing_if = "Option::is_none")]
322 pub request_write_access: Option<bool>,
323}
324
325/// Upon receiving a message with this object, Telegram clients will display a reply interface to the user
326/// (act as if the user has selected the bot's message and tapped 'Reply').
327///
328/// This can be extremely useful if you want to create user-friendly step-by-step interfaces without having to sacrifice privacy mode.
329///
330/// > **Example:** A poll bot for groups runs in privacy mode (only receives commands, replies to its messages and mentions).
331/// > There could be two ways to create a new poll:
332/// >
333/// > - Explain the user how to send a command with parameters (e.g. /newpoll question answer1 answer2).
334/// > May be appealing for hardcore users but lacks modern day polish.
335/// >
336/// > - Guide the user through a step-by-step process.
337/// > 'Please send me your question', 'Cool, now let's add the first answer option',
338/// > 'Great. Keep adding answer options, then send /done when you're ready'.
339/// >
340/// > The last option is definitely more attractive.
341/// > And if you use [ForceReply](https://core.telegram.org/bots/api#forcereply) in your bot's questions,
342/// > it will receive the user's answers even if it only receives replies, commands and mentions
343/// > — without any extra work for the user.
344
345#[derive(Debug, Clone, Serialize, Deserialize)]
346pub struct ForceReply {
347 /// Shows reply interface to the user, as if they manually selected the bot's message and tapped 'Reply'
348 force_reply: bool,
349 /// The placeholder to be shown in the input field when the reply is active; 1-64 characters
350 #[serde(skip_serializing_if = "Option::is_none")]
351 pub input_field_placeholder: Option<String>,
352 /// Use this parameter if you want to show the keyboard to specific users only.
353 ///
354 /// Targets:
355 /// 1) users that are @mentioned in the text of the [Message](https://core.telegram.org/bots/api#message) object;
356 /// 2) if the bot's message is a reply (has *reply_to_message_id*), sender of the original message.
357 ///
358 /// Example: A user requests to change the bot's language, bot replies to the request with a keyboard to select the new language.
359 /// Other users in the group don't see the keyboard.
360 #[serde(skip_serializing_if = "Option::is_none")]
361 pub selective: Option<bool>,
362}
363
364#[derive(Debug, Clone, Serialize, Deserialize, Copy, PartialEq, Eq, Hash)]
365pub enum ParseMode {
366 MarkdownV2,
367 HTML,
368 Markdown,
369}
370
371impl ParseMode {
372 /// Escape text to fit to given parse mode
373 pub fn escape(&self, text: impl AsRef<str>) -> String {
374 match self {
375 Self::MarkdownV2 => Self::escape_markdown_v2(text.as_ref()),
376 Self::HTML => Self::escape_html(text.as_ref()),
377 Self::Markdown => Self::escape_markdown(text.as_ref()),
378 }
379 }
380
381 fn escape_markdown_v2(text: &str) -> String {
382 const ESCAPE_CHARS: [char; 18] = [
383 '_', '*', '[', ']', '(', ')', '~', '`', '>', '#', '+', '-', '=', '|', '{', '}', '.',
384 '!',
385 ];
386 let mut output = String::with_capacity(text.len());
387 let mut block_begin = 0;
388 for (index, char) in text.char_indices() {
389 if ESCAPE_CHARS.contains(&char) {
390 output.push_str(&text[block_begin..index]);
391 output.push('\\');
392 output.push(char);
393 block_begin = index + 1;
394 }
395 }
396 if block_begin < text.len() {
397 output.push_str(&text[block_begin..]);
398 }
399 output
400 }
401
402 fn escape_html(text: &str) -> String {
403 let mut output = String::with_capacity(text.len());
404 let mut block_begin = 0;
405 for (index, char) in text.char_indices() {
406 let replacement = match char {
407 '<' => Some("<"),
408 '>' => Some(">"),
409 '&' => Some("&"),
410 _ => None,
411 };
412 if let Some(replacement) = replacement {
413 output.push_str(&text[block_begin..index]);
414 output.push_str(replacement);
415 block_begin = index + 1;
416 }
417 }
418 if block_begin < text.len() {
419 output.push_str(&text[block_begin..]);
420 }
421 output
422 }
423
424 fn escape_markdown(text: &str) -> String {
425 const ESCAPE_CHARS: [char; 4] = ['_', '*', '`', '['];
426 let mut output = String::with_capacity(text.len());
427 let mut block_begin = 0;
428 for (index, char) in text.char_indices() {
429 if ESCAPE_CHARS.contains(&char) {
430 output.push_str(&text[block_begin..index]);
431 output.push('\\');
432 output.push(char);
433 block_begin = index + 1;
434 }
435 }
436 if block_begin < text.len() {
437 output.push_str(&text[block_begin..]);
438 }
439 output
440 }
441}
442
443/// This object represents one special entity in a text message.
444///
445/// For example, hashtags, usernames, URLs, etc.
446#[derive(Debug, Clone, Serialize, Deserialize)]
447pub struct MessageEntity {
448 /// Type of the entity
449 #[serde(flatten)]
450 pub kind: MessageEntityKind,
451 /// Offset in UTF-16 code units to the start of the entity
452 pub offset: usize,
453 /// Length of the entity in UTF-16 code units
454 pub length: usize,
455}
456
457/// Type of the message entity
458#[derive(Debug, Clone, Serialize, Deserialize)]
459#[serde(rename_all = "snake_case", tag = "type")]
460pub enum MessageEntityKind {
461 /// `@username`
462 Mention,
463 /// `#hashtag`
464 Hashtag,
465 /// `$USD`
466 Cashtag,
467 /// `/start@jobs_bot`
468 BotCommand,
469 /// `https://telegram.org`
470 Url,
471 /// `do-not-reply@telegram.org`
472 Email,
473 /// `+1-212-555-0123`
474 PhoneNumber,
475 /// **bold text**
476 Bold,
477 /// *italic text*
478 Italic,
479 /// <ins>underlined text</ins>
480 Underline,
481 /// ~strikethrough text~
482 Strikethrough,
483 /// `monowidth string`
484 Code,
485 /// ```monowidth block```
486 Pre {
487 /// The programming language of the entity text
488 language: String,
489 },
490 /// clickable text URLs
491 TextLink {
492 /// Url that will be opened after user taps on the text
493 url: String,
494 },
495 /// mention for users [without usernames](https://telegram.org/blog/edit#new-mentions)
496 TextMention {
497 /// The mentioned user
498 user: User,
499 },
500 /// spoiler message
501 Spoiler,
502}
503
504impl MessageEntityKind {
505 pub fn code_language(&self) -> Option<&str> {
506 match self {
507 Self::Pre { language } => Some(language),
508 _ => None,
509 }
510 }
511
512 pub fn clickable_url(&self) -> Option<&str> {
513 match self {
514 Self::TextLink { url } => Some(url),
515 _ => None,
516 }
517 }
518
519 pub fn text_metioned_user(&self) -> Option<&User> {
520 match self {
521 Self::TextMention { user } => Some(user),
522 _ => None,
523 }
524 }
525
526 pub fn is_mention(&self) -> bool {
527 matches!(self, Self::Mention)
528 }
529
530 pub fn is_hashtag(&self) -> bool {
531 matches!(self, Self::Hashtag)
532 }
533
534 pub fn is_cashtag(&self) -> bool {
535 matches!(self, Self::Cashtag)
536 }
537
538 pub fn is_bot_command(&self) -> bool {
539 matches!(self, Self::BotCommand)
540 }
541
542 pub fn is_url(&self) -> bool {
543 matches!(self, Self::Url)
544 }
545
546 pub fn is_email(&self) -> bool {
547 matches!(self, Self::Email)
548 }
549
550 pub fn is_phone_number(&self) -> bool {
551 matches!(self, Self::PhoneNumber)
552 }
553
554 pub fn is_bold(&self) -> bool {
555 matches!(self, Self::Bold)
556 }
557 pub fn is_italic(&self) -> bool {
558 matches!(self, Self::Italic)
559 }
560
561 pub fn is_underline(&self) -> bool {
562 matches!(self, Self::Underline)
563 }
564
565 pub fn is_strikethrough(&self) -> bool {
566 matches!(self, Self::Strikethrough)
567 }
568
569 pub fn is_inline_code(&self) -> bool {
570 matches!(self, Self::Code)
571 }
572
573 pub fn is_code_block(&self) -> bool {
574 matches!(self, Self::Pre { .. })
575 }
576
577 pub fn is_clickable_link(&self) -> bool {
578 matches!(self, Self::TextLink { .. })
579 }
580
581 pub fn is_text_mention(&self) -> bool {
582 matches!(self, Self::TextMention { .. })
583 }
584}
585
586/// Reply markups
587#[derive(Clone, Serialize)]
588#[serde(untagged)]
589pub enum ReplyMarkup {
590 InlineKeyboard(InlineKeyboardMarkup),
591 ReplyKeyboard(ReplyKeyboardMarkup),
592 RemoveReplyKeyboard(ReplyKeyboardRemove),
593 ForceReply(ForceReply),
594}
595
596impl From<InlineKeyboardMarkup> for ReplyMarkup {
597 fn from(markup: InlineKeyboardMarkup) -> Self {
598 Self::InlineKeyboard(markup)
599 }
600}
601
602impl From<ReplyKeyboardMarkup> for ReplyMarkup {
603 fn from(markup: ReplyKeyboardMarkup) -> Self {
604 Self::ReplyKeyboard(markup)
605 }
606}
607
608impl From<ReplyKeyboardRemove> for ReplyMarkup {
609 fn from(markup: ReplyKeyboardRemove) -> Self {
610 Self::RemoveReplyKeyboard(markup)
611 }
612}
613
614impl From<ForceReply> for ReplyMarkup {
615 fn from(markup: ForceReply) -> Self {
616 Self::ForceReply(markup)
617 }
618}