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