Skip to main content

djs_model/gateway/
presence.rs

1//! Presence data sent over the gateway: activities and statuses.
2
3use compact_str::CompactString;
4use serde::{Deserialize, Serialize};
5
6use crate::{
7    id::{ApplicationId, EmojiId, GuildId, UserId},
8    macros::{int_enum, int_flags, str_enum},
9    user::{AvatarDecorationData, Collectibles, PrimaryGuild, UserFlags},
10    util::{ImageHash, Timestamp},
11};
12
13/// A user's [presence](https://docs.discord.com/developers/events/gateway-events#presence-update):
14/// their status and activities in a guild.
15///
16/// Received in `PRESENCE_UPDATE`, `GUILD_CREATE` (without `guild_id`), `GUILD_MEMBERS_CHUNK`
17/// and `THREAD_MEMBERS_UPDATE`. Requires the `GUILD_PRESENCES` intent.
18///
19/// discord.js counterpart: `Presence`.
20#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
21#[non_exhaustive]
22pub struct Presence {
23    /// The user (only `id` is guaranteed, D-074).
24    pub user: PresenceUser,
25    /// The guild (absent in `GUILD_CREATE`, where the guild is known).
26    #[serde(default, skip_serializing_if = "Option::is_none")]
27    pub guild_id: Option<GuildId>,
28    /// The overall status.
29    #[serde(default = "offline")]
30    pub status: Status,
31    /// The current activities.
32    #[serde(default, deserialize_with = "crate::serde_util::null_as_default")]
33    pub activities: Vec<Activity>,
34    /// The status on each platform.
35    #[serde(default)]
36    pub client_status: ClientStatus,
37}
38
39fn offline() -> Status {
40    Status::Offline
41}
42
43/// The partial user of a [`Presence`] (D-074): only [`id`](Self::id) is guaranteed; the other
44/// fields are present when they changed. `None` means "not sent" (or `null`).
45///
46/// discord.js counterpart: the `user` of the `presenceUpdate` data, used to update `User`s.
47#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
48#[non_exhaustive]
49pub struct PresenceUser {
50    /// The user's ID.
51    pub id: UserId,
52    /// The username.
53    #[serde(default, skip_serializing_if = "Option::is_none")]
54    pub username: Option<CompactString>,
55    /// The legacy tag (`0` for migrated users).
56    #[serde(
57        default,
58        skip_serializing_if = "Option::is_none",
59        with = "crate::user::option_discriminator"
60    )]
61    pub discriminator: Option<u16>,
62    /// The display name.
63    #[serde(default, skip_serializing_if = "Option::is_none")]
64    pub global_name: Option<CompactString>,
65    /// The avatar hash.
66    #[serde(default, skip_serializing_if = "Option::is_none")]
67    pub avatar: Option<ImageHash>,
68    /// Whether the user is a bot.
69    #[serde(default, skip_serializing_if = "Option::is_none")]
70    pub bot: Option<bool>,
71    /// Whether the user is a Discord system user.
72    #[serde(default, skip_serializing_if = "Option::is_none")]
73    pub system: Option<bool>,
74    /// The banner hash.
75    #[serde(default, skip_serializing_if = "Option::is_none")]
76    pub banner: Option<ImageHash>,
77    /// The banner color.
78    #[serde(default, skip_serializing_if = "Option::is_none")]
79    pub accent_color: Option<u32>,
80    /// The public flags.
81    #[serde(default, skip_serializing_if = "Option::is_none")]
82    pub public_flags: Option<UserFlags>,
83    /// The avatar decoration.
84    #[serde(default, skip_serializing_if = "Option::is_none")]
85    pub avatar_decoration_data: Option<Box<AvatarDecorationData>>,
86    /// The collectibles.
87    #[serde(default, skip_serializing_if = "Option::is_none")]
88    pub collectibles: Option<Box<Collectibles>>,
89    /// The displayed server tag.
90    #[serde(default, skip_serializing_if = "Option::is_none")]
91    pub primary_guild: Option<Box<PrimaryGuild>>,
92}
93
94/// A user's [status per platform](https://docs.discord.com/developers/events/gateway-events#client-status-object);
95/// a platform is `None` when the user is offline or invisible there.
96///
97/// discord.js counterpart: `ClientPresenceStatusData`.
98#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
99#[non_exhaustive]
100pub struct ClientStatus {
101    /// The desktop app session's status.
102    #[serde(default, skip_serializing_if = "Option::is_none")]
103    pub desktop: Option<Status>,
104    /// The mobile app session's status.
105    #[serde(default, skip_serializing_if = "Option::is_none")]
106    pub mobile: Option<Status>,
107    /// The web (browser, bot) session's status.
108    #[serde(default, skip_serializing_if = "Option::is_none")]
109    pub web: Option<Status>,
110    /// The virtual reality app session's status.
111    #[serde(default, skip_serializing_if = "Option::is_none")]
112    pub vr: Option<Status>,
113}
114
115/// An [activity](https://docs.discord.com/developers/events/gateway-events#activity-object): a
116/// game, stream, song, custom status, … shown in a user's presence.
117///
118/// Bots can only set [`name`](Self::name), [`state`](Self::state), [`kind`](Self::kind) and
119/// [`url`](Self::url) (see [`Activity::new`]).
120///
121/// discord.js counterpart: `Activity`.
122#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
123#[non_exhaustive]
124pub struct Activity {
125    /// The activity's name.
126    pub name: CompactString,
127    /// The kind of activity.
128    #[serde(rename = "type")]
129    pub kind: ActivityType,
130    /// The stream URL ([`Streaming`](ActivityType::Streaming); Twitch and YouTube only).
131    #[serde(default, skip_serializing_if = "Option::is_none")]
132    pub url: Option<CompactString>,
133    /// When the activity was added to the user's session.
134    #[serde(
135        default,
136        skip_serializing_if = "Option::is_none",
137        with = "crate::serde_util::option_unix_millis"
138    )]
139    pub created_at: Option<Timestamp>,
140    /// When the game started and/or ends.
141    #[serde(default, skip_serializing_if = "Option::is_none")]
142    pub timestamps: Option<ActivityTimestamps>,
143    /// The game's application.
144    #[serde(default, skip_serializing_if = "Option::is_none")]
145    pub application_id: Option<ApplicationId>,
146    /// Which field the member list shows as status text.
147    #[serde(default, skip_serializing_if = "Option::is_none")]
148    pub status_display_type: Option<StatusDisplayType>,
149    /// What the player is doing.
150    #[serde(default, skip_serializing_if = "Option::is_none")]
151    pub details: Option<CompactString>,
152    /// The URL linked from the details text.
153    #[serde(default, skip_serializing_if = "Option::is_none")]
154    pub details_url: Option<CompactString>,
155    /// The party status, or the text of a custom status.
156    #[serde(default, skip_serializing_if = "Option::is_none")]
157    pub state: Option<CompactString>,
158    /// The URL linked from the state text.
159    #[serde(default, skip_serializing_if = "Option::is_none")]
160    pub state_url: Option<CompactString>,
161    /// The emoji of a custom status.
162    #[serde(default, skip_serializing_if = "Option::is_none")]
163    pub emoji: Option<ActivityEmoji>,
164    /// The player's party.
165    #[serde(default, skip_serializing_if = "Option::is_none")]
166    pub party: Option<ActivityParty>,
167    /// The images and their hover texts.
168    #[serde(default, skip_serializing_if = "Option::is_none")]
169    pub assets: Option<Box<ActivityAssets>>,
170    /// The Rich Presence secrets for joining and spectating.
171    #[serde(default, skip_serializing_if = "Option::is_none")]
172    pub secrets: Option<Box<ActivitySecrets>>,
173    /// Whether the activity is an instanced game session.
174    #[serde(default, skip_serializing_if = "core::ops::Not::not")]
175    pub instance: bool,
176    /// What the activity supports.
177    #[serde(default, skip_serializing_if = "ActivityFlags::is_empty")]
178    pub flags: ActivityFlags,
179    /// The labels of the custom buttons (max 2; bots cannot see the URLs).
180    #[serde(default, skip_serializing_if = "Vec::is_empty")]
181    pub buttons: Vec<CompactString>,
182}
183
184impl Activity {
185    /// Creates an activity with the fields bots can set: a name and kind (set
186    /// [`state`](Self::state) for a custom status text, [`url`](Self::url) for a stream).
187    ///
188    /// discord.js counterpart: `ActivitiesOptions`.
189    #[must_use]
190    pub fn new(kind: ActivityType, name: impl Into<CompactString>) -> Self {
191        Self {
192            name: name.into(),
193            kind,
194            url: None,
195            created_at: None,
196            timestamps: None,
197            application_id: None,
198            status_display_type: None,
199            details: None,
200            details_url: None,
201            state: None,
202            state_url: None,
203            emoji: None,
204            party: None,
205            assets: None,
206            secrets: None,
207            instance: false,
208            flags: ActivityFlags::empty(),
209            buttons: Vec::new(),
210        }
211    }
212
213    /// "Playing {name}".
214    ///
215    /// discord.js counterpart: `ActivitiesOptions` with `type: ActivityType.Playing`.
216    ///
217    /// # Examples
218    ///
219    /// ```
220    /// use djs_model::gateway::{Activity, ActivityType};
221    ///
222    /// let activity = Activity::playing("with Rust");
223    /// assert_eq!((activity.kind, activity.name.as_str()), (ActivityType::Playing, "with Rust"));
224    /// ```
225    #[must_use]
226    pub fn playing(name: impl Into<CompactString>) -> Self {
227        Self::new(ActivityType::Playing, name)
228    }
229
230    /// "Streaming {name}", linking to `url`. Discord only accepts `https://twitch.tv/` and
231    /// `https://youtube.com/` URLs.
232    ///
233    /// discord.js counterpart: `ActivitiesOptions` with `type: ActivityType.Streaming`.
234    ///
235    /// # Examples
236    ///
237    /// ```
238    /// use djs_model::gateway::Activity;
239    ///
240    /// let activity = Activity::streaming("Rust live", "https://twitch.tv/example");
241    /// assert_eq!(
242    ///     serde_json::to_string(&activity).unwrap(),
243    ///     r#"{"name":"Rust live","type":1,"url":"https://twitch.tv/example"}"#
244    /// );
245    /// ```
246    #[must_use]
247    pub fn streaming(name: impl Into<CompactString>, url: impl Into<CompactString>) -> Self {
248        Self {
249            url: Some(url.into()),
250            ..Self::new(ActivityType::Streaming, name)
251        }
252    }
253
254    /// "Listening to {name}".
255    ///
256    /// discord.js counterpart: `ActivitiesOptions` with `type: ActivityType.Listening`.
257    #[must_use]
258    pub fn listening(name: impl Into<CompactString>) -> Self {
259        Self::new(ActivityType::Listening, name)
260    }
261
262    /// "Watching {name}".
263    ///
264    /// discord.js counterpart: `ActivitiesOptions` with `type: ActivityType.Watching`.
265    #[must_use]
266    pub fn watching(name: impl Into<CompactString>) -> Self {
267        Self::new(ActivityType::Watching, name)
268    }
269
270    /// "Competing in {name}".
271    ///
272    /// discord.js counterpart: `ActivitiesOptions` with `type: ActivityType.Competing`.
273    #[must_use]
274    pub fn competing(name: impl Into<CompactString>) -> Self {
275        Self::new(ActivityType::Competing, name)
276    }
277
278    /// A custom status showing `text` (stored in [`state`](Self::state); the name is
279    /// `"Custom Status"`, as Discord's clients send).
280    ///
281    /// discord.js counterpart: `ActivitiesOptions` with `type: ActivityType.Custom`.
282    ///
283    /// # Examples
284    ///
285    /// ```
286    /// use djs_model::gateway::Activity;
287    ///
288    /// let activity = Activity::custom("Fixing bugs");
289    /// assert_eq!(activity.state.as_deref(), Some("Fixing bugs"));
290    /// ```
291    #[must_use]
292    pub fn custom(text: impl Into<CompactString>) -> Self {
293        Self {
294            state: Some(text.into()),
295            ..Self::new(ActivityType::Custom, "Custom Status")
296        }
297    }
298}
299
300int_enum! {
301    /// The [kind of an activity](https://docs.discord.com/developers/events/gateway-events#activity-object-activity-types).
302    ///
303    /// discord.js counterpart: `ActivityType`.
304    pub enum ActivityType: u8 {
305        /// "Playing {name}".
306        Playing = 0,
307        /// "Streaming {details}".
308        Streaming = 1,
309        /// "Listening to {name}".
310        Listening = 2,
311        /// "Watching {name}".
312        Watching = 3,
313        /// "{emoji} {state}": a custom status.
314        Custom = 4,
315        /// "Competing in {name}".
316        Competing = 5,
317    }
318}
319
320int_enum! {
321    /// [Which field is shown](https://docs.discord.com/developers/events/gateway-events#activity-object-status-display-types)
322    /// as the status text in the member list.
323    ///
324    /// discord.js counterpart: `StatusDisplayType`.
325    pub enum StatusDisplayType: u8 {
326        /// The activity's name ("Listening to Spotify").
327        Name = 0,
328        /// The state ("Listening to Rick Astley").
329        State = 1,
330        /// The details ("Listening to Never Gonna Give You Up").
331        Details = 2,
332    }
333}
334
335/// When an [`Activity`] [started and ends](https://docs.discord.com/developers/events/gateway-events#activity-object-activity-timestamps)
336/// (both: a time bar for listening and watching).
337///
338/// discord.js counterpart: `GatewayActivityTimestamps` (discord-api-types).
339#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
340#[non_exhaustive]
341pub struct ActivityTimestamps {
342    /// When the activity started.
343    #[serde(
344        default,
345        skip_serializing_if = "Option::is_none",
346        with = "crate::serde_util::option_unix_millis"
347    )]
348    pub start: Option<Timestamp>,
349    /// When the activity ends.
350    #[serde(
351        default,
352        skip_serializing_if = "Option::is_none",
353        with = "crate::serde_util::option_unix_millis"
354    )]
355    pub end: Option<Timestamp>,
356}
357
358/// The [emoji of a custom status](https://docs.discord.com/developers/events/gateway-events#activity-object-activity-emoji).
359///
360/// discord.js counterpart: `GatewayActivityEmoji` (discord-api-types).
361#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
362#[non_exhaustive]
363pub struct ActivityEmoji {
364    /// The emoji's name (the character of a standard emoji).
365    pub name: CompactString,
366    /// The custom emoji's ID.
367    #[serde(default, skip_serializing_if = "Option::is_none")]
368    pub id: Option<EmojiId>,
369    /// Whether the custom emoji is animated.
370    #[serde(default, skip_serializing_if = "core::ops::Not::not")]
371    pub animated: bool,
372}
373
374/// The player's [party](https://docs.discord.com/developers/events/gateway-events#activity-object-activity-party).
375///
376/// discord.js counterpart: `GatewayActivityParty` (discord-api-types).
377#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
378#[non_exhaustive]
379pub struct ActivityParty {
380    /// The party's ID.
381    #[serde(default, skip_serializing_if = "Option::is_none")]
382    pub id: Option<CompactString>,
383    /// The party's `(current, maximum)` size.
384    #[serde(default, skip_serializing_if = "Option::is_none")]
385    pub size: Option<(u32, u32)>,
386}
387
388/// The [images of an activity](https://docs.discord.com/developers/events/gateway-events#activity-object-activity-assets)
389/// and their hover texts.
390///
391/// Images are an application asset ID or `mp:{image_id}` for an image of the media proxy
392/// (`https://media.discordapp.net/{image_id}`); they are user-provided and not sanitized.
393///
394/// discord.js counterpart: `GatewayActivityAssets` (discord-api-types).
395#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
396#[non_exhaustive]
397pub struct ActivityAssets {
398    /// The large image.
399    #[serde(default, skip_serializing_if = "Option::is_none")]
400    pub large_image: Option<CompactString>,
401    /// The large image's hover text.
402    #[serde(default, skip_serializing_if = "Option::is_none")]
403    pub large_text: Option<CompactString>,
404    /// The URL opened by clicking the large image.
405    #[serde(default, skip_serializing_if = "Option::is_none")]
406    pub large_url: Option<CompactString>,
407    /// The small image.
408    #[serde(default, skip_serializing_if = "Option::is_none")]
409    pub small_image: Option<CompactString>,
410    /// The small image's hover text.
411    #[serde(default, skip_serializing_if = "Option::is_none")]
412    pub small_text: Option<CompactString>,
413    /// The URL opened by clicking the small image.
414    #[serde(default, skip_serializing_if = "Option::is_none")]
415    pub small_url: Option<CompactString>,
416    /// The banner of a game invite.
417    #[serde(default, skip_serializing_if = "Option::is_none")]
418    pub invite_cover_image: Option<CompactString>,
419}
420
421/// The [Rich Presence secrets](https://docs.discord.com/developers/events/gateway-events#activity-object-activity-secrets)
422/// of an activity.
423///
424/// discord.js counterpart: `GatewayActivitySecrets` (discord-api-types).
425#[derive(Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
426#[non_exhaustive]
427pub struct ActivitySecrets {
428    /// The secret for joining the party.
429    #[serde(default, skip_serializing_if = "Option::is_none")]
430    pub join: Option<CompactString>,
431    /// The secret for spectating the game.
432    #[serde(default, skip_serializing_if = "Option::is_none")]
433    pub spectate: Option<CompactString>,
434    /// The secret for an instanced match.
435    #[serde(default, rename = "match", skip_serializing_if = "Option::is_none")]
436    pub match_: Option<CompactString>,
437}
438
439impl core::fmt::Debug for ActivitySecrets {
440    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
441        let redact = |secret: &Option<CompactString>| secret.as_ref().map(|_| "<redacted>");
442        f.debug_struct("ActivitySecrets")
443            .field("join", &redact(&self.join))
444            .field("spectate", &redact(&self.spectate))
445            .field("match", &redact(&self.match_))
446            .finish()
447    }
448}
449
450int_flags! {
451    /// [Flags of an activity](https://docs.discord.com/developers/events/gateway-events#activity-object-activity-flags):
452    /// what the activity supports (joining, spectating, …).
453    ///
454    /// discord.js counterpart: `ActivityFlags` / `ActivityFlagsBitField`.
455    pub struct ActivityFlags: u64 {
456        /// The activity is an instanced game session.
457        const INSTANCE = 1 << 0;
458        /// Others can join the activity.
459        const JOIN = 1 << 1;
460        /// Others can spectate the activity.
461        const SPECTATE = 1 << 2;
462        /// Others can ask to join the activity.
463        const JOIN_REQUEST = 1 << 3;
464        /// A Spotify-style synced activity ("Listen along").
465        const SYNC = 1 << 4;
466        /// The activity can be played.
467        const PLAY = 1 << 5;
468        /// Party privacy: only friends can join.
469        const PARTY_PRIVACY_FRIENDS = 1 << 6;
470        /// Party privacy: members of the same voice channel can join.
471        const PARTY_PRIVACY_VOICE_CHANNEL = 1 << 7;
472        /// The activity is an embedded app (Activity) running in Discord.
473        const EMBEDDED = 1 << 8;
474    }
475}
476
477str_enum! {
478    /// The [online status](https://docs.discord.com/developers/events/gateway-events#update-presence-status-types)
479    /// of a user.
480    ///
481    /// discord.js counterpart: `PresenceStatus` / `PresenceUpdateStatus`.
482    pub enum Status {
483        /// Online.
484        Online = "online",
485        /// Do not disturb.
486        DoNotDisturb = "dnd",
487        /// Idle (AFK).
488        Idle = "idle",
489        /// Invisible: shown to others as offline. Only used when setting the bot's own status.
490        Invisible = "invisible",
491        /// Offline.
492        Offline = "offline",
493    }
494}