djs-model 0.1.0-alpha.2

Discord API v10 types — users, guilds, channels, messages, interactions and gateway events.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
//! Bodies of the [webhook endpoints](https://docs.discord.com/developers/resources/webhook).
//!
//! Execute Slack-Compatible and GitHub-Compatible Webhook are not modelled (D-120).

use compact_str::CompactString;
use serde::{Serialize, Serializer};

use super::{Attachments, FileUpload, setters};
use crate::{
    component::Component,
    id::{ChannelId, TagId},
    message::{AllowedMentions, AttachmentRequest, Embed, MessageFlags},
    poll::CreatePoll,
    util::{ImageData, Patch},
};

/// The body of [Create Webhook](https://docs.discord.com/developers/resources/webhook#create-webhook).
///
/// The name (1-80 characters) cannot contain `clyde` or `discord`.
///
/// discord.js counterpart: `ChannelWebhookCreateOptions`.
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize)]
#[non_exhaustive]
pub struct CreateWebhook {
    /// The default name of the webhook's messages.
    pub name: CompactString,
    /// The default avatar of the webhook's messages.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub avatar: Option<ImageData>,
}

impl CreateWebhook {
    /// A webhook named `name`, with the default avatar.
    ///
    /// discord.js counterpart: `ChannelWebhookCreateOptions`.
    #[must_use]
    pub fn new(name: impl Into<CompactString>) -> Self {
        Self {
            name: name.into(),
            avatar: None,
        }
    }
}

/// The body of [Modify Webhook](https://docs.discord.com/developers/resources/webhook#modify-webhook)
/// and Modify Webhook with Token (which does not accept [`channel_id`](Self::channel_id)).
///
/// discord.js counterpart: `WebhookEditOptions`.
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize)]
#[non_exhaustive]
pub struct ModifyWebhook {
    /// The default name.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<CompactString>,
    /// The default avatar.
    #[serde(skip_serializing_if = "Patch::is_keep")]
    pub avatar: Patch<ImageData>,
    /// The channel to move the webhook to (not with a token).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub channel_id: Option<ChannelId>,
}

/// The body of [Execute Webhook](https://docs.discord.com/developers/resources/webhook#execute-webhook):
/// a message sent through a webhook.
///
/// At least one of `content`, `embeds`, `components`, `files` or `poll` is required. In a
/// forum or media channel, set [`thread_id`](Self::thread_id) or
/// [`thread_name`](Self::thread_name). Files get their `attachments` entries automatically
/// (D-094); [`thread_id`](Self::thread_id) and [`with_components`](Self::with_components)
/// are sent in the query string (D-119).
///
/// discord.js counterpart: `WebhookMessageCreateOptions`.
///
/// # Examples
///
/// ```
/// use djs_model::rest::ExecuteWebhook;
///
/// let body = ExecuteWebhook::from("Build #42 passed").username("CI");
/// assert_eq!(
///     serde_json::to_string(&body).unwrap(),
///     r#"{"content":"Build #42 passed","username":"CI"}"#
/// );
/// ```
#[derive(Clone, Debug, Default, PartialEq)]
#[non_exhaustive]
pub struct ExecuteWebhook {
    /// The text (up to 2000 characters).
    pub content: Option<CompactString>,
    /// Overrides the webhook's name for this message.
    pub username: Option<CompactString>,
    /// Overrides the webhook's avatar for this message (an image URL).
    pub avatar_url: Option<CompactString>,
    /// Whether the message is read aloud.
    pub tts: bool,
    /// Up to 10 rich embeds.
    pub embeds: Vec<Embed>,
    /// Which mentions in the content notify.
    pub allowed_mentions: Option<AllowedMentions>,
    /// The components; webhooks not owned by an application need
    /// [`with_components`](Self::with_components) and can only send non-interactive ones.
    pub components: Vec<Component>,
    /// Explicit attachment entries; files get theirs automatically (D-094).
    pub attachments: Option<Vec<AttachmentRequest>>,
    /// Only [`SUPPRESS_EMBEDS`](MessageFlags::SUPPRESS_EMBEDS),
    /// [`SUPPRESS_NOTIFICATIONS`](MessageFlags::SUPPRESS_NOTIFICATIONS) and
    /// [`IS_COMPONENTS_V2`](MessageFlags::IS_COMPONENTS_V2) can be set.
    pub flags: Option<MessageFlags>,
    /// In a forum or media channel: creates a post with this name.
    pub thread_name: Option<CompactString>,
    /// The tags of the post created with [`thread_name`](Self::thread_name).
    pub applied_tags: Vec<TagId>,
    /// A poll to create with the message.
    pub poll: Option<CreatePoll>,
    /// Files to upload with the message (D-087).
    pub files: Vec<FileUpload>,
    /// Sends the message in this thread of the webhook's channel (unarchiving it); sent in
    /// the query string.
    pub thread_id: Option<ChannelId>,
    /// Whether Discord uses [`components`](Self::components) (Discord's default: only for
    /// application-owned webhooks); sent in the query string.
    pub with_components: Option<bool>,
}

impl Serialize for ExecuteWebhook {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        #[derive(Serialize)]
        struct Wire<'a> {
            #[serde(skip_serializing_if = "Option::is_none")]
            content: Option<&'a CompactString>,
            #[serde(skip_serializing_if = "Option::is_none")]
            username: Option<&'a CompactString>,
            #[serde(skip_serializing_if = "Option::is_none")]
            avatar_url: Option<&'a CompactString>,
            #[serde(skip_serializing_if = "core::ops::Not::not")]
            tts: bool,
            #[serde(skip_serializing_if = "<[_]>::is_empty")]
            embeds: &'a [Embed],
            #[serde(skip_serializing_if = "Option::is_none")]
            allowed_mentions: Option<&'a AllowedMentions>,
            #[serde(skip_serializing_if = "<[_]>::is_empty")]
            components: &'a [Component],
            #[serde(skip_serializing_if = "Attachments::is_absent")]
            attachments: Attachments<'a>,
            #[serde(skip_serializing_if = "Option::is_none")]
            flags: Option<MessageFlags>,
            #[serde(skip_serializing_if = "Option::is_none")]
            thread_name: Option<&'a CompactString>,
            #[serde(skip_serializing_if = "<[_]>::is_empty")]
            applied_tags: &'a [TagId],
            #[serde(skip_serializing_if = "Option::is_none")]
            poll: Option<&'a CreatePoll>,
        }

        // Destructured without `..`, so a new field cannot be forgotten here. The query
        // fields are written by the REST client.
        let Self {
            content,
            username,
            avatar_url,
            tts,
            embeds,
            allowed_mentions,
            components,
            attachments,
            flags,
            thread_name,
            applied_tags,
            poll,
            files,
            thread_id: _,
            with_components: _,
        } = self;
        Wire {
            content: content.as_ref(),
            username: username.as_ref(),
            avatar_url: avatar_url.as_ref(),
            tts: *tts,
            embeds,
            allowed_mentions: allowed_mentions.as_ref(),
            components,
            attachments: Attachments::new(attachments.as_deref(), files),
            flags: *flags,
            thread_name: thread_name.as_ref(),
            applied_tags,
            poll: poll.as_ref(),
        }
        .serialize(serializer)
    }
}

setters::message_body!(ExecuteWebhook {
    content,
    embeds,
    components,
    allowed_mentions,
    flags,
    suppress_notifications,
    files,
    attachments,
    poll,
    tts,
});

/// The setters of the fields only [`ExecuteWebhook`] has (D-290).
impl ExecuteWebhook {
    /// Overrides the webhook's name for this message.
    ///
    /// discord.js counterpart: the `username` option.
    #[must_use]
    pub fn username(mut self, username: impl Into<CompactString>) -> Self {
        self.username = Some(username.into());
        self
    }

    /// Overrides the webhook's avatar for this message (an image URL).
    ///
    /// discord.js counterpart: the `avatarURL` option.
    #[must_use]
    pub fn avatar_url(mut self, url: impl Into<CompactString>) -> Self {
        self.avatar_url = Some(url.into());
        self
    }

    /// In a forum or media channel: creates a post with this name.
    ///
    /// discord.js counterpart: the `threadName` option.
    #[must_use]
    pub fn thread_name(mut self, name: impl Into<CompactString>) -> Self {
        self.thread_name = Some(name.into());
        self
    }

    /// Sets the tags of the post created with [`thread_name`](Self::thread_name).
    ///
    /// discord.js counterpart: the `appliedTags` option.
    #[must_use]
    pub fn applied_tags(mut self, tags: impl IntoIterator<Item = TagId>) -> Self {
        self.applied_tags = tags.into_iter().collect();
        self
    }

    /// Sends the message in this thread of the webhook's channel (unarchiving it).
    ///
    /// discord.js counterpart: the `threadId` option.
    #[must_use]
    pub const fn thread_id(mut self, thread_id: ChannelId) -> Self {
        self.thread_id = Some(thread_id);
        self
    }

    /// Sets whether Discord uses the [`components`](Self::components) (by default only for
    /// application-owned webhooks; others can send only non-interactive components).
    ///
    /// discord.js counterpart: the `withComponents` option.
    #[must_use]
    pub const fn with_components(mut self, with_components: bool) -> Self {
        self.with_components = Some(with_components);
        self
    }
}

/// The body of [Edit Webhook Message](https://docs.discord.com/developers/resources/webhook#edit-webhook-message),
/// also used to edit the original response to an interaction and its follow-up messages.
///
/// Every field is a [`Patch`]: fields left at [`Patch::Keep`] are not changed. Attachments
/// work like in [`EditMessage`](super::EditMessage): new [`files`](Self::files) are added to
/// the attachments listed in [`attachments`](Self::attachments), every other attachment is
/// removed, and [`Patch::Clear`] removes all of them.
///
/// discord.js counterpart: `WebhookMessageEditOptions` / `InteractionEditReplyOptions`.
///
/// # Examples
///
/// ```
/// use djs_model::rest::EditWebhookMessage;
///
/// let body = EditWebhookMessage::from("Done!");
/// assert_eq!(serde_json::to_string(&body).unwrap(), r#"{"content":"Done!"}"#);
/// ```
#[derive(Clone, Debug, Default, PartialEq)]
#[non_exhaustive]
pub struct EditWebhookMessage {
    /// The text (up to 2000 characters).
    pub content: Patch<CompactString>,
    /// Up to 10 rich embeds.
    pub embeds: Patch<Vec<Embed>>,
    /// Only [`SUPPRESS_EMBEDS`](MessageFlags::SUPPRESS_EMBEDS) can be set and unset;
    /// [`IS_COMPONENTS_V2`](MessageFlags::IS_COMPONENTS_V2) can only be set.
    pub flags: Patch<MessageFlags>,
    /// Which mentions in the content notify.
    pub allowed_mentions: Patch<AllowedMentions>,
    /// The components.
    pub components: Patch<Vec<Component>>,
    /// The attachments to keep (and the metadata of new files, which is otherwise generated).
    pub attachments: Patch<Vec<AttachmentRequest>>,
    /// A poll; it can only be added when editing a deferred interaction response.
    pub poll: Patch<CreatePoll>,
    /// Files to add (D-087).
    pub files: Vec<FileUpload>,
    /// The thread the message is in; sent in the query string (D-119).
    pub thread_id: Option<ChannelId>,
    /// Whether Discord uses [`components`](Self::components) (Discord's default: only for
    /// application-owned webhooks); sent in the query string.
    pub with_components: Option<bool>,
}

impl Serialize for EditWebhookMessage {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        #[derive(Serialize)]
        struct Wire<'a> {
            #[serde(skip_serializing_if = "Patch::is_keep")]
            content: Patch<&'a CompactString>,
            #[serde(skip_serializing_if = "Patch::is_keep")]
            embeds: Patch<&'a Vec<Embed>>,
            #[serde(skip_serializing_if = "Patch::is_keep")]
            flags: Patch<MessageFlags>,
            #[serde(skip_serializing_if = "Patch::is_keep")]
            allowed_mentions: Patch<&'a AllowedMentions>,
            #[serde(skip_serializing_if = "Patch::is_keep")]
            components: Patch<&'a Vec<Component>>,
            #[serde(skip_serializing_if = "Attachments::is_absent")]
            attachments: Attachments<'a>,
            #[serde(skip_serializing_if = "Patch::is_keep")]
            poll: Patch<&'a CreatePoll>,
        }

        // Destructured without `..`, so a new field cannot be forgotten here. The query
        // fields are written by the REST client.
        let Self {
            content,
            embeds,
            flags,
            allowed_mentions,
            components,
            attachments,
            poll,
            files,
            thread_id: _,
            with_components: _,
        } = self;
        Wire {
            content: content.as_ref(),
            embeds: embeds.as_ref(),
            flags: *flags,
            allowed_mentions: allowed_mentions.as_ref(),
            components: components.as_ref(),
            attachments: Attachments::from_patch(attachments, files),
            poll: poll.as_ref(),
        }
        .serialize(serializer)
    }
}

setters::message_body!(EditWebhookMessage {
    content,
    embeds,
    components,
    allowed_mentions,
    flags,
    files,
    attachments,
    poll,
});

/// The setters of the fields only [`EditWebhookMessage`] has (D-290).
impl EditWebhookMessage {
    /// Edits a message in this thread of the webhook's channel.
    ///
    /// discord.js counterpart: the `threadId` option.
    #[must_use]
    pub const fn thread_id(mut self, thread_id: ChannelId) -> Self {
        self.thread_id = Some(thread_id);
        self
    }

    /// Sets whether Discord uses the [`components`](Self::components) (by default only for
    /// application-owned webhooks).
    ///
    /// discord.js counterpart: the `withComponents` option.
    #[must_use]
    pub const fn with_components(mut self, with_components: bool) -> Self {
        self.with_components = Some(with_components);
        self
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn execute_webhook_keeps_query_fields_out_of_the_json() {
        let mut body = ExecuteWebhook::from("hi");
        body.thread_id = Some(ChannelId::new(5));
        body.with_components = Some(true);
        body.thread_name = Some("Release".into());
        body.applied_tags.push(TagId::new(3));
        body.files.push(FileUpload::new("notes.md", "# 1.0"));
        assert_eq!(
            serde_json::to_string(&body).unwrap(),
            concat!(
                r#"{"content":"hi","attachments":[{"id":0,"filename":"notes.md"}],"#,
                r#""thread_name":"Release","applied_tags":["3"]}"#
            )
        );

        let modify = ModifyWebhook {
            avatar: Patch::Clear,
            ..ModifyWebhook::default()
        };
        assert_eq!(
            serde_json::to_string(&modify).unwrap(),
            r#"{"avatar":null}"#
        );
    }

    #[test]
    fn edit_webhook_message() {
        let body = EditWebhookMessage {
            embeds: Patch::Clear,
            poll: Patch::Clear,
            files: vec![FileUpload::new("a.png", &b"a"[..])],
            ..EditWebhookMessage::from("x")
        };
        assert_eq!(
            serde_json::to_string(&body).unwrap(),
            r#"{"content":"x","embeds":null,"attachments":[{"id":0,"filename":"a.png"}],"poll":null}"#
        );
    }
}