serenity 0.12.5

A Rust library for the Discord API.
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
//! A set of utilities to help with common use cases that are not required to fully use the
//! library.

#[cfg(feature = "client")]
mod argument_convert;
#[cfg(feature = "cache")]
mod content_safe;
mod custom_message;
mod formatted_timestamp;
mod message_builder;
#[cfg(feature = "collector")]
mod quick_modal;

pub mod token;

use std::num::NonZeroU16;

#[cfg(feature = "client")]
pub use argument_convert::*;
#[cfg(feature = "cache")]
pub use content_safe::*;
pub use formatted_timestamp::*;
#[cfg(feature = "collector")]
pub use quick_modal::*;
use url::Url;

pub use self::custom_message::CustomMessage;
pub use self::message_builder::{Content, ContentModifier, EmbedMessageBuilding, MessageBuilder};
#[doc(inline)]
pub use self::token::validate as validate_token;
#[cfg(all(feature = "cache", feature = "model"))]
use crate::cache::Cache;
#[cfg(all(feature = "cache", feature = "model"))]
use crate::http::CacheHttp;
use crate::model::prelude::*;

/// Retrieves the "code" part of an invite out of a URL.
///
/// # Examples
///
/// Two formats of [invite][`RichInvite`] codes are supported, both regardless of protocol prefix.
/// Some examples:
///
/// 1. Retrieving the code from the URL `"https://discord.gg/0cDvIgU2voY8RSYL"`:
///
/// ```rust
/// use serenity::utils;
///
/// let url = "https://discord.gg/0cDvIgU2voY8RSYL";
///
/// assert_eq!(utils::parse_invite(url), "0cDvIgU2voY8RSYL");
/// ```
///
/// 2. Retrieving the code from the URL `"http://discord.com/invite/0cDvIgU2voY8RSYL"`:
///
/// ```rust
/// use serenity::utils;
///
/// let url = "http://discord.com/invite/0cDvIgU2voY8RSYL";
///
/// assert_eq!(utils::parse_invite(url), "0cDvIgU2voY8RSYL");
/// ```
///
/// [`RichInvite`]: crate::model::invite::RichInvite
#[must_use]
pub fn parse_invite(code: &str) -> &str {
    let code = code.trim_start_matches("http://").trim_start_matches("https://");
    let lower = code.to_lowercase();
    if lower.starts_with("discord.gg/") {
        &code[11..]
    } else if lower.starts_with("discord.com/invite/") {
        &code[19..]
    } else {
        code
    }
}

/// Retrieves the username and discriminator out of a user tag (`name#discrim`).
/// In order to accomodate next gen Discord usernames, this will also accept `name` style tags.
///
/// If the user tag is invalid, None is returned.
///
/// # Examples
/// ```rust
/// use std::num::NonZeroU16;
///
/// use serenity::utils::parse_user_tag;
///
/// assert_eq!(parse_user_tag("kangalioo#9108"), Some(("kangalioo", NonZeroU16::new(9108))));
/// assert_eq!(parse_user_tag("kangalioo#10108"), None);
/// assert_eq!(parse_user_tag("kangalioo"), Some(("kangalioo", None)));
/// ```
#[must_use]
pub fn parse_user_tag(s: &str) -> Option<(&str, Option<NonZeroU16>)> {
    if let Some((name, discrim)) = s.split_once('#') {
        let discrim: u16 = discrim.parse().ok()?;
        if discrim > 9999 {
            return None;
        }
        Some((name, NonZeroU16::new(discrim)))
    } else {
        Some((s, None))
    }
}

/// Retrieves an Id from a user mention.
///
/// If the mention is invalid, then [`None`] is returned.
///
/// # Examples
///
/// Retrieving an Id from a valid [`User`] mention:
///
/// ```rust
/// use serenity::model::id::UserId;
/// use serenity::utils::parse_username;
///
/// // regular username mention
/// assert_eq!(parse_username("<@114941315417899012>"), Some(UserId::new(114941315417899012)));
///
/// // nickname mention
/// assert_eq!(parse_username("<@!114941315417899012>"), Some(UserId::new(114941315417899012)));
/// ```
///
/// Asserting that an invalid username or nickname mention returns [`None`]:
///
/// ```rust
/// use serenity::utils::parse_username;
///
/// assert!(parse_username("<@1149413154aa17899012").is_none());
/// assert!(parse_username("<@!11494131541789a90b1c2").is_none());
/// ```
///
/// [`User`]: crate::model::user::User
#[must_use]
pub fn parse_user_mention(mention: &str) -> Option<UserId> {
    if mention.len() < 4 {
        return None;
    }

    let len = mention.len() - 1;
    if mention.starts_with("<@!") {
        mention[3..len].parse().ok()
    } else if mention.starts_with("<@") {
        mention[2..len].parse().ok()
    } else {
        None
    }
}

#[deprecated = "use `utils::parse_user_mention` instead"]
pub fn parse_username(mention: impl AsRef<str>) -> Option<UserId> {
    parse_user_mention(mention.as_ref())
}

/// Retrieves an Id from a role mention.
///
/// If the mention is invalid, then [`None`] is returned.
///
/// # Examples
///
/// Retrieving an Id from a valid [`Role`] mention:
///
/// ```rust
/// use serenity::model::id::RoleId;
/// use serenity::utils::parse_role;
///
/// assert_eq!(parse_role("<@&136107769680887808>"), Some(RoleId::new(136107769680887808)));
/// ```
///
/// Asserting that an invalid role mention returns [`None`]:
///
/// ```rust
/// use serenity::utils::parse_role;
///
/// assert!(parse_role("<@&136107769680887808").is_none());
/// ```
///
/// [`Role`]: crate::model::guild::Role
#[must_use]
pub fn parse_role_mention(mention: &str) -> Option<RoleId> {
    if mention.len() < 4 {
        return None;
    }

    if mention.starts_with("<@&") && mention.ends_with('>') {
        let len = mention.len() - 1;
        mention[3..len].parse().ok()
    } else {
        None
    }
}

#[deprecated = "use `utils::parse_role_mention` instead"]
pub fn parse_role(mention: impl AsRef<str>) -> Option<RoleId> {
    parse_role_mention(mention.as_ref())
}

/// Retrieves an Id from a channel mention.
///
/// If the channel mention is invalid, then [`None`] is returned.
///
/// # Examples
///
/// Retrieving an Id from a valid [`Channel`] mention:
///
/// ```rust
/// use serenity::model::id::ChannelId;
/// use serenity::utils::parse_channel;
///
/// assert_eq!(parse_channel("<#81384788765712384>"), Some(ChannelId::new(81384788765712384)));
/// ```
///
/// Asserting that an invalid channel mention returns [`None`]:
///
/// ```rust
/// use serenity::utils::parse_channel;
///
/// assert!(parse_channel("<#!81384788765712384>").is_none());
/// assert!(parse_channel("<#81384788765712384").is_none());
/// ```
///
/// [`Channel`]: crate::model::channel::Channel
#[must_use]
pub fn parse_channel_mention(mention: &str) -> Option<ChannelId> {
    if mention.len() < 4 {
        return None;
    }

    if mention.starts_with("<#") && mention.ends_with('>') {
        let len = mention.len() - 1;
        mention[2..len].parse().ok()
    } else {
        None
    }
}

#[deprecated = "use `utils::parse_channel_mention` instead"]
pub fn parse_channel(mention: impl AsRef<str>) -> Option<ChannelId> {
    parse_channel_mention(mention.as_ref())
}

/// Retrieves the animated state, name and Id from an emoji mention, in the form of an
/// [`EmojiIdentifier`].
///
/// If the emoji usage is invalid, then [`None`] is returned.
///
/// # Examples
///
/// Ensure that a valid [`Emoji`] usage is correctly parsed:
///
/// ```rust
/// use serenity::model::id::{EmojiId, GuildId};
/// use serenity::model::misc::EmojiIdentifier;
/// use serenity::utils::parse_emoji;
///
/// let emoji = parse_emoji("<:smugAnimeFace:302516740095606785>").unwrap();
/// assert_eq!(emoji.animated, false);
/// assert_eq!(emoji.id, EmojiId::new(302516740095606785));
/// assert_eq!(emoji.name, "smugAnimeFace".to_string());
/// ```
///
/// Asserting that an invalid emoji usage returns [`None`]:
///
/// ```rust
/// use serenity::utils::parse_emoji;
///
/// assert!(parse_emoji("<:smugAnimeFace:302516740095606785").is_none());
/// ```
///
/// [`Emoji`]: crate::model::guild::Emoji
pub fn parse_emoji(mention: impl AsRef<str>) -> Option<EmojiIdentifier> {
    let mention = mention.as_ref();

    let len = mention.len();

    if !(6..=56).contains(&len) {
        return None;
    }

    if (mention.starts_with("<:") || mention.starts_with("<a:")) && mention.ends_with('>') {
        let mut name = String::default();
        let mut id = String::default();
        let animated = &mention[1..3] == "a:";

        let start = if animated { 3 } else { 2 };

        for (i, x) in mention[start..].chars().enumerate() {
            if x == ':' {
                let from = i + start + 1;

                for y in mention[from..].chars() {
                    if y == '>' {
                        break;
                    }
                    id.push(y);
                }

                break;
            }
            name.push(x);
        }

        id.parse().ok().map(|id| EmojiIdentifier {
            animated,
            id,
            name,
        })
    } else {
        None
    }
}

/// Turns a string into a vector of string arguments, splitting by spaces, but parsing content
/// within quotes as one individual argument.
///
/// # Examples
///
/// Parsing two quoted commands:
///
/// ```rust
/// use serenity::utils::parse_quotes;
///
/// let command = r#""this is the first" "this is the second""#;
/// let expected = vec!["this is the first".to_string(), "this is the second".to_string()];
///
/// assert_eq!(parse_quotes(command), expected);
/// ```
///
/// ```rust
/// use serenity::utils::parse_quotes;
///
/// let command = r#""this is a quoted command that doesn't have an ending quotation"#;
/// let expected =
///     vec!["this is a quoted command that doesn't have an ending quotation".to_string()];
///
/// assert_eq!(parse_quotes(command), expected);
/// ```
pub fn parse_quotes(s: impl AsRef<str>) -> Vec<String> {
    let s = s.as_ref();
    let mut args = vec![];
    let mut in_string = false;
    let mut escaping = false;
    let mut current_str = String::default();

    for x in s.chars() {
        if in_string {
            if x == '\\' && !escaping {
                escaping = true;
            } else if x == '"' && !escaping {
                if !current_str.is_empty() {
                    args.push(current_str);
                }

                current_str = String::default();
                in_string = false;
            } else {
                current_str.push(x);
                escaping = false;
            }
        } else if x == ' ' {
            if !current_str.is_empty() {
                args.push(current_str.clone());
            }

            current_str = String::default();
        } else if x == '"' {
            if !current_str.is_empty() {
                args.push(current_str.clone());
            }

            in_string = true;
            current_str = String::default();
        } else {
            current_str.push(x);
        }
    }

    if !current_str.is_empty() {
        args.push(current_str);
    }

    args
}

/// Discord's official domains. This is used in [`parse_webhook`] and in its corresponding test.
const DOMAINS: &[&str] = &[
    "discord.com",
    "canary.discord.com",
    "ptb.discord.com",
    "discordapp.com",
    "canary.discordapp.com",
    "ptb.discordapp.com",
];

/// Parses the id and token from a webhook url. Expects a [`url::Url`] rather than a [`&str`].
///
/// # Examples
///
/// ```rust
/// use serenity::utils;
///
/// let url_str = "https://discord.com/api/webhooks/245037420704169985/ig5AO-wdVWpCBtUUMxmgsWryqgsW3DChbKYOINftJ4DCrUbnkedoYZD0VOH1QLr-S3sV";
/// let url = url_str.parse().unwrap();
/// let (id, token) = utils::parse_webhook(&url).unwrap();
///
/// assert_eq!(id, 245037420704169985);
/// assert_eq!(token, "ig5AO-wdVWpCBtUUMxmgsWryqgsW3DChbKYOINftJ4DCrUbnkedoYZD0VOH1QLr-S3sV");
/// ```
#[must_use]
pub fn parse_webhook(url: &Url) -> Option<(WebhookId, &str)> {
    let (webhook_id, token) = url.path().strip_prefix("/api/webhooks/")?.split_once('/')?;
    if !["http", "https"].contains(&url.scheme())
        || !DOMAINS.contains(&url.domain()?)
        || !(17..=20).contains(&webhook_id.len())
        || !(60..=68).contains(&token.len())
    {
        return None;
    }
    Some((webhook_id.parse().ok()?, token))
}

#[cfg(all(feature = "cache", feature = "model"))]
pub(crate) fn user_has_guild_perms(
    cache_http: impl CacheHttp,
    guild_id: GuildId,
    permissions: Permissions,
) -> Result<()> {
    if let Some(cache) = cache_http.cache() {
        if let Some(guild) = cache.guild(guild_id) {
            guild.require_perms(cache, permissions)?;
        }
    }
    Ok(())
}

/// Tries to find a user's permissions using the cache. Unlike [`user_has_perms`], this function
/// will return `true` even when the permissions are not in the cache.
#[cfg(all(feature = "cache", feature = "model"))]
#[inline]
pub(crate) fn user_has_perms_cache(
    cache: impl AsRef<Cache>,
    channel_id: ChannelId,
    required_permissions: Permissions,
) -> Result<()> {
    match user_perms(cache, channel_id) {
        Ok(perms) => {
            if perms.contains(required_permissions) {
                Ok(())
            } else {
                Err(Error::Model(ModelError::InvalidPermissions {
                    required: required_permissions,
                    present: perms,
                }))
            }
        },
        Err(Error::Model(err)) if err.is_cache_err() => Ok(()),
        Err(other) => Err(other),
    }
}

#[cfg(all(feature = "cache", feature = "model"))]
pub(crate) fn user_perms(cache: impl AsRef<Cache>, channel_id: ChannelId) -> Result<Permissions> {
    let cache = cache.as_ref();

    let Some(guild_id) = cache.channels.get(&channel_id).map(|c| *c) else {
        return Err(Error::Model(ModelError::ChannelNotFound));
    };

    let Some(guild) = cache.guild(guild_id) else {
        return Err(Error::Model(ModelError::GuildNotFound));
    };

    let Some(channel) = guild.channels.get(&channel_id) else {
        return Err(Error::Model(ModelError::ChannelNotFound));
    };

    let Some(member) = guild.members.get(&cache.current_user().id) else {
        return Err(Error::Model(ModelError::MemberNotFound));
    };

    Ok(guild.user_permissions_in(channel, member))
}

/// Calculates the Id of the shard responsible for a guild, given its Id and total number of shards
/// used.
///
/// # Examples
///
/// Retrieve the Id of the shard for a guild with Id `81384788765712384`, using 17 shards:
///
/// ```rust
/// use serenity::model::id::GuildId;
/// use serenity::utils;
///
/// assert_eq!(utils::shard_id(GuildId::new(81384788765712384), 17), 7);
/// ```
#[inline]
#[must_use]
pub fn shard_id(guild_id: GuildId, shard_count: u32) -> u32 {
    ((guild_id.get() >> 22) % (shard_count as u64)) as u32
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn test_invite_parser() {
        assert_eq!(parse_invite("https://discord.gg/abc"), "abc");
        assert_eq!(parse_invite("http://discord.gg/abc"), "abc");
        assert_eq!(parse_invite("discord.gg/abc"), "abc");
        assert_eq!(parse_invite("DISCORD.GG/ABC"), "ABC");
        assert_eq!(parse_invite("https://discord.com/invite/abc"), "abc");
        assert_eq!(parse_invite("http://discord.com/invite/abc"), "abc");
        assert_eq!(parse_invite("discord.com/invite/abc"), "abc");
    }

    #[test]
    fn test_username_parser() {
        assert_eq!(parse_user_mention("<@12345>").unwrap(), 12_345);
        assert_eq!(parse_user_mention("<@!12345>").unwrap(), 12_345);
    }

    #[test]
    fn role_parser() {
        assert_eq!(parse_role_mention("<@&12345>").unwrap(), 12_345);
    }

    #[test]
    fn test_channel_parser() {
        assert_eq!(parse_channel_mention("<#12345>").unwrap(), 12_345);
    }

    #[test]
    fn test_emoji_parser() {
        let emoji = parse_emoji("<:name:12345>").unwrap();
        assert_eq!(emoji.name, "name");
        assert_eq!(emoji.id, 12_345);
    }

    #[test]
    fn test_quote_parser() {
        let parsed = parse_quotes("a \"b c\" d\"e f\"  g");
        assert_eq!(parsed, ["a", "b c", "d", "e f", "g"]);
    }

    #[test]
    fn test_webhook_parser() {
        for domain in DOMAINS {
            let url = format!("https://{domain}/api/webhooks/245037420704169985/ig5AO-wdVWpCBtUUMxmgsWryqgsW3DChbKYOINftJ4DCrUbnkedoYZD0VOH1QLr-S3sV").parse().unwrap();
            let (id, token) = parse_webhook(&url).unwrap();
            assert_eq!(id, 245037420704169985);
            assert_eq!(
                token,
                "ig5AO-wdVWpCBtUUMxmgsWryqgsW3DChbKYOINftJ4DCrUbnkedoYZD0VOH1QLr-S3sV"
            );
        }
    }
}