Skip to main content

zaun_client/compose/
options.rs

1//! What a post or an edit says: discord.js's `MessageCreateOptions` and `MessageEditOptions`.
2
3use std::path::PathBuf;
4
5use zaun_community_protocol::ids::MessageId;
6
7use super::embed::{EmbedBuilder, Picture};
8
9/// A message to post: text, embeds, files and the message it answers. A plain `&str` is one
10/// with text only, so `channel.send("hi")` still reads as it did.
11///
12/// ```no_run
13/// # fn f(channel: &zaun_client::Channel) -> zaun_client::Result<()> {
14/// use zaun_client::{EmbedBuilder, MessageOptions, Picture};
15///
16/// channel.send(
17///     MessageOptions::new()
18///         .content("Today's weather")
19///         .embed(EmbedBuilder::new().title("Sunny").image(Picture::file("map.png")))
20///         .file("forecast.pdf"),
21/// )?;
22/// # Ok(())
23/// # }
24/// ```
25#[derive(Debug, Clone, Default, PartialEq, Eq)]
26pub struct MessageOptions {
27    pub(crate) content: String,
28    pub(crate) embeds: Vec<EmbedBuilder>,
29    pub(crate) files: Vec<Picture>,
30    pub(crate) reply_to: Option<MessageId>,
31    pub(crate) mentions: Option<zaun_community_protocol::command::object::Mentions>,
32}
33
34impl MessageOptions {
35    /// An empty message; it needs text, an embed or a file.
36    #[must_use]
37    pub fn new() -> Self {
38        Self::default()
39    }
40
41    /// The text (up to 4 000 characters; may be empty beside an embed or a file).
42    #[must_use]
43    pub fn content(mut self, content: impl Into<String>) -> Self {
44        self.content = content.into();
45        self
46    }
47
48    /// Adds an embed (up to 10). Its pictures are uploaded with the message's files.
49    #[must_use]
50    pub fn embed(mut self, embed: impl Into<EmbedBuilder>) -> Self {
51        self.embeds.push(embed.into());
52        self
53    }
54
55    /// Adds embeds.
56    #[must_use]
57    pub fn embeds(mut self, embeds: impl IntoIterator<Item = impl Into<EmbedBuilder>>) -> Self {
58        self.embeds.extend(embeds.into_iter().map(Into::into));
59        self
60    }
61
62    /// Attaches the file at `path` (with the embeds' pictures, up to 10 files in all). A file
63    /// that is also an embed's picture is uploaded once.
64    #[must_use]
65    pub fn file(mut self, path: impl Into<PathBuf>) -> Self {
66        self.files.push(Picture::File(path.into()));
67        self
68    }
69
70    /// Attaches `data` as a file named `name`.
71    #[must_use]
72    pub fn file_bytes(mut self, name: impl Into<String>, data: impl Into<Vec<u8>>) -> Self {
73        self.files.push(Picture::bytes(name, data));
74        self
75    }
76
77    /// Posts it as an answer to `message`.
78    #[must_use]
79    pub const fn reply_to(mut self, message: MessageId) -> Self {
80        self.reply_to = Some(message);
81        self
82    }
83}
84
85impl From<&str> for MessageOptions {
86    fn from(content: &str) -> Self {
87        Self::new().content(content)
88    }
89}
90
91impl From<&String> for MessageOptions {
92    fn from(content: &String) -> Self {
93        Self::new().content(content.as_str())
94    }
95}
96
97impl From<String> for MessageOptions {
98    fn from(content: String) -> Self {
99        Self::new().content(content)
100    }
101}
102
103impl From<EmbedBuilder> for MessageOptions {
104    fn from(embed: EmbedBuilder) -> Self {
105        Self::new().embed(embed)
106    }
107}
108
109/// An edit of one of this member's messages. A plain `&str` replaces the text and leaves the
110/// embeds and mentions as they are.
111///
112/// An edit uploads nothing: an embed's pictures must be attachments the message already has
113/// ([`Picture::Attachment`], or an [`Attachment`](crate::Attachment) of it).
114#[derive(Debug, Clone, Default, PartialEq, Eq)]
115pub struct EditMessage {
116    pub(crate) content: Option<String>,
117    pub(crate) embeds: Option<Vec<EmbedBuilder>>,
118    /// `None` leaves the message's mentions as they are; `Some` replaces them all.
119    pub(crate) mentions: Option<zaun_community_protocol::command::object::Mentions>,
120    /// Whether the text sent (new, or kept) adds the mentions it shows.
121    pub(crate) mentions_from_content: bool,
122}
123
124impl EditMessage {
125    /// An edit that changes nothing yet: the text stays (a [`Message`](crate::Message) knows
126    /// it; a [`PartialMessage`](crate::PartialMessage) needs [`content`](Self::content)), and
127    /// so do the embeds.
128    #[must_use]
129    pub fn new() -> Self {
130        Self::default()
131    }
132
133    /// The new text.
134    #[must_use]
135    pub fn content(mut self, content: impl Into<String>) -> Self {
136        self.content = Some(content.into());
137        self
138    }
139
140    /// Replaces the embeds with these, starting with this one.
141    #[must_use]
142    pub fn embed(mut self, embed: impl Into<EmbedBuilder>) -> Self {
143        self.embeds.get_or_insert_with(Vec::new).push(embed.into());
144        self
145    }
146
147    /// Replaces the embeds with `embeds` (none removes them all).
148    #[must_use]
149    pub fn embeds(mut self, embeds: impl IntoIterator<Item = impl Into<EmbedBuilder>>) -> Self {
150        self.embeds = Some(embeds.into_iter().map(Into::into).collect());
151        self
152    }
153
154    /// Removes every embed.
155    #[must_use]
156    pub fn clear_embeds(mut self) -> Self {
157        self.embeds = Some(Vec::new());
158        self
159    }
160}
161
162impl From<&str> for EditMessage {
163    fn from(content: &str) -> Self {
164        Self::new().content(content)
165    }
166}
167
168impl From<&String> for EditMessage {
169    fn from(content: &String) -> Self {
170        Self::new().content(content.as_str())
171    }
172}
173
174impl From<String> for EditMessage {
175    fn from(content: String) -> Self {
176        Self::new().content(content)
177    }
178}
179
180impl From<EmbedBuilder> for EditMessage {
181    fn from(embed: EmbedBuilder) -> Self {
182        Self::new().embed(embed)
183    }
184}
185
186#[cfg(test)]
187mod tests {
188    use super::*;
189
190    #[test]
191    fn text_alone_is_a_message() {
192        let o = MessageOptions::from("hi");
193        assert_eq!(o.content, "hi");
194        assert!(o.embeds.is_empty() && o.files.is_empty() && o.reply_to.is_none());
195        assert_eq!(MessageOptions::from(String::from("hi")), o);
196    }
197
198    #[test]
199    fn an_edit_of_the_text_alone_leaves_the_embeds_and_mentions() {
200        let e = EditMessage::from("new");
201        assert_eq!((e.content.as_deref(), e.embeds), (Some("new"), None));
202        let cleared = EditMessage::new().clear_embeds();
203        assert_eq!((cleared.content, cleared.embeds), (None, Some(Vec::new())));
204        let one = EditMessage::from(EmbedBuilder::new().title("t"));
205        assert_eq!(one.embeds.map(|e| e.len()), Some(1));
206        assert_eq!((e.mentions, e.mentions_from_content), (None, false));
207    }
208}