ferogram 0.3.8

Production-grade async Telegram MTProto client: updates, bots, flood-wait, dialogs, messages
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
// Copyright (c) Ankit Chaubey <ankitchaubey.dev@gmail.com>
//
// ferogram: async Telegram MTProto client in Rust
// https://github.com/ankit-chaubey/ferogram
//
// Licensed under either the MIT License or the Apache License 2.0.
// See the LICENSE-MIT or LICENSE-APACHE file in this repository:
// https://github.com/ankit-chaubey/ferogram
//
// Feel free to use, modify, and share this code.
// Please keep this notice when redistributing.

use ferogram_tl_types as tl;
use ferogram_tl_types::{Cursor, Deserializable};

use crate::{Client, InvocationError as Error};

/// Filter for [`IncomingMessage::find_button`].
#[derive(Debug, Clone)]
pub enum ButtonFilter<'a> {
    /// Match by grid position (`row`, `col`), 0-based.
    Pos(usize, usize),
    /// Match the first button whose label equals `text`.
    Text(&'a str),
    /// Match the first callback button whose data equals `data`.
    Data(&'a [u8]),
}

/// A new or edited message.
#[derive(Clone)]
pub struct IncomingMessage {
    /// The underlying TL message object.
    pub raw: tl::enums::Message,
    /// An embedded client reference, populated for messages received via
    /// `stream_updates()` and returned from send/search/history APIs.
    /// When present, the clientless action methods (`reply`, `respond`,
    /// `edit`, `delete`, `pin`, `unpin`, `react`, ...) can be called without
    /// passing a `&Client` argument.
    pub client: Option<Client>,
}

impl std::fmt::Debug for IncomingMessage {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("IncomingMessage")
            .field("raw", &self.raw)
            .field("has_client", &self.client.is_some())
            .finish()
    }
}

impl IncomingMessage {
    pub(crate) fn from_raw(raw: tl::enums::Message) -> Self {
        Self { raw, client: None }
    }

    /// Attach a `Client` so the clientless action methods work.
    ///
    /// Returns `self` for chaining:
    /// ```rust,ignore
    /// # use ferogram::update::IncomingMessage;
    /// # fn ex(raw: ferogram_tl_types::enums::Message, client: ferogram::Client) {
    /// let msg = IncomingMessage::from_raw(raw).with_client(client);
    /// # }
    /// ```
    pub(crate) fn with_client(mut self, client: Client) -> Self {
        self.client = Some(client);
        self
    }

    /// Returns an error when no client is embedded.
    fn require_client(&self, method: &str) -> Result<&Client, Error> {
        self.client.as_ref().ok_or_else(|| {
            Error::Deserialize(format!(
                "{method}: this IncomingMessage has no embedded client: \
                 use the `_with` variant and pass a &Client explicitly"
            ))
        })
    }

    /// The message text (or caption for media messages).
    pub fn text(&self) -> Option<&str> {
        match &self.raw {
            tl::enums::Message::Message(m) => {
                if m.message.is_empty() {
                    None
                } else {
                    Some(&m.message)
                }
            }
            _ => None,
        }
    }

    /// Unique message ID within the chat.
    pub fn id(&self) -> i32 {
        match &self.raw {
            tl::enums::Message::Message(m) => m.id,
            tl::enums::Message::Service(m) => m.id,
            tl::enums::Message::Empty(m) => m.id,
        }
    }

    /// The peer (chat) this message belongs to.
    pub fn peer_id(&self) -> Option<&tl::enums::Peer> {
        match &self.raw {
            tl::enums::Message::Message(m) => Some(&m.peer_id),
            tl::enums::Message::Service(m) => Some(&m.peer_id),
            _ => None,
        }
    }

    /// The sender peer, if available (not set for anonymous channel posts).
    pub fn sender_id(&self) -> Option<&tl::enums::Peer> {
        match &self.raw {
            tl::enums::Message::Message(m) => m.from_id.as_ref(),
            tl::enums::Message::Service(m) => m.from_id.as_ref(),
            _ => None,
        }
    }

    /// `true` if the message was sent by the logged-in account.
    pub fn outgoing(&self) -> bool {
        match &self.raw {
            tl::enums::Message::Message(m) => m.out,
            tl::enums::Message::Service(m) => m.out,
            _ => false,
        }
    }

    /// Unix timestamp when the message was sent.
    pub fn date(&self) -> i32 {
        match &self.raw {
            tl::enums::Message::Message(m) => m.date,
            tl::enums::Message::Service(m) => m.date,
            _ => 0,
        }
    }

    /// Unix timestamp of the last edit, if the message has been edited.
    pub fn edit_date(&self) -> Option<i32> {
        match &self.raw {
            tl::enums::Message::Message(m) => m.edit_date,
            _ => None,
        }
    }

    /// `true` if the logged-in user was mentioned in this message.
    pub fn mentioned(&self) -> bool {
        match &self.raw {
            tl::enums::Message::Message(m) => m.mentioned,
            tl::enums::Message::Service(m) => m.mentioned,
            _ => false,
        }
    }

    /// `true` if the message was sent silently (no notification).
    pub fn silent(&self) -> bool {
        match &self.raw {
            tl::enums::Message::Message(m) => m.silent,
            tl::enums::Message::Service(m) => m.silent,
            _ => false,
        }
    }

    /// `true` if this is a channel post (no sender).
    pub fn post(&self) -> bool {
        match &self.raw {
            tl::enums::Message::Message(m) => m.post,
            _ => false,
        }
    }

    /// `true` if this message is currently pinned.
    pub fn pinned(&self) -> bool {
        match &self.raw {
            tl::enums::Message::Message(m) => m.pinned,
            _ => false,
        }
    }

    /// Number of times the message has been forwarded (channels only).
    pub fn forward_count(&self) -> Option<i32> {
        match &self.raw {
            tl::enums::Message::Message(m) => m.forwards,
            _ => None,
        }
    }

    /// View count for channel posts.
    pub fn view_count(&self) -> Option<i32> {
        match &self.raw {
            tl::enums::Message::Message(m) => m.views,
            _ => None,
        }
    }

    /// Reply count (number of replies in a thread).
    pub fn reply_count(&self) -> Option<i32> {
        match &self.raw {
            tl::enums::Message::Message(m) => m.replies.as_ref().map(|r| match r {
                tl::enums::MessageReplies::MessageReplies(x) => x.replies,
            }),
            _ => None,
        }
    }

    /// ID of the message this one is replying to.
    pub fn reply_to_message_id(&self) -> Option<i32> {
        match &self.raw {
            tl::enums::Message::Message(m) => m.reply_to.as_ref().and_then(|r| match r {
                tl::enums::MessageReplyHeader::MessageReplyHeader(h) => h.reply_to_msg_id,
                _ => None,
            }),
            _ => None,
        }
    }

    /// Fetch the message that this one is replying to.
    ///
    /// Returns `None` if this message is not a reply or if the peer is unknown.
    /// Unlike [`reply_to_message_id`] this actually performs an API call to
    /// retrieve the full message object.
    ///
    /// [`reply_to_message_id`]: IncomingMessage::reply_to_message_id
    /// The message's send time as a [`chrono::DateTime<chrono::Utc>`].
    ///
    /// Typed wrapper around the raw `date()` Unix timestamp.
    pub fn date_utc(&self) -> Option<chrono::DateTime<chrono::Utc>> {
        use chrono::TimeZone;
        let ts = self.date();
        if ts == 0 {
            return None;
        }
        chrono::Utc.timestamp_opt(ts as i64, 0).single()
    }

    /// The last edit time as a [`chrono::DateTime<chrono::Utc>`], if edited.
    pub fn edit_date_utc(&self) -> Option<chrono::DateTime<chrono::Utc>> {
        use chrono::TimeZone;
        self.edit_date()
            .and_then(|ts| chrono::Utc.timestamp_opt(ts as i64, 0).single())
    }

    /// The media attached to this message, if any.
    pub fn media(&self) -> Option<&tl::enums::MessageMedia> {
        match &self.raw {
            tl::enums::Message::Message(m) => m.media.as_ref(),
            _ => None,
        }
    }

    /// Formatting entities (bold, italic, code, links, etc).
    pub fn entities(&self) -> Option<&Vec<tl::enums::MessageEntity>> {
        match &self.raw {
            tl::enums::Message::Message(m) => m.entities.as_ref(),
            _ => None,
        }
    }

    /// Group ID for album messages (multiple media in one).
    pub fn grouped_id(&self) -> Option<i64> {
        match &self.raw {
            tl::enums::Message::Message(m) => m.grouped_id,
            _ => None,
        }
    }

    /// `true` if this message was sent from a scheduled one.
    pub fn from_scheduled(&self) -> bool {
        match &self.raw {
            tl::enums::Message::Message(m) => m.from_scheduled,
            _ => false,
        }
    }

    /// `true` if the edit date is hidden from recipients.
    pub fn edit_hide(&self) -> bool {
        match &self.raw {
            tl::enums::Message::Message(m) => m.edit_hide,
            _ => false,
        }
    }

    /// `true` if the media in this message has not been read yet.
    pub fn media_unread(&self) -> bool {
        match &self.raw {
            tl::enums::Message::Message(m) => m.media_unread,
            tl::enums::Message::Service(m) => m.media_unread,
            _ => false,
        }
    }

    /// ID of the bot that sent this message via inline mode, if any.
    pub fn via_bot_id(&self) -> Option<i64> {
        match &self.raw {
            tl::enums::Message::Message(m) => m.via_bot_id,
            _ => None,
        }
    }

    /// Signature of the post author in a channel, if set.
    pub fn post_author(&self) -> Option<&str> {
        match &self.raw {
            tl::enums::Message::Message(m) => m.post_author.as_deref(),
            _ => None,
        }
    }

    /// Number of reactions on this message, if any.
    pub fn reaction_count(&self) -> i32 {
        match &self.raw {
            tl::enums::Message::Message(m) => m
                .reactions
                .as_ref()
                .map(|r| match r {
                    tl::enums::MessageReactions::MessageReactions(x) => x
                        .results
                        .iter()
                        .map(|res| match res {
                            tl::enums::ReactionCount::ReactionCount(c) => c.count,
                        })
                        .sum(),
                })
                .unwrap_or(0),
            _ => 0,
        }
    }

    /// Restriction reasons (why this message is unavailable in some regions).
    pub fn restriction_reason(&self) -> Option<&Vec<tl::enums::RestrictionReason>> {
        match &self.raw {
            tl::enums::Message::Message(m) => m.restriction_reason.as_ref(),
            _ => None,
        }
    }

    /// Reply markup (inline keyboards, etc).
    pub fn reply_markup(&self) -> Option<&tl::enums::ReplyMarkup> {
        match &self.raw {
            tl::enums::Message::Message(m) => m.reply_markup.as_ref(),
            _ => None,
        }
    }

    /// Forward info header, if this message was forwarded.
    pub fn forward_header(&self) -> Option<&tl::enums::MessageFwdHeader> {
        match &self.raw {
            tl::enums::Message::Message(m) => m.fwd_from.as_ref(),
            _ => None,
        }
    }

    /// `true` if forwarding this message is restricted.
    pub fn noforwards(&self) -> bool {
        match &self.raw {
            tl::enums::Message::Message(m) => m.noforwards,
            _ => false,
        }
    }

    /// Reconstruct Markdown from the message text and its formatting entities.
    ///
    /// Returns plain text if there are no entities.
    pub fn markdown_text(&self) -> Option<String> {
        let text = self.text()?;
        let entities = self.entities().map(|e| e.as_slice()).unwrap_or(&[]);
        Some(crate::parsers::generate_markdown(text, entities))
    }

    /// Reconstruct HTML from the message text and its formatting entities.
    ///
    /// Returns plain text if there are no entities.
    pub fn html_text(&self) -> Option<String> {
        let text = self.text()?;
        let entities = self.entities().map(|e| e.as_slice()).unwrap_or(&[]);
        Some(crate::parsers::generate_html(text, entities))
    }

    /// Service message action (e.g. "user joined", "call started").\
    /// Returns `None` for regular text/media messages.
    pub fn action(&self) -> Option<&tl::enums::MessageAction> {
        match &self.raw {
            tl::enums::Message::Service(m) => Some(&m.action),
            _ => None,
        }
    }

    /// Extract a `Photo` from the message media, if present.
    ///
    /// Shorthand for `Photo::from_media(msg.media()?)`.
    pub fn photo(&self) -> Option<crate::media::Photo> {
        crate::media::Photo::from_media(self.media()?)
    }

    /// Extract a `Document` from the message media, if present.
    ///
    /// Shorthand for `Document::from_media(msg.media()?)`.
    pub fn document(&self) -> Option<crate::media::Document> {
        crate::media::Document::from_media(self.media()?)
    }

    /// The bare numeric chat ID (positive for users/groups, negative for channels).
    pub fn chat_id(&self) -> i64 {
        match self.peer_id() {
            Some(tl::enums::Peer::User(u)) => u.user_id,
            Some(tl::enums::Peer::Chat(c)) => c.chat_id,
            Some(tl::enums::Peer::Channel(c)) => c.channel_id,
            None => 0,
        }
    }

    /// `true` when the message is in a private (1-on-1) chat.
    pub fn is_private(&self) -> bool {
        matches!(self.peer_id(), Some(tl::enums::Peer::User(_)))
    }

    /// `true` when the message is in a basic group.
    pub fn is_group(&self) -> bool {
        matches!(self.peer_id(), Some(tl::enums::Peer::Chat(_)))
    }

    /// `true` when the message is in a channel or supergroup.
    pub fn is_channel(&self) -> bool {
        matches!(self.peer_id(), Some(tl::enums::Peer::Channel(_)))
    }

    /// `true` when the message is in *any* multi-user chat (group or channel).
    pub fn is_any_group(&self) -> bool {
        self.is_group() || self.is_channel()
    }

    /// `true` when the message text begins with `/` (a bot command).
    pub fn is_bot_command(&self) -> bool {
        self.text().is_some_and(|t| t.starts_with('/'))
    }

    /// If the message is a bot command, returns `(command, rest)` where `command`
    /// is the command name without the `/` and optional `@BotName` suffix,
    /// and `rest` is everything after (trimmed).
    ///
    /// ```rust,no_run
    /// # fn ex(msg: ferogram::update::IncomingMessage) {
    /// if let Some((cmd, args)) = msg.command() {
    ///     // cmd = "start", args = "payload"
    /// }
    /// # }
    /// ```
    pub fn command(&self) -> Option<(&str, &str)> {
        let text = self.text()?;
        if !text.starts_with('/') {
            return None;
        }
        let without_slash = &text[1..];
        // Split off @BotName if present
        let cmd_full = without_slash.split_whitespace().next().unwrap_or("");
        let cmd = cmd_full.split('@').next().unwrap_or(cmd_full);
        let rest = text[1 + cmd_full.len()..].trim();
        Some((cmd, rest))
    }

    /// `true` if the message is the named command (case-insensitive, ignoring `@bot` suffix).
    pub fn is_command_named(&self, name: &str) -> bool {
        self.command()
            .is_some_and(|(cmd, _)| cmd.eq_ignore_ascii_case(name))
    }

    /// Return the arguments portion of a bot command (text after `/cmd`), trimmed.
    /// Returns `None` if the message is not a command.
    pub fn command_args(&self) -> Option<&str> {
        self.command().map(|(_, args)| args)
    }

    /// `true` if the message carries any media attachment.
    pub fn has_media(&self) -> bool {
        self.media().is_some()
    }

    /// `true` if the message carries a photo.
    pub fn has_photo(&self) -> bool {
        matches!(self.media(), Some(tl::enums::MessageMedia::Photo(_)))
    }

    /// `true` if the message carries a document (file, video, audio, etc).
    pub fn has_document(&self) -> bool {
        matches!(self.media(), Some(tl::enums::MessageMedia::Document(_)))
    }

    /// `true` if this message was forwarded from another chat or user.
    pub fn is_forwarded(&self) -> bool {
        self.forward_header().is_some()
    }

    /// `true` if this message is a reply to another message.
    pub fn is_reply(&self) -> bool {
        self.reply_to_message_id().is_some()
    }

    /// Alias of `grouped_id` - the album/grouped-media ID, if this message is
    /// part of an album.
    pub fn album_id(&self) -> Option<i64> {
        self.grouped_id()
    }

    /// Reply to this message (clientless: requires an embedded client).
    ///
    /// Returns the sent message so you can chain further operations on it.
    /// Reply to this message.
    ///
    /// Accepts a plain `&str`/`String` or a full [`InputMessage`](crate::InputMessage)
    /// (with keyboard, formatting, media, etc.).  The reply-to header is set automatically.
    ///
    /// ```rust,no_run
    /// # use ferogram::{InputMessage, update::IncomingMessage};
    /// # async fn example(msg: IncomingMessage, kb: ferogram::tl::enums::ReplyMarkup) -> Result<(), ferogram::InvocationError> {
    /// // plain text
    /// msg.reply("Hello!").await?;
    ///
    /// // HTML formatting
    /// msg.reply(InputMessage::html("<b>Bold</b> reply")).await?;
    ///
    /// // with keyboard
    /// msg.reply(InputMessage::text("Choose:").reply_markup(kb)).await?;
    /// # Ok(()) }
    /// ```
    pub async fn reply(
        &self,
        msg: impl Into<crate::InputMessage>,
    ) -> Result<IncomingMessage, Error> {
        let client = self.require_client("reply")?.clone();
        self.reply_with(&client, msg).await
    }

    async fn reply_with(
        &self,
        client: &Client,
        msg: impl Into<crate::InputMessage>,
    ) -> Result<IncomingMessage, Error> {
        let peer = self
            .peer_id()
            .cloned()
            .ok_or_else(|| Error::Deserialize("cannot reply: unknown peer".into()))?;
        client
            .send_message(peer, msg.into().reply_to(Some(self.id())))
            .await
    }
    /// Send to the same chat without quoting.
    ///
    /// Accepts a plain `&str`/`String` or a full [`InputMessage`](crate::InputMessage).
    pub async fn respond(
        &self,
        msg: impl Into<crate::InputMessage>,
    ) -> Result<IncomingMessage, Error> {
        let client = self.require_client("respond")?.clone();
        self.respond_with(&client, msg).await
    }

    async fn respond_with(
        &self,
        client: &Client,
        msg: impl Into<crate::InputMessage>,
    ) -> Result<IncomingMessage, Error> {
        let peer = self
            .peer_id()
            .cloned()
            .ok_or_else(|| Error::Deserialize("cannot respond: unknown peer".into()))?;
        client.send_message(peer, msg.into()).await
    }

    /// Edit this message.
    ///
    /// Accepts a plain `&str`/`String` or a full [`InputMessage`](crate::InputMessage)
    /// (for HTML/Markdown formatting, keyboard changes, etc.).
    ///
    /// ```rust,no_run
    /// # use ferogram::{InputMessage, update::IncomingMessage};
    /// # async fn example(msg: IncomingMessage) -> Result<(), ferogram::InvocationError> {
    /// msg.edit("Updated text").await?;
    /// msg.edit(InputMessage::html("<b>Updated</b>")).await?;
    /// # Ok(()) }
    /// ```
    pub async fn edit(&self, msg: impl Into<crate::InputMessage>) -> Result<(), Error> {
        let client = self.require_client("edit")?.clone();
        let peer = self
            .peer_id()
            .cloned()
            .ok_or_else(|| Error::Deserialize("cannot edit: unknown peer".into()))?;
        client.edit_message(peer, self.id(), msg.into()).await
    }

    /// Delete this message (clientless).
    pub async fn delete(&self) -> Result<(), Error> {
        let client = self.require_client("delete")?.clone();
        self.delete_with(&client).await
    }

    /// Delete this message.
    pub async fn delete_with(&self, client: &Client) -> Result<(), Error> {
        match self.peer_id() {
            Some(tl::enums::Peer::Channel(_)) => {
                // Channels and supergroups require channels.DeleteMessages.
                let peer = self
                    .peer_id()
                    .cloned()
                    .ok_or_else(|| Error::Deserialize("delete_with: no peer".into()))?;
                let input_peer = client.resolve_to_input_peer(&peer).await?;
                let channel = match input_peer {
                    tl::enums::InputPeer::Channel(ic) => {
                        tl::enums::InputChannel::InputChannel(tl::types::InputChannel {
                            channel_id: ic.channel_id,
                            access_hash: ic.access_hash,
                        })
                    }
                    _ => {
                        return Err(Error::Deserialize(
                            "delete_with: failed to resolve channel input".into(),
                        ));
                    }
                };
                let req = tl::functions::channels::DeleteMessages {
                    channel,
                    id: vec![self.id()],
                };
                client
                    .invoke(&req)
                    .await
                    .map(|_: tl::enums::messages::AffectedMessages| ())
            }
            _ => {
                let _p = self
                    .peer_id()
                    .cloned()
                    .ok_or_else(|| Error::Deserialize("delete: no peer".into()))?;
                client.delete_messages(&[self.id()], true).await.map(|_| ())
            }
        }
    }

    /// Mark this message (and all before it) as read (clientless).
    pub async fn mark_as_read(&self) -> Result<(), Error> {
        let client = self.require_client("mark_as_read")?.clone();
        self.mark_as_read_with(&client).await
    }

    /// Mark this message (and all before it) as read.
    pub async fn mark_as_read_with(&self, client: &Client) -> Result<(), Error> {
        let peer = self
            .peer_id()
            .cloned()
            .ok_or_else(|| Error::Deserialize("cannot mark_as_read: unknown peer".into()))?;
        client.mark_as_read(peer).await
    }

    /// Pin this message silently (clientless).
    pub async fn pin(&self) -> Result<(), Error> {
        let client = self.require_client("pin")?.clone();
        self.pin_with(&client).await
    }

    /// Pin this message silently.
    pub async fn pin_with(&self, client: &Client) -> Result<(), Error> {
        let peer = self
            .peer_id()
            .cloned()
            .ok_or_else(|| Error::Deserialize("cannot pin: unknown peer".into()))?;
        client.pin_message_raw(peer, self.id()).await.map(|_| ())
    }

    /// Unpin this message (clientless).
    pub async fn unpin(&self) -> Result<(), Error> {
        let client = self.require_client("unpin")?.clone();
        self.unpin_with(&client).await
    }

    /// Unpin this message.
    pub async fn unpin_with(&self, client: &Client) -> Result<(), Error> {
        let peer = self
            .peer_id()
            .cloned()
            .ok_or_else(|| Error::Deserialize("cannot unpin: unknown peer".into()))?;
        client.unpin_message(peer, self.id()).await
    }

    /// Forward this message to another chat (clientless).
    ///
    /// Returns the forwarded message in the destination chat.
    pub async fn forward_to(
        &self,
        destination: impl Into<crate::PeerRef>,
    ) -> Result<IncomingMessage, Error> {
        let client = self.require_client("forward_to")?.clone();
        self.forward_to_with(&client, destination).await
    }

    /// Forward this message to another chat.
    ///
    /// Returns the forwarded message in the destination chat.
    pub async fn forward_to_with(
        &self,
        client: &Client,
        destination: impl Into<crate::PeerRef>,
    ) -> Result<IncomingMessage, Error> {
        let src = self
            .peer_id()
            .cloned()
            .ok_or_else(|| Error::Deserialize("cannot forward: unknown source peer".into()))?;
        client
            .forward_messages(
                destination,
                &[self.id()],
                src,
                crate::ForwardOptions::default(),
            )
            .await?
            .into_iter()
            .next()
            .ok_or_else(|| Error::Deserialize("forward returned no message".into()))
    }

    /// Re-fetch this message from Telegram (clientless).
    ///
    /// Useful to get updated view/forward counts, reactions, edit state, etc.
    /// Updates `self` in place; returns an error if the message was deleted.
    pub async fn refetch(&mut self) -> Result<(), Error> {
        let client = self.require_client("refetch")?.clone();
        self.refetch_with(&client).await
    }

    /// Re-fetch this message from Telegram.
    pub async fn refetch_with(&mut self, client: &Client) -> Result<(), Error> {
        let peer = self
            .peer_id()
            .cloned()
            .ok_or_else(|| Error::Deserialize("cannot refetch: unknown peer".into()))?;
        let msgs_opt = client.get_message_by_id(peer, self.id()).await?;
        match msgs_opt {
            Some(m) => {
                self.raw = m.raw;
                Ok(())
            }
            None => Err(Error::Deserialize(
                "refetch: message not found (deleted?)".into(),
            )),
        }
    }

    /// Download attached media to `path` (clientless).
    pub async fn download_media(&self, path: impl AsRef<std::path::Path>) -> Result<bool, Error> {
        let client = self.require_client("download_media")?.clone();
        self.download_media_with(&client, path).await
    }

    /// Download attached media to `path`. Returns `true` if media was found.
    async fn download_media_with(
        &self,
        client: &Client,
        path: impl AsRef<std::path::Path>,
    ) -> Result<bool, Error> {
        if let Some((loc, dc_id)) = crate::media::download_location_from_media(self.media()) {
            client
                .download_media_to_file_on_dc(loc, dc_id, path)
                .await?;
            Ok(true)
        } else {
            Ok(false)
        }
    }

    /// Send a reaction (clientless).
    ///
    /// # Example
    /// ```rust,no_run
    /// # async fn f(msg: ferogram::update::IncomingMessage)
    /// #   -> Result<(), ferogram::InvocationError> {
    /// use ferogram::reactions::InputReactions;
    /// msg.react(InputReactions::emoticon("👍")).await?;
    /// # Ok(()) }
    /// ```
    pub async fn react(
        &self,
        reactions: impl Into<crate::reactions::InputReactions>,
    ) -> Result<(), Error> {
        let client = self.require_client("react")?.clone();
        self.react_with(&client, reactions).await
    }

    /// Send a reaction.
    pub async fn react_with(
        &self,
        client: &Client,
        reactions: impl Into<crate::reactions::InputReactions>,
    ) -> Result<(), Error> {
        let peer = self
            .peer_id()
            .cloned()
            .ok_or_else(|| Error::Deserialize("cannot react: unknown peer".into()))?;
        client.send_reaction(peer, self.id(), reactions).await
    }

    /// Fetch the message this is a reply to (clientless).
    pub async fn get_reply(&self) -> Result<Option<IncomingMessage>, Error> {
        let client = self.require_client("get_reply")?.clone();
        self.get_reply_with(&client).await
    }

    /// Fetch the message this is a reply to.
    pub async fn get_reply_with(&self, client: &Client) -> Result<Option<IncomingMessage>, Error> {
        client.get_reply_to_message(self).await
    }

    /// The sender's bare user-ID, if this is a user message.
    ///
    /// Returns `None` for anonymous channel posts.
    pub fn sender_user_id(&self) -> Option<i64> {
        match self.sender_id()? {
            tl::enums::Peer::User(u) => Some(u.user_id),
            _ => None,
        }
    }

    /// The chat/channel-ID the sender belongs to (non-user senders).
    pub fn sender_chat_id(&self) -> Option<i64> {
        match self.sender_id()? {
            tl::enums::Peer::Chat(c) => Some(c.chat_id),
            tl::enums::Peer::Channel(c) => Some(c.channel_id),
            _ => None,
        }
    }

    /// Fetch the sender as a typed [`User`](crate::types::User) (clientless, async).
    ///
    /// Returns `None` if the sender is not a user, or if the user is not in
    /// the local peer cache.  Performs a network call if needed.
    pub async fn sender_user(&self) -> Result<Option<crate::types::User>, Error> {
        let uid = match self.sender_user_id() {
            Some(id) => id,
            None => return Ok(None),
        };
        let client = self.require_client("sender_user")?.clone();
        let users = client.get_users_by_id(&[uid]).await?;
        Ok(users.into_iter().next().flatten())
    }

    fn extract_callback_data(&self, row: usize, col: usize) -> Result<Vec<u8>, Error> {
        let markup = self.reply_markup().ok_or_else(|| {
            Error::Deserialize("click_button: message has no reply markup".into())
        })?;
        let rows = match markup {
            tl::enums::ReplyMarkup::ReplyInlineMarkup(kb) => &kb.rows,
            _ => {
                return Err(Error::Deserialize(
                    "click_button: reply markup is not an inline keyboard".into(),
                ));
            }
        };
        let kb_row = rows.get(row).ok_or_else(|| {
            Error::Deserialize(format!(
                "click_button: row {row} out of range (keyboard has {} rows)",
                rows.len()
            ))
        })?;
        let buttons = match kb_row {
            tl::enums::KeyboardButtonRow::KeyboardButtonRow(r) => &r.buttons,
        };
        let btn = buttons.get(col).ok_or_else(|| {
            Error::Deserialize(format!(
                "click_button: col {col} out of range (row has {} buttons)",
                buttons.len()
            ))
        })?;
        match btn {
            tl::enums::KeyboardButton::Callback(b) => Ok(b.data.clone()),
            _ => Err(Error::Deserialize(format!(
                "click_button: button at ({row}, {col}) is not a callback button"
            ))),
        }
    }

    fn find_callback_data_by_text(&self, text: &str) -> Result<Vec<u8>, Error> {
        let markup = self.reply_markup().ok_or_else(|| {
            Error::Deserialize("click_button_by_text: message has no reply markup".into())
        })?;
        let rows = match markup {
            tl::enums::ReplyMarkup::ReplyInlineMarkup(kb) => &kb.rows,
            _ => {
                return Err(Error::Deserialize(
                    "click_button_by_text: reply markup is not an inline keyboard".into(),
                ));
            }
        };
        for row in rows {
            let buttons = match row {
                tl::enums::KeyboardButtonRow::KeyboardButtonRow(r) => &r.buttons,
            };
            for btn in buttons {
                if let tl::enums::KeyboardButton::Callback(b) = btn
                    && b.text == text
                {
                    return Ok(b.data.clone());
                }
            }
        }
        Err(Error::Deserialize(format!(
            "click_button_by_text: no callback button with label {text:?}"
        )))
    }

    async fn invoke_click(&self, client: &Client, data: Vec<u8>) -> Result<(), Error> {
        let peer = self
            .peer_id()
            .cloned()
            .ok_or_else(|| Error::Deserialize("click_button: unknown peer".into()))?;
        let input_peer = client.resolve_to_input_peer(&peer).await?;
        client
            .invoke(&tl::functions::messages::GetBotCallbackAnswer {
                game: false,
                peer: input_peer,
                msg_id: self.id(),
                data: Some(data),
                password: None,
            })
            .await
            .map(|_: tl::enums::messages::BotCallbackAnswer| ())
    }

    fn iter_inline_buttons(
        &self,
    ) -> impl Iterator<Item = (usize, usize, &tl::enums::KeyboardButton)> {
        let rows = match self.reply_markup() {
            Some(tl::enums::ReplyMarkup::ReplyInlineMarkup(kb)) => kb.rows.as_slice(),
            _ => &[],
        };
        rows.iter().enumerate().flat_map(|(r, row)| {
            let buttons = match row {
                tl::enums::KeyboardButtonRow::KeyboardButtonRow(rb) => rb.buttons.as_slice(),
            };
            buttons.iter().enumerate().map(move |(c, btn)| (r, c, btn))
        })
    }

    /// Press the first inline callback button matched by `predicate`.
    ///
    /// The closure receives `(text: &str, data: &[u8])` for each callback button.
    ///
    /// ```rust,no_run
    /// # use ferogram::update::IncomingMessage;
    /// # async fn example(msg: IncomingMessage) -> Result<(), ferogram::InvocationError> {
    /// msg.click_button_where(|text, _data| text.contains("Confirm")).await?;
    /// # Ok(()) }
    /// ```
    pub async fn click_button_where<F>(&self, predicate: F) -> Result<(), Error>
    where
        F: Fn(&str, &[u8]) -> bool,
    {
        let client = self.require_client("click_button_where")?.clone();
        self.click_button_where_with(&client, predicate).await
    }

    /// Press the first inline callback button matched by `predicate`, using an explicit client.
    async fn click_button_where_with<F>(&self, client: &Client, predicate: F) -> Result<(), Error>
    where
        F: Fn(&str, &[u8]) -> bool,
    {
        for (_, _, btn) in self.iter_inline_buttons() {
            if let tl::enums::KeyboardButton::Callback(b) = btn
                && predicate(&b.text, &b.data)
            {
                return self.invoke_click(client, b.data.clone()).await;
            }
        }
        Err(Error::Deserialize(
            "click_button_where: no callback button matched the predicate".into(),
        ))
    }

    /// Find the first inline callback button matching `filter` and return its `(row, col)`.
    ///
    /// Use `.is_some()` to check existence.
    ///
    /// ```rust,no_run
    /// # use ferogram::{ButtonFilter, update::IncomingMessage};
    /// # fn example(msg: IncomingMessage) {
    /// msg.find_button(ButtonFilter::Text("OK"));
    /// msg.find_button(ButtonFilter::Data(b"cb:ping"));
    /// msg.find_button(ButtonFilter::Pos(0, 0));
    /// # }
    /// ```
    pub fn find_button(&self, filter: ButtonFilter<'_>) -> Option<(usize, usize)> {
        match filter {
            ButtonFilter::Pos(row, col) => {
                if self.extract_callback_data(row, col).is_ok() {
                    Some((row, col))
                } else {
                    None
                }
            }
            ButtonFilter::Text(text) => self.iter_inline_buttons().find_map(|(r, c, btn)| {
                if let tl::enums::KeyboardButton::Callback(b) = btn {
                    if b.text == text { Some((r, c)) } else { None }
                } else {
                    None
                }
            }),
            ButtonFilter::Data(data) => self.iter_inline_buttons().find_map(|(r, c, btn)| {
                if let tl::enums::KeyboardButton::Callback(b) = btn {
                    if b.data.as_slice() == data {
                        Some((r, c))
                    } else {
                        None
                    }
                } else {
                    None
                }
            }),
        }
    }

    /// Find the first inline callback button satisfying `predicate` and return `(row, col)`.
    ///
    /// The closure receives `(text: &str, data: &[u8])`.
    pub fn find_button_where<F>(&self, predicate: F) -> Option<(usize, usize)>
    where
        F: Fn(&str, &[u8]) -> bool,
    {
        self.iter_inline_buttons().find_map(|(r, c, btn)| {
            if let tl::enums::KeyboardButton::Callback(b) = btn {
                if predicate(&b.text, &b.data) {
                    Some((r, c))
                } else {
                    None
                }
            } else {
                None
            }
        })
    }

    /// Press the inline button matching `filter`.
    ///
    /// ```rust,no_run
    /// # use ferogram::{ButtonFilter, update::IncomingMessage};
    /// # async fn example(msg: IncomingMessage) -> Result<(), ferogram::InvocationError> {
    /// msg.click_button(ButtonFilter::Pos(0, 0)).await?;
    /// msg.click_button(ButtonFilter::Text("OK")).await?;
    /// msg.click_button(ButtonFilter::Data(b"action:buy")).await?;
    /// # Ok(()) }
    /// ```
    pub async fn click_button(&self, filter: ButtonFilter<'_>) -> Result<(), Error> {
        let client = self.require_client("click_button")?.clone();
        let data = match filter {
            ButtonFilter::Pos(row, col) => self.extract_callback_data(row, col)?,
            ButtonFilter::Text(text) => self.find_callback_data_by_text(text)?,
            ButtonFilter::Data(data) => data.to_vec(),
        };
        self.invoke_click(&client, data).await
    }
}

/// One or more messages were deleted.
#[derive(Debug, Clone)]
pub struct MessageDeletion {
    /// IDs of the deleted messages.
    pub message_ids: Vec<i32>,
    /// Channel ID, if the deletion happened in a channel / supergroup.
    pub channel_id: Option<i64>,
}

impl MessageDeletion {
    /// Consume self and return the deleted message IDs without cloning.
    pub fn into_messages(self) -> Vec<i32> {
        self.message_ids
    }
}

/// A user pressed an inline keyboard button on a bot message.
#[derive(Debug, Clone)]
pub struct CallbackQuery {
    pub query_id: i64,
    pub user_id: i64,
    pub message_id: Option<i32>,
    pub chat_instance: i64,
    /// Raw `data` bytes from the button.
    pub data_raw: Option<Vec<u8>>,
    /// Game short name (if a game button was pressed).
    pub game_short_name: Option<String>,
    /// The peer (chat/channel/user) where the button was pressed.
    /// `None` for inline-message callback queries.
    pub chat_peer: Option<tl::enums::Peer>,
    /// For inline-message callbacks: the message ID token.
    pub inline_msg_id: Option<tl::enums::InputBotInlineMessageId>,
}

impl CallbackQuery {
    /// Button data as a UTF-8 string, if valid.
    pub fn data(&self) -> Option<&str> {
        self.data_raw
            .as_ref()
            .and_then(|d| std::str::from_utf8(d).ok())
    }

    /// Begin building an answer for this callback query.
    ///
    /// Finish with `.send(&client).await`:
    ///
    /// ```rust,no_run
    /// # use ferogram::{Client, update::CallbackQuery};
    /// # async fn example(query: CallbackQuery, client: Client) -> Result<(), ferogram::InvocationError> {
    /// query.answer().text("Done!").send(&client).await?;
    /// query.answer().alert("No permission!").send(&client).await?;
    /// query.answer().url("https://example.com/game").send(&client).await?;
    /// query.answer()
    /// .text("Cached")
    /// .cache_time(std::time::Duration::from_secs(60))
    /// .send(&client).await?;
    /// # Ok(()) }
    /// ```
    pub fn answer(&self) -> Answer<'_> {
        Answer {
            query_id: self.query_id,
            message: None,
            alert: false,
            url: None,
            cache_time: 0,
            _marker: std::marker::PhantomData,
        }
    }
}

/// Fluent builder returned by [`CallbackQuery::answer`]. Finalize with `.send(&client).await`.
pub struct Answer<'a> {
    query_id: i64,
    message: Option<String>,
    alert: bool,
    url: Option<String>,
    cache_time: i32,
    _marker: std::marker::PhantomData<&'a ()>,
}

impl<'a> Answer<'a> {
    /// Show `text` as a toast notification (fades automatically).
    pub fn text<S: Into<String>>(mut self, text: S) -> Self {
        self.message = Some(text.into());
        self.alert = false;
        self
    }

    /// Show `text` as a modal alert the user must dismiss.
    pub fn alert<S: Into<String>>(mut self, text: S) -> Self {
        self.message = Some(text.into());
        self.alert = true;
        self
    }

    /// Open `url` on the client (e.g. to launch a game).
    pub fn url<S: Into<String>>(mut self, url: S) -> Self {
        self.url = Some(url.into());
        self
    }

    /// Cache this answer for `duration` so repeated presses don't reach the bot.
    pub fn cache_time(mut self, duration: std::time::Duration) -> Self {
        self.cache_time = duration.as_secs().min(i32::MAX as u64) as i32;
        self
    }

    /// Send the answer to Telegram.
    pub async fn send(self, client: &Client) -> Result<(), Error> {
        let req = tl::functions::messages::SetBotCallbackAnswer {
            alert: self.alert,
            query_id: self.query_id,
            message: self.message,
            url: self.url,
            cache_time: self.cache_time,
        };
        client.rpc_call_raw(&req).await.map(|_| ())
    }
}

/// A user is typing an inline query (`@bot something`).
#[derive(Debug, Clone)]
pub struct InlineQuery {
    pub query_id: i64,
    pub user_id: i64,
    pub query: String,
    pub offset: String,
    /// Peer of the chat the user sent the inline query from, if available.
    pub peer: Option<tl::enums::Peer>,
}

impl InlineQuery {
    /// The text the user typed after the bot username.
    pub fn query(&self) -> &str {
        &self.query
    }
}

/// A user chose an inline result and sent it.
#[derive(Debug, Clone)]
pub struct InlineSend {
    pub user_id: i64,
    pub query: String,
    pub id: String,
    /// Message ID of the sent message, if available.
    pub msg_id: Option<tl::enums::InputBotInlineMessageId>,
}

impl InlineSend {
    /// Edit the inline message that was sent as a result of this inline query.
    ///
    /// Requires that [`msg_id`] is present (i.e. the result had `peer_type` set).
    /// Returns `Err` with a descriptive message if `msg_id` is `None`.
    ///
    /// [`msg_id`]: InlineSend::msg_id
    ///
    /// # Example
    /// ```rust,no_run
    /// # async fn f(client: ferogram::Client, send: ferogram::update::InlineSend)
    /// # -> Result<(), Box<dyn std::error::Error>> {
    /// send.edit_message(&client, "updated text", None).await?;
    /// # Ok(()) }
    /// ```
    pub async fn edit_message(
        &self,
        client: &Client,
        new_text: &str,
        reply_markup: Option<tl::enums::ReplyMarkup>,
    ) -> Result<bool, Error> {
        let msg_id =
            match self.msg_id.clone() {
                Some(id) => id,
                None => return Err(Error::Deserialize(
                    "InlineSend::edit_message: msg_id is None (bot_inline_send had no peer_type)"
                        .into(),
                )),
            };
        let req = tl::functions::messages::EditInlineBotMessage {
            no_webpage: false,
            invert_media: false,
            id: msg_id,
            message: Some(new_text.to_string()),
            media: None,
            reply_markup,
            entities: None,
        };
        let body: Vec<u8> = client.rpc_call_raw(&req).await?;
        // Returns Bool
        Ok(!body.is_empty())
    }
}

/// A TL update that has no dedicated high-level variant yet.
///
/// Carries the **original deserialized** [`tl::enums::Update`] so callers can
/// match on it directly, plus the pre-computed constructor ID for quick
/// dispatch without a second match.
///
/// # Example
/// ```rust,no_run
/// # use ferogram::{Update, update::RawUpdate};
/// # use ferogram_tl_types as tl;
/// # async fn example(mut stream: ferogram::UpdateStream) {
/// while let Some(raw) = stream.next_raw().await {
///     match raw.inner {
///         tl::enums::Update::ReadHistoryInbox(u) => { /* handle */ }
///         _ => {}
///     }
/// }
/// # }
/// ```
#[derive(Debug, Clone)]
pub struct RawUpdate {
    /// Constructor ID of the inner update (pre-computed for cheap dispatch).
    pub constructor_id: u32,
    /// The original deserialized TL update. Match on this to extract fields.
    pub inner: tl::enums::Update,
}

/// A user's online / offline status changed.
///
/// Delivered as [`Update::UserStatus`].
///
/// # Example
/// ```rust,no_run
/// # use ferogram::{Update, update::UserStatusUpdate};
/// # async fn example(mut stream: ferogram::UpdateStream) {
/// while let Some(upd) = stream.next().await {
/// if let Update::UserStatus(s) = upd {
///     println!("user {} status: {:?}", s.user_id, s.status);
/// }
/// }
/// # }
/// ```
#[derive(Debug, Clone)]
pub struct UserStatusUpdate {
    /// The bare user ID whose status changed.
    pub user_id: i64,
    /// New online/offline/recently/etc. status.
    pub status: tl::enums::UserStatus,
}

/// A user is performing a chat action (typing, uploading, recording...).
///
/// Delivered as [`Update::UserTyping`].  Covers DMs, groups, and channels.
///
/// # Example
/// ```rust,no_run
/// # use ferogram::{Update, update::ChatActionUpdate};
/// # async fn example(mut stream: ferogram::UpdateStream) {
/// while let Some(upd) = stream.next().await {
/// if let Update::UserTyping(a) = upd {
///     println!("user {} is typing in {:?}", a.user_id, a.peer);
/// }
/// }
/// # }
/// ```
#[derive(Debug, Clone)]
pub struct ChatActionUpdate {
    /// The peer (chat / channel) the action is happening in.
    /// For DM typing updates (`updateUserTyping`) this is the user's own peer.
    pub peer: tl::enums::Peer,
    /// The bare user ID performing the action.
    pub user_id: i64,
    /// What the user is currently doing (typing, uploading video, etc.).
    pub action: tl::enums::SendMessageAction,
}

/// A chat member's status changed (joined, left, promoted, banned, etc.).
///
/// Delivered as [`Update::ParticipantUpdate`].
/// Covers both basic groups (`updateChatParticipant`) and
/// channels/supergroups (`updateChannelParticipant`).
///
/// # Example
/// ```rust,no_run
/// # use ferogram::{Update, update::ParticipantUpdate};
/// # async fn example(mut stream: ferogram::UpdateStream) {
/// while let Some(upd) = stream.next().await {
///     if let Update::ParticipantUpdate(p) = upd {
///         println!(
///             "chat={:?} user={} actor={}: {:?} → {:?}",
///             p.chat_id, p.user_id, p.actor_id,
///             p.prev_participant, p.new_participant,
///         );
///     }
/// }
/// # }
/// ```
#[derive(Debug, Clone)]
pub struct ParticipantUpdate {
    /// The chat (basic-group ID) or channel ID the event happened in.
    pub chat_id: i64,
    /// The user whose membership changed.
    pub user_id: i64,
    /// The admin or bot that triggered the change.
    pub actor_id: i64,
    /// Unix timestamp of the event.
    pub date: i32,
    /// Previous participant record for basic groups
    /// (`None` = user wasn't in the chat before, or this is a channel update).
    pub prev_participant: Option<tl::enums::ChatParticipant>,
    /// New participant record for basic groups
    /// (`None` = user left / was kicked, or this is a channel update).
    pub new_participant: Option<tl::enums::ChatParticipant>,
    /// Previous participant record for channels/supergroups
    /// (`None` for basic-group updates).
    pub prev_channel_participant: Option<tl::enums::ChannelParticipant>,
    /// New participant record for channels/supergroups
    /// (`None` for basic-group updates).
    pub new_channel_participant: Option<tl::enums::ChannelParticipant>,
    /// The invite link used, if any.
    pub invite: Option<tl::enums::ExportedChatInvite>,
    /// QTS counter (used for acknowledgement).
    pub qts: i32,
    /// `true` when the update comes from a channel/supergroup,
    /// `false` for a basic group.
    pub is_channel: bool,
}

/// A user has requested to join a chat via an invite link.
///
/// Delivered as [`Update::JoinRequest`].
/// Only sent to bots that manage the chat (requires `manage_chat` admin right).
///
/// # Example
/// ```rust,no_run
/// # use ferogram::{Update, update::JoinRequestUpdate};
/// # async fn example(mut stream: ferogram::UpdateStream) {
/// while let Some(upd) = stream.next().await {
///     if let Update::JoinRequest(r) = upd {
///         println!("user {} wants to join {:?}: {:?}", r.user_id, r.peer, r.about);
///     }
/// }
/// # }
/// ```
#[derive(Debug, Clone)]
pub struct JoinRequestUpdate {
    /// The chat/channel/group the request is for.
    pub peer: tl::enums::Peer,
    /// The user requesting to join.
    pub user_id: i64,
    /// The user's bio / message attached to the request.
    pub about: String,
    /// The invite link they used.
    pub invite: tl::enums::ExportedChatInvite,
    /// Unix timestamp.
    pub date: i32,
    /// QTS counter.
    pub qts: i32,
}

/// A bot received a reaction on one of its messages.
///
/// Delivered as [`Update::MessageReaction`]. Only for bots.
#[derive(Debug, Clone)]
pub struct MessageReactionUpdate {
    /// The peer (chat/channel) where the reaction occurred.
    pub peer: tl::enums::Peer,
    /// The message ID that was reacted to.
    pub msg_id: i32,
    /// Unix timestamp.
    pub date: i32,
    /// The peer that reacted.
    pub actor: tl::enums::Peer,
    /// Reactions that were removed.
    pub old_reactions: Vec<tl::enums::Reaction>,
    /// Reactions that were added.
    pub new_reactions: Vec<tl::enums::Reaction>,
    /// QTS counter.
    pub qts: i32,
}

/// A user voted in a poll.
///
/// Delivered as [`Update::PollVote`]. Only for bots that sent the poll.
#[derive(Debug, Clone)]
pub struct PollVoteUpdate {
    /// The poll ID.
    pub poll_id: i64,
    /// The peer that voted.
    pub peer: tl::enums::Peer,
    /// The option bytes they selected.
    pub options: Vec<Vec<u8>>,
    /// Their positions in the option list.
    pub positions: Vec<i32>,
    /// QTS counter.
    pub qts: i32,
}

/// A user stopped (or restarted) the bot.
///
/// Delivered as [`Update::BotStopped`].
#[derive(Debug, Clone)]
pub struct BotStoppedUpdate {
    /// The user who stopped/restarted the bot.
    pub user_id: i64,
    /// Unix timestamp.
    pub date: i32,
    /// `true` if the bot was stopped, `false` if restarted.
    pub stopped: bool,
    /// QTS counter.
    pub qts: i32,
}

/// A user submitted a shipping address for a physical-goods invoice.
///
/// Delivered as [`Update::ShippingQuery`]. Only for bots.
///
/// Respond with [`Client::answer_shipping_query`].
#[derive(Debug, Clone)]
pub struct ShippingQueryUpdate {
    /// The query ID - pass to `answer_shipping_query`.
    pub query_id: i64,
    /// The user who submitted the address.
    pub user_id: i64,
    /// The invoice payload you set in `send_invoice`.
    pub payload: Vec<u8>,
    /// The address the user entered.
    pub shipping_address: tl::types::PostAddress,
}

/// A user confirmed payment on the final checkout screen.
///
/// Delivered as [`Update::PreCheckoutQuery`]. Only for bots.
///
/// Respond within 10 seconds via [`Client::answer_precheckout_query`].
#[derive(Debug, Clone)]
pub struct PreCheckoutQueryUpdate {
    /// The query ID - pass to `answer_precheckout_query`.
    pub query_id: i64,
    /// The user who pressed "Pay".
    pub user_id: i64,
    /// The invoice payload you set in `send_invoice`.
    pub payload: Vec<u8>,
    /// Payment info (name, email, phone, etc.) if requested.
    pub info: Option<tl::types::PaymentRequestedInfo>,
    /// The chosen shipping option ID, if applicable.
    pub shipping_option_id: Option<String>,
    /// ISO 4217 currency code (e.g. `"USD"`).
    pub currency: String,
    /// Total amount in the smallest currency unit (e.g. cents).
    pub total_amount: i64,
}

/// A channel was boosted via the bot.
///
/// Delivered as [`Update::ChatBoost`]. Only for bots that manage the channel.
#[derive(Debug, Clone)]
pub struct ChatBoostUpdate {
    /// The channel/chat that was boosted.
    pub peer: tl::enums::Peer,
    /// The boost record.
    pub boost: tl::enums::Boost,
    /// QTS counter.
    pub qts: i32,
}

/// A high-level event received from Telegram.
#[non_exhaustive]
#[derive(Debug, Clone)]
pub enum Update {
    /// A new message (personal chat, group, channel, or bot command).
    NewMessage(IncomingMessage),
    /// An existing message was edited.
    MessageEdited(IncomingMessage),
    /// One or more messages were deleted.
    MessageDeleted(MessageDeletion),
    /// An inline keyboard button was pressed on a bot message.
    CallbackQuery(CallbackQuery),
    /// A user typed an inline query for the bot.
    InlineQuery(InlineQuery),
    /// A user chose an inline result and sent it (bots only).
    InlineSend(InlineSend),
    /// A user's online status changed.
    UserStatus(UserStatusUpdate),
    /// A user is typing / uploading / recording in a chat.
    UserTyping(ChatActionUpdate),
    /// A chat member's status changed (joined, left, promoted, banned).
    /// Covers both basic groups and channels/supergroups.
    ParticipantUpdate(ParticipantUpdate),
    /// A user requested to join a chat via an invite link (bots only).
    JoinRequest(JoinRequestUpdate),
    /// A bot received a reaction on one of its messages (bots only).
    MessageReaction(MessageReactionUpdate),
    /// A user voted in a poll (bots only).
    PollVote(PollVoteUpdate),
    /// A user stopped or restarted the bot.
    BotStopped(BotStoppedUpdate),
    /// A user submitted a shipping address for a physical-goods invoice (bots only).
    ShippingQuery(ShippingQueryUpdate),
    /// A user confirmed payment on the final pre-checkout screen (bots only).
    PreCheckoutQuery(PreCheckoutQueryUpdate),
    /// A channel was boosted via the bot (bots only).
    ChatBoost(ChatBoostUpdate),
    /// A raw TL update not mapped to any of the above variants.
    Raw(Box<RawUpdate>),
}

#[allow(dead_code)]
const ID_UPDATES_TOO_LONG: u32 = 0xe317af7e;
#[allow(dead_code)]
const ID_UPDATE_SHORT_MESSAGE: u32 = 0x313bc7f8;
#[allow(dead_code)]
const ID_UPDATE_SHORT_CHAT_MSG: u32 = 0x4d6deea5;
#[allow(dead_code)]
const ID_UPDATE_SHORT: u32 = 0x78d4dec1;
#[allow(dead_code)]
const ID_UPDATES: u32 = 0x74ae4240;
#[allow(dead_code)]
const ID_UPDATES_COMBINED: u32 = 0x725b04c3;
#[allow(dead_code)]
const ID_UPDATE_SHORT_SENT_MSG: u32 = 0x9015e101;

/// Parse raw update container bytes into high-level [`Update`] values.
#[allow(dead_code)]
pub(crate) fn parse_updates(bytes: &[u8]) -> Vec<Update> {
    if bytes.len() < 4 {
        return vec![];
    }
    let cid = u32::from_le_bytes(bytes[..4].try_into().unwrap());

    match cid {
        ID_UPDATES_TOO_LONG => {
            tracing::warn!(
                "[ferogram] updatesTooLong: call client.get_difference() to recover missed updates"
            );
            vec![]
        }

        ID_UPDATE_SHORT_MESSAGE => {
            let mut cur = Cursor::from_slice(&bytes[4..]); // skip constructor prefix
            match tl::types::UpdateShortMessage::deserialize(&mut cur) {
                Ok(m) => vec![Update::NewMessage(make_short_dm(m))],
                Err(e) => {
                    tracing::debug!(
                        "[ferogram] updateShortMessage parse error (unknown constructor or newer layer): {e}"
                    );
                    vec![]
                }
            }
        }

        ID_UPDATE_SHORT_CHAT_MSG => {
            let mut cur = Cursor::from_slice(&bytes[4..]); // skip constructor prefix
            match tl::types::UpdateShortChatMessage::deserialize(&mut cur) {
                Ok(m) => vec![Update::NewMessage(make_short_chat(m))],
                Err(e) => {
                    tracing::debug!(
                        "[ferogram] updateShortChatMessage parse error (unknown constructor or newer layer): {e}"
                    );
                    vec![]
                }
            }
        }

        ID_UPDATE_SHORT => {
            let mut cur = Cursor::from_slice(&bytes[4..]); // skip constructor prefix
            match tl::types::UpdateShort::deserialize(&mut cur) {
                Ok(m) => from_single_update(m.update),
                Err(e) => {
                    tracing::debug!(
                        "[ferogram] updateShort parse error (unknown constructor or newer layer): {e}"
                    );
                    vec![]
                }
            }
        }

        ID_UPDATES => {
            let mut cur = Cursor::from_slice(bytes);
            match tl::enums::Updates::deserialize(&mut cur) {
                Ok(tl::enums::Updates::Updates(u)) => {
                    u.updates.into_iter().flat_map(from_single_update).collect()
                }
                Err(e) => {
                    tracing::debug!(
                        "[ferogram] Updates parse error (unknown constructor or newer layer): {e}"
                    );
                    vec![]
                }
                _ => vec![],
            }
        }

        ID_UPDATES_COMBINED => {
            let mut cur = Cursor::from_slice(bytes);
            match tl::enums::Updates::deserialize(&mut cur) {
                Ok(tl::enums::Updates::Combined(u)) => {
                    u.updates.into_iter().flat_map(from_single_update).collect()
                }
                Err(e) => {
                    tracing::debug!(
                        "[ferogram] UpdatesCombined parse error (unknown constructor or newer layer): {e}"
                    );
                    vec![]
                }
                _ => vec![],
            }
        }

        // updateShortSentMessage: pts is now handled by dispatch_updates/route_frame
        // directly (via EnvelopeResult::Pts or the push branch). parse_updates is only
        // called for the old code path; we absorb here as a safe fallback.
        ID_UPDATE_SHORT_SENT_MSG => vec![],

        _ => vec![],
    }
}

/// Convert a single `tl::enums::Update` into a `Vec<Update>`.
pub(crate) fn from_single_update(upd: tl::enums::Update) -> Vec<Update> {
    use tl::enums::Update::*;
    match upd {
        NewMessage(u) => vec![Update::NewMessage(IncomingMessage::from_raw(u.message))],
        NewChannelMessage(u) => vec![Update::NewMessage(IncomingMessage::from_raw(u.message))],
        EditMessage(u) => vec![Update::MessageEdited(IncomingMessage::from_raw(u.message))],
        EditChannelMessage(u) => vec![Update::MessageEdited(IncomingMessage::from_raw(u.message))],
        DeleteMessages(u) => vec![Update::MessageDeleted(MessageDeletion {
            message_ids: u.messages,
            channel_id: None,
        })],
        DeleteChannelMessages(u) => vec![Update::MessageDeleted(MessageDeletion {
            message_ids: u.messages,
            channel_id: Some(u.channel_id),
        })],
        BotCallbackQuery(u) => vec![Update::CallbackQuery(CallbackQuery {
            query_id: u.query_id,
            user_id: u.user_id,
            message_id: Some(u.msg_id),
            chat_instance: u.chat_instance,
            data_raw: u.data,
            game_short_name: u.game_short_name,
            chat_peer: Some(u.peer),
            inline_msg_id: None,
        })],
        InlineBotCallbackQuery(u) => vec![Update::CallbackQuery(CallbackQuery {
            query_id: u.query_id,
            user_id: u.user_id,
            message_id: None,
            chat_instance: u.chat_instance,
            data_raw: u.data,
            game_short_name: u.game_short_name,
            chat_peer: None,
            inline_msg_id: Some(u.msg_id),
        })],
        BotInlineQuery(u) => vec![Update::InlineQuery(InlineQuery {
            query_id: u.query_id,
            user_id: u.user_id,
            query: u.query,
            offset: u.offset,
            peer: None,
        })],
        BotInlineSend(u) => vec![Update::InlineSend(InlineSend {
            user_id: u.user_id,
            query: u.query,
            id: u.id,
            msg_id: u.msg_id,
        })],
        // typed UserStatus variant
        UserStatus(u) => vec![Update::UserStatus(UserStatusUpdate {
            user_id: u.user_id,
            status: u.status,
        })],
        // typed ChatAction variant: DM typing
        UserTyping(u) => vec![Update::UserTyping(ChatActionUpdate {
            peer: tl::enums::Peer::User(tl::types::PeerUser { user_id: u.user_id }),
            user_id: u.user_id,
            action: u.action,
        })],
        // group typing
        ChatUserTyping(u) => vec![Update::UserTyping(ChatActionUpdate {
            peer: tl::enums::Peer::Chat(tl::types::PeerChat { chat_id: u.chat_id }),
            user_id: match u.from_id {
                tl::enums::Peer::User(ref p) => p.user_id,
                tl::enums::Peer::Chat(ref p) => p.chat_id,
                tl::enums::Peer::Channel(ref p) => p.channel_id,
            },
            action: u.action,
        })],
        // channel / supergroup typing
        ChannelUserTyping(u) => vec![Update::UserTyping(ChatActionUpdate {
            peer: tl::enums::Peer::Channel(tl::types::PeerChannel {
                channel_id: u.channel_id,
            }),
            user_id: match u.from_id {
                tl::enums::Peer::User(ref p) => p.user_id,
                tl::enums::Peer::Chat(ref p) => p.chat_id,
                tl::enums::Peer::Channel(ref p) => p.channel_id,
            },
            action: u.action,
        })],
        // basic-group participant change
        ChatParticipant(u) => vec![Update::ParticipantUpdate(ParticipantUpdate {
            chat_id: u.chat_id,
            user_id: u.user_id,
            actor_id: u.actor_id,
            date: u.date,
            prev_participant: u.prev_participant,
            new_participant: u.new_participant,
            prev_channel_participant: None,
            new_channel_participant: None,
            invite: u.invite,
            qts: u.qts,
            is_channel: false,
        })],
        // channel/supergroup participant change
        ChannelParticipant(u) => vec![Update::ParticipantUpdate(ParticipantUpdate {
            chat_id: u.channel_id,
            user_id: u.user_id,
            actor_id: u.actor_id,
            date: u.date,
            prev_participant: None,
            new_participant: None,
            prev_channel_participant: u.prev_participant,
            new_channel_participant: u.new_participant,
            invite: u.invite,
            qts: u.qts,
            is_channel: true,
        })],
        // join request (bots only)
        BotChatInviteRequester(u) => vec![Update::JoinRequest(JoinRequestUpdate {
            peer: u.peer,
            user_id: u.user_id,
            about: u.about,
            invite: u.invite,
            date: u.date,
            qts: u.qts,
        })],
        // message reaction (bots only)
        BotMessageReaction(u) => vec![Update::MessageReaction(MessageReactionUpdate {
            peer: u.peer,
            msg_id: u.msg_id,
            date: u.date,
            actor: u.actor,
            old_reactions: u.old_reactions,
            new_reactions: u.new_reactions,
            qts: u.qts,
        })],
        // poll vote (bots only)
        MessagePollVote(u) => vec![Update::PollVote(PollVoteUpdate {
            poll_id: u.poll_id,
            peer: u.peer,
            options: u.options,
            positions: u.positions,
            qts: u.qts,
        })],
        // bot stopped / restarted
        BotStopped(u) => vec![Update::BotStopped(BotStoppedUpdate {
            user_id: u.user_id,
            date: u.date,
            stopped: u.stopped,
            qts: u.qts,
        })],
        // shipping query (bots only)
        BotShippingQuery(u) => vec![Update::ShippingQuery(ShippingQueryUpdate {
            query_id: u.query_id,
            user_id: u.user_id,
            payload: u.payload,
            shipping_address: match u.shipping_address {
                tl::enums::PostAddress::PostAddress(a) => a,
            },
        })],
        // pre-checkout query (bots only)
        BotPrecheckoutQuery(u) => vec![Update::PreCheckoutQuery(PreCheckoutQueryUpdate {
            query_id: u.query_id,
            user_id: u.user_id,
            payload: u.payload,
            info: u.info.map(|i| match i {
                tl::enums::PaymentRequestedInfo::PaymentRequestedInfo(x) => x,
            }),
            shipping_option_id: u.shipping_option_id,
            currency: u.currency,
            total_amount: u.total_amount,
        })],
        // channel boost (bots only)
        BotChatBoost(u) => vec![Update::ChatBoost(ChatBoostUpdate {
            peer: u.peer,
            boost: u.boost,
            qts: u.qts,
        })],
        other => {
            let cid = tl_constructor_id(&other);
            vec![Update::Raw(Box::new(RawUpdate {
                constructor_id: cid,
                inner: other,
            }))]
        }
    }
}

/// Extract constructor ID from a `tl::enums::Update` variant.
fn tl_constructor_id(upd: &tl::enums::Update) -> u32 {
    use tl::enums::Update::*;
    match upd {
        AttachMenuBots => 0x17b7a20b,
        AutoSaveSettings => 0xec05b097,
        BotBusinessConnect(_) => 0x8ae5c97a,
        BotCallbackQuery(_) => 0xb9cfc48d,
        BotChatBoost(_) => 0x904dd49c,
        BotChatInviteRequester(_) => 0x11dfa986,
        BotCommands(_) => 0x4d712f2e,
        BotDeleteBusinessMessage(_) => 0xa02a982e,
        BotEditBusinessMessage(_) => 0x7df587c,
        BotInlineQuery(_) => 0x496f379c,
        BotInlineSend(_) => 0x12f12a07,
        BotMenuButton(_) => 0x14b85813,
        BotMessageReaction(_) => 0xac21d3ce,
        BotMessageReactions(_) => 0x9cb7759,
        BotNewBusinessMessage(_) => 0x9ddb347c,
        BotPrecheckoutQuery(_) => 0x8caa9a96,
        BotPurchasedPaidMedia(_) => 0x283bd312,
        BotShippingQuery(_) => 0xb5aefd7d,
        BotStopped(_) => 0xc4870a49,
        BotWebhookJson(_) => 0x8317c0c3,
        BotWebhookJsonquery(_) => 0x9b9240a6,
        BusinessBotCallbackQuery(_) => 0x1ea2fda7,
        Channel(_) => 0x635b4c09,
        ChannelAvailableMessages(_) => 0xb23fc698,
        ChannelMessageForwards(_) => 0xd29a27f4,
        ChannelMessageViews(_) => 0xf226ac08,
        ChannelParticipant(_) => 0x985d3abb,
        ChannelReadMessagesContents(_) => 0x25f324f7,
        ChannelTooLong(_) => 0x108d941f,
        ChannelUserTyping(_) => 0x8c88c923,
        ChannelViewForumAsMessages(_) => 0x7b68920,
        ChannelWebPage(_) => 0x2f2ba99f,
        Chat(_) => 0xf89a6a4e,
        ChatDefaultBannedRights(_) => 0x54c01850,
        ChatParticipant(_) => 0xd087663a,
        ChatParticipantAdd(_) => 0x3dda5451,
        ChatParticipantAdmin(_) => 0xd7ca61a2,
        ChatParticipantDelete(_) => 0xe32f3d77,
        ChatParticipants(_) => 0x7761198,
        ChatUserTyping(_) => 0x83487af0,
        Config => 0xa229dd06,
        ContactsReset => 0x7084a7be,
        DcOptions(_) => 0x8e5e9873,
        DeleteChannelMessages(_) => 0xc32d5b12,
        DeleteGroupCallMessages(_) => 0x3e85e92c,
        DeleteMessages(_) => 0xa20db0e5,
        DeleteQuickReply(_) => 0x53e6f1ec,
        DeleteQuickReplyMessages(_) => 0x566fe7cd,
        DeleteScheduledMessages(_) => 0xf2a71983,
        DialogFilter(_) => 0x26ffde7d,
        DialogFilterOrder(_) => 0xa5d72105,
        DialogFilters => 0x3504914f,
        DialogPinned(_) => 0x6e6fe51c,
        DialogUnreadMark(_) => 0xb658f23e,
        DraftMessage(_) => 0xedfc111e,
        EditChannelMessage(_) => 0x1b3f4df7,
        EditMessage(_) => 0xe40370a3,
        EmojiGameInfo(_) => 0xfb9c547a,
        EncryptedChatTyping(_) => 0x1710f156,
        EncryptedMessagesRead(_) => 0x38fe25b7,
        Encryption(_) => 0xb4a2e88d,
        FavedStickers => 0xe511996d,
        FolderPeers(_) => 0x19360dc0,
        GeoLiveViewed(_) => 0x871fb939,
        GroupCall(_) => 0x9d2216e0,
        GroupCallChainBlocks(_) => 0xa477288f,
        GroupCallConnection(_) => 0xb783982,
        GroupCallEncryptedMessage(_) => 0xc957a766,
        GroupCallMessage(_) => 0xd8326f0d,
        GroupCallParticipants(_) => 0xf2ebdb4e,
        InlineBotCallbackQuery(_) => 0x691e9052,
        LangPack(_) => 0x56022f4d,
        LangPackTooLong(_) => 0x46560264,
        LoginToken => 0x564fe691,
        MessageExtendedMedia(_) => 0xd5a41724,
        MessageId(_) => 0x4e90bfd6,
        MessagePoll(_) => 0xaca1657b,
        MessagePollVote(_) => 0x24f40e77,
        MessageReactions(_) => 0x1e297bfa,
        MonoForumNoPaidException(_) => 0x9f812b08,
        MoveStickerSetToTop(_) => 0x86fccf85,
        NewAuthorization(_) => 0x8951abef,
        NewChannelMessage(_) => 0x62ba04d9,
        NewEncryptedMessage(_) => 0x12bcbd9a,
        NewMessage(_) => 0x1f2b0afd,
        NewQuickReply(_) => 0xf53da717,
        NewScheduledMessage(_) => 0x39a51dfb,
        NewStickerSet(_) => 0x688a30aa,
        NewStoryReaction(_) => 0x1824e40b,
        NotifySettings(_) => 0xbec268ef,
        PaidReactionPrivacy(_) => 0x8b725fce,
        PeerBlocked(_) => 0xebe07752,
        PeerHistoryTtl(_) => 0xbb9bb9a5,
        PeerLocated(_) => 0xb4afcfb0,
        PeerSettings(_) => 0x6a7e7366,
        PeerWallpaper(_) => 0xae3f101d,
        PendingJoinRequests(_) => 0x7063c3db,
        PhoneCall(_) => 0xab0f6b1e,
        PhoneCallSignalingData(_) => 0x2661bf09,
        PinnedChannelMessages(_) => 0x5bb98608,
        PinnedDialogs(_) => 0xfa0f3ca2,
        PinnedForumTopic(_) => 0x683b2c52,
        PinnedForumTopics(_) => 0xdef143d0,
        PinnedMessages(_) => 0xed85eab5,
        PinnedSavedDialogs(_) => 0x686c85a6,
        Privacy(_) => 0xee3b272a,
        PtsChanged => 0x3354678f,
        QuickReplies(_) => 0xf9470ab2,
        QuickReplyMessage(_) => 0x3e050d0f,
        ReadChannelDiscussionInbox(_) => 0xd6b19546,
        ReadChannelDiscussionOutbox(_) => 0x695c9e7c,
        ReadChannelInbox(_) => 0x922e6e10,
        ReadChannelOutbox(_) => 0xb75f99a9,
        ReadFeaturedEmojiStickers => 0xfb4c496c,
        ReadFeaturedStickers => 0x571d2742,
        ReadHistoryInbox(_) => 0x9e84bc99,
        ReadHistoryOutbox(_) => 0x2f2f21bf,
        ReadMessagesContents(_) => 0xf8227181,
        ReadMonoForumInbox(_) => 0x77b0e372,
        ReadMonoForumOutbox(_) => 0xa4a79376,
        ReadStories(_) => 0xf74e932b,
        RecentEmojiStatuses => 0x30f443db,
        RecentReactions => 0x6f7863f4,
        RecentStickers => 0x9a422c20,
        SavedDialogPinned(_) => 0xaeaf9e74,
        SavedGifs => 0x9375341e,
        SavedReactionTags => 0x39c67432,
        SavedRingtones => 0x74d8be99,
        SentPhoneCode(_) => 0x504aa18f,
        SentStoryReaction(_) => 0x7d627683,
        ServiceNotification(_) => 0xebe46819,
        SmsJob(_) => 0xf16269d4,
        StarGiftAuctionState(_) => 0x48e246c2,
        StarGiftAuctionUserState(_) => 0xdc58f31e,
        StarGiftCraftFail => 0xac072444,
        StarsBalance(_) => 0x4e80a379,
        StarsRevenueStatus(_) => 0xa584b019,
        StickerSets(_) => 0x31c24808,
        StickerSetsOrder(_) => 0xbb2d201,
        StoriesStealthMode(_) => 0x2c084dc1,
        Story(_) => 0x75b3b798,
        StoryId(_) => 0x1bf335b9,
        Theme(_) => 0x8216fba3,
        TranscribedAudio(_) => 0x84cd5a,
        User(_) => 0x20529438,
        UserEmojiStatus(_) => 0x28373599,
        UserName(_) => 0xa7848924,
        UserPhone(_) => 0x5492a13,
        UserStatus(_) => 0xe5bdf8de,
        UserTyping(_) => 0x2a17bf5c,
        WebPage(_) => 0x7f891213,
        WebViewResultSent(_) => 0x1592b79d,
        ChatParticipantRank(_) => 0xbd8367b9,
        ManagedBot(_) => 0x4880ed9a,
    }
}

pub(crate) fn make_short_dm(m: tl::types::UpdateShortMessage) -> IncomingMessage {
    let msg = tl::types::Message {
        out: m.out,
        mentioned: m.mentioned,
        media_unread: m.media_unread,
        silent: m.silent,
        post: false,
        from_scheduled: false,
        legacy: false,
        edit_hide: false,
        pinned: false,
        noforwards: false,
        invert_media: false,
        offline: false,
        video_processing_pending: false,
        id: m.id,
        from_id: Some(tl::enums::Peer::User(tl::types::PeerUser {
            user_id: m.user_id,
        })),
        peer_id: tl::enums::Peer::User(tl::types::PeerUser { user_id: m.user_id }),
        saved_peer_id: None,
        fwd_from: m.fwd_from,
        via_bot_id: m.via_bot_id,
        via_business_bot_id: None,
        reply_to: m.reply_to,
        date: m.date,
        message: m.message,
        media: None,
        reply_markup: None,
        entities: m.entities,
        views: None,
        forwards: None,
        replies: None,
        edit_date: None,
        post_author: None,
        grouped_id: None,
        reactions: None,
        restriction_reason: None,
        ttl_period: None,
        quick_reply_shortcut_id: None,
        effect: None,
        factcheck: None,
        report_delivery_until_date: None,
        paid_message_stars: None,
        suggested_post: None,
        from_rank: None,
        from_boosts_applied: None,
        paid_suggested_post_stars: false,
        paid_suggested_post_ton: false,
        schedule_repeat_period: None,
        summary_from_language: None,
    };
    IncomingMessage {
        raw: tl::enums::Message::Message(msg),
        client: None,
    }
}

pub(crate) fn make_short_chat(m: tl::types::UpdateShortChatMessage) -> IncomingMessage {
    let msg = tl::types::Message {
        out: m.out,
        mentioned: m.mentioned,
        media_unread: m.media_unread,
        silent: m.silent,
        post: false,
        from_scheduled: false,
        legacy: false,
        edit_hide: false,
        pinned: false,
        noforwards: false,
        invert_media: false,
        offline: false,
        video_processing_pending: false,
        id: m.id,
        from_id: Some(tl::enums::Peer::User(tl::types::PeerUser {
            user_id: m.from_id,
        })),
        peer_id: tl::enums::Peer::Chat(tl::types::PeerChat { chat_id: m.chat_id }),
        saved_peer_id: None,
        fwd_from: m.fwd_from,
        via_bot_id: m.via_bot_id,
        via_business_bot_id: None,
        reply_to: m.reply_to,
        date: m.date,
        message: m.message,
        media: None,
        reply_markup: None,
        entities: m.entities,
        views: None,
        forwards: None,
        replies: None,
        edit_date: None,
        post_author: None,
        grouped_id: None,
        reactions: None,
        restriction_reason: None,
        ttl_period: None,
        quick_reply_shortcut_id: None,
        effect: None,
        factcheck: None,
        report_delivery_until_date: None,
        paid_message_stars: None,
        suggested_post: None,
        from_rank: None,
        from_boosts_applied: None,
        paid_suggested_post_stars: false,
        paid_suggested_post_ton: false,
        schedule_repeat_period: None,
        summary_from_language: None,
    };
    IncomingMessage {
        raw: tl::enums::Message::Message(msg),
        client: None,
    }
}