djs_model/rest/channel.rs
1//! Bodies, queries and responses of the [channel endpoints](https://docs.discord.com/developers/resources/channel):
2//! channels, permission overwrites, invites, group DMs and threads.
3
4use core::fmt;
5
6use compact_str::CompactString;
7use serde::{Deserialize, Deserializer, Serialize, Serializer};
8
9use super::{Attachments, FileUpload};
10use crate::{
11 channel::{
12 AutoArchiveDuration, Channel, ChannelFlags, ChannelType, DefaultReaction, ForumLayoutType,
13 ForumTag, Overwrite, OverwriteType, SortOrderType, ThreadMember, VideoQualityMode,
14 },
15 component::Component,
16 id::{ApplicationId, ChannelId, EmojiId, RoleId, StickerId, TagId, UserId},
17 invite::InviteTargetType,
18 message::{AllowedMentions, AttachmentRequest, Embed, Message, MessageFlags},
19 permissions::Permissions,
20 util::{ImageData, Patch, Timestamp},
21};
22
23/// The body of [Modify Channel](https://docs.discord.com/developers/resources/channel#modify-channel)
24/// for a guild channel (D-109).
25///
26/// Every field is optional; [`Patch`] fields can also be cleared. Which fields apply depends
27/// on the channel's type (e.g. `bitrate` only for voice and stage channels).
28///
29/// discord.js counterpart: `GuildChannelEditOptions`.
30///
31/// # Examples
32///
33/// ```
34/// use djs_model::{rest::ModifyGuildChannel, util::Patch};
35///
36/// let mut body = ModifyGuildChannel::default();
37/// body.name = Some("general".into());
38/// body.topic = Patch::Clear;
39/// assert_eq!(serde_json::to_string(&body).unwrap(), r#"{"name":"general","topic":null}"#);
40/// ```
41#[derive(Clone, Debug, Default, PartialEq, Serialize)]
42#[non_exhaustive]
43pub struct ModifyGuildChannel {
44 /// The name (1-100 characters).
45 #[serde(skip_serializing_if = "Option::is_none")]
46 pub name: Option<CompactString>,
47 /// The new type; only text ↔ announcement, in guilds with the `NEWS` feature.
48 #[serde(rename = "type", skip_serializing_if = "Option::is_none")]
49 pub kind: Option<ChannelType>,
50 /// The position in the channel list (channels with the same position are sorted by ID).
51 #[serde(skip_serializing_if = "Patch::is_keep")]
52 pub position: Patch<i32>,
53 /// The topic (0-1024 characters, 0-4096 for forum and media channels).
54 #[serde(skip_serializing_if = "Patch::is_keep")]
55 pub topic: Patch<CompactString>,
56 /// Whether the channel is age-restricted.
57 #[serde(skip_serializing_if = "Patch::is_keep")]
58 pub nsfw: Patch<bool>,
59 /// Slowmode: seconds a member must wait between messages (0-21600).
60 #[serde(skip_serializing_if = "Patch::is_keep")]
61 pub rate_limit_per_user: Patch<u16>,
62 /// The bitrate of a voice or stage channel, in bits per second (min 8000; the maximum
63 /// depends on the guild's boost level).
64 #[serde(skip_serializing_if = "Patch::is_keep")]
65 pub bitrate: Patch<u32>,
66 /// The user limit of a voice (max 99) or stage (max 10 000) channel; 0 is no limit.
67 #[serde(skip_serializing_if = "Patch::is_keep")]
68 pub user_limit: Patch<u32>,
69 /// The permission overwrites (all of them; needs `MANAGE_ROLES`).
70 #[serde(skip_serializing_if = "Patch::is_keep")]
71 pub permission_overwrites: Patch<Vec<Overwrite>>,
72 /// The parent category.
73 #[serde(skip_serializing_if = "Patch::is_keep")]
74 pub parent_id: Patch<ChannelId>,
75 /// The voice region ID; [`Patch::Clear`] selects it automatically.
76 #[serde(skip_serializing_if = "Patch::is_keep")]
77 pub rtc_region: Patch<CompactString>,
78 /// The camera video quality of a voice or stage channel.
79 #[serde(skip_serializing_if = "Patch::is_keep")]
80 pub video_quality_mode: Patch<VideoQualityMode>,
81 /// The archive duration that clients preselect for new threads.
82 #[serde(skip_serializing_if = "Patch::is_keep")]
83 pub default_auto_archive_duration: Patch<AutoArchiveDuration>,
84 /// The channel's flags.
85 #[serde(skip_serializing_if = "Option::is_none")]
86 pub flags: Option<ChannelFlags>,
87 /// The tags of a forum or media channel (max 20); tags without an ID are created.
88 #[serde(skip_serializing_if = "Option::is_none")]
89 pub available_tags: Option<Vec<ForumTagData>>,
90 /// The emoji of the add-reaction button on posts of a forum or media channel.
91 #[serde(skip_serializing_if = "Patch::is_keep")]
92 pub default_reaction_emoji: Patch<DefaultReaction>,
93 /// The slowmode copied to new threads.
94 #[serde(skip_serializing_if = "Option::is_none")]
95 pub default_thread_rate_limit_per_user: Option<u16>,
96 /// The default order of posts in a forum or media channel.
97 #[serde(skip_serializing_if = "Patch::is_keep")]
98 pub default_sort_order: Patch<SortOrderType>,
99 /// The default layout of a forum channel.
100 #[serde(skip_serializing_if = "Option::is_none")]
101 pub default_forum_layout: Option<ForumLayoutType>,
102}
103
104/// The body of [Modify Channel](https://docs.discord.com/developers/resources/channel#modify-channel)
105/// for a thread (D-109).
106///
107/// Needs `MANAGE_THREADS`, except for unarchiving an unlocked thread (`SEND_MESSAGES`).
108///
109/// discord.js counterpart: `ThreadEditOptions`.
110#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize)]
111#[non_exhaustive]
112pub struct ModifyThread {
113 /// The name (1-100 characters).
114 #[serde(skip_serializing_if = "Option::is_none")]
115 pub name: Option<CompactString>,
116 /// Whether the thread is archived.
117 #[serde(skip_serializing_if = "Option::is_none")]
118 pub archived: Option<bool>,
119 /// The inactivity after which the thread is archived.
120 #[serde(skip_serializing_if = "Option::is_none")]
121 pub auto_archive_duration: Option<AutoArchiveDuration>,
122 /// Whether the thread is locked (only `MANAGE_THREADS` can unarchive it).
123 #[serde(skip_serializing_if = "Option::is_none")]
124 pub locked: Option<bool>,
125 /// Whether non-moderators can add other non-moderators (private threads only).
126 #[serde(skip_serializing_if = "Option::is_none")]
127 pub invitable: Option<bool>,
128 /// Slowmode: seconds a member must wait between messages (0-21600).
129 #[serde(skip_serializing_if = "Patch::is_keep")]
130 pub rate_limit_per_user: Patch<u16>,
131 /// The thread's flags (`PINNED` only for posts of forum and media channels).
132 #[serde(skip_serializing_if = "Option::is_none")]
133 pub flags: Option<ChannelFlags>,
134 /// The tags of a forum or media post (max 5).
135 #[serde(skip_serializing_if = "Option::is_none")]
136 pub applied_tags: Option<Vec<TagId>>,
137}
138
139/// The body of [Modify Channel](https://docs.discord.com/developers/resources/channel#modify-channel)
140/// for a group DM (D-109).
141///
142/// discord.js counterpart: `PartialGroupDMChannel#edit` data.
143#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize)]
144#[non_exhaustive]
145pub struct ModifyGroupDm {
146 /// The name (1-100 characters).
147 #[serde(skip_serializing_if = "Option::is_none")]
148 pub name: Option<CompactString>,
149 /// The icon.
150 #[serde(skip_serializing_if = "Patch::is_keep")]
151 pub icon: Patch<ImageData>,
152}
153
154/// A [forum tag](https://docs.discord.com/developers/resources/channel#forum-tag-object) in a
155/// request (D-114): tags without an [`id`](Self::id) are created.
156///
157/// discord.js counterpart: `GuildForumTagData`.
158///
159/// # Examples
160///
161/// ```
162/// use djs_model::rest::ForumTagData;
163///
164/// let mut tag = ForumTagData::new("solved");
165/// tag.emoji_name = Some("✅".into());
166/// assert_eq!(
167/// serde_json::to_string(&tag).unwrap(),
168/// r#"{"name":"solved","moderated":false,"emoji_name":"✅"}"#
169/// );
170/// ```
171#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize)]
172#[non_exhaustive]
173pub struct ForumTagData {
174 /// The ID of an existing tag; `None` for a new tag.
175 #[serde(skip_serializing_if = "Option::is_none")]
176 pub id: Option<TagId>,
177 /// The name (0-20 characters).
178 pub name: CompactString,
179 /// Whether only members with `MANAGE_THREADS` can add or remove the tag.
180 pub moderated: bool,
181 /// A custom emoji of the guild.
182 #[serde(skip_serializing_if = "Option::is_none")]
183 pub emoji_id: Option<EmojiId>,
184 /// A Unicode emoji.
185 #[serde(skip_serializing_if = "Option::is_none")]
186 pub emoji_name: Option<CompactString>,
187}
188
189impl ForumTagData {
190 /// A new tag named `name`, without an emoji.
191 ///
192 /// discord.js counterpart: `GuildForumTagData`.
193 #[must_use]
194 pub fn new(name: impl Into<CompactString>) -> Self {
195 Self {
196 id: None,
197 name: name.into(),
198 moderated: false,
199 emoji_id: None,
200 emoji_name: None,
201 }
202 }
203}
204
205/// An existing tag, sent back unchanged.
206impl From<ForumTag> for ForumTagData {
207 fn from(tag: ForumTag) -> Self {
208 let ForumTag {
209 id,
210 name,
211 moderated,
212 emoji_id,
213 emoji_name,
214 } = tag;
215 Self {
216 id: Some(id),
217 name,
218 moderated,
219 emoji_id,
220 emoji_name,
221 }
222 }
223}
224
225impl From<&ForumTag> for ForumTagData {
226 fn from(tag: &ForumTag) -> Self {
227 tag.clone().into()
228 }
229}
230
231/// The query of [Get Channel Member Permissions](https://docs.discord.com/developers/resources/channel#get-channel-member-permissions)
232/// and [Get Channel Role Permissions](https://docs.discord.com/developers/resources/channel#get-channel-role-permissions).
233///
234/// discord.js counterpart: `RESTGetAPIChannelMemberPermissionsQuery` (discord-api-types).
235#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
236#[non_exhaustive]
237pub struct GetChannelPermissions {
238 /// Whether to apply [implicit permissions](https://docs.discord.com/developers/topics/permissions#implicit-permissions)
239 /// (no permissions without `VIEW_CHANNEL`, or `CONNECT` in voice and stage channels;
240 /// Discord's default: yes). Never applied to bots.
241 pub implicit: Option<bool>,
242}
243
244/// The body of [Set Voice Channel Status](https://docs.discord.com/developers/resources/channel#set-voice-channel-status).
245///
246/// discord.js counterpart: `RESTPutAPIChannelVoiceStatusJSONBody` (discord-api-types).
247#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize)]
248#[non_exhaustive]
249pub struct SetVoiceChannelStatus {
250 /// The status (up to 500 characters); `None` removes it.
251 pub status: Option<CompactString>,
252}
253
254impl SetVoiceChannelStatus {
255 /// Sets the status to `status`, or removes it.
256 ///
257 /// discord.js counterpart: `RESTPutAPIChannelVoiceStatusJSONBody` (discord-api-types).
258 #[must_use]
259 pub fn new(status: Option<impl Into<CompactString>>) -> Self {
260 Self {
261 status: status.map(Into::into),
262 }
263 }
264}
265
266/// The body of [Edit Channel Permissions](https://docs.discord.com/developers/resources/channel#edit-channel-permissions):
267/// the permission overwrite of one role or member.
268///
269/// discord.js counterpart: `PermissionOverwriteOptions` (as bitfields).
270///
271/// # Examples
272///
273/// ```
274/// use djs_model::{channel::OverwriteType, permissions::Permissions, rest::EditChannelPermissions};
275///
276/// let mut muted = EditChannelPermissions::new(OverwriteType::Role);
277/// muted.deny = Some(Permissions::SEND_MESSAGES);
278/// assert_eq!(serde_json::to_string(&muted).unwrap(), r#"{"deny":"2048","type":0}"#);
279/// ```
280#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize)]
281#[non_exhaustive]
282pub struct EditChannelPermissions {
283 /// The permissions to allow (Discord's default: none).
284 #[serde(skip_serializing_if = "Option::is_none")]
285 pub allow: Option<Permissions>,
286 /// The permissions to deny (Discord's default: none).
287 #[serde(skip_serializing_if = "Option::is_none")]
288 pub deny: Option<Permissions>,
289 /// Whether the overwrite is for a role or a member.
290 #[serde(rename = "type")]
291 pub kind: OverwriteType,
292}
293
294impl EditChannelPermissions {
295 /// An overwrite for a role or member that allows and denies nothing yet.
296 ///
297 /// discord.js counterpart: `PermissionOverwriteOptions`.
298 #[must_use]
299 pub const fn new(kind: OverwriteType) -> Self {
300 Self {
301 allow: None,
302 deny: None,
303 kind,
304 }
305 }
306}
307
308/// The body of [Create Channel Invite](https://docs.discord.com/developers/resources/channel#create-channel-invite).
309///
310/// Every field is optional. The users who can accept the invite are given either as
311/// [`target_user_ids`](Self::target_user_ids) or, for more than 1000 users, as a CSV
312/// [`target_users_file`](Self::target_users_file) with one user ID per line (D-111).
313///
314/// discord.js counterpart: `InviteCreateOptions`.
315#[derive(Clone, Debug, Default, PartialEq, Serialize)]
316#[non_exhaustive]
317pub struct CreateChannelInvite {
318 /// Seconds until the invite expires (0-604800, 0 = never; Discord's default: 86400).
319 #[serde(skip_serializing_if = "Option::is_none")]
320 pub max_age: Option<u32>,
321 /// How many times the invite can be used (0-100, 0 = unlimited, the default).
322 #[serde(skip_serializing_if = "Option::is_none")]
323 pub max_uses: Option<u8>,
324 /// Whether the invite only grants temporary membership.
325 #[serde(skip_serializing_if = "core::ops::Not::not")]
326 pub temporary: bool,
327 /// Whether to always create a new invite instead of reusing a similar one.
328 #[serde(skip_serializing_if = "core::ops::Not::not")]
329 pub unique: bool,
330 /// What a voice channel invite opens.
331 #[serde(skip_serializing_if = "Option::is_none")]
332 pub target_type: Option<InviteTargetType>,
333 /// The streaming user whose stream the invite shows (for
334 /// [`InviteTargetType::Stream`]).
335 #[serde(skip_serializing_if = "Option::is_none")]
336 pub target_user_id: Option<UserId>,
337 /// The embedded application the invite opens (for
338 /// [`InviteTargetType::EmbeddedApplication`]).
339 #[serde(skip_serializing_if = "Option::is_none")]
340 pub target_application_id: Option<ApplicationId>,
341 /// The only users who can see and accept the invite (max 1000).
342 #[serde(skip_serializing_if = "Vec::is_empty")]
343 pub target_user_ids: Vec<UserId>,
344 /// The roles given to users who accept the invite (needs `MANAGE_ROLES`).
345 #[serde(skip_serializing_if = "Vec::is_empty")]
346 pub role_ids: Vec<RoleId>,
347 /// A CSV file of the only users who can accept the invite, instead of
348 /// [`target_user_ids`](Self::target_user_ids); sent as `multipart/form-data`. Build it with
349 /// [`FileUpload::target_users`] (D-127).
350 #[serde(skip)]
351 pub target_users_file: Option<FileUpload>,
352}
353
354/// The body of [Follow Announcement Channel](https://docs.discord.com/developers/resources/channel#follow-announcement-channel).
355///
356/// discord.js counterpart: `RESTPostAPIChannelFollowersJSONBody` (discord-api-types).
357#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize)]
358#[non_exhaustive]
359pub struct FollowAnnouncementChannel {
360 /// The channel that receives the announcements (needs `MANAGE_WEBHOOKS` there).
361 pub webhook_channel_id: ChannelId,
362}
363
364impl FollowAnnouncementChannel {
365 /// Follows into `webhook_channel_id`.
366 ///
367 /// discord.js counterpart: `NewsChannel#addFollower`.
368 #[must_use]
369 pub const fn new(webhook_channel_id: ChannelId) -> Self {
370 Self { webhook_channel_id }
371 }
372}
373
374/// The body of [Group DM Add Recipient](https://docs.discord.com/developers/resources/channel#group-dm-add-recipient).
375///
376/// The access token is redacted in the `Debug` output.
377///
378/// discord.js counterpart: `RESTPutAPIChannelRecipientJSONBody` (discord-api-types).
379#[derive(Clone, PartialEq, Eq, Hash, Serialize)]
380#[non_exhaustive]
381pub struct GroupDmAddRecipient {
382 /// The `OAuth2` access token of the user, who granted the `gdm.join` scope.
383 pub access_token: String,
384 /// The user's nickname in the group DM.
385 #[serde(skip_serializing_if = "Option::is_none")]
386 pub nick: Option<CompactString>,
387}
388
389impl GroupDmAddRecipient {
390 /// Adds the user whose access token is `access_token`.
391 ///
392 /// discord.js counterpart: `RESTPutAPIChannelRecipientJSONBody` (discord-api-types).
393 #[must_use]
394 pub fn new(access_token: impl Into<String>) -> Self {
395 Self {
396 access_token: access_token.into(),
397 nick: None,
398 }
399 }
400}
401
402impl fmt::Debug for GroupDmAddRecipient {
403 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
404 f.debug_struct("GroupDmAddRecipient")
405 .field("access_token", &"<redacted>")
406 .field("nick", &self.nick)
407 .finish()
408 }
409}
410
411/// The body of [Start Thread from Message](https://docs.discord.com/developers/resources/channel#start-thread-from-message).
412///
413/// discord.js counterpart: `StartThreadOptions`.
414#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize)]
415#[non_exhaustive]
416pub struct StartThreadFromMessage {
417 /// The name (1-100 characters).
418 pub name: CompactString,
419 /// The inactivity after which the thread is archived.
420 #[serde(skip_serializing_if = "Option::is_none")]
421 pub auto_archive_duration: Option<AutoArchiveDuration>,
422 /// Slowmode: seconds a member must wait between messages (0-21600).
423 #[serde(skip_serializing_if = "Option::is_none")]
424 pub rate_limit_per_user: Option<u16>,
425}
426
427impl StartThreadFromMessage {
428 /// A thread named `name`.
429 ///
430 /// discord.js counterpart: `StartThreadOptions`.
431 #[must_use]
432 pub fn new(name: impl Into<CompactString>) -> Self {
433 Self {
434 name: name.into(),
435 auto_archive_duration: None,
436 rate_limit_per_user: None,
437 }
438 }
439}
440
441/// The body of [Start Thread without Message](https://docs.discord.com/developers/resources/channel#start-thread-without-message).
442///
443/// The thread's type is always sent (Discord's default, a private thread, is going away).
444///
445/// discord.js counterpart: `GuildTextThreadCreateOptions`.
446///
447/// # Examples
448///
449/// ```
450/// use djs_model::{channel::ChannelType, rest::StartThreadWithoutMessage};
451///
452/// let body = StartThreadWithoutMessage::new("Support", ChannelType::PrivateThread);
453/// assert_eq!(serde_json::to_string(&body).unwrap(), r#"{"name":"Support","type":12}"#);
454/// ```
455#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize)]
456#[non_exhaustive]
457pub struct StartThreadWithoutMessage {
458 /// The name (1-100 characters).
459 pub name: CompactString,
460 /// The inactivity after which the thread is archived.
461 #[serde(skip_serializing_if = "Option::is_none")]
462 pub auto_archive_duration: Option<AutoArchiveDuration>,
463 /// The type of thread: public, private or (in announcement channels) announcement.
464 #[serde(rename = "type")]
465 pub kind: ChannelType,
466 /// Whether non-moderators can add other non-moderators (private threads only).
467 #[serde(skip_serializing_if = "Option::is_none")]
468 pub invitable: Option<bool>,
469 /// Slowmode: seconds a member must wait between messages (0-21600).
470 #[serde(skip_serializing_if = "Option::is_none")]
471 pub rate_limit_per_user: Option<u16>,
472}
473
474impl StartThreadWithoutMessage {
475 /// A thread of type `kind` named `name`.
476 ///
477 /// discord.js counterpart: `GuildTextThreadCreateOptions`.
478 #[must_use]
479 pub fn new(name: impl Into<CompactString>, kind: ChannelType) -> Self {
480 Self {
481 name: name.into(),
482 auto_archive_duration: None,
483 kind,
484 invitable: None,
485 rate_limit_per_user: None,
486 }
487 }
488}
489
490/// The body of [Start Thread in Forum or Media Channel](https://docs.discord.com/developers/resources/channel#start-thread-in-forum-or-media-channel):
491/// a post with its first message.
492///
493/// The files of the [`message`](Self::message) are uploaded with it.
494///
495/// discord.js counterpart: `GuildForumThreadCreateOptions`.
496///
497/// # Examples
498///
499/// ```
500/// use djs_model::rest::{ForumThreadMessage, StartThreadInForumOrMediaChannel};
501///
502/// let body = StartThreadInForumOrMediaChannel::new("Bug: crash", ForumThreadMessage::from("It crashes"));
503/// assert_eq!(
504/// serde_json::to_string(&body).unwrap(),
505/// r#"{"name":"Bug: crash","message":{"content":"It crashes"}}"#
506/// );
507/// ```
508#[derive(Clone, Debug, PartialEq, Serialize)]
509#[non_exhaustive]
510pub struct StartThreadInForumOrMediaChannel {
511 /// The name (1-100 characters).
512 pub name: CompactString,
513 /// The inactivity after which the thread is archived.
514 #[serde(skip_serializing_if = "Option::is_none")]
515 pub auto_archive_duration: Option<AutoArchiveDuration>,
516 /// Slowmode: seconds a member must wait between messages (0-21600).
517 #[serde(skip_serializing_if = "Option::is_none")]
518 pub rate_limit_per_user: Option<u16>,
519 /// The first message.
520 pub message: ForumThreadMessage,
521 /// The tags of the post (max 5).
522 #[serde(skip_serializing_if = "Vec::is_empty")]
523 pub applied_tags: Vec<TagId>,
524}
525
526impl StartThreadInForumOrMediaChannel {
527 /// A post named `name` starting with `message`.
528 ///
529 /// discord.js counterpart: `GuildForumThreadCreateOptions`.
530 #[must_use]
531 pub fn new(name: impl Into<CompactString>, message: ForumThreadMessage) -> Self {
532 Self {
533 name: name.into(),
534 auto_archive_duration: None,
535 rate_limit_per_user: None,
536 message,
537 applied_tags: Vec::new(),
538 }
539 }
540}
541
542/// The [first message](https://docs.discord.com/developers/resources/channel#start-thread-in-forum-or-media-channel-forum-and-media-thread-message-params-object)
543/// of a forum or media post (D-112).
544///
545/// At least one of `content`, `embeds`, `sticker_ids`, `components` or `files` is required.
546/// Like [`CreateMessage`](super::CreateMessage), every file gets an `attachments` entry
547/// automatically (D-094).
548///
549/// discord.js counterpart: the `message` of `RESTPostAPIGuildForumThreadsJSONBody` (discord-api-types).
550#[derive(Clone, Debug, Default, PartialEq)]
551#[non_exhaustive]
552pub struct ForumThreadMessage {
553 /// The text (up to 2000 characters).
554 pub content: Option<CompactString>,
555 /// Up to 10 rich embeds (up to 6000 characters in total).
556 pub embeds: Vec<Embed>,
557 /// Which mentions in the content notify.
558 pub allowed_mentions: Option<AllowedMentions>,
559 /// The components.
560 pub components: Vec<Component>,
561 /// Up to 3 stickers of the guild to send.
562 pub sticker_ids: Vec<StickerId>,
563 /// Explicit attachment entries. Usually left out: every file gets one automatically,
564 /// unless an entry with its `files[n]` index is listed here.
565 pub attachments: Option<Vec<AttachmentRequest>>,
566 /// Only [`SUPPRESS_EMBEDS`](MessageFlags::SUPPRESS_EMBEDS),
567 /// [`SUPPRESS_NOTIFICATIONS`](MessageFlags::SUPPRESS_NOTIFICATIONS) and
568 /// [`IS_COMPONENTS_V2`](MessageFlags::IS_COMPONENTS_V2) can be set.
569 pub flags: Option<MessageFlags>,
570 /// Files to upload with the message.
571 pub files: Vec<FileUpload>,
572}
573
574impl From<&str> for ForumThreadMessage {
575 fn from(content: &str) -> Self {
576 Self {
577 content: Some(content.into()),
578 ..Self::default()
579 }
580 }
581}
582
583impl From<String> for ForumThreadMessage {
584 fn from(content: String) -> Self {
585 Self {
586 content: Some(content.into()),
587 ..Self::default()
588 }
589 }
590}
591
592impl Serialize for ForumThreadMessage {
593 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
594 #[derive(Serialize)]
595 struct Wire<'a> {
596 #[serde(skip_serializing_if = "Option::is_none")]
597 content: Option<&'a CompactString>,
598 #[serde(skip_serializing_if = "<[_]>::is_empty")]
599 embeds: &'a [Embed],
600 #[serde(skip_serializing_if = "Option::is_none")]
601 allowed_mentions: Option<&'a AllowedMentions>,
602 #[serde(skip_serializing_if = "<[_]>::is_empty")]
603 components: &'a [Component],
604 #[serde(skip_serializing_if = "<[_]>::is_empty")]
605 sticker_ids: &'a [StickerId],
606 #[serde(skip_serializing_if = "Attachments::is_absent")]
607 attachments: Attachments<'a>,
608 #[serde(skip_serializing_if = "Option::is_none")]
609 flags: Option<MessageFlags>,
610 }
611
612 // Destructured without `..`, so a new field cannot be forgotten here.
613 let Self {
614 content,
615 embeds,
616 allowed_mentions,
617 components,
618 sticker_ids,
619 attachments,
620 flags,
621 files,
622 } = self;
623 Wire {
624 content: content.as_ref(),
625 embeds,
626 allowed_mentions: allowed_mentions.as_ref(),
627 components,
628 sticker_ids,
629 attachments: Attachments::new(attachments.as_deref(), files),
630 flags: *flags,
631 }
632 .serialize(serializer)
633 }
634}
635
636/// The response of [Start Thread in Forum or Media Channel](https://docs.discord.com/developers/resources/channel#start-thread-in-forum-or-media-channel):
637/// the created post and its first message (D-115).
638///
639/// discord.js counterpart: `RESTPostAPIChannelThreadsResult` (discord-api-types), with its first message.
640#[derive(Clone, Debug, PartialEq)]
641#[non_exhaustive]
642pub struct ForumThread {
643 /// The thread.
644 pub channel: Channel,
645 /// The thread's first message.
646 pub message: Option<Message>,
647}
648
649impl<'de> Deserialize<'de> for ForumThread {
650 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
651 // The message is nested inside the channel object.
652 #[derive(Deserialize)]
653 struct Wire {
654 #[serde(flatten)]
655 channel: Channel,
656 #[serde(default)]
657 message: Option<Message>,
658 }
659
660 let Wire { channel, message } = Wire::deserialize(deserializer)?;
661 Ok(Self { channel, message })
662 }
663}
664
665/// The query of [Get Thread Member](https://docs.discord.com/developers/resources/channel#get-thread-member).
666///
667/// discord.js counterpart: `RESTGetAPIChannelThreadMemberQuery` (discord-api-types).
668#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
669#[non_exhaustive]
670pub struct GetThreadMember {
671 /// Whether to include the guild [`member`](ThreadMember::member).
672 pub with_member: Option<bool>,
673}
674
675/// The query of [List Thread Members](https://docs.discord.com/developers/resources/channel#list-thread-members).
676///
677/// Needs the `GUILD_MEMBERS` privileged intent. With `with_member`, the results are
678/// paginated (100 per page by default).
679///
680/// discord.js counterpart: `RESTGetAPIChannelThreadMembersQuery` (discord-api-types).
681#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
682#[non_exhaustive]
683pub struct ListThreadMembers {
684 /// Whether to include each guild [`member`](ThreadMember::member) (and paginate).
685 pub with_member: Option<bool>,
686 /// Members after this user ID.
687 pub after: Option<UserId>,
688 /// The page size (1-100, default 100).
689 pub limit: Option<u8>,
690}
691
692/// The query of [List Public Archived Threads](https://docs.discord.com/developers/resources/channel#list-public-archived-threads)
693/// and [List Private Archived Threads](https://docs.discord.com/developers/resources/channel#list-private-archived-threads).
694///
695/// discord.js counterpart: `RESTGetAPIChannelThreadsArchivedQuery` (discord-api-types).
696#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
697#[non_exhaustive]
698pub struct ListArchivedThreads {
699 /// Threads archived before this time.
700 pub before: Option<Timestamp>,
701 /// The maximum number of threads.
702 pub limit: Option<u16>,
703}
704
705/// The query of [List Joined Private Archived Threads](https://docs.discord.com/developers/resources/channel#list-joined-private-archived-threads).
706///
707/// discord.js counterpart: `RESTGetAPIChannelThreadsArchivedQuery` (discord-api-types).
708#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
709#[non_exhaustive]
710pub struct ListJoinedPrivateArchivedThreads {
711 /// Threads with an ID below this one.
712 pub before: Option<ChannelId>,
713 /// The maximum number of threads.
714 pub limit: Option<u16>,
715}
716
717/// The response of the [archived thread lists](https://docs.discord.com/developers/resources/channel#list-public-archived-threads).
718///
719/// discord.js counterpart: `FetchedThreadsMore`.
720#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
721#[non_exhaustive]
722pub struct ArchivedThreads {
723 /// The threads, newest archived (or highest ID) first.
724 pub threads: Vec<Channel>,
725 /// The current user's membership of each returned thread they joined.
726 pub members: Vec<ThreadMember>,
727 /// Whether more threads may follow.
728 pub has_more: bool,
729}
730
731#[cfg(test)]
732mod tests {
733 use super::*;
734 use crate::id::GenericId;
735
736 #[test]
737 fn modify_bodies() {
738 let mut channel = ModifyGuildChannel {
739 parent_id: Patch::Clear,
740 user_limit: Patch::Set(10),
741 ..ModifyGuildChannel::default()
742 };
743 channel.permission_overwrites = Patch::Set(vec![Overwrite {
744 id: GenericId::new(5),
745 kind: OverwriteType::Member,
746 allow: Permissions::VIEW_CHANNEL,
747 deny: Permissions::empty(),
748 }]);
749 assert_eq!(
750 serde_json::to_string(&channel).unwrap(),
751 concat!(
752 r#"{"user_limit":10,"permission_overwrites":[{"id":"5","type":1,"allow":"1024","#,
753 r#""deny":"0"}],"parent_id":null}"#
754 )
755 );
756
757 let thread = ModifyThread {
758 archived: Some(false),
759 rate_limit_per_user: Patch::Clear,
760 applied_tags: Some(vec![TagId::new(3)]),
761 ..ModifyThread::default()
762 };
763 assert_eq!(
764 serde_json::to_string(&thread).unwrap(),
765 r#"{"archived":false,"rate_limit_per_user":null,"applied_tags":["3"]}"#
766 );
767
768 let group = ModifyGroupDm {
769 icon: Patch::Set(ImageData::with_content_type(&b"GIF89a"[..], "image/gif")),
770 ..ModifyGroupDm::default()
771 };
772 assert_eq!(
773 serde_json::to_string(&group).unwrap(),
774 r#"{"icon":"data:image/gif;base64,R0lGODlh"}"#
775 );
776 }
777
778 #[test]
779 fn invite_and_recipient_bodies() {
780 let invite = CreateChannelInvite {
781 max_age: Some(0),
782 unique: true,
783 target_users_file: Some(FileUpload::new("users.csv", "1\n")),
784 ..CreateChannelInvite::default()
785 };
786 assert_eq!(
787 serde_json::to_string(&invite).unwrap(),
788 r#"{"max_age":0,"unique":true}"#
789 );
790 assert_eq!(
791 serde_json::to_string(&CreateChannelInvite::default()).unwrap(),
792 "{}"
793 );
794
795 let recipient = GroupDmAddRecipient::new("super-secret");
796 assert!(!format!("{recipient:?}").contains("super-secret"));
797 assert_eq!(
798 serde_json::to_string(&recipient).unwrap(),
799 r#"{"access_token":"super-secret"}"#
800 );
801 }
802
803 #[test]
804 fn forum_thread_with_files() {
805 let mut message = ForumThreadMessage::from("see log");
806 message.files.push(FileUpload::new("log.txt", "ok"));
807 let mut body = StartThreadInForumOrMediaChannel::new("Report", message);
808 body.applied_tags.push(TagId::new(9));
809 assert_eq!(
810 serde_json::to_string(&body).unwrap(),
811 concat!(
812 r#"{"name":"Report","message":{"content":"see log","attachments":"#,
813 r#"[{"id":0,"filename":"log.txt"}]},"applied_tags":["9"]}"#
814 )
815 );
816 }
817
818 #[test]
819 fn forum_tags_round_trip() {
820 let tag: ForumTag = serde_json::from_str(
821 r#"{"id":"7","name":"bug","moderated":true,"emoji_id":null,"emoji_name":"🐛"}"#,
822 )
823 .unwrap();
824 assert_eq!(
825 serde_json::to_string(&ForumTagData::from(&tag)).unwrap(),
826 r#"{"id":"7","name":"bug","moderated":true,"emoji_name":"🐛"}"#
827 );
828 }
829}