Skip to main content

teloxide/dispatching/dialogue/
get_chat_id.rs

1use crate::types::{
2    BusinessMessagesDeleted, CallbackQuery, Chat, ChatId, ChatJoinRequest, ChatMemberUpdated,
3    MaybeInaccessibleMessage, Message, MessageGenerationStopped, MessageKind, SharedWidgetQuery,
4    Update, UpdateKind, WidgetQuery,
5};
6
7use super::DialogueKey;
8
9/// Something that may have a chat ID.
10///
11/// Guest queries (`UpdateKind::GuestMessage` and messages with
12/// `guest_query_id`) return `None` to avoid colliding with chat-keyed
13/// dialogues. Use [`GetChatId::dialogue_key`] for state lookups: it includes
14/// the business connection when one is present.
15pub trait GetChatId {
16    #[must_use]
17    fn chat_id(&self) -> Option<ChatId>;
18
19    /// Returns the dialogue key, falling back to an ordinary chat key by
20    /// default.
21    #[must_use]
22    fn dialogue_key(&self) -> Option<DialogueKey> {
23        self.chat_id().map(Into::into)
24    }
25}
26
27impl GetChatId for Message {
28    fn chat_id(&self) -> Option<ChatId> {
29        if self.guest_query_id.is_some() {
30            return None;
31        }
32        Some(self.chat.id)
33    }
34
35    fn dialogue_key(&self) -> Option<DialogueKey> {
36        let chat_id = self.chat_id()?;
37        if let MessageKind::Common(common) = &self.kind {
38            if let Some(connection) = &common.business_connection_id {
39                return Some(DialogueKey::business(chat_id, connection.clone()));
40            }
41        }
42        Some(chat_id.into())
43    }
44}
45
46impl GetChatId for CallbackQuery {
47    fn chat_id(&self) -> Option<ChatId> {
48        self.message.as_ref().and_then(|mes| match mes {
49            MaybeInaccessibleMessage::Regular(message) => message.chat_id(),
50            MaybeInaccessibleMessage::Inaccessible(message) => Some(message.chat.id),
51        })
52    }
53
54    fn dialogue_key(&self) -> Option<DialogueKey> {
55        match self.message.as_ref()? {
56            MaybeInaccessibleMessage::Regular(message) => message.dialogue_key(),
57            // Telegram omits the business connection on inaccessible messages,
58            // so using the ordinary key could route a business callback to it.
59            MaybeInaccessibleMessage::Inaccessible(_) => None,
60        }
61    }
62}
63
64impl GetChatId for Update {
65    fn chat_id(&self) -> Option<ChatId> {
66        match &self.kind {
67            UpdateKind::GuestMessage(_) => None,
68            UpdateKind::CallbackQuery(q) => q.chat_id(),
69            UpdateKind::WidgetQuery(q) => q.chat_id(),
70            UpdateKind::SharedWidgetQuery(q) => q.chat_id(),
71            UpdateKind::StoppedMessageGeneration(m) => m.chat_id(),
72            UpdateKind::Message(m)
73            | UpdateKind::EditedMessage(m)
74            | UpdateKind::ChannelPost(m)
75            | UpdateKind::EditedChannelPost(m)
76            | UpdateKind::BusinessMessage(m)
77            | UpdateKind::EditedBusinessMessage(m) => m.chat_id(),
78            _ => self.chat().map(|chat| chat.id),
79        }
80    }
81
82    fn dialogue_key(&self) -> Option<DialogueKey> {
83        match &self.kind {
84            UpdateKind::GuestMessage(_) => None,
85            UpdateKind::CallbackQuery(query) => query.dialogue_key(),
86            UpdateKind::BusinessMessage(message) | UpdateKind::EditedBusinessMessage(message) => {
87                // Never fall back to an ordinary chat key on a business update.
88                message.dialogue_key().filter(|key| key.business_connection_id.is_some())
89            }
90            UpdateKind::DeletedBusinessMessages(messages) => messages.dialogue_key(),
91            UpdateKind::Message(m)
92            | UpdateKind::EditedMessage(m)
93            | UpdateKind::ChannelPost(m)
94            | UpdateKind::EditedChannelPost(m) => m.dialogue_key(),
95            _ => self.chat_id().map(Into::into),
96        }
97    }
98}
99
100impl GetChatId for BusinessMessagesDeleted {
101    fn chat_id(&self) -> Option<ChatId> {
102        Some(self.chat.id)
103    }
104
105    fn dialogue_key(&self) -> Option<DialogueKey> {
106        Some(DialogueKey::business(self.chat.id, self.business_connection_id.clone()))
107    }
108}
109
110impl GetChatId for Chat {
111    fn chat_id(&self) -> Option<ChatId> {
112        Some(self.id)
113    }
114}
115
116impl GetChatId for ChatMemberUpdated {
117    fn chat_id(&self) -> Option<ChatId> {
118        Some(self.chat.id)
119    }
120}
121
122impl GetChatId for ChatJoinRequest {
123    fn chat_id(&self) -> Option<ChatId> {
124        Some(self.chat.id)
125    }
126}
127
128impl GetChatId for MessageGenerationStopped {
129    fn chat_id(&self) -> Option<ChatId> {
130        Some(self.chat.id)
131    }
132}
133
134impl GetChatId for WidgetQuery {
135    fn chat_id(&self) -> Option<ChatId> {
136        self.chat.as_ref().map(|c| c.id)
137    }
138}
139
140impl GetChatId for SharedWidgetQuery {
141    fn chat_id(&self) -> Option<ChatId> {
142        // Telegram does not include a chat ID in queries from forwarded widgets.
143        None
144    }
145}
146
147#[cfg(test)]
148mod tests {
149    use super::*;
150
151    #[test]
152    fn guest_messages_are_excluded_from_dialogue_chat_id() {
153        let regular_update: Update = serde_json::from_str(
154            r#"{
155                "update_id": 1,
156                "message": {
157                    "message_id": 10,
158                    "chat": { "id": -100500, "title": "Real Chat", "type": "supergroup" },
159                    "date": 1778200000,
160                    "text": "hello"
161                }
162            }"#,
163        )
164        .unwrap();
165        assert_eq!(regular_update.chat_id(), Some(ChatId(-100500)));
166
167        let guest_update: Update = serde_json::from_str(
168            r#"{
169                "update_id": 2,
170                "guest_message": {
171                    "message_id": 11,
172                    "from": { "id": 2001, "is_bot": false, "first_name": "Guest" },
173                    "chat": { "id": -100500, "title": "Guest Room", "type": "supergroup" },
174                    "date": 1778200001,
175                    "guest_query_id": "gq-1",
176                    "text": "@bot hi"
177                }
178            }"#,
179        )
180        .unwrap();
181        assert_eq!(guest_update.chat_id(), None);
182        if let UpdateKind::GuestMessage(msg) = &guest_update.kind {
183            assert_eq!(msg.chat_id(), None);
184        } else {
185            panic!("expected GuestMessage");
186        }
187
188        let regular_cb: Update = serde_json::from_str(
189            r#"{
190                "update_id": 3,
191                "callback_query": {
192                    "id": "cb-regular",
193                    "from": { "id": 2001, "is_bot": false, "first_name": "User" },
194                    "chat_instance": "ci-1",
195                    "message": {
196                        "message_id": 12,
197                        "chat": { "id": -100500, "title": "Real Chat", "type": "supergroup" },
198                        "date": 1778200002,
199                        "text": "regular"
200                    },
201                    "data": "ok"
202                }
203            }"#,
204        )
205        .unwrap();
206        assert_eq!(regular_cb.chat_id(), Some(ChatId(-100500)));
207
208        let guest_cb: Update = serde_json::from_str(
209            r#"{
210                "update_id": 4,
211                "callback_query": {
212                    "id": "cb-guest",
213                    "from": { "id": 2001, "is_bot": false, "first_name": "Guest" },
214                    "chat_instance": "ci-2",
215                    "message": {
216                        "message_id": 13,
217                        "chat": { "id": -100500, "title": "Guest Room", "type": "supergroup" },
218                        "date": 1778200003,
219                        "guest_query_id": "gq-1",
220                        "text": "guest menu"
221                    },
222                    "data": "ok"
223                }
224            }"#,
225        )
226        .unwrap();
227        assert_eq!(guest_cb.chat_id(), None);
228        if let UpdateKind::CallbackQuery(cb) = &guest_cb.kind {
229            assert_eq!(cb.chat_id(), None);
230        } else {
231            panic!("expected CallbackQuery");
232        }
233
234        let in_chat_wq: Update = serde_json::from_str(
235            r#"{
236                "update_id": 200,
237                "widget_query": {
238                    "id": "wq-chat",
239                    "from": { "id": 9, "is_bot": false, "first_name": "Ada" },
240                    "chat": { "id": -10077, "title": "Room", "type": "supergroup" },
241                    "message_id": 12,
242                    "chat_instance": "ci-1",
243                    "type": { "type": "data" },
244                    "data": "x"
245                }
246            }"#,
247        )
248        .unwrap();
249        assert_eq!(in_chat_wq.chat_id(), Some(ChatId(-10077)));
250
251        let inline_wq: Update = serde_json::from_str(
252            r#"{
253                "update_id": 201,
254                "widget_query": {
255                    "id": "wq-inline",
256                    "from": { "id": 9, "is_bot": false, "first_name": "Ada" },
257                    "inline_message_id": "inl-1",
258                    "chat_instance": "ci-2",
259                    "chat_type": "private",
260                    "type": { "type": "data" },
261                    "data": "x"
262                }
263            }"#,
264        )
265        .unwrap();
266        assert_eq!(inline_wq.chat_id(), None);
267
268        let shared_wq: Update = serde_json::from_str(
269            r#"{
270                "update_id": 202,
271                "shared_widget_query": {
272                    "id": "wq-shared",
273                    "from": { "id": 9, "is_bot": false, "first_name": "Ada" },
274                    "type": { "type": "data" },
275                    "data": "x",
276                    "widget_id": "w-9"
277                }
278            }"#,
279        )
280        .unwrap();
281        assert_eq!(shared_wq.chat_id(), None);
282    }
283
284    #[test]
285    fn bot_api_queries_and_business_messages_use_only_known_chats() {
286        use serde_json::{from_value, json};
287
288        let chat = json!({"id": -100500, "type": "supergroup"});
289        let user = json!({"id": 42, "is_bot": false, "first_name": "User"});
290        let stopped = json!({"chat": chat, "draft_id": 7});
291        let mut widget = json!({"id": "q", "from": user, "chat": chat, "message_id": 42,
292            "chat_instance": "instance", "type": {"type": "data"}, "data": "data"});
293        let query: WidgetQuery = from_value(widget.clone()).unwrap();
294        assert_eq!(query.chat_id(), Some(ChatId(-100500)));
295        let update: Update = from_value(json!({"update_id": 1, "widget_query": widget})).unwrap();
296        assert_eq!(update.chat_id(), Some(ChatId(-100500)));
297        widget.as_object_mut().unwrap().remove("chat");
298        widget.as_object_mut().unwrap().remove("message_id");
299        widget["inline_message_id"] = json!("inline");
300        let query: WidgetQuery = from_value(widget).unwrap();
301        assert_eq!(query.chat_id(), None);
302        let shared: SharedWidgetQuery = from_value(json!({"id":"q", "from":user,
303            "type":{"type":"data"}, "data":"data", "widget_id":"widget"}))
304        .unwrap();
305        assert_eq!(shared.chat_id(), None);
306        let stopped: MessageGenerationStopped = from_value(stopped).unwrap();
307        assert_eq!(stopped.chat_id(), Some(ChatId(-100500)));
308        let cb: CallbackQuery = from_value(json!({"id":"q", "from":user,
309            "chat_instance":"instance", "inline_message_id":"inline", "data":"data"}))
310        .unwrap();
311        assert_eq!(cb.chat_id(), None);
312        let cb: CallbackQuery = from_value(json!({"id":"q", "from":user,
313            "chat_instance":"instance", "message":{"message_id":1,"date":0,"chat":chat},
314            "data":"data"}))
315        .unwrap();
316        assert_eq!(cb.chat_id(), Some(ChatId(-100500)));
317        assert_eq!(cb.dialogue_key(), None);
318        let update: Update = from_value(json!({"update_id":1,"business_message":{
319            "message_id":1,"date":1,"chat":chat,"business_connection_id":"business","text":"hi"
320        }}))
321        .unwrap();
322        assert_eq!(update.chat_id(), Some(ChatId(-100500)));
323        let expected = DialogueKey::business(
324            ChatId(-100500),
325            crate::types::BusinessConnectionId("business".into()),
326        );
327        assert_eq!(update.dialogue_key(), Some(expected.clone()));
328        let UpdateKind::BusinessMessage(message) = update.kind else {
329            panic!("expected business message")
330        };
331        assert_eq!(message.dialogue_key(), Some(expected.clone()));
332        let update: Update =
333            from_value(json!({"update_id":1,"edited_business_message": message})).unwrap();
334        assert_eq!(update.dialogue_key(), Some(expected.clone()));
335        let update: Update = from_value(json!({"update_id":1,"deleted_business_messages": {
336            "chat": chat, "business_connection_id": "business", "message_ids": [1]
337        }}))
338        .unwrap();
339        assert_eq!(update.dialogue_key(), Some(expected.clone()));
340        let update: Update = from_value(json!({"update_id":1,"callback_query":{
341            "id":"q", "from":user, "chat_instance":"instance", "message":message, "data":"data"
342        }}))
343        .unwrap();
344        assert_eq!(update.dialogue_key(), Some(expected));
345        let update: Update = from_value(json!({"update_id":1,"business_message":{
346            "message_id":1,"date":1,"chat":chat,"text":"missing connection"
347        }}))
348        .unwrap();
349        assert_eq!(update.dialogue_key(), None);
350    }
351}