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
//! The event loop for handling bot updates.

#[allow(clippy::wildcard_imports)]
use crate::{
    contexts::{fields::Context, *},
    errors::{self, MethodCall},
    state::StatefulEventLoop,
    types::{
        self, callback,
        callback::Query,
        message::{
            self,
            text::{Entity, EntityKind},
            Message,
        },
        update, BotCommand,
    },
    Bot,
};
use std::{collections::HashMap, future::Future, sync::Arc};
use tracing::{error, instrument, trace, warn};
use type_map::concurrent::TypeMap;

#[macro_use]
mod handlers_macros;

mod polling;
pub mod webhook;

pub use {polling::Polling, webhook::Webhook};

// Wish trait alises came out soon
type Handler<T> = dyn Fn(Arc<T>) + Send + Sync;
type Handlers<T> = Vec<Box<Handler<T>>>;
type Map<T> = HashMap<String, Handlers<T>>;

/// Provides an event loop for handling Telegram updates.
///
/// With `EventLoop`, you can configure handlers and start listening to updates
/// via either [polling] or [webhook].
///
/// ```no_run
/// let mut bot = tbot::from_env!("BOT_TOKEN").event_loop();
///
/// bot.text(|_| async { println!("Got a text message") });
///
/// bot.polling().start();
/// ```
///
/// `tbot` has many update handlers, such as [`text`] you have seen
/// in the example. You can find all of them below on this page.
///
/// [polling]: Self::polling
/// [webhook]: Self::webhook
/// [`text`]: Self::text
#[must_use]
pub struct EventLoop {
    bot: Bot,
    username: Option<String>,

    command_handlers: Map<Command>,
    command_description: HashMap<String, String>,
    edited_command_handlers: Map<EditedCommand>,
    update_handlers: TypeMap,
}

impl EventLoop {
    pub(crate) fn new(bot: Bot) -> Self {
        Self {
            bot,
            username: None,
            command_handlers: HashMap::new(),
            command_description: HashMap::new(),
            edited_command_handlers: HashMap::new(),
            update_handlers: TypeMap::new(),
        }
    }

    /// Turns this event loop into a stateful one. Handlers added on this event
    /// loop are kept.
    pub fn into_stateful<S>(self, state: S) -> StatefulEventLoop<S>
    where
        S: Send + Sync + 'static,
    {
        StatefulEventLoop::new(self, state)
    }

    /// Sets the bot's username.
    ///
    /// The username is used when checking if a command such as
    /// `/command@username` was directed to the bot.
    pub fn username(&mut self, username: String) {
        self.username = Some(username);
    }

    /// Fetches the bot's username.
    ///
    /// The username is used when checking if a command such as
    /// `/command@username` was directed to the bot.
    pub async fn fetch_username(&mut self) -> Result<(), errors::MethodCall> {
        let me = self.bot.get_me().call().await?;

        let username = me
            .user
            .username
            .expect("[tbot] Expected the bot to have a username");
        self.username(username);

        Ok(())
    }

    /// Starts polling configuration.
    pub fn polling(self) -> Polling {
        Polling::new(self)
    }

    /// Starts webhook configuration.
    ///
    /// See our [wiki] to learn how to use webhook with `tbot`.
    ///
    /// [wiki]: https://gitlab.com/SnejUgal/tbot/wikis/How-to/How-to-use-webhooks
    pub fn webhook(self, url: &str, port: u16) -> Webhook<'_> {
        Webhook::new(self, url, port)
    }

    fn add_handler<C, H, F>(&mut self, handler: H)
    where
        C: Context,
        H: Fn(Arc<C>) -> F + Send + Sync + 'static,
        F: Future<Output = ()> + Send + 'static,
    {
        self.update_handlers
            .entry::<Handlers<C>>()
            .or_insert_with(Vec::new)
            .push(Box::new(move |context| {
                tokio::spawn(handler(context));
            }));
    }

    fn will_handle<C: Context>(&self) -> bool {
        self.update_handlers.contains::<Handlers<C>>()
    }

    #[allow(clippy::needless_pass_by_value)]
    fn handle<C: Context>(&self, context: Arc<C>) {
        let Some(handlers) = self.update_handlers.get::<Handlers<C>>() else {
            return;
        };

        handlers
            .iter()
            .for_each(|handler| handler(Arc::clone(&context)));
    }

    /// Registers a new handler for a command.
    ///
    /// Note that commands such as `/command@username` will be completely
    /// ignored unless you configure the event loop with your bot's username
    /// with either [`username`] or [`fetch_username`].
    ///
    /// It is idiomatic to omit the leading `/` in the command. Even though
    /// keeping it will work as expected, `tbot` will emit a warning in this case.
    ///
    /// [`username`]: Self::username
    /// [`fetch_username`]: Self::fetch_username
    pub fn command<H, F>(&mut self, command: &'static str, handler: H)
    where
        H: (Fn(Arc<Command>) -> F) + Send + Sync + 'static,
        F: Future<Output = ()> + Send + 'static,
    {
        let command = normalize_cmd_name(command);
        self.command_handlers
            .entry(command.to_string())
            .or_insert_with(Vec::new)
            .push(Box::new(move |context| {
                tokio::spawn(handler(context));
            }));
    }

    /// Registers a new handler for a command and sets its description.
    ///
    /// Note that commands such as `/command@username` will be completely
    /// ignored unless you configure the event loop with your bot's username
    /// with either [`username`] or [`fetch_username`].
    ///
    /// It is idiomatic to omit the leading `/` in the command. Even though
    /// keeping it will work as expected, `tbot` will emit a warning in this case.
    ///
    /// [`username`]: Self::username
    /// [`fetch_username`]: Self::fetch_username
    pub fn command_with_description<H, F>(
        &mut self,
        command: &'static str,
        description: &'static str,
        handler: H,
    ) where
        H: (Fn(Arc<Command>) -> F) + Send + Sync + 'static,
        F: Future<Output = ()> + Send + 'static,
    {
        let command = normalize_cmd_name(command);
        self.command_description
            .insert(command.to_string(), description.to_string());
        self.command(command, handler);
    }

    /// Registers a new handler for a sequence of commands.
    ///
    /// Note that commands such as `/command@username` will be completely
    /// ignored unless you configure the event loop with your bot's username
    /// with either [`username`] or [`fetch_username`].
    ///
    /// It is idiomatic to omit the leading `/` in the commands. Even though
    /// keeping it will work as expected, `tbot` will emit a warning in this case.
    ///
    /// [`username`]: Self::username
    /// [`fetch_username`]: Self::fetch_username
    pub fn commands<Cm, H, F>(&mut self, commands: Cm, handler: H)
    where
        Cm: IntoIterator<Item = &'static str>,
        F: Future<Output = ()> + Send + 'static,
        H: (Fn(Arc<Command>) -> F) + Send + Sync + 'static,
    {
        let handler = Arc::new(handler);

        for command in commands {
            let handler = Arc::clone(&handler);
            let command = normalize_cmd_name(command);
            self.command_handlers
                .entry(command.to_string())
                .or_insert_with(Vec::new)
                .push(Box::new(move |context| {
                    tokio::spawn(handler(context));
                }));
        }
    }

    fn will_handle_command(&self, command: &str) -> bool {
        self.command_handlers.contains_key(command)
    }

    fn handle_command(&self, command: &str, context: &Arc<Command>) {
        if let Some(handlers) = self.command_handlers.get(command) {
            for handler in handlers {
                handler(context.clone());
            }
        }
    }

    /// Registers a new handler for the `/start` command.
    pub fn start<H, F>(&mut self, handler: H)
    where
        H: (Fn(Arc<Command>) -> F) + Send + Sync + 'static,
        F: Future<Output = ()> + Send + 'static,
    {
        self.command("start", handler);
    }

    /// Registers a new handler for the `/start` command and sets its
    /// description.
    pub fn start_with_description<H, F>(
        &mut self,
        description: &'static str,
        handler: H,
    ) where
        H: (Fn(Arc<Command>) -> F) + Send + Sync + 'static,
        F: Future<Output = ()> + Send + 'static,
    {
        self.command_with_description("start", description, handler);
    }

    /// Registers a new handler for the `/settings` command.
    pub fn settings<H, F>(&mut self, handler: H)
    where
        H: (Fn(Arc<Command>) -> F) + Send + Sync + 'static,
        F: Future<Output = ()> + Send + 'static,
    {
        self.command("settings", handler);
    }

    /// Registers a new handler for the `/settings` command and sets its
    /// description.
    pub fn settings_with_description<H, F>(
        &mut self,
        description: &'static str,
        handler: H,
    ) where
        H: (Fn(Arc<Command>) -> F) + Send + Sync + 'static,
        F: Future<Output = ()> + Send + 'static,
    {
        self.command_with_description("settings", description, handler);
    }

    /// Registers a new handler for the `/help` command.
    pub fn help<H, F>(&mut self, handler: H)
    where
        H: (Fn(Arc<Command>) -> F) + Send + Sync + 'static,
        F: Future<Output = ()> + Send + 'static,
    {
        self.command("help", handler);
    }

    /// Registers a new handler for the `/help` command and sets its
    /// description.
    pub fn help_with_description<H, F>(
        &mut self,
        description: &'static str,
        handler: H,
    ) where
        H: (Fn(Arc<Command>) -> F) + Send + Sync + 'static,
        F: Future<Output = ()> + Send + 'static,
    {
        self.command_with_description("help", description, handler);
    }

    /// Registers a new handler for an edited command.
    ///
    /// It is idiomatic to omit the leading `/` in the commands. Even though
    /// keeping it will work as expected, `tbot` will emit a warning in this case.
    pub fn edited_command<H, F>(&mut self, command: &'static str, handler: H)
    where
        H: (Fn(Arc<EditedCommand>) -> F) + Send + Sync + 'static,
        F: Future<Output = ()> + Send + 'static,
    {
        let command = normalize_cmd_name(command);
        self.edited_command_handlers
            .entry(command.to_string())
            .or_insert_with(Vec::new)
            .push(Box::new(move |context| {
                tokio::spawn(handler(context));
            }));
    }

    /// Registers a new handler for an edited command from sequence of commands.
    ///
    /// It is idiomatic to omit the leading `/` in the commands. Even though
    /// keeping it will work as expected, `tbot` will emit a warning in this case.
    pub fn edited_commands<Cm, H, F>(&mut self, commands: Cm, handler: H)
    where
        Cm: IntoIterator<Item = &'static str>,
        F: Future<Output = ()> + Send + 'static,
        H: (Fn(Arc<EditedCommand>) -> F) + Send + Sync + 'static,
    {
        let handler = Arc::new(handler);

        for command in commands {
            let handler = Arc::clone(&handler);
            let command = normalize_cmd_name(command);
            self.edited_command_handlers
                .entry(command.to_string())
                .or_insert_with(Vec::new)
                .push(Box::new(move |context| {
                    tokio::spawn(handler(context));
                }));
        }
    }

    fn will_handle_edited_command(&self, command: &str) -> bool {
        self.edited_command_handlers.contains_key(command)
    }

    fn handle_edited_command(
        &self,
        command: &str,
        context: &Arc<EditedCommand>,
    ) {
        if let Some(handlers) = self.edited_command_handlers.get(command) {
            for handler in handlers {
                handler(context.clone());
            }
        }
    }

    handlers! {
        /// Registers a new handler for all incoming updates.
        ///
        /// `any_update` handlers are spawned before specialized handlers,
        /// for every update that could be deserialized (this means that
        /// processing new updates on old versions of `tbot` is not possible
        /// even via `any_update`).
        ///
        /// Note “spawned”: every handler is executed using [`tokio::spawn`],
        /// and `tbot` won't wait for them to finish. As such, `any_update` is
        /// not suitable for running some code before every specialized handler.
        ///
        /// Also, `any_update` does not affect [`unhandled`] in any way. It's
        /// executed if a _specialized_ handler corresponding to the incoming
        /// update wasn't registered.
        ///
        /// Registering specialized handler is still preferred. if at least
        /// one `any_update` handler is registered, `tbot` will have to clone
        /// every update in order to execute these and specialized handlers.
        ///
        /// [`unhandled`]: Self::unhandled
        any_update: AnyUpdate,
        /// Registers a new handler for animations.
        animation: Animation,
        /// Registers a new handler for audio.
        audio: Audio,
        /// Registers a new handler for changed auto-delete timers.
        changed_auto_delete_timer: ChangedAutoDeleteTimer,
        /// Registers a new handler for chat members' updated information.
        chat_member: ChatMember,
        /// Registers a new handler for chosen inline results.
        chosen_inline: ChosenInline,
        /// Registers a new handler for contacts.
        contact: Contact,
        /// Registers a new handler for connected websites.
        connected_website: ConnectedWebsite,
        /// Registers a new handler for created groups.
        created_group: CreatedGroup,
        /// Registers a new handler for data callbacks from chat messages.
        message_data_callback: MessageDataCallback,
        /// Registers a new handler for data callbacks from inline messages.
        inline_data_callback: InlineDataCallback,
        /// Registers a new handler for deleted chat photos.
        deleted_chat_photo: DeletedChatPhoto,
        /// Registers a new handler for dice.
        dice: Dice,
        /// Registers a new handler for documents.
        document: Document,
        /// Registers a new handler for edited animations.
        edited_animation: EditedAnimation,
        /// Registers a new handler for edited audio.
        edited_audio: EditedAudio,
        /// Registers a new handler for edited documents.
        edited_document: EditedDocument,
        /// Registers a new handler for edited locations.
        edited_location: EditedLocation,
        /// Registers a new handler for edited photos.
        edited_photo: EditedPhoto,
        /// Registers a new handler for edited text messages.
        edited_text: EditedText,
        /// Registers a new handler for edited videos.
        edited_video: EditedVideo,
        /// Registers a new handler for when a voice chat is ended.
        ended_voice_chat: EndedVoiceChat,
        /// Registers a new handler for game callbacks from chat messages.
        message_game_callback: MessageGameCallback,
        /// Registers a new handler for game callbacks from inline messages.
        inline_game_callback: InlineGameCallback,
        /// Registers a new handler for game messages.
        game: Game,
        /// Registers a new handler for inline queries.
        inline: Inline,
        /// Registers a new handler for when users are invited to a voice chat.
        invited_voice_chat_participants: InvitedVoiceChatParticipants,
        /// Registers a new handler for invoices.
        invoice: Invoice,
        /// Registers a new handler for left members.
        left_member: LeftMember,
        /// Registers a new handler for locations.
        location: Location,
        /// Registers a new handler for migrations.
        migration: Migration,
        /// Registers a new handler for the bot's update chat member status.
        my_chat_member: MyChatMember,
        /// Registers a new handler for new chat photos.
        new_chat_photo: NewChatPhoto,
        /// Registers a new handler for new chat titles.
        new_chat_title: NewChatTitle,
        /// Registers a new handler for new members.
        new_members: NewMembers,
        /// Registers a new handler for passport data.
        passport: Passport,
        /// Registers a new handler for successful payments.
        payment: Payment,
        /// Registers a new handler for photos.
        photo: Photo,
        /// Registers a new handler for pinned messages.
        pinned_message: PinnedMessage,
        /// Registers a new handler for poll messages.
        poll: Poll,
        /// Registers a new handler for pre-checkout queries.
        pre_checkout: PreCheckout,
        /// Registers a new handler for proximity alerts.
        proximity_alert: ProximityAlert,
        /// Registers a new handler for when a voice chat is scheduled.
        scheduled_voice_chat: ScheduledVoiceChat,
        /// Registers a new handler for shipping queries.
        shipping: Shipping,
        /// Registers a new handler for when a voice chat is started.
        started_voice_chat: StartedVoiceChat,
        /// Registers a new handler for stickers.
        sticker: Sticker,
        /// Registers a new handler for text messages.
        text: Text,
        /// Registers a new handler for unhandled updates.
        ///
        /// Note that regisering [`any_update`] handlers does not affect
        /// `unhandled` handlers in any way. An `unhandled` handler is spawned
        /// if a _specialized_ handler corresponding to the incoming update was
        /// not registered.
        ///
        /// [`any_update`]: Self::any_update
        unhandled: Unhandled,
        /// Registers a new handler for new states of polls.
        updated_poll: UpdatedPoll,
        /// Registers a new handler for new answers in the poll.
        poll_answer: PollAnswer,
        /// Registers a new handler for venues.
        venue: Venue,
        /// Registers a new handler for videos.
        video: Video,
        /// Registers a new handler for video notes.
        video_note: VideoNote,
        /// Registers a new handler for voice messages.
        voice: Voice,
    }

    fn handle_unhandled(&self, update: update::Kind) {
        let context = Arc::new(Unhandled::new(self.bot.clone(), update));
        self.handle(context);
    }

    #[instrument(skip(self, update))]
    fn handle_update(&self, update: types::Update) {
        trace!(?update);

        if self.will_handle::<AnyUpdate>() {
            let context = AnyUpdate::new(self.bot.clone(), update.clone());
            self.handle(Arc::new(context));
        }

        match update.kind {
            update::Kind::CallbackQuery(query) => match query {
                Query {
                    kind: callback::Kind::Data(data),
                    origin: callback::Origin::Message(message),
                    id,
                    from,
                    chat_instance,
                } if self.will_handle::<MessageDataCallback>() => {
                    let context = MessageDataCallback::new(
                        self.bot.clone(),
                        id,
                        from,
                        *message,
                        chat_instance,
                        data,
                    );
                    self.handle(Arc::new(context));
                }
                Query {
                    kind: callback::Kind::Data(data),
                    origin: callback::Origin::Inline(message_id),
                    id,
                    from,
                    chat_instance,
                } if self.will_handle::<InlineDataCallback>() => {
                    let context = InlineDataCallback::new(
                        self.bot.clone(),
                        id,
                        from,
                        message_id,
                        chat_instance,
                        data,
                    );
                    self.handle(Arc::new(context));
                }
                Query {
                    kind: callback::Kind::Game(game),
                    origin: callback::Origin::Message(message),
                    id,
                    from,
                    chat_instance,
                } if self.will_handle::<MessageGameCallback>() => {
                    let context = MessageGameCallback::new(
                        self.bot.clone(),
                        id,
                        from,
                        *message,
                        chat_instance,
                        game,
                    );
                    self.handle(Arc::new(context));
                }
                Query {
                    kind: callback::Kind::Game(game),
                    origin: callback::Origin::Inline(message_id),
                    id,
                    from,
                    chat_instance,
                } if self.will_handle::<InlineGameCallback>() => {
                    let context = InlineGameCallback::new(
                        self.bot.clone(),
                        id,
                        from,
                        message_id,
                        chat_instance,
                        game,
                    );
                    self.handle(Arc::new(context));
                }
                query if self.will_handle::<Unhandled>() => {
                    let update = update::Kind::CallbackQuery(query);
                    self.handle_unhandled(update);
                }
                Query {
                    kind: callback::Kind::Data(..) | callback::Kind::Game(..),
                    origin:
                        callback::Origin::Message(..) | callback::Origin::Inline(..),
                    ..
                } => (),
            },
            update::Kind::ChosenInlineResult(result)
                if self.will_handle::<ChosenInline>() =>
            {
                let context = ChosenInline::new(self.bot.clone(), result);
                self.handle(Arc::new(context));
            }
            update::Kind::EditedMessage(message)
            | update::Kind::EditedChannelPost(message) => {
                self.handle_message_edit_update(message);
            }
            update::Kind::InlineQuery(query)
                if self.will_handle::<Inline>() =>
            {
                let context = Inline::new(self.bot.clone(), query);
                self.handle(Arc::new(context));
            }
            update::Kind::Message(message)
            | update::Kind::ChannelPost(message) => {
                self.handle_message_update(message);
            }
            update::Kind::PreCheckoutQuery(query)
                if self.will_handle::<PreCheckout>() =>
            {
                let context = PreCheckout::new(self.bot.clone(), query);
                self.handle(Arc::new(context));
            }
            update::Kind::Poll(poll) if self.will_handle::<UpdatedPoll>() => {
                let context = UpdatedPoll::new(self.bot.clone(), poll);
                self.handle(Arc::new(context));
            }
            update::Kind::PollAnswer(answer)
                if self.will_handle::<PollAnswer>() =>
            {
                let context = PollAnswer::new(self.bot.clone(), answer);
                self.handle(Arc::new(context));
            }
            update::Kind::ShippingQuery(query)
                if self.will_handle::<Shipping>() =>
            {
                let context = Shipping::new(self.bot.clone(), query);
                self.handle(Arc::new(context));
            }
            update::Kind::ChatMember(update)
                if self.will_handle::<ChatMember>() =>
            {
                let context = ChatMember::new(self.bot.clone(), update);
                self.handle(Arc::new(context));
            }
            update::Kind::MyChatMember(update)
                if self.will_handle::<MyChatMember>() =>
            {
                let context = MyChatMember::new(self.bot.clone(), update);
                self.handle(Arc::new(context));
            }
            update if self.will_handle::<Unhandled>() => {
                self.handle_unhandled(update);
            }
            update::Kind::ChosenInlineResult(..)
            | update::Kind::InlineQuery(..)
            | update::Kind::Poll(..)
            | update::Kind::PollAnswer(..)
            | update::Kind::PreCheckoutQuery(..)
            | update::Kind::ShippingQuery(..)
            | update::Kind::ChatMember(..)
            | update::Kind::MyChatMember(..)
            | update::Kind::Unknown => (),
        }
    }

    #[allow(clippy::cognitive_complexity)]
    #[allow(clippy::too_many_lines)] // can't split the huge match
    fn handle_message_update(&self, message: types::Message) {
        let (data, kind) = message.split();

        match kind {
            message::Kind::Animation { animation, caption }
                if self.will_handle::<Animation>() =>
            {
                let context =
                    Animation::new(self.bot.clone(), data, *animation, caption);
                self.handle(Arc::new(context));
            }
            message::Kind::Audio {
                audio,
                caption,
                media_group_id,
            } if self.will_handle::<Audio>() => {
                let context = Audio::new(
                    self.bot.clone(),
                    data,
                    *audio,
                    caption,
                    media_group_id,
                );
                self.handle(Arc::new(context));
            }
            message::Kind::AutoDeleteTimerChanged(change)
                if self.will_handle::<ChangedAutoDeleteTimer>() =>
            {
                let context =
                    ChangedAutoDeleteTimer::new(self.bot.clone(), data, change);
                self.handle(Arc::new(context));
            }
            message::Kind::ChatPhotoDeleted
                if self.will_handle::<DeletedChatPhoto>() =>
            {
                let context = DeletedChatPhoto::new(self.bot.clone(), data);
                self.handle(Arc::new(context));
            }
            message::Kind::ConnectedWebsite(website)
                if self.will_handle::<ConnectedWebsite>() =>
            {
                let context =
                    ConnectedWebsite::new(self.bot.clone(), data, website);
                self.handle(Arc::new(context));
            }
            message::Kind::Contact(contact)
                if self.will_handle::<Contact>() =>
            {
                let context = Contact::new(self.bot.clone(), data, contact);
                self.handle(Arc::new(context));
            }
            message::Kind::Dice(dice) if self.will_handle::<Dice>() => {
                let context = Dice::new(self.bot.clone(), data, dice);
                self.handle(Arc::new(context));
            }
            message::Kind::Document {
                document,
                caption,
                media_group_id,
            } if self.will_handle::<Document>() => {
                let context = Document::new(
                    self.bot.clone(),
                    data,
                    *document,
                    caption,
                    media_group_id,
                );
                self.handle(Arc::new(context));
            }
            message::Kind::Game(game) if self.will_handle::<Game>() => {
                let context = Game::new(self.bot.clone(), data, *game);
                self.handle(Arc::new(context));
            }
            message::Kind::GroupCreated
                if self.will_handle::<CreatedGroup>() =>
            {
                let context = CreatedGroup::new(self.bot.clone(), data);
                self.handle(Arc::new(context));
            }
            message::Kind::Invoice(invoice)
                if self.will_handle::<Invoice>() =>
            {
                let context = Invoice::new(self.bot.clone(), data, invoice);
                self.handle(Arc::new(context));
            }
            message::Kind::LeftChatMember(member)
                if self.will_handle::<LeftMember>() =>
            {
                let context = LeftMember::new(self.bot.clone(), data, member);
                self.handle(Arc::new(context));
            }
            message::Kind::Location(location)
                if self.will_handle::<Location>() =>
            {
                let context = Location::new(self.bot.clone(), data, location);
                self.handle(Arc::new(context));
            }
            message::Kind::MigrateFrom(old_id)
                if self.will_handle::<Migration>() =>
            {
                let context = Migration::new(self.bot.clone(), data, old_id);
                self.handle(Arc::new(context));
            }
            message::Kind::MigrateTo(..) => (), // ignored on purpose
            message::Kind::NewChatMembers(members)
                if self.will_handle::<NewMembers>() =>
            {
                let context = NewMembers::new(self.bot.clone(), data, members);
                self.handle(Arc::new(context));
            }
            message::Kind::NewChatPhoto(photo)
                if self.will_handle::<NewChatPhoto>() =>
            {
                let context = NewChatPhoto::new(self.bot.clone(), data, photo);
                self.handle(Arc::new(context));
            }
            message::Kind::NewChatTitle(title)
                if self.will_handle::<NewChatTitle>() =>
            {
                let context = NewChatTitle::new(self.bot.clone(), data, title);
                self.handle(Arc::new(context));
            }
            message::Kind::PassportData(passport_data)
                if self.will_handle::<Passport>() =>
            {
                let context =
                    Passport::new(self.bot.clone(), data, passport_data);
                self.handle(Arc::new(context));
            }
            message::Kind::Photo {
                photo,
                caption,
                media_group_id,
            } if self.will_handle::<Photo>() => {
                let context = Photo::new(
                    self.bot.clone(),
                    data,
                    photo,
                    caption,
                    media_group_id,
                );
                self.handle(Arc::new(context));
            }
            message::Kind::Pinned(message)
                if self.will_handle::<PinnedMessage>() =>
            {
                let context =
                    PinnedMessage::new(self.bot.clone(), data, *message);
                self.handle(Arc::new(context));
            }
            message::Kind::Poll(poll) if self.will_handle::<Poll>() => {
                let context = Poll::new(self.bot.clone(), data, poll);
                self.handle(Arc::new(context));
            }
            message::Kind::ProximityAlert(alert)
                if self.will_handle::<ProximityAlert>() =>
            {
                let context =
                    ProximityAlert::new(self.bot.clone(), data, alert);
                self.handle(Arc::new(context));
            }
            message::Kind::Sticker(sticker)
                if self.will_handle::<Sticker>() =>
            {
                let context = Sticker::new(self.bot.clone(), data, *sticker);
                self.handle(Arc::new(context));
            }
            message::Kind::SuccessfulPayment(payment)
                if self.will_handle::<Payment>() =>
            {
                let context = Payment::new(self.bot.clone(), data, *payment);
                self.handle(Arc::new(context));
            }
            message::Kind::Text(text) if is_command(&text) => {
                let (command, username) = parse_command(&text);

                if !self.is_for_this_bot(username) {
                    return;
                }

                if self.will_handle_command(&command) {
                    let text = trim_command(text);
                    let context = Command::new(
                        self.bot.clone(),
                        data,
                        text,
                        command.clone(),
                    );
                    self.handle_command(&command, &Arc::new(context));
                } else if self.will_handle::<Unhandled>() {
                    let kind = message::Kind::Text(text);
                    let message = Message::new(data, kind);
                    let update = update::Kind::Message(message);
                    self.handle_unhandled(update);
                }
            }
            message::Kind::Text(text) if self.will_handle::<Text>() => {
                let context = Text::new(self.bot.clone(), data, text);
                self.handle(Arc::new(context));
            }
            message::Kind::Venue(venue) if self.will_handle::<Venue>() => {
                let context = Venue::new(self.bot.clone(), data, venue);
                self.handle(Arc::new(context));
            }
            message::Kind::Video {
                video,
                caption,
                media_group_id,
            } if self.will_handle::<Video>() => {
                let context = Video::new(
                    self.bot.clone(),
                    data,
                    *video,
                    caption,
                    media_group_id,
                );
                self.handle(Arc::new(context));
            }
            message::Kind::VideoNote(video_note)
                if self.will_handle::<VideoNote>() =>
            {
                let context =
                    VideoNote::new(self.bot.clone(), data, video_note);
                self.handle(Arc::new(context));
            }
            message::Kind::Voice { voice, caption }
                if self.will_handle::<Voice>() =>
            {
                let context =
                    Voice::new(self.bot.clone(), data, voice, caption);
                self.handle(Arc::new(context));
            }
            message::Kind::VoiceChatEnded(ended)
                if self.will_handle::<EndedVoiceChat>() =>
            {
                let context =
                    EndedVoiceChat::new(self.bot.clone(), data, ended);
                self.handle(Arc::new(context));
            }
            message::Kind::VoiceChatParticipantsInvited(invited)
                if self.will_handle::<InvitedVoiceChatParticipants>() =>
            {
                let context = InvitedVoiceChatParticipants::new(
                    self.bot.clone(),
                    data,
                    invited,
                );
                self.handle(Arc::new(context));
            }
            message::Kind::VoiceChatScheduled(scheduled)
                if self.will_handle::<ScheduledVoiceChat>() =>
            {
                let context =
                    ScheduledVoiceChat::new(self.bot.clone(), data, scheduled);
                self.handle(Arc::new(context));
            }
            message::Kind::VoiceChatStarted
                if self.will_handle::<StartedVoiceChat>() =>
            {
                let context = StartedVoiceChat::new(self.bot.clone(), data);
                self.handle(Arc::new(context));
            }
            message::Kind::SupergroupCreated
            | message::Kind::ChannelCreated => {
                warn!("Update not expected; skipping it");
            }
            kind if self.will_handle::<Unhandled>() => {
                let message = Message::new(data, kind);
                let update = update::Kind::Message(message);
                self.handle_unhandled(update);
            }
            message::Kind::Animation { .. }
            | message::Kind::Audio { .. }
            | message::Kind::AutoDeleteTimerChanged(..)
            | message::Kind::ChatPhotoDeleted
            | message::Kind::ConnectedWebsite(..)
            | message::Kind::Contact(..)
            | message::Kind::Dice(..)
            | message::Kind::Document { .. }
            | message::Kind::Game(..)
            | message::Kind::GroupCreated
            | message::Kind::Invoice(..)
            | message::Kind::LeftChatMember(..)
            | message::Kind::Location(..)
            | message::Kind::MigrateFrom(..)
            | message::Kind::NewChatMembers(..)
            | message::Kind::NewChatPhoto(..)
            | message::Kind::NewChatTitle(..)
            | message::Kind::PassportData(..)
            | message::Kind::Photo { .. }
            | message::Kind::Pinned(..)
            | message::Kind::Poll(..)
            | message::Kind::ProximityAlert(..)
            | message::Kind::Sticker(..)
            | message::Kind::SuccessfulPayment(..)
            | message::Kind::Text(..)
            | message::Kind::Venue(..)
            | message::Kind::Video { .. }
            | message::Kind::VideoNote(..)
            | message::Kind::Voice { .. }
            | message::Kind::VoiceChatEnded(..)
            | message::Kind::VoiceChatParticipantsInvited(..)
            | message::Kind::VoiceChatScheduled(..)
            | message::Kind::VoiceChatStarted
            | message::Kind::Unknown => (),
        }
    }

    #[allow(clippy::too_many_lines, clippy::cognitive_complexity)] // can't split the huge match
    fn handle_message_edit_update(&self, message: types::Message) {
        let (data, kind) = message.split();
        let Some(edit_date) = data.edit_date else {
            error!("No `edit_date` on an edited message; skipping it");
            return;
        };

        match kind {
            message::Kind::Animation { animation, caption }
                if self.will_handle::<EditedAnimation>() =>
            {
                let context = EditedAnimation::new(
                    self.bot.clone(),
                    data,
                    edit_date,
                    *animation,
                    caption,
                );
                self.handle(Arc::new(context));
            }
            message::Kind::Audio {
                audio,
                caption,
                media_group_id,
            } if self.will_handle::<EditedAudio>() => {
                let context = EditedAudio::new(
                    self.bot.clone(),
                    data,
                    edit_date,
                    *audio,
                    caption,
                    media_group_id,
                );
                self.handle(Arc::new(context));
            }
            message::Kind::Document {
                document,
                caption,
                media_group_id,
            } if self.will_handle::<EditedDocument>() => {
                let context = EditedDocument::new(
                    self.bot.clone(),
                    data,
                    edit_date,
                    *document,
                    caption,
                    media_group_id,
                );
                self.handle(Arc::new(context));
            }
            message::Kind::Location(location)
                if self.will_handle::<EditedLocation>() =>
            {
                let context = EditedLocation::new(
                    self.bot.clone(),
                    data,
                    edit_date,
                    location,
                );
                self.handle(Arc::new(context));
            }
            message::Kind::Photo {
                photo,
                caption,
                media_group_id,
            } if self.will_handle::<EditedPhoto>() => {
                let context = EditedPhoto::new(
                    self.bot.clone(),
                    data,
                    edit_date,
                    photo,
                    caption,
                    media_group_id,
                );
                self.handle(Arc::new(context));
            }
            message::Kind::Text(text) if is_command(&text) => {
                let (command, username) = parse_command(&text);
                if !self.is_for_this_bot(username) {
                    return;
                }

                if self.will_handle_edited_command(&command) {
                    let text = trim_command(text);
                    let context = EditedCommand::new(
                        self.bot.clone(),
                        data,
                        edit_date,
                        text,
                        command.clone(),
                    );
                    self.handle_edited_command(&command, &Arc::new(context));
                } else if self.will_handle::<Unhandled>() {
                    let kind = message::Kind::Text(text);
                    let message = Message::new(data, kind);
                    let update = update::Kind::EditedMessage(message);
                    self.handle_unhandled(update);
                }
            }
            message::Kind::Text(text) if self.will_handle::<EditedText>() => {
                let context =
                    EditedText::new(self.bot.clone(), data, edit_date, text);
                self.handle(Arc::new(context));
            }
            message::Kind::Video {
                video,
                caption,
                media_group_id,
            } if self.will_handle::<EditedVideo>() => {
                let context = EditedVideo::new(
                    self.bot.clone(),
                    data,
                    edit_date,
                    *video,
                    caption,
                    media_group_id,
                );
                self.handle(Arc::new(context));
            }

            message::Kind::Contact(..)
            | message::Kind::Dice(..)
            | message::Kind::Game(..)
            | message::Kind::Invoice(..)
            | message::Kind::Poll(..)
            | message::Kind::Sticker(..)
            | message::Kind::Venue(..)
            | message::Kind::VideoNote(..)
            | message::Kind::Voice { .. }
            | message::Kind::VoiceChatEnded(..)
            | message::Kind::VoiceChatParticipantsInvited(..)
            | message::Kind::VoiceChatScheduled(..)
            | message::Kind::VoiceChatStarted
            | message::Kind::ChannelCreated
            | message::Kind::ChatPhotoDeleted
            | message::Kind::ConnectedWebsite(..)
            | message::Kind::GroupCreated
            | message::Kind::LeftChatMember(..)
            | message::Kind::MigrateFrom(..)
            | message::Kind::MigrateTo(..)
            | message::Kind::NewChatMembers(..)
            | message::Kind::NewChatPhoto(..)
            | message::Kind::NewChatTitle(..)
            | message::Kind::PassportData(..)
            | message::Kind::Pinned(..)
            | message::Kind::ProximityAlert(..)
            | message::Kind::SuccessfulPayment(..)
            | message::Kind::AutoDeleteTimerChanged(..)
            | message::Kind::SupergroupCreated => warn!(
                "Unexpected message kind received as an edited message; \
                skipping it"
            ),

            kind if self.will_handle::<Unhandled>() => {
                let message = Message::new(data, kind);
                let update = update::Kind::EditedMessage(message);
                self.handle_unhandled(update);
            }
            message::Kind::Animation { .. }
            | message::Kind::Audio { .. }
            | message::Kind::Document { .. }
            | message::Kind::Location(..)
            | message::Kind::Photo { .. }
            | message::Kind::Text(..)
            | message::Kind::Video { .. }
            | message::Kind::Unknown => (),
        }
    }

    fn is_for_this_bot(&self, username: Option<&str>) -> bool {
        username.map_or(true, |username| {
            self.username.as_ref().map(|x| x == username) == Some(true)
        })
    }

    pub(crate) async fn set_commands_descriptions(
        &self,
    ) -> Result<(), MethodCall> {
        if self.command_description.is_empty() {
            return Ok(());
        }

        let commands: Vec<_> = self
            .command_description
            .iter()
            .map(|(name, description)| BotCommand::new(name, description))
            .collect();

        self.bot.set_my_commands(commands).call().await?;

        Ok(())
    }
}

fn is_command(text: &message::Text) -> bool {
    text.entities.get(0).map(|entity| {
        entity.kind == EntityKind::BotCommand && entity.offset == 0
    }) == Some(true)
}

fn parse_command(text: &message::Text) -> (String, Option<&str>) {
    let mut iter =
        // As this function is only run when a message starts with `/`,
        // the first value will always be yielded.
        text.value.split_whitespace().next().unwrap()[1..].split('@');

    // `split` always yields the first value.
    let command = iter.next().unwrap();
    let username = iter.next();

    (command.to_string(), username)
}

fn trim_command(text: message::Text) -> message::Text {
    let mut entities = text.entities.into_iter();
    // As this function is only called when the message is a command, the first
    // entity will always exist.
    let command_entity = entities.next().unwrap();
    let old_length = text.value.chars().count();

    let value: String = text
        .value
        .chars()
        .skip(command_entity.length)
        .skip_while(|x| x.is_whitespace())
        .collect();
    let new_length = value.chars().count();

    let entities = entities
        .map(|entity| Entity {
            kind: entity.kind,
            length: entity.length,
            offset: entity.offset - (old_length - new_length),
        })
        .collect();

    message::Text { value, entities }
}

fn normalize_cmd_name(command: &str) -> &str {
    // Putting side effects into functional combinators doesn't look very good.
    #[allow(clippy::option_if_let_else)]
    if let Some(stripped) = command.strip_prefix('/') {
        tracing::warn!(
            ?command,
            "Commands should not start with `/`. `tbot` will strip it, but it is idiomatic to omit it in the source code.",
        );
        stripped
    } else {
        command
    }
}