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
//! This crate helps writing bots for Telegram. This is a framework to build the bots,
//! the main wrapped crate is `telegram-bot` which provides the actual protocol access.
//!
//! How to use it
//! -------------
//!
//! The first step is always to create the AwesomeBot instance,
//! this will represent your bot, so, if you have more than one bot,
//! you will have to create more instances.
//!
//! You have two ways to create the bot, with `new`,
//! that you pass the bot token directly, or with `from_env`, more recommended.
//!
//! This framework uses the "route" pattern to apply behavior.
//! There are plenty of routing ways available, the main ones are:
//! `command`, `simple_command`, `any_fn`.
//! But there are many more, check the docs of [AwesomeBot](struct.AwesomeBot.html)
//!
//! Then, to send things you need to use the SendBuilder struct, to create an instance use
//! the `send` or `answer` methods in `AwesomeBot`.
//!
//! This uses the "builder" pattern, for example, to answer a message with a text,
//! while disabling web pages, you do (Assuming that bot is `&AwesomeBot` and msg is `&Message`):
//!
//! ``` ignore
//! bot.answer(msg).text("Answering this text").disable_preview(true).end();
//! ```
//!
//! Check [`SendBuilder`](struct.SendBuilder.html) struct implementation to see the methods
//! available (text, photo, audio, ...)
//!
//! Once you have all your routings, you need to start the bot, right now it supports only
//! getUpdates method, just call the `simple_start` method in AwesomeBot.
//!
//! You don't have to worry about blocking the bot in a function handler,
//! because it uses a thread pool (of 4 threads right now,
//! it will be configurable in the future), so the handling for
//! a message is done in his own thread.
//!
//! # Examples
//!
//! ## Minimalistic example (Echo text)
//! ```no_run
//! extern crate awesome_bot;
//!
//! use awesome_bot::*;
//!
//! fn echohandler(bot: &AwesomeBot, msg: &Message, _: String, args: Vec<String>) {
//!     // We can access safely because the pattern match have that argument mandatory
//!     let toecho = &args[1];
//!     let phrase = format!("Echoed: {}", toecho);
//!     // Send the text in a beauty way :)
//!     let sended = bot.answer(msg).text(&phrase).end();
//!     println!("{:?}", sended);
//! }
//!
//! fn main() {
//!     // Create the Awesome Bot (You need TELEGRAM_BOT_TOKEN environment with the token)
//!     let mut bot = AwesomeBot::from_env("TELEGRAM_BOT_TOKEN");
//!     // Add a command, this will add the routing to that function.
//!     bot.command("echo (.+)", echohandler);
//!
//!     // Start the bot with getUpdates
//!     let res = bot.simple_start();
//!     if let Err(e) = res {
//!         println!("An error occurred: {}", e);
//!     }
//! }
//! ```
//!
//! ## More examples
//! You have more examples in `examples/` directory in the project's repository.
//!

extern crate regex;
extern crate rustc_serialize;
extern crate scoped_threadpool;
extern crate telegram_bot;

mod send;
mod test;

pub use send::*;

pub use telegram_bot::*;

use scoped_threadpool::Pool;

use regex::Regex;
use std::env;
use std::sync::Arc;

/// Represents audio and voice, this is used in `all_music_fn` handler.
pub enum GeneralSound {
    Audio(Audio),
    Voice(Voice),
}

// This enumeration determines what type of routing handler to use
#[derive(Clone)]
enum Muxer {
    PatternMux(
        Regex,
        Arc<Fn(&AwesomeBot, &Message, String, Vec<String>) + Send + Sync + 'static>,
    ),
    TextMux(
        Regex,
        Arc<Fn(&AwesomeBot, &Message, String) + Send + Sync + 'static>,
    ),
    PhotoMux(Arc<Fn(&AwesomeBot, &Message, Vec<PhotoSize>) + Send + Sync + 'static>),
    VideoMux(Arc<Fn(&AwesomeBot, &Message, Video) + Send + Sync + 'static>),
    DocumentMux(Arc<Fn(&AwesomeBot, &Message, Document) + Send + Sync + 'static>),
    StickerMux(Arc<Fn(&AwesomeBot, &Message, Sticker) + Send + Sync + 'static>),
    AudioMux(Arc<Fn(&AwesomeBot, &Message, Audio) + Send + Sync + 'static>),
    VoiceMux(Arc<Fn(&AwesomeBot, &Message, Voice) + Send + Sync + 'static>),
    GeneralAudioMux(Arc<Fn(&AwesomeBot, &Message, GeneralSound) + Send + Sync + 'static>),
    ContactMux(Arc<Fn(&AwesomeBot, &Message, Contact) + Send + Sync + 'static>),
    LocationMux(Arc<Fn(&AwesomeBot, &Message, Float, Float) + Send + Sync + 'static>),
    NewParticipantMux(Arc<Fn(&AwesomeBot, &Message, User) + Send + Sync + 'static>),
    LeftParticipantMux(Arc<Fn(&AwesomeBot, &Message, User) + Send + Sync + 'static>),
    NewTitleMux(Arc<Fn(&AwesomeBot, &Message, String) + Send + Sync + 'static>),
    NewChatPhotoMux(Arc<Fn(&AwesomeBot, &Message, Vec<PhotoSize>) + Send + Sync + 'static>),
    DeleteChatPhotoMux(Arc<Fn(&AwesomeBot, &Message, Chat) + Send + Sync + 'static>),
    GroupChatCreatedMux(Arc<Fn(&AwesomeBot, &Message, Chat) + Send + Sync + 'static>),
    SuperGroupChatCreatedMux(
        Arc<Fn(&AwesomeBot, &Message, GroupToSuperGroupMigration) + Send + Sync + 'static>,
    ),
    ChannelChatCreatedMux(Arc<Fn(&AwesomeBot, &Message, Chat) + Send + Sync + 'static>),
    AnyMux(Arc<Fn(&AwesomeBot, &Message) + Send + Sync + 'static>),
}

// This macro matches one muxer and executes a block while sending "Any" message :)
// First: self
// Second: msg to pass
// Third: List of Patterns to match => Code block to execute for that Pattern
macro_rules! muxer_match {
    ($_self: expr, $msg: expr, [$($pat:pat => $result: expr),*]) => {
        for m in &$_self.muxers {
            match m {
                &Muxer::AnyMux(ref f) => {
                    f($_self, &$msg);
                },
                $($pat => $result,)*
                _ => {},
            }
        }
    }
}

// This macro adds a muxer to the muxers vec
// First: self
// Second: handler (function to add)
// Third: The Muxer enum type
// Fourth: List of extra parameters, in order, first passed to the muxer
macro_rules! add_muxer {
    ($_self: expr,
     $handler: expr,
     $mux: expr,
     [$($extra: expr),*]) => {
        {
            let fa = Arc::new($handler);
            $_self.muxers.push($mux($($extra,)* fa.clone()));
            $_self
        }
    }
}

/// Main type for building the Telegram Bot.
///
/// Create a new instance using `new` or `from_env`, add routing handlers and start the bot.
pub struct AwesomeBot {
    bot: Api,
    /// The ID of the bot.
    pub id: Integer,
    /// The username of the bot.
    pub username: String,
    muxers: Vec<Muxer>,
}

impl Clone for AwesomeBot {
    fn clone(&self) -> AwesomeBot {
        let b = self.bot.clone();
        let mut v: Vec<Muxer> = Vec::new();
        for m in &self.muxers {
            v.push(m.clone());
        }
        AwesomeBot {
            bot: b,
            id: self.id,
            username: self.username.clone(),
            muxers: v,
        }
    }
}

// unsafe impl Send for AwesomeBot { }
// unsafe impl Sync for AwesomeBot { }

impl AwesomeBot {
    // ===========================================================
    // Constructors
    // ===========================================================
    /// Creates a new bot with the given token. This checks that the token is a
    /// valid Telegram Bot Token by calling `get_me`.
    /// It panics if the token is invalid.
    pub fn new(token: &str) -> AwesomeBot {
        let bot = Api::from_token(token).unwrap();
        match bot.get_me() {
            Ok(user) => AwesomeBot {
                bot: bot,
                id: user.id,
                username: user.username.unwrap_or("".to_string()),
                muxers: Vec::new(),
            },
            Err(e) => panic!("Invalid token! ({})", e),
        }
    }

    /// Will receive the Bot Token from the environment variable `var` and call `new`.
    /// It panics if the environment variable can't be read or if the token is invalid.
    pub fn from_env(var: &str) -> AwesomeBot {
        let token = env::var(var)
            .ok()
            .expect(&format!("Environment variable {} error.", var));

        Self::new(&token)
    }

    // Listener functions

    /// Start the bot using `getUpdates` method, calling the routes defined before calling this method.
    pub fn simple_start(&self) -> Result<()> {
        let mut listener = self.bot.listener(ListeningMethod::LongPoll(Some(20)));
        let mut pool = Pool::new(4);
        // let botcloned = Arc::new(self.clone());

        pool.scoped(|scoped| {
            // Handle updates
            let result = listener.listen(|u| {
                if let Some(m) = u.message {
                    // let bot_instance = botcloned.clone();
                    scoped.execute(move || {
                        // bot_instance.handle_message(m);
                        self.handle_message(m);
                    });
                }
                Ok(ListeningAction::Continue)
            });
            scoped.join_all(); // Wait all scoped threads to finish
            result
        })
    }

    // Send builders
    /// Start a SendBuilder directly with the id, this is useful when you have the id saved and want to send a message.
    pub fn send(&self, id: Integer) -> SendBuilder {
        SendBuilder::new(id, self.bot.clone())
    }

    /// Start a SendBuilder answering a message directly, this is used to answer in a handler to the sender of the message.
    pub fn answer(&self, m: &Message) -> SendBuilder {
        self.send(m.chat.id())
    }

    // AUXILIARY FUNCTIONS

    // This function modifies the command by adding the username and some regex cleanup
    fn modify_command(orig: &str, username: &str) -> String {
        let s = String::from(orig);
        let mut words: Vec<String> = s.split_whitespace().map(|x| String::from(x)).collect();

        if words.len() >= 1 {
            let mut lastchar = "";
            let mut comm = words.remove(0);
            if comm.ends_with("$") {
                lastchar = "$";
                comm.pop();
            }
            let ns: String = format!("{}(?:@{})?{}", comm, username, lastchar);
            words.insert(0, ns);
        }

        let mut ns: String = words.join(" ");
        if !ns.starts_with("^/") {
            if !ns.starts_with("/") {
                ns.insert(0, '/');
            }
            if !s.starts_with("^") {
                ns.insert(0, '^');
            }
        }
        if !ns.ends_with("$") {
            ns.push_str("$");
        }
        ns
    }
}

// Internal handler functions
impl AwesomeBot {
    fn handle_text_msg(&self, msg: &Message, text: String) {
        use Muxer::*;
        muxer_match!(self, msg,
                     [&TextMux(ref r, ref f) =>
                      {
                         if r.is_match(&text) {
                             f(self, msg, text.clone());
                         }
                      },
                      &PatternMux(ref r, ref f) =>
                      {
                          if r.is_match(&text) { // If there are matches
                              r.captures(&text) // Get the captures
                                  .map(|c| { // Map over them because they are Option<_>
                                      // Change the capture groups to Vec<String>
                                      c.iter().map(|x| String::from(x.unwrap_or("")))
                                          .collect::<Vec<_>>()
                                  })
                                  .map(|captures_vec|{
                                      // If everything goes well, call the function
                                      f(self, msg, text.clone(), captures_vec)
                                  });
                          }
                      }]
                     );
    }

    fn handle_image_msg(&self, msg: &Message, photos: Vec<PhotoSize>) {
        use Muxer::*;
        muxer_match!(self, msg,
                          [&PhotoMux(ref f) => f(self, msg, photos.clone())]
                          );
    }

    fn handle_video_msg(&self, msg: &Message, video: Video) {
        use Muxer::*;
        muxer_match!(self, msg,
                     [&VideoMux(ref f) => f(self, msg, video.clone())]
                     );
    }

    fn handle_document_msg(&self, msg: &Message, document: Document) {
        use Muxer::*;
        muxer_match!(self, msg,
                     [&DocumentMux(ref f) => f(self, msg, document.clone())]
                     );
    }

    fn handle_sticker_msg(&self, msg: &Message, sticker: Sticker) {
        use Muxer::*;
        muxer_match!(self, msg,
                     [&StickerMux(ref f) => f(self, msg, sticker.clone())]
                     );
    }

    fn handle_audio_msg(&self, msg: &Message, audio: Audio) {
        use Muxer::*;
        muxer_match!(self, msg,
                     [&AudioMux(ref f) => f(self, msg, audio.clone()),
                      &GeneralAudioMux(ref f) => f(self, msg, GeneralSound::Audio(audio.clone()))]
                          );
    }

    fn handle_voice_msg(&self, msg: &Message, voice: Voice) {
        use Muxer::*;
        muxer_match!(self, msg,
                          [&VoiceMux(ref f) => f(self, msg, voice.clone()),
                           &GeneralAudioMux(ref f) => f(self, msg, GeneralSound::Voice(voice.clone()))]
                          );
    }

    fn handle_contact_msg(&self, msg: &Message, cont: Contact) {
        use Muxer::*;
        muxer_match!(self, msg,
                          [&ContactMux(ref f) => f(self, msg, cont.clone())]
                          );
    }

    fn handle_location_msg(&self, msg: &Message, f1: Float, f2: Float) {
        use Muxer::*;
        muxer_match!(self, msg,
                          [&LocationMux(ref f) => f(self, msg, f1, f2)]
                          );
    }

    fn handle_new_chat_msg(&self, msg: &Message, newp: User) {
        use Muxer::*;
        muxer_match!(self, msg,
                          [&NewParticipantMux(ref f) => f(self, msg, newp.clone())]
                          );
    }

    fn handle_left_part_msg(&self, msg: &Message, user: User) {
        use Muxer::*;
        muxer_match!(self, msg,
                          [&LeftParticipantMux(ref f) => f(self, msg, user.clone())]
                          );
    }

    fn handle_new_title_msg(&self, msg: &Message, title: String) {
        use Muxer::*;
        muxer_match!(self, msg,
                          [&NewTitleMux(ref f) => f(self, msg, title.clone())]
                          );
    }

    fn handle_chat_photo_msg(&self, msg: &Message, photos: Vec<PhotoSize>) {
        use Muxer::*;
        muxer_match!(self, msg,
                          [&NewChatPhotoMux(ref f) => f(self, msg, photos.clone())]
                          );
    }

    fn handle_delete_photo_msg(&self, msg: &Message, group: Chat) {
        use Muxer::*;
        muxer_match!(self, msg,
                          [&DeleteChatPhotoMux(ref f) => f(self, msg, group.clone())]
                          );
    }

    fn handle_group_created_msg(&self, msg: &Message, group: Chat) {
        use Muxer::*;
        muxer_match!(self, msg,
                          [&GroupChatCreatedMux(ref f) => f(self, msg, group.clone())]
                          );
    }

    fn handle_super_group_chat_created_msg(
        &self,
        msg: &Message,
        migration: GroupToSuperGroupMigration,
    ) {
        use Muxer::*;
        muxer_match!(self, msg, [&SuperGroupChatCreatedMux (ref f) => f(self, msg, migration.clone())]);
    }

    fn handle_channel_chat_created_msg(&self, msg: &Message, chat: Chat) {
        use Muxer::*;
        muxer_match!(self, msg, [&ChannelChatCreatedMux (ref f) => f(self, msg, chat.clone())]);
    }

    fn handle_message(&self, message: Message) {
        // use MessageType::*; // When nightly becomes stable?
        use telegram_bot::MessageType::*;
        // // Any message
        // let anybot = bot.clone();
        // let anym = m.clone();
        // thread::spawn(move || {
        //     anybot.handle_any_msg(anym);
        // });

        // Rest of messages :)
        match message.msg.clone() {
            Text(text) => self.handle_text_msg(&message, text),
            Audio(audio) => self.handle_audio_msg(&message, audio),
            Voice(voice) => self.handle_voice_msg(&message, voice),
            Photo(photos) => self.handle_image_msg(&message, photos),
            File(document) => self.handle_document_msg(&message, document),
            Sticker(sticker) => self.handle_sticker_msg(&message, sticker),
            Video(video) => self.handle_video_msg(&message, video),
            Contact(contact) => self.handle_contact_msg(&message, contact),
            Location(loc) => self.handle_location_msg(&message, loc.latitude, loc.longitude),
            NewChatParticipant(user) => self.handle_new_chat_msg(&message, user),
            LeftChatParticipant(user) => self.handle_left_part_msg(&message, user),
            NewChatTitle(title) => self.handle_new_title_msg(&message, title),
            NewChatPhoto(photos) => self.handle_chat_photo_msg(&message, photos),
            DeleteChatPhoto => self.handle_delete_photo_msg(&message, message.chat.clone()),
            GroupChatCreated => self.handle_group_created_msg(&message, message.chat.clone()),
            SuperGroupChatCreated(migration) => {
                self.handle_super_group_chat_created_msg(&message, migration)
            }
            ChannelChatCreated => {
                self.handle_channel_chat_created_msg(&message, message.chat.clone())
            }
        }
    }
}

// Add functions implementation
/// Methods to add function handlers to different routes.
///
/// The different parameters of the handlers are:
///
/// - Common:
///    - `&AwesomeBot`: First argument of all the handlers is the bot itself, so you can send/answer.
///    - `&Message`: Second argument of all the handlers is the message that has triggered
///                  the handler, you can grab all the information you want. This struct comes
///                  from `telegram-bot` crate.
/// - Specific to some handlers:
///    - `String`: Refers to the full text if it's a command or regular expression,
///                or the new title of a group.
///    - `Vec<String>`: These are only in `command` and `regex` methods, and represent a vector
///                     of the capture groups.
///    - `Vec<PhotoSize>`: Represents an image (it's received in different sizes) and you get it
///                        when a photo arrives or when someone change a group photo.
///    - `Video`, `Document`, `Sticker`, `Audio`, `Voice`, `GeneralSound`, `Contact`, `Float`:
///                  All these parameters are the media that made the handler trigger, for example,
///                  in `video_fn` you will receive a `Video`.
///    - `User`: An User is received when a participants leave or enter a group.
///    - `Chat::Group`: Whenever someone delete a chat photo, or create a group (add the bot to
///                     the group) you receive this.
impl AwesomeBot {
    /// Add complex command routing (With capture groups).
    ///
    /// This method will transform the pattern to be exhaustive and include the mention to the bot,
    /// for example, the pattern `echo (.+)` will be used inside an the regular expression
    /// `^/start(?:@usernamebot)? (.+)$`
    pub fn command<H>(&mut self, pattern: &str, handler: H) -> &mut AwesomeBot
    where
        H: Fn(&AwesomeBot, &Message, String, Vec<String>) + Send + Sync + 'static,
    {
        let nr = Self::modify_command(pattern, &self.username);
        match Regex::new(&*nr) {
            Ok(r) => add_muxer!(self, handler, Muxer::PatternMux, [r]),
            Err(_) => self,
        }
    }

    /// Add simple command routing (Without capture groups).
    ///
    /// This method will transform the pattern the same as `command` method, but the handler
    /// will not receive the capture groups.
    pub fn simple_command<H>(&mut self, pattern: &str, handler: H) -> &mut AwesomeBot
    where
        H: Fn(&AwesomeBot, &Message, String) + Send + Sync + 'static,
    {
        let nr = Self::modify_command(pattern, &self.username);
        match Regex::new(&*nr) {
            Ok(r) => add_muxer!(self, handler, Muxer::TextMux, [r]),
            Err(_) => self,
        }
    }

    /// Add complex regular expression routing (With capture groups)
    ///
    /// This method won't tranform anything about the regular expression, you are free to write
    /// the expression you want and receive the capture groups matched.
    pub fn regex<H>(&mut self, pattern: &str, handler: H) -> &mut AwesomeBot
    where
        H: Fn(&AwesomeBot, &Message, String, Vec<String>) + Send + Sync + 'static,
    {
        match Regex::new(pattern) {
            Ok(r) => add_muxer!(self, handler, Muxer::PatternMux, [r]),
            Err(_) => self,
        }
    }

    /// Add complex regular expression routing (Without capture groups)
    ///
    /// This method won't tranform anything about the regular expression, you are free to write
    /// the expression. The difference from `regex` is that you won't receive any capture groups.
    pub fn simple_regex<H>(&mut self, pattern: &str, handler: H) -> &mut AwesomeBot
    where
        H: Fn(&AwesomeBot, &Message, String) + Send + Sync + 'static,
    {
        match Regex::new(pattern) {
            Ok(r) => add_muxer!(self, handler, Muxer::TextMux, [r]),
            Err(_) => self,
        }
    }

    // pub fn multi_regex<H>(&mut self, patterns: Vec<&str>, handler: H) -> &mut AwesomeBot
    //     where H: Fn(&AwesomeBot, &Message, String, Vec<String>) + Send + Sync + 'static
    // {
    // }

    /// Add a routing handler that will be triggerer on every message, useful for logging.
    pub fn any_fn<H>(&mut self, handler: H) -> &mut AwesomeBot
    where
        H: Fn(&AwesomeBot, &Message) + Send + Sync + 'static,
    {
        add_muxer!(self, handler, Muxer::AnyMux, [])
    }

    /// Add a photo media routing handler.
    pub fn photo_fn<H>(&mut self, handler: H) -> &mut AwesomeBot
    where
        H: Fn(&AwesomeBot, &Message, Vec<PhotoSize>) + Send + Sync + 'static,
    {
        add_muxer!(self, handler, Muxer::PhotoMux, [])
    }

    /// Add a video media routing handler.
    pub fn video_fn<H>(&mut self, handler: H) -> &mut AwesomeBot
    where
        H: Fn(&AwesomeBot, &Message, Video) + Send + Sync + 'static,
    {
        add_muxer!(self, handler, Muxer::VideoMux, [])
    }

    /// Add a document media routing handler.
    pub fn document_fn<H>(&mut self, handler: H) -> &mut AwesomeBot
    where
        H: Fn(&AwesomeBot, &Message, Document) + Send + Sync + 'static,
    {
        add_muxer!(self, handler, Muxer::DocumentMux, [])
    }

    /// Add a sticker media routing handler.
    pub fn sticker_fn<H>(&mut self, handler: H) -> &mut AwesomeBot
    where
        H: Fn(&AwesomeBot, &Message, Sticker) + Send + Sync + 'static,
    {
        add_muxer!(self, handler, Muxer::StickerMux, [])
    }

    /// Add an audio media routing handler.
    pub fn audio_fn<H>(&mut self, handler: H) -> &mut AwesomeBot
    where
        H: Fn(&AwesomeBot, &Message, Audio) + Send + Sync + 'static,
    {
        add_muxer!(self, handler, Muxer::AudioMux, [])
    }

    /// Add a voice media routing handler.
    pub fn voice_fn<H>(&mut self, handler: H) -> &mut AwesomeBot
    where
        H: Fn(&AwesomeBot, &Message, Voice) + Send + Sync + 'static,
    {
        add_muxer!(self, handler, Muxer::VoiceMux, [])
    }

    /// Add a routing handler that is triggered when an `Audio` or a `Voice` is received.
    pub fn all_music_fn<H>(&mut self, handler: H) -> &mut AwesomeBot
    where
        H: Fn(&AwesomeBot, &Message, GeneralSound) + Send + Sync + 'static,
    {
        add_muxer!(self, handler, Muxer::GeneralAudioMux, [])
    }

    /// Add a contact routing handler.
    pub fn contact_fn<H>(&mut self, handler: H) -> &mut AwesomeBot
    where
        H: Fn(&AwesomeBot, &Message, Contact) + Send + Sync + 'static,
    {
        add_muxer!(self, handler, Muxer::ContactMux, [])
    }

    /// Add a location routing handler.
    pub fn location_fn<H>(&mut self, handler: H) -> &mut AwesomeBot
    where
        H: Fn(&AwesomeBot, &Message, Float, Float) + Send + Sync + 'static,
    {
        add_muxer!(self, handler, Muxer::LocationMux, [])
    }

    /// Add a routing handler that is triggered when a new participant enters a group.
    pub fn new_participant_fn<H>(&mut self, handler: H) -> &mut AwesomeBot
    where
        H: Fn(&AwesomeBot, &Message, User) + Send + Sync + 'static,
    {
        add_muxer!(self, handler, Muxer::NewParticipantMux, [])
    }

    /// Add a routing handler that is triggered when a participant leaves a group.
    pub fn left_participant_fn<H>(&mut self, handler: H) -> &mut AwesomeBot
    where
        H: Fn(&AwesomeBot, &Message, User) + Send + Sync + 'static,
    {
        add_muxer!(self, handler, Muxer::LeftParticipantMux, [])
    }

    /// Add a routing handler that is triggered when the title of a group chat is changed.
    pub fn new_title_fn<H>(&mut self, handler: H) -> &mut AwesomeBot
    where
        H: Fn(&AwesomeBot, &Message, String) + Send + Sync + 'static,
    {
        add_muxer!(self, handler, Muxer::NewTitleMux, [])
    }

    /// Add a routing handler that is triggered when the photo of a group chat is changed.
    pub fn new_chat_photo_fn<H>(&mut self, handler: H) -> &mut AwesomeBot
    where
        H: Fn(&AwesomeBot, &Message, Vec<PhotoSize>) + Send + Sync + 'static,
    {
        add_muxer!(self, handler, Muxer::NewChatPhotoMux, [])
    }

    /// Add a routing handler that is triggered when the photo of a group chat is deleted.
    pub fn delete_chat_photo_fn<H>(&mut self, handler: H) -> &mut AwesomeBot
    where
        H: Fn(&AwesomeBot, &Message, Chat) + Send + Sync + 'static,
    {
        add_muxer!(self, handler, Muxer::DeleteChatPhotoMux, [])
    }

    /// Add a routing handler that is triggered when a group chat is created.
    pub fn group_chat_created_fn<H>(&mut self, handler: H) -> &mut AwesomeBot
    where
        H: Fn(&AwesomeBot, &Message, Chat) + Send + Sync + 'static,
    {
        add_muxer!(self, handler, Muxer::GroupChatCreatedMux, [])
    }

    /// Add a routing handler that is triggered when a super group chat is created.
    pub fn super_group_chat_created_fn<H>(&mut self, handler: H) -> &mut AwesomeBot
    where
        H: Fn(&AwesomeBot, &Message, GroupToSuperGroupMigration) + Send + Sync + 'static,
    {
        add_muxer!(self, handler, Muxer::SuperGroupChatCreatedMux, [])
    }

    /// Add a routing handler that is triggered when a channel chat is created.
    pub fn channel_chat_created_fn<H>(&mut self, handler: H) -> &mut AwesomeBot
    where
        H: Fn(&AwesomeBot, &Message, Chat) + Send + Sync + 'static,
    {
        add_muxer!(self, handler, Muxer::ChannelChatCreatedMux, [])
    }
}

// fn detect_file_or_id(name: &str, path: String) -> SendPath {
//     // When PathExt becomes stable, use Path::new(&path).exists() instead of this!
//     let check = fs::metadata(&path);
//     if path.contains(".") && check.is_ok() && check.unwrap().is_file() {
//         SendPath::File(name.to_owned(), Path::new(&path).to_path_buf())
//     } else {
//         SendPath::Id(name.to_owned(), path)
//     }
// }