Skip to main content

djs_model/message/
mod.rs

1//! [Messages](https://docs.discord.com/developers/resources/message): their content, embeds,
2//! attachments, reactions, references and everything else attached to them.
3
4mod attachment;
5mod embed;
6mod interaction_metadata;
7
8use core::{fmt, ops::Deref};
9
10use compact_str::CompactString;
11use serde::{
12    Deserialize, Deserializer, Serialize, Serializer,
13    de::{Error as DeError, Visitor},
14};
15
16pub use self::{
17    attachment::{Attachment, AttachmentRequest, AttachmentRequestId},
18    embed::{
19        Embed, EmbedAuthor, EmbedField, EmbedFooter, EmbedImage, EmbedProvider, EmbedType,
20        EmbedVideo,
21    },
22    interaction_metadata::{
23        CommandMetadata, ComponentMetadata, InteractionMetadata, ModalSubmitMetadata,
24        UnknownMetadata,
25    },
26};
27use crate::{
28    application::PartialApplication,
29    channel::{Channel, ChannelType},
30    component::Component,
31    emoji::PartialEmoji,
32    guild::PartialMember,
33    id::{ApplicationId, ChannelId, GuildId, MessageId, RoleId, SkuId, UserId, WebhookId},
34    interaction::{MessageInteraction, Resolved},
35    macros::{int_enum, int_flags, str_enum},
36    poll::Poll,
37    sticker::{Sticker, StickerItem},
38    user::{AvatarDecorationData, Collectibles, PrimaryGuild, User, UserFlags},
39    util::{ImageHash, Timestamp},
40};
41
42/// A [message](https://docs.discord.com/developers/resources/message#message-object) sent in a
43/// channel.
44///
45/// The same type is used for messages received through the gateway (`MESSAGE_CREATE`,
46/// `MESSAGE_UPDATE`) and from REST. The gateway adds a few fields ([`guild_id`](Self::guild_id),
47/// [`member`](Self::member), the members of [`mentions`](Self::mentions),
48/// [`channel_type`](Self::channel_type)) that REST responses do not have.
49///
50/// Without the `MESSAGE_CONTENT` privileged intent, [`content`](Self::content),
51/// [`embeds`](Self::embeds) and [`attachments`](Self::attachments) are empty and
52/// [`poll`](Self::poll) is absent, except in DMs, in messages that mention the bot and in the
53/// bot's own messages.
54///
55/// Rare sub-objects are boxed so a typical message stays small (D-054).
56///
57/// Contains floats (through [`Attachment`]), so it is `PartialEq` but not `Eq` (D-064).
58///
59/// discord.js counterpart: `Message`.
60#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
61#[non_exhaustive]
62pub struct Message {
63    /// The message's ID.
64    pub id: MessageId,
65    /// The ID of the channel the message was sent in.
66    pub channel_id: ChannelId,
67    /// The ID of the guild the message was sent in (gateway only).
68    #[serde(default, skip_serializing_if = "Option::is_none")]
69    pub guild_id: Option<GuildId>,
70    /// The author of the message.
71    ///
72    /// For webhook messages this is a pseudo-user built from the webhook's ID, name and avatar
73    /// (check [`webhook_id`](Self::webhook_id)).
74    pub author: User,
75    /// The author's member in the guild (gateway only, guild messages not sent by webhooks).
76    #[serde(default, skip_serializing_if = "Option::is_none")]
77    pub member: Option<Box<PartialMember>>,
78    /// The text content of the message.
79    ///
80    /// Empty without the `MESSAGE_CONTENT` privileged intent (see above).
81    pub content: CompactString,
82    /// When the message was sent.
83    pub timestamp: Timestamp,
84    /// When the message was last edited, if ever.
85    pub edited_timestamp: Option<Timestamp>,
86    /// Whether this was a text-to-speech message (always `false` in `MESSAGE_UPDATE`).
87    pub tts: bool,
88    /// Whether the message mentions `@everyone` (or `@here`).
89    pub mention_everyone: bool,
90    /// The users mentioned in the message, with their members in guild messages received
91    /// through the gateway (D-060).
92    #[serde(default)]
93    pub mentions: Vec<Mention>,
94    /// The roles mentioned in the message.
95    #[serde(default)]
96    pub mention_roles: Vec<RoleId>,
97    /// The channels mentioned in the message. Only channels visible to everyone in public
98    /// guilds are listed, and currently only on crossposted messages.
99    #[serde(default, skip_serializing_if = "Vec::is_empty")]
100    pub mention_channels: Vec<ChannelMention>,
101    /// The attached files (except those referenced in embeds or components).
102    #[serde(default)]
103    pub attachments: Vec<Attachment>,
104    /// The embeds.
105    #[serde(default)]
106    pub embeds: Vec<Embed>,
107    /// The reactions.
108    #[serde(default, skip_serializing_if = "Vec::is_empty")]
109    pub reactions: Vec<Reaction>,
110    /// The value the sender used to check that the message was sent.
111    #[serde(default, skip_serializing_if = "Option::is_none")]
112    pub nonce: Option<Nonce>,
113    /// Whether the message is pinned.
114    pub pinned: bool,
115    /// If the message was generated by a webhook, the webhook's ID.
116    #[serde(default, skip_serializing_if = "Option::is_none")]
117    pub webhook_id: Option<WebhookId>,
118    /// The kind of message.
119    #[serde(rename = "type")]
120    pub kind: MessageType,
121    /// The Rich Presence activity of a Rich Presence chat embed.
122    #[serde(default, skip_serializing_if = "Option::is_none")]
123    pub activity: Option<Box<MessageActivity>>,
124    /// The application of a Rich Presence chat embed.
125    #[serde(default, skip_serializing_if = "Option::is_none")]
126    pub application: Option<Box<PartialApplication>>,
127    /// The application of an interaction response or an application-owned webhook message.
128    #[serde(default, skip_serializing_if = "Option::is_none")]
129    pub application_id: Option<ApplicationId>,
130    /// The message's flags.
131    #[serde(default)]
132    pub flags: MessageFlags,
133    /// The source of a crosspost, channel follow, pin, reply, forward, … (see
134    /// [`MessageReference`]).
135    #[serde(default, skip_serializing_if = "Option::is_none")]
136    pub message_reference: Option<MessageReference>,
137    /// The forwarded message(s), when [`message_reference`](Self::message_reference) is a
138    /// [forward](MessageReferenceType::Forward).
139    #[serde(default, skip_serializing_if = "Vec::is_empty")]
140    pub message_snapshots: Vec<MessageSnapshot>,
141    /// The message this one replies to (or starts a thread from, or a context menu command was
142    /// run on), for messages of type [`Reply`](MessageType::Reply),
143    /// [`ThreadStarterMessage`](MessageType::ThreadStarterMessage) and
144    /// [`ContextMenuCommand`](MessageType::ContextMenuCommand) (D-061).
145    #[serde(default, skip_serializing_if = "ReferencedMessage::is_not_fetched")]
146    pub referenced_message: ReferencedMessage,
147    /// The interaction the message was sent for.
148    #[serde(default, skip_serializing_if = "Option::is_none")]
149    pub interaction_metadata: Option<Box<InteractionMetadata>>,
150    /// The interaction the message responds to. **Deprecated** by Discord in favor of
151    /// [`interaction_metadata`](Self::interaction_metadata).
152    #[serde(default, skip_serializing_if = "Option::is_none")]
153    pub interaction: Option<Box<MessageInteraction>>,
154    /// The components (buttons, select menus, or Components V2 layout with
155    /// [`IS_COMPONENTS_V2`](MessageFlags::IS_COMPONENTS_V2)). Empty without the
156    /// `MESSAGE_CONTENT` privileged intent (see above).
157    #[serde(default, skip_serializing_if = "Vec::is_empty")]
158    pub components: Vec<Component>,
159    /// The thread started from this message (with the current user's thread member, if any).
160    #[serde(default, skip_serializing_if = "Option::is_none")]
161    pub thread: Option<Box<Channel>>,
162    /// The users, members, channels and roles referenced by the message's components
163    /// (Components V2 messages with select menu default values or mentions).
164    #[serde(default, skip_serializing_if = "Option::is_none")]
165    pub resolved: Option<Box<Resolved>>,
166    /// The stickers sent with the message.
167    #[serde(default, skip_serializing_if = "Vec::is_empty")]
168    pub sticker_items: Vec<StickerItem>,
169    /// The full stickers sent with the message. **Deprecated** by Discord in favor of
170    /// [`sticker_items`](Self::sticker_items).
171    #[serde(default, skip_serializing_if = "Vec::is_empty")]
172    pub stickers: Vec<Sticker>,
173    /// The approximate position of the message in its thread: a generally increasing number
174    /// (with possible gaps and duplicates) for messages in threads.
175    #[serde(default, skip_serializing_if = "Option::is_none")]
176    pub position: Option<u32>,
177    /// The role subscription purchase or renewal a
178    /// [`RoleSubscriptionPurchase`](MessageType::RoleSubscriptionPurchase) message announces.
179    #[serde(default, skip_serializing_if = "Option::is_none")]
180    pub role_subscription_data: Option<Box<RoleSubscriptionData>>,
181    /// The poll.
182    #[serde(default, skip_serializing_if = "Option::is_none")]
183    pub poll: Option<Box<Poll>>,
184    /// The call a [`Call`](MessageType::Call) message is about.
185    #[serde(default, skip_serializing_if = "Option::is_none")]
186    pub call: Option<Box<MessageCall>>,
187    /// A client theme shared through the message.
188    #[serde(default, skip_serializing_if = "Option::is_none")]
189    pub shared_client_theme: Option<Box<SharedClientTheme>>,
190    /// The type of the channel the message was sent in (gateway only).
191    #[serde(default, skip_serializing_if = "Option::is_none")]
192    pub channel_type: Option<ChannelType>,
193}
194
195/// A user mentioned in a [`Message`] (D-060).
196///
197/// In guild messages received through the gateway, Discord adds the mentioned user's
198/// [`member`](Self::member). `Mention` dereferences to its [`User`], so `mention.id` works.
199///
200/// discord.js counterpart: `MessageMentions#users` / `MessageMentions#members`.
201#[derive(Clone, Debug, PartialEq, Eq)]
202#[non_exhaustive]
203pub struct Mention {
204    /// The mentioned user.
205    pub user: User,
206    /// The user's member in the guild (gateway only).
207    pub member: Option<Box<PartialMember>>,
208}
209
210impl Mention {
211    /// Creates a mention of `user` without member data.
212    ///
213    /// discord.js counterpart: an element of the `mentions` of `APIMessage` (discord-api-types).
214    #[must_use]
215    pub const fn new(user: User) -> Self {
216        Self { user, member: None }
217    }
218}
219
220impl Deref for Mention {
221    type Target = User;
222
223    fn deref(&self) -> &User {
224        &self.user
225    }
226}
227
228impl From<User> for Mention {
229    fn from(user: User) -> Self {
230        Self::new(user)
231    }
232}
233
234/// The fields of a [`User`] plus `member`, decoded in one pass (D-060). Must list the same
235/// fields with the same serde attributes as [`User`]; `tests::mention_decodes_like_user` checks
236/// that.
237#[derive(Deserialize)]
238struct RawMention {
239    id: UserId,
240    username: CompactString,
241    #[serde(with = "crate::user::discriminator")]
242    discriminator: u16,
243    global_name: Option<CompactString>,
244    avatar: Option<ImageHash>,
245    #[serde(default)]
246    bot: bool,
247    #[serde(default)]
248    system: bool,
249    #[serde(default)]
250    banner: Option<ImageHash>,
251    #[serde(default)]
252    accent_color: Option<u32>,
253    #[serde(default)]
254    public_flags: Option<UserFlags>,
255    #[serde(default)]
256    avatar_decoration_data: Option<Box<AvatarDecorationData>>,
257    #[serde(default)]
258    collectibles: Option<Box<Collectibles>>,
259    #[serde(default)]
260    primary_guild: Option<Box<PrimaryGuild>>,
261    #[serde(default)]
262    member: Option<Box<PartialMember>>,
263}
264
265impl<'de> Deserialize<'de> for Mention {
266    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
267        let raw = RawMention::deserialize(deserializer)?;
268        Ok(Self {
269            user: User {
270                id: raw.id,
271                username: raw.username,
272                discriminator: raw.discriminator,
273                global_name: raw.global_name,
274                avatar: raw.avatar,
275                bot: raw.bot,
276                system: raw.system,
277                banner: raw.banner,
278                accent_color: raw.accent_color,
279                public_flags: raw.public_flags,
280                avatar_decoration_data: raw.avatar_decoration_data,
281                collectibles: raw.collectibles,
282                primary_guild: raw.primary_guild,
283            },
284            member: raw.member,
285        })
286    }
287}
288
289impl Serialize for Mention {
290    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
291        #[derive(Serialize)]
292        struct Flat<'a> {
293            #[serde(flatten)]
294            user: &'a User,
295            #[serde(skip_serializing_if = "Option::is_none")]
296            member: Option<&'a PartialMember>,
297        }
298
299        Flat {
300            user: &self.user,
301            member: self.member.as_deref(),
302        }
303        .serialize(serializer)
304    }
305}
306
307/// The message a reply (or thread starter, or context menu command message) refers to (D-061).
308///
309/// Discord distinguishes an absent field ("did not try to fetch it") from `null` ("it was
310/// deleted"); this type keeps that distinction.
311///
312/// discord.js counterpart: `Message#fetchReference`'s message; the `referenced_message` of `APIMessage` (discord-api-types).
313#[derive(Clone, Debug, Default, PartialEq)]
314#[non_exhaustive]
315pub enum ReferencedMessage {
316    /// The field was absent: Discord did not try to fetch the message, so its state is unknown
317    /// (also the case for messages of other types).
318    #[default]
319    NotFetched,
320    /// The field was `null`: the referenced message was deleted.
321    Deleted,
322    /// The referenced message.
323    Message(Box<Message>),
324}
325
326impl ReferencedMessage {
327    /// Returns the referenced message, if Discord sent it.
328    ///
329    /// discord.js counterpart: `Message#fetchReference`.
330    #[must_use]
331    pub fn as_message(&self) -> Option<&Message> {
332        match self {
333            Self::Message(message) => Some(message),
334            Self::NotFetched | Self::Deleted => None,
335        }
336    }
337
338    /// Converts into the referenced message, if Discord sent it.
339    ///
340    /// discord.js counterpart: `Message#fetchReference`.
341    #[must_use]
342    pub fn into_message(self) -> Option<Box<Message>> {
343        match self {
344            Self::Message(message) => Some(message),
345            Self::NotFetched | Self::Deleted => None,
346        }
347    }
348
349    /// Whether the field was absent (the state of the referenced message is unknown).
350    ///
351    /// discord.js counterpart: none (discord.js fetches the reference on demand).
352    #[must_use]
353    pub const fn is_not_fetched(&self) -> bool {
354        matches!(self, Self::NotFetched)
355    }
356
357    /// Whether the referenced message was deleted.
358    ///
359    /// discord.js counterpart: none (`Message#fetchReference` rejects for a deleted message).
360    #[must_use]
361    pub const fn is_deleted(&self) -> bool {
362        matches!(self, Self::Deleted)
363    }
364}
365
366impl Serialize for ReferencedMessage {
367    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
368        // `NotFetched` is skipped by `Message`; on its own it is written as `null` too.
369        match self {
370            Self::Message(message) => message.serialize(serializer),
371            Self::NotFetched | Self::Deleted => serializer.serialize_none(),
372        }
373    }
374}
375
376impl<'de> Deserialize<'de> for ReferencedMessage {
377    /// Reads `null` as [`Deleted`](Self::Deleted) and an object as the message. An absent field
378    /// becomes [`NotFetched`](Self::NotFetched) through `#[serde(default)]`.
379    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
380        Ok(match Option::<Box<Message>>::deserialize(deserializer)? {
381            Some(message) => Self::Message(message),
382            None => Self::Deleted,
383        })
384    }
385}
386
387/// The [nonce](https://docs.discord.com/developers/resources/message#message-object) a sender
388/// attached to a message: an integer or a string (up to 25 characters).
389///
390/// Integers outside the `i64` range are kept as their decimal text in [`Nonce::String`].
391///
392/// discord.js counterpart: the `nonce` of `APIMessage` (discord-api-types), a string or a number.
393#[derive(Clone, Debug, PartialEq, Eq, Hash)]
394pub enum Nonce {
395    /// An integer nonce.
396    Integer(i64),
397    /// A string nonce.
398    String(CompactString),
399}
400
401impl Serialize for Nonce {
402    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
403        match self {
404            Self::Integer(value) => serializer.serialize_i64(*value),
405            Self::String(value) => serializer.serialize_str(value),
406        }
407    }
408}
409
410impl<'de> Deserialize<'de> for Nonce {
411    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
412        struct NonceVisitor;
413
414        impl Visitor<'_> for NonceVisitor {
415            type Value = Nonce;
416
417            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
418                f.write_str("an integer or string nonce")
419            }
420
421            fn visit_i64<E: DeError>(self, value: i64) -> Result<Nonce, E> {
422                Ok(Nonce::Integer(value))
423            }
424
425            fn visit_u64<E: DeError>(self, value: u64) -> Result<Nonce, E> {
426                Ok(i64::try_from(value).map_or_else(
427                    |_| Nonce::String(compact_str::format_compact!("{value}")),
428                    Nonce::Integer,
429                ))
430            }
431
432            fn visit_str<E: DeError>(self, value: &str) -> Result<Nonce, E> {
433                Ok(Nonce::String(value.into()))
434            }
435        }
436
437        deserializer.deserialize_any(NonceVisitor)
438    }
439}
440
441/// A reference from one message to another: a reply or a forward.
442///
443/// See the [message reference object](https://docs.discord.com/developers/resources/message#message-reference-object).
444///
445/// discord.js counterpart: `MessageReference` / `Message#reference`.
446///
447/// # Examples
448///
449/// Referencing a message to reply to it:
450///
451/// ```
452/// use djs_model::{id::MessageId, message::MessageReference};
453///
454/// let reply = MessageReference::reply(MessageId::new(1_300_000_000_000_000_000));
455/// assert_eq!(
456///     serde_json::to_string(&reply).unwrap(),
457///     r#"{"type":0,"message_id":"1300000000000000000"}"#
458/// );
459/// ```
460#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
461#[non_exhaustive]
462pub struct MessageReference {
463    /// The kind of reference. Defaults to [`MessageReferenceType::Default`] (a reply) when
464    /// absent.
465    #[serde(rename = "type", default)]
466    pub kind: MessageReferenceType,
467    /// The ID of the referenced message.
468    #[serde(default, skip_serializing_if = "Option::is_none")]
469    pub message_id: Option<MessageId>,
470    /// The ID of the referenced message's channel.
471    ///
472    /// Optional when sending a reply, required when forwarding, always present when received.
473    #[serde(default, skip_serializing_if = "Option::is_none")]
474    pub channel_id: Option<ChannelId>,
475    /// The ID of the referenced message's guild.
476    #[serde(default, skip_serializing_if = "Option::is_none")]
477    pub guild_id: Option<GuildId>,
478    /// When sending: whether to fail if the referenced message does not exist (Discord's default
479    /// is `true`) instead of sending a normal, non-reply message.
480    #[serde(default, skip_serializing_if = "Option::is_none")]
481    pub fail_if_not_exists: Option<bool>,
482}
483
484impl MessageReference {
485    /// Creates a reference that replies to `message_id` in the same channel.
486    ///
487    /// discord.js counterpart: the `reply.messageReference` of `MessageCreateOptions`.
488    #[must_use]
489    pub const fn reply(message_id: MessageId) -> Self {
490        Self {
491            kind: MessageReferenceType::Default,
492            message_id: Some(message_id),
493            channel_id: None,
494            guild_id: None,
495            fail_if_not_exists: None,
496        }
497    }
498}
499
500int_enum! {
501    /// The [type of a message reference](https://docs.discord.com/developers/resources/message#message-reference-types).
502    ///
503    /// discord.js counterpart: `MessageReferenceType` (discord-api-types).
504    #[derive(Default)]
505    pub enum MessageReferenceType: u8 {
506        /// A standard reference used by replies (`referenced_message` is populated).
507        #[default]
508        Default = 0,
509        /// A reference used to forward a message at a point in time (`message_snapshots` is
510        /// populated).
511        Forward = 1,
512    }
513}
514
515int_enum! {
516    /// The [type of a message](https://docs.discord.com/developers/resources/message#message-object-message-types).
517    ///
518    /// discord.js counterpart: `MessageType` (re-exported from discord-api-types).
519    pub enum MessageType: u8 {
520        /// A regular message.
521        Default = 0,
522        /// A recipient was added to a group DM.
523        RecipientAdd = 1,
524        /// A recipient was removed from a group DM.
525        RecipientRemove = 2,
526        /// A call was started.
527        Call = 3,
528        /// A channel's name was changed.
529        ChannelNameChange = 4,
530        /// A channel's icon was changed.
531        ChannelIconChange = 5,
532        /// A message was pinned.
533        ChannelPinnedMessage = 6,
534        /// A member joined the guild.
535        UserJoin = 7,
536        /// A member boosted the guild.
537        GuildBoost = 8,
538        /// A boost brought the guild to tier 1.
539        GuildBoostTier1 = 9,
540        /// A boost brought the guild to tier 2.
541        GuildBoostTier2 = 10,
542        /// A boost brought the guild to tier 3.
543        GuildBoostTier3 = 11,
544        /// A channel follow (announcement channel subscription) was added.
545        ChannelFollowAdd = 12,
546        /// The guild was disqualified from Server Discovery.
547        GuildDiscoveryDisqualified = 14,
548        /// The guild was requalified for Server Discovery.
549        GuildDiscoveryRequalified = 15,
550        /// Initial warning of the Server Discovery grace period.
551        GuildDiscoveryGracePeriodInitialWarning = 16,
552        /// Final warning of the Server Discovery grace period.
553        GuildDiscoveryGracePeriodFinalWarning = 17,
554        /// A thread was created from a message.
555        ThreadCreated = 18,
556        /// A reply to another message.
557        Reply = 19,
558        /// The response to a slash (chat input) command.
559        ChatInputCommand = 20,
560        /// The first message of a thread, referencing the message the thread was started from.
561        ThreadStarterMessage = 21,
562        /// A reminder to invite people to the guild.
563        GuildInviteReminder = 22,
564        /// The response to a context menu command.
565        ContextMenuCommand = 23,
566        /// An auto moderation action was taken.
567        AutoModerationAction = 24,
568        /// A role subscription was purchased.
569        RoleSubscriptionPurchase = 25,
570        /// An upsell for a premium interaction.
571        InteractionPremiumUpsell = 26,
572        /// A stage started.
573        StageStart = 27,
574        /// A stage ended.
575        StageEnd = 28,
576        /// A member became a stage speaker.
577        StageSpeaker = 29,
578        /// A member raised their hand on a stage.
579        ///
580        /// Not listed in the official documentation; present in discord-api-types.
581        StageRaiseHand = 30,
582        /// A stage's topic was changed.
583        StageTopic = 31,
584        /// A guild application premium subscription was purchased.
585        GuildApplicationPremiumSubscription = 32,
586        /// Incident alert mode (raid protection) was enabled.
587        GuildIncidentAlertModeEnabled = 36,
588        /// Incident alert mode (raid protection) was disabled.
589        GuildIncidentAlertModeDisabled = 37,
590        /// A raid was reported.
591        GuildIncidentReportRaid = 38,
592        /// A raid report was marked as a false alarm.
593        GuildIncidentReportFalseAlarm = 39,
594        /// A purchase notification.
595        PurchaseNotification = 44,
596        /// The results of a poll.
597        PollResult = 46,
598    }
599}
600
601impl MessageType {
602    /// Returns `true` if messages of this type can be deleted.
603    ///
604    /// Based on the "Deletable" column of the Discord documentation. Unknown types are assumed to
605    /// be deletable. `AutoModerationAction` messages additionally require the `MANAGE_MESSAGES`
606    /// permission.
607    ///
608    /// discord.js counterpart: `Message#deletable`, for the type part.
609    #[must_use]
610    pub const fn is_deletable(self) -> bool {
611        !matches!(
612            self,
613            Self::RecipientAdd
614                | Self::RecipientRemove
615                | Self::Call
616                | Self::ChannelNameChange
617                | Self::ChannelIconChange
618                | Self::ThreadStarterMessage
619        )
620    }
621}
622
623/// The [Rich Presence activity](https://docs.discord.com/developers/resources/message#message-object-message-activity-structure)
624/// of a Rich Presence chat embed.
625///
626/// discord.js counterpart: `MessageActivity`.
627#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
628#[non_exhaustive]
629pub struct MessageActivity {
630    /// The kind of activity.
631    #[serde(rename = "type")]
632    pub kind: MessageActivityType,
633    /// The `party_id` from a Rich Presence event.
634    #[serde(default, skip_serializing_if = "Option::is_none")]
635    pub party_id: Option<CompactString>,
636}
637
638int_enum! {
639    /// The [type of a message activity](https://docs.discord.com/developers/resources/message#message-object-message-activity-types).
640    ///
641    /// discord.js counterpart: `MessageActivityType`.
642    pub enum MessageActivityType: u8 {
643        /// An invitation to join.
644        Join = 1,
645        /// An invitation to spectate.
646        Spectate = 2,
647        /// An invitation to listen along.
648        Listen = 3,
649        /// A request to join.
650        JoinRequest = 5,
651        /// A request to watch a stream.
652        StreamRequest = 6,
653    }
654}
655
656/// The [call](https://docs.discord.com/developers/resources/message#message-call-object) in a
657/// private channel that a [`Call`](MessageType::Call) message is about.
658///
659/// discord.js counterpart: `MessageCall`.
660#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
661#[non_exhaustive]
662pub struct MessageCall {
663    /// The users who took part in the call.
664    pub participants: Vec<UserId>,
665    /// When the call ended (`None` while it is going on).
666    #[serde(default, skip_serializing_if = "Option::is_none")]
667    pub ended_timestamp: Option<Timestamp>,
668}
669
670/// A [forwarded message](https://docs.discord.com/developers/resources/message#message-snapshot-object)
671/// at the time it was forwarded.
672///
673/// discord.js counterpart: `MessageSnapshot` (`Message#messageSnapshots`).
674#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
675#[non_exhaustive]
676pub struct MessageSnapshot {
677    /// The subset of the forwarded message's fields.
678    pub message: SnapshotMessage,
679}
680
681/// The fields of a forwarded message kept in a [`MessageSnapshot`]: a partial [`Message`]
682/// (D-051).
683///
684/// discord.js counterpart: `APIMessageSnapshotFields` (discord-api-types).
685#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
686#[non_exhaustive]
687#[doc(alias = "MessageSnapshotFields")]
688pub struct SnapshotMessage {
689    /// The kind of message.
690    #[serde(rename = "type")]
691    pub kind: MessageType,
692    /// The text content.
693    #[serde(default)]
694    pub content: CompactString,
695    /// The embeds.
696    #[serde(default)]
697    pub embeds: Vec<Embed>,
698    /// The attached files.
699    #[serde(default)]
700    pub attachments: Vec<Attachment>,
701    /// When the message was sent.
702    pub timestamp: Timestamp,
703    /// When the message was last edited, if ever.
704    #[serde(default)]
705    pub edited_timestamp: Option<Timestamp>,
706    /// The message's flags.
707    #[serde(default)]
708    pub flags: MessageFlags,
709    /// The users mentioned in the message.
710    #[serde(default)]
711    pub mentions: Vec<User>,
712    /// The roles mentioned in the message.
713    #[serde(default)]
714    pub mention_roles: Vec<RoleId>,
715    /// The full stickers. **Deprecated** by Discord in favor of
716    /// [`sticker_items`](Self::sticker_items).
717    #[serde(default, skip_serializing_if = "Vec::is_empty")]
718    pub stickers: Vec<Sticker>,
719    /// The stickers.
720    #[serde(default, skip_serializing_if = "Vec::is_empty")]
721    pub sticker_items: Vec<StickerItem>,
722    /// The components.
723    #[serde(default, skip_serializing_if = "Vec::is_empty")]
724    pub components: Vec<Component>,
725}
726
727int_enum! {
728    /// The [kind of a reaction](https://docs.discord.com/developers/resources/message#get-reactions-reaction-types):
729    /// a normal reaction or a super reaction.
730    ///
731    /// discord.js counterpart: `ReactionType`.
732    #[derive(Default)]
733    pub enum ReactionType: u8 {
734        /// A normal reaction.
735        #[default]
736        Normal = 0,
737        /// A super reaction (burst).
738        Burst = 1,
739    }
740}
741
742/// A [reaction](https://docs.discord.com/developers/resources/message#reaction-object) to a
743/// message: one emoji and how often it was used.
744///
745/// discord.js counterpart: `MessageReaction`.
746#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
747#[non_exhaustive]
748#[doc(alias = "MessageReaction")]
749pub struct Reaction {
750    /// How many times the emoji was used, including super reactions.
751    pub count: u32,
752    /// The count split into normal and super reactions.
753    pub count_details: ReactionCountDetails,
754    /// Whether the current user reacted with this emoji.
755    pub me: bool,
756    /// Whether the current user super-reacted with this emoji.
757    pub me_burst: bool,
758    /// The emoji.
759    pub emoji: PartialEmoji,
760    /// The colors of the super reaction animation, as hex strings.
761    #[serde(default)]
762    pub burst_colors: Vec<CompactString>,
763}
764
765impl Reaction {
766    /// Creates a reaction with `emoji` that nobody has used yet (all counts zero), to be
767    /// counted up — for example by a cache applying `MESSAGE_REACTION_ADD`.
768    ///
769    /// discord.js counterpart: `MessageReaction`.
770    ///
771    /// # Examples
772    ///
773    /// ```
774    /// use djs_model::{emoji::PartialEmoji, message::Reaction};
775    ///
776    /// let mut reaction = Reaction::new(PartialEmoji::Unicode { name: "🔥".into() });
777    /// reaction.count += 1;
778    /// reaction.count_details.normal += 1;
779    /// assert_eq!(reaction.count, 1);
780    /// assert!(!reaction.me);
781    /// ```
782    #[must_use]
783    pub fn new(emoji: PartialEmoji) -> Self {
784        Self {
785            count: 0,
786            count_details: ReactionCountDetails::default(),
787            me: false,
788            me_burst: false,
789            emoji,
790            burst_colors: Vec::new(),
791        }
792    }
793}
794
795/// The [count of a reaction](https://docs.discord.com/developers/resources/message#reaction-count-details-object),
796/// split into normal and super ("burst") reactions.
797///
798/// discord.js counterpart: `APIReactionCountDetails` (discord-api-types).
799#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
800#[non_exhaustive]
801pub struct ReactionCountDetails {
802    /// The number of super reactions.
803    pub burst: u32,
804    /// The number of normal reactions.
805    pub normal: u32,
806}
807
808/// A [channel mentioned](https://docs.discord.com/developers/resources/message#channel-mention-object)
809/// in a crossposted message.
810///
811/// discord.js counterpart: `ChannelMention`.
812#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
813#[non_exhaustive]
814pub struct ChannelMention {
815    /// The channel's ID.
816    pub id: ChannelId,
817    /// The guild containing the channel.
818    pub guild_id: GuildId,
819    /// The channel's type.
820    #[serde(rename = "type")]
821    pub kind: ChannelType,
822    /// The channel's name.
823    pub name: CompactString,
824}
825
826/// [Which mentions of a message notify](https://docs.discord.com/developers/resources/message#allowed-mentions-object)
827/// their targets, when sending.
828///
829/// Mentions are always rendered; this only controls the notifications. The
830/// [default](Self::default) (everything empty) notifies nobody. When the field is absent from a
831/// request, Discord notifies every mention in regular messages, and only users in interaction
832/// responses and webhook messages.
833///
834/// The permissions still apply: roles notify only if they are mentionable or the bot has
835/// `MENTION_EVERYONE`, which is also needed for `@everyone` and `@here`.
836///
837/// discord.js counterpart: `MessageMentionOptions` (`allowedMentions`).
838#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
839#[non_exhaustive]
840pub struct AllowedMentions {
841    /// The mention types to parse from the content. Do not combine
842    /// [`Users`](AllowedMentionType::Users) with [`users`](Self::users) (or
843    /// [`Roles`](AllowedMentionType::Roles) with [`roles`](Self::roles)): Discord rejects it.
844    #[serde(default, skip_serializing_if = "Vec::is_empty")]
845    pub parse: Vec<AllowedMentionType>,
846    /// The roles that may be notified (max 100).
847    #[serde(default, skip_serializing_if = "Vec::is_empty")]
848    pub roles: Vec<RoleId>,
849    /// The users that may be notified (max 100).
850    #[serde(default, skip_serializing_if = "Vec::is_empty")]
851    pub users: Vec<UserId>,
852    /// Whether the author of the replied-to message is notified.
853    #[serde(default, skip_serializing_if = "core::ops::Not::not")]
854    pub replied_user: bool,
855}
856
857str_enum! {
858    /// An [allowed mention type](https://docs.discord.com/developers/resources/message#allowed-mentions-object-allowed-mention-types).
859    ///
860    /// discord.js counterpart: `AllowedMentionsTypes`.
861    #[doc(alias = "AllowedMentionsTypes")]
862    pub enum AllowedMentionType {
863        /// Role mentions.
864        Roles = "roles",
865        /// User mentions.
866        Users = "users",
867        /// `@everyone` and `@here`.
868        Everyone = "everyone",
869    }
870}
871
872/// The [role subscription](https://docs.discord.com/developers/resources/message#role-subscription-data-object)
873/// a [`RoleSubscriptionPurchase`](MessageType::RoleSubscriptionPurchase) message announces.
874///
875/// discord.js counterpart: `RoleSubscriptionData`.
876#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
877#[non_exhaustive]
878pub struct RoleSubscriptionData {
879    /// The SKU and listing the user subscribed to.
880    pub role_subscription_listing_id: SkuId,
881    /// The name of the tier.
882    pub tier_name: CompactString,
883    /// The total number of months the user has been subscribed for.
884    pub total_months_subscribed: u32,
885    /// Whether this is a renewal rather than a new purchase.
886    pub is_renewal: bool,
887}
888
889/// A [pinned message](https://docs.discord.com/developers/resources/message#message-pin-object)
890/// (`GET /channels/{channel.id}/messages/pins`).
891///
892/// discord.js counterpart: `MessagePin`.
893#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
894#[non_exhaustive]
895pub struct MessagePin {
896    /// When the message was pinned.
897    pub pinned_at: Timestamp,
898    /// The pinned message.
899    pub message: Message,
900}
901
902/// A [client theme shared](https://docs.discord.com/developers/resources/message#shared-client-theme-object)
903/// through a message.
904///
905/// discord.js counterpart: `SharedClientTheme`.
906#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
907#[non_exhaustive]
908pub struct SharedClientTheme {
909    /// The theme's colors as hex strings (max 5).
910    pub colors: Vec<CompactString>,
911    /// The direction of the gradient, in degrees (max 360).
912    pub gradient_angle: u16,
913    /// The intensity of the colors (max 100).
914    pub base_mix: u8,
915    /// The mode of the theme.
916    #[serde(default, skip_serializing_if = "Option::is_none")]
917    pub base_theme: Option<BaseTheme>,
918}
919
920int_enum! {
921    /// The [mode of a shared client theme](https://docs.discord.com/developers/resources/message#base-theme-types).
922    ///
923    /// discord.js counterpart: `BaseThemeType` (discord-api-types).
924    pub enum BaseTheme: u8 {
925        /// Not set (same as [`Dark`](Self::Dark)).
926        Unset = 0,
927        /// Dark.
928        Dark = 1,
929        /// Light.
930        Light = 2,
931        /// Darker.
932        Darker = 3,
933        /// Midnight.
934        Midnight = 4,
935    }
936}
937
938int_flags! {
939    /// [Flags of a message](https://docs.discord.com/developers/resources/message#message-object-message-flags).
940    ///
941    /// Received on every message. When sending (creating or editing a message, or responding to
942    /// an interaction) only some flags may be set: `SUPPRESS_EMBEDS`, `SUPPRESS_NOTIFICATIONS`,
943    /// `IS_VOICE_MESSAGE`, `IS_COMPONENTS_V2` and, for interaction responses, `EPHEMERAL`.
944    ///
945    /// discord.js counterpart: `MessageFlags` / `MessageFlagsBitField`.
946    ///
947    /// # Examples
948    ///
949    /// ```
950    /// use djs_model::message::MessageFlags;
951    ///
952    /// let flags = MessageFlags::EPHEMERAL | MessageFlags::SUPPRESS_EMBEDS;
953    /// assert_eq!(flags.bits(), 68);
954    /// assert_eq!(serde_json::to_string(&flags).unwrap(), "68");
955    /// ```
956    pub struct MessageFlags: u64 {
957        /// The message was published to the channels following this announcement channel.
958        const CROSSPOSTED = 1 << 0;
959        /// The message is a copy of a message published in a followed announcement channel.
960        const IS_CROSSPOST = 1 << 1;
961        /// Embeds are not shown for this message.
962        const SUPPRESS_EMBEDS = 1 << 2;
963        /// The original of this crossposted message has been deleted.
964        const SOURCE_MESSAGE_DELETED = 1 << 3;
965        /// The message comes from Discord's urgent message system.
966        const URGENT = 1 << 4;
967        /// A thread was started from this message; the thread has the message's ID.
968        const HAS_THREAD = 1 << 5;
969        /// Only the user who triggered the interaction can see the message.
970        const EPHEMERAL = 1 << 6;
971        /// The message is a deferred interaction response: the app is "thinking".
972        const LOADING = 1 << 7;
973        /// Some mentioned roles could not be mentioned, so their members were not added to the
974        /// thread.
975        const FAILED_TO_MENTION_SOME_ROLES_IN_THREAD = 1 << 8;
976        /// The client warns before opening links in this message.
977        ///
978        /// **Undocumented:** known from discord-api-types, not in the official docs; may
979        /// change without notice.
980        const SHOULD_SHOW_LINK_NOT_DISCORD_WARNING = 1 << 10;
981        /// The message does not trigger push or desktop notifications.
982        const SUPPRESS_NOTIFICATIONS = 1 << 12;
983        /// The message is a voice message.
984        const IS_VOICE_MESSAGE = 1 << 13;
985        /// The message contains a snapshot of a forwarded message.
986        const HAS_SNAPSHOT = 1 << 14;
987        /// The message is laid out entirely with components (Components V2) instead of
988        /// `content` and embeds. Once a message has been sent with this flag, the flag cannot be
989        /// removed.
990        const IS_COMPONENTS_V2 = 1 << 15;
991    }
992}
993
994int_flags! {
995    /// [Flags of an attachment](https://docs.discord.com/developers/resources/message#attachment-object-attachment-flags).
996    ///
997    /// discord.js counterpart: `AttachmentFlags` / `AttachmentFlagsBitField`.
998    pub struct AttachmentFlags: u64 {
999        /// The attachment is a clip recorded from a stream.
1000        const IS_CLIP = 1 << 0;
1001        /// The attachment is the thumbnail of a media-channel thread: shown in the channel's
1002        /// grid, not on the message.
1003        const IS_THUMBNAIL = 1 << 1;
1004        /// The attachment was edited with the mobile remix feature. **Deprecated** by Discord.
1005        const IS_REMIX = 1 << 2;
1006        /// The attachment is marked as a spoiler and blurred until clicked.
1007        const IS_SPOILER = 1 << 3;
1008        /// Discord's content scanning flagged the attachment as explicit.
1009        const CONTAINS_EXPLICIT_CONTENT = 1 << 4;
1010        /// The attachment is an animated image.
1011        const IS_ANIMATED = 1 << 5;
1012        /// Discord's content scanning flagged the attachment as gore.
1013        const CONTAINS_GORE_CONTENT = 1 << 6;
1014        /// Discord's content scanning flagged the attachment as self-harm.
1015        const CONTAINS_SELF_HARM_CONTENT = 1 << 7;
1016    }
1017}
1018
1019int_flags! {
1020    /// [Flags of an embed](https://docs.discord.com/developers/resources/message#embed-object-embed-flags).
1021    ///
1022    /// Set by Discord on received embeds.
1023    ///
1024    /// discord.js counterpart: `EmbedFlags` (discord-api-types).
1025    pub struct EmbedFlags: u64 {
1026        /// Discord's content scanning flagged the embed's media as explicit.
1027        const CONTAINS_EXPLICIT_CONTENT = 1 << 4;
1028        /// The embed is the fallback shown for a reply to an activity card.
1029        const IS_CONTENT_INVENTORY_ENTRY = 1 << 5;
1030        /// Discord's content scanning flagged the embed's media as gore.
1031        const CONTAINS_GORE_CONTENT = 1 << 6;
1032        /// Discord's content scanning flagged the embed's media as self-harm.
1033        const CONTAINS_SELF_HARM_CONTENT = 1 << 7;
1034    }
1035}
1036
1037int_flags! {
1038    /// [Flags of an embed's image, thumbnail or video](https://docs.discord.com/developers/resources/message#embed-object-embed-media-flags).
1039    ///
1040    /// discord.js counterpart: `EmbedMediaFlags` (discord-api-types).
1041    pub struct EmbedMediaFlags: u64 {
1042        /// The media is an animated image.
1043        const IS_ANIMATED = 1 << 5;
1044    }
1045}
1046
1047#[cfg(test)]
1048mod tests {
1049    use super::*;
1050
1051    #[test]
1052    fn sizes() {
1053        // Guards against accidental growth of the hottest gateway type (D-054). A typical
1054        // message is decoded into one allocation of this size (plus its strings and vectors).
1055        assert!(size_of::<Message>() <= 656, "{}", size_of::<Message>());
1056        assert!(size_of::<Mention>() <= 152, "{}", size_of::<Mention>());
1057        assert!(
1058            size_of::<Attachment>() <= 312,
1059            "{}",
1060            size_of::<Attachment>()
1061        );
1062        assert!(size_of::<Embed>() <= 232, "{}", size_of::<Embed>());
1063        assert_eq!(size_of::<ReferencedMessage>(), 16);
1064    }
1065
1066    #[test]
1067    fn message_type_forward_compatible() {
1068        assert_eq!(MessageType::from(19), MessageType::Reply);
1069        assert_eq!(MessageType::from(250), MessageType::Unknown(250));
1070        assert!(MessageType::from(250).is_unknown());
1071        assert!(!MessageType::Reply.is_unknown());
1072        // `Unknown` holding a known value is equal to the named variant.
1073        assert_eq!(MessageType::Unknown(0), MessageType::Default);
1074        assert!(!MessageType::Unknown(0).is_unknown());
1075        assert_eq!(serde_json::to_string(&MessageType::Reply).unwrap(), "19");
1076    }
1077}