Skip to main content

djs_model/
guild.rs

1//! [Guilds](https://docs.discord.com/developers/resources/guild) (servers).
2
3use compact_str::CompactString;
4use serde::{Deserialize, Serialize};
5
6use crate::{
7    emoji::{Emoji, PartialEmoji},
8    gateway::Status,
9    id::{
10        ApplicationId, ChannelId, EmojiId, GenericId, GuildId, IntegrationId, RoleId, SkuId, UserId,
11    },
12    macros::{int_enum, int_flags, str_enum},
13    oauth2::Scope,
14    permissions::Permissions,
15    sticker::Sticker,
16    user::{AvatarDecorationData, Collectibles, User},
17    util::{ImageHash, Locale, Timestamp},
18};
19
20/// A guild that is not (or not yet) available to the client.
21///
22/// The [`Ready`](crate::gateway::payload::Ready) event lists every guild the bot is in as
23/// unavailable; full guild data then arrives in `GUILD_CREATE` events. A guild also becomes
24/// unavailable during a Discord outage.
25///
26/// See the [unavailable guild object](https://docs.discord.com/developers/resources/guild#unavailable-guild-object).
27///
28/// discord.js counterpart: guilds with `available === false`.
29#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
30#[non_exhaustive]
31pub struct UnavailableGuild {
32    /// The guild's ID.
33    pub id: GuildId,
34    /// Whether the guild is unavailable due to an outage.
35    ///
36    /// In `GUILD_DELETE` events this is `false` (absent) when the bot was removed from the guild
37    /// rather than the guild becoming unavailable.
38    #[serde(default)]
39    pub unavailable: bool,
40}
41
42impl UnavailableGuild {
43    /// Creates an unavailable guild entry.
44    ///
45    /// discord.js counterpart: `APIUnavailableGuild` (discord-api-types).
46    #[must_use]
47    pub const fn new(id: GuildId, unavailable: bool) -> Self {
48        Self { id, unavailable }
49    }
50}
51
52/// A [guild member](https://docs.discord.com/developers/resources/guild#guild-member-object): a
53/// user's membership in one guild, with guild-specific data such as nickname and roles.
54///
55/// This is the complete shape (it includes the [`user`](Self::user)), as returned by
56/// `GET /guilds/{guild.id}/members/{user.id}` and member gateway events. Messages carry a
57/// [`PartialMember`] instead (D-051).
58///
59/// discord.js counterpart: `GuildMember`.
60///
61/// # Examples
62///
63/// ```
64/// use djs_model::guild::Member;
65///
66/// let member: Member = serde_json::from_str(r#"{
67///     "user": {"id": "80351110224678912", "username": "nelly", "discriminator": "0",
68///              "global_name": "Nelly", "avatar": null},
69///     "nick": "NOT API SUPPORT", "roles": [], "joined_at": "2015-04-26T06:26:56.936000+00:00",
70///     "deaf": false, "mute": false, "flags": 0
71/// }"#)?;
72/// assert_eq!(member.display_name(), "NOT API SUPPORT");
73/// # Ok::<(), serde_json::Error>(())
74/// ```
75#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
76#[non_exhaustive]
77pub struct Member {
78    /// The user this membership belongs to.
79    pub user: User,
80    /// The member's nickname in this guild.
81    #[serde(default, skip_serializing_if = "Option::is_none")]
82    pub nick: Option<CompactString>,
83    /// The member's [guild avatar hash](https://docs.discord.com/developers/reference#image-formatting),
84    /// overriding the user's avatar in this guild.
85    #[serde(default, skip_serializing_if = "Option::is_none")]
86    pub avatar: Option<ImageHash>,
87    /// The member's [guild banner hash](https://docs.discord.com/developers/reference#image-formatting).
88    #[serde(default, skip_serializing_if = "Option::is_none")]
89    pub banner: Option<ImageHash>,
90    /// The IDs of the member's roles (the `@everyone` role is implied and not listed).
91    pub roles: Vec<RoleId>,
92    /// When the user joined the guild. `None` for guest members.
93    pub joined_at: Option<Timestamp>,
94    /// When the user started boosting the guild.
95    #[serde(default, skip_serializing_if = "Option::is_none")]
96    pub premium_since: Option<Timestamp>,
97    /// Whether the member is deafened in voice channels.
98    #[serde(default)]
99    pub deaf: bool,
100    /// Whether the member is muted in voice channels.
101    #[serde(default)]
102    pub mute: bool,
103    /// The member's [flags](MemberFlags).
104    #[serde(default)]
105    pub flags: MemberFlags,
106    /// Whether the member has not yet passed the guild's membership screening. Such members
107    /// cannot use most of the guild until they do.
108    #[serde(default, skip_serializing_if = "core::ops::Not::not")]
109    pub pending: bool,
110    /// When the member's [timeout](https://support.discord.com/hc/en-us/articles/4413305239191)
111    /// ends. A time in the past means the member is no longer timed out.
112    #[serde(default, skip_serializing_if = "Option::is_none")]
113    pub communication_disabled_until: Option<Timestamp>,
114    /// The member's guild-specific avatar decoration.
115    #[serde(default, skip_serializing_if = "Option::is_none")]
116    pub avatar_decoration_data: Option<Box<AvatarDecorationData>>,
117    /// The member's guild-specific collectibles.
118    #[serde(default, skip_serializing_if = "Option::is_none")]
119    pub collectibles: Option<Box<Collectibles>>,
120}
121
122impl Member {
123    /// Returns the name shown for the member in this guild: the nickname, else the user's
124    /// display name, else the username.
125    ///
126    /// discord.js counterpart: `GuildMember#displayName`.
127    #[must_use]
128    pub fn display_name(&self) -> &str {
129        self.nick
130            .as_deref()
131            .unwrap_or_else(|| self.user.display_name())
132    }
133
134    /// Returns whether the member is timed out at `now`.
135    ///
136    /// discord.js counterpart: `GuildMember#isCommunicationDisabled`.
137    #[must_use]
138    pub fn is_timed_out(&self, now: Timestamp) -> bool {
139        self.communication_disabled_until
140            .is_some_and(|until| until > now)
141    }
142}
143
144/// A [guild member](https://docs.discord.com/developers/resources/guild#guild-member-object)
145/// without its [`User`], as attached to messages (`MESSAGE_CREATE`, `MESSAGE_UPDATE`) where the
146/// user is the message's author (D-051).
147///
148/// Combine it with the author through [`PartialMember::into_member`].
149///
150/// discord.js counterpart: the `member` of a `Message` (a `GuildMember`).
151#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
152#[non_exhaustive]
153pub struct PartialMember {
154    /// The member's nickname in this guild.
155    #[serde(default, skip_serializing_if = "Option::is_none")]
156    pub nick: Option<CompactString>,
157    /// The member's [guild avatar hash](https://docs.discord.com/developers/reference#image-formatting),
158    /// overriding the user's avatar in this guild.
159    #[serde(default, skip_serializing_if = "Option::is_none")]
160    pub avatar: Option<ImageHash>,
161    /// The member's [guild banner hash](https://docs.discord.com/developers/reference#image-formatting).
162    #[serde(default, skip_serializing_if = "Option::is_none")]
163    pub banner: Option<ImageHash>,
164    /// The IDs of the member's roles (the `@everyone` role is implied and not listed).
165    pub roles: Vec<RoleId>,
166    /// When the user joined the guild. `None` for guest members.
167    pub joined_at: Option<Timestamp>,
168    /// When the user started boosting the guild.
169    #[serde(default, skip_serializing_if = "Option::is_none")]
170    pub premium_since: Option<Timestamp>,
171    /// Whether the member is deafened in voice channels.
172    #[serde(default)]
173    pub deaf: bool,
174    /// Whether the member is muted in voice channels.
175    #[serde(default)]
176    pub mute: bool,
177    /// The member's [flags](MemberFlags).
178    #[serde(default)]
179    pub flags: MemberFlags,
180    /// Whether the member has not yet passed the guild's membership screening. Such members
181    /// cannot use most of the guild until they do.
182    #[serde(default, skip_serializing_if = "core::ops::Not::not")]
183    pub pending: bool,
184    /// When the member's [timeout](https://support.discord.com/hc/en-us/articles/4413305239191)
185    /// ends. A time in the past means the member is no longer timed out.
186    #[serde(default, skip_serializing_if = "Option::is_none")]
187    pub communication_disabled_until: Option<Timestamp>,
188    /// The member's guild-specific avatar decoration.
189    #[serde(default, skip_serializing_if = "Option::is_none")]
190    pub avatar_decoration_data: Option<Box<AvatarDecorationData>>,
191    /// The member's guild-specific collectibles.
192    #[serde(default, skip_serializing_if = "Option::is_none")]
193    pub collectibles: Option<Box<Collectibles>>,
194}
195
196impl PartialMember {
197    /// Completes this member with its user, typically the author of the message the member
198    /// came with.
199    ///
200    /// discord.js counterpart: none (discord.js builds the `GuildMember` itself).
201    #[must_use]
202    pub fn into_member(self, user: User) -> Member {
203        Member {
204            user,
205            nick: self.nick,
206            avatar: self.avatar,
207            banner: self.banner,
208            roles: self.roles,
209            joined_at: self.joined_at,
210            premium_since: self.premium_since,
211            deaf: self.deaf,
212            mute: self.mute,
213            flags: self.flags,
214            pending: self.pending,
215            communication_disabled_until: self.communication_disabled_until,
216            avatar_decoration_data: self.avatar_decoration_data,
217            collectibles: self.collectibles,
218        }
219    }
220}
221
222/// A [role](https://docs.discord.com/developers/topics/permissions#role-object): a named set of
223/// permissions (and a color, icon and position in the member list) that members can have.
224///
225/// The `@everyone` role has the guild's ID.
226///
227/// discord.js counterpart: `Role`.
228#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
229#[non_exhaustive]
230pub struct Role {
231    /// The role's ID.
232    pub id: RoleId,
233    /// The role's name.
234    pub name: CompactString,
235    /// The role's primary color as an RGB integer. **Deprecated** by Discord in favor of
236    /// [`colors`](Self::colors), but still sent.
237    pub color: u32,
238    /// The role's colors (solid, gradient or holographic).
239    pub colors: RoleColors,
240    /// Whether members with this role are listed separately in the member list.
241    pub hoist: bool,
242    /// The [role icon hash](https://docs.discord.com/developers/reference#image-formatting).
243    #[serde(default, skip_serializing_if = "Option::is_none")]
244    pub icon: Option<ImageHash>,
245    /// The role's Unicode emoji, shown instead of an icon.
246    #[serde(default, skip_serializing_if = "Option::is_none")]
247    pub unicode_emoji: Option<CompactString>,
248    /// The role's position in the role list; roles with equal positions are ordered by ID.
249    pub position: i32,
250    /// The permissions the role grants.
251    pub permissions: Permissions,
252    /// Whether the role is managed by an integration (bot role, booster role, …).
253    pub managed: bool,
254    /// Whether everyone can mention the role.
255    pub mentionable: bool,
256    /// What the role is tied to (a bot, an integration, boosting, a subscription, …).
257    #[serde(default, skip_serializing_if = "Option::is_none")]
258    pub tags: Option<Box<RoleTags>>,
259    /// The role's [flags](RoleFlags).
260    #[serde(default)]
261    pub flags: RoleFlags,
262}
263
264/// The [colors of a role](https://docs.discord.com/developers/topics/permissions#role-object-role-colors-object).
265///
266/// A role without colors has `primary_color == 0` and does not affect the member's color.
267/// Secondary and tertiary colors need the guild feature `ENHANCED_ROLE_COLORS`.
268///
269/// discord.js counterpart: `RoleColors` (`Role#colors`).
270#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
271pub struct RoleColors {
272    /// The primary color as an RGB integer.
273    pub primary_color: u32,
274    /// The secondary color: makes the role a gradient between the colors.
275    pub secondary_color: Option<u32>,
276    /// The tertiary color: makes the gradient holographic.
277    pub tertiary_color: Option<u32>,
278}
279
280impl RoleColors {
281    /// The only colors Discord accepts for a holographic role (when a tertiary color is sent).
282    ///
283    /// discord.js counterpart: `Constants.HolographicStyle`.
284    pub const HOLOGRAPHIC: Self = Self {
285        primary_color: 11_127_295,
286        secondary_color: Some(16_759_788),
287        tertiary_color: Some(16_761_760),
288    };
289
290    /// A solid color.
291    ///
292    /// discord.js counterpart: the `primaryColor` of `RoleColorsResolvable`.
293    #[must_use]
294    pub const fn solid(color: u32) -> Self {
295        Self {
296            primary_color: color,
297            secondary_color: None,
298            tertiary_color: None,
299        }
300    }
301}
302
303/// The [tags of a role](https://docs.discord.com/developers/topics/permissions#role-object-role-tags-structure):
304/// what the role belongs to.
305///
306/// On the wire, the boolean tags are keys whose value is `null` when true and that are absent
307/// when false; here they are plain `bool`s.
308///
309/// discord.js counterpart: `APIRoleTags` (discord-api-types).
310#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
311#[non_exhaustive]
312pub struct RoleTags {
313    /// The bot this role belongs to (the bot's managed role).
314    #[serde(default, skip_serializing_if = "Option::is_none")]
315    pub bot_id: Option<UserId>,
316    /// The integration this role belongs to.
317    #[serde(default, skip_serializing_if = "Option::is_none")]
318    pub integration_id: Option<IntegrationId>,
319    /// Whether this is the guild's Booster role.
320    #[serde(
321        default,
322        with = "null_flag",
323        skip_serializing_if = "core::ops::Not::not"
324    )]
325    pub premium_subscriber: bool,
326    /// The SKU and listing of the role's subscription.
327    #[serde(default, skip_serializing_if = "Option::is_none")]
328    pub subscription_listing_id: Option<SkuId>,
329    /// Whether the role can be purchased.
330    #[serde(
331        default,
332        with = "null_flag",
333        skip_serializing_if = "core::ops::Not::not"
334    )]
335    pub available_for_purchase: bool,
336    /// Whether the role is a guild's linked role.
337    #[serde(
338        default,
339        with = "null_flag",
340        skip_serializing_if = "core::ops::Not::not"
341    )]
342    pub guild_connections: bool,
343}
344
345/// (De)serializes a "null means true" flag: the key is present with a `null` value when the
346/// flag is set and absent otherwise (absence is handled by `#[serde(default)]` and
347/// `skip_serializing_if`).
348mod null_flag {
349    use serde::{Deserialize, Deserializer, Serializer};
350
351    #[expect(
352        clippy::trivially_copy_pass_by_ref,
353        reason = "signature required by serde(with)"
354    )]
355    pub(super) fn serialize<S: Serializer>(_: &bool, serializer: S) -> Result<S::Ok, S::Error> {
356        serializer.serialize_unit()
357    }
358
359    pub(super) fn deserialize<'de, D: Deserializer<'de>>(
360        deserializer: D,
361    ) -> Result<bool, D::Error> {
362        Option::<()>::deserialize(deserializer).map(|_| true)
363    }
364}
365
366/// A [guild](https://docs.discord.com/developers/resources/guild#guild-object) (called a
367/// "server" in the Discord client).
368///
369/// This is the shape returned by `GET /guilds/{guild.id}` and sent in `GUILD_UPDATE`. The
370/// `GUILD_CREATE` event carries additional data (members, channels, …) in its own payload type.
371///
372/// discord.js counterpart: `Guild`.
373#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
374#[non_exhaustive]
375pub struct Guild {
376    /// The guild's ID.
377    pub id: GuildId,
378    /// The guild's name (2-100 characters).
379    pub name: CompactString,
380    /// The [icon hash](https://docs.discord.com/developers/reference#image-formatting).
381    pub icon: Option<ImageHash>,
382    /// The icon hash as sent in guild template objects.
383    #[serde(default, skip_serializing_if = "Option::is_none")]
384    pub icon_hash: Option<ImageHash>,
385    /// The [invite splash hash](https://docs.discord.com/developers/reference#image-formatting).
386    pub splash: Option<ImageHash>,
387    /// The [discovery splash hash](https://docs.discord.com/developers/reference#image-formatting);
388    /// only for guilds with the [`DISCOVERABLE`](Feature::Discoverable) feature.
389    pub discovery_splash: Option<ImageHash>,
390    /// Whether the current user owns the guild (only in `GET /users/@me/guilds`).
391    #[serde(default, skip_serializing_if = "core::ops::Not::not")]
392    pub owner: bool,
393    /// The owner's user ID.
394    pub owner_id: UserId,
395    /// The current user's permissions in the guild, without channel overwrites (only in
396    /// `GET /users/@me/guilds`).
397    #[serde(default, skip_serializing_if = "Option::is_none")]
398    pub permissions: Option<Permissions>,
399    /// The guild's voice region. **Deprecated** by Discord: regions are set per voice channel.
400    #[serde(default, skip_serializing_if = "Option::is_none")]
401    pub region: Option<CompactString>,
402    /// The AFK voice channel.
403    pub afk_channel_id: Option<ChannelId>,
404    /// How long a member must be idle before being moved to the AFK channel, in seconds.
405    pub afk_timeout: u32,
406    /// Whether the server widget is enabled.
407    #[serde(default, skip_serializing_if = "core::ops::Not::not")]
408    pub widget_enabled: bool,
409    /// The channel the widget's invite points to; `None` when the widget has no invite.
410    #[serde(default, skip_serializing_if = "Option::is_none")]
411    pub widget_channel_id: Option<ChannelId>,
412    /// What members must have before they can talk in the guild.
413    pub verification_level: VerificationLevel,
414    /// The default notification setting for members.
415    pub default_message_notifications: DefaultMessageNotificationLevel,
416    /// Whose media Discord scans for explicit content.
417    pub explicit_content_filter: ExplicitContentFilterLevel,
418    /// The guild's roles.
419    pub roles: Vec<Role>,
420    /// The guild's custom emojis.
421    pub emojis: Vec<Emoji>,
422    /// The guild's enabled [features](Feature).
423    pub features: Vec<Feature>,
424    /// Whether moderators need two-factor authentication.
425    pub mfa_level: MfaLevel,
426    /// The application that created the guild, for bot-created guilds.
427    pub application_id: Option<ApplicationId>,
428    /// The channel where welcome messages and boost notices are posted.
429    pub system_channel_id: Option<ChannelId>,
430    /// Which notices are *not* posted in the system channel.
431    pub system_channel_flags: SystemChannelFlags,
432    /// The rules channel of a Community guild.
433    pub rules_channel_id: Option<ChannelId>,
434    /// The maximum number of presences (`None` except for the largest guilds).
435    #[serde(default, skip_serializing_if = "Option::is_none")]
436    pub max_presences: Option<u32>,
437    /// The maximum number of members.
438    #[serde(default, skip_serializing_if = "Option::is_none")]
439    pub max_members: Option<u32>,
440    /// The vanity invite code (`discord.gg/<code>`).
441    pub vanity_url_code: Option<CompactString>,
442    /// The guild's description.
443    pub description: Option<CompactString>,
444    /// The [banner hash](https://docs.discord.com/developers/reference#image-formatting).
445    pub banner: Option<ImageHash>,
446    /// The Server Boost level.
447    pub premium_tier: PremiumTier,
448    /// The number of boosts the guild currently has.
449    #[serde(default, skip_serializing_if = "Option::is_none")]
450    pub premium_subscription_count: Option<u32>,
451    /// The preferred locale of a Community guild (used in discovery and Discord notices).
452    pub preferred_locale: Locale,
453    /// The channel where moderators of a Community guild receive notices from Discord.
454    pub public_updates_channel_id: Option<ChannelId>,
455    /// The maximum number of users in a video channel.
456    #[serde(default, skip_serializing_if = "Option::is_none")]
457    pub max_video_channel_users: Option<u32>,
458    /// The maximum number of users in a stage video channel.
459    #[serde(default, skip_serializing_if = "Option::is_none")]
460    pub max_stage_video_channel_users: Option<u32>,
461    /// The approximate number of members (`GET /guilds/{guild.id}?with_counts=true`).
462    #[serde(default, skip_serializing_if = "Option::is_none")]
463    pub approximate_member_count: Option<u32>,
464    /// The approximate number of online members (`with_counts=true`).
465    #[serde(default, skip_serializing_if = "Option::is_none")]
466    pub approximate_presence_count: Option<u32>,
467    /// The welcome screen of a Community guild (sent with invites).
468    #[serde(default, skip_serializing_if = "Option::is_none")]
469    pub welcome_screen: Option<Box<WelcomeScreen>>,
470    /// The guild's age-restriction (NSFW) level. Defaults to
471    /// [`Default`](AgeRestrictionLevel::Default) when absent (older payloads).
472    #[serde(default)]
473    pub nsfw_level: AgeRestrictionLevel,
474    /// The guild's custom stickers.
475    #[serde(default, skip_serializing_if = "Vec::is_empty")]
476    pub stickers: Vec<Sticker>,
477    /// Whether the boost progress bar is shown.
478    #[serde(default)]
479    pub premium_progress_bar_enabled: bool,
480    /// The channel where moderators of a Community guild receive safety alerts.
481    pub safety_alerts_channel_id: Option<ChannelId>,
482    /// Active safety incidents (paused invites or DMs, detected raids or DM spam).
483    pub incidents_data: Option<Box<IncidentsData>>,
484}
485
486/// A partial [`Guild`], as attached to an application (D-051).
487///
488/// discord.js counterpart: `APIPartialGuild` (discord-api-types).
489#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
490#[non_exhaustive]
491pub struct PartialGuild {
492    /// The guild's ID.
493    pub id: GuildId,
494    /// The guild's name.
495    pub name: CompactString,
496    /// The [icon hash](https://docs.discord.com/developers/reference#image-formatting).
497    pub icon: Option<ImageHash>,
498    /// The [invite splash hash](https://docs.discord.com/developers/reference#image-formatting).
499    #[serde(default)]
500    pub splash: Option<ImageHash>,
501    /// The [banner hash](https://docs.discord.com/developers/reference#image-formatting).
502    #[serde(default, skip_serializing_if = "Option::is_none")]
503    pub banner: Option<ImageHash>,
504    /// The guild's description.
505    #[serde(default, skip_serializing_if = "Option::is_none")]
506    pub description: Option<CompactString>,
507    /// The guild's features.
508    #[serde(default, skip_serializing_if = "Vec::is_empty")]
509    pub features: Vec<Feature>,
510    /// The guild's verification level.
511    #[serde(default, skip_serializing_if = "Option::is_none")]
512    pub verification_level: Option<VerificationLevel>,
513    /// The vanity invite code.
514    #[serde(default, skip_serializing_if = "Option::is_none")]
515    pub vanity_url_code: Option<CompactString>,
516    /// The welcome screen of a Community guild.
517    #[serde(default, skip_serializing_if = "Option::is_none")]
518    pub welcome_screen: Option<Box<WelcomeScreen>>,
519}
520
521int_enum! {
522    /// The [default notification level](https://docs.discord.com/developers/resources/guild#guild-object-default-message-notification-level)
523    /// of a guild's members.
524    ///
525    /// discord.js counterpart: `GuildDefaultMessageNotifications`.
526    pub enum DefaultMessageNotificationLevel: u8 {
527        /// Members are notified of every message.
528        AllMessages = 0,
529        /// Members are only notified of messages that mention them.
530        OnlyMentions = 1,
531    }
532}
533
534int_enum! {
535    /// The [explicit content filter level](https://docs.discord.com/developers/resources/guild#guild-object-explicit-content-filter-level):
536    /// whose media is scanned.
537    ///
538    /// discord.js counterpart: `GuildExplicitContentFilter`.
539    pub enum ExplicitContentFilterLevel: u8 {
540        /// No scanning.
541        Disabled = 0,
542        /// Media sent by members without roles is scanned.
543        MembersWithoutRoles = 1,
544        /// Media sent by all members is scanned.
545        AllMembers = 2,
546    }
547}
548
549int_enum! {
550    /// The [MFA level](https://docs.discord.com/developers/resources/guild#guild-object-mfa-level)
551    /// required for moderation actions.
552    ///
553    /// discord.js counterpart: `GuildMFALevel`.
554    pub enum MfaLevel: u8 {
555        /// No two-factor authentication requirement.
556        None = 0,
557        /// Moderators need two-factor authentication.
558        Elevated = 1,
559    }
560}
561
562int_enum! {
563    /// The [verification level](https://docs.discord.com/developers/resources/guild#guild-object-verification-level)
564    /// members must meet before they can talk.
565    ///
566    /// discord.js counterpart: `GuildVerificationLevel`.
567    pub enum VerificationLevel: u8 {
568        /// Unrestricted.
569        None = 0,
570        /// A verified email address.
571        Low = 1,
572        /// Registered on Discord for more than 5 minutes.
573        Medium = 2,
574        /// Member of the guild for more than 10 minutes.
575        High = 3,
576        /// A verified phone number.
577        VeryHigh = 4,
578    }
579}
580
581int_enum! {
582    /// The [age-restriction level](https://docs.discord.com/developers/resources/guild#guild-object-guild-nsfw-level)
583    /// of a guild (`nsfw_level`).
584    ///
585    /// discord.js counterpart: `GuildNSFWLevel`.
586    #[doc(alias = "NsfwLevel")]
587    #[derive(Default)]
588    pub enum AgeRestrictionLevel: u8 {
589        /// Not rated.
590        #[default]
591        Default = 0,
592        /// Explicit content.
593        Explicit = 1,
594        /// Safe for everyone.
595        Safe = 2,
596        /// Age restricted.
597        AgeRestricted = 3,
598    }
599}
600
601int_enum! {
602    /// The [premium tier](https://docs.discord.com/developers/resources/guild#guild-object-premium-tier)
603    /// (Server Boost level) of a guild.
604    ///
605    /// discord.js counterpart: `GuildPremiumTier`.
606    pub enum PremiumTier: u8 {
607        /// No Server Boost perks.
608        None = 0,
609        /// Server Boost level 1.
610        Tier1 = 1,
611        /// Server Boost level 2.
612        Tier2 = 2,
613        /// Server Boost level 3.
614        Tier3 = 3,
615    }
616}
617
618str_enum! {
619    /// A [guild feature](https://docs.discord.com/developers/resources/guild#guild-object-guild-features):
620    /// something a guild has access to or has enabled.
621    ///
622    /// Bots can toggle `COMMUNITY`, `DISCOVERABLE`, `INVITES_DISABLED` and
623    /// `RAID_ALERTS_DISABLED` when modifying a guild (with the required permissions).
624    ///
625    /// discord.js counterpart: `GuildFeature`.
626    #[doc(alias = "GuildFeature")]
627    pub enum Feature {
628        /// Can set an animated banner.
629        AnimatedBanner = "ANIMATED_BANNER",
630        /// Can set an animated icon.
631        AnimatedIcon = "ANIMATED_ICON",
632        /// Uses the old application command permissions behavior.
633        ApplicationCommandPermissionsV2 = "APPLICATION_COMMAND_PERMISSIONS_V2",
634        /// Has auto moderation rules set up.
635        AutoModeration = "AUTO_MODERATION",
636        /// Can set a banner.
637        Banner = "BANNER",
638        /// A Community guild: welcome screen, membership screening, stage channels, discovery
639        /// and community updates.
640        Community = "COMMUNITY",
641        /// Has enabled monetization.
642        CreatorMonetizableProvisional = "CREATOR_MONETIZABLE_PROVISIONAL",
643        /// Has enabled the role subscription promo page.
644        CreatorStorePage = "CREATOR_STORE_PAGE",
645        /// Is the support server of an app in the App Directory.
646        DeveloperSupportServer = "DEVELOPER_SUPPORT_SERVER",
647        /// Can be discovered in the directory.
648        Discoverable = "DISCOVERABLE",
649        /// Can give roles gradient colors.
650        EnhancedRoleColors = "ENHANCED_ROLE_COLORS",
651        /// Can be featured in the directory.
652        Featurable = "FEATURABLE",
653        /// Has access to guest invites.
654        GuestsEnabled = "GUESTS_ENABLED",
655        /// Can set guild (server) tags.
656        GuildTags = "GUILD_TAGS",
657        /// Is listed in a directory channel.
658        ///
659        /// **Undocumented:** known from discord-api-types, not in the official docs; may change
660        /// without notice.
661        HasDirectoryEntry = "HAS_DIRECTORY_ENTRY",
662        /// Is a Student Hub.
663        ///
664        /// **Undocumented:** known from discord-api-types, not in the official docs; may change
665        /// without notice.
666        Hub = "HUB",
667        /// Has paused invites; no new users can join.
668        InvitesDisabled = "INVITES_DISABLED",
669        /// Can set an invite splash background.
670        InviteSplash = "INVITE_SPLASH",
671        /// Is part of a Student Hub.
672        ///
673        /// **Undocumented:** known from discord-api-types, not in the official docs; may change
674        /// without notice.
675        LinkedToHub = "LINKED_TO_HUB",
676        /// Has enabled membership screening.
677        MemberVerificationGateEnabled = "MEMBER_VERIFICATION_GATE_ENABLED",
678        /// Has enabled monetization.
679        ///
680        /// **Undocumented:** known from discord-api-types, not in the official docs; may change
681        /// without notice.
682        MonetizationEnabled = "MONETIZATION_ENABLED",
683        /// Has more custom soundboard sound slots.
684        MoreSoundboard = "MORE_SOUNDBOARD",
685        /// Has more custom sticker slots.
686        MoreStickers = "MORE_STICKERS",
687        /// Can create announcement channels.
688        News = "NEWS",
689        /// Is partnered.
690        Partnered = "PARTNERED",
691        /// Has completed the migration to the separate pin-messages permission.
692        ///
693        /// **Undocumented:** known from discord-api-types, not in the official docs; may change
694        /// without notice.
695        PinPermissionMigrationComplete = "PIN_PERMISSION_MIGRATION_COMPLETE",
696        /// Can be previewed before joining (membership screening or the directory).
697        PreviewEnabled = "PREVIEW_ENABLED",
698        /// Can create private threads.
699        ///
700        /// **Undocumented:** known from discord-api-types, not in the official docs; may change
701        /// without notice.
702        PrivateThreads = "PRIVATE_THREADS",
703        /// Pruning members requires the administrator permission.
704        PruneRequiresAdmin = "PRUNE_REQUIRES_ADMIN",
705        /// Has disabled raid alerts in the safety alerts channel.
706        RaidAlertsDisabled = "RAID_ALERTS_DISABLED",
707        /// Uses Discord's relay (sharded gateway) infrastructure.
708        ///
709        /// **Undocumented:** known from discord-api-types, not in the official docs; may change
710        /// without notice.
711        RelayEnabled = "RELAY_ENABLED",
712        /// Can set role icons.
713        RoleIcons = "ROLE_ICONS",
714        /// Has role subscriptions that can be purchased.
715        RoleSubscriptionsAvailableForPurchase = "ROLE_SUBSCRIPTIONS_AVAILABLE_FOR_PURCHASE",
716        /// Has enabled role subscriptions.
717        RoleSubscriptionsEnabled = "ROLE_SUBSCRIPTIONS_ENABLED",
718        /// Has created soundboard sounds.
719        Soundboard = "SOUNDBOARD",
720        /// Has enabled ticketed events.
721        TicketedEventsEnabled = "TICKETED_EVENTS_ENABLED",
722        /// Can set a vanity URL.
723        VanityUrl = "VANITY_URL",
724        /// Is verified.
725        Verified = "VERIFIED",
726        /// Can use 384 kbps voice bitrate (formerly VIP voice servers).
727        VipRegions = "VIP_REGIONS",
728        /// Has enabled the welcome screen.
729        WelcomeScreenEnabled = "WELCOME_SCREEN_ENABLED",
730    }
731}
732
733/// The [preview of a guild](https://docs.discord.com/developers/resources/guild#guild-preview-object),
734/// visible to non-members of discoverable guilds.
735///
736/// discord.js counterpart: `GuildPreview`.
737#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
738#[non_exhaustive]
739#[doc(alias = "GuildPreview")]
740pub struct Preview {
741    /// The guild's ID.
742    pub id: GuildId,
743    /// The guild's name.
744    pub name: CompactString,
745    /// The [icon hash](https://docs.discord.com/developers/reference#image-formatting).
746    pub icon: Option<ImageHash>,
747    /// The [invite splash hash](https://docs.discord.com/developers/reference#image-formatting).
748    pub splash: Option<ImageHash>,
749    /// The [discovery splash hash](https://docs.discord.com/developers/reference#image-formatting).
750    pub discovery_splash: Option<ImageHash>,
751    /// The guild's custom emojis.
752    pub emojis: Vec<Emoji>,
753    /// The guild's enabled features.
754    pub features: Vec<Feature>,
755    /// The approximate number of members.
756    pub approximate_member_count: u32,
757    /// The approximate number of online members.
758    pub approximate_presence_count: u32,
759    /// The guild's description.
760    pub description: Option<CompactString>,
761    /// The guild's custom stickers.
762    pub stickers: Vec<Sticker>,
763}
764
765/// The [widget settings](https://docs.discord.com/developers/resources/guild#guild-widget-settings-object)
766/// of a guild.
767///
768/// discord.js counterpart: `GuildWidgetSettings`.
769#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
770#[non_exhaustive]
771pub struct WidgetSettings {
772    /// Whether the widget is enabled.
773    pub enabled: bool,
774    /// The channel the widget's invite points to.
775    pub channel_id: Option<ChannelId>,
776}
777
778/// The public [widget](https://docs.discord.com/developers/resources/guild#guild-widget-object)
779/// of a guild (`GET /guilds/{guild.id}/widget.json`).
780///
781/// discord.js counterpart: `Widget`.
782#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
783#[non_exhaustive]
784pub struct Widget {
785    /// The guild's ID.
786    pub id: GuildId,
787    /// The guild's name.
788    pub name: CompactString,
789    /// An instant invite to the widget's channel.
790    pub instant_invite: Option<CompactString>,
791    /// The voice and stage channels everyone can access.
792    pub channels: Vec<WidgetChannel>,
793    /// Up to 100 online members, anonymized.
794    pub members: Vec<WidgetMember>,
795    /// The number of online members.
796    pub presence_count: u32,
797}
798
799/// A channel listed in a [`Widget`].
800///
801/// discord.js counterpart: `WidgetChannel`.
802#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
803#[non_exhaustive]
804pub struct WidgetChannel {
805    /// The channel's ID.
806    pub id: ChannelId,
807    /// The channel's name.
808    pub name: CompactString,
809    /// The channel's position.
810    pub position: i32,
811}
812
813/// An online member listed in a [`Widget`]. Members are anonymized: the ID is an index, not a
814/// user ID.
815///
816/// discord.js counterpart: `WidgetMember`.
817#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
818#[non_exhaustive]
819pub struct WidgetMember {
820    /// An anonymous index (`"0"`, `"1"`, …).
821    pub id: CompactString,
822    /// The member's username.
823    pub username: CompactString,
824    /// The member's discriminator (anonymized as `"0000"`).
825    pub discriminator: CompactString,
826    /// The member's avatar hash (anonymized as `None`).
827    pub avatar: Option<ImageHash>,
828    /// The member's online status.
829    pub status: Status,
830    /// What the member is doing.
831    #[serde(default, skip_serializing_if = "Option::is_none")]
832    pub activity: Option<WidgetActivity>,
833    /// A URL of the member's avatar image.
834    pub avatar_url: CompactString,
835}
836
837/// The activity of a [`WidgetMember`].
838///
839/// discord.js counterpart: `WidgetActivity`.
840#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
841#[non_exhaustive]
842pub struct WidgetActivity {
843    /// The activity's name.
844    pub name: CompactString,
845}
846
847str_enum! {
848    /// The [style of a widget image](https://docs.discord.com/developers/resources/guild#get-guild-widget-image-widget-style-options)
849    /// (`GET /guilds/{guild.id}/widget.png?style=`).
850    ///
851    /// discord.js counterpart: `GuildWidgetStyle`.
852    pub enum WidgetStyle {
853        /// A shield with the Discord icon and the online member count.
854        Shield = "shield",
855        /// A large image with the guild icon, name and online count, "POWERED BY DISCORD" below.
856        Banner1 = "banner1",
857        /// A smaller image with the guild icon, name and online count, the Discord logo on the
858        /// right.
859        Banner2 = "banner2",
860        /// A large image with the guild icon, name and online count, with a "Chat Now" button.
861        Banner3 = "banner3",
862        /// A large Discord logo with the guild icon, name and online count, and a large
863        /// "JOIN MY SERVER" button.
864        Banner4 = "banner4",
865    }
866}
867
868/// An [integration](https://docs.discord.com/developers/resources/guild#integration-object)
869/// in a guild: a bot or app, or a Twitch/YouTube subscription.
870///
871/// Fields marked "not for Discord bots" are absent for `discord` integrations.
872///
873/// discord.js counterpart: `Integration`.
874#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
875#[non_exhaustive]
876pub struct Integration {
877    /// The integration's ID.
878    pub id: IntegrationId,
879    /// The integration's name.
880    pub name: CompactString,
881    /// The kind of integration.
882    #[serde(rename = "type")]
883    pub kind: IntegrationType,
884    /// Whether the integration is enabled.
885    pub enabled: bool,
886    /// Whether the integration is syncing (not for Discord bots).
887    #[serde(default, skip_serializing_if = "core::ops::Not::not")]
888    pub syncing: bool,
889    /// The role given to subscribers (not for Discord bots).
890    #[serde(default, skip_serializing_if = "Option::is_none")]
891    pub role_id: Option<RoleId>,
892    /// Whether emoticons are synced (Twitch only).
893    #[serde(default, skip_serializing_if = "core::ops::Not::not")]
894    pub enable_emoticons: bool,
895    /// What happens to expired subscribers (not for Discord bots).
896    #[serde(default, skip_serializing_if = "Option::is_none")]
897    pub expire_behavior: Option<IntegrationExpireBehavior>,
898    /// The grace period before subscribers expire, in days (not for Discord bots).
899    #[serde(default, skip_serializing_if = "Option::is_none")]
900    pub expire_grace_period: Option<u32>,
901    /// The user who added the integration.
902    #[serde(default, skip_serializing_if = "Option::is_none")]
903    pub user: Option<Box<User>>,
904    /// The integration's account.
905    pub account: IntegrationAccount,
906    /// When the integration last synced (not for Discord bots).
907    #[serde(default, skip_serializing_if = "Option::is_none")]
908    pub synced_at: Option<Timestamp>,
909    /// The number of subscribers (not for Discord bots).
910    #[serde(default, skip_serializing_if = "Option::is_none")]
911    pub subscriber_count: Option<u32>,
912    /// Whether the integration was revoked (not for Discord bots).
913    #[serde(default, skip_serializing_if = "core::ops::Not::not")]
914    pub revoked: bool,
915    /// The bot or `OAuth2` application of a Discord integration.
916    #[serde(default, skip_serializing_if = "Option::is_none")]
917    pub application: Option<Box<IntegrationApplication>>,
918    /// The scopes the application was authorized for.
919    #[serde(default, skip_serializing_if = "Vec::is_empty")]
920    pub scopes: Vec<Scope>,
921}
922
923/// A partial [`Integration`], as listed on a user's
924/// [`Connection`](crate::user::Connection) and in an [`AuditLog`](crate::audit_log::AuditLog)
925/// (D-051).
926///
927/// Discord does not document which fields are present; only the ID is required here.
928///
929/// discord.js counterpart: the `integrations` of `APIConnection` (discord-api-types).
930#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
931#[non_exhaustive]
932pub struct PartialIntegration {
933    /// The integration's ID.
934    pub id: IntegrationId,
935    /// The integration's name.
936    #[serde(default, skip_serializing_if = "Option::is_none")]
937    pub name: Option<CompactString>,
938    /// The kind of integration.
939    #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
940    pub kind: Option<IntegrationType>,
941    /// Whether the integration is enabled.
942    #[serde(default, skip_serializing_if = "core::ops::Not::not")]
943    pub enabled: bool,
944    /// Whether the integration is syncing.
945    #[serde(default, skip_serializing_if = "core::ops::Not::not")]
946    pub syncing: bool,
947    /// The role given to subscribers.
948    #[serde(default, skip_serializing_if = "Option::is_none")]
949    pub role_id: Option<RoleId>,
950    /// Whether emoticons are synced (Twitch only).
951    #[serde(default, skip_serializing_if = "core::ops::Not::not")]
952    pub enable_emoticons: bool,
953    /// What happens to expired subscribers.
954    #[serde(default, skip_serializing_if = "Option::is_none")]
955    pub expire_behavior: Option<IntegrationExpireBehavior>,
956    /// The grace period before subscribers expire, in days.
957    #[serde(default, skip_serializing_if = "Option::is_none")]
958    pub expire_grace_period: Option<u32>,
959    /// The user who added the integration.
960    #[serde(default, skip_serializing_if = "Option::is_none")]
961    pub user: Option<Box<User>>,
962    /// The integration's account.
963    #[serde(default, skip_serializing_if = "Option::is_none")]
964    pub account: Option<IntegrationAccount>,
965    /// When the integration last synced.
966    #[serde(default, skip_serializing_if = "Option::is_none")]
967    pub synced_at: Option<Timestamp>,
968    /// The number of subscribers.
969    #[serde(default, skip_serializing_if = "Option::is_none")]
970    pub subscriber_count: Option<u32>,
971    /// Whether the integration was revoked.
972    #[serde(default, skip_serializing_if = "core::ops::Not::not")]
973    pub revoked: bool,
974    /// The bot or `OAuth2` application of a Discord integration.
975    #[serde(default, skip_serializing_if = "Option::is_none")]
976    pub application: Option<Box<IntegrationApplication>>,
977    /// The ID of the integration's application (audit log integrations; shown in the docs'
978    /// audit log example but not in the integration table).
979    #[serde(default, skip_serializing_if = "Option::is_none")]
980    pub application_id: Option<ApplicationId>,
981    /// The scopes the application was authorized for.
982    #[serde(default, skip_serializing_if = "Vec::is_empty")]
983    pub scopes: Vec<Scope>,
984}
985
986str_enum! {
987    /// The kind of an [`Integration`].
988    ///
989    /// discord.js counterpart: `IntegrationType`.
990    pub enum IntegrationType {
991        /// A Twitch subscription.
992        Twitch = "twitch",
993        /// A YouTube membership.
994        Youtube = "youtube",
995        /// A Discord bot or `OAuth2` app.
996        Discord = "discord",
997        /// A guild (role) subscription.
998        GuildSubscription = "guild_subscription",
999    }
1000}
1001
1002int_enum! {
1003    /// [What happens to expired subscribers](https://docs.discord.com/developers/resources/guild#integration-object-integration-expire-behaviors)
1004    /// of an integration.
1005    ///
1006    /// discord.js counterpart: `IntegrationExpireBehavior`.
1007    pub enum IntegrationExpireBehavior: u8 {
1008        /// The subscriber role is removed.
1009        RemoveRole = 0,
1010        /// The member is kicked.
1011        Kick = 1,
1012    }
1013}
1014
1015/// The [account of an integration](https://docs.discord.com/developers/resources/guild#integration-account-object)
1016/// (e.g. the Twitch channel).
1017///
1018/// discord.js counterpart: `IntegrationAccount`.
1019#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1020#[non_exhaustive]
1021pub struct IntegrationAccount {
1022    /// The account's ID on the platform.
1023    pub id: CompactString,
1024    /// The account's name.
1025    pub name: CompactString,
1026}
1027
1028/// The [application of a Discord integration](https://docs.discord.com/developers/resources/guild#integration-application-object).
1029///
1030/// discord.js counterpart: `IntegrationApplication`.
1031#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
1032#[non_exhaustive]
1033pub struct IntegrationApplication {
1034    /// The application's ID.
1035    pub id: ApplicationId,
1036    /// The application's name.
1037    pub name: CompactString,
1038    /// The [icon hash](https://docs.discord.com/developers/reference#image-formatting).
1039    pub icon: Option<ImageHash>,
1040    /// The application's description.
1041    pub description: CompactString,
1042    /// The application's bot user.
1043    #[serde(default, skip_serializing_if = "Option::is_none")]
1044    pub bot: Option<User>,
1045}
1046
1047/// A [ban](https://docs.discord.com/developers/resources/guild#ban-object).
1048///
1049/// discord.js counterpart: `GuildBan`.
1050#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
1051#[non_exhaustive]
1052pub struct Ban {
1053    /// The reason given for the ban.
1054    pub reason: Option<CompactString>,
1055    /// The banned user.
1056    pub user: User,
1057}
1058
1059/// The [welcome screen](https://docs.discord.com/developers/resources/guild#welcome-screen-object)
1060/// of a Community guild, shown to new members.
1061///
1062/// discord.js counterpart: `WelcomeScreen`.
1063#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
1064#[non_exhaustive]
1065pub struct WelcomeScreen {
1066    /// The guild description shown on the welcome screen.
1067    pub description: Option<CompactString>,
1068    /// Up to 5 suggested channels.
1069    pub welcome_channels: Vec<WelcomeScreenChannel>,
1070}
1071
1072/// A [channel suggested on the welcome screen](https://docs.discord.com/developers/resources/guild#welcome-screen-object-welcome-screen-channel-structure).
1073///
1074/// discord.js counterpart: `WelcomeChannel`.
1075#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1076#[non_exhaustive]
1077pub struct WelcomeScreenChannel {
1078    /// The channel's ID.
1079    pub channel_id: ChannelId,
1080    /// The description shown for the channel.
1081    pub description: CompactString,
1082    /// The custom emoji's ID, for a custom emoji.
1083    pub emoji_id: Option<EmojiId>,
1084    /// The custom emoji's name, the Unicode emoji itself, or `None` without an emoji.
1085    pub emoji_name: Option<CompactString>,
1086}
1087
1088impl WelcomeScreenChannel {
1089    /// A suggested channel without an emoji.
1090    ///
1091    /// discord.js counterpart: `WelcomeChannelData`.
1092    #[must_use]
1093    pub fn new(channel_id: ChannelId, description: impl Into<CompactString>) -> Self {
1094        Self {
1095            channel_id,
1096            description: description.into(),
1097            emoji_id: None,
1098            emoji_name: None,
1099        }
1100    }
1101}
1102
1103/// The [onboarding](https://docs.discord.com/developers/resources/guild#guild-onboarding-object)
1104/// flow of a guild: questions that give new members channels and roles.
1105///
1106/// discord.js counterpart: `GuildOnboarding`.
1107#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
1108#[non_exhaustive]
1109#[doc(alias = "GuildOnboarding")]
1110pub struct Onboarding {
1111    /// The guild's ID.
1112    pub guild_id: GuildId,
1113    /// The questions shown in onboarding and in "Channels & Roles".
1114    pub prompts: Vec<OnboardingPrompt>,
1115    /// Channels members are opted into automatically.
1116    pub default_channel_ids: Vec<ChannelId>,
1117    /// Whether onboarding is enabled.
1118    pub enabled: bool,
1119    /// Which channels count towards onboarding constraints. Defaults to
1120    /// [`Default`](OnboardingMode::Default) when absent (older payloads).
1121    #[serde(default)]
1122    pub mode: OnboardingMode,
1123}
1124
1125/// A [question in onboarding](https://docs.discord.com/developers/resources/guild#guild-onboarding-object-onboarding-prompt-structure).
1126///
1127/// discord.js counterpart: `GuildOnboardingPrompt`.
1128#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
1129#[non_exhaustive]
1130pub struct OnboardingPrompt {
1131    /// The prompt's ID.
1132    pub id: GenericId,
1133    /// How the prompt is displayed.
1134    #[serde(rename = "type")]
1135    pub kind: PromptType,
1136    /// The answers to choose from.
1137    pub options: Vec<PromptOption>,
1138    /// The question.
1139    pub title: CompactString,
1140    /// Whether only one answer can be chosen.
1141    pub single_select: bool,
1142    /// Whether the prompt must be answered to finish onboarding.
1143    pub required: bool,
1144    /// Whether the prompt is part of onboarding; if not, it only appears in "Channels & Roles".
1145    pub in_onboarding: bool,
1146}
1147
1148/// An [answer of an onboarding prompt](https://docs.discord.com/developers/resources/guild#guild-onboarding-object-prompt-option-structure).
1149///
1150/// When creating or editing an option, Discord expects `emoji_id`/`emoji_name`/`emoji_animated`
1151/// instead of the [`emoji`](Self::emoji) object received here.
1152///
1153/// discord.js counterpart: `GuildOnboardingPromptOption`.
1154#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
1155#[non_exhaustive]
1156pub struct PromptOption {
1157    /// The option's ID.
1158    pub id: GenericId,
1159    /// Channels the member is added to when choosing this option.
1160    pub channel_ids: Vec<ChannelId>,
1161    /// Roles the member gets when choosing this option.
1162    pub role_ids: Vec<RoleId>,
1163    /// The option's emoji.
1164    #[serde(default, skip_serializing_if = "Option::is_none")]
1165    pub emoji: Option<PartialEmoji>,
1166    /// The option's title.
1167    pub title: CompactString,
1168    /// The option's description.
1169    pub description: Option<CompactString>,
1170}
1171
1172int_enum! {
1173    /// The [onboarding mode](https://docs.discord.com/developers/resources/guild#guild-onboarding-object-onboarding-mode):
1174    /// what counts towards the onboarding constraints.
1175    ///
1176    /// discord.js counterpart: `GuildOnboardingMode`.
1177    #[derive(Default)]
1178    pub enum OnboardingMode: u8 {
1179        /// Only default channels count.
1180        #[default]
1181        Default = 0,
1182        /// Default channels and questions count.
1183        Advanced = 1,
1184    }
1185}
1186
1187int_enum! {
1188    /// How an [`OnboardingPrompt`] is displayed.
1189    ///
1190    /// discord.js counterpart: `GuildOnboardingPromptType`.
1191    pub enum PromptType: u8 {
1192        /// Multiple choice buttons.
1193        MultipleChoice = 0,
1194        /// A dropdown.
1195        Dropdown = 1,
1196    }
1197}
1198
1199/// [Safety incidents](https://docs.discord.com/developers/resources/guild#incidents-data-object)
1200/// of a guild: paused invites or DMs and detected raids or DM spam.
1201///
1202/// discord.js counterpart: `IncidentActions`.
1203#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1204#[non_exhaustive]
1205pub struct IncidentsData {
1206    /// When invites are enabled again.
1207    pub invites_disabled_until: Option<Timestamp>,
1208    /// When direct messages between members are enabled again.
1209    pub dms_disabled_until: Option<Timestamp>,
1210    /// When DM spam was detected.
1211    #[serde(default, skip_serializing_if = "Option::is_none")]
1212    pub dm_spam_detected_at: Option<Timestamp>,
1213    /// When a raid was detected.
1214    #[serde(default, skip_serializing_if = "Option::is_none")]
1215    pub raid_detected_at: Option<Timestamp>,
1216}
1217
1218int_flags! {
1219    /// [Flags of a guild's system channel](https://docs.discord.com/developers/resources/guild#guild-object-system-channel-flags):
1220    /// which automatic messages Discord does **not** post there.
1221    ///
1222    /// discord.js counterpart: `GuildSystemChannelFlags` / `SystemChannelFlagsBitField`.
1223    pub struct SystemChannelFlags: u64 {
1224        /// No message when a member joins.
1225        const SUPPRESS_JOIN_NOTIFICATIONS = 1 << 0;
1226        /// No message when the guild is boosted.
1227        const SUPPRESS_PREMIUM_SUBSCRIPTIONS = 1 << 1;
1228        /// No server setup tips.
1229        const SUPPRESS_GUILD_REMINDER_NOTIFICATIONS = 1 << 2;
1230        /// No sticker reply button on join messages.
1231        const SUPPRESS_JOIN_NOTIFICATION_REPLIES = 1 << 3;
1232        /// No message when a role subscription is purchased or renewed.
1233        const SUPPRESS_ROLE_SUBSCRIPTION_PURCHASE_NOTIFICATIONS = 1 << 4;
1234        /// No sticker reply button on role subscription messages.
1235        const SUPPRESS_ROLE_SUBSCRIPTION_PURCHASE_NOTIFICATION_REPLIES = 1 << 5;
1236    }
1237}
1238
1239int_flags! {
1240    /// [Flags of a guild member](https://docs.discord.com/developers/resources/guild#guild-member-object-guild-member-flags).
1241    ///
1242    /// Only [`BYPASSES_VERIFICATION`](Self::BYPASSES_VERIFICATION) can be changed by bots
1243    /// (when modifying a member); the others are set by Discord.
1244    ///
1245    /// discord.js counterpart: `GuildMemberFlags` / `GuildMemberFlagsBitField`.
1246    pub struct MemberFlags: u64 {
1247        /// The member left the guild and joined again.
1248        const DID_REJOIN = 1 << 0;
1249        /// The member completed onboarding.
1250        const COMPLETED_ONBOARDING = 1 << 1;
1251        /// The member is exempt from the guild's verification requirements. Editable.
1252        const BYPASSES_VERIFICATION = 1 << 2;
1253        /// The member started onboarding.
1254        const STARTED_ONBOARDING = 1 << 3;
1255        /// The member is a guest who can only access the voice channel they were invited to.
1256        const IS_GUEST = 1 << 4;
1257        /// The member started the Server Guide new-member actions.
1258        const STARTED_HOME_ACTIONS = 1 << 5;
1259        /// The member completed the Server Guide new-member actions.
1260        const COMPLETED_HOME_ACTIONS = 1 << 6;
1261        /// AutoMod blocks the member's username, display name or nickname.
1262        const AUTOMOD_QUARANTINED_USERNAME = 1 << 7;
1263        /// AutoMod blocks the member's bio.
1264        ///
1265        /// **Deprecated** by Discord.
1266        ///
1267        /// **Undocumented:** known from discord-api-types, not in the official docs; may
1268        /// change without notice.
1269        const AUTOMOD_QUARANTINED_BIO = 1 << 8;
1270        /// The member dismissed the DM settings upsell.
1271        const DM_SETTINGS_UPSELL_ACKNOWLEDGED = 1 << 9;
1272        /// AutoMod blocks the member's guild tag.
1273        const AUTOMOD_QUARANTINED_GUILD_TAG = 1 << 10;
1274    }
1275}
1276
1277int_flags! {
1278    /// [Flags of a role](https://docs.discord.com/developers/topics/permissions#role-object-role-flags).
1279    ///
1280    /// discord.js counterpart: `RoleFlags` / `RoleFlagsBitField`.
1281    pub struct RoleFlags: u64 {
1282        /// Members can pick the role in an onboarding prompt.
1283        const IN_PROMPT = 1 << 0;
1284    }
1285}
1286
1287#[cfg(test)]
1288mod tests {
1289    use super::*;
1290
1291    const USER: &str = r#"{"id":"80351110224678912","username":"nelly","discriminator":"0","global_name":"Nelly","avatar":null}"#;
1292
1293    #[test]
1294    fn member_from_documented_example() {
1295        // The docs example with its empty `user` filled in.
1296        let json = format!(
1297            r#"{{"user":{USER},"nick":"NOT API SUPPORT","avatar":null,"banner":null,"roles":[],
1298                "joined_at":"2015-04-26T06:26:56.936000+00:00","deaf":false,"mute":false}}"#
1299        );
1300        let member: Member = serde_json::from_str(&json).unwrap();
1301        assert_eq!(member.user.id.get(), 80_351_110_224_678_912);
1302        assert_eq!(member.nick.as_deref(), Some("NOT API SUPPORT"));
1303        assert_eq!(member.avatar, None);
1304        assert_eq!(
1305            member.joined_at.unwrap().to_string(),
1306            "2015-04-26T06:26:56.936000+00:00"
1307        );
1308        assert_eq!(member.flags, MemberFlags::empty());
1309        assert!(!member.pending);
1310        assert_eq!(member.display_name(), "NOT API SUPPORT");
1311    }
1312
1313    #[test]
1314    fn partial_member_from_message_create() {
1315        // The `member` of a real MESSAGE_CREATE payload: no `user`.
1316        let json = r#"{"roles":["1100000000000000001"],"premium_since":null,"pending":false,
1317            "nick":null,"mute":false,"joined_at":"2024-05-01T12:00:00.000000+00:00","flags":2,
1318            "deaf":false,"communication_disabled_until":"2026-11-10T20:00:00.000000+00:00",
1319            "banner":null,"avatar":null}"#;
1320        let partial: PartialMember = serde_json::from_str(json).unwrap();
1321        assert_eq!(partial.roles.len(), 1);
1322        assert_eq!(partial.flags, MemberFlags::COMPLETED_ONBOARDING);
1323        let user: User = serde_json::from_str(USER).unwrap();
1324        let member = partial.into_member(user);
1325        assert_eq!(member.display_name(), "Nelly");
1326        let before: Timestamp = "2026-11-10T19:00:00.000000+00:00".parse().unwrap();
1327        let after: Timestamp = "2026-11-10T21:00:00.000000+00:00".parse().unwrap();
1328        assert!(member.is_timed_out(before));
1329        assert!(!member.is_timed_out(after));
1330    }
1331
1332    #[test]
1333    fn role_from_documented_example() {
1334        let json = r#"{"id":"41771983423143936","name":"WE DEM BOYZZ!!!!!!","color":3447003,
1335            "colors":{"primary_color":3447003,"secondary_color":null,"tertiary_color":null},
1336            "hoist":true,"icon":"cf3ced8600b777c9486c6d8d84fb4327","unicode_emoji":null,
1337            "position":1,"permissions":"66321471","managed":false,"mentionable":false,"flags":0}"#;
1338        let role: Role = serde_json::from_str(json).unwrap();
1339        assert_eq!(role.colors, RoleColors::solid(3_447_003));
1340        assert_eq!(role.permissions.bits(), 66_321_471);
1341        assert!(role.permissions.contains(Permissions::SEND_MESSAGES));
1342        assert_eq!(role.position, 1);
1343        assert!(role.tags.is_none());
1344        assert_eq!(
1345            role.icon.unwrap().to_string(),
1346            "cf3ced8600b777c9486c6d8d84fb4327"
1347        );
1348    }
1349
1350    #[test]
1351    fn role_tags_null_flags() {
1352        let json = r#"{"bot_id":"1","premium_subscriber":null,"guild_connections":null}"#;
1353        let tags: RoleTags = serde_json::from_str(json).unwrap();
1354        assert_eq!(tags.bot_id.map(crate::id::Id::get), Some(1));
1355        assert!(tags.premium_subscriber);
1356        assert!(tags.guild_connections);
1357        assert!(!tags.available_for_purchase);
1358        // Set flags are written back as `null`, unset flags are omitted.
1359        assert_eq!(serde_json::to_string(&tags).unwrap(), json);
1360    }
1361
1362    #[test]
1363    fn holographic_colors_serialize_like_the_docs() {
1364        assert_eq!(
1365            serde_json::to_string(&RoleColors::HOLOGRAPHIC).unwrap(),
1366            r#"{"primary_color":11127295,"secondary_color":16759788,"tertiary_color":16761760}"#
1367        );
1368    }
1369
1370    #[test]
1371    fn hot_type_sizes() {
1372        assert!(
1373            size_of::<Member>() <= 304,
1374            "Member is {} bytes",
1375            size_of::<Member>()
1376        );
1377        assert!(
1378            size_of::<PartialMember>() <= 160,
1379            "PartialMember is {} bytes",
1380            size_of::<PartialMember>()
1381        );
1382        assert!(
1383            size_of::<Role>() <= 128,
1384            "Role is {} bytes",
1385            size_of::<Role>()
1386        );
1387    }
1388}