twilight_http/request/channel/thread/create_forum_thread/
message.rs

1use super::{CreateForumThread, ForumThread};
2use crate::{
3    request::{attachment::PartialAttachment, Nullable, TryIntoRequest},
4    response::{Response, ResponseFuture},
5    Error,
6};
7use serde::Serialize;
8use std::{future::IntoFuture, mem};
9use twilight_model::{
10    channel::message::{AllowedMentions, Component, Embed, MessageFlags},
11    http::attachment::Attachment,
12    id::{marker::StickerMarker, Id},
13};
14use twilight_validate::message::{
15    attachment_filename as validate_attachment_filename, components as validate_components,
16    content as validate_content, embeds as validate_embeds, sticker_ids as validate_sticker_ids,
17    MessageValidationError,
18};
19
20/// Contents of the first message in the new forum thread.
21#[derive(Serialize)]
22pub(super) struct CreateForumThreadMessageFields<'a> {
23    #[serde(skip_serializing_if = "Option::is_none")]
24    pub(super) allowed_mentions: Option<Nullable<&'a AllowedMentions>>,
25    #[serde(skip_serializing_if = "Option::is_none")]
26    pub(super) attachments: Option<Vec<PartialAttachment<'a>>>,
27    #[serde(skip_serializing_if = "Option::is_none")]
28    pub(super) components: Option<&'a [Component]>,
29    #[serde(skip_serializing_if = "Option::is_none")]
30    pub(super) content: Option<&'a str>,
31    #[serde(skip_serializing_if = "Option::is_none")]
32    pub(super) embeds: Option<&'a [Embed]>,
33    #[serde(skip_serializing_if = "Option::is_none")]
34    pub(super) flags: Option<MessageFlags>,
35    #[serde(skip_serializing_if = "Option::is_none")]
36    pub(super) payload_json: Option<&'a [u8]>,
37    #[serde(skip_serializing_if = "Option::is_none")]
38    pub(super) sticker_ids: Option<&'a [Id<StickerMarker>]>,
39}
40
41#[must_use = "requests must be configured and executed"]
42pub struct CreateForumThreadMessage<'a>(Result<CreateForumThread<'a>, MessageValidationError>);
43
44impl<'a> CreateForumThreadMessage<'a> {
45    pub(super) const fn new(inner: CreateForumThread<'a>) -> Self {
46        Self(Ok(inner))
47    }
48
49    /// Specify the [`AllowedMentions`] for the message.
50    ///
51    /// Unless otherwise called, the request will use the client's default
52    /// allowed mentions. Set to `None` to ignore this default.
53    pub fn allowed_mentions(mut self, allowed_mentions: Option<&'a AllowedMentions>) -> Self {
54        if let Ok(inner) = self.0.as_mut() {
55            inner.fields.message.allowed_mentions = Some(Nullable(allowed_mentions));
56        }
57
58        self
59    }
60
61    /// Attach multiple files to the message.
62    ///
63    /// Calling this method will clear any previous calls.
64    ///
65    /// # Errors
66    ///
67    /// Returns an error of type [`AttachmentFilename`] if any filename is
68    /// invalid.
69    ///
70    /// [`AttachmentFilename`]: twilight_validate::message::MessageValidationErrorType::AttachmentFilename
71    pub fn attachments(mut self, attachments: &'a [Attachment]) -> Self {
72        if self.0.is_ok() {
73            let validation = attachments
74                .iter()
75                .try_for_each(|attachment| validate_attachment_filename(&attachment.filename));
76
77            if let Err(source) = validation {
78                self.0 = Err(source);
79            } else if let Ok(inner) = self.0.as_mut() {
80                let mut manager = mem::take(&mut inner.attachment_manager);
81                manager = manager.set_files(attachments.iter().collect());
82
83                inner.attachment_manager = manager;
84            }
85        }
86
87        self
88    }
89
90    /// Set the message's list of [`Component`]s.
91    ///
92    /// Calling this method will clear previous calls.
93    ///
94    /// Requires a webhook owned by the application.
95    ///
96    /// # Errors
97    ///
98    /// Refer to the errors section of
99    /// [`twilight_validate::component::component`] for a list of errors that
100    /// may be returned as a result of validating each provided component.
101    pub fn components(mut self, components: &'a [Component]) -> Self {
102        self.0 = self.0.and_then(|mut inner| {
103            validate_components(components)?;
104            inner.fields.message.components = Some(components);
105
106            Ok(inner)
107        });
108
109        self
110    }
111
112    /// Set the message's content.
113    ///
114    /// The maximum length is 2000 UTF-16 characters.
115    ///
116    /// # Errors
117    ///
118    /// Returns an error of type [`ContentInvalid`] if the content length is too
119    /// long.
120    ///
121    /// [`ContentInvalid`]: twilight_validate::message::MessageValidationErrorType::ContentInvalid
122    pub fn content(mut self, content: &'a str) -> Self {
123        self.0 = self.0.and_then(|mut inner| {
124            validate_content(content)?;
125            inner.fields.message.content = Some(content);
126
127            Ok(inner)
128        });
129
130        self
131    }
132
133    /// Set the message's list of embeds.
134    ///
135    /// Calling this method will clear previous calls.
136    ///
137    /// The amount of embeds must not exceed [`EMBED_COUNT_LIMIT`]. The total
138    /// character length of each embed must not exceed [`EMBED_TOTAL_LENGTH`]
139    /// characters. Additionally, the internal fields also have character
140    /// limits. Refer to [Discord Docs/Embed Limits] for more information.
141    ///
142    /// # Errors
143    ///
144    /// Returns an error of type [`TooManyEmbeds`] if there are too many embeds.
145    ///
146    /// Otherwise, refer to the errors section of
147    /// [`twilight_validate::embed::embed`] for a list of errors that may occur.
148    ///
149    /// [Discord Docs/Embed Limits]: https://discord.com/developers/docs/resources/channel#embed-limits
150    /// [`EMBED_COUNT_LIMIT`]: twilight_validate::message::EMBED_COUNT_LIMIT
151    /// [`EMBED_TOTAL_LENGTH`]: twilight_validate::embed::EMBED_TOTAL_LENGTH
152    /// [`TooManyEmbeds`]: twilight_validate::message::MessageValidationErrorType::TooManyEmbeds
153    pub fn embeds(mut self, embeds: &'a [Embed]) -> Self {
154        self.0 = self.0.and_then(|mut inner| {
155            validate_embeds(embeds)?;
156            inner.fields.message.embeds = Some(embeds);
157
158            Ok(inner)
159        });
160
161        self
162    }
163
164    /// Set the message's flags.
165    ///
166    /// The only supported flags are [`SUPPRESS_EMBEDS`] and
167    /// [`SUPPRESS_NOTIFICATIONS`].
168    ///
169    /// [`SUPPRESS_EMBEDS`]: MessageFlags::SUPPRESS_EMBEDS
170    /// [`SUPPRESS_NOTIFICATIONS`]: MessageFlags::SUPPRESS_NOTIFICATIONS
171    pub fn flags(mut self, flags: MessageFlags) -> Self {
172        if let Ok(inner) = self.0.as_mut() {
173            inner.fields.message.flags = Some(flags);
174        }
175
176        self
177    }
178
179    /// JSON encoded body of any additional request fields.
180    ///
181    /// If this method is called, all other fields are ignored, except for
182    /// [`attachments`]. See [Discord Docs/Uploading Files].
183    ///
184    /// # Examples
185    ///
186    /// See [`ExecuteWebhook::payload_json`] for examples.
187    ///
188    /// [Discord Docs/Uploading Files]: https://discord.com/developers/docs/reference#uploading-files
189    /// [`ExecuteWebhook::payload_json`]: crate::request::channel::webhook::ExecuteWebhook::payload_json
190    /// [`attachments`]: Self::attachments
191    pub fn payload_json(mut self, payload_json: &'a [u8]) -> Self {
192        if let Ok(inner) = self.0.as_mut() {
193            inner.fields.message.payload_json = Some(payload_json);
194        }
195
196        self
197    }
198
199    /// Set the IDs of up to 3 guild stickers.
200    ///
201    /// # Errors
202    ///
203    /// Returns an error of type [`StickersInvalid`] if the length is invalid.
204    ///
205    /// [`StickersInvalid`]: twilight_validate::message::MessageValidationErrorType::StickersInvalid
206    pub fn sticker_ids(mut self, sticker_ids: &'a [Id<StickerMarker>]) -> Self {
207        self.0 = self.0.and_then(|mut inner| {
208            validate_sticker_ids(sticker_ids)?;
209            inner.fields.message.sticker_ids = Some(sticker_ids);
210
211            Ok(inner)
212        });
213
214        self
215    }
216}
217
218impl IntoFuture for CreateForumThreadMessage<'_> {
219    type Output = Result<Response<ForumThread>, Error>;
220
221    type IntoFuture = ResponseFuture<ForumThread>;
222
223    fn into_future(self) -> Self::IntoFuture {
224        match self.0 {
225            Ok(inner) => inner.exec(),
226            Err(source) => ResponseFuture::error(Error::validation(source)),
227        }
228    }
229}
230
231impl TryIntoRequest for CreateForumThreadMessage<'_> {
232    fn try_into_request(self) -> Result<crate::request::Request, Error> {
233        self.0
234            .map_err(Error::validation)
235            .and_then(CreateForumThread::try_into_request)
236    }
237}