twilight_http/request/application/interaction/update_followup.rs
1//! Update a followup message created from a interaction.
2
3use crate::{
4 client::Client,
5 error::Error,
6 request::{
7 attachment::{AttachmentManager, PartialAttachment},
8 Nullable, Request, TryIntoRequest,
9 },
10 response::{Response, ResponseFuture},
11 routing::Route,
12};
13use serde::Serialize;
14use std::future::IntoFuture;
15use twilight_model::{
16 channel::message::{AllowedMentions, Component, Embed, Message},
17 http::attachment::Attachment,
18 id::{
19 marker::{ApplicationMarker, AttachmentMarker, MessageMarker},
20 Id,
21 },
22};
23use twilight_validate::message::{
24 attachment as validate_attachment, content as validate_content, embeds as validate_embeds,
25 MessageValidationError,
26};
27
28#[derive(Serialize)]
29struct UpdateFollowupFields<'a> {
30 #[serde(skip_serializing_if = "Option::is_none")]
31 allowed_mentions: Option<Nullable<&'a AllowedMentions>>,
32 /// List of attachments to keep, and new attachments to add.
33 #[serde(skip_serializing_if = "Option::is_none")]
34 attachments: Option<Nullable<Vec<PartialAttachment<'a>>>>,
35 #[serde(skip_serializing_if = "Option::is_none")]
36 components: Option<Nullable<&'a [Component]>>,
37 #[serde(skip_serializing_if = "Option::is_none")]
38 content: Option<Nullable<&'a str>>,
39 #[serde(skip_serializing_if = "Option::is_none")]
40 embeds: Option<Nullable<&'a [Embed]>>,
41 #[serde(skip_serializing_if = "Option::is_none")]
42 payload_json: Option<&'a [u8]>,
43}
44
45/// Edit a followup message of an interaction, by its token and the message ID.
46///
47/// You can pass [`None`] to any of the methods to remove the associated field.
48/// Pass [`None`] to [`content`] to remove the content. You must ensure that the
49/// message still contains at least one of [`attachments`], [`components`],
50/// [`content`], or [`embeds`].
51///
52/// This endpoint is not bound to the application's global rate limit.
53///
54/// # Examples
55///
56/// Update a followup message by setting the content to `test <@3>` -
57/// attempting to mention user ID 3 - while specifying that no entities can be
58/// mentioned.
59///
60/// ```no_run
61/// # #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> {
62/// use std::env;
63/// use twilight_http::Client;
64/// use twilight_model::{channel::message::AllowedMentions, id::Id};
65///
66/// let client = Client::new(env::var("DISCORD_TOKEN")?);
67/// let application_id = Id::new(1);
68///
69/// client
70/// .interaction(application_id)
71/// .update_followup("token here", Id::new(2))
72/// // By creating a default set of allowed mentions, no entity can be
73/// // mentioned.
74/// .allowed_mentions(Some(&AllowedMentions::default()))
75/// .content(Some("test <@3>"))
76/// .await?;
77/// # Ok(()) }
78/// ```
79///
80/// [`attachments`]: Self::attachments
81/// [`components`]: Self::components
82/// [`content`]: Self::content
83/// [`embeds`]: Self::embeds
84#[must_use = "requests must be configured and executed"]
85pub struct UpdateFollowup<'a> {
86 application_id: Id<ApplicationMarker>,
87 attachment_manager: AttachmentManager<'a>,
88 fields: Result<UpdateFollowupFields<'a>, MessageValidationError>,
89 http: &'a Client,
90 message_id: Id<MessageMarker>,
91 token: &'a str,
92}
93
94impl<'a> UpdateFollowup<'a> {
95 pub(crate) const fn new(
96 http: &'a Client,
97 application_id: Id<ApplicationMarker>,
98 token: &'a str,
99 message_id: Id<MessageMarker>,
100 ) -> Self {
101 Self {
102 application_id,
103 attachment_manager: AttachmentManager::new(),
104 fields: Ok(UpdateFollowupFields {
105 allowed_mentions: None,
106 attachments: None,
107 components: None,
108 content: None,
109 embeds: None,
110 payload_json: None,
111 }),
112 http,
113 message_id,
114 token,
115 }
116 }
117
118 /// Specify the [`AllowedMentions`] for the message.
119 ///
120 /// Unless otherwise called, the request will use the client's default
121 /// allowed mentions. Set to `None` to ignore this default.
122 pub fn allowed_mentions(mut self, allowed_mentions: Option<&'a AllowedMentions>) -> Self {
123 if let Ok(fields) = self.fields.as_mut() {
124 fields.allowed_mentions = Some(Nullable(allowed_mentions));
125 }
126
127 self
128 }
129
130 /// Attach multiple new files to the message.
131 ///
132 /// This method clears previous calls.
133 ///
134 /// # Errors
135 ///
136 /// Returns an error of type [`AttachmentDescriptionTooLarge`] if
137 /// the attachments' description is too large.
138 ///
139 /// Returns an error of type [`AttachmentFilename`] if any filename is
140 /// invalid.
141 ///
142 /// [`AttachmentDescriptionTooLarge`]: twilight_validate::message::MessageValidationErrorType::AttachmentDescriptionTooLarge
143 /// [`AttachmentFilename`]: twilight_validate::message::MessageValidationErrorType::AttachmentFilename
144 pub fn attachments(mut self, attachments: &'a [Attachment]) -> Self {
145 if self.fields.is_ok() {
146 if let Err(source) = attachments.iter().try_for_each(validate_attachment) {
147 self.fields = Err(source);
148 } else {
149 self.attachment_manager = self
150 .attachment_manager
151 .set_files(attachments.iter().collect());
152 }
153 }
154
155 self
156 }
157
158 /// Set the message's list of [`Component`]s.
159 ///
160 /// Calling this method will clear previous calls.
161 ///
162 /// # Editing
163 ///
164 /// Pass [`None`] to clear existing components.
165 ///
166 /// # Manual Validation
167 ///
168 /// Validation of components is not done automatically here, as we don't know which component
169 /// version is in use, you can validate them manually using the [`twilight_validate::component::component_v1`]
170 /// or [`twilight_validate::component::component_v2`] functions.
171 pub fn components(mut self, components: Option<&'a [Component]>) -> Self {
172 self.fields = self.fields.map(|mut fields| {
173 fields.components = Some(Nullable(components));
174 fields
175 });
176
177 self
178 }
179
180 /// Set the message's content.
181 ///
182 /// The maximum length is 2000 UTF-16 characters.
183 ///
184 /// # Editing
185 ///
186 /// Pass [`None`] to remove the message content. This is impossible if it
187 /// would leave the message empty of `attachments`, `content`, or `embeds`.
188 ///
189 /// # Errors
190 ///
191 /// Returns an error of type [`ContentInvalid`] if the content length is too
192 /// long.
193 ///
194 /// [`ContentInvalid`]: twilight_validate::message::MessageValidationErrorType::ContentInvalid
195 pub fn content(mut self, content: Option<&'a str>) -> Self {
196 self.fields = self.fields.and_then(|mut fields| {
197 if let Some(content_ref) = content.as_ref() {
198 validate_content(content_ref)?;
199 }
200
201 fields.content = Some(Nullable(content));
202
203 Ok(fields)
204 });
205
206 self
207 }
208
209 /// Set the message's list of embeds.
210 ///
211 /// Calling this method will clear previous calls.
212 ///
213 /// The amount of embeds must not exceed [`EMBED_COUNT_LIMIT`]. The total
214 /// character length of each embed must not exceed [`EMBED_TOTAL_LENGTH`]
215 /// characters. Additionally, the internal fields also have character
216 /// limits. See [Discord Docs/Embed Limits].
217 ///
218 /// # Editing
219 ///
220 /// To keep all embeds, do not call this method. To modify one or more
221 /// embeds in the message, acquire them from the previous message, mutate
222 /// them in place, then pass that list to this method. To remove all embeds,
223 /// pass [`None`]. This is impossible if it would leave the message empty of
224 /// `attachments`, `content`, or `embeds`.
225 ///
226 /// # Examples
227 ///
228 /// Create an embed and update the message with the new embed. The content
229 /// of the original message is unaffected and only the embed(s) are
230 /// modified.
231 ///
232 /// ```no_run
233 /// # #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> {
234 /// use twilight_http::Client;
235 /// use twilight_model::id::Id;
236 /// use twilight_util::builder::embed::EmbedBuilder;
237 ///
238 /// let client = Client::new("token".to_owned());
239 /// let application_id = Id::new(1);
240 /// let message_id = Id::new(2);
241 ///
242 /// let embed = EmbedBuilder::new()
243 /// .description(
244 /// "Powerful, flexible, and scalable ecosystem of Rust \
245 /// libraries for the Discord API.",
246 /// )
247 /// .title("Twilight")
248 /// .url("https://twilight.rs")
249 /// .validate()?
250 /// .build();
251 ///
252 /// client
253 /// .interaction(application_id)
254 /// .update_followup("token", message_id)
255 /// .embeds(Some(&[embed]))
256 /// .await?;
257 /// # Ok(()) }
258 /// ```
259 ///
260 /// # Errors
261 ///
262 /// Returns an error of type [`TooManyEmbeds`] if there are too many embeds.
263 ///
264 /// Otherwise, refer to the errors section of
265 /// [`twilight_validate::embed::embed`] for a list of errors that may occur.
266 ///
267 /// [`EMBED_COUNT_LIMIT`]: twilight_validate::message::EMBED_COUNT_LIMIT
268 /// [`EMBED_TOTAL_LENGTH`]: twilight_validate::embed::EMBED_TOTAL_LENGTH
269 /// [`TooManyEmbeds`]: twilight_validate::message::MessageValidationErrorType::TooManyEmbeds
270 /// [Discord Docs/Embed Limits]: https://discord.com/developers/docs/resources/channel#embed-limits
271 pub fn embeds(mut self, embeds: Option<&'a [Embed]>) -> Self {
272 self.fields = self.fields.and_then(|mut fields| {
273 if let Some(embeds) = embeds {
274 validate_embeds(embeds)?;
275 }
276
277 fields.embeds = Some(Nullable(embeds));
278
279 Ok(fields)
280 });
281
282 self
283 }
284
285 /// Specify multiple [`Id<AttachmentMarker>`]s already present in the target
286 /// message to keep.
287 ///
288 /// If called, all unspecified attachments (except ones added with
289 /// [`attachments`]) will be removed from the message. This is impossible if
290 /// it would leave the message empty of `attachments`, `content`, or
291 /// `embeds`. If not called, all attachments will be kept.
292 ///
293 /// [`attachments`]: Self::attachments
294 pub fn keep_attachment_ids(mut self, attachment_ids: &'a [Id<AttachmentMarker>]) -> Self {
295 if let Ok(fields) = self.fields.as_mut() {
296 self.attachment_manager = self.attachment_manager.set_ids(attachment_ids.to_vec());
297
298 // Set an empty list. This will be overwritten in `TryIntoRequest` if
299 // the actual list is not empty.
300 fields.attachments = Some(Nullable(Some(Vec::new())));
301 }
302
303 self
304 }
305
306 /// JSON encoded body of any additional request fields.
307 ///
308 /// If this method is called, all other fields are ignored, except for
309 /// [`attachments`]. See [Discord Docs/Uploading Files].
310 ///
311 /// # Examples
312 ///
313 /// See [`ExecuteWebhook::payload_json`] for examples.
314 ///
315 /// [`attachments`]: Self::attachments
316 /// [`ExecuteWebhook::payload_json`]: crate::request::channel::webhook::ExecuteWebhook::payload_json
317 /// [Discord Docs/Uploading Files]: https://discord.com/developers/docs/reference#uploading-files
318 pub fn payload_json(mut self, payload_json: &'a [u8]) -> Self {
319 if let Ok(fields) = self.fields.as_mut() {
320 fields.payload_json = Some(payload_json);
321 }
322
323 self
324 }
325}
326
327impl IntoFuture for UpdateFollowup<'_> {
328 type Output = Result<Response<Message>, Error>;
329
330 type IntoFuture = ResponseFuture<Message>;
331
332 fn into_future(self) -> Self::IntoFuture {
333 let http = self.http;
334
335 match self.try_into_request() {
336 Ok(request) => http.request(request),
337 Err(source) => ResponseFuture::error(source),
338 }
339 }
340}
341
342impl TryIntoRequest for UpdateFollowup<'_> {
343 fn try_into_request(self) -> Result<Request, Error> {
344 let mut fields = self.fields.map_err(Error::validation)?;
345 let mut request = Request::builder(&Route::UpdateWebhookMessage {
346 message_id: self.message_id.get(),
347 thread_id: None,
348 token: self.token,
349 webhook_id: self.application_id.get(),
350 });
351
352 // Interaction executions don't need the authorization token, only the
353 // interaction token.
354 request = request.use_authorization_token(false);
355
356 // Set the default allowed mentions if required.
357 if fields.allowed_mentions.is_none() {
358 if let Some(allowed_mentions) = self.http.default_allowed_mentions() {
359 fields.allowed_mentions = Some(Nullable(Some(allowed_mentions)));
360 }
361 }
362
363 // Determine whether we need to use a multipart/form-data body or a JSON
364 // body.
365 if !self.attachment_manager.is_empty() {
366 let form = if let Some(payload_json) = fields.payload_json {
367 self.attachment_manager.build_form(payload_json)
368 } else {
369 fields.attachments = Some(Nullable(Some(
370 self.attachment_manager.get_partial_attachments(),
371 )));
372
373 let fields = crate::json::to_vec(&fields).map_err(Error::json)?;
374
375 self.attachment_manager.build_form(fields.as_ref())
376 };
377
378 request = request.form(form);
379 } else if let Some(payload_json) = fields.payload_json {
380 request = request.body(payload_json.to_vec());
381 } else {
382 request = request.json(&fields);
383 }
384
385 request.build()
386 }
387}
388
389#[cfg(test)]
390mod tests {
391 use crate::{client::Client, request::TryIntoRequest};
392 use std::error::Error;
393 use twilight_http_ratelimiting::Path;
394 use twilight_model::id::Id;
395
396 #[test]
397 fn update_followup_message() -> Result<(), Box<dyn Error>> {
398 let application_id = Id::new(1);
399 let message_id = Id::new(2);
400 let token = "foo".to_owned();
401
402 let client = Client::new(String::new());
403 let req = client
404 .interaction(application_id)
405 .update_followup(&token, message_id)
406 .content(Some("test"))
407 .try_into_request()?;
408
409 assert!(!req.use_authorization_token());
410 assert_eq!(
411 &Path::WebhooksIdTokenMessagesId(application_id.get(), token),
412 req.ratelimit_path()
413 );
414
415 Ok(())
416 }
417}