telegram-bot2 0.2.0

telegram-bot2 is a framework to write bot for Telegram
Documentation
use crate::models::{CallbackQuery, ChatJoinRequest, ChatMember, ChosenInlineResult, InlineQuery, Message, Poll, PollAnswer, PreCheckoutQuery, ShippingQuery};
use crate::FileHolder;
use serde::{Deserialize, Serialize};

#[derive(Deserialize, Debug, Clone)]
/// Incoming update json
pub(crate) struct UpdateStruct {
    /// The update's unique identifier. Update identifiers start from a certain positive number and increase sequentially. This ID becomes especially handy if you're using webhooks, since it allows you to ignore repeated updates or to restore the correct update sequence, should they get out of order. If there are no new updates for at least a week, then identifier of the next update will be chosen randomly instead of sequentially.
    pub(crate) update_id: i64,
    /// New incoming message of any kind - text, photo, sticker, etc.
    message: Option<Message>,
    /// New version of a message that is known to the bot and was edited
    edited_message: Option<Message>,
    /// New incoming channel post of any kind - text, photo, sticker, etc.
    channel_post: Option<Message>,
    /// New version of a channel post that is known to the bot and was edited
    edited_channel_post: Option<Message>,
    /// New incoming inline query
    inline_query: Option<InlineQuery>,
    /// The result of an inline query that was chosen by a user and sent to their chat partner. Please see our documentation on the feedback collecting for details on how to enable these updates for your bot.
    chosen_inline_result: Option<ChosenInlineResult>,
    /// New incoming callback query
    callback_query: Option<CallbackQuery>,
    /// New incoming shipping query. Only for invoices with flexible price
    shipping_query: Option<ShippingQuery>,
    /// New incoming pre-checkout query. Contains full information about checkout
    pre_checkout_query: Option<PreCheckoutQuery>,
    /// New poll state. Bots receive only updates about stopped polls and polls, which are sent by the bot
    poll: Option<Poll>,
    /// A user changed their answer in a non-anonymous poll. Bots receive new votes only in polls that were sent by the bot itself.
    poll_answer: Option<PollAnswer>,
    /// The bot's chat member status was updated in a chat. For private chats, this update is received only when the bot is blocked or unblocked by the user.
    my_chat_member: Option<ChatMember>,
    /// A chat member's status was updated in a chat. The bot must be an administrator in the chat and must explicitly specify “chat_member” in the list of allowed_updates to receive these updates.
    chat_member: Option<ChatMember>,
    /// A request to join the chat has been sent. The bot must have the can_invite_users administrator right in the chat to receive these updates.
    chat_join_request: Option<ChatJoinRequest>,
}

#[derive(Serialize, FileHolder)]
pub(crate) struct GetUpdates {
    /// Identifier of the first update to be returned. Must be greater by one than the highest among the identifiers of previously received updates. By default, updates starting with the earliest unconfirmed update are returned. An update is considered confirmed as soon as getUpdates is called with an offset higher than its update_id. The negative offset can be specified to retrieve updates starting from -offset update from the end of the updates queue. All previous updates will forgotten.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(crate) offset: Option<i64>,

    /// Limits the number of updates to be retrieved. Values between 1-100 are accepted. Defaults to 100.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(crate) limit: Option<i64>,

    /// Timeout in seconds for long polling. Defaults to 0, i.e. usual short polling. Should be positive, short polling should be used for testing purposes only.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(crate) timeout: Option<i64>,

    /// A JSON-serialized list of the update types you want your bot to receive. For example, specify \[“message”, “edited_channel_post”, “callback_query”] to only receive updates of these types. See Update for a complete list of available update types. Specify an empty list to receive all update types except chat_member (default). If not specified, the previous setting will be used.
    /// Please note that this parameter doesn't affect updates created before the call to the getUpdates, so unwanted updates may be received for a short period of time.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub(crate) allowed_updates: Vec<UpdateType>,
}

/// This object represents an incoming update
#[allow(clippy::large_enum_variant)]
#[derive(Debug, Clone)]
pub enum Update {
    /// New incoming message of any kind - text, photo, sticker, etc.
    NewMessage(i64, Message),
    /// New version of a message that is known to the bot and was edited
    EditedMessage(i64, Message),

    /// New incoming channel post of any kind - text, photo, sticker, etc.
    NewChannelPost(i64, Message),
    /// New version of a channel post that is known to the bot and was edited
    EditedChannelPost(i64, Message),

    /// New incoming inline query
    InlineQuery(i64, InlineQuery),
    /// The result of an inline query that was chosen by a user and sent to their chat partner. Please see our documentation on the feedback collecting for details on how to enable these updates for your bot
    ChosenInlineResult(i64, ChosenInlineResult),
    /// New incoming callback query
    CallBackQuery(i64, CallbackQuery),

    /// New incoming shipping query. Only for invoices with flexible price
    ShippingQuery(i64, ShippingQuery),
    /// New incoming pre-checkout query. Contains full information about checkout
    PreCheckoutQuery(i64, PreCheckoutQuery),

    /// New poll state. Bots receive only updates about stopped polls and polls, which are sent by the bot
    Poll(i64, Poll),
    /// A user changed their answer in a non-anonymous poll. Bots receive new votes only in polls that were sent by the bot itself.
    PollAnswer(i64, PollAnswer),

    /// The bot's chat member status was updated in a chat. For private chats, this update is received only when the bot is blocked or unblocked by the user.
    /// The parameter will always be ChatMemberUpdated
    BotStatus(i64, ChatMember),
    /// A chat member's status was updated in a chat. The bot must be an administrator in the chat and must explicitly specify “chat_member” in the list of allowed_updates to receive these updates.
    /// The parameter will always be ChatMemberUpdated
    MemberStatus(i64, ChatMember),

    /// A request to join the chat has been sent. The bot must have the can_invite_users administrator right in the chat to receive these updates.
    ChatJoinRequest(i64, ChatJoinRequest),
}

#[derive(Serialize, Copy, Clone, Debug, Eq, PartialEq)]
#[serde(rename_all = "snake_case")]
/// Type of an incoming update
pub enum UpdateType {
    /// New incoming message of any kind - text, photo, sticker, etc.
    #[serde(rename = "message")]
    NewMessage,
    /// New version of a message that is known to the bot and was edited
    EditedMessage,

    /// New incoming channel post of any kind - text, photo, sticker, etc.
    #[serde(rename = "channel_post")]
    NewChannelPost,
    /// New version of a channel post that is known to the bot and was edited
    EditedChannelPost,

    /// New incoming inline query
    InlineQuery,
    /// The result of an inline query that was chosen by a user and sent to their chat partner. Please see our documentation on the feedback collecting for details on how to enable these updates for your bot
    ChosenInlineResult,
    /// New incoming callback query
    CallBackQuery,

    /// New incoming shipping query. Only for invoices with flexible price
    ShippingQuery,
    /// New incoming pre-checkout query. Contains full information about checkout
    PreCheckoutQuery,

    /// New poll state. Bots receive only updates about stopped polls and polls, which are sent by the bot
    Poll,
    /// A user changed their answer in a non-anonymous poll. Bots receive new votes only in polls that were sent by the bot itself.
    PollAnswer,

    /// The bot's chat member status was updated in a chat. For private chats, this update is received only when the bot is blocked or unblocked by the user.
    /// The parameter will always be ChatMemberUpdated
    #[serde(rename = "my_chat_member")]
    BotStatus,
    /// A chat member's status was updated in a chat. The bot must be an administrator in the chat and must explicitly specify “chat_member” in the list of allowed_updates to receive these updates.
    /// The parameter will always be ChatMemberUpdated
    #[serde(rename = "chat_member")]
    MemberStatus,

    /// A request to join the chat has been sent. The bot must have the can_invite_users administrator right in the chat to receive these updates.
    ChatJoinRequest,
}

impl Update {
    #[allow(missing_docs)]
    pub fn get_type(&self) -> UpdateType {
        match self {
            Update::NewMessage(_, _) => UpdateType::NewMessage,
            Update::EditedMessage(_, _) => UpdateType::EditedMessage,
            Update::NewChannelPost(_, _) => UpdateType::NewChannelPost,
            Update::EditedChannelPost(_, _) => UpdateType::EditedChannelPost,
            Update::InlineQuery(_, _) => UpdateType::InlineQuery,
            Update::ChosenInlineResult(_, _) => UpdateType::ChosenInlineResult,
            Update::CallBackQuery(_, _) => UpdateType::CallBackQuery,
            Update::ShippingQuery(_, _) => UpdateType::ShippingQuery,
            Update::PreCheckoutQuery(_, _) => UpdateType::PreCheckoutQuery,
            Update::Poll(_, _) => UpdateType::Poll,
            Update::PollAnswer(_, _) => UpdateType::PollAnswer,
            Update::BotStatus(_, _) => UpdateType::BotStatus,
            Update::MemberStatus(_, _) => UpdateType::MemberStatus,
            Update::ChatJoinRequest(_, _) => UpdateType::ChatJoinRequest,
        }
    }

    #[allow(missing_docs)]
    pub fn get_id(&self) -> i64 {
        *match self {
            Update::NewMessage(id, _) => id,
            Update::EditedMessage(id, _) => id,
            Update::NewChannelPost(id, _) => id,
            Update::EditedChannelPost(id, _) => id,
            Update::InlineQuery(id, _) => id,
            Update::ChosenInlineResult(id, _) => id,
            Update::CallBackQuery(id, _) => id,
            Update::ShippingQuery(id, _) => id,
            Update::PreCheckoutQuery(id, _) => id,
            Update::Poll(id, _) => id,
            Update::PollAnswer(id, _) => id,
            Update::BotStatus(id, _) => id,
            Update::MemberStatus(id, _) => id,
            Update::ChatJoinRequest(id, _) => id,
        }
    }
}

impl TryFrom<UpdateStruct> for Update {
    type Error = ();

    fn try_from(value: UpdateStruct) -> Result<Self, Self::Error> {
        if let Some(message) = value.message {
            Ok(Update::NewMessage(value.update_id, message))
        } else if let Some(edited_message) = value.edited_message {
            Ok(Update::EditedMessage(value.update_id, edited_message))
        } else if let Some(channel_post) = value.channel_post {
            Ok(Update::NewChannelPost(value.update_id, channel_post))
        } else if let Some(edited_channel_post) = value.edited_channel_post {
            Ok(Update::EditedChannelPost(value.update_id, edited_channel_post))
        } else if let Some(callback_query) = value.callback_query {
            Ok(Update::CallBackQuery(value.update_id, callback_query))
        } else if let Some(poll) = value.poll {
            Ok(Update::Poll(value.update_id, poll))
        } else if let Some(poll_answer) = value.poll_answer {
            Ok(Update::PollAnswer(value.update_id, poll_answer))
        } else if let Some(my_chat_member) = value.my_chat_member {
            Ok(Update::BotStatus(value.update_id, my_chat_member))
        } else if let Some(chat_member) = value.chat_member {
            Ok(Update::MemberStatus(value.update_id, chat_member))
        } else if let Some(chat_join_request) = value.chat_join_request {
            Ok(Update::ChatJoinRequest(value.update_id, chat_join_request))
        } else if let Some(shipping_query) = value.shipping_query {
            Ok(Update::ShippingQuery(value.update_id, shipping_query))
        } else if let Some(pre_checkout_query) = value.pre_checkout_query {
            Ok(Update::PreCheckoutQuery(value.update_id, pre_checkout_query))
        } else if let Some(inline_query) = value.inline_query {
            Ok(Update::InlineQuery(value.update_id, inline_query))
        } else if let Some(chosen_inline_result) = value.chosen_inline_result {
            Ok(Update::ChosenInlineResult(value.update_id, chosen_inline_result))
        } else {
            Err(())
        }
    }
}