djs-model 0.1.0-alpha.2

Discord API v10 types — users, guilds, channels, messages, interactions and gateway events.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
//! [Messages](https://docs.discord.com/developers/resources/message): their content, embeds,
//! attachments, reactions, references and everything else attached to them.

mod attachment;
mod embed;
mod interaction_metadata;

use core::{fmt, ops::Deref};

use compact_str::CompactString;
use serde::{
    Deserialize, Deserializer, Serialize, Serializer,
    de::{Error as DeError, Visitor},
};

pub use self::{
    attachment::{Attachment, AttachmentRequest, AttachmentRequestId},
    embed::{
        Embed, EmbedAuthor, EmbedField, EmbedFooter, EmbedImage, EmbedProvider, EmbedType,
        EmbedVideo,
    },
    interaction_metadata::{
        CommandMetadata, ComponentMetadata, InteractionMetadata, ModalSubmitMetadata,
        UnknownMetadata,
    },
};
use crate::{
    application::PartialApplication,
    channel::{Channel, ChannelType},
    component::Component,
    emoji::PartialEmoji,
    guild::PartialMember,
    id::{ApplicationId, ChannelId, GuildId, MessageId, RoleId, SkuId, UserId, WebhookId},
    interaction::{MessageInteraction, Resolved},
    macros::{int_enum, int_flags, str_enum},
    poll::Poll,
    sticker::{Sticker, StickerItem},
    user::{AvatarDecorationData, Collectibles, PrimaryGuild, User, UserFlags},
    util::{ImageHash, Timestamp},
};

/// A [message](https://docs.discord.com/developers/resources/message#message-object) sent in a
/// channel.
///
/// The same type is used for messages received through the gateway (`MESSAGE_CREATE`,
/// `MESSAGE_UPDATE`) and from REST. The gateway adds a few fields ([`guild_id`](Self::guild_id),
/// [`member`](Self::member), the members of [`mentions`](Self::mentions),
/// [`channel_type`](Self::channel_type)) that REST responses do not have.
///
/// Without the `MESSAGE_CONTENT` privileged intent, [`content`](Self::content),
/// [`embeds`](Self::embeds) and [`attachments`](Self::attachments) are empty and
/// [`poll`](Self::poll) is absent, except in DMs, in messages that mention the bot and in the
/// bot's own messages.
///
/// Rare sub-objects are boxed so a typical message stays small (D-054).
///
/// Contains floats (through [`Attachment`]), so it is `PartialEq` but not `Eq` (D-064).
///
/// discord.js counterpart: `Message`.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Message {
    /// The message's ID.
    pub id: MessageId,
    /// The ID of the channel the message was sent in.
    pub channel_id: ChannelId,
    /// The ID of the guild the message was sent in (gateway only).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub guild_id: Option<GuildId>,
    /// The author of the message.
    ///
    /// For webhook messages this is a pseudo-user built from the webhook's ID, name and avatar
    /// (check [`webhook_id`](Self::webhook_id)).
    pub author: User,
    /// The author's member in the guild (gateway only, guild messages not sent by webhooks).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub member: Option<Box<PartialMember>>,
    /// The text content of the message.
    ///
    /// Empty without the `MESSAGE_CONTENT` privileged intent (see above).
    pub content: CompactString,
    /// When the message was sent.
    pub timestamp: Timestamp,
    /// When the message was last edited, if ever.
    pub edited_timestamp: Option<Timestamp>,
    /// Whether this was a text-to-speech message (always `false` in `MESSAGE_UPDATE`).
    pub tts: bool,
    /// Whether the message mentions `@everyone` (or `@here`).
    pub mention_everyone: bool,
    /// The users mentioned in the message, with their members in guild messages received
    /// through the gateway (D-060).
    #[serde(default)]
    pub mentions: Vec<Mention>,
    /// The roles mentioned in the message.
    #[serde(default)]
    pub mention_roles: Vec<RoleId>,
    /// The channels mentioned in the message. Only channels visible to everyone in public
    /// guilds are listed, and currently only on crossposted messages.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub mention_channels: Vec<ChannelMention>,
    /// The attached files (except those referenced in embeds or components).
    #[serde(default)]
    pub attachments: Vec<Attachment>,
    /// The embeds.
    #[serde(default)]
    pub embeds: Vec<Embed>,
    /// The reactions.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub reactions: Vec<Reaction>,
    /// The value the sender used to check that the message was sent.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub nonce: Option<Nonce>,
    /// Whether the message is pinned.
    pub pinned: bool,
    /// If the message was generated by a webhook, the webhook's ID.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub webhook_id: Option<WebhookId>,
    /// The kind of message.
    #[serde(rename = "type")]
    pub kind: MessageType,
    /// The Rich Presence activity of a Rich Presence chat embed.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub activity: Option<Box<MessageActivity>>,
    /// The application of a Rich Presence chat embed.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub application: Option<Box<PartialApplication>>,
    /// The application of an interaction response or an application-owned webhook message.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub application_id: Option<ApplicationId>,
    /// The message's flags.
    #[serde(default)]
    pub flags: MessageFlags,
    /// The source of a crosspost, channel follow, pin, reply, forward, … (see
    /// [`MessageReference`]).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub message_reference: Option<MessageReference>,
    /// The forwarded message(s), when [`message_reference`](Self::message_reference) is a
    /// [forward](MessageReferenceType::Forward).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub message_snapshots: Vec<MessageSnapshot>,
    /// The message this one replies to (or starts a thread from, or a context menu command was
    /// run on), for messages of type [`Reply`](MessageType::Reply),
    /// [`ThreadStarterMessage`](MessageType::ThreadStarterMessage) and
    /// [`ContextMenuCommand`](MessageType::ContextMenuCommand) (D-061).
    #[serde(default, skip_serializing_if = "ReferencedMessage::is_not_fetched")]
    pub referenced_message: ReferencedMessage,
    /// The interaction the message was sent for.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub interaction_metadata: Option<Box<InteractionMetadata>>,
    /// The interaction the message responds to. **Deprecated** by Discord in favor of
    /// [`interaction_metadata`](Self::interaction_metadata).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub interaction: Option<Box<MessageInteraction>>,
    /// The components (buttons, select menus, or Components V2 layout with
    /// [`IS_COMPONENTS_V2`](MessageFlags::IS_COMPONENTS_V2)). Empty without the
    /// `MESSAGE_CONTENT` privileged intent (see above).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub components: Vec<Component>,
    /// The thread started from this message (with the current user's thread member, if any).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub thread: Option<Box<Channel>>,
    /// The users, members, channels and roles referenced by the message's components
    /// (Components V2 messages with select menu default values or mentions).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub resolved: Option<Box<Resolved>>,
    /// The stickers sent with the message.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub sticker_items: Vec<StickerItem>,
    /// The full stickers sent with the message. **Deprecated** by Discord in favor of
    /// [`sticker_items`](Self::sticker_items).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub stickers: Vec<Sticker>,
    /// The approximate position of the message in its thread: a generally increasing number
    /// (with possible gaps and duplicates) for messages in threads.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub position: Option<u32>,
    /// The role subscription purchase or renewal a
    /// [`RoleSubscriptionPurchase`](MessageType::RoleSubscriptionPurchase) message announces.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub role_subscription_data: Option<Box<RoleSubscriptionData>>,
    /// The poll.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub poll: Option<Box<Poll>>,
    /// The call a [`Call`](MessageType::Call) message is about.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub call: Option<Box<MessageCall>>,
    /// A client theme shared through the message.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub shared_client_theme: Option<Box<SharedClientTheme>>,
    /// The type of the channel the message was sent in (gateway only).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub channel_type: Option<ChannelType>,
}

/// A user mentioned in a [`Message`] (D-060).
///
/// In guild messages received through the gateway, Discord adds the mentioned user's
/// [`member`](Self::member). `Mention` dereferences to its [`User`], so `mention.id` works.
///
/// discord.js counterpart: `MessageMentions#users` / `MessageMentions#members`.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Mention {
    /// The mentioned user.
    pub user: User,
    /// The user's member in the guild (gateway only).
    pub member: Option<Box<PartialMember>>,
}

impl Mention {
    /// Creates a mention of `user` without member data.
    ///
    /// discord.js counterpart: an element of the `mentions` of `APIMessage` (discord-api-types).
    #[must_use]
    pub const fn new(user: User) -> Self {
        Self { user, member: None }
    }
}

impl Deref for Mention {
    type Target = User;

    fn deref(&self) -> &User {
        &self.user
    }
}

impl From<User> for Mention {
    fn from(user: User) -> Self {
        Self::new(user)
    }
}

/// The fields of a [`User`] plus `member`, decoded in one pass (D-060). Must list the same
/// fields with the same serde attributes as [`User`]; `tests::mention_decodes_like_user` checks
/// that.
#[derive(Deserialize)]
struct RawMention {
    id: UserId,
    username: CompactString,
    #[serde(with = "crate::user::discriminator")]
    discriminator: u16,
    global_name: Option<CompactString>,
    avatar: Option<ImageHash>,
    #[serde(default)]
    bot: bool,
    #[serde(default)]
    system: bool,
    #[serde(default)]
    banner: Option<ImageHash>,
    #[serde(default)]
    accent_color: Option<u32>,
    #[serde(default)]
    public_flags: Option<UserFlags>,
    #[serde(default)]
    avatar_decoration_data: Option<Box<AvatarDecorationData>>,
    #[serde(default)]
    collectibles: Option<Box<Collectibles>>,
    #[serde(default)]
    primary_guild: Option<Box<PrimaryGuild>>,
    #[serde(default)]
    member: Option<Box<PartialMember>>,
}

impl<'de> Deserialize<'de> for Mention {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let raw = RawMention::deserialize(deserializer)?;
        Ok(Self {
            user: User {
                id: raw.id,
                username: raw.username,
                discriminator: raw.discriminator,
                global_name: raw.global_name,
                avatar: raw.avatar,
                bot: raw.bot,
                system: raw.system,
                banner: raw.banner,
                accent_color: raw.accent_color,
                public_flags: raw.public_flags,
                avatar_decoration_data: raw.avatar_decoration_data,
                collectibles: raw.collectibles,
                primary_guild: raw.primary_guild,
            },
            member: raw.member,
        })
    }
}

impl Serialize for Mention {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        #[derive(Serialize)]
        struct Flat<'a> {
            #[serde(flatten)]
            user: &'a User,
            #[serde(skip_serializing_if = "Option::is_none")]
            member: Option<&'a PartialMember>,
        }

        Flat {
            user: &self.user,
            member: self.member.as_deref(),
        }
        .serialize(serializer)
    }
}

/// The message a reply (or thread starter, or context menu command message) refers to (D-061).
///
/// Discord distinguishes an absent field ("did not try to fetch it") from `null` ("it was
/// deleted"); this type keeps that distinction.
///
/// discord.js counterpart: `Message#fetchReference`'s message; the `referenced_message` of `APIMessage` (discord-api-types).
#[derive(Clone, Debug, Default, PartialEq)]
#[non_exhaustive]
pub enum ReferencedMessage {
    /// The field was absent: Discord did not try to fetch the message, so its state is unknown
    /// (also the case for messages of other types).
    #[default]
    NotFetched,
    /// The field was `null`: the referenced message was deleted.
    Deleted,
    /// The referenced message.
    Message(Box<Message>),
}

impl ReferencedMessage {
    /// Returns the referenced message, if Discord sent it.
    ///
    /// discord.js counterpart: `Message#fetchReference`.
    #[must_use]
    pub fn as_message(&self) -> Option<&Message> {
        match self {
            Self::Message(message) => Some(message),
            Self::NotFetched | Self::Deleted => None,
        }
    }

    /// Converts into the referenced message, if Discord sent it.
    ///
    /// discord.js counterpart: `Message#fetchReference`.
    #[must_use]
    pub fn into_message(self) -> Option<Box<Message>> {
        match self {
            Self::Message(message) => Some(message),
            Self::NotFetched | Self::Deleted => None,
        }
    }

    /// Whether the field was absent (the state of the referenced message is unknown).
    ///
    /// discord.js counterpart: none (discord.js fetches the reference on demand).
    #[must_use]
    pub const fn is_not_fetched(&self) -> bool {
        matches!(self, Self::NotFetched)
    }

    /// Whether the referenced message was deleted.
    ///
    /// discord.js counterpart: none (`Message#fetchReference` rejects for a deleted message).
    #[must_use]
    pub const fn is_deleted(&self) -> bool {
        matches!(self, Self::Deleted)
    }
}

impl Serialize for ReferencedMessage {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        // `NotFetched` is skipped by `Message`; on its own it is written as `null` too.
        match self {
            Self::Message(message) => message.serialize(serializer),
            Self::NotFetched | Self::Deleted => serializer.serialize_none(),
        }
    }
}

impl<'de> Deserialize<'de> for ReferencedMessage {
    /// Reads `null` as [`Deleted`](Self::Deleted) and an object as the message. An absent field
    /// becomes [`NotFetched`](Self::NotFetched) through `#[serde(default)]`.
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        Ok(match Option::<Box<Message>>::deserialize(deserializer)? {
            Some(message) => Self::Message(message),
            None => Self::Deleted,
        })
    }
}

/// The [nonce](https://docs.discord.com/developers/resources/message#message-object) a sender
/// attached to a message: an integer or a string (up to 25 characters).
///
/// Integers outside the `i64` range are kept as their decimal text in [`Nonce::String`].
///
/// discord.js counterpart: the `nonce` of `APIMessage` (discord-api-types), a string or a number.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum Nonce {
    /// An integer nonce.
    Integer(i64),
    /// A string nonce.
    String(CompactString),
}

impl Serialize for Nonce {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        match self {
            Self::Integer(value) => serializer.serialize_i64(*value),
            Self::String(value) => serializer.serialize_str(value),
        }
    }
}

impl<'de> Deserialize<'de> for Nonce {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        struct NonceVisitor;

        impl Visitor<'_> for NonceVisitor {
            type Value = Nonce;

            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                f.write_str("an integer or string nonce")
            }

            fn visit_i64<E: DeError>(self, value: i64) -> Result<Nonce, E> {
                Ok(Nonce::Integer(value))
            }

            fn visit_u64<E: DeError>(self, value: u64) -> Result<Nonce, E> {
                Ok(i64::try_from(value).map_or_else(
                    |_| Nonce::String(compact_str::format_compact!("{value}")),
                    Nonce::Integer,
                ))
            }

            fn visit_str<E: DeError>(self, value: &str) -> Result<Nonce, E> {
                Ok(Nonce::String(value.into()))
            }
        }

        deserializer.deserialize_any(NonceVisitor)
    }
}

/// A reference from one message to another: a reply or a forward.
///
/// See the [message reference object](https://docs.discord.com/developers/resources/message#message-reference-object).
///
/// discord.js counterpart: `MessageReference` / `Message#reference`.
///
/// # Examples
///
/// Referencing a message to reply to it:
///
/// ```
/// use djs_model::{id::MessageId, message::MessageReference};
///
/// let reply = MessageReference::reply(MessageId::new(1_300_000_000_000_000_000));
/// assert_eq!(
///     serde_json::to_string(&reply).unwrap(),
///     r#"{"type":0,"message_id":"1300000000000000000"}"#
/// );
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[non_exhaustive]
pub struct MessageReference {
    /// The kind of reference. Defaults to [`MessageReferenceType::Default`] (a reply) when
    /// absent.
    #[serde(rename = "type", default)]
    pub kind: MessageReferenceType,
    /// The ID of the referenced message.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub message_id: Option<MessageId>,
    /// The ID of the referenced message's channel.
    ///
    /// Optional when sending a reply, required when forwarding, always present when received.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub channel_id: Option<ChannelId>,
    /// The ID of the referenced message's guild.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub guild_id: Option<GuildId>,
    /// When sending: whether to fail if the referenced message does not exist (Discord's default
    /// is `true`) instead of sending a normal, non-reply message.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub fail_if_not_exists: Option<bool>,
}

impl MessageReference {
    /// Creates a reference that replies to `message_id` in the same channel.
    ///
    /// discord.js counterpart: the `reply.messageReference` of `MessageCreateOptions`.
    #[must_use]
    pub const fn reply(message_id: MessageId) -> Self {
        Self {
            kind: MessageReferenceType::Default,
            message_id: Some(message_id),
            channel_id: None,
            guild_id: None,
            fail_if_not_exists: None,
        }
    }
}

int_enum! {
    /// The [type of a message reference](https://docs.discord.com/developers/resources/message#message-reference-types).
    ///
    /// discord.js counterpart: `MessageReferenceType` (discord-api-types).
    #[derive(Default)]
    pub enum MessageReferenceType: u8 {
        /// A standard reference used by replies (`referenced_message` is populated).
        #[default]
        Default = 0,
        /// A reference used to forward a message at a point in time (`message_snapshots` is
        /// populated).
        Forward = 1,
    }
}

int_enum! {
    /// The [type of a message](https://docs.discord.com/developers/resources/message#message-object-message-types).
    ///
    /// discord.js counterpart: `MessageType` (re-exported from discord-api-types).
    pub enum MessageType: u8 {
        /// A regular message.
        Default = 0,
        /// A recipient was added to a group DM.
        RecipientAdd = 1,
        /// A recipient was removed from a group DM.
        RecipientRemove = 2,
        /// A call was started.
        Call = 3,
        /// A channel's name was changed.
        ChannelNameChange = 4,
        /// A channel's icon was changed.
        ChannelIconChange = 5,
        /// A message was pinned.
        ChannelPinnedMessage = 6,
        /// A member joined the guild.
        UserJoin = 7,
        /// A member boosted the guild.
        GuildBoost = 8,
        /// A boost brought the guild to tier 1.
        GuildBoostTier1 = 9,
        /// A boost brought the guild to tier 2.
        GuildBoostTier2 = 10,
        /// A boost brought the guild to tier 3.
        GuildBoostTier3 = 11,
        /// A channel follow (announcement channel subscription) was added.
        ChannelFollowAdd = 12,
        /// The guild was disqualified from Server Discovery.
        GuildDiscoveryDisqualified = 14,
        /// The guild was requalified for Server Discovery.
        GuildDiscoveryRequalified = 15,
        /// Initial warning of the Server Discovery grace period.
        GuildDiscoveryGracePeriodInitialWarning = 16,
        /// Final warning of the Server Discovery grace period.
        GuildDiscoveryGracePeriodFinalWarning = 17,
        /// A thread was created from a message.
        ThreadCreated = 18,
        /// A reply to another message.
        Reply = 19,
        /// The response to a slash (chat input) command.
        ChatInputCommand = 20,
        /// The first message of a thread, referencing the message the thread was started from.
        ThreadStarterMessage = 21,
        /// A reminder to invite people to the guild.
        GuildInviteReminder = 22,
        /// The response to a context menu command.
        ContextMenuCommand = 23,
        /// An auto moderation action was taken.
        AutoModerationAction = 24,
        /// A role subscription was purchased.
        RoleSubscriptionPurchase = 25,
        /// An upsell for a premium interaction.
        InteractionPremiumUpsell = 26,
        /// A stage started.
        StageStart = 27,
        /// A stage ended.
        StageEnd = 28,
        /// A member became a stage speaker.
        StageSpeaker = 29,
        /// A member raised their hand on a stage.
        ///
        /// Not listed in the official documentation; present in discord-api-types.
        StageRaiseHand = 30,
        /// A stage's topic was changed.
        StageTopic = 31,
        /// A guild application premium subscription was purchased.
        GuildApplicationPremiumSubscription = 32,
        /// Incident alert mode (raid protection) was enabled.
        GuildIncidentAlertModeEnabled = 36,
        /// Incident alert mode (raid protection) was disabled.
        GuildIncidentAlertModeDisabled = 37,
        /// A raid was reported.
        GuildIncidentReportRaid = 38,
        /// A raid report was marked as a false alarm.
        GuildIncidentReportFalseAlarm = 39,
        /// A purchase notification.
        PurchaseNotification = 44,
        /// The results of a poll.
        PollResult = 46,
    }
}

impl MessageType {
    /// Returns `true` if messages of this type can be deleted.
    ///
    /// Based on the "Deletable" column of the Discord documentation. Unknown types are assumed to
    /// be deletable. `AutoModerationAction` messages additionally require the `MANAGE_MESSAGES`
    /// permission.
    ///
    /// discord.js counterpart: `Message#deletable`, for the type part.
    #[must_use]
    pub const fn is_deletable(self) -> bool {
        !matches!(
            self,
            Self::RecipientAdd
                | Self::RecipientRemove
                | Self::Call
                | Self::ChannelNameChange
                | Self::ChannelIconChange
                | Self::ThreadStarterMessage
        )
    }
}

/// The [Rich Presence activity](https://docs.discord.com/developers/resources/message#message-object-message-activity-structure)
/// of a Rich Presence chat embed.
///
/// discord.js counterpart: `MessageActivity`.
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[non_exhaustive]
pub struct MessageActivity {
    /// The kind of activity.
    #[serde(rename = "type")]
    pub kind: MessageActivityType,
    /// The `party_id` from a Rich Presence event.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub party_id: Option<CompactString>,
}

int_enum! {
    /// The [type of a message activity](https://docs.discord.com/developers/resources/message#message-object-message-activity-types).
    ///
    /// discord.js counterpart: `MessageActivityType`.
    pub enum MessageActivityType: u8 {
        /// An invitation to join.
        Join = 1,
        /// An invitation to spectate.
        Spectate = 2,
        /// An invitation to listen along.
        Listen = 3,
        /// A request to join.
        JoinRequest = 5,
        /// A request to watch a stream.
        StreamRequest = 6,
    }
}

/// The [call](https://docs.discord.com/developers/resources/message#message-call-object) in a
/// private channel that a [`Call`](MessageType::Call) message is about.
///
/// discord.js counterpart: `MessageCall`.
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[non_exhaustive]
pub struct MessageCall {
    /// The users who took part in the call.
    pub participants: Vec<UserId>,
    /// When the call ended (`None` while it is going on).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ended_timestamp: Option<Timestamp>,
}

/// A [forwarded message](https://docs.discord.com/developers/resources/message#message-snapshot-object)
/// at the time it was forwarded.
///
/// discord.js counterpart: `MessageSnapshot` (`Message#messageSnapshots`).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct MessageSnapshot {
    /// The subset of the forwarded message's fields.
    pub message: SnapshotMessage,
}

/// The fields of a forwarded message kept in a [`MessageSnapshot`]: a partial [`Message`]
/// (D-051).
///
/// discord.js counterpart: `APIMessageSnapshotFields` (discord-api-types).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
#[doc(alias = "MessageSnapshotFields")]
pub struct SnapshotMessage {
    /// The kind of message.
    #[serde(rename = "type")]
    pub kind: MessageType,
    /// The text content.
    #[serde(default)]
    pub content: CompactString,
    /// The embeds.
    #[serde(default)]
    pub embeds: Vec<Embed>,
    /// The attached files.
    #[serde(default)]
    pub attachments: Vec<Attachment>,
    /// When the message was sent.
    pub timestamp: Timestamp,
    /// When the message was last edited, if ever.
    #[serde(default)]
    pub edited_timestamp: Option<Timestamp>,
    /// The message's flags.
    #[serde(default)]
    pub flags: MessageFlags,
    /// The users mentioned in the message.
    #[serde(default)]
    pub mentions: Vec<User>,
    /// The roles mentioned in the message.
    #[serde(default)]
    pub mention_roles: Vec<RoleId>,
    /// The full stickers. **Deprecated** by Discord in favor of
    /// [`sticker_items`](Self::sticker_items).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub stickers: Vec<Sticker>,
    /// The stickers.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub sticker_items: Vec<StickerItem>,
    /// The components.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub components: Vec<Component>,
}

int_enum! {
    /// The [kind of a reaction](https://docs.discord.com/developers/resources/message#get-reactions-reaction-types):
    /// a normal reaction or a super reaction.
    ///
    /// discord.js counterpart: `ReactionType`.
    #[derive(Default)]
    pub enum ReactionType: u8 {
        /// A normal reaction.
        #[default]
        Normal = 0,
        /// A super reaction (burst).
        Burst = 1,
    }
}

/// A [reaction](https://docs.discord.com/developers/resources/message#reaction-object) to a
/// message: one emoji and how often it was used.
///
/// discord.js counterpart: `MessageReaction`.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
#[doc(alias = "MessageReaction")]
pub struct Reaction {
    /// How many times the emoji was used, including super reactions.
    pub count: u32,
    /// The count split into normal and super reactions.
    pub count_details: ReactionCountDetails,
    /// Whether the current user reacted with this emoji.
    pub me: bool,
    /// Whether the current user super-reacted with this emoji.
    pub me_burst: bool,
    /// The emoji.
    pub emoji: PartialEmoji,
    /// The colors of the super reaction animation, as hex strings.
    #[serde(default)]
    pub burst_colors: Vec<CompactString>,
}

impl Reaction {
    /// Creates a reaction with `emoji` that nobody has used yet (all counts zero), to be
    /// counted up — for example by a cache applying `MESSAGE_REACTION_ADD`.
    ///
    /// discord.js counterpart: `MessageReaction`.
    ///
    /// # Examples
    ///
    /// ```
    /// use djs_model::{emoji::PartialEmoji, message::Reaction};
    ///
    /// let mut reaction = Reaction::new(PartialEmoji::Unicode { name: "🔥".into() });
    /// reaction.count += 1;
    /// reaction.count_details.normal += 1;
    /// assert_eq!(reaction.count, 1);
    /// assert!(!reaction.me);
    /// ```
    #[must_use]
    pub fn new(emoji: PartialEmoji) -> Self {
        Self {
            count: 0,
            count_details: ReactionCountDetails::default(),
            me: false,
            me_burst: false,
            emoji,
            burst_colors: Vec::new(),
        }
    }
}

/// The [count of a reaction](https://docs.discord.com/developers/resources/message#reaction-count-details-object),
/// split into normal and super ("burst") reactions.
///
/// discord.js counterpart: `APIReactionCountDetails` (discord-api-types).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[non_exhaustive]
pub struct ReactionCountDetails {
    /// The number of super reactions.
    pub burst: u32,
    /// The number of normal reactions.
    pub normal: u32,
}

/// A [channel mentioned](https://docs.discord.com/developers/resources/message#channel-mention-object)
/// in a crossposted message.
///
/// discord.js counterpart: `ChannelMention`.
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[non_exhaustive]
pub struct ChannelMention {
    /// The channel's ID.
    pub id: ChannelId,
    /// The guild containing the channel.
    pub guild_id: GuildId,
    /// The channel's type.
    #[serde(rename = "type")]
    pub kind: ChannelType,
    /// The channel's name.
    pub name: CompactString,
}

/// [Which mentions of a message notify](https://docs.discord.com/developers/resources/message#allowed-mentions-object)
/// their targets, when sending.
///
/// Mentions are always rendered; this only controls the notifications. The
/// [default](Self::default) (everything empty) notifies nobody. When the field is absent from a
/// request, Discord notifies every mention in regular messages, and only users in interaction
/// responses and webhook messages.
///
/// The permissions still apply: roles notify only if they are mentionable or the bot has
/// `MENTION_EVERYONE`, which is also needed for `@everyone` and `@here`.
///
/// discord.js counterpart: `MessageMentionOptions` (`allowedMentions`).
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[non_exhaustive]
pub struct AllowedMentions {
    /// The mention types to parse from the content. Do not combine
    /// [`Users`](AllowedMentionType::Users) with [`users`](Self::users) (or
    /// [`Roles`](AllowedMentionType::Roles) with [`roles`](Self::roles)): Discord rejects it.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub parse: Vec<AllowedMentionType>,
    /// The roles that may be notified (max 100).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub roles: Vec<RoleId>,
    /// The users that may be notified (max 100).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub users: Vec<UserId>,
    /// Whether the author of the replied-to message is notified.
    #[serde(default, skip_serializing_if = "core::ops::Not::not")]
    pub replied_user: bool,
}

str_enum! {
    /// An [allowed mention type](https://docs.discord.com/developers/resources/message#allowed-mentions-object-allowed-mention-types).
    ///
    /// discord.js counterpart: `AllowedMentionsTypes`.
    #[doc(alias = "AllowedMentionsTypes")]
    pub enum AllowedMentionType {
        /// Role mentions.
        Roles = "roles",
        /// User mentions.
        Users = "users",
        /// `@everyone` and `@here`.
        Everyone = "everyone",
    }
}

/// The [role subscription](https://docs.discord.com/developers/resources/message#role-subscription-data-object)
/// a [`RoleSubscriptionPurchase`](MessageType::RoleSubscriptionPurchase) message announces.
///
/// discord.js counterpart: `RoleSubscriptionData`.
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[non_exhaustive]
pub struct RoleSubscriptionData {
    /// The SKU and listing the user subscribed to.
    pub role_subscription_listing_id: SkuId,
    /// The name of the tier.
    pub tier_name: CompactString,
    /// The total number of months the user has been subscribed for.
    pub total_months_subscribed: u32,
    /// Whether this is a renewal rather than a new purchase.
    pub is_renewal: bool,
}

/// A [pinned message](https://docs.discord.com/developers/resources/message#message-pin-object)
/// (`GET /channels/{channel.id}/messages/pins`).
///
/// discord.js counterpart: `MessagePin`.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct MessagePin {
    /// When the message was pinned.
    pub pinned_at: Timestamp,
    /// The pinned message.
    pub message: Message,
}

/// A [client theme shared](https://docs.discord.com/developers/resources/message#shared-client-theme-object)
/// through a message.
///
/// discord.js counterpart: `SharedClientTheme`.
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[non_exhaustive]
pub struct SharedClientTheme {
    /// The theme's colors as hex strings (max 5).
    pub colors: Vec<CompactString>,
    /// The direction of the gradient, in degrees (max 360).
    pub gradient_angle: u16,
    /// The intensity of the colors (max 100).
    pub base_mix: u8,
    /// The mode of the theme.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub base_theme: Option<BaseTheme>,
}

int_enum! {
    /// The [mode of a shared client theme](https://docs.discord.com/developers/resources/message#base-theme-types).
    ///
    /// discord.js counterpart: `BaseThemeType` (discord-api-types).
    pub enum BaseTheme: u8 {
        /// Not set (same as [`Dark`](Self::Dark)).
        Unset = 0,
        /// Dark.
        Dark = 1,
        /// Light.
        Light = 2,
        /// Darker.
        Darker = 3,
        /// Midnight.
        Midnight = 4,
    }
}

int_flags! {
    /// [Flags of a message](https://docs.discord.com/developers/resources/message#message-object-message-flags).
    ///
    /// Received on every message. When sending (creating or editing a message, or responding to
    /// an interaction) only some flags may be set: `SUPPRESS_EMBEDS`, `SUPPRESS_NOTIFICATIONS`,
    /// `IS_VOICE_MESSAGE`, `IS_COMPONENTS_V2` and, for interaction responses, `EPHEMERAL`.
    ///
    /// discord.js counterpart: `MessageFlags` / `MessageFlagsBitField`.
    ///
    /// # Examples
    ///
    /// ```
    /// use djs_model::message::MessageFlags;
    ///
    /// let flags = MessageFlags::EPHEMERAL | MessageFlags::SUPPRESS_EMBEDS;
    /// assert_eq!(flags.bits(), 68);
    /// assert_eq!(serde_json::to_string(&flags).unwrap(), "68");
    /// ```
    pub struct MessageFlags: u64 {
        /// The message was published to the channels following this announcement channel.
        const CROSSPOSTED = 1 << 0;
        /// The message is a copy of a message published in a followed announcement channel.
        const IS_CROSSPOST = 1 << 1;
        /// Embeds are not shown for this message.
        const SUPPRESS_EMBEDS = 1 << 2;
        /// The original of this crossposted message has been deleted.
        const SOURCE_MESSAGE_DELETED = 1 << 3;
        /// The message comes from Discord's urgent message system.
        const URGENT = 1 << 4;
        /// A thread was started from this message; the thread has the message's ID.
        const HAS_THREAD = 1 << 5;
        /// Only the user who triggered the interaction can see the message.
        const EPHEMERAL = 1 << 6;
        /// The message is a deferred interaction response: the app is "thinking".
        const LOADING = 1 << 7;
        /// Some mentioned roles could not be mentioned, so their members were not added to the
        /// thread.
        const FAILED_TO_MENTION_SOME_ROLES_IN_THREAD = 1 << 8;
        /// The client warns before opening links in this message.
        ///
        /// **Undocumented:** known from discord-api-types, not in the official docs; may
        /// change without notice.
        const SHOULD_SHOW_LINK_NOT_DISCORD_WARNING = 1 << 10;
        /// The message does not trigger push or desktop notifications.
        const SUPPRESS_NOTIFICATIONS = 1 << 12;
        /// The message is a voice message.
        const IS_VOICE_MESSAGE = 1 << 13;
        /// The message contains a snapshot of a forwarded message.
        const HAS_SNAPSHOT = 1 << 14;
        /// The message is laid out entirely with components (Components V2) instead of
        /// `content` and embeds. Once a message has been sent with this flag, the flag cannot be
        /// removed.
        const IS_COMPONENTS_V2 = 1 << 15;
    }
}

int_flags! {
    /// [Flags of an attachment](https://docs.discord.com/developers/resources/message#attachment-object-attachment-flags).
    ///
    /// discord.js counterpart: `AttachmentFlags` / `AttachmentFlagsBitField`.
    pub struct AttachmentFlags: u64 {
        /// The attachment is a clip recorded from a stream.
        const IS_CLIP = 1 << 0;
        /// The attachment is the thumbnail of a media-channel thread: shown in the channel's
        /// grid, not on the message.
        const IS_THUMBNAIL = 1 << 1;
        /// The attachment was edited with the mobile remix feature. **Deprecated** by Discord.
        const IS_REMIX = 1 << 2;
        /// The attachment is marked as a spoiler and blurred until clicked.
        const IS_SPOILER = 1 << 3;
        /// Discord's content scanning flagged the attachment as explicit.
        const CONTAINS_EXPLICIT_CONTENT = 1 << 4;
        /// The attachment is an animated image.
        const IS_ANIMATED = 1 << 5;
        /// Discord's content scanning flagged the attachment as gore.
        const CONTAINS_GORE_CONTENT = 1 << 6;
        /// Discord's content scanning flagged the attachment as self-harm.
        const CONTAINS_SELF_HARM_CONTENT = 1 << 7;
    }
}

int_flags! {
    /// [Flags of an embed](https://docs.discord.com/developers/resources/message#embed-object-embed-flags).
    ///
    /// Set by Discord on received embeds.
    ///
    /// discord.js counterpart: `EmbedFlags` (discord-api-types).
    pub struct EmbedFlags: u64 {
        /// Discord's content scanning flagged the embed's media as explicit.
        const CONTAINS_EXPLICIT_CONTENT = 1 << 4;
        /// The embed is the fallback shown for a reply to an activity card.
        const IS_CONTENT_INVENTORY_ENTRY = 1 << 5;
        /// Discord's content scanning flagged the embed's media as gore.
        const CONTAINS_GORE_CONTENT = 1 << 6;
        /// Discord's content scanning flagged the embed's media as self-harm.
        const CONTAINS_SELF_HARM_CONTENT = 1 << 7;
    }
}

int_flags! {
    /// [Flags of an embed's image, thumbnail or video](https://docs.discord.com/developers/resources/message#embed-object-embed-media-flags).
    ///
    /// discord.js counterpart: `EmbedMediaFlags` (discord-api-types).
    pub struct EmbedMediaFlags: u64 {
        /// The media is an animated image.
        const IS_ANIMATED = 1 << 5;
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn sizes() {
        // Guards against accidental growth of the hottest gateway type (D-054). A typical
        // message is decoded into one allocation of this size (plus its strings and vectors).
        assert!(size_of::<Message>() <= 656, "{}", size_of::<Message>());
        assert!(size_of::<Mention>() <= 152, "{}", size_of::<Mention>());
        assert!(
            size_of::<Attachment>() <= 312,
            "{}",
            size_of::<Attachment>()
        );
        assert!(size_of::<Embed>() <= 232, "{}", size_of::<Embed>());
        assert_eq!(size_of::<ReferencedMessage>(), 16);
    }

    #[test]
    fn message_type_forward_compatible() {
        assert_eq!(MessageType::from(19), MessageType::Reply);
        assert_eq!(MessageType::from(250), MessageType::Unknown(250));
        assert!(MessageType::from(250).is_unknown());
        assert!(!MessageType::Reply.is_unknown());
        // `Unknown` holding a known value is equal to the named variant.
        assert_eq!(MessageType::Unknown(0), MessageType::Default);
        assert!(!MessageType::Unknown(0).is_unknown());
        assert_eq!(serde_json::to_string(&MessageType::Reply).unwrap(), "19");
    }
}