Skip to main content

djs_rs/manager/
channel.rs

1//! [`ChannelManager`].
2
3use std::{future::Future, sync::Arc};
4
5use djs_cache::{Backend, CacheView};
6use djs_model::{
7    channel::{Channel, OverwriteType},
8    id::{ChannelId, GenericId, RoleId, UserId},
9    permissions::Permissions,
10    rest::{EditChannelPermissions, ModifyGuildChannel, ModifyThread, SendSoundboardSound},
11};
12use djs_rest::Error;
13
14use super::Fetch;
15use crate::Context;
16
17/// The channels the bot can see, by ID. Returned by [`Context::channels`].
18///
19/// Messages are sent through [`Context::messages`]; a guild's channels are created, listed
20/// and reordered through [`Context::guild_channels`] (D-234).
21///
22/// discord.js counterpart: `ChannelManager` (`client.channels`).
23#[derive(Debug)]
24pub struct ChannelManager<'a, B: Backend> {
25    ctx: &'a Context<B>,
26}
27
28impl<B: Backend> Clone for ChannelManager<'_, B> {
29    fn clone(&self) -> Self {
30        *self
31    }
32}
33
34impl<B: Backend> Copy for ChannelManager<'_, B> {}
35
36impl<'a, B: Backend> ChannelManager<'a, B> {
37    pub(crate) const fn new(ctx: &'a Context<B>) -> Self {
38        Self { ctx }
39    }
40
41    /// The cached guild and DM channels (threads are cached per guild,
42    /// [`Cache::threads`](djs_cache::Cache::threads)), if the client has a cache.
43    ///
44    /// discord.js counterpart: `ChannelManager#cache`.
45    #[must_use]
46    pub fn cache(self) -> Option<CacheView<'a, ChannelId, Channel, B>> {
47        self.ctx.cache().map(djs_cache::Cache::channels)
48    }
49
50    /// A channel or thread: the cached channel, or [Get
51    /// Channel](djs_rest::Rest::get_channel), whose result is cached (a thread among the
52    /// guild's threads).
53    ///
54    /// discord.js counterpart: `ChannelManager#fetch`.
55    ///
56    /// # Errors
57    ///
58    /// Returns the REST error if Discord was asked and the request failed.
59    pub fn fetch(
60        self,
61        channel_id: ChannelId,
62    ) -> Fetch<Arc<Channel>, impl Future<Output = Result<Arc<Channel>, Error>> + Send + 'a> {
63        let cached = self.ctx.ops().channel(channel_id);
64        let ctx = self.ctx;
65        Fetch::new(cached, async move {
66            let channel = ctx.rest().get_channel(channel_id).await?;
67            Ok(ctx.store_channel(&channel))
68        })
69    }
70
71    /// Shows the bot as typing in a channel for about 10 seconds, or until it sends a message.
72    ///
73    /// discord.js counterpart: `TextChannel#sendTyping`.
74    ///
75    /// # Errors
76    ///
77    /// Returns the REST error if the request failed.
78    pub async fn send_typing(self, channel_id: ChannelId) -> Result<(), Error> {
79        self.ctx.rest().trigger_typing_indicator(channel_id).await
80    }
81    /// Edits a guild channel ([Modify Channel](djs_rest::Rest::modify_channel)); the result
82    /// is cached.
83    ///
84    /// discord.js counterpart: `GuildChannelManager#edit` / `GuildChannel#edit`.
85    ///
86    /// # Errors
87    ///
88    /// Returns the REST error if the request failed (it needs `MANAGE_CHANNELS`).
89    pub async fn edit(
90        self,
91        channel_id: ChannelId,
92        body: &ModifyGuildChannel,
93        reason: Option<&str>,
94    ) -> Result<Arc<Channel>, Error> {
95        let channel = self
96            .ctx
97            .rest()
98            .modify_channel(channel_id, body, reason)
99            .await?;
100        Ok(self.ctx.store_channel(&channel))
101    }
102
103    /// Edits a thread ([Modify Thread](djs_rest::Rest::modify_thread)): its name, archiving,
104    /// locking, slowmode, tags; the result is cached.
105    ///
106    /// discord.js counterpart: `ThreadChannel#edit`.
107    ///
108    /// # Errors
109    ///
110    /// Returns the REST error if the request failed.
111    pub async fn edit_thread(
112        self,
113        thread_id: ChannelId,
114        body: &ModifyThread,
115        reason: Option<&str>,
116    ) -> Result<Arc<Channel>, Error> {
117        let thread = self
118            .ctx
119            .rest()
120            .modify_thread(thread_id, body, reason)
121            .await?;
122        Ok(self.ctx.store_channel(&thread))
123    }
124
125    /// Deletes a channel, or closes a DM ([Delete Channel](djs_rest::Rest::delete_channel)),
126    /// returning what Discord sent back. The cache is updated by the `CHANNEL_DELETE` event
127    /// that follows, whose handlers get the channel as it was (D-236).
128    ///
129    /// discord.js counterpart: `GuildChannelManager#delete` / `GuildChannel#delete`.
130    ///
131    /// # Errors
132    ///
133    /// Returns the REST error if the request failed (it needs `MANAGE_CHANNELS`, or
134    /// `MANAGE_THREADS` for a thread).
135    pub async fn delete(
136        self,
137        channel_id: ChannelId,
138        reason: Option<&str>,
139    ) -> Result<Channel, Error> {
140        self.ctx.rest().delete_channel(channel_id, reason).await
141    }
142
143    /// Plays a soundboard sound in the voice channel the bot is connected to ([Send
144    /// Soundboard Sound](djs_rest::Rest::send_soundboard_sound)).
145    ///
146    /// discord.js counterpart: `VoiceChannel#sendSoundboardSound`.
147    ///
148    /// # Errors
149    ///
150    /// Returns the REST error if the request failed (it needs `SPEAK` and
151    /// `USE_SOUNDBOARD`, and the bot must not be muted or deafened).
152    pub async fn send_soundboard_sound(
153        self,
154        channel_id: ChannelId,
155        body: &SendSoundboardSound,
156    ) -> Result<(), Error> {
157        self.ctx
158            .rest()
159            .send_soundboard_sound(channel_id, body)
160            .await
161    }
162
163    /// Sets a channel's permission overwrite for a role or a member (D-235): `allow` and
164    /// `deny` replace the whole overwrite, as Discord does ([Edit Channel
165    /// Permissions](djs_rest::Rest::edit_channel_permissions)).
166    ///
167    /// The target is a [`RoleId`] or a [`UserId`] (the `@everyone` role has the guild's ID:
168    /// `guild_id.cast()`).
169    ///
170    /// discord.js counterpart: `PermissionOverwriteManager#create`.
171    ///
172    /// # Errors
173    ///
174    /// Returns the REST error if the request failed (it needs `MANAGE_ROLES`).
175    pub fn set_permissions(
176        self,
177        channel_id: ChannelId,
178        target: impl Into<OverwriteTarget>,
179        allow: Permissions,
180        deny: Permissions,
181        reason: Option<&str>,
182    ) -> impl Future<Output = Result<(), Error>> + Send {
183        let (id, kind) = target.into().parts();
184        let mut body = EditChannelPermissions::new(kind);
185        body.allow = Some(allow);
186        body.deny = Some(deny);
187        let ctx = self.ctx;
188        async move {
189            ctx.rest()
190                .edit_channel_permissions(channel_id, id, &body, reason)
191                .await
192        }
193    }
194
195    /// Removes a channel's permission overwrite for a role or a member ([Delete Channel
196    /// Permission](djs_rest::Rest::delete_channel_permission)).
197    ///
198    /// discord.js counterpart: `PermissionOverwriteManager#delete`.
199    ///
200    /// # Errors
201    ///
202    /// Returns the REST error if the request failed (it needs `MANAGE_ROLES`).
203    pub fn delete_permissions(
204        self,
205        channel_id: ChannelId,
206        target: impl Into<OverwriteTarget>,
207        reason: Option<&str>,
208    ) -> impl Future<Output = Result<(), Error>> + Send {
209        let (id, _) = target.into().parts();
210        let ctx = self.ctx;
211        async move {
212            ctx.rest()
213                .delete_channel_permission(channel_id, id, reason)
214                .await
215        }
216    }
217}
218
219/// Whose permissions a channel overwrite changes (D-235): built from a [`RoleId`] or a
220/// [`UserId`].
221///
222/// discord.js counterpart: the `UserResolvable | RoleResolvable` of
223/// `PermissionOverwriteManager`.
224#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
225pub enum OverwriteTarget {
226    /// A role (the guild's ID for `@everyone`).
227    Role(RoleId),
228    /// A member.
229    Member(UserId),
230}
231
232impl OverwriteTarget {
233    const fn parts(self) -> (GenericId, OverwriteType) {
234        match self {
235            Self::Role(id) => (id.cast(), OverwriteType::Role),
236            Self::Member(id) => (id.cast(), OverwriteType::Member),
237        }
238    }
239}
240
241impl From<RoleId> for OverwriteTarget {
242    fn from(id: RoleId) -> Self {
243        Self::Role(id)
244    }
245}
246
247impl From<UserId> for OverwriteTarget {
248    fn from(id: UserId) -> Self {
249        Self::Member(id)
250    }
251}