dyncord 0.13.6

A high-level, ergonomic, batteries-included Discord bot library for Rust. WIP.
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
use std::fmt::Display;

use twilight_mention::ParseMention;
use twilight_model::id::Id;
use twilight_model::id::marker::{ChannelMarker, RoleMarker, UserMarker};

use crate::commands::errors::ArgumentError;
use crate::commands::prefixed::context::PrefixedContext;
use crate::state::StateBound;
use crate::utils::DynFuture;
use crate::wrappers::types::channels::{Channel, ChannelMention};
use crate::wrappers::types::roles::{Role, RoleMention};
use crate::wrappers::types::users::{User, UserMention};

/// Implements conversion from a raw message into a command's argument.
pub trait IntoArgument<State = ()>: Sized + Send + Sync
where
    State: StateBound,
{
    /// Converts a raw message into a command's argument.
    ///
    /// This function takes two arguments, the command context and the raw arguments. It returns
    /// the parsed argument and the remaining raw arguments if successful, or an [`ArgumentError`]
    /// if parsing the argument failed.
    ///
    /// For example, to parse a `String` argument (which takes one word), the implementation looks
    /// like this:
    ///
    /// ```
    /// fn into_argument(
    ///     _ctx: CommandContext<State>,
    ///     args: String,
    /// ) -> DynFuture<'static, Result<(Self, String), ArgumentError>> {
    ///     Box::pin(async move {
    ///         let trimmed = args.trim_start();
    ///
    ///         match trimmed.split_once(' ') {
    ///             Some((arg, remaining)) => Ok((arg.to_string(), remaining.to_string())),
    ///             None => {
    ///                 if args.is_empty() {
    ///                     Err(ArgumentError::Missing)
    ///                 } else {
    ///                     Ok((args.to_string(), "".to_string()))
    ///                 }
    ///             }
    ///         }
    ///     })
    /// }
    /// ```
    ///
    /// Arguments:
    /// * `ctx` - The command context, which contains information about the message, channel,
    ///   guild, etc.
    /// * `args` - The raw arguments passed to the command, which can be parsed into the command's
    ///   arguments.
    ///
    /// Returns:
    /// * `Ok((argument, remaining_args))` - The parsed argument and the remaining raw arguments if
    ///   parsing was successful.
    /// * `Err(ArgumentError)` - A parsing error if parsing the argument failed.
    fn into_argument(
        ctx: PrefixedContext<State>,
        args: String,
    ) -> DynFuture<'static, Result<(Self, String), ArgumentError>>;
}

impl<State> IntoArgument<State> for String
where
    State: StateBound,
{
    fn into_argument(
        _ctx: PrefixedContext<State>,
        args: String,
    ) -> DynFuture<'static, Result<(Self, String), ArgumentError>> {
        Box::pin(async move {
            let trimmed = args.trim_start();

            if let Some(argument) = parse_token(trimmed) {
                let remaining = trimmed[(argument.value().last + 1)..].to_string();

                Ok((argument.to_string(), remaining))
            } else {
                Err(ArgumentError::Missing)
            }
        })
    }
}

#[derive(Debug)]
enum Token {
    String(TokenValue),
    InSingleQuote(TokenValue),
    InDoubleQuote(TokenValue),
    Spaces(TokenValue),
}

impl Token {
    /// Returns the inner [`TokenValue`] of this token.
    ///
    /// Returns:
    /// [`TokenValue`] - The token's value and metadata.
    fn value(&self) -> &TokenValue {
        match self {
            Self::InDoubleQuote(value) => value,
            Self::InSingleQuote(value) => value,
            Self::Spaces(value) => value,
            Self::String(value) => value,
        }
    }
}

impl Display for Token {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::String(inner) => f.write_str(&inner.value),
            Self::Spaces(inner) => f.write_str(&inner.value),
            Self::InDoubleQuote(inner) => f.write_str(&inner.value),
            Self::InSingleQuote(inner) => f.write_str(&inner.value),
        }
    }
}

#[derive(Debug)]
#[allow(dead_code)]
struct TokenValue {
    value: String,
    first: usize,
    last: usize,
}

/// Parses the first token of raw arguments.
///
/// This tokenizer parses into 4 different token types:
/// - [`Token::String`] - A string word, unquoted.
/// - [`Token::InSingleQuote`] - A single-quote-quoted string. E.g. `'hello world!'`.
/// - [`Token::InDoubleQuote`] - A double-quote-quoted string. E.g. `"hello world!"`.
/// - [`Token::Spaces`] - One or more spaces, separating string and quoted-string tokens.
///
/// This function is an extract of a tokenizer that parses all tokens in a string. This one just
/// parses and returns the first found token.
///
/// It delegates the parsing of each token type to each of the `parse_*` functions (defined below),
/// [`parse_string`], [`parse_space`], [`parse_single_quote`], and [`parse_double_quote`]. Each of
/// them takes a mutable reference to the cursor (`i`, in this function `&mut 0` since it only
/// parses one token) and advances it as it consumes characters from `args` into the token being
/// parsed.
///
/// This tokenizer is used to parse quoted strings as argument values in commands. For example,
/// `!hello "Mike Wazowski"` makes `Mike Wazowski` the first [`String`] argument of this command.
/// It also supports escapes and single-quote quoting, meaning `!hello 'Mike Wazowski'` also works
/// like the first example, and `!echo 'it\'s tuesday!'`'s first argument will be properly parsed
/// as `it's tuesday!`.
///
/// Some examples of how the tokenizer will convert arguments into tokens are:
///
/// - `hello "world"` -> `[String("hello"), Spaces(" "), InDoubleQuotes("world")]`
/// - `hello"world"` -> `[String("hello\"world\"")]`
/// - `hello \"world\"` -> `[String("hello"), Spaces(" "), String("\"world\"")]`
///
/// Note that this tokenizer function only parses the first token, so only the first token of those
/// arrays is returned in practice.
///
/// Arguments:
/// * `args` - The raw args from which to parse the first token.
///
/// Returns:
/// [`Option<Token>`] - The first token parsed, if `args` wasn't empty.
fn parse_token(args: &str) -> Option<Token> {
    if args.is_empty() {
        return None;
    }

    let chars: Vec<_> = args.chars().collect();

    match chars[0] {
        ' ' => Some(parse_space(&chars, &mut 0)),
        '\'' => Some(parse_single_quote(&chars, &mut 0)),
        '"' => Some(parse_double_quote(&chars, &mut 0)),
        _ => Some(parse_string(&chars, &mut 0)),
    }
}

/// Parses a raw string into a [`Token::String`].
///
/// [`Token::String`] tokens are unquoted strings. They support escaping quotes, e.g.
/// `\"hello\"` -> `Token::String("\"hello\"")`, but quotes inside this token are treated like
/// literals. This token ends when either there's no characters left to parse or a white space is
/// found.
///
/// This function will advance the cursor as chars are being parsed into the token, and the cursor
/// will be `last_token_index + 1` when the function returns.
///
/// Note: The cursor MUST be the starting index of the string token to parse when this function is
///       called. Not guaranteeing so before calling this function will cause the wrong characters,
///       potentially not belonging in a [`Token::String`], to be parsed into a [`Token::String`].
///
/// Arguments:
/// * `chars` - A slice pointing to all chars being parsed.
/// * `i` - A mutable reference to the parsing cursor.
///
/// Returns:
/// [`Token::String`] - The string token parsed.
fn parse_string(chars: &[char], i: &mut usize) -> Token {
    let mut current = String::new();

    let first_i = *i;

    while *i < chars.len() {
        let current_char = chars[*i];

        match current_char {
            ' ' => {
                break;
            }
            '\\' => {
                *i += 1;

                if ['\'', '"', '\\'].contains(&chars[*i]) {
                    current.push(chars[*i]);
                } else {
                    current.push('\\');
                    current.push(chars[*i]);
                }
            }
            ch => {
                current.push(ch);
            }
        }

        *i += 1;
    }

    Token::String(TokenValue {
        value: current,
        first: first_i,
        last: *i - 1,
    })
}

/// Parses zero or more white spaces into a [`Token::Spaces`].
///
/// Even though the [`parse_token`] function indicates that [`Token::Spaces`] tokens contain one or
/// more white spaces, this function may return a [`Token::Spaces`] containing an empty string if
/// the passed cursor does not point to a white space when this function is called.
///
/// This function will advance the cursor as chars are being parsed into the token, and the cursor
/// will be `last_token_index + 1` when the function returns.
///
/// Arguments:
/// * `chars` - A slice pointing to all chars being parsed.
/// * `i` - A mutable reference to the parsing cursor.
///
/// Returns:
/// [`Token::Spaces`] - The spaces token parsed.
fn parse_space(chars: &[char], i: &mut usize) -> Token {
    let mut current = String::new();

    let first_i = *i;

    while *i < chars.len() && chars[*i] == ' ' {
        current.push(chars[*i]);
        *i += 1;
    }

    Token::Spaces(TokenValue {
        value: current,
        first: first_i,
        last: *i - 1,
    })
}

/// Parses a single-quote-quoted token, or a [`Token::String`] if there's no closing quote.
///
/// [`Token::InSingleQuote`] tokens represent single-quote-quoted strings. For example,
/// `'hello world'`. It supports escaping such quotes, and escaping backslashes not to escape
/// single quotes.
///
/// If the single-quote-quoted string being parsed ends up not having a closing quote, this'll
/// fall back to parsing the token as a [`Token::String`] using [`parse_string`].
///
/// This function will advance the cursor as chars are being parsed into the token, and the cursor
/// will be `last_token_index + 1` when the function returns.
///
/// Note: The cursor MUST be the starting index of the single-quote-quoted token to parse when this
///       function is called. This means `i` should be the index of a `'\''` char in `chars`. Not
///       guaranteeing so before calling this function to panic.
///
/// Arguments:
/// * `chars` - A slice pointing to all chars being parsed.
/// * `i` - A mutable reference to the parsing cursor.
///
/// Returns:
/// * [`Token::InSingleQuote`] - If the token was successfully parsed as a single-quote-quoted
///   string.
/// * [`Token::String`] - If the token didn't have a closing single quote. E.g. `'hello`.
///
/// Panics:
/// * If `i` is not the index of a `'\''` char in `chars` when the function is called.
fn parse_single_quote(chars: &[char], i: &mut usize) -> Token {
    // In case we don't find a closing quote, this will let us restart as a string.
    let first_i = *i;

    let mut current = String::new();

    if chars[*i] != '\'' {
        unreachable!("The first character of a single-quote string must be a single quote (').");
    }

    // Skip the leading single quote.
    *i += 1;

    while *i < chars.len() {
        match chars[*i] {
            '\\' => {
                *i += 1; // Let's check what the following character is.

                if let Some(next) = chars.get(*i) {
                    if ['\\', '\''].contains(next) {
                        // The next char is escape-able, we push it directly.
                        current.push(*next);
                    } else {
                        // The next char is not escape-able, so the backslash is just a backslash.
                        current.push('\\');
                        current.push(*next);
                    }
                } else {
                    break; // There's no next loop run, we stop before *i += 1 after this `match`.
                }
            }
            '\'' => {
                // Point to the next char for the next parser and return what we found.
                *i += 1;
                return Token::InSingleQuote(TokenValue {
                    value: current,
                    first: first_i,
                    last: *i - 1,
                });
            }
            ch => {
                current.push(ch);
            }
        }

        *i += 1;
    }

    // In single quote, but we never found the closing quote. This was a string all the time.
    *i = first_i;
    parse_string(chars, i)
}

/// Parses a double-quote-quoted token, or a [`Token::String`] if there's no closing quote.
///
/// [`Token::InDoubleQuote`] tokens represent double-quote-quoted strings. For example,
/// `"hello world"`. It supports escaping such quotes, and escaping backslashes not to escape
/// double quotes.
///
/// If the double-quote-quoted string being parsed ends up not having a closing quote, this'll
/// fall back to parsing the token as a [`Token::String`] using [`parse_string`].
///
/// This function will advance the cursor as chars are being parsed into the token, and the cursor
/// will be `last_token_index + 1` when the function returns.
///
/// Note: The cursor MUST be the starting index of the double-quote-quoted token to parse when this
///       function is called. This means `i` should be the index of a `'"'` char in `chars`. Not
///       guaranteeing so before calling this function to panic.
///
/// Arguments:
/// * `chars` - A slice pointing to all chars being parsed.
/// * `i` - A mutable reference to the parsing cursor.
///
/// Returns:
/// * [`Token::InDoubleQuote`] - If the token was successfully parsed as a double-quote-quoted
///   string.
/// * [`Token::String`] - If the token didn't have a closing single quote. E.g. `"hello`.
///
/// Panics:
/// * If `i` is not the index of a `'"'` char in `chars` when the function is called.
fn parse_double_quote(chars: &[char], i: &mut usize) -> Token {
    // In case we don't find a closing quote, this will let us restart as a string.
    let first_i = *i;

    let mut current = String::new();

    if chars[*i] != '"' {
        unreachable!("The first character of a double-quote string must be a double quote (\").");
    }

    // Skip the leading double quote.
    *i += 1;

    while *i < chars.len() {
        match chars[*i] {
            '\\' => {
                *i += 1; // Let's check what the following character is.

                if let Some(next) = chars.get(*i) {
                    if ['\\', '"'].contains(next) {
                        // The next char is escape-able, we push it directly.
                        current.push(*next);
                    } else {
                        // The next char is not escape-able, so the backslash is just a backslash.
                        current.push('\\');
                        current.push(*next);
                    }
                } else {
                    break; // There's no next loop run, we stop before *i += 1 after this `match`.
                }
            }
            '"' => {
                // Point to the next char for the next parser and return what we found.
                *i += 1;
                return Token::InDoubleQuote(TokenValue {
                    value: current,
                    first: first_i,
                    last: *i - 1,
                });
            }
            ch => {
                current.push(ch);
            }
        }

        *i += 1;
    }

    // In double quote, but we never found the closing quote. This was a string all the time.
    *i = first_i;
    parse_string(chars, i)
}

/// Takes all remaining raw arguments as a single string argument.
///
/// For example, if a command is invoked with `.echo Hello, world!`, the `GreedyString` argument
/// will be parsed as `Hello, world!` instead of just `Hello,`.
///
/// To use it in a handler, just add it as an argument like follows:
///
/// ```
/// async fn echo(ctx: CommandContext, GreedyString(message): GreedyString) {
///     ctx.send(message).await.unwrap();
/// }
/// ```
pub struct GreedyString(pub String);

impl<State> IntoArgument<State> for GreedyString
where
    State: StateBound,
{
    fn into_argument(
        _ctx: PrefixedContext<State>,
        args: String,
    ) -> DynFuture<'static, Result<(Self, String), ArgumentError>> {
        Box::pin(async move { Ok((GreedyString(args.trim_start().to_string()), "".to_string())) })
    }
}

impl<State> IntoArgument<State> for char
where
    State: StateBound,
{
    fn into_argument(
        ctx: PrefixedContext<State>,
        args: String,
    ) -> DynFuture<'static, Result<(Self, String), ArgumentError>> {
        Box::pin(async move {
            let (arg, remaining) = String::into_argument(ctx, args).await?;
            let mut chars = arg.chars();

            match (chars.next(), chars.next()) {
                (Some(c), None) => Ok((c, remaining)),
                _ => Err(ArgumentError::Misformatted),
            }
        })
    }
}

impl<State> IntoArgument<State> for i8
where
    State: StateBound,
{
    fn into_argument(
        ctx: PrefixedContext<State>,
        args: String,
    ) -> DynFuture<'static, Result<(Self, String), ArgumentError>> {
        Box::pin(async move {
            let (arg, remaining) = String::into_argument(ctx, args).await?;
            match arg.parse::<Self>() {
                Ok(num) => Ok((num, remaining)),
                Err(_) => Err(ArgumentError::Misformatted),
            }
        })
    }
}

impl<State> IntoArgument<State> for i16
where
    State: StateBound,
{
    fn into_argument(
        ctx: PrefixedContext<State>,
        args: String,
    ) -> DynFuture<'static, Result<(Self, String), ArgumentError>> {
        Box::pin(async move {
            let (arg, remaining) = String::into_argument(ctx, args).await?;
            match arg.parse::<Self>() {
                Ok(num) => Ok((num, remaining)),
                Err(_) => Err(ArgumentError::Misformatted),
            }
        })
    }
}

impl<State> IntoArgument<State> for i32
where
    State: StateBound,
{
    fn into_argument(
        ctx: PrefixedContext<State>,
        args: String,
    ) -> DynFuture<'static, Result<(Self, String), ArgumentError>> {
        Box::pin(async move {
            let (arg, remaining) = String::into_argument(ctx, args).await?;
            match arg.parse::<Self>() {
                Ok(num) => Ok((num, remaining)),
                Err(_) => Err(ArgumentError::Misformatted),
            }
        })
    }
}

impl<State> IntoArgument<State> for i64
where
    State: StateBound,
{
    fn into_argument(
        ctx: PrefixedContext<State>,
        args: String,
    ) -> DynFuture<'static, Result<(Self, String), ArgumentError>> {
        Box::pin(async move {
            let (arg, remaining) = String::into_argument(ctx, args).await?;
            match arg.parse::<Self>() {
                Ok(num) => Ok((num, remaining)),
                Err(_) => Err(ArgumentError::Misformatted),
            }
        })
    }
}

impl<State> IntoArgument<State> for i128
where
    State: StateBound,
{
    fn into_argument(
        ctx: PrefixedContext<State>,
        args: String,
    ) -> DynFuture<'static, Result<(Self, String), ArgumentError>> {
        Box::pin(async move {
            let (arg, remaining) = String::into_argument(ctx, args).await?;
            match arg.parse::<Self>() {
                Ok(num) => Ok((num, remaining)),
                Err(_) => Err(ArgumentError::Misformatted),
            }
        })
    }
}

impl<State> IntoArgument<State> for isize
where
    State: StateBound,
{
    fn into_argument(
        ctx: PrefixedContext<State>,
        args: String,
    ) -> DynFuture<'static, Result<(Self, String), ArgumentError>> {
        Box::pin(async move {
            let (arg, remaining) = String::into_argument(ctx, args).await?;
            match arg.parse::<Self>() {
                Ok(num) => Ok((num, remaining)),
                Err(_) => Err(ArgumentError::Misformatted),
            }
        })
    }
}

impl<State> IntoArgument<State> for u8
where
    State: StateBound,
{
    fn into_argument(
        ctx: PrefixedContext<State>,
        args: String,
    ) -> DynFuture<'static, Result<(Self, String), ArgumentError>> {
        Box::pin(async move {
            let (arg, remaining) = String::into_argument(ctx, args).await?;
            match arg.parse::<Self>() {
                Ok(num) => Ok((num, remaining)),
                Err(_) => Err(ArgumentError::Misformatted),
            }
        })
    }
}

impl<State> IntoArgument<State> for u16
where
    State: StateBound,
{
    fn into_argument(
        ctx: PrefixedContext<State>,
        args: String,
    ) -> DynFuture<'static, Result<(Self, String), ArgumentError>> {
        Box::pin(async move {
            let (arg, remaining) = String::into_argument(ctx, args).await?;
            match arg.parse::<Self>() {
                Ok(num) => Ok((num, remaining)),
                Err(_) => Err(ArgumentError::Misformatted),
            }
        })
    }
}

impl<State> IntoArgument<State> for u32
where
    State: StateBound,
{
    fn into_argument(
        ctx: PrefixedContext<State>,
        args: String,
    ) -> DynFuture<'static, Result<(Self, String), ArgumentError>> {
        Box::pin(async move {
            let (arg, remaining) = String::into_argument(ctx, args).await?;
            match arg.parse::<Self>() {
                Ok(num) => Ok((num, remaining)),
                Err(_) => Err(ArgumentError::Misformatted),
            }
        })
    }
}

impl<State> IntoArgument<State> for u64
where
    State: StateBound,
{
    fn into_argument(
        ctx: PrefixedContext<State>,
        args: String,
    ) -> DynFuture<'static, Result<(Self, String), ArgumentError>> {
        Box::pin(async move {
            let (arg, remaining) = String::into_argument(ctx, args).await?;
            match arg.parse::<Self>() {
                Ok(num) => Ok((num, remaining)),
                Err(_) => Err(ArgumentError::Misformatted),
            }
        })
    }
}

impl<State> IntoArgument<State> for u128
where
    State: StateBound,
{
    fn into_argument(
        ctx: PrefixedContext<State>,
        args: String,
    ) -> DynFuture<'static, Result<(Self, String), ArgumentError>> {
        Box::pin(async move {
            let (arg, remaining) = String::into_argument(ctx, args).await?;
            match arg.parse::<Self>() {
                Ok(num) => Ok((num, remaining)),
                Err(_) => Err(ArgumentError::Misformatted),
            }
        })
    }
}

impl<State> IntoArgument<State> for usize
where
    State: StateBound,
{
    fn into_argument(
        ctx: PrefixedContext<State>,
        args: String,
    ) -> DynFuture<'static, Result<(Self, String), ArgumentError>> {
        Box::pin(async move {
            let (arg, remaining) = String::into_argument(ctx, args).await?;
            match arg.parse::<Self>() {
                Ok(num) => Ok((num, remaining)),
                Err(_) => Err(ArgumentError::Misformatted),
            }
        })
    }
}

impl<State> IntoArgument<State> for f32
where
    State: StateBound,
{
    fn into_argument(
        ctx: PrefixedContext<State>,
        args: String,
    ) -> DynFuture<'static, Result<(Self, String), ArgumentError>> {
        Box::pin(async move {
            let (arg, remaining) = String::into_argument(ctx, args).await?;
            match arg.parse::<Self>() {
                Ok(num) => Ok((num, remaining)),
                Err(_) => Err(ArgumentError::Misformatted),
            }
        })
    }
}

impl<State> IntoArgument<State> for f64
where
    State: StateBound,
{
    fn into_argument(
        ctx: PrefixedContext<State>,
        args: String,
    ) -> DynFuture<'static, Result<(Self, String), ArgumentError>> {
        Box::pin(async move {
            let (arg, remaining) = String::into_argument(ctx, args).await?;
            match arg.parse::<Self>() {
                Ok(num) => Ok((num, remaining)),
                Err(_) => Err(ArgumentError::Misformatted),
            }
        })
    }
}

impl<State> IntoArgument<State> for bool
where
    State: StateBound,
{
    fn into_argument(
        ctx: PrefixedContext<State>,
        args: String,
    ) -> DynFuture<'static, Result<(Self, String), ArgumentError>> {
        Box::pin(async move {
            let (arg, remaining) = String::into_argument(ctx, args).await?;
            match arg.to_lowercase().as_str() {
                "true" | "y" | "yes" | "1" | "on" => Ok((true, remaining)),
                "false" | "n" | "no" | "0" | "off" => Ok((false, remaining)),
                _ => Err(ArgumentError::Misformatted),
            }
        })
    }
}

impl<State> IntoArgument<State> for User
where
    State: StateBound,
{
    fn into_argument(
        ctx: PrefixedContext<State>,
        args: String,
    ) -> DynFuture<'static, Result<(Self, String), ArgumentError>> {
        Box::pin(async move {
            let (arg, remaining) = String::into_argument(ctx.clone(), args).await?;

            let user_id = Id::<UserMarker>::parse(&arg).map_err(|_| ArgumentError::Misformatted)?;

            // Users may write a properly-formatted mention that points to no user (or to no
            // accessible user). We check for mentions received so that if Discord didn't send
            // any we can fail fast.
            ctx.event
                .mentions
                .iter()
                .find(|mention| mention.id == user_id)
                .ok_or(ArgumentError::MissingResolved)?;

            let user = ctx
                .handle
                .get_or_fetch_user(user_id.get())
                .await
                .map_err(ArgumentError::new)?;

            Ok((user, remaining))
        })
    }
}

impl<State> IntoArgument<State> for UserMention
where
    State: StateBound,
{
    fn into_argument(
        ctx: PrefixedContext<State>,
        args: String,
    ) -> DynFuture<'static, Result<(Self, String), ArgumentError>> {
        Box::pin(async move {
            let (arg, remaining) = String::into_argument(ctx.clone(), args).await?;

            let user_id = Id::<UserMarker>::parse(&arg).map_err(|_| ArgumentError::Misformatted)?;

            let mention = ctx
                .event
                .mentions
                .iter()
                .find(|mention| mention.id == user_id)
                .ok_or(ArgumentError::MissingResolved)?;

            Ok((mention.clone().into(), remaining))
        })
    }
}

impl<State> IntoArgument<State> for Channel
where
    State: StateBound,
{
    fn into_argument(
        ctx: PrefixedContext<State>,
        args: String,
    ) -> DynFuture<'static, Result<(Self, String), ArgumentError>> {
        Box::pin(async move {
            let (arg, remaining) = String::into_argument(ctx.clone(), args).await?;

            let channel_id =
                Id::<ChannelMarker>::parse(&arg).map_err(|_| ArgumentError::Misformatted)?;

            // Users may write a properly-formatted mention that points to no channel (or to no
            // accessible channel). We check for mentions received so that if Discord didn't send
            // any we can fail fast.
            ctx.event
                .mention_channels
                .iter()
                .find(|mention| mention.id == channel_id)
                .ok_or(ArgumentError::MissingResolved)?;

            let channel = ctx
                .handle
                .client
                .channel(channel_id)
                .await
                .map_err(ArgumentError::new)?
                .model()
                .await
                .map_err(ArgumentError::new)?;

            Ok((channel.into(), remaining))
        })
    }
}

impl<State> IntoArgument<State> for ChannelMention
where
    State: StateBound,
{
    fn into_argument(
        ctx: PrefixedContext<State>,
        args: String,
    ) -> DynFuture<'static, Result<(Self, String), ArgumentError>> {
        Box::pin(async move {
            let (arg, remaining) = String::into_argument(ctx.clone(), args).await?;

            let channel_id =
                Id::<ChannelMarker>::parse(&arg).map_err(|_| ArgumentError::Misformatted)?;

            let mention = ctx
                .event
                .mention_channels
                .iter()
                .find(|mention| mention.id == channel_id)
                .ok_or(ArgumentError::MissingResolved)?;

            Ok((mention.clone().into(), remaining))
        })
    }
}

impl<State> IntoArgument<State> for Role
where
    State: StateBound,
{
    fn into_argument(
        ctx: PrefixedContext<State>,
        args: String,
    ) -> DynFuture<'static, Result<(Self, String), ArgumentError>> {
        Box::pin(async move {
            if let Some(guild_id) = ctx.event.guild_id {
                let (arg, remaining) = String::into_argument(ctx.clone(), args).await?;

                let role_id =
                    Id::<RoleMarker>::parse(&arg).map_err(|_| ArgumentError::Misformatted)?;

                // Users may write a properly-formatted mention that points to no role (or to no
                // accessible role). We check for mentions received so that if Discord didn't send
                // any we can fail fast.
                ctx.event
                    .mention_roles
                    .iter()
                    .find(|mention| **mention == role_id)
                    .ok_or(ArgumentError::MissingResolved)?;

                let role = ctx
                    .handle
                    .client
                    .role(guild_id, role_id)
                    .await
                    .map_err(ArgumentError::new)?
                    .model()
                    .await
                    .map_err(ArgumentError::new)?;

                Ok((role.into(), remaining))
            } else {
                Err(ArgumentError::WrongContext)
            }
        })
    }
}

impl<State> IntoArgument<State> for RoleMention
where
    State: StateBound,
{
    fn into_argument(
        ctx: PrefixedContext<State>,
        args: String,
    ) -> DynFuture<'static, Result<(Self, String), ArgumentError>> {
        Box::pin(async move {
            let (arg, remaining) = String::into_argument(ctx.clone(), args).await?;

            let role_id = Id::<RoleMarker>::parse(&arg).map_err(|_| ArgumentError::Misformatted)?;

            let mention = ctx
                .event
                .mention_roles
                .iter()
                .find(|mention| **mention == role_id)
                .ok_or(ArgumentError::MissingResolved)?;

            Ok(((*mention).into(), remaining))
        })
    }
}

impl<State, T> IntoArgument<State> for Option<T>
where
    State: StateBound,
    T: IntoArgument<State>,
{
    fn into_argument(
        ctx: PrefixedContext<State>,
        args: String,
    ) -> DynFuture<'static, Result<(Self, String), ArgumentError>> {
        Box::pin(async move {
            match T::into_argument(ctx, args.clone()).await {
                Ok((arg, remaining)) => Ok((Some(arg), remaining)),
                Err(_) => Ok((None, args)),
            }
        })
    }
}