Skip to main content

djs_model/
user.rs

1//! [Users](https://docs.discord.com/developers/resources/user).
2
3use std::collections::BTreeMap;
4
5use compact_str::CompactString;
6use serde::{Deserialize, Serialize};
7
8use crate::{
9    guild::PartialIntegration,
10    id::{GuildId, SkuId, UserId},
11    macros::{int_enum, int_flags, str_enum},
12    util::{ImageHash, Locale},
13};
14
15/// A Discord user — a person or a bot account.
16///
17/// Users are global: they are not tied to a guild. Guild-specific data (nickname, roles, …)
18/// lives on [guild members](crate::guild). This type holds the fields Discord sends for any
19/// user; the logged-in user's own account is a [`CurrentUser`] (D-052).
20///
21/// Several fields are only present in some payloads: `banner` and `accent_color` only when a
22/// user is fetched directly (`GET /users/{user.id}`), and message authors of webhooks carry
23/// only the basic fields.
24///
25/// See the [user object](https://docs.discord.com/developers/resources/user#user-object).
26///
27/// discord.js counterpart: `User`.
28///
29/// # Examples
30///
31/// ```
32/// use djs_model::user::User;
33///
34/// let user: User = serde_json::from_str(
35///     r#"{"id":"80351110224678912","username":"nelly","discriminator":"0",
36///         "global_name":"Nelly","avatar":null,"public_flags":64}"#,
37/// )?;
38/// assert_eq!(user.display_name(), "Nelly");
39/// assert_eq!(user.tag(), "nelly");
40/// # Ok::<(), serde_json::Error>(())
41/// ```
42#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
43#[non_exhaustive]
44pub struct User {
45    /// The user's ID.
46    pub id: UserId,
47    /// The user's username. Not unique across the platform for bots; unique for migrated users.
48    pub username: CompactString,
49    /// The legacy four-digit Discord tag, or `0` for users migrated to unique usernames.
50    ///
51    /// Discord sends this as a string (`"0"`, `"0420"`); it is stored as an integer.
52    #[serde(with = "discriminator")]
53    pub discriminator: u16,
54    /// The user's display name, if set. For bots this is the application name.
55    pub global_name: Option<CompactString>,
56    /// The user's [avatar hash](https://docs.discord.com/developers/reference#image-formatting).
57    pub avatar: Option<ImageHash>,
58    /// Whether the user belongs to an `OAuth2` application (is a bot).
59    #[serde(default, skip_serializing_if = "core::ops::Not::not")]
60    pub bot: bool,
61    /// Whether the user is an official Discord system user (part of the urgent message system).
62    #[serde(default, skip_serializing_if = "core::ops::Not::not")]
63    pub system: bool,
64    /// The user's [banner hash](https://docs.discord.com/developers/reference#image-formatting).
65    /// Only present when the user is fetched directly.
66    #[serde(default, skip_serializing_if = "Option::is_none")]
67    pub banner: Option<ImageHash>,
68    /// The banner color as an RGB integer (`0xRRGGBB`), used when there is no banner image.
69    /// Only present when the user is fetched directly.
70    #[serde(default, skip_serializing_if = "Option::is_none")]
71    pub accent_color: Option<u32>,
72    /// The user's public [flags](UserFlags) (badges).
73    #[serde(default, skip_serializing_if = "Option::is_none")]
74    pub public_flags: Option<UserFlags>,
75    /// The user's avatar decoration.
76    #[serde(default, skip_serializing_if = "Option::is_none")]
77    pub avatar_decoration_data: Option<Box<AvatarDecorationData>>,
78    /// The user's collectibles (nameplate, …).
79    #[serde(default, skip_serializing_if = "Option::is_none")]
80    pub collectibles: Option<Box<Collectibles>>,
81    /// The guild whose server tag the user displays.
82    #[serde(default, skip_serializing_if = "Option::is_none")]
83    pub primary_guild: Option<Box<PrimaryGuild>>,
84}
85
86impl User {
87    /// Returns the name to display for this user: the global display name if set, otherwise
88    /// the username.
89    ///
90    /// discord.js counterpart: `User#displayName`.
91    #[must_use]
92    pub fn display_name(&self) -> &str {
93        display_name(&self.username, self.global_name.as_deref())
94    }
95
96    /// Returns the user's tag: `username#1234` for legacy users, or just `username` for users
97    /// migrated to unique usernames (discriminator `0`).
98    ///
99    /// discord.js counterpart: `User#tag`.
100    ///
101    /// # Examples
102    ///
103    /// ```
104    /// use djs_model::user::User;
105    ///
106    /// let legacy: User = serde_json::from_str(
107    ///     r#"{"id":"1","username":"nelly","discriminator":"0042","global_name":null,"avatar":null}"#,
108    /// )?;
109    /// assert_eq!(legacy.tag(), "nelly#0042");
110    /// # Ok::<(), serde_json::Error>(())
111    /// ```
112    #[must_use]
113    pub fn tag(&self) -> CompactString {
114        tag(&self.username, self.discriminator)
115    }
116}
117
118/// The user account the client is logged in as, with the fields Discord only sends for it
119/// (D-052).
120///
121/// Received in [`Ready`](crate::gateway::payload::Ready) and from `GET /users/@me`. With an
122/// `OAuth2` bearer token, `email` and `verified` require the `email` scope. Bots receive these
123/// fields too (`email` is then `None`).
124///
125/// See the [user object](https://docs.discord.com/developers/resources/user#user-object).
126///
127/// discord.js counterpart: `ClientUser`.
128#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
129#[non_exhaustive]
130pub struct CurrentUser {
131    /// The user's ID.
132    pub id: UserId,
133    /// The user's username.
134    pub username: CompactString,
135    /// The legacy four-digit Discord tag, or `0` for migrated users. See
136    /// [`User::discriminator`].
137    #[serde(with = "discriminator")]
138    pub discriminator: u16,
139    /// The user's display name, if set.
140    pub global_name: Option<CompactString>,
141    /// The user's [avatar hash](https://docs.discord.com/developers/reference#image-formatting).
142    pub avatar: Option<ImageHash>,
143    /// Whether the user is a bot.
144    #[serde(default, skip_serializing_if = "core::ops::Not::not")]
145    pub bot: bool,
146    /// Whether the user is an official Discord system user.
147    #[serde(default, skip_serializing_if = "core::ops::Not::not")]
148    pub system: bool,
149    /// Whether the account has two-factor authentication enabled.
150    #[serde(default, skip_serializing_if = "core::ops::Not::not")]
151    pub mfa_enabled: bool,
152    /// The user's [banner hash](https://docs.discord.com/developers/reference#image-formatting).
153    #[serde(default, skip_serializing_if = "Option::is_none")]
154    pub banner: Option<ImageHash>,
155    /// The banner color as an RGB integer (`0xRRGGBB`).
156    #[serde(default, skip_serializing_if = "Option::is_none")]
157    pub accent_color: Option<u32>,
158    /// The language the user chose in the client.
159    #[serde(default, skip_serializing_if = "Option::is_none")]
160    pub locale: Option<Locale>,
161    /// Whether the account's email address is verified.
162    #[serde(default, skip_serializing_if = "core::ops::Not::not")]
163    pub verified: bool,
164    /// The account's email address (`OAuth2` `email` scope; always `None` for bots).
165    #[serde(default, skip_serializing_if = "Option::is_none")]
166    pub email: Option<CompactString>,
167    /// All [flags](UserFlags) on the account, including non-public ones.
168    #[serde(default, skip_serializing_if = "Option::is_none")]
169    pub flags: Option<UserFlags>,
170    /// The account's Nitro subscription.
171    #[serde(default, skip_serializing_if = "Option::is_none")]
172    pub premium_type: Option<PremiumType>,
173    /// The public [flags](UserFlags) (badges).
174    #[serde(default, skip_serializing_if = "Option::is_none")]
175    pub public_flags: Option<UserFlags>,
176    /// The user's avatar decoration.
177    #[serde(default, skip_serializing_if = "Option::is_none")]
178    pub avatar_decoration_data: Option<Box<AvatarDecorationData>>,
179    /// The user's collectibles.
180    #[serde(default, skip_serializing_if = "Option::is_none")]
181    pub collectibles: Option<Box<Collectibles>>,
182    /// The guild whose server tag the user displays.
183    #[serde(default, skip_serializing_if = "Option::is_none")]
184    pub primary_guild: Option<Box<PrimaryGuild>>,
185}
186
187impl CurrentUser {
188    /// Returns the global display name if set, otherwise the username.
189    ///
190    /// discord.js counterpart: `User#displayName`.
191    #[must_use]
192    pub fn display_name(&self) -> &str {
193        display_name(&self.username, self.global_name.as_deref())
194    }
195
196    /// Returns the tag: `username#1234` for legacy users, `username` for migrated users.
197    ///
198    /// discord.js counterpart: `User#tag`.
199    #[must_use]
200    pub fn tag(&self) -> CompactString {
201        tag(&self.username, self.discriminator)
202    }
203}
204
205impl From<CurrentUser> for User {
206    /// Keeps the fields every user has and drops the account-only ones.
207    fn from(user: CurrentUser) -> Self {
208        Self {
209            id: user.id,
210            username: user.username,
211            discriminator: user.discriminator,
212            global_name: user.global_name,
213            avatar: user.avatar,
214            bot: user.bot,
215            system: user.system,
216            banner: user.banner,
217            accent_color: user.accent_color,
218            public_flags: user.public_flags,
219            avatar_decoration_data: user.avatar_decoration_data,
220            collectibles: user.collectibles,
221            primary_guild: user.primary_guild,
222        }
223    }
224}
225
226fn display_name<'a>(username: &'a str, global_name: Option<&'a str>) -> &'a str {
227    global_name.unwrap_or(username)
228}
229
230fn tag(username: &str, discriminator: u16) -> CompactString {
231    if discriminator == 0 {
232        username.into()
233    } else {
234        compact_str::format_compact!("{username}#{discriminator:04}")
235    }
236}
237
238/// An [avatar decoration](https://docs.discord.com/developers/resources/user#avatar-decoration-data-object):
239/// the animated frame shown around a user's avatar.
240///
241/// discord.js counterpart: `AvatarDecorationData`.
242#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
243#[non_exhaustive]
244pub struct AvatarDecorationData {
245    /// The [decoration's image hash](https://docs.discord.com/developers/reference#image-formatting).
246    pub asset: ImageHash,
247    /// The SKU the decoration belongs to.
248    pub sku_id: SkuId,
249}
250
251/// The [collectibles](https://docs.discord.com/developers/resources/user#collectibles) a user
252/// has equipped.
253///
254/// discord.js counterpart: `Collectibles`.
255#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
256#[non_exhaustive]
257pub struct Collectibles {
258    /// The nameplate shown behind the user's name in member lists.
259    #[serde(default, skip_serializing_if = "Option::is_none")]
260    pub nameplate: Option<Nameplate>,
261}
262
263/// A [nameplate](https://docs.discord.com/developers/resources/user#nameplate): the background
264/// shown behind a user's name in member lists.
265///
266/// discord.js counterpart: `APINameplateData` (discord-api-types).
267#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
268#[non_exhaustive]
269pub struct Nameplate {
270    /// The nameplate's SKU.
271    pub sku_id: SkuId,
272    /// The path of the [nameplate asset](https://docs.discord.com/developers/reference#image-formatting).
273    pub asset: CompactString,
274    /// The nameplate's label (currently unused by Discord).
275    pub label: CompactString,
276    /// The background color.
277    pub palette: NameplatePalette,
278}
279
280str_enum! {
281    /// The background color of a [`Nameplate`].
282    ///
283    /// discord.js counterpart: `NameplatePalette` (discord-api-types).
284    pub enum NameplatePalette {
285        /// Crimson.
286        Crimson = "crimson",
287        /// Berry.
288        Berry = "berry",
289        /// Sky.
290        Sky = "sky",
291        /// Teal.
292        Teal = "teal",
293        /// Forest.
294        Forest = "forest",
295        /// Bubble gum.
296        BubbleGum = "bubble_gum",
297        /// Violet.
298        Violet = "violet",
299        /// Cobalt (seen in the docs' example user; not in the documented list).
300        Cobalt = "cobalt",
301        /// Clover.
302        ///
303        /// **Undocumented:** known from discord-api-types, not in the official docs; may
304        /// change without notice.
305        Clover = "clover",
306        /// Lemon.
307        ///
308        /// **Undocumented:** known from discord-api-types, not in the official docs; may
309        /// change without notice.
310        Lemon = "lemon",
311        /// White.
312        ///
313        /// **Undocumented:** known from discord-api-types, not in the official docs; may
314        /// change without notice.
315        White = "white",
316    }
317}
318
319/// The [primary guild](https://docs.discord.com/developers/resources/user#user-object-user-primary-guild)
320/// of a user: the guild whose server tag is shown next to their name.
321///
322/// discord.js counterpart: `APIUserPrimaryGuild` (discord-api-types).
323#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
324#[non_exhaustive]
325pub struct PrimaryGuild {
326    /// The guild's ID.
327    pub identity_guild_id: Option<GuildId>,
328    /// Whether the user displays the server tag. `None` when Discord cleared the identity (for
329    /// example because the guild no longer supports tags).
330    pub identity_enabled: Option<bool>,
331    /// The server tag (up to 4 characters).
332    pub tag: Option<CompactString>,
333    /// The [server tag badge hash](https://docs.discord.com/developers/reference#image-formatting).
334    pub badge: Option<ImageHash>,
335}
336
337int_enum! {
338    /// The [Nitro subscription](https://docs.discord.com/developers/resources/user#user-object-premium-types)
339    /// of a user.
340    ///
341    /// discord.js counterpart: `UserPremiumType`.
342    pub enum PremiumType: u8 {
343        /// No Nitro.
344        None = 0,
345        /// Nitro Classic.
346        NitroClassic = 1,
347        /// Nitro.
348        Nitro = 2,
349        /// Nitro Basic.
350        NitroBasic = 3,
351    }
352}
353
354/// Like [`discriminator`] for `Option<u16>` (partial users: absent / `null` = `None`).
355pub(crate) mod option_discriminator {
356    use serde::{Deserialize, Deserializer, Serializer};
357
358    #[derive(Deserialize)]
359    struct Discriminator(#[serde(with = "super::discriminator")] u16);
360
361    #[expect(
362        clippy::ref_option,
363        clippy::trivially_copy_pass_by_ref,
364        reason = "signature required by serde(with)"
365    )]
366    pub(crate) fn serialize<S: Serializer>(
367        value: &Option<u16>,
368        serializer: S,
369    ) -> Result<S::Ok, S::Error> {
370        match value {
371            Some(value) => super::discriminator::serialize(value, serializer),
372            None => serializer.serialize_none(),
373        }
374    }
375
376    pub(crate) fn deserialize<'de, D: Deserializer<'de>>(
377        deserializer: D,
378    ) -> Result<Option<u16>, D::Error> {
379        Option::<Discriminator>::deserialize(deserializer).map(|value| value.map(|value| value.0))
380    }
381}
382
383/// (De)serializes a discriminator: a string of digits on the wire, `u16` in memory.
384pub(crate) mod discriminator {
385    use core::fmt;
386
387    use serde::{
388        Deserializer, Serializer,
389        de::{Error, Unexpected, Visitor},
390    };
391
392    #[expect(
393        clippy::trivially_copy_pass_by_ref,
394        reason = "signature required by serde(with)"
395    )]
396    pub(crate) fn serialize<S: Serializer>(value: &u16, serializer: S) -> Result<S::Ok, S::Error> {
397        if *value == 0 {
398            serializer.serialize_str("0")
399        } else {
400            serializer.collect_str(&format_args!("{value:04}"))
401        }
402    }
403
404    pub(crate) fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<u16, D::Error> {
405        struct DiscriminatorVisitor;
406
407        impl Visitor<'_> for DiscriminatorVisitor {
408            type Value = u16;
409
410            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
411                f.write_str("a discriminator of up to four digits")
412            }
413
414            fn visit_str<E: Error>(self, value: &str) -> Result<u16, E> {
415                if value.is_empty() || value.len() > 4 || !value.bytes().all(|b| b.is_ascii_digit())
416                {
417                    return Err(E::invalid_value(Unexpected::Str(value), &self));
418                }
419                value
420                    .parse()
421                    .map_err(|_| E::invalid_value(Unexpected::Str(value), &self))
422            }
423
424            fn visit_u64<E: Error>(self, value: u64) -> Result<u16, E> {
425                u16::try_from(value)
426                    .ok()
427                    .filter(|value| *value <= 9999)
428                    .ok_or_else(|| E::invalid_value(Unexpected::Unsigned(value), &self))
429            }
430        }
431
432        deserializer.deserialize_any(DiscriminatorVisitor)
433    }
434}
435
436int_flags! {
437    /// [Flags on a user](https://docs.discord.com/developers/resources/user#user-object-user-flags),
438    /// most of them shown as profile badges.
439    ///
440    /// Users carry these in `public_flags` (visible to everyone) and, for the current user
441    /// with the right OAuth2 scope, in `flags`.
442    ///
443    /// discord.js counterpart: `UserFlags` / `UserFlagsBitField`.
444    ///
445    /// # Examples
446    ///
447    /// ```
448    /// use djs_model::user::UserFlags;
449    ///
450    /// let flags: UserFlags = serde_json::from_str("65536").unwrap();
451    /// assert_eq!(flags, UserFlags::VERIFIED_BOT);
452    /// ```
453    pub struct UserFlags: u64 {
454        /// Discord employee.
455        const STAFF = 1 << 0;
456        /// Owner of a partnered server.
457        const PARTNER = 1 << 1;
458        /// Member of HypeSquad Events.
459        const HYPESQUAD = 1 << 2;
460        /// Bug Hunter, level 1.
461        const BUG_HUNTER_LEVEL_1 = 1 << 3;
462        /// The account has SMS two-factor authentication enabled.
463        ///
464        /// **Undocumented:** known from discord-api-types, not in the official docs; may
465        /// change without notice.
466        const MFA_SMS = 1 << 4;
467        /// The user dismissed a Nitro promotion.
468        ///
469        /// **Undocumented:** known from discord-api-types, not in the official docs; may
470        /// change without notice.
471        const PREMIUM_PROMO_DISMISSED = 1 << 5;
472        /// Member of HypeSquad house Bravery.
473        const HYPESQUAD_ONLINE_HOUSE_1 = 1 << 6;
474        /// Member of HypeSquad house Brilliance.
475        const HYPESQUAD_ONLINE_HOUSE_2 = 1 << 7;
476        /// Member of HypeSquad house Balance.
477        const HYPESQUAD_ONLINE_HOUSE_3 = 1 << 8;
478        /// Early Nitro supporter.
479        const PREMIUM_EARLY_SUPPORTER = 1 << 9;
480        /// The "user" is a [team](https://docs.discord.com/developers/topics/teams) account.
481        const TEAM_PSEUDO_USER = 1 << 10;
482        /// The user has unread urgent messages from Discord.
483        ///
484        /// **Undocumented:** known from discord-api-types, not in the official docs; may
485        /// change without notice.
486        const HAS_UNREAD_URGENT_MESSAGES = 1 << 13;
487        /// Bug Hunter, level 2.
488        const BUG_HUNTER_LEVEL_2 = 1 << 14;
489        /// A verified bot.
490        const VERIFIED_BOT = 1 << 16;
491        /// Early verified bot developer.
492        const VERIFIED_DEVELOPER = 1 << 17;
493        /// Alumnus of the Discord Moderator Programs.
494        const CERTIFIED_MODERATOR = 1 << 18;
495        /// A bot that only uses HTTP interactions; it is shown in the online member list.
496        const BOT_HTTP_INTERACTIONS = 1 << 19;
497        /// The account is flagged as a spammer.
498        ///
499        /// **Undocumented:** known from discord-api-types, not in the official docs; may
500        /// change without notice.
501        const SPAMMER = 1 << 20;
502        /// Nitro features are disabled for the account.
503        ///
504        /// **Undocumented:** known from discord-api-types, not in the official docs; may
505        /// change without notice.
506        const DISABLE_PREMIUM = 1 << 21;
507        /// Holder of the Active Developer badge.
508        ///
509        /// Discord no longer grants this flag.
510        ///
511        /// **Undocumented:** known from discord-api-types, not in the official docs; may
512        /// change without notice.
513        const ACTIVE_DEVELOPER = 1 << 22;
514        /// The account is quarantined.
515        ///
516        /// **Undocumented:** known from discord-api-types, not in the official docs; may
517        /// change without notice.
518        const QUARANTINED = 1 << 44;
519        /// The user is a collaborator on an application team.
520        ///
521        /// **Undocumented:** known from discord-api-types, not in the official docs; may
522        /// change without notice.
523        const COLLABORATOR = 1 << 50;
524        /// The user is a restricted collaborator on an application team.
525        ///
526        /// **Undocumented:** known from discord-api-types, not in the official docs; may
527        /// change without notice.
528        const RESTRICTED_COLLABORATOR = 1 << 51;
529    }
530}
531
532/// A third-party account [connected](https://docs.discord.com/developers/resources/user#connection-object)
533/// to the current user (`GET /users/@me/connections`, `OAuth2` scope `connections`).
534///
535/// discord.js counterpart: none (discord-api-types `APIConnection`).
536#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
537#[non_exhaustive]
538pub struct Connection {
539    /// The account's ID on the service (not a snowflake).
540    pub id: CompactString,
541    /// The account's username on the service.
542    pub name: CompactString,
543    /// The service.
544    #[serde(rename = "type")]
545    pub kind: ConnectionService,
546    /// Whether the connection is revoked.
547    #[serde(default, skip_serializing_if = "core::ops::Not::not")]
548    pub revoked: bool,
549    /// The guild integrations that use the connection (partial objects).
550    #[serde(default, skip_serializing_if = "Vec::is_empty")]
551    pub integrations: Vec<PartialIntegration>,
552    /// Whether the connection is verified.
553    pub verified: bool,
554    /// Whether friend sync is enabled.
555    pub friend_sync: bool,
556    /// Whether activities of the service are shown in presence updates.
557    pub show_activity: bool,
558    /// Whether Discord holds an `OAuth2` token for the service account.
559    pub two_way_link: bool,
560    /// Who can see the connection.
561    pub visibility: ConnectionVisibility,
562}
563
564str_enum! {
565    /// A [connection service](https://docs.discord.com/developers/resources/user#connection-object-services).
566    ///
567    /// discord-api-types counterpart: `ConnectionService`.
568    ///
569    /// discord.js counterpart: `ConnectionService` (discord-api-types).
570    #[doc(alias = "Services")]
571    pub enum ConnectionService {
572        /// Amazon Music.
573        AmazonMusic = "amazon-music",
574        /// Battle.net. **Deprecated:** Battle.net connections were removed on 2026-09-22.
575        ///
576        /// **Undocumented:** known from discord-api-types, no longer in the official docs.
577        BattleNet = "battlenet",
578        /// Bluesky.
579        Bluesky = "bluesky",
580        /// Bungie.net.
581        BungieNet = "bungie",
582        /// Crunchyroll.
583        Crunchyroll = "crunchyroll",
584        /// A domain name.
585        Domain = "domain",
586        /// eBay.
587        Ebay = "ebay",
588        /// Epic Games.
589        EpicGames = "epicgames",
590        /// Facebook.
591        Facebook = "facebook",
592        /// GitHub.
593        GitHub = "github",
594        /// Instagram. Can no longer be added by users.
595        Instagram = "instagram",
596        /// League of Legends. **Deprecated:** no longer returned by Discord.
597        ///
598        /// **Undocumented:** known from discord-api-types, no longer in the official docs.
599        LeagueOfLegends = "leagueoflegends",
600        /// Mastodon.
601        Mastodon = "mastodon",
602        /// PayPal.
603        PayPal = "paypal",
604        /// PlayStation Network.
605        PlayStationNetwork = "playstation",
606        /// Reddit.
607        Reddit = "reddit",
608        /// Riot Games. **Deprecated:** no longer returned by Discord.
609        ///
610        /// **Undocumented:** known from discord-api-types, no longer in the official docs.
611        RiotGames = "riotgames",
612        /// Roblox.
613        Roblox = "roblox",
614        /// Spotify.
615        Spotify = "spotify",
616        /// Skype. Can no longer be added by users.
617        Skype = "skype",
618        /// Steam.
619        Steam = "steam",
620        /// TikTok.
621        TikTok = "tiktok",
622        /// Twitch.
623        Twitch = "twitch",
624        /// X (formerly Twitter).
625        #[doc(alias = "Twitter")]
626        X = "twitter",
627        /// Xbox.
628        Xbox = "xbox",
629        /// YouTube.
630        YouTube = "youtube",
631    }
632}
633
634int_enum! {
635    /// [Who can see](https://docs.discord.com/developers/resources/user#connection-object-visibility-types)
636    /// a [`Connection`].
637    ///
638    /// discord-api-types counterpart: `ConnectionVisibility`.
639    ///
640    /// discord.js counterpart: `ConnectionVisibility` (discord-api-types).
641    pub enum ConnectionVisibility: u8 {
642        /// Only the user.
643        None = 0,
644        /// Everyone.
645        Everyone = 1,
646    }
647}
648
649/// The [role connection](https://docs.discord.com/developers/resources/user#application-role-connection-object)
650/// an app stored for a user (linked roles).
651///
652/// discord.js counterpart: none (discord-api-types `APIApplicationRoleConnection`).
653#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
654#[non_exhaustive]
655pub struct ApplicationRoleConnection {
656    /// The vanity name of the connected platform (max 50 characters).
657    #[serde(default, skip_serializing_if = "Option::is_none")]
658    pub platform_name: Option<CompactString>,
659    /// The user's name on the connected platform (max 100 characters).
660    #[serde(default, skip_serializing_if = "Option::is_none")]
661    pub platform_username: Option<CompactString>,
662    /// The user's values, keyed by
663    /// [`ApplicationRoleConnectionMetadata::key`](crate::application_role_connection_metadata::ApplicationRoleConnectionMetadata::key)
664    /// (each value stringified, max 100 characters; D-058).
665    #[serde(
666        default,
667        skip_serializing_if = "BTreeMap::is_empty",
668        deserialize_with = "crate::serde_util::null_as_default"
669    )]
670    pub metadata: BTreeMap<CompactString, CompactString>,
671}
672
673#[cfg(test)]
674mod tests {
675    use super::*;
676
677    /// The example user object from the Discord API documentation.
678    const DOCS_EXAMPLE: &str = r#"{
679        "id": "80351110224678912",
680        "username": "Nelly",
681        "global_name": null,
682        "discriminator": "1337",
683        "avatar": "8342729096ea3675442027381ff50dfe",
684        "verified": true,
685        "email": "nelly@discord.com",
686        "flags": 64,
687        "banner": "06c16474723fe537c283b8efa61a30c8",
688        "accent_color": 16711680,
689        "premium_type": 0,
690        "public_flags": 64,
691        "avatar_decoration_data": {
692            "sku_id": "1144058844004233369",
693            "asset": "a_fed43ab12698df65902ba06727e20c0e"
694        },
695        "collectibles": {
696            "nameplate": {
697                "sku_id": "2247558840304243311",
698                "asset": "nameplates/nameplates/twilight/",
699                "label": "",
700                "palette": "cobalt"
701            }
702        },
703        "primary_guild": {
704            "identity_guild_id": "1234647491267808778",
705            "identity_enabled": true,
706            "tag": "DISC",
707            "badge": "7d1734ae5a615e82bc7a4033b98fade8"
708        }
709    }"#;
710
711    #[test]
712    fn deserialize_documented_example_as_user() {
713        let user: User = serde_json::from_str(DOCS_EXAMPLE).unwrap();
714        assert_eq!(user.id.get(), 80_351_110_224_678_912);
715        assert_eq!(user.username, "Nelly");
716        assert_eq!(user.discriminator, 1337);
717        assert_eq!(user.global_name, None);
718        assert_eq!(
719            user.avatar.unwrap().to_string(),
720            "8342729096ea3675442027381ff50dfe"
721        );
722        assert!(!user.bot);
723        assert_eq!(user.accent_color, Some(0xFF_0000));
724        assert_eq!(user.public_flags, Some(UserFlags::HYPESQUAD_ONLINE_HOUSE_1));
725        let decoration = user.avatar_decoration_data.as_ref().unwrap();
726        assert_eq!(decoration.sku_id.get(), 1_144_058_844_004_233_369);
727        assert!(decoration.asset.is_animated());
728        let nameplate = user
729            .collectibles
730            .as_ref()
731            .unwrap()
732            .nameplate
733            .as_ref()
734            .unwrap();
735        assert_eq!(nameplate.palette, NameplatePalette::Cobalt);
736        assert_eq!(nameplate.asset, "nameplates/nameplates/twilight/");
737        let guild = user.primary_guild.as_ref().unwrap();
738        assert_eq!(guild.tag.as_deref(), Some("DISC"));
739        assert_eq!(guild.identity_enabled, Some(true));
740        assert_eq!(user.tag(), "Nelly#1337");
741        assert_eq!(user.display_name(), "Nelly");
742    }
743
744    #[test]
745    fn deserialize_documented_example_as_current_user() {
746        let user: CurrentUser = serde_json::from_str(DOCS_EXAMPLE).unwrap();
747        assert!(user.verified);
748        assert_eq!(user.email.as_deref(), Some("nelly@discord.com"));
749        assert_eq!(user.flags, Some(UserFlags::HYPESQUAD_ONLINE_HOUSE_1));
750        assert_eq!(user.premium_type, Some(PremiumType::None));
751        assert!(!user.mfa_enabled);
752        assert_eq!(user.locale, None);
753        let plain = User::from(user.clone());
754        assert_eq!(plain, serde_json::from_str::<User>(DOCS_EXAMPLE).unwrap());
755    }
756
757    #[test]
758    fn serialization_keeps_discord_shape() {
759        let json = r#"{"id":"1","username":"bot","discriminator":"0007","global_name":"Bot","avatar":null,"bot":true}"#;
760        let user: User = serde_json::from_str(json).unwrap();
761        // `?type` fields are written as null, absent `field?` fields are skipped (D-049).
762        assert_eq!(serde_json::to_string(&user).unwrap(), json);
763    }
764
765    #[test]
766    fn missing_nullable_fields_are_accepted() {
767        // Some partial user payloads omit `global_name`/`avatar` entirely.
768        let user: User =
769            serde_json::from_str(r#"{"id":"1","username":"a","discriminator":"0"}"#).unwrap();
770        assert_eq!(user.global_name, None);
771        assert_eq!(user.avatar, None);
772    }
773
774    #[test]
775    fn migrated_user_discriminator() {
776        let json =
777            r#"{"id":"1","username":"a","discriminator":"0","global_name":null,"avatar":null}"#;
778        let user: User = serde_json::from_str(json).unwrap();
779        assert_eq!(user.discriminator, 0);
780        assert!(
781            serde_json::to_string(&user)
782                .unwrap()
783                .contains(r#""discriminator":"0""#)
784        );
785    }
786
787    #[test]
788    fn rejects_bad_discriminator() {
789        for bad in [r#""12345""#, r#""""#, r#""12a""#] {
790            let json =
791                format!(r#"{{"id":"1","username":"a","discriminator":{bad},"avatar":null}}"#);
792            assert!(
793                serde_json::from_str::<User>(&json).is_err(),
794                "{bad} should be rejected"
795            );
796        }
797    }
798
799    #[test]
800    fn hot_type_sizes() {
801        // Guard against accidental growth of the message author type.
802        assert!(
803            size_of::<User>() <= 256,
804            "User is {} bytes",
805            size_of::<User>()
806        );
807    }
808}