Skip to main content

djs_cache/
model.rs

1//! The cache's own types, for the resources whose model types do not fit (D-160).
2
3use std::sync::Arc;
4
5use compact_str::CompactString;
6use djs_model::{
7    application::PartialApplication,
8    channel::{Channel, ChannelType},
9    component::Component,
10    gateway::{
11        Activity, ClientStatus, Presence, Status,
12        payload::{AvailableGuild, GuildMemberUpdate},
13    },
14    guild::{
15        AgeRestrictionLevel, DefaultMessageNotificationLevel, ExplicitContentFilterLevel, Feature,
16        Guild, IncidentsData, Member, MemberFlags, MfaLevel, PartialMember, PremiumTier,
17        SystemChannelFlags, VerificationLevel, WelcomeScreen,
18    },
19    id::{ApplicationId, ChannelId, GuildId, MessageId, RoleId, UserId, WebhookId},
20    interaction::{MessageInteraction, Resolved},
21    message::{
22        Attachment, ChannelMention, Embed, InteractionMetadata, Mention, Message, MessageActivity,
23        MessageCall, MessageFlags, MessageReference, MessageSnapshot, MessageType, Nonce, Reaction,
24        ReferencedMessage, RoleSubscriptionData, SharedClientTheme,
25    },
26    permissions::Permissions,
27    poll::Poll,
28    sticker::{Sticker, StickerItem},
29    user::{AvatarDecorationData, Collectibles, PrimaryGuild, User, UserFlags},
30    util::{ImageHash, Locale, Timestamp},
31};
32
33/// A cached guild: a [`Guild`] without its roles, emojis and stickers, which the cache keeps
34/// in their own resources, plus what `GUILD_CREATE` adds.
35///
36/// Read the guild's roles with [`Cache::roles`](crate::Cache::roles), its emojis with
37/// [`Cache::emojis`](crate::Cache::emojis), its stickers with
38/// [`Cache::stickers`](crate::Cache::stickers) and its channels with
39/// [`CacheView::in_guild`](crate::CacheView::in_guild).
40///
41/// The fields mean the same as in [`Guild`]; see the
42/// [guild object](https://docs.discord.com/developers/resources/guild#guild-object).
43///
44/// discord.js counterpart: `Guild`.
45#[derive(Clone, Debug, PartialEq, Eq)]
46#[non_exhaustive]
47#[expect(missing_docs, reason = "the fields are documented on `Guild`")]
48#[expect(clippy::struct_excessive_bools, reason = "mirrors the guild object")]
49pub struct CachedGuild {
50    pub id: GuildId,
51    pub name: CompactString,
52    pub icon: Option<ImageHash>,
53    pub icon_hash: Option<ImageHash>,
54    pub splash: Option<ImageHash>,
55    pub discovery_splash: Option<ImageHash>,
56    pub owner: bool,
57    pub owner_id: UserId,
58    pub permissions: Option<Permissions>,
59    pub region: Option<CompactString>,
60    pub afk_channel_id: Option<ChannelId>,
61    pub afk_timeout: u32,
62    pub widget_enabled: bool,
63    pub widget_channel_id: Option<ChannelId>,
64    pub verification_level: VerificationLevel,
65    pub default_message_notifications: DefaultMessageNotificationLevel,
66    pub explicit_content_filter: ExplicitContentFilterLevel,
67    pub features: Vec<Feature>,
68    pub mfa_level: MfaLevel,
69    pub application_id: Option<ApplicationId>,
70    pub system_channel_id: Option<ChannelId>,
71    pub system_channel_flags: SystemChannelFlags,
72    pub rules_channel_id: Option<ChannelId>,
73    pub max_presences: Option<u32>,
74    pub max_members: Option<u32>,
75    pub vanity_url_code: Option<CompactString>,
76    pub description: Option<CompactString>,
77    pub banner: Option<ImageHash>,
78    pub premium_tier: PremiumTier,
79    pub premium_subscription_count: Option<u32>,
80    pub preferred_locale: Locale,
81    pub public_updates_channel_id: Option<ChannelId>,
82    pub max_video_channel_users: Option<u32>,
83    pub max_stage_video_channel_users: Option<u32>,
84    pub approximate_member_count: Option<u32>,
85    pub approximate_presence_count: Option<u32>,
86    pub welcome_screen: Option<Box<WelcomeScreen>>,
87    pub nsfw_level: AgeRestrictionLevel,
88    pub premium_progress_bar_enabled: bool,
89    pub safety_alerts_channel_id: Option<ChannelId>,
90    pub incidents_data: Option<Box<IncidentsData>>,
91    /// When the bot joined the guild (from `GUILD_CREATE`).
92    pub joined_at: Option<Timestamp>,
93    /// Whether the guild is large (more members than the identify `large_threshold`).
94    pub large: bool,
95    /// The number of members, from `GUILD_CREATE`, kept up to date by member joins and
96    /// leaves.
97    ///
98    /// discord.js: `Guild#memberCount`.
99    pub member_count: u32,
100}
101
102impl CachedGuild {
103    /// Builds a cached guild from a `GUILD_CREATE`.
104    pub(crate) fn from_available(guild: &AvailableGuild) -> Self {
105        Self::new(
106            &guild.guild,
107            guild.joined_at,
108            guild.large,
109            guild.member_count,
110        )
111    }
112
113    /// Builds the cached guild after a `GUILD_UPDATE`, which lacks the `GUILD_CREATE` extras:
114    /// they are kept from `previous`.
115    pub(crate) fn updated(guild: &Guild, previous: &Self) -> Self {
116        Self::new(
117            guild,
118            previous.joined_at,
119            previous.large,
120            previous.member_count,
121        )
122    }
123
124    pub(crate) fn new(
125        guild: &Guild,
126        joined_at: Option<Timestamp>,
127        large: bool,
128        member_count: u32,
129    ) -> Self {
130        Self {
131            id: guild.id,
132            name: guild.name.clone(),
133            icon: guild.icon,
134            icon_hash: guild.icon_hash,
135            splash: guild.splash,
136            discovery_splash: guild.discovery_splash,
137            owner: guild.owner,
138            owner_id: guild.owner_id,
139            permissions: guild.permissions,
140            region: guild.region.clone(),
141            afk_channel_id: guild.afk_channel_id,
142            afk_timeout: guild.afk_timeout,
143            widget_enabled: guild.widget_enabled,
144            widget_channel_id: guild.widget_channel_id,
145            verification_level: guild.verification_level,
146            default_message_notifications: guild.default_message_notifications,
147            explicit_content_filter: guild.explicit_content_filter,
148            features: guild.features.clone(),
149            mfa_level: guild.mfa_level,
150            application_id: guild.application_id,
151            system_channel_id: guild.system_channel_id,
152            system_channel_flags: guild.system_channel_flags,
153            rules_channel_id: guild.rules_channel_id,
154            max_presences: guild.max_presences,
155            max_members: guild.max_members,
156            vanity_url_code: guild.vanity_url_code.clone(),
157            description: guild.description.clone(),
158            banner: guild.banner,
159            premium_tier: guild.premium_tier,
160            premium_subscription_count: guild.premium_subscription_count,
161            preferred_locale: guild.preferred_locale.clone(),
162            public_updates_channel_id: guild.public_updates_channel_id,
163            max_video_channel_users: guild.max_video_channel_users,
164            max_stage_video_channel_users: guild.max_stage_video_channel_users,
165            approximate_member_count: guild.approximate_member_count,
166            approximate_presence_count: guild.approximate_presence_count,
167            welcome_screen: guild.welcome_screen.clone(),
168            nsfw_level: guild.nsfw_level,
169            premium_progress_bar_enabled: guild.premium_progress_bar_enabled,
170            safety_alerts_channel_id: guild.safety_alerts_channel_id,
171            incidents_data: guild.incidents_data.clone(),
172            joined_at,
173            large,
174            member_count,
175        }
176    }
177}
178
179/// A cached user (D-177): a [`User`] with its rarely set fields behind one box.
180///
181/// Every user has an ID, a username and usually a display name and an avatar; few have a
182/// banner, an accent color, an avatar decoration, collectibles or a primary guild. Those are
183/// kept in one allocation that only exists when one of them is set, and read through methods
184/// ([`banner`](Self::banner), …). That keeps the user a user in many guilds shares with their
185/// members and messages at about two thirds of a [`User`].
186///
187/// The fields mean the same as in [`User`]; see the
188/// [user object](https://docs.discord.com/developers/resources/user#user-object).
189///
190/// discord.js counterpart: `User`.
191///
192/// # Examples
193///
194/// ```
195/// use djs_cache::{Cache, CacheConfig, Limit};
196/// use djs_model::{gateway::payload::GuildMemberAdd, id::UserId};
197///
198/// let cache = Cache::with_config(CacheConfig::builder().users(Limit::Unlimited).build());
199/// let member: GuildMemberAdd = serde_json::from_str(
200///     r#"{"guild_id":"1","user":{"id":"2","username":"nelly","discriminator":"0",
201///         "global_name":"Nelly","avatar":null},"roles":[],"joined_at":null,
202///         "deaf":false,"mute":false,"flags":0}"#,
203/// )?;
204/// cache.update(&member);
205/// let user = cache.users().get(UserId::new(2)).unwrap();
206/// assert_eq!(user.display_name(), "Nelly");
207/// assert_eq!(user.tag(), "nelly");
208/// assert_eq!(user.banner(), None);
209/// # Ok::<(), serde_json::Error>(())
210/// ```
211#[derive(Clone, Debug, PartialEq, Eq)]
212#[non_exhaustive]
213#[expect(missing_docs, reason = "the fields are documented on `User`")]
214pub struct CachedUser {
215    pub id: UserId,
216    pub username: CompactString,
217    pub discriminator: u16,
218    pub global_name: Option<CompactString>,
219    pub avatar: Option<ImageHash>,
220    pub bot: bool,
221    pub system: bool,
222    pub public_flags: Option<UserFlags>,
223    extras: Option<Box<UserExtras>>,
224}
225
226/// The rarely set fields of a [`CachedUser`].
227#[derive(Clone, Debug, PartialEq, Eq)]
228struct UserExtras {
229    banner: Option<ImageHash>,
230    accent_color: Option<u32>,
231    avatar_decoration_data: Option<AvatarDecorationData>,
232    collectibles: Option<Collectibles>,
233    primary_guild: Option<PrimaryGuild>,
234}
235
236impl CachedUser {
237    pub(crate) fn new(user: &User) -> Self {
238        let rare = user.banner.is_some()
239            || user.accent_color.is_some()
240            || user.avatar_decoration_data.is_some()
241            || user.collectibles.is_some()
242            || user.primary_guild.is_some();
243        Self {
244            id: user.id,
245            username: user.username.clone(),
246            discriminator: user.discriminator,
247            global_name: user.global_name.clone(),
248            avatar: user.avatar,
249            bot: user.bot,
250            system: user.system,
251            public_flags: user.public_flags,
252            extras: rare.then(|| {
253                Box::new(UserExtras {
254                    banner: user.banner,
255                    accent_color: user.accent_color,
256                    avatar_decoration_data: user.avatar_decoration_data.as_deref().cloned(),
257                    collectibles: user.collectibles.as_deref().cloned(),
258                    primary_guild: user.primary_guild.as_deref().cloned(),
259                })
260            }),
261        }
262    }
263
264    /// Whether this holds the same data as `user` (so an equal user is not stored again).
265    pub(crate) fn is(&self, user: &User) -> bool {
266        self.id == user.id
267            && self.username == user.username
268            && self.discriminator == user.discriminator
269            && self.global_name == user.global_name
270            && self.avatar == user.avatar
271            && self.bot == user.bot
272            && self.system == user.system
273            && self.public_flags == user.public_flags
274            && self.banner() == user.banner
275            && self.accent_color() == user.accent_color
276            && self.avatar_decoration_data() == user.avatar_decoration_data.as_deref()
277            && self.collectibles() == user.collectibles.as_deref()
278            && self.primary_guild() == user.primary_guild.as_deref()
279    }
280
281    /// The user's banner (Nitro).
282    ///
283    /// discord.js counterpart: `User#banner`.
284    #[must_use]
285    pub fn banner(&self) -> Option<ImageHash> {
286        self.extras.as_ref().and_then(|extras| extras.banner)
287    }
288
289    /// The user's banner color, as an RGB integer.
290    ///
291    /// discord.js counterpart: `User#accentColor`.
292    #[must_use]
293    pub fn accent_color(&self) -> Option<u32> {
294        self.extras.as_ref().and_then(|extras| extras.accent_color)
295    }
296
297    /// The user's avatar decoration.
298    ///
299    /// discord.js counterpart: `User#avatarDecorationData`.
300    #[must_use]
301    pub fn avatar_decoration_data(&self) -> Option<&AvatarDecorationData> {
302        self.extras.as_ref()?.avatar_decoration_data.as_ref()
303    }
304
305    /// The user's collectibles (such as a nameplate).
306    ///
307    /// discord.js counterpart: `User#collectibles`.
308    #[must_use]
309    pub fn collectibles(&self) -> Option<&Collectibles> {
310        self.extras.as_ref()?.collectibles.as_ref()
311    }
312
313    /// The guild whose tag the user displays.
314    ///
315    /// discord.js counterpart: `User#primaryGuild`.
316    #[must_use]
317    pub fn primary_guild(&self) -> Option<&PrimaryGuild> {
318        self.extras.as_ref()?.primary_guild.as_ref()
319    }
320
321    /// The name to display: the global display name if set, otherwise the username.
322    ///
323    /// discord.js counterpart: `User#displayName`.
324    #[must_use]
325    pub fn display_name(&self) -> &str {
326        self.global_name.as_deref().unwrap_or(&self.username)
327    }
328
329    /// The user's tag: `username#1234` for a legacy user, the username for a user with a
330    /// unique username (discriminator `0`).
331    ///
332    /// discord.js counterpart: `User#tag`.
333    #[must_use]
334    pub fn tag(&self) -> CompactString {
335        if self.discriminator == 0 {
336            self.username.clone()
337        } else {
338            compact_str::format_compact!("{}#{:04}", self.username, self.discriminator)
339        }
340    }
341}
342
343/// A cached guild member (D-177): a [`Member`] with its guild, its user shared with the user
344/// resource, and its rarely set fields behind one box.
345///
346/// When users are cached ([`Resource::User`](crate::Resource::User)), `user` is the same
347/// [`Arc`] the user resource holds, so a user in many guilds is stored once. A guild avatar
348/// or banner, a boost or timeout time, an avatar decoration and collectibles are kept in one
349/// allocation that only exists when one of them is set, and read through methods
350/// ([`avatar`](Self::avatar), …).
351///
352/// The fields mean the same as in [`Member`]; see the
353/// [guild member object](https://docs.discord.com/developers/resources/guild#guild-member-object).
354///
355/// discord.js counterpart: `GuildMember`.
356#[derive(Clone, Debug, PartialEq, Eq)]
357#[non_exhaustive]
358#[expect(missing_docs, reason = "the fields are documented on `Member`")]
359pub struct CachedMember {
360    /// The guild the member belongs to.
361    pub guild_id: GuildId,
362    pub user: Arc<CachedUser>,
363    pub nick: Option<CompactString>,
364    pub roles: Box<[RoleId]>,
365    pub joined_at: Option<Timestamp>,
366    pub deaf: bool,
367    pub mute: bool,
368    pub pending: bool,
369    pub flags: MemberFlags,
370    extras: Option<Box<MemberExtras>>,
371}
372
373/// The rarely set fields of a [`CachedMember`].
374#[derive(Clone, Debug, PartialEq, Eq)]
375struct MemberExtras {
376    avatar: Option<ImageHash>,
377    banner: Option<ImageHash>,
378    premium_since: Option<Timestamp>,
379    communication_disabled_until: Option<Timestamp>,
380    avatar_decoration_data: Option<AvatarDecorationData>,
381    collectibles: Option<Collectibles>,
382}
383
384impl MemberExtras {
385    /// The extras, or `None` when none of them is set.
386    fn new(
387        avatar: Option<ImageHash>,
388        banner: Option<ImageHash>,
389        premium_since: Option<Timestamp>,
390        communication_disabled_until: Option<Timestamp>,
391        avatar_decoration_data: Option<&AvatarDecorationData>,
392        collectibles: Option<&Collectibles>,
393    ) -> Option<Box<Self>> {
394        let rare = avatar.is_some()
395            || banner.is_some()
396            || premium_since.is_some()
397            || communication_disabled_until.is_some()
398            || avatar_decoration_data.is_some()
399            || collectibles.is_some();
400        rare.then(|| {
401            Box::new(Self {
402                avatar,
403                banner,
404                premium_since,
405                communication_disabled_until,
406                avatar_decoration_data: avatar_decoration_data.cloned(),
407                collectibles: collectibles.cloned(),
408            })
409        })
410    }
411}
412
413impl CachedMember {
414    pub(crate) fn new(guild_id: GuildId, member: &Member, user: Arc<CachedUser>) -> Self {
415        Self {
416            guild_id,
417            user,
418            nick: member.nick.clone(),
419            roles: member.roles.as_slice().into(),
420            joined_at: member.joined_at,
421            deaf: member.deaf,
422            mute: member.mute,
423            pending: member.pending,
424            flags: member.flags,
425            extras: MemberExtras::new(
426                member.avatar,
427                member.banner,
428                member.premium_since,
429                member.communication_disabled_until,
430                member.avatar_decoration_data.as_deref(),
431                member.collectibles.as_deref(),
432            ),
433        }
434    }
435
436    /// Builds the member after a `GUILD_MEMBER_UPDATE`. Fields the update may omit (`deaf`,
437    /// `mute`, `pending`, `flags`) are kept from `previous`, or default when the member was
438    /// not cached.
439    pub(crate) fn updated(
440        update: &GuildMemberUpdate,
441        user: Arc<CachedUser>,
442        previous: Option<&Self>,
443    ) -> Self {
444        Self {
445            guild_id: update.guild_id,
446            user,
447            nick: update.nick.clone(),
448            roles: update.roles.as_slice().into(),
449            joined_at: update
450                .joined_at
451                .or_else(|| previous.and_then(|member| member.joined_at)),
452            deaf: update
453                .deaf
454                .unwrap_or_else(|| previous.is_some_and(|member| member.deaf)),
455            mute: update
456                .mute
457                .unwrap_or_else(|| previous.is_some_and(|member| member.mute)),
458            pending: update
459                .pending
460                .unwrap_or_else(|| previous.is_some_and(|member| member.pending)),
461            flags: update
462                .flags
463                .unwrap_or_else(|| previous.map_or_else(MemberFlags::empty, |member| member.flags)),
464            extras: MemberExtras::new(
465                update.avatar,
466                update.banner,
467                update.premium_since,
468                update.communication_disabled_until,
469                update.avatar_decoration_data.as_deref(),
470                update.collectibles.as_deref(),
471            ),
472        }
473    }
474
475    /// Builds a member from the partial member attached to a message (or an interaction),
476    /// whose user is the message's author.
477    pub(crate) fn from_partial(
478        guild_id: GuildId,
479        member: &PartialMember,
480        user: Arc<CachedUser>,
481    ) -> Self {
482        Self {
483            guild_id,
484            user,
485            nick: member.nick.clone(),
486            roles: member.roles.as_slice().into(),
487            joined_at: member.joined_at,
488            deaf: member.deaf,
489            mute: member.mute,
490            pending: member.pending,
491            flags: member.flags,
492            extras: MemberExtras::new(
493                member.avatar,
494                member.banner,
495                member.premium_since,
496                member.communication_disabled_until,
497                member.avatar_decoration_data.as_deref(),
498                member.collectibles.as_deref(),
499            ),
500        }
501    }
502
503    /// The member's ID (their user's ID).
504    ///
505    /// discord.js counterpart: `GuildMember#id`.
506    #[must_use]
507    pub fn id(&self) -> UserId {
508        self.user.id
509    }
510
511    /// The name shown in the guild: the nickname, else the user's display name, else the
512    /// username.
513    ///
514    /// discord.js counterpart: `GuildMember#displayName`.
515    #[must_use]
516    pub fn display_name(&self) -> &str {
517        self.nick
518            .as_deref()
519            .unwrap_or_else(|| self.user.display_name())
520    }
521
522    /// The member's guild avatar (overriding their user's avatar in the guild).
523    ///
524    /// discord.js counterpart: `GuildMember#avatar`.
525    #[must_use]
526    pub fn avatar(&self) -> Option<ImageHash> {
527        self.extras.as_ref().and_then(|extras| extras.avatar)
528    }
529
530    /// The member's guild banner.
531    ///
532    /// discord.js counterpart: `GuildMember#banner`.
533    #[must_use]
534    pub fn banner(&self) -> Option<ImageHash> {
535        self.extras.as_ref().and_then(|extras| extras.banner)
536    }
537
538    /// When the member started boosting the guild.
539    ///
540    /// discord.js counterpart: `GuildMember#premiumSince`.
541    #[must_use]
542    pub fn premium_since(&self) -> Option<Timestamp> {
543        self.extras.as_ref().and_then(|extras| extras.premium_since)
544    }
545
546    /// When the member's timeout ends (`None` or a past time: not timed out).
547    ///
548    /// discord.js counterpart: `GuildMember#communicationDisabledUntil`.
549    #[must_use]
550    pub fn communication_disabled_until(&self) -> Option<Timestamp> {
551        self.extras
552            .as_ref()
553            .and_then(|extras| extras.communication_disabled_until)
554    }
555
556    /// The member's guild avatar decoration.
557    ///
558    /// discord.js counterpart: `GuildMember#avatarDecorationData`.
559    #[must_use]
560    pub fn avatar_decoration_data(&self) -> Option<&AvatarDecorationData> {
561        self.extras.as_ref()?.avatar_decoration_data.as_ref()
562    }
563
564    /// The member's guild collectibles.
565    ///
566    /// discord.js counterpart: `GuildMember#collectibles`.
567    #[must_use]
568    pub fn collectibles(&self) -> Option<&Collectibles> {
569        self.extras.as_ref()?.collectibles.as_ref()
570    }
571}
572
573/// A cached message: a [`Message`] whose author is shared with the user resource, without the
574/// `member` field (members are a resource of their own, D-165).
575///
576/// When users are cached ([`Resource::User`](crate::Resource::User)), `author` is the same
577/// [`Arc`] the user resource holds, so an author of many messages is stored once. The author's
578/// guild member, when the message came with one, is cached as a member.
579///
580/// The fields mean the same as in [`Message`]; see the
581/// [message object](https://docs.discord.com/developers/resources/message#message-object).
582///
583/// discord.js counterpart: `Message`.
584#[derive(Clone, Debug, PartialEq)]
585#[non_exhaustive]
586#[expect(missing_docs, reason = "the fields are documented on `Message`")]
587pub struct CachedMessage {
588    pub id: MessageId,
589    pub channel_id: ChannelId,
590    pub guild_id: Option<GuildId>,
591    pub author: Arc<CachedUser>,
592    pub content: CompactString,
593    pub timestamp: Timestamp,
594    pub edited_timestamp: Option<Timestamp>,
595    pub tts: bool,
596    pub mention_everyone: bool,
597    pub mentions: Vec<Mention>,
598    pub mention_roles: Vec<RoleId>,
599    pub mention_channels: Vec<ChannelMention>,
600    pub attachments: Vec<Attachment>,
601    pub embeds: Vec<Embed>,
602    pub reactions: Vec<Reaction>,
603    pub nonce: Option<Nonce>,
604    pub pinned: bool,
605    pub webhook_id: Option<WebhookId>,
606    pub kind: MessageType,
607    pub activity: Option<Box<MessageActivity>>,
608    pub application: Option<Box<PartialApplication>>,
609    pub application_id: Option<ApplicationId>,
610    pub flags: MessageFlags,
611    pub message_reference: Option<MessageReference>,
612    pub message_snapshots: Vec<MessageSnapshot>,
613    pub referenced_message: ReferencedMessage,
614    pub interaction_metadata: Option<Box<InteractionMetadata>>,
615    pub interaction: Option<Box<MessageInteraction>>,
616    pub components: Vec<Component>,
617    pub thread: Option<Box<Channel>>,
618    pub resolved: Option<Box<Resolved>>,
619    pub sticker_items: Vec<StickerItem>,
620    pub stickers: Vec<Sticker>,
621    pub position: Option<u32>,
622    pub role_subscription_data: Option<Box<RoleSubscriptionData>>,
623    pub poll: Option<Box<Poll>>,
624    pub call: Option<Box<MessageCall>>,
625    pub shared_client_theme: Option<Box<SharedClientTheme>>,
626    pub channel_type: Option<ChannelType>,
627}
628
629impl CachedMessage {
630    pub(crate) fn new(message: &Message, author: Arc<CachedUser>) -> Self {
631        Self {
632            id: message.id,
633            channel_id: message.channel_id,
634            guild_id: message.guild_id,
635            author,
636            content: message.content.clone(),
637            timestamp: message.timestamp,
638            edited_timestamp: message.edited_timestamp,
639            tts: message.tts,
640            mention_everyone: message.mention_everyone,
641            mentions: message.mentions.clone(),
642            mention_roles: message.mention_roles.clone(),
643            mention_channels: message.mention_channels.clone(),
644            attachments: message.attachments.clone(),
645            embeds: message.embeds.clone(),
646            reactions: message.reactions.clone(),
647            nonce: message.nonce.clone(),
648            pinned: message.pinned,
649            webhook_id: message.webhook_id,
650            kind: message.kind,
651            activity: message.activity.clone(),
652            application: message.application.clone(),
653            application_id: message.application_id,
654            flags: message.flags,
655            message_reference: message.message_reference,
656            message_snapshots: message.message_snapshots.clone(),
657            referenced_message: message.referenced_message.clone(),
658            interaction_metadata: message.interaction_metadata.clone(),
659            interaction: message.interaction.clone(),
660            components: message.components.clone(),
661            thread: message.thread.clone(),
662            resolved: message.resolved.clone(),
663            sticker_items: message.sticker_items.clone(),
664            stickers: message.stickers.clone(),
665            position: message.position,
666            role_subscription_data: message.role_subscription_data.clone(),
667            poll: message.poll.clone(),
668            call: message.call.clone(),
669            shared_client_theme: message.shared_client_theme.clone(),
670            channel_type: message.channel_type,
671        }
672    }
673}
674
675/// A cached presence: a member's status and activities (D-164).
676///
677/// It keeps its user's ID only; the user's data lives in the user resource. The activities are
678/// the model's, complete, in a boxed slice. Offline members have no cached presence.
679///
680/// See the [presence update](https://docs.discord.com/developers/events/gateway-events#presence-update).
681///
682/// discord.js counterpart: `Presence`.
683#[derive(Clone, Debug, PartialEq)]
684#[non_exhaustive]
685pub struct CachedPresence {
686    /// The guild the presence is in.
687    pub guild_id: GuildId,
688    /// The user the presence is of.
689    pub user_id: UserId,
690    /// The overall status.
691    pub status: Status,
692    /// The status on each platform.
693    pub client_status: ClientStatus,
694    /// The current activities.
695    pub activities: Box<[Activity]>,
696}
697
698impl CachedPresence {
699    pub(crate) fn new(guild_id: GuildId, presence: &Presence) -> Self {
700        Self {
701            guild_id,
702            user_id: presence.user.id,
703            status: presence.status.clone(),
704            client_status: presence.client_status.clone(),
705            activities: presence.activities.clone().into_boxed_slice(),
706        }
707    }
708}