1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
use crate::types::login_url::LoginUrl;
use serde::{Deserialize, Serialize};
use serde_json::{Error as JsonError, Value as JsonValue};
use std::{error::Error as StdError, fmt};

/// Inline keyboard that appears right next to the message it belongs to
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct InlineKeyboardMarkup {
    inline_keyboard: Vec<Vec<InlineKeyboardButton>>,
}

impl InlineKeyboardMarkup {
    /// Returns a KeyboardMarkup with given keyboard
    pub fn from_vec(inline_keyboard: Vec<Vec<InlineKeyboardButton>>) -> Self {
        InlineKeyboardMarkup { inline_keyboard }
    }

    /// Adds a row to keyboard
    pub fn row(mut self, row: Vec<InlineKeyboardButton>) -> Self {
        self.inline_keyboard.push(row);
        self
    }

    pub(crate) fn serialize(&self) -> Result<String, InlineKeyboardError> {
        serde_json::to_string(self).map_err(InlineKeyboardError::SerializeMarkup)
    }
}

impl From<Vec<Vec<InlineKeyboardButton>>> for InlineKeyboardMarkup {
    fn from(keyboard: Vec<Vec<InlineKeyboardButton>>) -> InlineKeyboardMarkup {
        InlineKeyboardMarkup::from_vec(keyboard)
    }
}

/// Button of an inline keyboard
///
/// You must use exactly one of the optional fields
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct InlineKeyboardButton {
    text: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    url: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    callback_data: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    switch_inline_query: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    switch_inline_query_current_chat: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    callback_game: Option<JsonValue>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pay: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    login_url: Option<LoginUrl>,
}

impl InlineKeyboardButton {
    /// HTTP or tg:// url to be opened when button is pressed
    pub fn with_url<S: Into<String>>(text: S, url: S) -> Self {
        InlineKeyboardButton {
            text: text.into(),
            url: Some(url.into()),
            callback_data: None,
            switch_inline_query: None,
            switch_inline_query_current_chat: None,
            callback_game: None,
            pay: None,
            login_url: None,
        }
    }

    /// Data to be sent in a callback query to the bot when button is pressed, 1-64 bytes
    pub fn with_callback_data<S: Into<String>>(text: S, callback_data: S) -> Self {
        InlineKeyboardButton {
            text: text.into(),
            url: None,
            callback_data: Some(callback_data.into()),
            switch_inline_query: None,
            switch_inline_query_current_chat: None,
            callback_game: None,
            pay: None,
            login_url: None,
        }
    }

    /// Same as with_callback_data, but takes a serializable type
    ///
    /// Data will be serialized using serde_json
    pub fn with_callback_data_struct<S: Into<String>, D: Serialize>(
        text: S,
        callback_data: &D,
    ) -> Result<Self, InlineKeyboardError> {
        Ok(InlineKeyboardButton {
            text: text.into(),
            url: None,
            callback_data: Some(
                serde_json::to_string(callback_data).map_err(InlineKeyboardError::SerializeCallbackData)?,
            ),
            switch_inline_query: None,
            switch_inline_query_current_chat: None,
            callback_game: None,
            pay: None,
            login_url: None,
        })
    }

    /// 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
    ///
    /// Note: This offers an easy way for users to start using your bot
    /// in inline mode when they are currently in a private chat with it
    ///
    /// Especially useful when combined with switch_pm… actions – in this case the user
    /// will be automatically returned to the chat they switched from,
    /// skipping the chat selection screen
    pub fn with_switch_inline_query<S: Into<String>>(text: S, switch_inline_query: S) -> Self {
        InlineKeyboardButton {
            text: text.into(),
            url: None,
            callback_data: None,
            switch_inline_query: Some(switch_inline_query.into()),
            switch_inline_query_current_chat: None,
            callback_game: None,
            pay: None,
            login_url: None,
        }
    }

    /// If set, pressing the button will insert the bot‘s username and
    /// the specified inline query in the current chat's input field
    ///
    /// Can be empty, in which case only the bot’s username will be inserted
    /// This offers a quick way for the user to open your bot in
    /// inline mode in the same chat – good for selecting something from multiple options
    pub fn with_switch_inline_query_current_chat<S: Into<String>>(
        text: S,
        switch_inline_query_current_chat: S,
    ) -> Self {
        InlineKeyboardButton {
            text: text.into(),
            url: None,
            callback_data: None,
            switch_inline_query: None,
            switch_inline_query_current_chat: Some(switch_inline_query_current_chat.into()),
            callback_game: None,
            pay: None,
            login_url: None,
        }
    }

    /// Description of the game that will be launched when the user presses the button
    ///
    /// NOTE: This type of button must always be the first button in the first row
    pub fn with_callback_game<S: Into<String>>(text: S) -> Self {
        InlineKeyboardButton {
            text: text.into(),
            url: None,
            callback_data: None,
            switch_inline_query: None,
            switch_inline_query_current_chat: None,
            callback_game: Some(serde_json::json!({})),
            pay: None,
            login_url: None,
        }
    }

    /// Send a Pay button
    ///
    /// NOTE: This type of button must always be the first button in the first row
    pub fn with_pay<S: Into<String>>(text: S) -> Self {
        InlineKeyboardButton {
            text: text.into(),
            url: None,
            callback_data: None,
            switch_inline_query: None,
            switch_inline_query_current_chat: None,
            callback_game: None,
            pay: Some(true),
            login_url: None,
        }
    }

    /// An HTTP URL used to automatically authorize the user
    ///
    /// Can be used as a replacement for the [Telegram Login Widget][1]
    ///
    /// [1]: https://core.telegram.org/widgets/login
    pub fn with_login_url<T, U>(text: T, login_url: U) -> Self
    where
        T: Into<String>,
        U: Into<LoginUrl>,
    {
        InlineKeyboardButton {
            text: text.into(),
            url: None,
            callback_data: None,
            switch_inline_query: None,
            switch_inline_query_current_chat: None,
            callback_game: None,
            pay: None,
            login_url: Some(login_url.into()),
        }
    }
}

/// An error occurred with inline keyboard
#[derive(Debug)]
pub enum InlineKeyboardError {
    /// Can not serialize callback data
    SerializeCallbackData(JsonError),
    /// Can not serialize markup
    SerializeMarkup(JsonError),
}

impl StdError for InlineKeyboardError {
    fn source(&self) -> Option<&(dyn StdError + 'static)> {
        use self::InlineKeyboardError::*;
        Some(match self {
            SerializeCallbackData(err) => err,
            SerializeMarkup(err) => err,
        })
    }
}

impl fmt::Display for InlineKeyboardError {
    fn fmt(&self, out: &mut fmt::Formatter) -> fmt::Result {
        use self::InlineKeyboardError::*;
        match self {
            SerializeCallbackData(err) => write!(out, "failed to serialize callback data: {}", err),
            SerializeMarkup(err) => write!(out, "failed to serialize markup: {}", err),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::types::ReplyMarkup;

    #[derive(Serialize)]
    struct CallbackData {
        value: String,
    }

    #[test]
    fn serialize() {
        let callback_data = CallbackData {
            value: String::from("cdstruct"),
        };

        let markup: ReplyMarkup = vec![vec![
            InlineKeyboardButton::with_url("url", "tg://user?id=1"),
            InlineKeyboardButton::with_callback_data("cd", "cd"),
            InlineKeyboardButton::with_callback_data_struct("cd", &callback_data).unwrap(),
            InlineKeyboardButton::with_switch_inline_query("siq", "siq"),
            InlineKeyboardButton::with_switch_inline_query_current_chat("siqcc", "siqcc"),
            InlineKeyboardButton::with_callback_game("cg"),
            InlineKeyboardButton::with_pay("pay"),
            InlineKeyboardButton::with_login_url("login url", "http://example.com"),
        ]]
        .into();
        let data = serde_json::to_value(&markup).unwrap();
        assert_eq!(
            data,
            serde_json::json!({
                "inline_keyboard": [
                    [
                        {"text":"url","url":"tg://user?id=1"},
                        {"text":"cd","callback_data":"cd"},
                        {"text":"cd","callback_data":"{\"value\":\"cdstruct\"}"},
                        {"text":"siq","switch_inline_query":"siq"},
                        {"text":"siqcc","switch_inline_query_current_chat":"siqcc"},
                        {"text":"cg","callback_game":{}},
                        {"text":"pay","pay":true},
                        {"text":"login url","login_url":{"url":"http://example.com"}}
                    ]
                ]
            })
        );
    }

    #[test]
    fn deserialize() {
        let buttons: Vec<InlineKeyboardButton> = serde_json::from_value(serde_json::json!(
            [
                {"text":"url","url":"tg://user?id=1"},
                {"text":"cd","callback_data":"cd"},
                {"text":"cd","callback_data":"{\"value\":\"cdstruct\"}"},
                {"text":"siq","switch_inline_query":"siq"},
                {"text":"siqcc","switch_inline_query_current_chat":"siqcc"},
                {"text":"cg","callback_game":{}},
                {"text":"pay","pay":true},
                {"text":"login url","login_url":{"url":"http://example.com"}}
            ]
        ))
        .unwrap();
        assert_eq!(buttons.len(), 8);
        assert_eq!(buttons[0].text, "url");
        assert_eq!(buttons[1].text, "cd");
        assert_eq!(buttons[2].text, "cd");
        assert_eq!(buttons[3].text, "siq");
        assert_eq!(buttons[4].text, "siqcc");
        assert_eq!(buttons[5].text, "cg");
        assert_eq!(buttons[6].text, "pay");
        assert_eq!(buttons[7].text, "login url");
    }
}