Skip to main content

teloxide/dispatching/dialogue/
get_chat_id.rs

1use crate::types::{
2    CallbackQuery, Chat, ChatId, ChatJoinRequest, ChatMemberUpdated, MaybeInaccessibleMessage,
3    Message, MessageGenerationStopped, SharedWidgetQuery, Update, UpdateKind, WidgetQuery,
4};
5
6/// Something that may have a chat ID.
7///
8/// Guest queries (`UpdateKind::GuestMessage` and messages with
9/// `guest_query_id`) return `None` to avoid colliding with chat-keyed
10/// dialogues. Note that business messages (`UpdateKind::BusinessMessage` /
11/// `UpdateKind::EditedBusinessMessage` and messages carrying
12/// `business_connection_id`) currently still return `Some(chat.id)` for
13/// backwards compatibility; dedicated business-connection scoping is deferred.
14pub trait GetChatId {
15    #[must_use]
16    fn chat_id(&self) -> Option<ChatId>;
17}
18
19impl GetChatId for Message {
20    fn chat_id(&self) -> Option<ChatId> {
21        if self.guest_query_id.is_some() {
22            return None;
23        }
24        Some(self.chat.id)
25    }
26}
27
28impl GetChatId for CallbackQuery {
29    fn chat_id(&self) -> Option<ChatId> {
30        self.message.as_ref().and_then(|mes| match mes {
31            MaybeInaccessibleMessage::Regular(message) => message.chat_id(),
32            MaybeInaccessibleMessage::Inaccessible(message) => Some(message.chat.id),
33        })
34    }
35}
36
37impl GetChatId for Update {
38    fn chat_id(&self) -> Option<ChatId> {
39        match &self.kind {
40            UpdateKind::GuestMessage(_) => None,
41            UpdateKind::CallbackQuery(q) => q.chat_id(),
42            UpdateKind::WidgetQuery(q) => q.chat_id(),
43            UpdateKind::SharedWidgetQuery(q) => q.chat_id(),
44            UpdateKind::StoppedMessageGeneration(m) => m.chat_id(),
45            UpdateKind::Message(m)
46            | UpdateKind::EditedMessage(m)
47            | UpdateKind::ChannelPost(m)
48            | UpdateKind::EditedChannelPost(m)
49            | UpdateKind::BusinessMessage(m)
50            | UpdateKind::EditedBusinessMessage(m) => m.chat_id(),
51            _ => self.chat().map(|chat| chat.id),
52        }
53    }
54}
55
56impl GetChatId for Chat {
57    fn chat_id(&self) -> Option<ChatId> {
58        Some(self.id)
59    }
60}
61
62impl GetChatId for ChatMemberUpdated {
63    fn chat_id(&self) -> Option<ChatId> {
64        Some(self.chat.id)
65    }
66}
67
68impl GetChatId for ChatJoinRequest {
69    fn chat_id(&self) -> Option<ChatId> {
70        Some(self.chat.id)
71    }
72}
73
74impl GetChatId for MessageGenerationStopped {
75    fn chat_id(&self) -> Option<ChatId> {
76        Some(self.chat.id)
77    }
78}
79
80impl GetChatId for WidgetQuery {
81    fn chat_id(&self) -> Option<ChatId> {
82        self.chat.as_ref().map(|c| c.id)
83    }
84}
85
86impl GetChatId for SharedWidgetQuery {
87    fn chat_id(&self) -> Option<ChatId> {
88        // Telegram does not include a chat ID in queries from forwarded widgets.
89        None
90    }
91}
92
93#[cfg(test)]
94mod tests {
95    use super::*;
96
97    #[test]
98    fn guest_messages_are_excluded_from_dialogue_chat_id() {
99        let regular_update: Update = serde_json::from_str(
100            r#"{
101                "update_id": 1,
102                "message": {
103                    "message_id": 10,
104                    "chat": { "id": -100500, "title": "Real Chat", "type": "supergroup" },
105                    "date": 1778200000,
106                    "text": "hello"
107                }
108            }"#,
109        )
110        .unwrap();
111        assert_eq!(regular_update.chat_id(), Some(ChatId(-100500)));
112
113        let guest_update: Update = serde_json::from_str(
114            r#"{
115                "update_id": 2,
116                "guest_message": {
117                    "message_id": 11,
118                    "from": { "id": 2001, "is_bot": false, "first_name": "Guest" },
119                    "chat": { "id": -100500, "title": "Guest Room", "type": "supergroup" },
120                    "date": 1778200001,
121                    "guest_query_id": "gq-1",
122                    "text": "@bot hi"
123                }
124            }"#,
125        )
126        .unwrap();
127        assert_eq!(guest_update.chat_id(), None);
128        if let UpdateKind::GuestMessage(msg) = &guest_update.kind {
129            assert_eq!(msg.chat_id(), None);
130        } else {
131            panic!("expected GuestMessage");
132        }
133
134        let regular_cb: Update = serde_json::from_str(
135            r#"{
136                "update_id": 3,
137                "callback_query": {
138                    "id": "cb-regular",
139                    "from": { "id": 2001, "is_bot": false, "first_name": "User" },
140                    "chat_instance": "ci-1",
141                    "message": {
142                        "message_id": 12,
143                        "chat": { "id": -100500, "title": "Real Chat", "type": "supergroup" },
144                        "date": 1778200002,
145                        "text": "regular"
146                    },
147                    "data": "ok"
148                }
149            }"#,
150        )
151        .unwrap();
152        assert_eq!(regular_cb.chat_id(), Some(ChatId(-100500)));
153
154        let guest_cb: Update = serde_json::from_str(
155            r#"{
156                "update_id": 4,
157                "callback_query": {
158                    "id": "cb-guest",
159                    "from": { "id": 2001, "is_bot": false, "first_name": "Guest" },
160                    "chat_instance": "ci-2",
161                    "message": {
162                        "message_id": 13,
163                        "chat": { "id": -100500, "title": "Guest Room", "type": "supergroup" },
164                        "date": 1778200003,
165                        "guest_query_id": "gq-1",
166                        "text": "guest menu"
167                    },
168                    "data": "ok"
169                }
170            }"#,
171        )
172        .unwrap();
173        assert_eq!(guest_cb.chat_id(), None);
174        if let UpdateKind::CallbackQuery(cb) = &guest_cb.kind {
175            assert_eq!(cb.chat_id(), None);
176        } else {
177            panic!("expected CallbackQuery");
178        }
179
180        let in_chat_wq: Update = serde_json::from_str(
181            r#"{
182                "update_id": 200,
183                "widget_query": {
184                    "id": "wq-chat",
185                    "from": { "id": 9, "is_bot": false, "first_name": "Ada" },
186                    "chat": { "id": -10077, "title": "Room", "type": "supergroup" },
187                    "message_id": 12,
188                    "chat_instance": "ci-1",
189                    "type": { "type": "data" },
190                    "data": "x"
191                }
192            }"#,
193        )
194        .unwrap();
195        assert_eq!(in_chat_wq.chat_id(), Some(ChatId(-10077)));
196
197        let inline_wq: Update = serde_json::from_str(
198            r#"{
199                "update_id": 201,
200                "widget_query": {
201                    "id": "wq-inline",
202                    "from": { "id": 9, "is_bot": false, "first_name": "Ada" },
203                    "inline_message_id": "inl-1",
204                    "chat_instance": "ci-2",
205                    "chat_type": "private",
206                    "type": { "type": "data" },
207                    "data": "x"
208                }
209            }"#,
210        )
211        .unwrap();
212        assert_eq!(inline_wq.chat_id(), None);
213
214        let shared_wq: Update = serde_json::from_str(
215            r#"{
216                "update_id": 202,
217                "shared_widget_query": {
218                    "id": "wq-shared",
219                    "from": { "id": 9, "is_bot": false, "first_name": "Ada" },
220                    "type": { "type": "data" },
221                    "data": "x",
222                    "widget_id": "w-9"
223                }
224            }"#,
225        )
226        .unwrap();
227        assert_eq!(shared_wq.chat_id(), None);
228    }
229
230    #[test]
231    fn bot_api_queries_and_business_messages_use_only_known_chats() {
232        use serde_json::{from_value, json};
233
234        let chat = json!({"id": -100500, "type": "supergroup"});
235        let user = json!({"id": 42, "is_bot": false, "first_name": "User"});
236        let stopped = json!({"chat": chat, "draft_id": 7});
237        let mut widget = json!({"id": "q", "from": user, "chat": chat, "message_id": 42,
238            "chat_instance": "instance", "type": {"type": "data"}, "data": "data"});
239        let query: WidgetQuery = from_value(widget.clone()).unwrap();
240        assert_eq!(query.chat_id(), Some(ChatId(-100500)));
241        let update: Update = from_value(json!({"update_id": 1, "widget_query": widget})).unwrap();
242        assert_eq!(update.chat_id(), Some(ChatId(-100500)));
243        widget.as_object_mut().unwrap().remove("chat");
244        widget.as_object_mut().unwrap().remove("message_id");
245        widget["inline_message_id"] = json!("inline");
246        let query: WidgetQuery = from_value(widget).unwrap();
247        assert_eq!(query.chat_id(), None);
248        let shared: SharedWidgetQuery = from_value(json!({"id":"q", "from":user,
249            "type":{"type":"data"}, "data":"data", "widget_id":"widget"}))
250        .unwrap();
251        assert_eq!(shared.chat_id(), None);
252        let stopped: MessageGenerationStopped = from_value(stopped).unwrap();
253        assert_eq!(stopped.chat_id(), Some(ChatId(-100500)));
254        let cb: CallbackQuery = from_value(json!({"id":"q", "from":user,
255            "chat_instance":"instance", "inline_message_id":"inline", "data":"data"}))
256        .unwrap();
257        assert_eq!(cb.chat_id(), None);
258        let cb: CallbackQuery = from_value(json!({"id":"q", "from":user,
259            "chat_instance":"instance", "message":{"message_id":1,"date":0,"chat":chat},
260            "data":"data"}))
261        .unwrap();
262        assert_eq!(cb.chat_id(), Some(ChatId(-100500)));
263        let update: Update = from_value(json!({"update_id":1,"business_message":{
264            "message_id":1,"date":1,"chat":chat,"business_connection_id":"business","text":"hi"
265        }}))
266        .unwrap();
267        assert_eq!(update.chat_id(), Some(ChatId(-100500)));
268    }
269}