teloxide-fork 0.20.0

An elegant Telegram bots framework for Rust
Documentation
use crate::types::{
    BusinessMessagesDeleted, CallbackQuery, Chat, ChatId, ChatJoinRequest, ChatMemberUpdated,
    MaybeInaccessibleMessage, Message, MessageGenerationStopped, MessageKind, SharedWidgetQuery,
    Update, UpdateKind, WidgetQuery,
};

use super::DialogueKey;

/// Something that may have a chat ID.
///
/// Guest queries (`UpdateKind::GuestMessage` and messages with
/// `guest_query_id`) return `None` to avoid colliding with chat-keyed
/// dialogues. Use [`GetChatId::dialogue_key`] for state lookups: it includes
/// the business connection when one is present.
pub trait GetChatId {
    #[must_use]
    fn chat_id(&self) -> Option<ChatId>;

    /// Returns the dialogue key, falling back to an ordinary chat key by
    /// default.
    #[must_use]
    fn dialogue_key(&self) -> Option<DialogueKey> {
        self.chat_id().map(Into::into)
    }
}

impl GetChatId for Message {
    fn chat_id(&self) -> Option<ChatId> {
        if self.guest_query_id.is_some() {
            return None;
        }
        Some(self.chat.id)
    }

    fn dialogue_key(&self) -> Option<DialogueKey> {
        let chat_id = self.chat_id()?;
        if let MessageKind::Common(common) = &self.kind {
            if let Some(connection) = &common.business_connection_id {
                return Some(DialogueKey::business(chat_id, connection.clone()));
            }
        }
        Some(chat_id.into())
    }
}

impl GetChatId for CallbackQuery {
    fn chat_id(&self) -> Option<ChatId> {
        self.message.as_ref().and_then(|mes| match mes {
            MaybeInaccessibleMessage::Regular(message) => message.chat_id(),
            MaybeInaccessibleMessage::Inaccessible(message) => Some(message.chat.id),
        })
    }

    fn dialogue_key(&self) -> Option<DialogueKey> {
        match self.message.as_ref()? {
            MaybeInaccessibleMessage::Regular(message) => message.dialogue_key(),
            // Telegram omits the business connection on inaccessible messages,
            // so using the ordinary key could route a business callback to it.
            MaybeInaccessibleMessage::Inaccessible(_) => None,
        }
    }
}

impl GetChatId for Update {
    fn chat_id(&self) -> Option<ChatId> {
        match &self.kind {
            UpdateKind::GuestMessage(_) => None,
            UpdateKind::CallbackQuery(q) => q.chat_id(),
            UpdateKind::WidgetQuery(q) => q.chat_id(),
            UpdateKind::SharedWidgetQuery(q) => q.chat_id(),
            UpdateKind::StoppedMessageGeneration(m) => m.chat_id(),
            UpdateKind::Message(m)
            | UpdateKind::EditedMessage(m)
            | UpdateKind::ChannelPost(m)
            | UpdateKind::EditedChannelPost(m)
            | UpdateKind::BusinessMessage(m)
            | UpdateKind::EditedBusinessMessage(m) => m.chat_id(),
            _ => self.chat().map(|chat| chat.id),
        }
    }

    fn dialogue_key(&self) -> Option<DialogueKey> {
        match &self.kind {
            UpdateKind::GuestMessage(_) => None,
            UpdateKind::CallbackQuery(query) => query.dialogue_key(),
            UpdateKind::BusinessMessage(message) | UpdateKind::EditedBusinessMessage(message) => {
                // Never fall back to an ordinary chat key on a business update.
                message.dialogue_key().filter(|key| key.business_connection_id.is_some())
            }
            UpdateKind::DeletedBusinessMessages(messages) => messages.dialogue_key(),
            UpdateKind::Message(m)
            | UpdateKind::EditedMessage(m)
            | UpdateKind::ChannelPost(m)
            | UpdateKind::EditedChannelPost(m) => m.dialogue_key(),
            _ => self.chat_id().map(Into::into),
        }
    }
}

impl GetChatId for BusinessMessagesDeleted {
    fn chat_id(&self) -> Option<ChatId> {
        Some(self.chat.id)
    }

    fn dialogue_key(&self) -> Option<DialogueKey> {
        Some(DialogueKey::business(self.chat.id, self.business_connection_id.clone()))
    }
}

impl GetChatId for Chat {
    fn chat_id(&self) -> Option<ChatId> {
        Some(self.id)
    }
}

impl GetChatId for ChatMemberUpdated {
    fn chat_id(&self) -> Option<ChatId> {
        Some(self.chat.id)
    }
}

impl GetChatId for ChatJoinRequest {
    fn chat_id(&self) -> Option<ChatId> {
        Some(self.chat.id)
    }
}

impl GetChatId for MessageGenerationStopped {
    fn chat_id(&self) -> Option<ChatId> {
        Some(self.chat.id)
    }
}

impl GetChatId for WidgetQuery {
    fn chat_id(&self) -> Option<ChatId> {
        self.chat.as_ref().map(|c| c.id)
    }
}

impl GetChatId for SharedWidgetQuery {
    fn chat_id(&self) -> Option<ChatId> {
        // Telegram does not include a chat ID in queries from forwarded widgets.
        None
    }
}

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

    #[test]
    fn guest_messages_are_excluded_from_dialogue_chat_id() {
        let regular_update: Update = serde_json::from_str(
            r#"{
                "update_id": 1,
                "message": {
                    "message_id": 10,
                    "chat": { "id": -100500, "title": "Real Chat", "type": "supergroup" },
                    "date": 1778200000,
                    "text": "hello"
                }
            }"#,
        )
        .unwrap();
        assert_eq!(regular_update.chat_id(), Some(ChatId(-100500)));

        let guest_update: Update = serde_json::from_str(
            r#"{
                "update_id": 2,
                "guest_message": {
                    "message_id": 11,
                    "from": { "id": 2001, "is_bot": false, "first_name": "Guest" },
                    "chat": { "id": -100500, "title": "Guest Room", "type": "supergroup" },
                    "date": 1778200001,
                    "guest_query_id": "gq-1",
                    "text": "@bot hi"
                }
            }"#,
        )
        .unwrap();
        assert_eq!(guest_update.chat_id(), None);
        if let UpdateKind::GuestMessage(msg) = &guest_update.kind {
            assert_eq!(msg.chat_id(), None);
        } else {
            panic!("expected GuestMessage");
        }

        let regular_cb: Update = serde_json::from_str(
            r#"{
                "update_id": 3,
                "callback_query": {
                    "id": "cb-regular",
                    "from": { "id": 2001, "is_bot": false, "first_name": "User" },
                    "chat_instance": "ci-1",
                    "message": {
                        "message_id": 12,
                        "chat": { "id": -100500, "title": "Real Chat", "type": "supergroup" },
                        "date": 1778200002,
                        "text": "regular"
                    },
                    "data": "ok"
                }
            }"#,
        )
        .unwrap();
        assert_eq!(regular_cb.chat_id(), Some(ChatId(-100500)));

        let guest_cb: Update = serde_json::from_str(
            r#"{
                "update_id": 4,
                "callback_query": {
                    "id": "cb-guest",
                    "from": { "id": 2001, "is_bot": false, "first_name": "Guest" },
                    "chat_instance": "ci-2",
                    "message": {
                        "message_id": 13,
                        "chat": { "id": -100500, "title": "Guest Room", "type": "supergroup" },
                        "date": 1778200003,
                        "guest_query_id": "gq-1",
                        "text": "guest menu"
                    },
                    "data": "ok"
                }
            }"#,
        )
        .unwrap();
        assert_eq!(guest_cb.chat_id(), None);
        if let UpdateKind::CallbackQuery(cb) = &guest_cb.kind {
            assert_eq!(cb.chat_id(), None);
        } else {
            panic!("expected CallbackQuery");
        }

        let in_chat_wq: Update = serde_json::from_str(
            r#"{
                "update_id": 200,
                "widget_query": {
                    "id": "wq-chat",
                    "from": { "id": 9, "is_bot": false, "first_name": "Ada" },
                    "chat": { "id": -10077, "title": "Room", "type": "supergroup" },
                    "message_id": 12,
                    "chat_instance": "ci-1",
                    "type": { "type": "data" },
                    "data": "x"
                }
            }"#,
        )
        .unwrap();
        assert_eq!(in_chat_wq.chat_id(), Some(ChatId(-10077)));

        let inline_wq: Update = serde_json::from_str(
            r#"{
                "update_id": 201,
                "widget_query": {
                    "id": "wq-inline",
                    "from": { "id": 9, "is_bot": false, "first_name": "Ada" },
                    "inline_message_id": "inl-1",
                    "chat_instance": "ci-2",
                    "chat_type": "private",
                    "type": { "type": "data" },
                    "data": "x"
                }
            }"#,
        )
        .unwrap();
        assert_eq!(inline_wq.chat_id(), None);

        let shared_wq: Update = serde_json::from_str(
            r#"{
                "update_id": 202,
                "shared_widget_query": {
                    "id": "wq-shared",
                    "from": { "id": 9, "is_bot": false, "first_name": "Ada" },
                    "type": { "type": "data" },
                    "data": "x",
                    "widget_id": "w-9"
                }
            }"#,
        )
        .unwrap();
        assert_eq!(shared_wq.chat_id(), None);
    }

    #[test]
    fn bot_api_queries_and_business_messages_use_only_known_chats() {
        use serde_json::{from_value, json};

        let chat = json!({"id": -100500, "type": "supergroup"});
        let user = json!({"id": 42, "is_bot": false, "first_name": "User"});
        let stopped = json!({"chat": chat, "draft_id": 7});
        let mut widget = json!({"id": "q", "from": user, "chat": chat, "message_id": 42,
            "chat_instance": "instance", "type": {"type": "data"}, "data": "data"});
        let query: WidgetQuery = from_value(widget.clone()).unwrap();
        assert_eq!(query.chat_id(), Some(ChatId(-100500)));
        let update: Update = from_value(json!({"update_id": 1, "widget_query": widget})).unwrap();
        assert_eq!(update.chat_id(), Some(ChatId(-100500)));
        widget.as_object_mut().unwrap().remove("chat");
        widget.as_object_mut().unwrap().remove("message_id");
        widget["inline_message_id"] = json!("inline");
        let query: WidgetQuery = from_value(widget).unwrap();
        assert_eq!(query.chat_id(), None);
        let shared: SharedWidgetQuery = from_value(json!({"id":"q", "from":user,
            "type":{"type":"data"}, "data":"data", "widget_id":"widget"}))
        .unwrap();
        assert_eq!(shared.chat_id(), None);
        let stopped: MessageGenerationStopped = from_value(stopped).unwrap();
        assert_eq!(stopped.chat_id(), Some(ChatId(-100500)));
        let cb: CallbackQuery = from_value(json!({"id":"q", "from":user,
            "chat_instance":"instance", "inline_message_id":"inline", "data":"data"}))
        .unwrap();
        assert_eq!(cb.chat_id(), None);
        let cb: CallbackQuery = from_value(json!({"id":"q", "from":user,
            "chat_instance":"instance", "message":{"message_id":1,"date":0,"chat":chat},
            "data":"data"}))
        .unwrap();
        assert_eq!(cb.chat_id(), Some(ChatId(-100500)));
        assert_eq!(cb.dialogue_key(), None);
        let update: Update = from_value(json!({"update_id":1,"business_message":{
            "message_id":1,"date":1,"chat":chat,"business_connection_id":"business","text":"hi"
        }}))
        .unwrap();
        assert_eq!(update.chat_id(), Some(ChatId(-100500)));
        let expected = DialogueKey::business(
            ChatId(-100500),
            crate::types::BusinessConnectionId("business".into()),
        );
        assert_eq!(update.dialogue_key(), Some(expected.clone()));
        let UpdateKind::BusinessMessage(message) = update.kind else {
            panic!("expected business message")
        };
        assert_eq!(message.dialogue_key(), Some(expected.clone()));
        let update: Update =
            from_value(json!({"update_id":1,"edited_business_message": message})).unwrap();
        assert_eq!(update.dialogue_key(), Some(expected.clone()));
        let update: Update = from_value(json!({"update_id":1,"deleted_business_messages": {
            "chat": chat, "business_connection_id": "business", "message_ids": [1]
        }}))
        .unwrap();
        assert_eq!(update.dialogue_key(), Some(expected.clone()));
        let update: Update = from_value(json!({"update_id":1,"callback_query":{
            "id":"q", "from":user, "chat_instance":"instance", "message":message, "data":"data"
        }}))
        .unwrap();
        assert_eq!(update.dialogue_key(), Some(expected));
        let update: Update = from_value(json!({"update_id":1,"business_message":{
            "message_id":1,"date":1,"chat":chat,"text":"missing connection"
        }}))
        .unwrap();
        assert_eq!(update.dialogue_key(), None);
    }
}