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