Skip to main content

djs_model/rest/
guild.rs

1//! Bodies, queries and responses of the [guild endpoints](https://docs.discord.com/developers/resources/guild):
2//! the guild, its channels, members, bans, roles, prune, widget, welcome screen, onboarding
3//! and incident actions.
4//!
5//! Deprecated request fields are left out (`region`, role `color`, ban
6//! `delete_message_days`, the prune body's `reason`; C-048).
7
8use core::{
9    fmt,
10    sync::atomic::{AtomicU64, Ordering},
11};
12// `std::time` has no clock on `wasm32-unknown-unknown`; `web-time` reads the JS host's (D-397).
13#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
14use std::time::{SystemTime, UNIX_EPOCH};
15
16#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
17use web_time::{SystemTime, UNIX_EPOCH};
18
19use compact_str::CompactString;
20use serde::{Deserialize, Serialize, Serializer};
21
22use super::ForumTagData;
23use crate::{
24    channel::{
25        AutoArchiveDuration, Channel, ChannelFlags, ChannelType, DefaultReaction, ForumLayoutType,
26        Overwrite, SortOrderType, ThreadMember, VideoQualityMode,
27    },
28    emoji::PartialEmoji,
29    guild::{
30        DefaultMessageNotificationLevel, ExplicitContentFilterLevel, Feature, MemberFlags,
31        OnboardingMode, OnboardingPrompt, PromptOption, PromptType, RoleColors, SystemChannelFlags,
32        VerificationLevel, WelcomeScreenChannel,
33    },
34    id::{ChannelId, EmojiId, GenericId, RoleId, UserId},
35    permissions::Permissions,
36    util::{ImageData, Locale, Patch, Timestamp},
37};
38
39/// The query of [Get Guild](https://docs.discord.com/developers/resources/guild#get-guild).
40///
41/// discord.js counterpart: `RESTGetAPIGuildQuery` (discord-api-types).
42#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
43#[non_exhaustive]
44pub struct GetGuild {
45    /// Whether to include the approximate member and presence counts.
46    pub with_counts: Option<bool>,
47}
48
49/// The body of [Modify Guild](https://docs.discord.com/developers/resources/guild#modify-guild).
50///
51/// Every field is optional; [`Patch`] fields can also be cleared. Adding or removing the
52/// `COMMUNITY` feature needs `ADMINISTRATOR`.
53///
54/// discord.js counterpart: `GuildEditOptions`.
55#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize)]
56#[non_exhaustive]
57pub struct ModifyGuild {
58    /// The name.
59    #[serde(skip_serializing_if = "Option::is_none")]
60    pub name: Option<CompactString>,
61    /// Who can talk in the guild.
62    #[serde(skip_serializing_if = "Patch::is_keep")]
63    pub verification_level: Patch<VerificationLevel>,
64    /// Which messages notify members by default.
65    #[serde(skip_serializing_if = "Patch::is_keep")]
66    pub default_message_notifications: Patch<DefaultMessageNotificationLevel>,
67    /// Whose media is scanned for explicit content.
68    #[serde(skip_serializing_if = "Patch::is_keep")]
69    pub explicit_content_filter: Patch<ExplicitContentFilterLevel>,
70    /// The AFK voice channel.
71    #[serde(skip_serializing_if = "Patch::is_keep")]
72    pub afk_channel_id: Patch<ChannelId>,
73    /// Seconds of inactivity before members are moved to the AFK channel: 60, 300, 900,
74    /// 1800 or 3600.
75    #[serde(skip_serializing_if = "Option::is_none")]
76    pub afk_timeout: Option<u32>,
77    /// The icon (1024×1024; an animated GIF with the `ANIMATED_ICON` feature).
78    #[serde(skip_serializing_if = "Patch::is_keep")]
79    pub icon: Patch<ImageData>,
80    /// The invite splash (16:9; needs the `INVITE_SPLASH` feature).
81    #[serde(skip_serializing_if = "Patch::is_keep")]
82    pub splash: Patch<ImageData>,
83    /// The discovery splash (16:9; needs the `DISCOVERABLE` feature).
84    #[serde(skip_serializing_if = "Patch::is_keep")]
85    pub discovery_splash: Patch<ImageData>,
86    /// The banner (16:9; needs the `BANNER` feature, animated with `ANIMATED_BANNER`).
87    #[serde(skip_serializing_if = "Patch::is_keep")]
88    pub banner: Patch<ImageData>,
89    /// The channel of welcome and boost messages.
90    #[serde(skip_serializing_if = "Patch::is_keep")]
91    pub system_channel_id: Patch<ChannelId>,
92    /// Which messages the system channel shows (set flags suppress them).
93    #[serde(skip_serializing_if = "Option::is_none")]
94    pub system_channel_flags: Option<SystemChannelFlags>,
95    /// The rules or guidelines channel of a community guild.
96    #[serde(skip_serializing_if = "Patch::is_keep")]
97    pub rules_channel_id: Patch<ChannelId>,
98    /// The channel where community guild moderators get notices from Discord.
99    #[serde(skip_serializing_if = "Patch::is_keep")]
100    pub public_updates_channel_id: Patch<ChannelId>,
101    /// The language of a community guild (Discord's default: `en-US`).
102    #[serde(skip_serializing_if = "Patch::is_keep")]
103    pub preferred_locale: Patch<Locale>,
104    /// The enabled features (all of them).
105    #[serde(skip_serializing_if = "Option::is_none")]
106    pub features: Option<Vec<Feature>>,
107    /// The description.
108    #[serde(skip_serializing_if = "Patch::is_keep")]
109    pub description: Patch<CompactString>,
110    /// Whether the boost progress bar is shown.
111    #[serde(skip_serializing_if = "Option::is_none")]
112    pub premium_progress_bar_enabled: Option<bool>,
113    /// The channel where community guild moderators get safety alerts.
114    #[serde(skip_serializing_if = "Patch::is_keep")]
115    pub safety_alerts_channel_id: Patch<ChannelId>,
116}
117
118/// The body of [Create Guild Channel](https://docs.discord.com/developers/resources/guild#create-guild-channel).
119///
120/// Only the name is required; Discord creates a text channel when
121/// [`kind`](Self::kind) is `None`. Which fields apply depends on the type.
122///
123/// discord.js counterpart: `GuildChannelCreateOptions`.
124///
125/// # Examples
126///
127/// ```
128/// use djs_model::{channel::ChannelType, rest::CreateGuildChannel};
129///
130/// let mut voice = CreateGuildChannel::new("Lounge");
131/// voice.kind = Some(ChannelType::GuildVoice);
132/// voice.user_limit = Some(10);
133/// assert_eq!(
134///     serde_json::to_string(&voice).unwrap(),
135///     r#"{"name":"Lounge","type":2,"user_limit":10}"#
136/// );
137/// ```
138#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize)]
139#[non_exhaustive]
140pub struct CreateGuildChannel {
141    /// The name (1-100 characters).
142    pub name: CompactString,
143    /// The type (Discord's default: a text channel).
144    #[serde(rename = "type", skip_serializing_if = "Option::is_none")]
145    pub kind: Option<ChannelType>,
146    /// The topic (0-1024 characters).
147    #[serde(skip_serializing_if = "Option::is_none")]
148    pub topic: Option<CompactString>,
149    /// The bitrate of a voice or stage channel, in bits per second (min 8000).
150    #[serde(skip_serializing_if = "Option::is_none")]
151    pub bitrate: Option<u32>,
152    /// The user limit of a voice or stage channel; 0 is no limit.
153    #[serde(skip_serializing_if = "Option::is_none")]
154    pub user_limit: Option<u32>,
155    /// Slowmode: seconds a member must wait between messages (0-21600).
156    #[serde(skip_serializing_if = "Option::is_none")]
157    pub rate_limit_per_user: Option<u16>,
158    /// The position in the channel list.
159    #[serde(skip_serializing_if = "Option::is_none")]
160    pub position: Option<i32>,
161    /// The permission overwrites; only permissions the bot has can be allowed or denied.
162    #[serde(skip_serializing_if = "Vec::is_empty")]
163    pub permission_overwrites: Vec<Overwrite>,
164    /// The parent category.
165    #[serde(skip_serializing_if = "Option::is_none")]
166    pub parent_id: Option<ChannelId>,
167    /// Whether the channel is age-restricted.
168    #[serde(skip_serializing_if = "core::ops::Not::not")]
169    pub nsfw: bool,
170    /// The voice region ID (Discord's default: automatic).
171    #[serde(skip_serializing_if = "Option::is_none")]
172    pub rtc_region: Option<CompactString>,
173    /// The camera video quality of a voice or stage channel.
174    #[serde(skip_serializing_if = "Option::is_none")]
175    pub video_quality_mode: Option<VideoQualityMode>,
176    /// The archive duration that clients preselect for new threads.
177    #[serde(skip_serializing_if = "Option::is_none")]
178    pub default_auto_archive_duration: Option<AutoArchiveDuration>,
179    /// The emoji of the add-reaction button on posts of a forum or media channel.
180    #[serde(skip_serializing_if = "Option::is_none")]
181    pub default_reaction_emoji: Option<DefaultReaction>,
182    /// The tags of a forum or media channel (max 20).
183    #[serde(skip_serializing_if = "Vec::is_empty")]
184    pub available_tags: Vec<ForumTagData>,
185    /// The default order of posts in a forum or media channel.
186    #[serde(skip_serializing_if = "Option::is_none")]
187    pub default_sort_order: Option<SortOrderType>,
188    /// The default layout of a forum channel.
189    #[serde(skip_serializing_if = "Option::is_none")]
190    pub default_forum_layout: Option<ForumLayoutType>,
191    /// The slowmode copied to new threads.
192    #[serde(skip_serializing_if = "Option::is_none")]
193    pub default_thread_rate_limit_per_user: Option<u16>,
194    /// The channel's flags.
195    #[serde(skip_serializing_if = "Option::is_none")]
196    pub flags: Option<ChannelFlags>,
197}
198
199impl CreateGuildChannel {
200    /// A channel named `name`, with Discord's defaults for everything else.
201    ///
202    /// discord.js counterpart: `GuildChannelCreateOptions`.
203    #[must_use]
204    pub fn new(name: impl Into<CompactString>) -> Self {
205        Self {
206            name: name.into(),
207            kind: None,
208            topic: None,
209            bitrate: None,
210            user_limit: None,
211            rate_limit_per_user: None,
212            position: None,
213            permission_overwrites: Vec::new(),
214            parent_id: None,
215            nsfw: false,
216            rtc_region: None,
217            video_quality_mode: None,
218            default_auto_archive_duration: None,
219            default_reaction_emoji: None,
220            available_tags: Vec::new(),
221            default_sort_order: None,
222            default_forum_layout: None,
223            default_thread_rate_limit_per_user: None,
224            flags: None,
225        }
226    }
227}
228
229/// One entry of [Modify Guild Channel Positions](https://docs.discord.com/developers/resources/guild#modify-guild-channel-positions).
230///
231/// At most one entry per request may change [`parent_id`](Self::parent_id).
232///
233/// discord.js counterpart: an element of `RESTPatchAPIGuildChannelPositionsJSONBody` (discord-api-types).
234#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize)]
235#[non_exhaustive]
236pub struct ModifyGuildChannelPosition {
237    /// The channel.
238    pub id: ChannelId,
239    /// The new position.
240    #[serde(skip_serializing_if = "Patch::is_keep")]
241    pub position: Patch<i32>,
242    /// When moving to a new category, whether to sync the permission overwrites with it.
243    #[serde(skip_serializing_if = "Patch::is_keep")]
244    pub lock_permissions: Patch<bool>,
245    /// The new parent category; [`Patch::Clear`] moves the channel out of its category.
246    #[serde(skip_serializing_if = "Patch::is_keep")]
247    pub parent_id: Patch<ChannelId>,
248}
249
250impl ModifyGuildChannelPosition {
251    /// Moves channel `id` to `position`.
252    ///
253    /// discord.js counterpart: `ChannelPosition`.
254    #[must_use]
255    pub const fn new(id: ChannelId, position: i32) -> Self {
256        Self {
257            id,
258            position: Patch::Set(position),
259            lock_permissions: Patch::Keep,
260            parent_id: Patch::Keep,
261        }
262    }
263}
264
265/// The response of [List Active Guild Threads](https://docs.discord.com/developers/resources/guild#list-active-guild-threads).
266///
267/// discord.js counterpart: `FetchedThreads`.
268#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
269#[non_exhaustive]
270pub struct ActiveThreads {
271    /// The active threads, highest ID first.
272    pub threads: Vec<Channel>,
273    /// The current user's membership of each returned thread they joined.
274    pub members: Vec<ThreadMember>,
275}
276
277/// The query of [List Guild Members](https://docs.discord.com/developers/resources/guild#list-guild-members).
278///
279/// Needs the `GUILD_MEMBERS` privileged intent.
280///
281/// discord.js counterpart: `RESTGetAPIGuildMembersQuery` (discord-api-types).
282#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
283#[non_exhaustive]
284pub struct ListGuildMembers {
285    /// The page size (1-1000; Discord's default: 1).
286    pub limit: Option<u16>,
287    /// The highest user ID of the previous page.
288    pub after: Option<UserId>,
289}
290
291/// The query of [Search Guild Members](https://docs.discord.com/developers/resources/guild#search-guild-members).
292///
293/// discord.js counterpart: `RESTGetAPIGuildMembersSearchQuery` (discord-api-types).
294#[derive(Clone, Debug, PartialEq, Eq, Hash)]
295#[non_exhaustive]
296pub struct SearchGuildMembers {
297    /// The start of the usernames and nicknames to find.
298    pub query: CompactString,
299    /// The maximum number of members (1-1000; Discord's default: 1).
300    pub limit: Option<u16>,
301}
302
303impl SearchGuildMembers {
304    /// Members whose username or nickname starts with `query`.
305    ///
306    /// discord.js counterpart: `GuildSearchMembersOptions`.
307    #[must_use]
308    pub fn new(query: impl Into<CompactString>) -> Self {
309        Self {
310            query: query.into(),
311            limit: None,
312        }
313    }
314}
315
316/// The body of [Add Guild Member](https://docs.discord.com/developers/resources/guild#add-guild-member).
317///
318/// The access token is redacted in the `Debug` output.
319///
320/// discord.js counterpart: `RESTPutAPIGuildMemberJSONBody` (discord-api-types).
321#[derive(Clone, PartialEq, Eq, Hash, Serialize)]
322#[non_exhaustive]
323pub struct AddGuildMember {
324    /// The `OAuth2` access token of the user, granted to the bot's application with the
325    /// `guilds.join` scope.
326    pub access_token: String,
327    /// The nickname (needs `MANAGE_NICKNAMES`).
328    #[serde(skip_serializing_if = "Option::is_none")]
329    pub nick: Option<CompactString>,
330    /// The roles (needs `MANAGE_ROLES`).
331    #[serde(skip_serializing_if = "Vec::is_empty")]
332    pub roles: Vec<RoleId>,
333    /// Whether the member is muted in voice channels (needs `MUTE_MEMBERS`).
334    #[serde(skip_serializing_if = "Option::is_none")]
335    pub mute: Option<bool>,
336    /// Whether the member is deafened in voice channels (needs `DEAFEN_MEMBERS`).
337    #[serde(skip_serializing_if = "Option::is_none")]
338    pub deaf: Option<bool>,
339}
340
341impl AddGuildMember {
342    /// Adds the user whose access token is `access_token`.
343    ///
344    /// discord.js counterpart: `AddGuildMemberOptions`.
345    #[must_use]
346    pub fn new(access_token: impl Into<String>) -> Self {
347        Self {
348            access_token: access_token.into(),
349            nick: None,
350            roles: Vec::new(),
351            mute: None,
352            deaf: None,
353        }
354    }
355}
356
357impl fmt::Debug for AddGuildMember {
358    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
359        f.debug_struct("AddGuildMember")
360            .field("access_token", &"<redacted>")
361            .field("nick", &self.nick)
362            .field("roles", &self.roles)
363            .field("mute", &self.mute)
364            .field("deaf", &self.deaf)
365            .finish()
366    }
367}
368
369/// The body of [Modify Guild Member](https://docs.discord.com/developers/resources/guild#modify-guild-member).
370///
371/// Every field is optional and can be cleared.
372///
373/// discord.js counterpart: `GuildMemberEditOptions`.
374///
375/// # Examples
376///
377/// ```
378/// use djs_model::{rest::ModifyGuildMember, util::{Patch, Timestamp}};
379///
380/// // A timeout until one hour after 2027-01-15 08:00 UTC.
381/// let until = Timestamp::from_unix_secs(1_800_000_000 + 3600).unwrap();
382/// let mut body = ModifyGuildMember::default();
383/// body.communication_disabled_until = Patch::Set(until);
384/// assert_eq!(
385///     serde_json::to_string(&body).unwrap(),
386///     r#"{"communication_disabled_until":"2027-01-15T09:00:00.000000+00:00"}"#
387/// );
388/// ```
389#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize)]
390#[non_exhaustive]
391pub struct ModifyGuildMember {
392    /// The nickname (needs `MANAGE_NICKNAMES`).
393    #[serde(skip_serializing_if = "Patch::is_keep")]
394    pub nick: Patch<CompactString>,
395    /// The roles, all of them (needs `MANAGE_ROLES`).
396    #[serde(skip_serializing_if = "Patch::is_keep")]
397    pub roles: Patch<Vec<RoleId>>,
398    /// Whether the member is muted in voice channels (needs `MUTE_MEMBERS`; the member must
399    /// be connected).
400    #[serde(skip_serializing_if = "Patch::is_keep")]
401    pub mute: Patch<bool>,
402    /// Whether the member is deafened in voice channels (needs `DEAFEN_MEMBERS`; the member
403    /// must be connected).
404    #[serde(skip_serializing_if = "Patch::is_keep")]
405    pub deaf: Patch<bool>,
406    /// The voice channel to move the member to (needs `MOVE_MEMBERS` and `CONNECT` there);
407    /// [`Patch::Clear`] disconnects them.
408    #[serde(skip_serializing_if = "Patch::is_keep")]
409    pub channel_id: Patch<ChannelId>,
410    /// When the member's [timeout](https://support.discord.com/hc/en-us/articles/4413305239191)
411    /// ends (at most 28 days ahead; needs `MODERATE_MEMBERS`); [`Patch::Clear`] ends it.
412    #[serde(skip_serializing_if = "Patch::is_keep")]
413    pub communication_disabled_until: Patch<Timestamp>,
414    /// The member's flags (only some can be set).
415    #[serde(skip_serializing_if = "Patch::is_keep")]
416    pub flags: Patch<MemberFlags>,
417}
418
419/// The body of [Modify Current Member](https://docs.discord.com/developers/resources/guild#modify-current-member):
420/// the bot's own guild profile.
421///
422/// discord.js counterpart: `GuildMemberManager#editMe`.
423#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize)]
424#[non_exhaustive]
425pub struct ModifyCurrentMember {
426    /// The nickname (needs `CHANGE_NICKNAME`).
427    #[serde(skip_serializing_if = "Patch::is_keep")]
428    pub nick: Patch<CompactString>,
429    /// The guild banner.
430    #[serde(skip_serializing_if = "Patch::is_keep")]
431    pub banner: Patch<ImageData>,
432    /// The guild avatar.
433    #[serde(skip_serializing_if = "Patch::is_keep")]
434    pub avatar: Patch<ImageData>,
435    /// The guild bio.
436    #[serde(skip_serializing_if = "Patch::is_keep")]
437    pub bio: Patch<CompactString>,
438}
439
440/// The query of [Get Guild Bans](https://docs.discord.com/developers/resources/guild#get-guild-bans).
441///
442/// Bans are sorted by user ID; with both `before` and `after`, only `before` is used.
443///
444/// discord.js counterpart: `RESTGetAPIGuildBansQuery` (discord-api-types).
445#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
446#[non_exhaustive]
447pub struct GetGuildBans {
448    /// The page size (max 1000, the default).
449    pub limit: Option<u16>,
450    /// Bans of users with a lower ID.
451    pub before: Option<UserId>,
452    /// Bans of users with a higher ID.
453    pub after: Option<UserId>,
454}
455
456/// The body of [Create Guild Ban](https://docs.discord.com/developers/resources/guild#create-guild-ban).
457///
458/// discord.js counterpart: `RESTPutAPIGuildBanJSONBody` (discord-api-types).
459#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize)]
460#[non_exhaustive]
461pub struct CreateGuildBan {
462    /// How many seconds of the user's recent messages to delete (0-604800, 7 days).
463    #[serde(skip_serializing_if = "Option::is_none")]
464    pub delete_message_seconds: Option<u32>,
465}
466
467/// The body of [Bulk Guild Ban](https://docs.discord.com/developers/resources/guild#bulk-guild-ban).
468///
469/// discord.js counterpart: `RESTPostAPIGuildBulkBanJSONBody` (discord-api-types).
470#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize)]
471#[non_exhaustive]
472pub struct BulkGuildBan {
473    /// The users to ban (max 200).
474    pub user_ids: Vec<UserId>,
475    /// How many seconds of their recent messages to delete (0-604800, 7 days).
476    #[serde(skip_serializing_if = "Option::is_none")]
477    pub delete_message_seconds: Option<u32>,
478}
479
480impl BulkGuildBan {
481    /// Bans `user_ids`.
482    ///
483    /// discord.js counterpart: `GuildBanManager#bulkCreate`.
484    #[must_use]
485    pub const fn new(user_ids: Vec<UserId>) -> Self {
486        Self {
487            user_ids,
488            delete_message_seconds: None,
489        }
490    }
491}
492
493/// The [response](https://docs.discord.com/developers/resources/guild#bulk-guild-ban-bulk-ban-response)
494/// of Bulk Guild Ban.
495///
496/// discord.js counterpart: `BulkBanResult`.
497#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
498#[non_exhaustive]
499pub struct BulkBanResponse {
500    /// The users that were banned.
501    pub banned_users: Vec<UserId>,
502    /// The users that could not be banned.
503    pub failed_users: Vec<UserId>,
504}
505
506/// The body of [Create Guild Role](https://docs.discord.com/developers/resources/guild#create-guild-role).
507///
508/// Every field is optional (Discord's defaults: `new role`, the `@everyone` permissions, no
509/// color).
510///
511/// discord.js counterpart: `RoleCreateOptions`.
512#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize)]
513#[non_exhaustive]
514pub struct CreateGuildRole {
515    /// The name (max 100 characters).
516    #[serde(skip_serializing_if = "Option::is_none")]
517    pub name: Option<CompactString>,
518    /// The permissions.
519    #[serde(skip_serializing_if = "Option::is_none")]
520    pub permissions: Option<Permissions>,
521    /// The colors.
522    #[serde(skip_serializing_if = "Option::is_none")]
523    pub colors: Option<RoleColors>,
524    /// Whether members with the role are shown separately in the member list.
525    #[serde(skip_serializing_if = "core::ops::Not::not")]
526    pub hoist: bool,
527    /// The icon (needs the `ROLE_ICONS` feature).
528    #[serde(skip_serializing_if = "Option::is_none")]
529    pub icon: Option<ImageData>,
530    /// A Unicode emoji as the icon (needs the `ROLE_ICONS` feature).
531    #[serde(skip_serializing_if = "Option::is_none")]
532    pub unicode_emoji: Option<CompactString>,
533    /// Whether everyone can mention the role.
534    #[serde(skip_serializing_if = "core::ops::Not::not")]
535    pub mentionable: bool,
536}
537
538/// One entry of [Modify Guild Role Positions](https://docs.discord.com/developers/resources/guild#modify-guild-role-positions).
539///
540/// discord.js counterpart: an element of `RESTPatchAPIGuildRolePositionsJSONBody` (discord-api-types).
541#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize)]
542#[non_exhaustive]
543pub struct ModifyGuildRolePosition {
544    /// The role.
545    pub id: RoleId,
546    /// The new position.
547    #[serde(skip_serializing_if = "Patch::is_keep")]
548    pub position: Patch<i32>,
549}
550
551impl ModifyGuildRolePosition {
552    /// Moves role `id` to `position`.
553    ///
554    /// discord.js counterpart: `RolePosition`.
555    #[must_use]
556    pub const fn new(id: RoleId, position: i32) -> Self {
557        Self {
558            id,
559            position: Patch::Set(position),
560        }
561    }
562}
563
564/// The body of [Modify Guild Role](https://docs.discord.com/developers/resources/guild#modify-guild-role).
565///
566/// Every field is optional; [`Patch`] fields can also be cleared.
567///
568/// discord.js counterpart: `RoleEditOptions`.
569#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize)]
570#[non_exhaustive]
571pub struct ModifyGuildRole {
572    /// The name (max 100 characters).
573    #[serde(skip_serializing_if = "Option::is_none")]
574    pub name: Option<CompactString>,
575    /// The permissions.
576    #[serde(skip_serializing_if = "Option::is_none")]
577    pub permissions: Option<Permissions>,
578    /// The colors; [`Patch::Clear`] removes them.
579    #[serde(skip_serializing_if = "Patch::is_keep")]
580    pub colors: Patch<RoleColors>,
581    /// Whether members with the role are shown separately in the member list.
582    #[serde(skip_serializing_if = "Option::is_none")]
583    pub hoist: Option<bool>,
584    /// The icon (needs the `ROLE_ICONS` feature).
585    #[serde(skip_serializing_if = "Patch::is_keep")]
586    pub icon: Patch<ImageData>,
587    /// A Unicode emoji as the icon (needs the `ROLE_ICONS` feature).
588    #[serde(skip_serializing_if = "Patch::is_keep")]
589    pub unicode_emoji: Patch<CompactString>,
590    /// Whether everyone can mention the role.
591    #[serde(skip_serializing_if = "Option::is_none")]
592    pub mentionable: Option<bool>,
593}
594
595/// The query of [Get Guild Prune Count](https://docs.discord.com/developers/resources/guild#get-guild-prune-count).
596///
597/// By default members with roles are never pruned; members whose roles are all in
598/// [`include_roles`](Self::include_roles) are.
599///
600/// discord.js counterpart: `RESTGetAPIGuildPruneCountQuery` (discord-api-types).
601#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
602#[non_exhaustive]
603pub struct GetGuildPruneCount {
604    /// Days of inactivity (1-30; Discord's default: 7).
605    pub days: Option<u8>,
606    /// Roles whose members may be pruned too (sent comma-separated).
607    pub include_roles: Vec<RoleId>,
608}
609
610/// The body of [Begin Guild Prune](https://docs.discord.com/developers/resources/guild#begin-guild-prune).
611///
612/// The reason is the `reason` parameter of the method (the body field is deprecated).
613///
614/// discord.js counterpart: `RESTPostAPIGuildPruneJSONBody` (discord-api-types).
615#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize)]
616#[non_exhaustive]
617pub struct BeginGuildPrune {
618    /// Days of inactivity (1-30; Discord's default: 7).
619    #[serde(skip_serializing_if = "Option::is_none")]
620    pub days: Option<u8>,
621    /// Whether to return the number of pruned members (Discord's default: yes;
622    /// discouraged for large guilds).
623    #[serde(skip_serializing_if = "Option::is_none")]
624    pub compute_prune_count: Option<bool>,
625    /// Roles whose members may be pruned too.
626    #[serde(skip_serializing_if = "Vec::is_empty")]
627    pub include_roles: Vec<RoleId>,
628}
629
630/// The body of [Modify Guild Widget](https://docs.discord.com/developers/resources/guild#modify-guild-widget).
631///
632/// discord.js counterpart: `RESTPatchAPIGuildWidgetSettingsJSONBody` (discord-api-types).
633#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize)]
634#[non_exhaustive]
635pub struct ModifyGuildWidget {
636    /// Whether the widget is enabled.
637    #[serde(skip_serializing_if = "Option::is_none")]
638    pub enabled: Option<bool>,
639    /// The channel the widget's invite leads to.
640    #[serde(skip_serializing_if = "Patch::is_keep")]
641    pub channel_id: Patch<ChannelId>,
642}
643
644/// The response of [Get Guild Vanity URL](https://docs.discord.com/developers/resources/guild#get-guild-vanity-url).
645///
646/// discord.js counterpart: `RESTGetAPIGuildVanityUrlResult` (discord-api-types).
647#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
648#[non_exhaustive]
649pub struct VanityUrl {
650    /// The vanity invite code (`discord.gg/<code>`), `None` when not set.
651    pub code: Option<CompactString>,
652    /// How many times it was used.
653    pub uses: u32,
654}
655
656/// The body of [Modify Guild Welcome Screen](https://docs.discord.com/developers/resources/guild#modify-guild-welcome-screen).
657///
658/// Every field is optional and can be cleared.
659///
660/// discord.js counterpart: `RESTPatchAPIGuildWelcomeScreenJSONBody` (discord-api-types).
661#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize)]
662#[non_exhaustive]
663pub struct ModifyGuildWelcomeScreen {
664    /// Whether the welcome screen is enabled.
665    #[serde(skip_serializing_if = "Patch::is_keep")]
666    pub enabled: Patch<bool>,
667    /// The suggested channels (all of them).
668    #[serde(skip_serializing_if = "Patch::is_keep")]
669    pub welcome_channels: Patch<Vec<WelcomeScreenChannel>>,
670    /// The guild description shown on the welcome screen.
671    #[serde(skip_serializing_if = "Patch::is_keep")]
672    pub description: Patch<CompactString>,
673}
674
675/// The body of [Modify Guild Onboarding](https://docs.discord.com/developers/resources/guild#modify-guild-onboarding).
676///
677/// When enabled, onboarding needs at least 7 default channels, 5 of which `@everyone` can
678/// send messages in (with the default [`mode`](Self::mode)).
679///
680/// discord.js counterpart: `GuildOnboardingEditOptions`.
681#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize)]
682#[non_exhaustive]
683pub struct ModifyGuildOnboarding {
684    /// The prompts (all of them).
685    #[serde(skip_serializing_if = "Option::is_none")]
686    pub prompts: Option<Vec<OnboardingPromptData>>,
687    /// The channels new members get automatically.
688    #[serde(skip_serializing_if = "Option::is_none")]
689    pub default_channel_ids: Option<Vec<ChannelId>>,
690    /// Whether onboarding is enabled.
691    #[serde(skip_serializing_if = "Option::is_none")]
692    pub enabled: Option<bool>,
693    /// Which channels count towards the requirements.
694    #[serde(skip_serializing_if = "Option::is_none")]
695    pub mode: Option<OnboardingMode>,
696}
697
698/// An [onboarding prompt](https://docs.discord.com/developers/resources/guild#guild-onboarding-object-onboarding-prompt-structure)
699/// in a request (D-118).
700///
701/// Discord requires an ID even for new prompts: a prompt without one gets an ID generated
702/// from the current time when it is serialized, like discord.js does.
703///
704/// discord.js counterpart: `GuildOnboardingPromptData`.
705#[derive(Clone, Debug, PartialEq, Eq, Hash)]
706#[non_exhaustive]
707pub struct OnboardingPromptData {
708    /// The ID of an existing prompt; `None` for a new one.
709    pub id: Option<GenericId>,
710    /// How the options are shown.
711    pub kind: PromptType,
712    /// The options.
713    pub options: Vec<PromptOptionData>,
714    /// The title.
715    pub title: CompactString,
716    /// Whether members can only pick one option.
717    pub single_select: bool,
718    /// Whether members must answer before finishing onboarding.
719    pub required: bool,
720    /// Whether the prompt is part of onboarding (otherwise only in Channels & Roles).
721    pub in_onboarding: bool,
722}
723
724impl OnboardingPromptData {
725    /// A new multiple-choice prompt titled `title` with `options`, shown during onboarding.
726    ///
727    /// discord.js counterpart: `GuildOnboardingPromptData`.
728    #[must_use]
729    pub fn new(title: impl Into<CompactString>, options: Vec<PromptOptionData>) -> Self {
730        Self {
731            id: None,
732            kind: PromptType::MultipleChoice,
733            options,
734            title: title.into(),
735            single_select: false,
736            required: false,
737            in_onboarding: true,
738        }
739    }
740}
741
742impl From<OnboardingPrompt> for OnboardingPromptData {
743    fn from(prompt: OnboardingPrompt) -> Self {
744        let OnboardingPrompt {
745            id,
746            kind,
747            options,
748            title,
749            single_select,
750            required,
751            in_onboarding,
752            ..
753        } = prompt;
754        Self {
755            id: Some(id),
756            kind,
757            options: options.into_iter().map(Into::into).collect(),
758            title,
759            single_select,
760            required,
761            in_onboarding,
762        }
763    }
764}
765
766impl Serialize for OnboardingPromptData {
767    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
768        #[derive(Serialize)]
769        struct Wire<'a> {
770            id: GenericId,
771            #[serde(rename = "type")]
772            kind: PromptType,
773            options: &'a [PromptOptionData],
774            title: &'a str,
775            single_select: bool,
776            required: bool,
777            in_onboarding: bool,
778        }
779
780        // Destructured without `..`, so a new field cannot be forgotten here.
781        let Self {
782            id,
783            kind,
784            options,
785            title,
786            single_select,
787            required,
788            in_onboarding,
789        } = self;
790        Wire {
791            id: id.unwrap_or_else(generated_id),
792            kind: *kind,
793            options,
794            title,
795            single_select: *single_select,
796            required: *required,
797            in_onboarding: *in_onboarding,
798        }
799        .serialize(serializer)
800    }
801}
802
803/// A fresh, unique snowflake for a new onboarding prompt: the current time, plus a
804/// process-wide counter in the increment bits so prompts serialized in the same millisecond
805/// still differ.
806fn generated_id() -> GenericId {
807    static INCREMENT: AtomicU64 = AtomicU64::new(0);
808    let now_ms = SystemTime::now()
809        .duration_since(UNIX_EPOCH)
810        .map_or(0, |since| {
811            u64::try_from(since.as_millis()).unwrap_or(u64::MAX)
812        });
813    let base = GenericId::from_timestamp_ms(now_ms).map_or(1 << 22, GenericId::get);
814    GenericId::new(base | (INCREMENT.fetch_add(1, Ordering::Relaxed) & 0xfff))
815}
816
817/// A [prompt option](https://docs.discord.com/developers/resources/guild#guild-onboarding-object-prompt-option-structure)
818/// in a request (D-118): the emoji is given by its parts, as Discord requires here.
819///
820/// discord.js counterpart: `GuildOnboardingPromptOptionData`.
821#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize)]
822#[non_exhaustive]
823pub struct PromptOptionData {
824    /// The ID of an existing option; `None` for a new one.
825    #[serde(skip_serializing_if = "Option::is_none")]
826    pub id: Option<GenericId>,
827    /// The channels a member is added to when they pick the option.
828    pub channel_ids: Vec<ChannelId>,
829    /// The roles a member gets when they pick the option.
830    pub role_ids: Vec<RoleId>,
831    /// The custom emoji's ID.
832    #[serde(skip_serializing_if = "Option::is_none")]
833    pub emoji_id: Option<EmojiId>,
834    /// The custom emoji's name, or the Unicode emoji.
835    #[serde(skip_serializing_if = "Option::is_none")]
836    pub emoji_name: Option<CompactString>,
837    /// Whether the custom emoji is animated.
838    #[serde(skip_serializing_if = "Option::is_none")]
839    pub emoji_animated: Option<bool>,
840    /// The title.
841    pub title: CompactString,
842    /// The description.
843    pub description: Option<CompactString>,
844}
845
846impl PromptOptionData {
847    /// A new option titled `title` that gives nothing yet.
848    ///
849    /// discord.js counterpart: `GuildOnboardingPromptOptionData`.
850    #[must_use]
851    pub fn new(title: impl Into<CompactString>) -> Self {
852        Self {
853            id: None,
854            channel_ids: Vec::new(),
855            role_ids: Vec::new(),
856            emoji_id: None,
857            emoji_name: None,
858            emoji_animated: None,
859            title: title.into(),
860            description: None,
861        }
862    }
863}
864
865impl From<PromptOption> for PromptOptionData {
866    fn from(option: PromptOption) -> Self {
867        let PromptOption {
868            id,
869            channel_ids,
870            role_ids,
871            emoji,
872            title,
873            description,
874            ..
875        } = option;
876        let (emoji_id, emoji_name, emoji_animated) = match emoji {
877            Some(PartialEmoji::Custom { id, name, animated }) => (Some(id), name, Some(animated)),
878            Some(PartialEmoji::Unicode { name }) => (None, Some(name), None),
879            None => (None, None, None),
880        };
881        Self {
882            id: Some(id),
883            channel_ids,
884            role_ids,
885            emoji_id,
886            emoji_name,
887            emoji_animated,
888            title,
889            description,
890        }
891    }
892}
893
894/// The body of [Modify Guild Incident Actions](https://docs.discord.com/developers/resources/guild#modify-guild-incident-actions).
895///
896/// Both actions last at most 24 hours; [`Patch::Clear`] ends one.
897///
898/// discord.js counterpart: `RESTPutAPIGuildIncidentActionsJSONBody` (discord-api-types).
899#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize)]
900#[non_exhaustive]
901pub struct ModifyGuildIncidentActions {
902    /// Until when invites are disabled.
903    #[serde(skip_serializing_if = "Patch::is_keep")]
904    pub invites_disabled_until: Patch<Timestamp>,
905    /// Until when direct messages between members are disabled.
906    #[serde(skip_serializing_if = "Patch::is_keep")]
907    pub dms_disabled_until: Patch<Timestamp>,
908}
909
910#[cfg(test)]
911mod tests {
912    use super::*;
913
914    #[test]
915    fn modify_guild_and_member() {
916        let guild = ModifyGuild {
917            name: Some("Rustaceans".into()),
918            icon: Patch::Clear,
919            preferred_locale: Patch::Set(Locale::Polish),
920            ..ModifyGuild::default()
921        };
922        assert_eq!(
923            serde_json::to_string(&guild).unwrap(),
924            r#"{"name":"Rustaceans","icon":null,"preferred_locale":"pl"}"#
925        );
926
927        let member = ModifyGuildMember {
928            nick: Patch::Clear,
929            roles: Patch::Set(vec![RoleId::new(1)]),
930            channel_id: Patch::Clear,
931            ..ModifyGuildMember::default()
932        };
933        assert_eq!(
934            serde_json::to_string(&member).unwrap(),
935            r#"{"nick":null,"roles":["1"],"channel_id":null}"#
936        );
937
938        let add = AddGuildMember::new("super-secret");
939        assert!(!format!("{add:?}").contains("super-secret"));
940    }
941
942    #[test]
943    fn positions_and_roles() {
944        let mut moved = ModifyGuildChannelPosition::new(ChannelId::new(2), 0);
945        moved.parent_id = Patch::Clear;
946        moved.lock_permissions = Patch::Set(true);
947        assert_eq!(
948            serde_json::to_string(&[moved]).unwrap(),
949            r#"[{"id":"2","position":0,"lock_permissions":true,"parent_id":null}]"#
950        );
951
952        let role = CreateGuildRole {
953            name: Some("mods".into()),
954            colors: Some(RoleColors::solid(0x0000_ff00)),
955            hoist: true,
956            ..CreateGuildRole::default()
957        };
958        assert_eq!(
959            serde_json::to_string(&role).unwrap(),
960            concat!(
961                r#"{"name":"mods","colors":{"primary_color":65280,"secondary_color":null,"#,
962                r#""tertiary_color":null},"hoist":true}"#
963            )
964        );
965        let modify = ModifyGuildRole {
966            unicode_emoji: Patch::Clear,
967            ..ModifyGuildRole::default()
968        };
969        assert_eq!(
970            serde_json::to_string(&modify).unwrap(),
971            r#"{"unicode_emoji":null}"#
972        );
973    }
974
975    #[test]
976    fn new_prompts_get_unique_generated_ids() {
977        let mut option = PromptOptionData::new("Rust");
978        option.emoji_name = Some("🦀".into());
979        let prompt = OnboardingPromptData::new("Languages", vec![option]);
980        let first: serde_json::Value = serde_json::to_value(&prompt).unwrap();
981        let second: serde_json::Value = serde_json::to_value(&prompt).unwrap();
982        assert_ne!(first["id"], second["id"]);
983        let id: u64 = first["id"].as_str().unwrap().parse().unwrap();
984        let now_ms = SystemTime::now()
985            .duration_since(UNIX_EPOCH)
986            .unwrap()
987            .as_millis();
988        let id_ms = u128::from(GenericId::new(id).timestamp_ms());
989        assert!(now_ms.abs_diff(id_ms) < 60_000, "{id_ms} vs {now_ms}");
990        assert_eq!(
991            first["options"],
992            serde_json::json!([{
993                "channel_ids": [], "role_ids": [], "emoji_name": "🦀", "title": "Rust",
994                "description": null
995            }])
996        );
997
998        let existing = OnboardingPromptData {
999            id: Some(GenericId::new(42)),
1000            ..prompt
1001        };
1002        assert_eq!(serde_json::to_value(&existing).unwrap()["id"], "42");
1003    }
1004}