Skip to main content

djs_model/
channel.rs

1//! [Channels](https://docs.discord.com/developers/resources/channel): guild text, voice, forum
2//! and media channels, threads and direct messages.
3//!
4//! A [`Channel`] is an enum with one variant per [`ChannelType`], each holding a struct with
5//! the fields that kind of channel has (D-057).
6
7use compact_str::CompactString;
8use serde::{Deserialize, Deserializer, Serialize, Serializer, de::Error as DeError};
9
10use crate::{
11    guild::Member,
12    id::{
13        ApplicationId, ChannelId, EmojiId, GenericId, GuildId, MessageId, RoleId, TagId, UserId,
14        WebhookId,
15    },
16    macros::{int_enum, int_flags},
17    permissions::Permissions,
18    user::User,
19    util::{ImageHash, Timestamp},
20};
21
22/// A [channel](https://docs.discord.com/developers/resources/channel#channel-object) of any
23/// kind (D-057).
24///
25/// Match on the variant to get the fields of a specific kind of channel, or use the methods for
26/// the fields most kinds share.
27///
28/// discord.js counterpart: `Channel` and its subclasses (`TextChannel`, `VoiceChannel`,
29/// `ThreadChannel`, …).
30///
31/// # Examples
32///
33/// ```
34/// use djs_model::channel::{Channel, ChannelType};
35///
36/// let channel: Channel = serde_json::from_str(
37///     r#"{"id":"41771983423143937","guild_id":"41771983423143937","name":"general",
38///         "type":0,"position":6,"permission_overwrites":[],"rate_limit_per_user":2,
39///         "nsfw":true,"topic":"24/7 chat about how to gank Mike #2",
40///         "last_message_id":"155117677105512449","parent_id":"399942396007890945"}"#,
41/// )?;
42/// assert_eq!(channel.kind(), ChannelType::GuildText);
43/// assert_eq!(channel.name(), Some("general"));
44/// if let Channel::Text(text) = &channel {
45///     assert_eq!(text.rate_limit_per_user, 2);
46/// }
47/// # Ok::<(), serde_json::Error>(())
48/// ```
49#[derive(Clone, Debug, PartialEq, Eq)]
50#[non_exhaustive]
51pub enum Channel {
52    /// A text channel in a guild (`GUILD_TEXT`).
53    Text(TextChannel),
54    /// A direct message between two users (`DM`).
55    Dm(DmChannel),
56    /// A voice channel in a guild (`GUILD_VOICE`).
57    Voice(VoiceChannel),
58    /// A direct message between several users (`GROUP_DM`).
59    GroupDm(GroupDmChannel),
60    /// A category that contains up to 50 channels (`GUILD_CATEGORY`).
61    Category(CategoryChannel),
62    /// An announcement channel whose messages can be followed and crossposted
63    /// (`GUILD_ANNOUNCEMENT`).
64    Announcement(TextChannel),
65    /// A thread in an announcement channel (`ANNOUNCEMENT_THREAD`).
66    AnnouncementThread(ThreadChannel),
67    /// A public thread in a text, forum or media channel (`PUBLIC_THREAD`).
68    PublicThread(ThreadChannel),
69    /// A private thread in a text channel (`PRIVATE_THREAD`).
70    PrivateThread(ThreadChannel),
71    /// A stage channel for events with an audience (`GUILD_STAGE_VOICE`).
72    Stage(VoiceChannel),
73    /// The channel of a Student Hub listing its servers (`GUILD_DIRECTORY`).
74    Directory(DirectoryChannel),
75    /// A channel that only contains threads (posts) (`GUILD_FORUM`).
76    Forum(ForumChannel),
77    /// A forum-like channel for media posts (`GUILD_MEDIA`).
78    Media(ForumChannel),
79    /// A kind of channel this version of the library does not know about (C-010).
80    Unknown(UnknownChannel),
81}
82
83impl Channel {
84    /// The channel's ID.
85    ///
86    /// discord.js counterpart: `BaseChannel#id`.
87    #[must_use]
88    pub const fn id(&self) -> ChannelId {
89        match self {
90            Self::Text(channel) | Self::Announcement(channel) => channel.id,
91            Self::Dm(channel) => channel.id,
92            Self::Voice(channel) | Self::Stage(channel) => channel.id,
93            Self::GroupDm(channel) => channel.id,
94            Self::Category(channel) => channel.id,
95            Self::AnnouncementThread(channel)
96            | Self::PublicThread(channel)
97            | Self::PrivateThread(channel) => channel.id,
98            Self::Directory(channel) => channel.id,
99            Self::Forum(channel) | Self::Media(channel) => channel.id,
100            Self::Unknown(channel) => channel.id,
101        }
102    }
103
104    /// The kind of channel.
105    ///
106    /// discord.js counterpart: `BaseChannel#type`.
107    #[must_use]
108    pub const fn kind(&self) -> ChannelType {
109        match self {
110            Self::Text(_) => ChannelType::GuildText,
111            Self::Dm(_) => ChannelType::Dm,
112            Self::Voice(_) => ChannelType::GuildVoice,
113            Self::GroupDm(_) => ChannelType::GroupDm,
114            Self::Category(_) => ChannelType::GuildCategory,
115            Self::Announcement(_) => ChannelType::GuildAnnouncement,
116            Self::AnnouncementThread(_) => ChannelType::AnnouncementThread,
117            Self::PublicThread(_) => ChannelType::PublicThread,
118            Self::PrivateThread(_) => ChannelType::PrivateThread,
119            Self::Stage(_) => ChannelType::GuildStageVoice,
120            Self::Directory(_) => ChannelType::GuildDirectory,
121            Self::Forum(_) => ChannelType::GuildForum,
122            Self::Media(_) => ChannelType::GuildMedia,
123            Self::Unknown(channel) => channel.kind,
124        }
125    }
126
127    /// The guild the channel belongs to. `None` for DMs, and for guild channels inside
128    /// `GUILD_CREATE` (where Discord omits it).
129    ///
130    /// discord.js counterpart: `GuildChannel#guildId`.
131    #[must_use]
132    pub const fn guild_id(&self) -> Option<GuildId> {
133        match self {
134            Self::Text(channel) | Self::Announcement(channel) => channel.guild_id,
135            Self::Voice(channel) | Self::Stage(channel) => channel.guild_id,
136            Self::Category(channel) => channel.guild_id,
137            Self::AnnouncementThread(channel)
138            | Self::PublicThread(channel)
139            | Self::PrivateThread(channel) => channel.guild_id,
140            Self::Directory(channel) => channel.guild_id,
141            Self::Forum(channel) | Self::Media(channel) => channel.guild_id,
142            Self::Unknown(channel) => channel.guild_id,
143            Self::Dm(_) | Self::GroupDm(_) => None,
144        }
145    }
146
147    /// The channel's name. `None` for DMs and unnamed group DMs.
148    ///
149    /// discord.js counterpart: `GuildChannel#name`.
150    #[must_use]
151    pub fn name(&self) -> Option<&str> {
152        match self {
153            Self::Text(channel) | Self::Announcement(channel) => Some(&channel.name),
154            Self::Voice(channel) | Self::Stage(channel) => Some(&channel.name),
155            Self::Category(channel) => Some(&channel.name),
156            Self::AnnouncementThread(channel)
157            | Self::PublicThread(channel)
158            | Self::PrivateThread(channel) => Some(&channel.name),
159            Self::Directory(channel) => Some(&channel.name),
160            Self::Forum(channel) | Self::Media(channel) => Some(&channel.name),
161            Self::GroupDm(channel) => channel.name.as_deref(),
162            Self::Unknown(channel) => channel.name.as_deref(),
163            Self::Dm(_) => None,
164        }
165    }
166
167    /// The parent: the category of a guild channel, or the channel a thread was created in.
168    ///
169    /// discord.js counterpart: `GuildChannel#parentId`.
170    #[must_use]
171    pub const fn parent_id(&self) -> Option<ChannelId> {
172        match self {
173            Self::Text(channel) | Self::Announcement(channel) => channel.parent_id,
174            Self::Voice(channel) | Self::Stage(channel) => channel.parent_id,
175            Self::AnnouncementThread(channel)
176            | Self::PublicThread(channel)
177            | Self::PrivateThread(channel) => channel.parent_id,
178            Self::Directory(channel) => channel.parent_id,
179            Self::Forum(channel) | Self::Media(channel) => channel.parent_id,
180            Self::Unknown(channel) => channel.parent_id,
181            Self::Dm(_) | Self::GroupDm(_) | Self::Category(_) => None,
182        }
183    }
184
185    /// The channel's [flags](ChannelFlags).
186    ///
187    /// discord.js counterpart: `BaseChannel#flags`.
188    #[must_use]
189    pub const fn flags(&self) -> ChannelFlags {
190        match self {
191            Self::Text(channel) | Self::Announcement(channel) => channel.flags,
192            Self::Dm(channel) => channel.flags,
193            Self::Voice(channel) | Self::Stage(channel) => channel.flags,
194            Self::GroupDm(channel) => channel.flags,
195            Self::Category(channel) => channel.flags,
196            Self::AnnouncementThread(channel)
197            | Self::PublicThread(channel)
198            | Self::PrivateThread(channel) => channel.flags,
199            Self::Directory(channel) => channel.flags,
200            Self::Forum(channel) | Self::Media(channel) => channel.flags,
201            Self::Unknown(channel) => channel.flags,
202        }
203    }
204
205    /// The permission overwrites of a guild channel; empty for DMs and threads.
206    ///
207    /// discord.js counterpart: `GuildChannel#permissionOverwrites`.
208    #[must_use]
209    pub fn permission_overwrites(&self) -> &[Overwrite] {
210        match self {
211            Self::Text(channel) | Self::Announcement(channel) => &channel.permission_overwrites,
212            Self::Voice(channel) | Self::Stage(channel) => &channel.permission_overwrites,
213            Self::Category(channel) => &channel.permission_overwrites,
214            Self::Directory(channel) => &channel.permission_overwrites,
215            Self::Forum(channel) | Self::Media(channel) => &channel.permission_overwrites,
216            Self::Dm(_)
217            | Self::GroupDm(_)
218            | Self::AnnouncementThread(_)
219            | Self::PublicThread(_)
220            | Self::PrivateThread(_)
221            | Self::Unknown(_) => &[],
222        }
223    }
224
225    /// Returns the thread data if this channel is a thread.
226    ///
227    /// discord.js counterpart: `BaseChannel#isThread`.
228    #[must_use]
229    pub const fn as_thread(&self) -> Option<&ThreadChannel> {
230        match self {
231            Self::AnnouncementThread(channel)
232            | Self::PublicThread(channel)
233            | Self::PrivateThread(channel) => Some(channel),
234            _ => None,
235        }
236    }
237}
238
239int_enum! {
240    /// The [type of a channel](https://docs.discord.com/developers/resources/channel#channel-object-channel-types).
241    ///
242    /// discord.js counterpart: `ChannelType`.
243    pub enum ChannelType: u8 {
244        /// A text channel in a guild.
245        GuildText = 0,
246        /// A direct message between two users.
247        Dm = 1,
248        /// A voice channel in a guild.
249        GuildVoice = 2,
250        /// A direct message between several users.
251        GroupDm = 3,
252        /// A category that organizes up to 50 channels.
253        GuildCategory = 4,
254        /// A channel that users can follow and crosspost into their own guild.
255        GuildAnnouncement = 5,
256        /// A thread in an announcement channel.
257        AnnouncementThread = 10,
258        /// A public thread in a text, forum or media channel.
259        PublicThread = 11,
260        /// A private thread in a text channel, visible to invited members and moderators.
261        PrivateThread = 12,
262        /// A voice channel for hosting events with an audience.
263        GuildStageVoice = 13,
264        /// The channel of a Student Hub listing its servers.
265        GuildDirectory = 14,
266        /// A channel that can only contain threads.
267        GuildForum = 15,
268        /// A channel that can only contain threads, for media posts.
269        GuildMedia = 16,
270    }
271}
272
273impl ChannelType {
274    /// Whether channels of this type are threads.
275    ///
276    /// discord.js counterpart: `BaseChannel#isThread`.
277    #[must_use]
278    pub const fn is_thread(self) -> bool {
279        matches!(
280            self,
281            Self::AnnouncementThread | Self::PublicThread | Self::PrivateThread
282        )
283    }
284}
285
286/// A text or announcement channel in a guild.
287///
288/// discord.js counterpart: `TextChannel` / `NewsChannel`.
289#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
290#[non_exhaustive]
291pub struct TextChannel {
292    /// The channel's ID.
293    pub id: ChannelId,
294    /// The guild; `None` inside `GUILD_CREATE`.
295    #[serde(skip_serializing_if = "Option::is_none")]
296    pub guild_id: Option<GuildId>,
297    /// The channel's name (1-100 characters).
298    pub name: CompactString,
299    /// The sorting position; channels with equal positions are ordered by ID.
300    pub position: i32,
301    /// Explicit permissions for roles and members.
302    pub permission_overwrites: Vec<Overwrite>,
303    /// The parent category.
304    pub parent_id: Option<ChannelId>,
305    /// Whether the channel is [age-restricted](https://support.discord.com/hc/en-us/articles/115000084051).
306    pub nsfw: bool,
307    /// The channel topic (0-1024 characters).
308    pub topic: Option<CompactString>,
309    /// The last message sent (it may not exist any more).
310    pub last_message_id: Option<MessageId>,
311    /// Slowmode: seconds a user must wait between messages (0-21600). Bots and members with
312    /// `MANAGE_MESSAGES`/`MANAGE_CHANNELS` are exempt.
313    pub rate_limit_per_user: u16,
314    /// When the last message was pinned.
315    #[serde(skip_serializing_if = "Option::is_none")]
316    pub last_pin_timestamp: Option<Timestamp>,
317    /// The auto-archive duration copied onto new threads.
318    #[serde(skip_serializing_if = "Option::is_none")]
319    pub default_auto_archive_duration: Option<AutoArchiveDuration>,
320    /// The slowmode copied onto new threads.
321    #[serde(skip_serializing_if = "Option::is_none")]
322    pub default_thread_rate_limit_per_user: Option<u16>,
323    /// The channel's flags.
324    pub flags: ChannelFlags,
325}
326
327/// A voice or stage channel in a guild.
328///
329/// Voice channels also have a text chat.
330///
331/// discord.js counterpart: `VoiceChannel` / `StageChannel`.
332#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
333#[non_exhaustive]
334pub struct VoiceChannel {
335    /// The channel's ID.
336    pub id: ChannelId,
337    /// The guild; `None` inside `GUILD_CREATE`.
338    #[serde(skip_serializing_if = "Option::is_none")]
339    pub guild_id: Option<GuildId>,
340    /// The channel's name (1-100 characters).
341    pub name: CompactString,
342    /// The sorting position.
343    pub position: i32,
344    /// Explicit permissions for roles and members.
345    pub permission_overwrites: Vec<Overwrite>,
346    /// The parent category.
347    pub parent_id: Option<ChannelId>,
348    /// Whether the channel is age-restricted.
349    pub nsfw: bool,
350    /// The topic of a stage channel.
351    #[serde(skip_serializing_if = "Option::is_none")]
352    pub topic: Option<CompactString>,
353    /// The last message sent in the channel's text chat.
354    pub last_message_id: Option<MessageId>,
355    /// Slowmode of the text chat, in seconds.
356    pub rate_limit_per_user: u16,
357    /// The audio bitrate in bits per second.
358    pub bitrate: u32,
359    /// The maximum number of users; `0` means no limit.
360    pub user_limit: u32,
361    /// The [voice region](https://docs.discord.com/developers/resources/voice#voice-region-object);
362    /// `None` means automatic.
363    pub rtc_region: Option<CompactString>,
364    /// The camera video quality.
365    pub video_quality_mode: VideoQualityMode,
366    /// The channel's flags.
367    pub flags: ChannelFlags,
368}
369
370/// A category that organizes channels.
371///
372/// discord.js counterpart: `CategoryChannel`.
373#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
374#[non_exhaustive]
375pub struct CategoryChannel {
376    /// The category's ID.
377    pub id: ChannelId,
378    /// The guild; `None` inside `GUILD_CREATE`.
379    #[serde(skip_serializing_if = "Option::is_none")]
380    pub guild_id: Option<GuildId>,
381    /// The category's name.
382    pub name: CompactString,
383    /// The sorting position.
384    pub position: i32,
385    /// Explicit permissions, synced onto channels that follow the category.
386    pub permission_overwrites: Vec<Overwrite>,
387    /// Whether the category is age-restricted.
388    pub nsfw: bool,
389    /// The category's flags.
390    pub flags: ChannelFlags,
391}
392
393/// A forum or media channel: it only contains threads (posts).
394///
395/// discord.js counterpart: `ForumChannel` / `MediaChannel`.
396#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
397#[non_exhaustive]
398pub struct ForumChannel {
399    /// The channel's ID.
400    pub id: ChannelId,
401    /// The guild; `None` inside `GUILD_CREATE`.
402    #[serde(skip_serializing_if = "Option::is_none")]
403    pub guild_id: Option<GuildId>,
404    /// The channel's name.
405    pub name: CompactString,
406    /// The sorting position.
407    pub position: i32,
408    /// Explicit permissions for roles and members.
409    pub permission_overwrites: Vec<Overwrite>,
410    /// The parent category.
411    pub parent_id: Option<ChannelId>,
412    /// Whether the channel is age-restricted.
413    pub nsfw: bool,
414    /// The guidelines shown to posters (0-4096 characters).
415    pub topic: Option<CompactString>,
416    /// The last thread created (it may not exist any more).
417    pub last_message_id: Option<MessageId>,
418    /// Slowmode for creating posts, in seconds.
419    pub rate_limit_per_user: u16,
420    /// The auto-archive duration copied onto new posts.
421    #[serde(skip_serializing_if = "Option::is_none")]
422    pub default_auto_archive_duration: Option<AutoArchiveDuration>,
423    /// The tags posts can have (up to 20).
424    pub available_tags: Vec<ForumTag>,
425    /// The slowmode copied onto new posts.
426    #[serde(skip_serializing_if = "Option::is_none")]
427    pub default_thread_rate_limit_per_user: Option<u16>,
428    /// The emoji shown on the add-reaction button of posts.
429    pub default_reaction_emoji: Option<DefaultReaction>,
430    /// How posts are sorted by default; `None` when not set.
431    pub default_sort_order: Option<SortOrderType>,
432    /// How posts are displayed by default (forum channels only).
433    pub default_forum_layout: ForumLayoutType,
434    /// The channel's flags.
435    pub flags: ChannelFlags,
436}
437
438/// A thread: a temporary sub-channel of a text, announcement, forum or media channel.
439///
440/// discord.js counterpart: `ThreadChannel`.
441#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
442#[non_exhaustive]
443pub struct ThreadChannel {
444    /// The thread's ID (for threads started from a message, the message's ID).
445    pub id: ChannelId,
446    /// The guild; `None` inside `GUILD_CREATE`.
447    #[serde(skip_serializing_if = "Option::is_none")]
448    pub guild_id: Option<GuildId>,
449    /// The thread's name.
450    pub name: CompactString,
451    /// The channel the thread was created in.
452    pub parent_id: Option<ChannelId>,
453    /// Who created the thread.
454    #[serde(skip_serializing_if = "Option::is_none")]
455    pub owner_id: Option<UserId>,
456    /// Whether the thread is age-restricted (inherited from the parent).
457    pub nsfw: bool,
458    /// The last message sent (it may not exist any more).
459    pub last_message_id: Option<MessageId>,
460    /// Slowmode, in seconds.
461    pub rate_limit_per_user: u16,
462    /// When the last message was pinned.
463    #[serde(skip_serializing_if = "Option::is_none")]
464    pub last_pin_timestamp: Option<Timestamp>,
465    /// The number of messages, not counting the starter message and deleted messages.
466    #[serde(skip_serializing_if = "Option::is_none")]
467    pub message_count: Option<u32>,
468    /// The approximate number of members; stops counting at 50.
469    #[serde(skip_serializing_if = "Option::is_none")]
470    pub member_count: Option<u32>,
471    /// The number of messages ever sent; unlike `message_count` it does not go down when
472    /// messages are deleted.
473    #[serde(skip_serializing_if = "Option::is_none")]
474    pub total_message_sent: Option<u32>,
475    /// Thread-specific data.
476    pub thread_metadata: ThreadMetadata,
477    /// The current user's membership, when they joined the thread (only in some endpoints).
478    #[serde(skip_serializing_if = "Option::is_none")]
479    pub member: Option<Box<ThreadMember>>,
480    /// The tags applied to a forum or media post.
481    #[serde(skip_serializing_if = "Vec::is_empty")]
482    pub applied_tags: Vec<TagId>,
483    /// The thread's flags.
484    pub flags: ChannelFlags,
485}
486
487/// A direct message between the current user and one other user.
488///
489/// discord.js counterpart: `DMChannel`.
490#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
491#[non_exhaustive]
492pub struct DmChannel {
493    /// The channel's ID.
494    pub id: ChannelId,
495    /// The last message sent (it may not exist any more).
496    pub last_message_id: Option<MessageId>,
497    /// The other user(s) of the DM.
498    pub recipients: Vec<User>,
499    /// When the last message was pinned.
500    #[serde(skip_serializing_if = "Option::is_none")]
501    pub last_pin_timestamp: Option<Timestamp>,
502    /// The channel's flags.
503    pub flags: ChannelFlags,
504}
505
506/// A direct message between several users.
507///
508/// discord.js counterpart: `PartialGroupDMChannel`.
509#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
510#[non_exhaustive]
511pub struct GroupDmChannel {
512    /// The channel's ID.
513    pub id: ChannelId,
514    /// The group's name.
515    pub name: Option<CompactString>,
516    /// The [group icon hash](https://docs.discord.com/developers/reference#image-formatting).
517    pub icon: Option<ImageHash>,
518    /// The users in the group.
519    pub recipients: Vec<User>,
520    /// Who created the group.
521    pub owner_id: UserId,
522    /// The application that created the group, if any.
523    #[serde(skip_serializing_if = "Option::is_none")]
524    pub application_id: Option<ApplicationId>,
525    /// Whether an application manages the group through the `gdm.join` scope.
526    pub managed: bool,
527    /// The last message sent (it may not exist any more).
528    pub last_message_id: Option<MessageId>,
529    /// When the last message was pinned.
530    #[serde(skip_serializing_if = "Option::is_none")]
531    pub last_pin_timestamp: Option<Timestamp>,
532    /// The channel's flags.
533    pub flags: ChannelFlags,
534}
535
536/// The directory channel of a Student Hub.
537///
538/// discord.js counterpart: `DirectoryChannel`.
539#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
540#[non_exhaustive]
541pub struct DirectoryChannel {
542    /// The channel's ID.
543    pub id: ChannelId,
544    /// The guild; `None` inside `GUILD_CREATE`.
545    #[serde(skip_serializing_if = "Option::is_none")]
546    pub guild_id: Option<GuildId>,
547    /// The channel's name.
548    pub name: CompactString,
549    /// The sorting position.
550    pub position: i32,
551    /// Explicit permissions for roles and members.
552    pub permission_overwrites: Vec<Overwrite>,
553    /// The parent category.
554    pub parent_id: Option<ChannelId>,
555    /// The channel's flags.
556    pub flags: ChannelFlags,
557}
558
559/// A channel of a [`ChannelType`] this version of the library does not know about. Only the
560/// fields every channel has are kept.
561///
562/// discord.js counterpart: none (a channel type unknown to this version, kept as received).
563#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
564#[non_exhaustive]
565pub struct UnknownChannel {
566    /// The channel's ID.
567    pub id: ChannelId,
568    /// The raw channel type.
569    #[serde(skip)]
570    pub kind: ChannelType,
571    /// The guild, if any.
572    #[serde(skip_serializing_if = "Option::is_none")]
573    pub guild_id: Option<GuildId>,
574    /// The channel's name, if any.
575    #[serde(skip_serializing_if = "Option::is_none")]
576    pub name: Option<CompactString>,
577    /// The parent channel, if any.
578    #[serde(skip_serializing_if = "Option::is_none")]
579    pub parent_id: Option<ChannelId>,
580    /// The channel's flags.
581    pub flags: ChannelFlags,
582}
583
584/// Every field of every kind of channel; decoded in one pass and then converted into the
585/// [`Channel`] variant selected by `type` (D-057).
586#[derive(Deserialize)]
587struct RawChannel {
588    id: ChannelId,
589    #[serde(rename = "type")]
590    kind: ChannelType,
591    #[serde(default)]
592    guild_id: Option<GuildId>,
593    #[serde(default)]
594    position: Option<i32>,
595    #[serde(default)]
596    permission_overwrites: Vec<Overwrite>,
597    #[serde(default)]
598    name: Option<CompactString>,
599    #[serde(default)]
600    topic: Option<CompactString>,
601    #[serde(default)]
602    nsfw: bool,
603    #[serde(default)]
604    last_message_id: Option<MessageId>,
605    #[serde(default)]
606    bitrate: Option<u32>,
607    #[serde(default)]
608    user_limit: Option<u32>,
609    #[serde(default)]
610    rate_limit_per_user: Option<u16>,
611    #[serde(default)]
612    recipients: Vec<User>,
613    #[serde(default)]
614    icon: Option<ImageHash>,
615    #[serde(default)]
616    owner_id: Option<UserId>,
617    #[serde(default)]
618    application_id: Option<ApplicationId>,
619    #[serde(default)]
620    managed: bool,
621    #[serde(default)]
622    parent_id: Option<ChannelId>,
623    #[serde(default)]
624    last_pin_timestamp: Option<Timestamp>,
625    #[serde(default)]
626    rtc_region: Option<CompactString>,
627    #[serde(default)]
628    video_quality_mode: Option<VideoQualityMode>,
629    #[serde(default)]
630    message_count: Option<u32>,
631    #[serde(default)]
632    member_count: Option<u32>,
633    #[serde(default)]
634    thread_metadata: Option<ThreadMetadata>,
635    #[serde(default)]
636    member: Option<Box<ThreadMember>>,
637    #[serde(default)]
638    default_auto_archive_duration: Option<AutoArchiveDuration>,
639    #[serde(default)]
640    flags: ChannelFlags,
641    #[serde(default)]
642    total_message_sent: Option<u32>,
643    #[serde(default)]
644    available_tags: Vec<ForumTag>,
645    #[serde(default)]
646    applied_tags: Vec<TagId>,
647    #[serde(default)]
648    default_reaction_emoji: Option<DefaultReaction>,
649    #[serde(default)]
650    default_thread_rate_limit_per_user: Option<u16>,
651    #[serde(default)]
652    default_sort_order: Option<SortOrderType>,
653    #[serde(default)]
654    default_forum_layout: Option<ForumLayoutType>,
655}
656
657impl RawChannel {
658    fn name<E: DeError>(&mut self) -> Result<CompactString, E> {
659        self.name.take().ok_or_else(|| E::missing_field("name"))
660    }
661
662    fn into_channel<E: DeError>(mut self) -> Result<Channel, E> {
663        Ok(match self.kind {
664            ChannelType::GuildText => Channel::Text(self.text()?),
665            ChannelType::GuildAnnouncement => Channel::Announcement(self.text()?),
666            ChannelType::GuildVoice => Channel::Voice(self.voice()?),
667            ChannelType::GuildStageVoice => Channel::Stage(self.voice()?),
668            ChannelType::GuildForum => Channel::Forum(self.forum()?),
669            ChannelType::GuildMedia => Channel::Media(self.forum()?),
670            ChannelType::AnnouncementThread => Channel::AnnouncementThread(self.thread()?),
671            ChannelType::PublicThread => Channel::PublicThread(self.thread()?),
672            ChannelType::PrivateThread => Channel::PrivateThread(self.thread()?),
673            ChannelType::GuildCategory => Channel::Category(CategoryChannel {
674                id: self.id,
675                guild_id: self.guild_id,
676                name: self.name()?,
677                position: self.position.unwrap_or_default(),
678                permission_overwrites: self.permission_overwrites,
679                nsfw: self.nsfw,
680                flags: self.flags,
681            }),
682            ChannelType::Dm => Channel::Dm(DmChannel {
683                id: self.id,
684                last_message_id: self.last_message_id,
685                recipients: self.recipients,
686                last_pin_timestamp: self.last_pin_timestamp,
687                flags: self.flags,
688            }),
689            ChannelType::GroupDm => Channel::GroupDm(GroupDmChannel {
690                id: self.id,
691                name: self.name,
692                icon: self.icon,
693                recipients: self.recipients,
694                owner_id: self.owner_id.ok_or_else(|| E::missing_field("owner_id"))?,
695                application_id: self.application_id,
696                managed: self.managed,
697                last_message_id: self.last_message_id,
698                last_pin_timestamp: self.last_pin_timestamp,
699                flags: self.flags,
700            }),
701            ChannelType::GuildDirectory => Channel::Directory(DirectoryChannel {
702                id: self.id,
703                guild_id: self.guild_id,
704                name: self.name()?,
705                position: self.position.unwrap_or_default(),
706                permission_overwrites: self.permission_overwrites,
707                parent_id: self.parent_id,
708                flags: self.flags,
709            }),
710            ChannelType::Unknown(_) => Channel::Unknown(UnknownChannel {
711                id: self.id,
712                kind: self.kind,
713                guild_id: self.guild_id,
714                name: self.name,
715                parent_id: self.parent_id,
716                flags: self.flags,
717            }),
718        })
719    }
720
721    fn text<E: DeError>(mut self) -> Result<TextChannel, E> {
722        Ok(TextChannel {
723            id: self.id,
724            guild_id: self.guild_id,
725            name: self.name()?,
726            position: self.position.unwrap_or_default(),
727            permission_overwrites: self.permission_overwrites,
728            parent_id: self.parent_id,
729            nsfw: self.nsfw,
730            topic: self.topic,
731            last_message_id: self.last_message_id,
732            rate_limit_per_user: self.rate_limit_per_user.unwrap_or_default(),
733            last_pin_timestamp: self.last_pin_timestamp,
734            default_auto_archive_duration: self.default_auto_archive_duration,
735            default_thread_rate_limit_per_user: self.default_thread_rate_limit_per_user,
736            flags: self.flags,
737        })
738    }
739
740    fn voice<E: DeError>(mut self) -> Result<VoiceChannel, E> {
741        Ok(VoiceChannel {
742            id: self.id,
743            guild_id: self.guild_id,
744            name: self.name()?,
745            position: self.position.unwrap_or_default(),
746            permission_overwrites: self.permission_overwrites,
747            parent_id: self.parent_id,
748            nsfw: self.nsfw,
749            topic: self.topic,
750            last_message_id: self.last_message_id,
751            rate_limit_per_user: self.rate_limit_per_user.unwrap_or_default(),
752            bitrate: self.bitrate.unwrap_or_default(),
753            user_limit: self.user_limit.unwrap_or_default(),
754            rtc_region: self.rtc_region,
755            video_quality_mode: self.video_quality_mode.unwrap_or_default(),
756            flags: self.flags,
757        })
758    }
759
760    fn forum<E: DeError>(mut self) -> Result<ForumChannel, E> {
761        Ok(ForumChannel {
762            id: self.id,
763            guild_id: self.guild_id,
764            name: self.name()?,
765            position: self.position.unwrap_or_default(),
766            permission_overwrites: self.permission_overwrites,
767            parent_id: self.parent_id,
768            nsfw: self.nsfw,
769            topic: self.topic,
770            last_message_id: self.last_message_id,
771            rate_limit_per_user: self.rate_limit_per_user.unwrap_or_default(),
772            default_auto_archive_duration: self.default_auto_archive_duration,
773            available_tags: self.available_tags,
774            default_thread_rate_limit_per_user: self.default_thread_rate_limit_per_user,
775            default_reaction_emoji: self.default_reaction_emoji,
776            default_sort_order: self.default_sort_order,
777            default_forum_layout: self.default_forum_layout.unwrap_or_default(),
778            flags: self.flags,
779        })
780    }
781
782    fn thread<E: DeError>(mut self) -> Result<ThreadChannel, E> {
783        Ok(ThreadChannel {
784            id: self.id,
785            guild_id: self.guild_id,
786            name: self.name()?,
787            parent_id: self.parent_id,
788            owner_id: self.owner_id,
789            nsfw: self.nsfw,
790            last_message_id: self.last_message_id,
791            rate_limit_per_user: self.rate_limit_per_user.unwrap_or_default(),
792            last_pin_timestamp: self.last_pin_timestamp,
793            message_count: self.message_count,
794            member_count: self.member_count,
795            total_message_sent: self.total_message_sent,
796            thread_metadata: self
797                .thread_metadata
798                .ok_or_else(|| E::missing_field("thread_metadata"))?,
799            member: self.member,
800            applied_tags: self.applied_tags,
801            flags: self.flags,
802        })
803    }
804}
805
806impl<'de> Deserialize<'de> for Channel {
807    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
808        RawChannel::deserialize(deserializer)?.into_channel()
809    }
810}
811
812/// Serializes a variant's struct together with its `type`.
813#[derive(Serialize)]
814struct Tagged<'a, T> {
815    #[serde(rename = "type")]
816    kind: ChannelType,
817    #[serde(flatten)]
818    channel: &'a T,
819}
820
821impl Serialize for Channel {
822    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
823        let kind = self.kind();
824        match self {
825            Self::Text(channel) | Self::Announcement(channel) => {
826                Tagged { kind, channel }.serialize(serializer)
827            }
828            Self::Dm(channel) => Tagged { kind, channel }.serialize(serializer),
829            Self::Voice(channel) | Self::Stage(channel) => {
830                Tagged { kind, channel }.serialize(serializer)
831            }
832            Self::GroupDm(channel) => Tagged { kind, channel }.serialize(serializer),
833            Self::Category(channel) => Tagged { kind, channel }.serialize(serializer),
834            Self::AnnouncementThread(channel)
835            | Self::PublicThread(channel)
836            | Self::PrivateThread(channel) => Tagged { kind, channel }.serialize(serializer),
837            Self::Directory(channel) => Tagged { kind, channel }.serialize(serializer),
838            Self::Forum(channel) | Self::Media(channel) => {
839                Tagged { kind, channel }.serialize(serializer)
840            }
841            Self::Unknown(channel) => Tagged { kind, channel }.serialize(serializer),
842        }
843    }
844}
845
846/// A [permission overwrite](https://docs.discord.com/developers/resources/channel#overwrite-object):
847/// permissions explicitly allowed or denied for a role or member in a channel.
848///
849/// discord.js counterpart: `PermissionOverwrites`.
850#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
851#[non_exhaustive]
852#[doc(alias = "PermissionOverwrite")]
853pub struct Overwrite {
854    /// The role or user ID, depending on [`kind`](Self::kind).
855    pub id: GenericId,
856    /// Whether the overwrite is for a role or a member.
857    #[serde(rename = "type")]
858    pub kind: OverwriteType,
859    /// The permissions explicitly allowed.
860    pub allow: Permissions,
861    /// The permissions explicitly denied.
862    pub deny: Permissions,
863}
864
865impl Overwrite {
866    /// An overwrite of `kind` for the role or user `id`.
867    ///
868    /// discord.js counterpart: `OverwriteData`.
869    #[must_use]
870    pub const fn new(
871        id: GenericId,
872        kind: OverwriteType,
873        allow: Permissions,
874        deny: Permissions,
875    ) -> Self {
876        Self {
877            id,
878            kind,
879            allow,
880            deny,
881        }
882    }
883
884    /// An overwrite for a role (`@everyone` has the guild's ID).
885    ///
886    /// discord.js counterpart: `OverwriteData` with `type: OverwriteType.Role`.
887    ///
888    /// # Examples
889    ///
890    /// ```
891    /// use djs_model::{channel::Overwrite, id::RoleId, permissions::Permissions};
892    ///
893    /// let read_only = Overwrite::role(RoleId::new(1), Permissions::VIEW_CHANNEL, Permissions::SEND_MESSAGES);
894    /// assert_eq!(read_only.role_id(), Some(RoleId::new(1)));
895    /// ```
896    #[must_use]
897    pub const fn role(role_id: RoleId, allow: Permissions, deny: Permissions) -> Self {
898        Self::new(role_id.cast(), OverwriteType::Role, allow, deny)
899    }
900
901    /// An overwrite for a member.
902    ///
903    /// discord.js counterpart: `OverwriteData` with `type: OverwriteType.Member`.
904    #[must_use]
905    pub const fn member(user_id: UserId, allow: Permissions, deny: Permissions) -> Self {
906        Self::new(user_id.cast(), OverwriteType::Member, allow, deny)
907    }
908
909    /// The role this overwrite applies to, if it is a role overwrite.
910    ///
911    /// discord.js counterpart: `PermissionOverwrites#id` of a role overwrite.
912    #[must_use]
913    pub fn role_id(&self) -> Option<RoleId> {
914        (self.kind == OverwriteType::Role).then(|| self.id.cast())
915    }
916
917    /// The member this overwrite applies to, if it is a member overwrite.
918    ///
919    /// discord.js counterpart: `PermissionOverwrites#id` of a member overwrite.
920    #[must_use]
921    pub fn user_id(&self) -> Option<UserId> {
922        (self.kind == OverwriteType::Member).then(|| self.id.cast())
923    }
924}
925
926int_enum! {
927    /// Whether an [`Overwrite`] is for a role or a member.
928    ///
929    /// discord.js counterpart: `OverwriteType`.
930    pub enum OverwriteType: u8 {
931        /// A role overwrite.
932        Role = 0,
933        /// A member overwrite.
934        Member = 1,
935    }
936}
937
938int_enum! {
939    /// The [camera video quality](https://docs.discord.com/developers/resources/channel#channel-object-video-quality-modes)
940    /// of a voice channel.
941    ///
942    /// discord.js counterpart: `VideoQualityMode`.
943    #[derive(Default)]
944    pub enum VideoQualityMode: u8 {
945        /// Discord picks the best quality (the default when absent).
946        #[default]
947        Auto = 1,
948        /// 720p.
949        Full = 2,
950    }
951}
952
953int_enum! {
954    /// How the posts of a forum or media channel are [sorted](https://docs.discord.com/developers/resources/channel#channel-object-sort-order-types).
955    ///
956    /// discord.js counterpart: `SortOrderType`.
957    pub enum SortOrderType: u8 {
958        /// By recent activity.
959        LatestActivity = 0,
960        /// By creation time, newest first.
961        CreationDate = 1,
962    }
963}
964
965int_enum! {
966    /// How the posts of a forum channel are [displayed](https://docs.discord.com/developers/resources/channel#channel-object-forum-layout-types).
967    ///
968    /// discord.js counterpart: `ForumLayoutType`.
969    #[derive(Default)]
970    pub enum ForumLayoutType: u8 {
971        /// No default set (the default when absent).
972        #[default]
973        NotSet = 0,
974        /// A list.
975        ListView = 1,
976        /// A gallery of tiles.
977        GalleryView = 2,
978    }
979}
980
981int_enum! {
982    /// After how many minutes of inactivity a thread is archived (hidden from the channel
983    /// list). Discord only accepts these values.
984    ///
985    /// discord.js counterpart: `ThreadAutoArchiveDuration`.
986    #[doc(alias = "ThreadAutoArchiveDuration")]
987    pub enum AutoArchiveDuration: u16 {
988        /// One hour.
989        OneHour = 60,
990        /// One day.
991        OneDay = 1440,
992        /// Three days.
993        ThreeDays = 4320,
994        /// One week.
995        OneWeek = 10080,
996    }
997}
998
999/// [Thread-specific data](https://docs.discord.com/developers/resources/channel#thread-metadata-object).
1000///
1001/// discord.js counterpart: the thread fields of `ThreadChannel` (`archived`, `locked`, …).
1002#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1003#[non_exhaustive]
1004pub struct ThreadMetadata {
1005    /// Whether the thread is archived.
1006    pub archived: bool,
1007    /// After how long without activity the thread is archived.
1008    pub auto_archive_duration: AutoArchiveDuration,
1009    /// When the archive status last changed (used to compute recent activity).
1010    pub archive_timestamp: Timestamp,
1011    /// Whether the thread is locked: only members with `MANAGE_THREADS` can unarchive it.
1012    pub locked: bool,
1013    /// Whether non-moderators can add other non-moderators (private threads only).
1014    #[serde(default, skip_serializing_if = "core::ops::Not::not")]
1015    pub invitable: bool,
1016    /// When the thread was created; only set for threads created after 2022-01-09.
1017    #[serde(default, skip_serializing_if = "Option::is_none")]
1018    pub create_timestamp: Option<Timestamp>,
1019}
1020
1021/// A [user's membership in a thread](https://docs.discord.com/developers/resources/channel#thread-member-object).
1022///
1023/// discord.js counterpart: `ThreadMember`.
1024#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
1025#[non_exhaustive]
1026pub struct ThreadMember {
1027    /// The thread's ID (omitted inside `GUILD_CREATE`).
1028    #[serde(default, skip_serializing_if = "Option::is_none")]
1029    pub id: Option<ChannelId>,
1030    /// The user's ID (omitted inside `GUILD_CREATE`).
1031    #[serde(default, skip_serializing_if = "Option::is_none")]
1032    pub user_id: Option<UserId>,
1033    /// When the user last joined the thread.
1034    pub join_timestamp: Timestamp,
1035    /// The user's thread settings (notifications).
1036    pub flags: ThreadMemberFlags,
1037    /// The user's guild member data (with `with_member=true`).
1038    #[serde(default, skip_serializing_if = "Option::is_none")]
1039    pub member: Option<Box<Member>>,
1040}
1041
1042int_flags! {
1043    /// The settings of a [`ThreadMember`], currently about notifications.
1044    ///
1045    /// discord.js counterpart: `ThreadMemberFlags`.
1046    pub struct ThreadMemberFlags: u64 {
1047        /// The user has interacted with the thread.
1048        ///
1049        /// **Undocumented:** known from discord-api-types, not in the official docs; may
1050        /// change without notice.
1051        const HAS_INTERACTED = 1 << 0;
1052        /// The user is notified of all messages.
1053        ///
1054        /// **Undocumented:** known from discord-api-types, not in the official docs; may
1055        /// change without notice.
1056        const ALL_MESSAGES = 1 << 1;
1057        /// The user is only notified of mentions.
1058        ///
1059        /// **Undocumented:** known from discord-api-types, not in the official docs; may
1060        /// change without notice.
1061        const ONLY_MENTIONS = 1 << 2;
1062        /// The user is not notified.
1063        ///
1064        /// **Undocumented:** known from discord-api-types, not in the official docs; may
1065        /// change without notice.
1066        const NO_MESSAGES = 1 << 3;
1067    }
1068}
1069
1070/// The [emoji of the add-reaction button](https://docs.discord.com/developers/resources/channel#default-reaction-object)
1071/// on posts of a forum or media channel. Exactly one of the fields is set.
1072///
1073/// discord.js counterpart: `DefaultReactionEmoji`.
1074#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1075#[non_exhaustive]
1076pub struct DefaultReaction {
1077    /// A custom emoji of the guild.
1078    pub emoji_id: Option<EmojiId>,
1079    /// A Unicode emoji.
1080    pub emoji_name: Option<CompactString>,
1081}
1082
1083impl DefaultReaction {
1084    /// A custom emoji of the guild.
1085    ///
1086    /// discord.js counterpart: the `id` of `DefaultReactionEmoji`.
1087    #[must_use]
1088    pub const fn custom(emoji_id: EmojiId) -> Self {
1089        Self {
1090            emoji_id: Some(emoji_id),
1091            emoji_name: None,
1092        }
1093    }
1094
1095    /// A Unicode emoji (e.g. `"👍"`).
1096    ///
1097    /// discord.js counterpart: the `name` of `DefaultReactionEmoji`.
1098    #[must_use]
1099    pub fn unicode(emoji: impl Into<CompactString>) -> Self {
1100        Self {
1101            emoji_id: None,
1102            emoji_name: Some(emoji.into()),
1103        }
1104    }
1105}
1106
1107/// A [tag](https://docs.discord.com/developers/resources/channel#forum-tag-object) that can be
1108/// applied to posts of a forum or media channel.
1109///
1110/// discord.js counterpart: `GuildForumTag`.
1111#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1112#[non_exhaustive]
1113pub struct ForumTag {
1114    /// The tag's ID.
1115    pub id: TagId,
1116    /// The tag's name (0-20 characters).
1117    pub name: CompactString,
1118    /// Whether only members with `MANAGE_THREADS` can add or remove the tag.
1119    pub moderated: bool,
1120    /// The tag's custom emoji.
1121    pub emoji_id: Option<EmojiId>,
1122    /// The tag's Unicode emoji.
1123    pub emoji_name: Option<CompactString>,
1124}
1125
1126/// The result of [following an announcement channel](https://docs.discord.com/developers/resources/channel#followed-channel-object).
1127///
1128/// discord.js counterpart: the return value of `NewsChannel#addFollower`.
1129#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
1130#[non_exhaustive]
1131pub struct FollowedChannel {
1132    /// The followed (source) channel.
1133    pub channel_id: ChannelId,
1134    /// The webhook created in the target channel.
1135    pub webhook_id: WebhookId,
1136}
1137
1138int_flags! {
1139    /// [Flags of a channel](https://docs.discord.com/developers/resources/channel#channel-object-channel-flags).
1140    ///
1141    /// discord.js counterpart: `ChannelFlags` / `ChannelFlagsBitField`.
1142    pub struct ChannelFlags: u64 {
1143        /// The channel was removed from the guild's feed.
1144        ///
1145        /// **Undocumented:** known from discord-api-types, not in the official docs; may
1146        /// change without notice.
1147        const GUILD_FEED_REMOVED = 1 << 0;
1148        /// The thread is pinned to the top of its forum or media channel.
1149        const PINNED = 1 << 1;
1150        /// The channel was removed from the guild's active channels.
1151        ///
1152        /// **Undocumented:** known from discord-api-types, not in the official docs; may
1153        /// change without notice.
1154        const ACTIVE_CHANNELS_REMOVED = 1 << 2;
1155        /// New threads in this forum or media channel must have a tag (`applied_tags`).
1156        const REQUIRE_TAG = 1 << 4;
1157        /// The channel is marked as spam.
1158        ///
1159        /// **Undocumented:** known from discord-api-types, not in the official docs; may
1160        /// change without notice.
1161        const IS_SPAM = 1 << 5;
1162        /// The channel is a guild resource channel (Server Guide).
1163        ///
1164        /// **Undocumented:** known from discord-api-types, not in the official docs; may
1165        /// change without notice.
1166        const IS_GUILD_RESOURCE_CHANNEL = 1 << 7;
1167        /// Clyde AI is enabled in the channel (feature retired by Discord).
1168        ///
1169        /// **Undocumented:** known from discord-api-types, not in the official docs; may
1170        /// change without notice.
1171        const CLYDE_AI = 1 << 8;
1172        /// The channel is scheduled for deletion.
1173        ///
1174        /// **Undocumented:** known from discord-api-types, not in the official docs; may
1175        /// change without notice.
1176        const IS_SCHEDULED_FOR_DELETION = 1 << 9;
1177        /// Media download options are hidden. Media channels only.
1178        const HIDE_MEDIA_DOWNLOAD_OPTIONS = 1 << 15;
1179        /// The channel's metadata is hidden because the current user cannot view the channel.
1180        /// Only set on channels received over the gateway.
1181        const CHANNEL_OBFUSCATED = 1 << 17;
1182        /// A spoiler channel: users must opt in to see its contents. Textual guild channels and
1183        /// voice channels.
1184        const IS_SPOILER_CHANNEL = 1 << 21;
1185    }
1186}