Skip to main content

zaun_community_protocol/command/object/interaction/
body.rs

1//! The message body of bot replies, follow-ups and edits, and message flags (§8.14).
2
3use serde::{Deserialize, Serialize};
4
5use crate::command::object::{
6    Component, Embed, Mentions, check_embeds, check_message_components, check_pictures,
7    component_attachments,
8};
9use crate::command::{BodyError, check};
10use crate::ids::AttachmentId;
11use crate::limits::{ATTACHMENTS_PER_MESSAGE, MESSAGE_CONTENT};
12
13/// Message flags (u32, Discord's values).
14pub mod flags {
15    /// Embeds are not shown.
16    pub const SUPPRESS_EMBEDS: u32 = 4;
17    /// Only the invoker sees it; never stored (§8.14).
18    pub const EPHEMERAL: u32 = 64;
19    /// A deferred reply still loading; set only by the host.
20    pub const LOADING: u32 = 128;
21    /// Mentions do not notify.
22    pub const SUPPRESS_NOTIFICATIONS: u32 = 4_096;
23    /// The message is laid out by components only.
24    pub const IS_COMPONENTS_V2: u32 = 32_768;
25    /// What a sender may set.
26    pub const SETTABLE: u32 =
27        SUPPRESS_EMBEDS | EPHEMERAL | SUPPRESS_NOTIFICATIONS | IS_COMPONENTS_V2;
28}
29
30/// Content, embeds, components, attachments, mentions and flags of a bot's message.
31#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
32pub struct MessageBody {
33    /// ≤ 4 000 scalars.
34    #[serde(default, skip_serializing_if = "Option::is_none")]
35    pub content: Option<String>,
36    /// ≤ 10 embeds.
37    #[serde(default, skip_serializing_if = "Option::is_none")]
38    pub embeds: Option<Vec<Embed>>,
39    /// Components (§8.14).
40    #[serde(default, skip_serializing_if = "Option::is_none")]
41    pub components: Option<Vec<Component>>,
42    /// Attachments the bot uploaded to the channel, not yet on a message.
43    #[serde(default, skip_serializing_if = "Vec::is_empty")]
44    pub attachments: Vec<AttachmentId>,
45    /// Who to notify.
46    #[serde(default, skip_serializing_if = "Option::is_none")]
47    pub mentions: Option<Mentions>,
48    /// [`flags`] bits.
49    #[serde(default, skip_serializing_if = "Option::is_none")]
50    pub flags: Option<u32>,
51}
52
53impl MessageBody {
54    /// The flags, 0 when absent.
55    #[must_use]
56    pub fn flag_bits(&self) -> u32 {
57        self.flags.unwrap_or(0)
58    }
59
60    /// Whether `EPHEMERAL` is set.
61    #[must_use]
62    pub fn is_ephemeral(&self) -> bool {
63        self.flag_bits() & flags::EPHEMERAL != 0
64    }
65
66    /// State-free rules. `whole`: a new message (needs something to show), not an edit.
67    ///
68    /// # Errors
69    /// The first violated rule.
70    pub fn check(&self, whole: bool) -> Result<(), BodyError> {
71        let bits = self.flag_bits();
72        if bits & !flags::SETTABLE != 0 {
73            return Err(BodyError::bad("flags", "sets a flag a sender cannot set"));
74        }
75        // An edit without flags keeps the stored ones, which only the host knows: it re-checks
76        // the components against them, so here V2 kinds pass.
77        let v2 = bits & flags::IS_COMPONENTS_V2 != 0 || (!whole && self.flags.is_none());
78        let content = self.content.as_deref().unwrap_or_default();
79        let embeds = self.embeds.as_deref().unwrap_or_default();
80        let components = self.components.as_deref().unwrap_or_default();
81        if bits & flags::IS_COMPONENTS_V2 != 0 && (!content.is_empty() || !embeds.is_empty()) {
82            return Err(BodyError::bad(
83                "content",
84                "a components V2 message has no content or embeds",
85            ));
86        }
87        let shows = !content.is_empty()
88            || !embeds.is_empty()
89            || !components.is_empty()
90            || !self.attachments.is_empty();
91        if whole && !shows {
92            return Err(BodyError::bad("content", "the message shows nothing"));
93        }
94        check::text("content", content, (0, MESSAGE_CONTENT.1))?;
95        if let Some(m) = &self.mentions {
96            m.check()?;
97        }
98        check::count(
99            "attachments",
100            self.attachments.len(),
101            ATTACHMENTS_PER_MESSAGE,
102        )?;
103        check::unique("attachments", &self.attachments)?;
104        check_embeds(embeds, None)?;
105        check_message_components(components, v2)?;
106        if whole {
107            check_pictures(embeds, &self.attachments)?;
108            for (field, id) in component_attachments(components) {
109                if !self.attachments.contains(&id) {
110                    return Err(BodyError::bad(
111                        field,
112                        "is not one of the message's attachments",
113                    ));
114                }
115            }
116        }
117        Ok(())
118    }
119}