Skip to main content

djs_model/rest/
guild_scheduled_event.rs

1//! Bodies and queries of the [guild scheduled event endpoints](https://docs.discord.com/developers/resources/guild-scheduled-event).
2
3use compact_str::CompactString;
4use serde::Serialize;
5
6use crate::{
7    guild_scheduled_event::{
8        EntityMetadata, EntityType, PrivacyLevel, RecurrenceFrequency, RecurrenceMonth,
9        RecurrenceNWeekday, RecurrenceRule, RecurrenceWeekday, Status,
10    },
11    id::{ChannelId, UserId},
12    util::{ImageData, Patch, Timestamp},
13};
14
15/// The query of [List Scheduled Events for Guild](https://docs.discord.com/developers/resources/guild-scheduled-event#list-scheduled-events-for-guild).
16///
17/// discord.js counterpart: `RESTGetAPIGuildScheduledEventsQuery` (discord-api-types).
18#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
19#[non_exhaustive]
20pub struct ListScheduledEventsForGuild {
21    /// Whether to include each event's [`user_count`](crate::guild_scheduled_event::GuildScheduledEvent::user_count).
22    pub with_user_count: Option<bool>,
23}
24
25/// The query of [Get Guild Scheduled Event](https://docs.discord.com/developers/resources/guild-scheduled-event#get-guild-scheduled-event).
26///
27/// discord.js counterpart: `RESTGetAPIGuildScheduledEventQuery` (discord-api-types).
28#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
29#[non_exhaustive]
30pub struct GetGuildScheduledEvent {
31    /// Whether to include the event's [`user_count`](crate::guild_scheduled_event::GuildScheduledEvent::user_count).
32    pub with_user_count: Option<bool>,
33}
34
35/// The query of [Get Guild Scheduled Event Users](https://docs.discord.com/developers/resources/guild-scheduled-event#get-guild-scheduled-event-users).
36///
37/// Users are sorted by ID; with both `before` and `after`, only `before` is used.
38///
39/// discord.js counterpart: `RESTGetAPIGuildScheduledEventUsersQuery` (discord-api-types).
40#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
41#[non_exhaustive]
42pub struct GetGuildScheduledEventUsers {
43    /// The page size (max 100, the default).
44    pub limit: Option<u8>,
45    /// Whether to include each user's member data in the guild.
46    pub with_member: Option<bool>,
47    /// Users with a lower ID.
48    pub before: Option<UserId>,
49    /// Users with a higher ID.
50    pub after: Option<UserId>,
51}
52
53/// How a scheduled event repeats, as sent to Discord (D-124): the settable fields of a
54/// [`RecurrenceRule`].
55///
56/// Discord accepts only some combinations; the constructors build exactly those shapes:
57/// [`daily`](Self::daily), [`daily_on`](Self::daily_on) (a known set of weekdays),
58/// [`weekly`](Self::weekly), [`every_other_week`](Self::every_other_week),
59/// [`monthly`](Self::monthly) (the n-th weekday) and [`yearly`](Self::yearly).
60/// [`From<RecurrenceRule>`](#impl-From<RecurrenceRule>-for-RecurrenceRuleData) keeps the rule of
61/// an existing event.
62///
63/// discord.js counterpart: `GuildScheduledEventRecurrenceRuleOptions`.
64///
65/// # Examples
66///
67/// ```
68/// use djs_model::{
69///     guild_scheduled_event::RecurrenceWeekday, rest::RecurrenceRuleData, util::Timestamp,
70/// };
71///
72/// let start = Timestamp::parse("2026-11-17T18:00:00Z")?;
73/// let rule = RecurrenceRuleData::monthly(start, 3, RecurrenceWeekday::Tuesday);
74/// assert_eq!(
75///     serde_json::to_string(&rule)?,
76///     r#"{"start":"2026-11-17T18:00:00.000000+00:00","frequency":1,"interval":1,"by_n_weekday":[{"n":3,"day":1}]}"#
77/// );
78/// # Ok::<(), Box<dyn std::error::Error>>(())
79/// ```
80#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
81#[non_exhaustive]
82pub struct RecurrenceRuleData {
83    /// When the recurrence starts (the first occurrence).
84    pub start: Timestamp,
85    /// How often the event repeats.
86    pub frequency: RecurrenceFrequency,
87    /// The spacing between occurrences in units of `frequency`; only weekly events may use 2.
88    pub interval: u16,
89    /// The weekdays to repeat on (daily: a known set; weekly: one day).
90    #[serde(skip_serializing_if = "Vec::is_empty")]
91    pub by_weekday: Vec<RecurrenceWeekday>,
92    /// The n-th weekday of the month to repeat on (monthly: one entry).
93    #[serde(skip_serializing_if = "Vec::is_empty")]
94    pub by_n_weekday: Vec<RecurrenceNWeekday>,
95    /// The month to repeat in (yearly: one entry, with [`by_month_day`](Self::by_month_day)).
96    #[serde(skip_serializing_if = "Vec::is_empty")]
97    pub by_month: Vec<RecurrenceMonth>,
98    /// The day of the month to repeat on (yearly: one entry, with [`by_month`](Self::by_month)).
99    #[serde(skip_serializing_if = "Vec::is_empty")]
100    pub by_month_day: Vec<u8>,
101}
102
103impl RecurrenceRuleData {
104    const fn new(start: Timestamp, frequency: RecurrenceFrequency, interval: u16) -> Self {
105        Self {
106            start,
107            frequency,
108            interval,
109            by_weekday: Vec::new(),
110            by_n_weekday: Vec::new(),
111            by_month: Vec::new(),
112            by_month_day: Vec::new(),
113        }
114    }
115
116    /// Every day.
117    ///
118    /// discord.js counterpart: `GuildScheduledEventRecurrenceRuleOptions` with `frequency: Daily`.
119    #[must_use]
120    pub const fn daily(start: Timestamp) -> Self {
121        Self::new(start, RecurrenceFrequency::Daily, 1)
122    }
123
124    /// Every day of a set of weekdays. Discord accepts these sets only: Monday–Friday,
125    /// Tuesday–Saturday, Sunday–Thursday, Friday and Saturday, Saturday and Sunday, Sunday and
126    /// Monday.
127    ///
128    /// discord.js counterpart: `GuildScheduledEventRecurrenceRuleOptions` with `frequency: Daily` and `byWeekday`.
129    #[must_use]
130    pub fn daily_on(start: Timestamp, days: impl IntoIterator<Item = RecurrenceWeekday>) -> Self {
131        Self {
132            by_weekday: days.into_iter().collect(),
133            ..Self::daily(start)
134        }
135    }
136
137    /// Every week on `day`.
138    ///
139    /// discord.js counterpart: `GuildScheduledEventRecurrenceRuleOptions` with `frequency: Weekly`.
140    #[must_use]
141    pub fn weekly(start: Timestamp, day: RecurrenceWeekday) -> Self {
142        Self {
143            by_weekday: vec![day],
144            ..Self::new(start, RecurrenceFrequency::Weekly, 1)
145        }
146    }
147
148    /// Every other week on `day`.
149    ///
150    /// discord.js counterpart: `GuildScheduledEventRecurrenceRuleOptions` with `frequency: Weekly` and `interval: 2`.
151    #[must_use]
152    pub fn every_other_week(start: Timestamp, day: RecurrenceWeekday) -> Self {
153        Self {
154            by_weekday: vec![day],
155            ..Self::new(start, RecurrenceFrequency::Weekly, 2)
156        }
157    }
158
159    /// Every month on the `n`-th (1-5) `day`, e.g. the third Tuesday.
160    ///
161    /// discord.js counterpart: `GuildScheduledEventRecurrenceRuleOptions` with `frequency: Monthly`.
162    #[must_use]
163    pub fn monthly(start: Timestamp, n: u8, day: RecurrenceWeekday) -> Self {
164        Self {
165            by_n_weekday: vec![RecurrenceNWeekday::new(n, day)],
166            ..Self::new(start, RecurrenceFrequency::Monthly, 1)
167        }
168    }
169
170    /// Every year on `day` of `month`.
171    ///
172    /// discord.js counterpart: `GuildScheduledEventRecurrenceRuleOptions` with `frequency: Yearly`.
173    #[must_use]
174    pub fn yearly(start: Timestamp, month: RecurrenceMonth, day: u8) -> Self {
175        Self {
176            by_month: vec![month],
177            by_month_day: vec![day],
178            ..Self::new(start, RecurrenceFrequency::Yearly, 1)
179        }
180    }
181}
182
183impl From<RecurrenceRule> for RecurrenceRuleData {
184    /// Keeps the settable fields of an existing rule (not `end`, `count`, `by_year_day`).
185    fn from(rule: RecurrenceRule) -> Self {
186        Self {
187            start: rule.start,
188            frequency: rule.frequency,
189            interval: rule.interval,
190            by_weekday: rule.by_weekday.unwrap_or_default(),
191            by_n_weekday: rule.by_n_weekday.unwrap_or_default(),
192            by_month: rule.by_month.unwrap_or_default(),
193            by_month_day: rule.by_month_day.unwrap_or_default(),
194        }
195    }
196}
197
198/// The body of [Create Guild Scheduled Event](https://docs.discord.com/developers/resources/guild-scheduled-event#create-guild-scheduled-event).
199///
200/// Build it with the constructor of the event's place (D-125) — [`stage`](Self::stage),
201/// [`voice`](Self::voice) or [`external`](Self::external) — which sets the fields that place
202/// requires; the rest are optional. A guild can have at most 100 scheduled or active events.
203///
204/// discord.js counterpart: `GuildScheduledEventCreateOptions`.
205///
206/// # Examples
207///
208/// ```
209/// use djs_model::{rest::CreateGuildScheduledEvent, util::Timestamp};
210///
211/// let start = Timestamp::parse("2026-11-20T18:00:00Z")?;
212/// let end = Timestamp::parse("2026-11-20T20:00:00Z")?;
213/// let mut body = CreateGuildScheduledEvent::external("Rust meetup, Kraków", "Meetup", start, end);
214/// body.description = Some("Talks and pizza".into());
215/// let json = serde_json::to_string(&body)?;
216/// assert!(json.starts_with(r#"{"entity_metadata":{"location":"Rust meetup, Kraków"},"name":"Meetup","privacy_level":2,"#));
217/// assert!(json.ends_with(r#""description":"Talks and pizza","entity_type":3}"#));
218/// # Ok::<(), Box<dyn std::error::Error>>(())
219/// ```
220#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
221#[non_exhaustive]
222pub struct CreateGuildScheduledEvent {
223    /// The stage or voice channel (not for external events).
224    #[serde(skip_serializing_if = "Option::is_none")]
225    pub channel_id: Option<ChannelId>,
226    /// The location of an external event.
227    #[serde(skip_serializing_if = "Option::is_none")]
228    pub entity_metadata: Option<EntityMetadata>,
229    /// The name (1-100 characters).
230    pub name: CompactString,
231    /// Who can see the event (only [`PrivacyLevel::GuildOnly`] exists).
232    pub privacy_level: PrivacyLevel,
233    /// When the event starts.
234    pub scheduled_start_time: Timestamp,
235    /// When the event ends (required for external events).
236    #[serde(skip_serializing_if = "Option::is_none")]
237    pub scheduled_end_time: Option<Timestamp>,
238    /// The description (1-1000 characters).
239    #[serde(skip_serializing_if = "Option::is_none")]
240    pub description: Option<CompactString>,
241    /// Where the event takes place.
242    pub entity_type: EntityType,
243    /// The cover image.
244    #[serde(skip_serializing_if = "Option::is_none")]
245    pub image: Option<ImageData>,
246    /// How the event repeats.
247    #[serde(skip_serializing_if = "Option::is_none")]
248    pub recurrence_rule: Option<RecurrenceRuleData>,
249}
250
251impl CreateGuildScheduledEvent {
252    fn new(name: CompactString, start: Timestamp, entity_type: EntityType) -> Self {
253        Self {
254            channel_id: None,
255            entity_metadata: None,
256            name,
257            privacy_level: PrivacyLevel::GuildOnly,
258            scheduled_start_time: start,
259            scheduled_end_time: None,
260            description: None,
261            entity_type,
262            image: None,
263            recurrence_rule: None,
264        }
265    }
266
267    /// An event in the stage channel `channel_id`.
268    ///
269    /// discord.js counterpart: `GuildScheduledEventCreateOptions` with a stage channel.
270    #[must_use]
271    pub fn stage(channel_id: ChannelId, name: impl Into<CompactString>, start: Timestamp) -> Self {
272        Self {
273            channel_id: Some(channel_id),
274            ..Self::new(name.into(), start, EntityType::StageInstance)
275        }
276    }
277
278    /// An event in the voice channel `channel_id`.
279    ///
280    /// discord.js counterpart: `GuildScheduledEventCreateOptions` with a voice channel.
281    #[must_use]
282    pub fn voice(channel_id: ChannelId, name: impl Into<CompactString>, start: Timestamp) -> Self {
283        Self {
284            channel_id: Some(channel_id),
285            ..Self::new(name.into(), start, EntityType::Voice)
286        }
287    }
288
289    /// An event outside Discord's voice channels, at `location` (1-100 characters), from
290    /// `start` to `end`.
291    ///
292    /// discord.js counterpart: `GuildScheduledEventCreateOptions` with `entityMetadata.location`.
293    #[must_use]
294    pub fn external(
295        location: impl Into<CompactString>,
296        name: impl Into<CompactString>,
297        start: Timestamp,
298        end: Timestamp,
299    ) -> Self {
300        Self {
301            entity_metadata: Some(EntityMetadata::new(location)),
302            scheduled_end_time: Some(end),
303            ..Self::new(name.into(), start, EntityType::External)
304        }
305    }
306}
307
308/// The body of [Modify Guild Scheduled Event](https://docs.discord.com/developers/resources/guild-scheduled-event#modify-guild-scheduled-event).
309///
310/// Every field is optional; [`Patch`] fields can also be cleared. Starting, ending or
311/// canceling an event is a change of [`status`](Self::status). Moving an event to
312/// [`EntityType::External`] needs [`channel_id`](Self::channel_id) set to [`Patch::Clear`],
313/// a location in [`entity_metadata`](Self::entity_metadata) and a
314/// [`scheduled_end_time`](Self::scheduled_end_time).
315///
316/// discord.js counterpart: `GuildScheduledEventEditOptions`.
317///
318/// # Examples
319///
320/// ```
321/// use djs_model::{guild_scheduled_event::Status, rest::ModifyGuildScheduledEvent};
322///
323/// let mut body = ModifyGuildScheduledEvent::default();
324/// body.status = Some(Status::Active); // start the event
325/// assert_eq!(serde_json::to_string(&body)?, r#"{"status":2}"#);
326/// # Ok::<(), serde_json::Error>(())
327/// ```
328#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
329#[non_exhaustive]
330pub struct ModifyGuildScheduledEvent {
331    /// The stage or voice channel; [`Patch::Clear`] when moving the event outside.
332    #[serde(skip_serializing_if = "Patch::is_keep")]
333    pub channel_id: Patch<ChannelId>,
334    /// The location of an external event (ignored for other events).
335    #[serde(skip_serializing_if = "Patch::is_keep")]
336    pub entity_metadata: Patch<EntityMetadata>,
337    /// The name (1-100 characters).
338    #[serde(skip_serializing_if = "Option::is_none")]
339    pub name: Option<CompactString>,
340    /// Who can see the event.
341    #[serde(skip_serializing_if = "Option::is_none")]
342    pub privacy_level: Option<PrivacyLevel>,
343    /// When the event starts.
344    #[serde(skip_serializing_if = "Option::is_none")]
345    pub scheduled_start_time: Option<Timestamp>,
346    /// When the event ends.
347    #[serde(skip_serializing_if = "Option::is_none")]
348    pub scheduled_end_time: Option<Timestamp>,
349    /// The description; [`Patch::Clear`] removes it.
350    #[serde(skip_serializing_if = "Patch::is_keep")]
351    pub description: Patch<CompactString>,
352    /// Where the event takes place.
353    #[serde(skip_serializing_if = "Option::is_none")]
354    pub entity_type: Option<EntityType>,
355    /// The status: scheduled events can become active or canceled, active events completed.
356    #[serde(skip_serializing_if = "Option::is_none")]
357    pub status: Option<Status>,
358    /// The cover image; [`Patch::Clear`] removes it.
359    #[serde(skip_serializing_if = "Patch::is_keep")]
360    pub image: Patch<ImageData>,
361    /// How the event repeats; [`Patch::Clear`] makes it a one-time event.
362    #[serde(skip_serializing_if = "Patch::is_keep")]
363    pub recurrence_rule: Patch<RecurrenceRuleData>,
364}
365
366#[cfg(test)]
367mod tests {
368    use serde_json::{Value, json};
369
370    use super::*;
371    use crate::guild_scheduled_event::{RecurrenceMonth, RecurrenceWeekday};
372
373    fn start() -> Timestamp {
374        Timestamp::parse("2026-12-01T18:00:00.000000+00:00").unwrap()
375    }
376
377    fn json(rule: &RecurrenceRuleData) -> Value {
378        let mut value = serde_json::to_value(rule).unwrap();
379        value.as_object_mut().unwrap().remove("start");
380        value
381    }
382
383    #[test]
384    fn recurrence_rules_as_discord_writes_them() {
385        use RecurrenceWeekday::{Friday, Monday, Tuesday};
386
387        assert_eq!(
388            json(&RecurrenceRuleData::daily(start())),
389            json!({"frequency": 3, "interval": 1})
390        );
391        assert_eq!(
392            json(&RecurrenceRuleData::daily_on(start(), [Monday, Tuesday])),
393            json!({"frequency": 3, "interval": 1, "by_weekday": [0, 1]})
394        );
395        assert_eq!(
396            json(&RecurrenceRuleData::weekly(start(), Friday)),
397            json!({"frequency": 2, "interval": 1, "by_weekday": [4]})
398        );
399        assert_eq!(
400            json(&RecurrenceRuleData::every_other_week(start(), Friday)),
401            json!({"frequency": 2, "interval": 2, "by_weekday": [4]})
402        );
403        assert_eq!(
404            json(&RecurrenceRuleData::monthly(start(), 1, Monday)),
405            json!({"frequency": 1, "interval": 1, "by_n_weekday": [{"n": 1, "day": 0}]})
406        );
407        assert_eq!(
408            json(&RecurrenceRuleData::yearly(
409                start(),
410                RecurrenceMonth::July,
411                4
412            )),
413            json!({"frequency": 0, "interval": 1, "by_month": [7], "by_month_day": [4]})
414        );
415    }
416
417    #[test]
418    fn a_voice_event_names_its_channel() {
419        let event = CreateGuildScheduledEvent::voice(ChannelId::new(5), "Movie night", start());
420        let value = serde_json::to_value(&event).unwrap();
421        assert_eq!(value["channel_id"], "5");
422        assert_eq!(value["entity_type"], 2);
423        assert_eq!(value["name"], "Movie night");
424    }
425}