tgbot/types/reply/markup/
mod.rs

1use std::{error::Error, fmt};
2
3use serde::{Deserialize, Serialize};
4use serde_json::Error as JsonError;
5
6pub use self::{force_reply::*, inline_keyboard::*, reply_keyboard::*};
7
8mod force_reply;
9mod inline_keyboard;
10mod reply_keyboard;
11
12/// Represents a reply markup.
13#[derive(Clone, Debug, derive_more::From, Deserialize, PartialEq, Serialize)]
14#[serde(untagged)]
15pub enum ReplyMarkup {
16    /// A force reply
17    ForceReply(ForceReply),
18    /// An inline keyboard
19    InlineKeyboardMarkup(InlineKeyboardMarkup),
20    /// A custom keyboard with reply options
21    ReplyKeyboardMarkup(ReplyKeyboardMarkup),
22    /// A remove keyboard
23    ReplyKeyboardRemove(ReplyKeyboardRemove),
24}
25
26impl ReplyMarkup {
27    pub(crate) fn serialize(&self) -> Result<String, ReplyMarkupError> {
28        serde_json::to_string(self).map_err(ReplyMarkupError::Serialize)
29    }
30}
31
32impl<const A: usize, const B: usize> From<[[InlineKeyboardButton; B]; A]> for ReplyMarkup {
33    fn from(value: [[InlineKeyboardButton; B]; A]) -> Self {
34        ReplyMarkup::InlineKeyboardMarkup(value.into())
35    }
36}
37
38impl From<Vec<Vec<InlineKeyboardButton>>> for ReplyMarkup {
39    fn from(markup: Vec<Vec<InlineKeyboardButton>>) -> ReplyMarkup {
40        ReplyMarkup::InlineKeyboardMarkup(markup.into())
41    }
42}
43
44impl<const A: usize, const B: usize> From<[[KeyboardButton; B]; A]> for ReplyMarkup {
45    fn from(value: [[KeyboardButton; B]; A]) -> Self {
46        ReplyMarkup::ReplyKeyboardMarkup(value.into())
47    }
48}
49
50impl From<Vec<Vec<KeyboardButton>>> for ReplyMarkup {
51    fn from(markup: Vec<Vec<KeyboardButton>>) -> ReplyMarkup {
52        ReplyMarkup::ReplyKeyboardMarkup(markup.into())
53    }
54}
55
56/// Represents an error occurred with reply markup.
57#[derive(Debug)]
58pub enum ReplyMarkupError {
59    /// Can not serialize markup
60    Serialize(JsonError),
61}
62
63impl Error for ReplyMarkupError {
64    fn source(&self) -> Option<&(dyn Error + 'static)> {
65        match self {
66            ReplyMarkupError::Serialize(err) => Some(err),
67        }
68    }
69}
70
71impl fmt::Display for ReplyMarkupError {
72    fn fmt(&self, out: &mut fmt::Formatter) -> fmt::Result {
73        match self {
74            ReplyMarkupError::Serialize(err) => write!(out, "can not serialize reply markup: {err}"),
75        }
76    }
77}