djs_model/rest/webhook.rs
1//! Bodies of the [webhook endpoints](https://docs.discord.com/developers/resources/webhook).
2//!
3//! Execute Slack-Compatible and GitHub-Compatible Webhook are not modelled (D-120).
4
5use compact_str::CompactString;
6use serde::{Serialize, Serializer};
7
8use super::{Attachments, FileUpload, setters};
9use crate::{
10 component::Component,
11 id::{ChannelId, TagId},
12 message::{AllowedMentions, AttachmentRequest, Embed, MessageFlags},
13 poll::CreatePoll,
14 util::{ImageData, Patch},
15};
16
17/// The body of [Create Webhook](https://docs.discord.com/developers/resources/webhook#create-webhook).
18///
19/// The name (1-80 characters) cannot contain `clyde` or `discord`.
20///
21/// discord.js counterpart: `ChannelWebhookCreateOptions`.
22#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize)]
23#[non_exhaustive]
24pub struct CreateWebhook {
25 /// The default name of the webhook's messages.
26 pub name: CompactString,
27 /// The default avatar of the webhook's messages.
28 #[serde(skip_serializing_if = "Option::is_none")]
29 pub avatar: Option<ImageData>,
30}
31
32impl CreateWebhook {
33 /// A webhook named `name`, with the default avatar.
34 ///
35 /// discord.js counterpart: `ChannelWebhookCreateOptions`.
36 #[must_use]
37 pub fn new(name: impl Into<CompactString>) -> Self {
38 Self {
39 name: name.into(),
40 avatar: None,
41 }
42 }
43}
44
45/// The body of [Modify Webhook](https://docs.discord.com/developers/resources/webhook#modify-webhook)
46/// and Modify Webhook with Token (which does not accept [`channel_id`](Self::channel_id)).
47///
48/// discord.js counterpart: `WebhookEditOptions`.
49#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize)]
50#[non_exhaustive]
51pub struct ModifyWebhook {
52 /// The default name.
53 #[serde(skip_serializing_if = "Option::is_none")]
54 pub name: Option<CompactString>,
55 /// The default avatar.
56 #[serde(skip_serializing_if = "Patch::is_keep")]
57 pub avatar: Patch<ImageData>,
58 /// The channel to move the webhook to (not with a token).
59 #[serde(skip_serializing_if = "Option::is_none")]
60 pub channel_id: Option<ChannelId>,
61}
62
63/// The body of [Execute Webhook](https://docs.discord.com/developers/resources/webhook#execute-webhook):
64/// a message sent through a webhook.
65///
66/// At least one of `content`, `embeds`, `components`, `files` or `poll` is required. In a
67/// forum or media channel, set [`thread_id`](Self::thread_id) or
68/// [`thread_name`](Self::thread_name). Files get their `attachments` entries automatically
69/// (D-094); [`thread_id`](Self::thread_id) and [`with_components`](Self::with_components)
70/// are sent in the query string (D-119).
71///
72/// discord.js counterpart: `WebhookMessageCreateOptions`.
73///
74/// # Examples
75///
76/// ```
77/// use djs_model::rest::ExecuteWebhook;
78///
79/// let body = ExecuteWebhook::from("Build #42 passed").username("CI");
80/// assert_eq!(
81/// serde_json::to_string(&body).unwrap(),
82/// r#"{"content":"Build #42 passed","username":"CI"}"#
83/// );
84/// ```
85#[derive(Clone, Debug, Default, PartialEq)]
86#[non_exhaustive]
87pub struct ExecuteWebhook {
88 /// The text (up to 2000 characters).
89 pub content: Option<CompactString>,
90 /// Overrides the webhook's name for this message.
91 pub username: Option<CompactString>,
92 /// Overrides the webhook's avatar for this message (an image URL).
93 pub avatar_url: Option<CompactString>,
94 /// Whether the message is read aloud.
95 pub tts: bool,
96 /// Up to 10 rich embeds.
97 pub embeds: Vec<Embed>,
98 /// Which mentions in the content notify.
99 pub allowed_mentions: Option<AllowedMentions>,
100 /// The components; webhooks not owned by an application need
101 /// [`with_components`](Self::with_components) and can only send non-interactive ones.
102 pub components: Vec<Component>,
103 /// Explicit attachment entries; files get theirs automatically (D-094).
104 pub attachments: Option<Vec<AttachmentRequest>>,
105 /// Only [`SUPPRESS_EMBEDS`](MessageFlags::SUPPRESS_EMBEDS),
106 /// [`SUPPRESS_NOTIFICATIONS`](MessageFlags::SUPPRESS_NOTIFICATIONS) and
107 /// [`IS_COMPONENTS_V2`](MessageFlags::IS_COMPONENTS_V2) can be set.
108 pub flags: Option<MessageFlags>,
109 /// In a forum or media channel: creates a post with this name.
110 pub thread_name: Option<CompactString>,
111 /// The tags of the post created with [`thread_name`](Self::thread_name).
112 pub applied_tags: Vec<TagId>,
113 /// A poll to create with the message.
114 pub poll: Option<CreatePoll>,
115 /// Files to upload with the message (D-087).
116 pub files: Vec<FileUpload>,
117 /// Sends the message in this thread of the webhook's channel (unarchiving it); sent in
118 /// the query string.
119 pub thread_id: Option<ChannelId>,
120 /// Whether Discord uses [`components`](Self::components) (Discord's default: only for
121 /// application-owned webhooks); sent in the query string.
122 pub with_components: Option<bool>,
123}
124
125impl Serialize for ExecuteWebhook {
126 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
127 #[derive(Serialize)]
128 struct Wire<'a> {
129 #[serde(skip_serializing_if = "Option::is_none")]
130 content: Option<&'a CompactString>,
131 #[serde(skip_serializing_if = "Option::is_none")]
132 username: Option<&'a CompactString>,
133 #[serde(skip_serializing_if = "Option::is_none")]
134 avatar_url: Option<&'a CompactString>,
135 #[serde(skip_serializing_if = "core::ops::Not::not")]
136 tts: bool,
137 #[serde(skip_serializing_if = "<[_]>::is_empty")]
138 embeds: &'a [Embed],
139 #[serde(skip_serializing_if = "Option::is_none")]
140 allowed_mentions: Option<&'a AllowedMentions>,
141 #[serde(skip_serializing_if = "<[_]>::is_empty")]
142 components: &'a [Component],
143 #[serde(skip_serializing_if = "Attachments::is_absent")]
144 attachments: Attachments<'a>,
145 #[serde(skip_serializing_if = "Option::is_none")]
146 flags: Option<MessageFlags>,
147 #[serde(skip_serializing_if = "Option::is_none")]
148 thread_name: Option<&'a CompactString>,
149 #[serde(skip_serializing_if = "<[_]>::is_empty")]
150 applied_tags: &'a [TagId],
151 #[serde(skip_serializing_if = "Option::is_none")]
152 poll: Option<&'a CreatePoll>,
153 }
154
155 // Destructured without `..`, so a new field cannot be forgotten here. The query
156 // fields are written by the REST client.
157 let Self {
158 content,
159 username,
160 avatar_url,
161 tts,
162 embeds,
163 allowed_mentions,
164 components,
165 attachments,
166 flags,
167 thread_name,
168 applied_tags,
169 poll,
170 files,
171 thread_id: _,
172 with_components: _,
173 } = self;
174 Wire {
175 content: content.as_ref(),
176 username: username.as_ref(),
177 avatar_url: avatar_url.as_ref(),
178 tts: *tts,
179 embeds,
180 allowed_mentions: allowed_mentions.as_ref(),
181 components,
182 attachments: Attachments::new(attachments.as_deref(), files),
183 flags: *flags,
184 thread_name: thread_name.as_ref(),
185 applied_tags,
186 poll: poll.as_ref(),
187 }
188 .serialize(serializer)
189 }
190}
191
192setters::message_body!(ExecuteWebhook {
193 content,
194 embeds,
195 components,
196 allowed_mentions,
197 flags,
198 suppress_notifications,
199 files,
200 attachments,
201 poll,
202 tts,
203});
204
205/// The setters of the fields only [`ExecuteWebhook`] has (D-290).
206impl ExecuteWebhook {
207 /// Overrides the webhook's name for this message.
208 ///
209 /// discord.js counterpart: the `username` option.
210 #[must_use]
211 pub fn username(mut self, username: impl Into<CompactString>) -> Self {
212 self.username = Some(username.into());
213 self
214 }
215
216 /// Overrides the webhook's avatar for this message (an image URL).
217 ///
218 /// discord.js counterpart: the `avatarURL` option.
219 #[must_use]
220 pub fn avatar_url(mut self, url: impl Into<CompactString>) -> Self {
221 self.avatar_url = Some(url.into());
222 self
223 }
224
225 /// In a forum or media channel: creates a post with this name.
226 ///
227 /// discord.js counterpart: the `threadName` option.
228 #[must_use]
229 pub fn thread_name(mut self, name: impl Into<CompactString>) -> Self {
230 self.thread_name = Some(name.into());
231 self
232 }
233
234 /// Sets the tags of the post created with [`thread_name`](Self::thread_name).
235 ///
236 /// discord.js counterpart: the `appliedTags` option.
237 #[must_use]
238 pub fn applied_tags(mut self, tags: impl IntoIterator<Item = TagId>) -> Self {
239 self.applied_tags = tags.into_iter().collect();
240 self
241 }
242
243 /// Sends the message in this thread of the webhook's channel (unarchiving it).
244 ///
245 /// discord.js counterpart: the `threadId` option.
246 #[must_use]
247 pub const fn thread_id(mut self, thread_id: ChannelId) -> Self {
248 self.thread_id = Some(thread_id);
249 self
250 }
251
252 /// Sets whether Discord uses the [`components`](Self::components) (by default only for
253 /// application-owned webhooks; others can send only non-interactive components).
254 ///
255 /// discord.js counterpart: the `withComponents` option.
256 #[must_use]
257 pub const fn with_components(mut self, with_components: bool) -> Self {
258 self.with_components = Some(with_components);
259 self
260 }
261}
262
263/// The body of [Edit Webhook Message](https://docs.discord.com/developers/resources/webhook#edit-webhook-message),
264/// also used to edit the original response to an interaction and its follow-up messages.
265///
266/// Every field is a [`Patch`]: fields left at [`Patch::Keep`] are not changed. Attachments
267/// work like in [`EditMessage`](super::EditMessage): new [`files`](Self::files) are added to
268/// the attachments listed in [`attachments`](Self::attachments), every other attachment is
269/// removed, and [`Patch::Clear`] removes all of them.
270///
271/// discord.js counterpart: `WebhookMessageEditOptions` / `InteractionEditReplyOptions`.
272///
273/// # Examples
274///
275/// ```
276/// use djs_model::rest::EditWebhookMessage;
277///
278/// let body = EditWebhookMessage::from("Done!");
279/// assert_eq!(serde_json::to_string(&body).unwrap(), r#"{"content":"Done!"}"#);
280/// ```
281#[derive(Clone, Debug, Default, PartialEq)]
282#[non_exhaustive]
283pub struct EditWebhookMessage {
284 /// The text (up to 2000 characters).
285 pub content: Patch<CompactString>,
286 /// Up to 10 rich embeds.
287 pub embeds: Patch<Vec<Embed>>,
288 /// Only [`SUPPRESS_EMBEDS`](MessageFlags::SUPPRESS_EMBEDS) can be set and unset;
289 /// [`IS_COMPONENTS_V2`](MessageFlags::IS_COMPONENTS_V2) can only be set.
290 pub flags: Patch<MessageFlags>,
291 /// Which mentions in the content notify.
292 pub allowed_mentions: Patch<AllowedMentions>,
293 /// The components.
294 pub components: Patch<Vec<Component>>,
295 /// The attachments to keep (and the metadata of new files, which is otherwise generated).
296 pub attachments: Patch<Vec<AttachmentRequest>>,
297 /// A poll; it can only be added when editing a deferred interaction response.
298 pub poll: Patch<CreatePoll>,
299 /// Files to add (D-087).
300 pub files: Vec<FileUpload>,
301 /// The thread the message is in; sent in the query string (D-119).
302 pub thread_id: Option<ChannelId>,
303 /// Whether Discord uses [`components`](Self::components) (Discord's default: only for
304 /// application-owned webhooks); sent in the query string.
305 pub with_components: Option<bool>,
306}
307
308impl Serialize for EditWebhookMessage {
309 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
310 #[derive(Serialize)]
311 struct Wire<'a> {
312 #[serde(skip_serializing_if = "Patch::is_keep")]
313 content: Patch<&'a CompactString>,
314 #[serde(skip_serializing_if = "Patch::is_keep")]
315 embeds: Patch<&'a Vec<Embed>>,
316 #[serde(skip_serializing_if = "Patch::is_keep")]
317 flags: Patch<MessageFlags>,
318 #[serde(skip_serializing_if = "Patch::is_keep")]
319 allowed_mentions: Patch<&'a AllowedMentions>,
320 #[serde(skip_serializing_if = "Patch::is_keep")]
321 components: Patch<&'a Vec<Component>>,
322 #[serde(skip_serializing_if = "Attachments::is_absent")]
323 attachments: Attachments<'a>,
324 #[serde(skip_serializing_if = "Patch::is_keep")]
325 poll: Patch<&'a CreatePoll>,
326 }
327
328 // Destructured without `..`, so a new field cannot be forgotten here. The query
329 // fields are written by the REST client.
330 let Self {
331 content,
332 embeds,
333 flags,
334 allowed_mentions,
335 components,
336 attachments,
337 poll,
338 files,
339 thread_id: _,
340 with_components: _,
341 } = self;
342 Wire {
343 content: content.as_ref(),
344 embeds: embeds.as_ref(),
345 flags: *flags,
346 allowed_mentions: allowed_mentions.as_ref(),
347 components: components.as_ref(),
348 attachments: Attachments::from_patch(attachments, files),
349 poll: poll.as_ref(),
350 }
351 .serialize(serializer)
352 }
353}
354
355setters::message_body!(EditWebhookMessage {
356 content,
357 embeds,
358 components,
359 allowed_mentions,
360 flags,
361 files,
362 attachments,
363 poll,
364});
365
366/// The setters of the fields only [`EditWebhookMessage`] has (D-290).
367impl EditWebhookMessage {
368 /// Edits a message in this thread of the webhook's channel.
369 ///
370 /// discord.js counterpart: the `threadId` option.
371 #[must_use]
372 pub const fn thread_id(mut self, thread_id: ChannelId) -> Self {
373 self.thread_id = Some(thread_id);
374 self
375 }
376
377 /// Sets whether Discord uses the [`components`](Self::components) (by default only for
378 /// application-owned webhooks).
379 ///
380 /// discord.js counterpart: the `withComponents` option.
381 #[must_use]
382 pub const fn with_components(mut self, with_components: bool) -> Self {
383 self.with_components = Some(with_components);
384 self
385 }
386}
387
388#[cfg(test)]
389mod tests {
390 use super::*;
391
392 #[test]
393 fn execute_webhook_keeps_query_fields_out_of_the_json() {
394 let mut body = ExecuteWebhook::from("hi");
395 body.thread_id = Some(ChannelId::new(5));
396 body.with_components = Some(true);
397 body.thread_name = Some("Release".into());
398 body.applied_tags.push(TagId::new(3));
399 body.files.push(FileUpload::new("notes.md", "# 1.0"));
400 assert_eq!(
401 serde_json::to_string(&body).unwrap(),
402 concat!(
403 r#"{"content":"hi","attachments":[{"id":0,"filename":"notes.md"}],"#,
404 r#""thread_name":"Release","applied_tags":["3"]}"#
405 )
406 );
407
408 let modify = ModifyWebhook {
409 avatar: Patch::Clear,
410 ..ModifyWebhook::default()
411 };
412 assert_eq!(
413 serde_json::to_string(&modify).unwrap(),
414 r#"{"avatar":null}"#
415 );
416 }
417
418 #[test]
419 fn edit_webhook_message() {
420 let body = EditWebhookMessage {
421 embeds: Patch::Clear,
422 poll: Patch::Clear,
423 files: vec![FileUpload::new("a.png", &b"a"[..])],
424 ..EditWebhookMessage::from("x")
425 };
426 assert_eq!(
427 serde_json::to_string(&body).unwrap(),
428 r#"{"content":"x","embeds":null,"attachments":[{"id":0,"filename":"a.png"}],"poll":null}"#
429 );
430 }
431}