Skip to main content

telegrambot/types/
reply_markup.rs

1use std::ops::Not;
2
3use serde::ser::{Serialize, Serializer};
4
5use crate::types::primitive::True;
6
7#[derive(Debug, Clone, PartialEq, PartialOrd)]
8pub enum ReplyMarkup {
9  InlineKeyboardMarkup(InlineKeyboardMarkup),
10  ReplyKeyboardMarkup(ReplyKeyboardMarkup),
11  ReplyKeyboardRemove(ReplyKeyboardRemove),
12  ForceReply(ForceReply),
13}
14
15impl From<InlineKeyboardMarkup> for ReplyMarkup {
16  fn from(value: InlineKeyboardMarkup) -> ReplyMarkup {
17    ReplyMarkup::InlineKeyboardMarkup(value)
18  }
19}
20
21impl From<ReplyKeyboardMarkup> for ReplyMarkup {
22  fn from(value: ReplyKeyboardMarkup) -> ReplyMarkup {
23    ReplyMarkup::ReplyKeyboardMarkup(value)
24  }
25}
26
27impl From<ReplyKeyboardRemove> for ReplyMarkup {
28  fn from(value: ReplyKeyboardRemove) -> ReplyMarkup {
29    ReplyMarkup::ReplyKeyboardRemove(value)
30  }
31}
32
33impl From<ForceReply> for ReplyMarkup {
34  fn from(value: ForceReply) -> ReplyMarkup {
35    ReplyMarkup::ForceReply(value)
36  }
37}
38
39impl Serialize for ReplyMarkup {
40  fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer {
41    match *self {
42      ReplyMarkup::InlineKeyboardMarkup(ref value) => value.serialize(serializer),
43      ReplyMarkup::ReplyKeyboardMarkup(ref value) => value.serialize(serializer),
44      ReplyMarkup::ReplyKeyboardRemove(ref value) => value.serialize(serializer),
45      ReplyMarkup::ForceReply(ref value) => value.serialize(serializer),
46    }
47  }
48}
49
50/// This object represents a custom keyboard with reply options.
51#[derive(Debug, Clone, PartialEq, PartialOrd, Serialize)]
52pub struct ReplyKeyboardMarkup {
53  keyboard: Vec<Vec<KeyboardButton>>,
54  #[serde(skip_serializing_if = "Not::not")]
55  resize_keyboard: bool,
56  #[serde(skip_serializing_if = "Not::not")]
57  one_time_keyboard: bool,
58  #[serde(skip_serializing_if = "Not::not")]
59  selective: bool,
60}
61
62impl ReplyKeyboardMarkup {
63  pub fn new() -> Self {
64    ReplyKeyboardMarkup {
65      keyboard: Vec::new(),
66      resize_keyboard: false,
67      one_time_keyboard: false,
68      selective: false,
69    }
70  }
71
72  fn init(rows: Vec<Vec<KeyboardButton>>) -> Self {
73    let mut keyboard = Self::new();
74    keyboard.keyboard = rows;
75    keyboard
76  }
77
78  /// Requests clients to resize the keyboard vertically for
79  /// optimal fit (e.g., make the keyboard smaller if there
80  /// are just two rows of buttons). Defaults to false, in which case
81  /// the custom keyboard is always of the same height as the app's standard keyboard.
82  pub fn resize_keyboard(&mut self) -> &mut Self {
83    self.resize_keyboard = true;
84    self
85  }
86
87  /// Requests clients to hide the keyboard as soon as it's been used.
88  /// The keyboard will still be available, but clients will automatically
89  /// display the usual letter-keyboard in the chat – the user can
90  /// press a special button in the input field to see the custom
91  /// keyboard again. Defaults to false.
92  pub fn one_time_keyboard(&mut self) -> &mut Self {
93    self.one_time_keyboard = true;
94    self
95  }
96
97  /// Use this method if you want to force reply from specific users only.
98  /// Targets: 1) users that are @mentioned in the text of
99  /// the Message object; 2) if the bot's message is a reply (has reply_to_message_id),
100  /// sender of the original message.
101  pub fn selective(&mut self) -> &mut Self {
102    self.selective = true;
103    self
104  }
105
106  pub fn add_row(&mut self, row: Vec<KeyboardButton>) -> &mut Vec<KeyboardButton> {
107    self.keyboard.push(row);
108    self.keyboard.last_mut().unwrap()
109  }
110
111  pub fn add_empty_row(&mut self) -> &mut Vec<KeyboardButton> {
112    self.add_row(Default::default())
113  }
114}
115
116impl From<Vec<Vec<KeyboardButton>>> for ReplyKeyboardMarkup {
117  fn from(value: Vec<Vec<KeyboardButton>>) -> Self { Self::init(value) }
118}
119
120/// This object represents one button of the reply keyboard.
121#[derive(Debug, Clone, PartialEq, PartialOrd, Serialize)]
122pub struct KeyboardButton {
123  text: String,
124  #[serde(skip_serializing_if = "Not::not")]
125  request_contact: bool,
126  #[serde(skip_serializing_if = "Not::not")]
127  request_location: bool,
128}
129
130impl KeyboardButton {
131  pub fn new<S: AsRef<str>>(text: S) -> Self {
132    Self {
133      text: text.as_ref().to_string(),
134      request_contact: false,
135      request_location: false,
136    }
137  }
138
139  /// The user's phone number will be sent as a contact when the
140  /// button is pressed. Available in private chats only
141  pub fn request_contact(&mut self) -> &mut Self {
142    self.request_location = false;
143    self.request_contact = true;
144    self
145  }
146
147  /// The user's current location will be sent when the
148  /// button is pressed. Available in private chats only
149  pub fn request_location(&mut self) -> &mut Self {
150    self.request_contact = false;
151    self.request_location = true;
152    self
153  }
154}
155
156impl<'a> From<&'a str> for KeyboardButton {
157  fn from(value: &'a str) -> KeyboardButton {
158    KeyboardButton::new(value)
159  }
160}
161
162impl From<String> for KeyboardButton {
163  fn from(value: String) -> KeyboardButton {
164    KeyboardButton::new(value)
165  }
166}
167
168/// Upon receiving a message with this object, Telegram clients will remove
169/// the current custom keyboard and display the default letter-keyboard.
170/// By default, custom keyboards are displayed until a new keyboard is sent
171/// by a bot. An exception is made for one-time keyboards that are hidden
172/// immediately after the user presses a button (see ReplyKeyboardMarkup).
173#[derive(Debug, Clone, PartialEq, PartialOrd, Serialize)]
174pub struct ReplyKeyboardRemove {
175  remove_keyboard: True,
176  #[serde(skip_serializing_if = "Not::not")]
177  selective: bool,
178}
179
180impl ReplyKeyboardRemove {
181  pub fn new() -> Self {
182    Self {
183      remove_keyboard: True,
184      selective: false,
185    }
186  }
187
188  /// Use this method if you want to force reply from specific users only.
189  /// Targets: 1) users that are @mentioned in the text of
190  /// the Message object; 2) if the bot's message is a reply (has reply_to_message_id),
191  /// sender of the original message.
192  pub fn selective(&mut self) -> &mut Self {
193    self.selective = true;
194    self
195  }
196}
197
198/// This object represents an inline keyboard that appears right next to the message it belongs to.
199#[derive(Debug, Clone, PartialEq, PartialOrd, Serialize)]
200pub struct InlineKeyboardMarkup {
201  inline_keyboard: Vec<Vec<InlineKeyboardButton>>
202}
203
204impl InlineKeyboardMarkup {
205  pub fn new() -> Self {
206    Self {
207      inline_keyboard: Default::default(),
208    }
209  }
210
211  fn init(inline_keyboard: Vec<Vec<InlineKeyboardButton>>) -> Self {
212    Self {
213      inline_keyboard,
214    }
215  }
216
217  pub fn add_row(&mut self, row: Vec<InlineKeyboardButton>) -> &mut Vec<InlineKeyboardButton> {
218    self.inline_keyboard.push(row);
219    self.inline_keyboard.last_mut().unwrap()
220  }
221
222  pub fn add_empty_row(&mut self) -> &mut Vec<InlineKeyboardButton> {
223    self.add_row(Default::default())
224  }
225}
226
227impl From<Vec<Vec<InlineKeyboardButton>>> for InlineKeyboardMarkup {
228  fn from(value: Vec<Vec<InlineKeyboardButton>>) -> Self { Self::init(value) }
229}
230
231/// This object represents one button of an inline keyboard.
232#[derive(Debug, Clone, PartialEq, PartialOrd)]
233pub struct InlineKeyboardButton {
234  text: String,
235  kind: InlineKeyboardButtonKind,
236}
237
238impl InlineKeyboardButton {
239  /// Data to be sent in a callback query to the bot when button is pressed, 1-64 bytes
240  pub fn callback<T: AsRef<str>, C: AsRef<str>>(text: T, callback: C) -> Self {
241    Self {
242      text: text.as_ref().to_string(),
243      kind: InlineKeyboardButtonKind::CallbackData(callback.as_ref().to_string()),
244    }
245  }
246}
247
248impl Serialize for InlineKeyboardButton {
249  fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer {
250    use self::InlineKeyboardButtonKind::*;
251
252    let mut raw = InlineKeyboardButtonRaw {
253      text: &self.text,
254      url: None,
255      callback_data: None,
256      switch_inline_query: None,
257      switch_inline_query_current_chat: None,
258//            callback_game: None,
259    };
260
261    match self.kind {
262//            Url(ref data) => raw.url = Some(data),
263      CallbackData(ref data) => raw.callback_data = Some(data),
264//            SwitchInlineQuery(ref data) => raw.switch_inline_query = Some(data),
265//            SwitchInlineQueryCurrentChat(ref data) => raw.switch_inline_query_current_chat = Some(data),
266//            CallbackGame(ref data) => raw.callback_game = Some(data),
267    }
268
269    Serialize::serialize(&raw, serializer)
270  }
271}
272
273#[derive(Debug, Clone, PartialEq, PartialOrd)]
274pub enum InlineKeyboardButtonKind {
275  //    Url(String), // TODO(knsd): Url?
276  CallbackData(String),  //TODO(knsd) Validate size?
277//    SwitchInlineQuery(String),
278//    SwitchInlineQueryCurrentChat(String),
279//    CallbackGame(CallbackGame),
280}
281
282#[derive(Debug, Clone, PartialEq, PartialOrd, Serialize)]
283struct InlineKeyboardButtonRaw<'a> {
284  text: &'a str,
285  #[serde(skip_serializing_if = "Option::is_none")]
286  url: Option<&'a str>,
287  // TODO(knsd): Url?
288  #[serde(skip_serializing_if = "Option::is_none")]
289  callback_data: Option<&'a str>,
290  //TODO(knsd) Validate size?
291  #[serde(skip_serializing_if = "Option::is_none")]
292  switch_inline_query: Option<&'a str>,
293  #[serde(skip_serializing_if = "Option::is_none")]
294  switch_inline_query_current_chat: Option<&'a str>,
295//    callback_game: Option<CallbackGame>,
296}
297
298/// Upon receiving a message with this object, Telegram clients will
299/// display a reply interface to the user (act as if the user has
300/// selected the bot‘s message and tapped ’Reply'). This can be
301/// extremely useful if you want to create user-friendly step-by-step
302/// interfaces without having to sacrifice privacy mod
303#[derive(Debug, Clone, PartialEq, PartialOrd, Serialize)]
304pub struct ForceReply {
305  force_reply: True,
306  #[serde(skip_serializing_if = "Not::not")]
307  selective: bool,
308}
309
310impl ForceReply {
311  pub fn new() -> Self {
312    Self {
313      force_reply: True,
314      selective: false,
315    }
316  }
317
318  /// Use this method if you want to force reply from specific users only.
319  /// Targets: 1) users that are @mentioned in the text of
320  /// the Message object; 2) if the bot's message is a reply (has reply_to_message_id),
321  /// sender of the original message.
322  pub fn selective(&mut self) -> &mut Self {
323    self.selective = true;
324    self
325  }
326}