Skip to main content

djs_model/rest/
message.rs

1//! Bodies, query parameters and responses of the
2//! [message endpoints](https://docs.discord.com/developers/resources/message#get-channel-messages).
3
4use compact_str::CompactString;
5use serde::{Deserialize, Serialize, Serializer};
6
7use super::{Attachments, FileUpload, setters};
8use crate::{
9    channel::{Channel, ThreadMember},
10    component::Component,
11    id::{ChannelId, MessageId, RoleId, StickerId, UserId},
12    macros::str_enum,
13    message::{
14        AllowedMentions, AttachmentRequest, Embed, Message, MessageFlags, MessagePin,
15        MessageReference, Nonce, ReactionType, SharedClientTheme,
16    },
17    poll::CreatePoll,
18    util::{Patch, Timestamp},
19};
20
21/// The body of [Create Message](https://docs.discord.com/developers/resources/message#create-message)
22/// (`POST /channels/{channel.id}/messages`).
23///
24/// At least one of `content`, `embeds`, `sticker_ids`, `components`, `files`, `poll` or
25/// `shared_client_theme` must be set; a forward needs only `message_reference`. With
26/// [`MessageFlags::IS_COMPONENTS_V2`], only `components` (and files) may be set.
27///
28/// Every file in [`files`](Self::files) gets its `attachments` entry automatically (D-094),
29/// and the request is then sent as `multipart/form-data`.
30///
31/// discord.js counterpart: `MessageCreateOptions` / `RESTPostAPIChannelMessageJSONBody`.
32///
33/// # Examples
34///
35/// ```
36/// use djs_model::rest::{CreateMessage, FileUpload};
37///
38/// let body = CreateMessage::from("Pong!");
39/// assert_eq!(serde_json::to_string(&body).unwrap(), r#"{"content":"Pong!"}"#);
40///
41/// let body = CreateMessage::from("A log").file(FileUpload::new("log.txt", "line 1\nline 2\n"));
42/// assert_eq!(
43///     serde_json::to_string(&body).unwrap(),
44///     r#"{"content":"A log","attachments":[{"id":0,"filename":"log.txt"}]}"#
45/// );
46/// ```
47#[derive(Clone, Debug, Default, PartialEq)]
48#[non_exhaustive]
49pub struct CreateMessage {
50    /// The text (up to 2000 characters).
51    pub content: Option<CompactString>,
52    /// A value to recognize the message in its `MESSAGE_CREATE` event (up to 25 characters).
53    pub nonce: Option<Nonce>,
54    /// Whether the message is read aloud (needs `SEND_TTS_MESSAGES`).
55    pub tts: bool,
56    /// Up to 10 rich embeds (up to 6000 characters in total).
57    pub embeds: Vec<Embed>,
58    /// Which mentions in the content notify.
59    pub allowed_mentions: Option<AllowedMentions>,
60    /// The message to reply to or forward.
61    pub message_reference: Option<MessageReference>,
62    /// The components.
63    pub components: Vec<Component>,
64    /// Up to 3 stickers of the guild to send.
65    pub sticker_ids: Vec<StickerId>,
66    /// Explicit attachment entries. Usually left out: every file gets one automatically,
67    /// unless an entry with its `files[n]` index is listed here.
68    pub attachments: Option<Vec<AttachmentRequest>>,
69    /// Only [`SUPPRESS_EMBEDS`](MessageFlags::SUPPRESS_EMBEDS),
70    /// [`SUPPRESS_NOTIFICATIONS`](MessageFlags::SUPPRESS_NOTIFICATIONS),
71    /// [`IS_VOICE_MESSAGE`](MessageFlags::IS_VOICE_MESSAGE) and
72    /// [`IS_COMPONENTS_V2`](MessageFlags::IS_COMPONENTS_V2) can be set.
73    pub flags: Option<MessageFlags>,
74    /// With a [`nonce`](Self::nonce): if the same author sent a message with the same nonce in
75    /// the last few minutes, that message is returned instead of creating a new one.
76    pub enforce_nonce: bool,
77    /// A poll to create with the message.
78    pub poll: Option<CreatePoll>,
79    /// A client theme to share through the message.
80    pub shared_client_theme: Option<SharedClientTheme>,
81    /// Files to upload with the message (D-087).
82    pub files: Vec<FileUpload>,
83}
84
85impl Serialize for CreateMessage {
86    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
87        #[derive(Serialize)]
88        struct Wire<'a> {
89            #[serde(skip_serializing_if = "Option::is_none")]
90            content: Option<&'a CompactString>,
91            #[serde(skip_serializing_if = "Option::is_none")]
92            nonce: Option<&'a Nonce>,
93            #[serde(skip_serializing_if = "core::ops::Not::not")]
94            tts: bool,
95            #[serde(skip_serializing_if = "<[_]>::is_empty")]
96            embeds: &'a [Embed],
97            #[serde(skip_serializing_if = "Option::is_none")]
98            allowed_mentions: Option<&'a AllowedMentions>,
99            #[serde(skip_serializing_if = "Option::is_none")]
100            message_reference: Option<&'a MessageReference>,
101            #[serde(skip_serializing_if = "<[_]>::is_empty")]
102            components: &'a [Component],
103            #[serde(skip_serializing_if = "<[_]>::is_empty")]
104            sticker_ids: &'a [StickerId],
105            #[serde(skip_serializing_if = "Attachments::is_absent")]
106            attachments: Attachments<'a>,
107            #[serde(skip_serializing_if = "Option::is_none")]
108            flags: Option<MessageFlags>,
109            #[serde(skip_serializing_if = "core::ops::Not::not")]
110            enforce_nonce: bool,
111            #[serde(skip_serializing_if = "Option::is_none")]
112            poll: Option<&'a CreatePoll>,
113            #[serde(skip_serializing_if = "Option::is_none")]
114            shared_client_theme: Option<&'a SharedClientTheme>,
115        }
116
117        // Destructured without `..`, so a new field cannot be forgotten here.
118        let Self {
119            content,
120            nonce,
121            tts,
122            embeds,
123            allowed_mentions,
124            message_reference,
125            components,
126            sticker_ids,
127            attachments,
128            flags,
129            enforce_nonce,
130            poll,
131            shared_client_theme,
132            files,
133        } = self;
134        Wire {
135            content: content.as_ref(),
136            nonce: nonce.as_ref(),
137            tts: *tts,
138            embeds,
139            allowed_mentions: allowed_mentions.as_ref(),
140            message_reference: message_reference.as_ref(),
141            components,
142            sticker_ids,
143            attachments: Attachments::new(attachments.as_deref(), files),
144            flags: *flags,
145            enforce_nonce: *enforce_nonce,
146            poll: poll.as_ref(),
147            shared_client_theme: shared_client_theme.as_ref(),
148        }
149        .serialize(serializer)
150    }
151}
152
153setters::message_body!(CreateMessage {
154    content,
155    embeds,
156    components,
157    allowed_mentions,
158    flags,
159    suppress_notifications,
160    files,
161    attachments,
162    poll,
163    tts,
164});
165
166/// The setters of the fields only [`CreateMessage`] has (D-290).
167impl CreateMessage {
168    /// Makes the message a reply to `message_id`, in the same channel.
169    ///
170    /// discord.js counterpart: `reply: { messageReference }`.
171    #[must_use]
172    pub const fn reply_to(mut self, message_id: MessageId) -> Self {
173        self.message_reference = Some(MessageReference::reply(message_id));
174        self
175    }
176
177    /// Sets the message this one replies to or forwards.
178    ///
179    /// discord.js counterpart: the `reply` and `forward` options.
180    #[must_use]
181    pub fn message_reference(mut self, reference: MessageReference) -> Self {
182        self.message_reference = Some(reference);
183        self
184    }
185
186    /// Adds a sticker of the guild, after the ones set before (up to 3).
187    ///
188    /// discord.js counterpart: an item of the `stickers` option.
189    #[must_use]
190    pub fn sticker(mut self, sticker_id: StickerId) -> Self {
191        self.sticker_ids.push(sticker_id);
192        self
193    }
194
195    /// Replaces the stickers (up to 3 of the guild's).
196    ///
197    /// discord.js counterpart: the `stickers` option.
198    #[must_use]
199    pub fn stickers(mut self, sticker_ids: impl IntoIterator<Item = StickerId>) -> Self {
200        self.sticker_ids = sticker_ids.into_iter().collect();
201        self
202    }
203
204    /// Sets a value to recognize the message in its `MESSAGE_CREATE` event; with
205    /// `enforce`, a message with the same nonce sent by the same author in the last few
206    /// minutes is returned instead of creating a new one.
207    ///
208    /// discord.js counterpart: the `nonce` and `enforceNonce` options.
209    #[must_use]
210    pub fn nonce(mut self, nonce: Nonce, enforce: bool) -> Self {
211        self.nonce = Some(nonce);
212        self.enforce_nonce = enforce;
213        self
214    }
215
216    /// Shares a client theme through the message.
217    ///
218    /// discord.js counterpart: none (not in discord.js v14).
219    #[must_use]
220    pub fn shared_client_theme(mut self, theme: SharedClientTheme) -> Self {
221        self.shared_client_theme = Some(theme);
222        self
223    }
224}
225
226/// The body of [Edit Message](https://docs.discord.com/developers/resources/message#edit-message)
227/// (`PATCH /channels/{channel.id}/messages/{message.id}`).
228///
229/// Every field is a [`Patch`]: fields left at [`Patch::Keep`] are not changed. The author can
230/// edit everything; other users with `MANAGE_MESSAGES` only the flags.
231///
232/// **Attachments:** new [`files`](Self::files) are added to the attachments listed in
233/// [`attachments`](Self::attachments), and every attachment that is in neither is removed
234/// (API v10). To keep the existing ones, list them with [`AttachmentRequest::existing`];
235/// [`Patch::Clear`] removes all of them (sent as an empty list).
236///
237/// discord.js counterpart: `MessageEditOptions` / `RESTPatchAPIChannelMessageJSONBody`.
238///
239/// # Examples
240///
241/// ```
242/// use djs_model::{rest::EditMessage, util::Patch};
243///
244/// // Setters for the usual fields (D-290); `Patch::Clear` by hand to remove a field.
245/// let mut body = EditMessage::from("Edited");
246/// body.embeds = Patch::Clear;
247/// assert_eq!(
248///     serde_json::to_string(&body).unwrap(),
249///     r#"{"content":"Edited","embeds":null}"#
250/// );
251/// ```
252#[derive(Clone, Debug, Default, PartialEq)]
253#[non_exhaustive]
254pub struct EditMessage {
255    /// The text (up to 2000 characters).
256    pub content: Patch<CompactString>,
257    /// Up to 10 rich embeds.
258    pub embeds: Patch<Vec<Embed>>,
259    /// Only [`SUPPRESS_EMBEDS`](MessageFlags::SUPPRESS_EMBEDS) can be set and unset;
260    /// [`IS_COMPONENTS_V2`](MessageFlags::IS_COMPONENTS_V2) can only be set.
261    pub flags: Patch<MessageFlags>,
262    /// Which mentions in the content notify.
263    pub allowed_mentions: Patch<AllowedMentions>,
264    /// The components.
265    pub components: Patch<Vec<Component>>,
266    /// The attachments to keep (and the metadata of new files, which is otherwise generated).
267    pub attachments: Patch<Vec<AttachmentRequest>>,
268    /// Files to add (D-087).
269    pub files: Vec<FileUpload>,
270}
271
272impl Serialize for EditMessage {
273    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
274        #[derive(Serialize)]
275        struct Wire<'a> {
276            #[serde(skip_serializing_if = "Patch::is_keep")]
277            content: Patch<&'a CompactString>,
278            #[serde(skip_serializing_if = "Patch::is_keep")]
279            embeds: Patch<&'a Vec<Embed>>,
280            #[serde(skip_serializing_if = "Patch::is_keep")]
281            flags: Patch<MessageFlags>,
282            #[serde(skip_serializing_if = "Patch::is_keep")]
283            allowed_mentions: Patch<&'a AllowedMentions>,
284            #[serde(skip_serializing_if = "Patch::is_keep")]
285            components: Patch<&'a Vec<Component>>,
286            #[serde(skip_serializing_if = "Attachments::is_absent")]
287            attachments: Attachments<'a>,
288        }
289
290        // Destructured without `..`, so a new field cannot be forgotten here.
291        let Self {
292            content,
293            embeds,
294            flags,
295            allowed_mentions,
296            components,
297            attachments,
298            files,
299        } = self;
300        Wire {
301            content: content.as_ref(),
302            embeds: embeds.as_ref(),
303            flags: *flags,
304            allowed_mentions: allowed_mentions.as_ref(),
305            components: components.as_ref(),
306            attachments: Attachments::from_patch(attachments, files),
307        }
308        .serialize(serializer)
309    }
310}
311
312setters::message_body!(EditMessage {
313    content,
314    embeds,
315    components,
316    allowed_mentions,
317    flags,
318    files,
319    attachments,
320});
321
322/// The query of [Get Channel Messages](https://docs.discord.com/developers/resources/message#get-channel-messages)
323/// (`GET /channels/{channel.id}/messages`). Messages are returned newest first.
324///
325/// `around`, `before` and `after` are mutually exclusive: set at most one.
326///
327/// discord.js counterpart: `FetchMessagesOptions`.
328#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
329#[non_exhaustive]
330pub struct GetChannelMessages {
331    /// Messages around this message.
332    pub around: Option<MessageId>,
333    /// Messages before this message.
334    pub before: Option<MessageId>,
335    /// Messages after this message.
336    pub after: Option<MessageId>,
337    /// How many messages (1-100; Discord's default is 50).
338    pub limit: Option<u8>,
339}
340
341/// The query of [Get Reactions](https://docs.discord.com/developers/resources/message#get-reactions)
342/// (`GET /channels/{channel.id}/messages/{message.id}/reactions/{emoji}`).
343///
344/// discord.js counterpart: `ReactionManager#fetch` options.
345#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
346#[non_exhaustive]
347pub struct GetReactions {
348    /// Normal or super reactions (Discord's default: normal).
349    pub kind: Option<ReactionType>,
350    /// Users after this user.
351    pub after: Option<UserId>,
352    /// How many users (1-100; Discord's default is 25).
353    pub limit: Option<u8>,
354}
355
356/// The body of [Bulk Delete Messages](https://docs.discord.com/developers/resources/message#bulk-delete-messages)
357/// (`POST /channels/{channel.id}/messages/bulk-delete`).
358///
359/// discord.js counterpart: `TextChannel#bulkDelete`.
360#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize)]
361#[non_exhaustive]
362pub struct BulkDeleteMessages {
363    /// The messages to delete: 2 to 100, none older than two weeks and no duplicates.
364    pub messages: Vec<MessageId>,
365}
366
367impl BulkDeleteMessages {
368    /// Deletes `messages`.
369    ///
370    /// discord.js counterpart: `TextChannel#bulkDelete`.
371    #[must_use]
372    pub const fn new(messages: Vec<MessageId>) -> Self {
373        Self { messages }
374    }
375}
376
377/// The query of [Get Channel Pins](https://docs.discord.com/developers/resources/message#get-channel-pins)
378/// (`GET /channels/{channel.id}/messages/pins`). Pins are returned newest first; to get the
379/// next page, pass the `pinned_at` of the last pin as `before`.
380///
381/// discord.js counterpart: `MessageManager#fetchPins` options.
382#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
383#[non_exhaustive]
384pub struct GetChannelPins {
385    /// Pins made before this time.
386    pub before: Option<Timestamp>,
387    /// How many pins (1-50; Discord's default is 50).
388    pub limit: Option<u8>,
389}
390
391/// The response of [Get Channel Pins](https://docs.discord.com/developers/resources/message#get-channel-pins).
392///
393/// discord.js counterpart: `RESTGetAPIChannelMessagesPinsResult` (discord-api-types).
394#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
395#[non_exhaustive]
396pub struct ChannelPins {
397    /// The pins, newest first.
398    pub items: Vec<MessagePin>,
399    /// Whether there are older pins.
400    pub has_more: bool,
401}
402
403/// The query of [Search Guild Messages](https://docs.discord.com/developers/resources/message#search-guild-messages)
404/// (`GET /guilds/{guild.id}/messages/search`). Every filter is optional; list filters match
405/// any of their values.
406///
407/// The endpoint needs `READ_MESSAGE_HISTORY` and depends on the `MESSAGE_CONTENT` privileged
408/// intent. While the guild is not indexed yet, the request fails with
409/// `ErrorKind::NotYetIndexed` of `djs-rest` (D-104).
410///
411/// discord.js counterpart: `RESTGetAPIGuildMessagesSearchQuery` (discord-api-types).
412///
413/// # Examples
414///
415/// ```
416/// use djs_model::rest::{SearchFilter, SearchGuildMessages, SearchHasType};
417///
418/// let mut query = SearchGuildMessages::default();
419/// query.content = Some("release".into());
420/// query.has = vec![SearchFilter::Include(SearchHasType::Link)];
421/// query.author_type = vec![SearchFilter::Exclude(djs_model::rest::SearchAuthorType::Bot)];
422/// ```
423#[derive(Clone, Debug, Default, PartialEq, Eq)]
424#[non_exhaustive]
425pub struct SearchGuildMessages {
426    /// How many messages (1-25; Discord's default is 25).
427    pub limit: Option<u8>,
428    /// How many results to skip (max 9975).
429    pub offset: Option<u16>,
430    /// Messages before this message.
431    pub max_id: Option<MessageId>,
432    /// Messages after this message.
433    pub min_id: Option<MessageId>,
434    /// How many words may lie between the matching words of `content` (max 100; default 2).
435    pub slop: Option<u8>,
436    /// Text the messages contain (max 1024 characters).
437    pub content: Option<CompactString>,
438    /// Messages in these channels (max 500).
439    pub channel_id: Vec<ChannelId>,
440    /// Messages by these kinds of authors (or not, with [`SearchFilter::Exclude`]).
441    pub author_type: Vec<SearchFilter<SearchAuthorType>>,
442    /// Messages by these users (max 100).
443    pub author_id: Vec<UserId>,
444    /// Messages mentioning these users (max 100).
445    pub mentions: Vec<UserId>,
446    /// Messages mentioning these roles (max 100).
447    pub mentions_role_id: Vec<RoleId>,
448    /// Messages that do (or do not) mention `@everyone`.
449    pub mention_everyone: Option<bool>,
450    /// Messages replying to these users (max 100).
451    pub replied_to_user_id: Vec<UserId>,
452    /// Messages replying to these messages (max 100).
453    pub replied_to_message_id: Vec<MessageId>,
454    /// Messages that are (or are not) pinned.
455    pub pinned: Option<bool>,
456    /// Messages that have (or do not have) these things.
457    pub has: Vec<SearchFilter<SearchHasType>>,
458    /// Messages with these kinds of embeds.
459    pub embed_type: Vec<SearchEmbedType>,
460    /// Messages with embeds from these providers, case-sensitive (e.g. `Tenor`; max 100).
461    pub embed_provider: Vec<CompactString>,
462    /// Messages with links to these host names (e.g. `discordapp.com`; max 100).
463    pub link_hostname: Vec<CompactString>,
464    /// Messages with attachments of these file names (max 100).
465    pub attachment_filename: Vec<CompactString>,
466    /// Messages with attachments of these extensions (e.g. `txt`; max 100).
467    pub attachment_extension: Vec<CompactString>,
468    /// How to sort (Discord's default: by time).
469    pub sort_by: Option<SearchSortMode>,
470    /// The direction (Discord's default: descending); ignored when sorting by relevance.
471    pub sort_order: Option<SearchSortOrder>,
472    /// Whether to include age-restricted channels (Discord's default: no).
473    pub include_nsfw: Option<bool>,
474}
475
476/// A search filter value that includes or excludes matching messages (Discord writes an
477/// exclusion with a leading `-`).
478///
479/// discord.js counterpart: none (a value of `RESTGetAPIGuildMessagesSearchQuery` that may be negated).
480#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
481pub enum SearchFilter<T> {
482    /// Only messages that match.
483    Include(T),
484    /// Only messages that do not match.
485    Exclude(T),
486}
487
488impl<T> From<T> for SearchFilter<T> {
489    /// Includes the value.
490    fn from(value: T) -> Self {
491        Self::Include(value)
492    }
493}
494
495str_enum! {
496    /// An [author type](https://docs.discord.com/developers/resources/message#search-guild-messages-author-types)
497    /// of a message search.
498    ///
499    /// discord.js counterpart: `MessageSearchAuthorType` (discord-api-types).
500    pub enum SearchAuthorType {
501        /// Messages of user accounts.
502        User = "user",
503        /// Messages of bot accounts.
504        Bot = "bot",
505        /// Messages of webhooks.
506        Webhook = "webhook",
507    }
508}
509
510str_enum! {
511    /// Something a message [has](https://docs.discord.com/developers/resources/message#search-guild-messages-search-has-types),
512    /// for a message search.
513    ///
514    /// discord.js counterpart: `MessageSearchHasType` (discord-api-types).
515    pub enum SearchHasType {
516        /// An image.
517        Image = "image",
518        /// A sound attachment.
519        Sound = "sound",
520        /// A video.
521        Video = "video",
522        /// An attachment.
523        File = "file",
524        /// A sticker.
525        Sticker = "sticker",
526        /// An embed.
527        Embed = "embed",
528        /// A link.
529        Link = "link",
530        /// A poll.
531        Poll = "poll",
532        /// A forwarded message.
533        Snapshot = "snapshot",
534    }
535}
536
537str_enum! {
538    /// An [embed type](https://docs.discord.com/developers/resources/message#search-guild-messages-search-embed-types)
539    /// of a message search (broader than the embed types of messages).
540    ///
541    /// discord.js counterpart: `MessageSearchEmbedType` (discord-api-types).
542    pub enum SearchEmbedType {
543        /// Image embeds.
544        Image = "image",
545        /// Video embeds.
546        Video = "video",
547        /// GIF (`gifv`) embeds.
548        Gif = "gif",
549        /// Sound embeds.
550        Sound = "sound",
551        /// Article embeds.
552        Article = "article",
553    }
554}
555
556str_enum! {
557    /// A [sort mode](https://docs.discord.com/developers/resources/message#search-guild-messages-search-sort-modes)
558    /// of a message search.
559    ///
560    /// discord.js counterpart: `MessageSearchSortMode` (discord-api-types).
561    pub enum SearchSortMode {
562        /// By creation time (the default).
563        Timestamp = "timestamp",
564        /// By relevance to the search.
565        Relevance = "relevance",
566    }
567}
568
569str_enum! {
570    /// The direction of a message search's sorting.
571    ///
572    /// discord.js counterpart: the `sort_order` of `RESTGetAPIGuildMessagesSearchQuery` (discord-api-types).
573    pub enum SearchSortOrder {
574        /// Oldest first.
575        Ascending = "asc",
576        /// Newest first (the default).
577        Descending = "desc",
578    }
579}
580
581/// The response of [Search Guild Messages](https://docs.discord.com/developers/resources/message#search-guild-messages-response-body).
582///
583/// Messages come without their `reactions`. Do not paginate by the number of messages
584/// returned: the search may return fewer than the limit.
585///
586/// discord.js counterpart: `APIMessageSearchResult` (discord-api-types).
587#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
588#[non_exhaustive]
589pub struct MessageSearchResults {
590    /// Whether the guild is going through a deep historical indexing.
591    pub doing_deep_historical_index: bool,
592    /// How many documents the current indexing has processed, if one is running.
593    #[serde(default, skip_serializing_if = "Option::is_none")]
594    pub documents_indexed: Option<u64>,
595    /// How many messages match in total (may be inexact while messages are being created
596    /// or deleted).
597    pub total_results: u64,
598    /// The matching messages; each inner list holds one message (Discord used to add
599    /// surrounding messages for context).
600    pub messages: Vec<Vec<Message>>,
601    /// The threads the messages are in.
602    #[serde(default, skip_serializing_if = "Vec::is_empty")]
603    pub threads: Vec<Channel>,
604    /// The current user's thread member for each returned thread it has joined.
605    #[serde(default, skip_serializing_if = "Vec::is_empty")]
606    pub members: Vec<ThreadMember>,
607}
608
609#[cfg(test)]
610mod tests {
611    use super::*;
612    use crate::{id::AttachmentId, message::Embed};
613
614    fn json<T: Serialize>(body: &T) -> String {
615        serde_json::to_string(body).unwrap()
616    }
617
618    #[test]
619    fn create_message_fields() {
620        let mut body = CreateMessage::from("Hello, World!");
621        body.nonce = Some(Nonce::String("n-1".into()));
622        body.enforce_nonce = true;
623        body.tts = true;
624        body.embeds.push(Embed {
625            title: Some("Hello, Embed!".into()),
626            ..Embed::default()
627        });
628        body.sticker_ids
629            .push(StickerId::new(1_300_000_000_000_000_000));
630        body.flags = Some(MessageFlags::SUPPRESS_NOTIFICATIONS);
631        assert_eq!(
632            json(&body),
633            concat!(
634                r#"{"content":"Hello, World!","nonce":"n-1","tts":true,"#,
635                r#""embeds":[{"title":"Hello, Embed!"}],"sticker_ids":["1300000000000000000"],"#,
636                r#""flags":4096,"enforce_nonce":true}"#
637            )
638        );
639        assert_eq!(json(&CreateMessage::default()), "{}");
640    }
641
642    #[test]
643    fn edit_message_patches() {
644        assert_eq!(json(&EditMessage::default()), "{}");
645
646        let body = EditMessage {
647            flags: Patch::Set(MessageFlags::SUPPRESS_EMBEDS),
648            components: Patch::Clear,
649            allowed_mentions: Patch::Clear,
650            ..EditMessage::default()
651        };
652        assert_eq!(
653            json(&body),
654            r#"{"flags":4,"allowed_mentions":null,"components":null}"#
655        );
656
657        // New files are added to the kept attachments.
658        let mut body = EditMessage {
659            attachments: Patch::Set(vec![AttachmentRequest::existing(AttachmentId::new(
660                1_300_000_000_000_000_001,
661            ))]),
662            files: vec![FileUpload::new("new.png", &b"png"[..])],
663            ..EditMessage::default()
664        };
665        assert_eq!(
666            json(&body),
667            r#"{"attachments":[{"id":"1300000000000000001"},{"id":0,"filename":"new.png"}]}"#
668        );
669
670        // Clearing removes every attachment: an empty list, or only the new files.
671        body.attachments = Patch::Clear;
672        assert_eq!(
673            json(&body),
674            r#"{"attachments":[{"id":0,"filename":"new.png"}]}"#
675        );
676        body.files.clear();
677        assert_eq!(json(&body), r#"{"attachments":[]}"#);
678    }
679
680    #[test]
681    fn bulk_delete_and_pins() {
682        let body = BulkDeleteMessages::new(vec![MessageId::new(1), MessageId::new(2)]);
683        assert_eq!(json(&body), r#"{"messages":["1","2"]}"#);
684
685        let pins: ChannelPins = serde_json::from_str(r#"{"items":[],"has_more":false}"#).unwrap();
686        assert!(pins.items.is_empty() && !pins.has_more);
687    }
688}