Skip to main content

djs_rs/manager/
mod.rs

1//! Managers: the operations of one resource, reached from the [`Context`] (D-229).
2//!
3//! ```no_run
4//! # use djs_rs::prelude::*;
5//! # use djs_rs::model::id::{GuildId, UserId};
6//! # async fn run(ctx: Context, guild: GuildId, user: UserId) -> Result<(), djs_rs::rest::Error> {
7//! // The cache first, then the REST API; the REST result is cached (D-230).
8//! let member = ctx.members(guild).fetch(user).await?;
9//! println!("{} joined at {:?}", member.user.username, member.joined_at);
10//!
11//! // Always ask Discord.
12//! let fresh = ctx.members(guild).fetch(user).force().await?;
13//!
14//! // Lists are `Collection`s in Discord's order (D-231).
15//! let roles = ctx.roles(guild).list().await?;
16//! let hoisted = roles.filter(|role, _| role.hoist);
17//! # let _ = (fresh, hoisted);
18//! # Ok(())
19//! # }
20//! ```
21//!
22//! # What managers return
23//!
24//! The type the cache stores (D-233): `Arc<CachedMember>`, `Arc<CachedMessage>`,
25//! `Arc<CachedGuild>`, `Arc<CachedUser>` for the compact cached types, `Arc<Channel>` and
26//! `Arc<Role>` where the cache keeps the model type — whether the value came from the cache or
27//! from Discord. A REST result is converted to that type and stored when its resource is
28//! enabled in the [`CacheConfig`](djs_cache::CacheConfig); without a cache it is only
29//! converted. Objects the cache never keeps (bans) are returned as their
30//! [`djs-model`](djs_model) type.
31//!
32//! Managers are small `Copy` values borrowing the context; their methods consume them, so
33//! `ctx.members(guild).kick(user, None).await` needs no binding.
34//!
35//! discord.js counterpart: the `*Manager` classes (`GuildMemberManager`, `MessageManager`, …).
36
37mod application_emoji;
38mod auto_moderation;
39mod ban;
40mod channel;
41mod command;
42mod emoji;
43#[cfg(feature = "gateway")]
44mod gateway;
45mod guild;
46mod guild_channel;
47mod invite;
48mod member;
49mod message;
50mod role;
51mod scheduled_event;
52mod soundboard;
53mod stage_instance;
54mod sticker;
55mod thread;
56mod user;
57mod webhook;
58
59use core::{
60    fmt,
61    future::{Future, IntoFuture},
62    pin::Pin,
63    task::{Context as TaskContext, Poll},
64};
65use std::sync::Arc;
66
67use djs_cache::{Backend, CachedGuild, CachedMember, CachedMessage, CachedUser};
68use djs_collection::Collection;
69use djs_model::{
70    channel::Channel,
71    emoji::Emoji,
72    guild::{Guild, Member, Role},
73    guild_scheduled_event::GuildScheduledEvent,
74    id::{ChannelId, GuildId, SoundboardSoundId, StickerId, StickerPackId},
75    message::Message,
76    soundboard::SoundboardSound,
77    stage_instance::StageInstance,
78    sticker::{Sticker, StickerPack},
79    user::User,
80};
81use djs_rest::Error;
82
83pub use self::{
84    application_emoji::ApplicationEmojiManager,
85    auto_moderation::AutoModerationRuleManager,
86    ban::BanManager,
87    channel::{ChannelManager, OverwriteTarget},
88    command::{CommandManager, GuildCommandManager},
89    emoji::EmojiManager,
90    guild::GuildManager,
91    guild_channel::GuildChannelManager,
92    invite::InviteManager,
93    member::MemberManager,
94    message::MessageManager,
95    role::RoleManager,
96    scheduled_event::ScheduledEventManager,
97    soundboard::SoundboardSoundManager,
98    stage_instance::StageInstanceManager,
99    sticker::StickerManager,
100    thread::{FetchedThreads, ThreadManager, ThreadMemberManager},
101    user::UserManager,
102    webhook::WebhookManager,
103};
104
105#[cfg(feature = "gateway")]
106#[cfg_attr(docsrs, doc(cfg(feature = "gateway")))]
107pub use self::gateway::{FetchMembers, GatewayRequestError, GuildSoundboardSounds};
108use crate::Context;
109
110/// A `fetch` that is not sent yet: await it to read the cache first and ask Discord when the
111/// cache does not hold the value (D-230), or call [`force`](Self::force) first to always ask
112/// Discord.
113///
114/// A cache hit allocates nothing; the REST request is only made (and boxed) when needed.
115///
116/// discord.js counterpart: the `fetch(id, { force })` methods of the managers.
117#[must_use = "a fetch does nothing until it is awaited"]
118pub struct Fetch<T, F> {
119    cached: Option<T>,
120    rest: F,
121    force: bool,
122}
123
124impl<T, F> Fetch<T, F> {
125    pub(crate) const fn new(cached: Option<T>, rest: F) -> Self {
126        Self {
127            cached,
128            rest,
129            force: false,
130        }
131    }
132
133    /// Skips the cache: the value is always requested from Discord (and the cache updated).
134    ///
135    /// discord.js counterpart: the `force: true` fetch option.
136    pub fn force(mut self) -> Self {
137        self.force = true;
138        self
139    }
140
141    /// Whether the cache holds the value, so awaiting this fetch (without
142    /// [`force`](Self::force)) makes no request.
143    ///
144    /// discord.js counterpart: none (discord.js answers from the cache inside `fetch`).
145    #[must_use]
146    pub const fn is_cached(&self) -> bool {
147        self.cached.is_some()
148    }
149}
150
151impl<T, F> fmt::Debug for Fetch<T, F> {
152    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
153        f.debug_struct("Fetch")
154            .field("cached", &self.cached.is_some())
155            .field("force", &self.force)
156            .finish_non_exhaustive()
157    }
158}
159
160impl<T: Unpin, F: Future<Output = Result<T, Error>>> IntoFuture for Fetch<T, F> {
161    type Output = Result<T, Error>;
162    type IntoFuture = FetchFuture<T, F>;
163
164    fn into_future(self) -> FetchFuture<T, F> {
165        match self.cached {
166            Some(cached) if !self.force => FetchFuture(State::Cached(Some(cached))),
167            _ => FetchFuture(State::Rest(Box::pin(self.rest))),
168        }
169    }
170}
171
172/// The future of an awaited [`Fetch`].
173///
174/// discord.js counterpart: the promise a manager's `fetch` returns.
175#[must_use = "futures do nothing unless polled"]
176pub struct FetchFuture<T, F>(State<T, F>);
177
178enum State<T, F> {
179    Cached(Option<T>),
180    Rest(Pin<Box<F>>),
181}
182
183impl<T, F> fmt::Debug for FetchFuture<T, F> {
184    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
185        let state = match self.0 {
186            State::Cached(_) => "cached",
187            State::Rest(_) => "requesting",
188        };
189        f.debug_tuple("FetchFuture").field(&state).finish()
190    }
191}
192
193impl<T: Unpin, F: Future<Output = Result<T, Error>>> Future for FetchFuture<T, F> {
194    type Output = Result<T, Error>;
195
196    fn poll(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
197        match &mut self.get_mut().0 {
198            State::Cached(cached) => Poll::Ready(Ok(cached
199                .take()
200                .expect("`FetchFuture` polled after completion"))),
201            State::Rest(rest) => rest.as_mut().poll(cx),
202        }
203    }
204}
205
206/// Converts REST objects to the cached types through the context's cache (D-230, D-233),
207/// with the code compiled in djs-rs (D-289).
208impl<B: Backend> Context<B> {
209    pub(crate) fn store_guild(&self, guild: &Guild) -> Arc<CachedGuild> {
210        self.ops().store_guild(guild)
211    }
212
213    pub(crate) fn store_channel(&self, channel: &Channel) -> Arc<Channel> {
214        self.ops().store_channel(channel)
215    }
216
217    pub(crate) fn store_user(&self, user: &User) -> Arc<CachedUser> {
218        self.ops().store_user(user)
219    }
220
221    pub(crate) fn store_member(&self, guild_id: GuildId, member: &Member) -> Arc<CachedMember> {
222        self.ops().store_member(guild_id, member)
223    }
224
225    pub(crate) fn store_message(&self, message: &Message) -> Arc<CachedMessage> {
226        self.ops().store_message(message)
227    }
228
229    pub(crate) fn store_role(&self, guild_id: GuildId, role: &Role) -> Arc<Role> {
230        self.ops().store_role(guild_id, role)
231    }
232
233    pub(crate) fn store_emoji(&self, guild_id: GuildId, emoji: &Emoji) -> Arc<Emoji> {
234        self.ops().store_emoji(guild_id, emoji)
235    }
236
237    pub(crate) fn store_sticker(&self, guild_id: GuildId, sticker: &Sticker) -> Arc<Sticker> {
238        self.ops().store_sticker(guild_id, sticker)
239    }
240
241    pub(crate) fn store_scheduled_event(
242        &self,
243        guild_id: GuildId,
244        event: &GuildScheduledEvent,
245    ) -> Arc<GuildScheduledEvent> {
246        self.ops().store_scheduled_event(guild_id, event)
247    }
248
249    pub(crate) fn store_stage_instance(
250        &self,
251        guild_id: GuildId,
252        stage: &StageInstance,
253    ) -> Arc<StageInstance> {
254        self.ops().store_stage_instance(guild_id, stage)
255    }
256
257    pub(crate) fn store_soundboard_sound(
258        &self,
259        guild_id: GuildId,
260        sound: &SoundboardSound,
261    ) -> Arc<SoundboardSound> {
262        self.ops().store_soundboard_sound(guild_id, sound)
263    }
264
265    /// Returns the guild manager (D-229).
266    ///
267    /// discord.js counterpart: `Client#guilds`.
268    #[must_use]
269    pub const fn guilds(&self) -> GuildManager<'_, B> {
270        GuildManager::new(self)
271    }
272
273    /// Returns the channel manager.
274    ///
275    /// discord.js counterpart: `Client#channels`.
276    #[must_use]
277    pub const fn channels(&self) -> ChannelManager<'_, B> {
278        ChannelManager::new(self)
279    }
280
281    /// Returns the manager of a guild's channels as a whole: create, list, positions (D-234).
282    ///
283    /// discord.js counterpart: `Guild#channels`.
284    #[must_use]
285    pub const fn guild_channels(&self, guild_id: GuildId) -> GuildChannelManager<'_, B> {
286        GuildChannelManager::new(self, guild_id)
287    }
288
289    /// Returns the user manager.
290    ///
291    /// discord.js counterpart: `Client#users`.
292    #[must_use]
293    pub const fn users(&self) -> UserManager<'_, B> {
294        UserManager::new(self)
295    }
296
297    /// Returns the manager of a guild's members.
298    ///
299    /// discord.js counterpart: `Guild#members`.
300    #[must_use]
301    pub const fn members(&self, guild_id: GuildId) -> MemberManager<'_, B> {
302        MemberManager::new(self, guild_id)
303    }
304
305    /// Returns the manager of a channel's messages.
306    ///
307    /// discord.js counterpart: `TextChannel#messages` (and `TextChannel#send`).
308    #[must_use]
309    pub const fn messages(&self, channel_id: ChannelId) -> MessageManager<'_, B> {
310        MessageManager::new(self, channel_id)
311    }
312
313    /// Returns the manager of a guild's roles.
314    ///
315    /// discord.js counterpart: `Guild#roles`.
316    #[must_use]
317    pub const fn roles(&self, guild_id: GuildId) -> RoleManager<'_, B> {
318        RoleManager::new(self, guild_id)
319    }
320
321    /// Returns the manager of a guild's bans.
322    ///
323    /// discord.js counterpart: `Guild#bans`.
324    #[must_use]
325    pub const fn bans(&self, guild_id: GuildId) -> BanManager<'_, B> {
326        BanManager::new(self, guild_id)
327    }
328
329    /// Returns the manager of a guild's custom emojis.
330    ///
331    /// discord.js counterpart: `Guild#emojis`.
332    #[must_use]
333    pub const fn emojis(&self, guild_id: GuildId) -> EmojiManager<'_, B> {
334        EmojiManager::new(self, guild_id)
335    }
336
337    /// Returns the manager of a guild's stickers.
338    ///
339    /// discord.js counterpart: `Guild#stickers`.
340    #[must_use]
341    pub const fn stickers(&self, guild_id: GuildId) -> StickerManager<'_, B> {
342        StickerManager::new(self, guild_id)
343    }
344
345    /// Returns the manager of a guild's scheduled events.
346    ///
347    /// discord.js counterpart: `Guild#scheduledEvents`.
348    #[must_use]
349    pub const fn scheduled_events(&self, guild_id: GuildId) -> ScheduledEventManager<'_, B> {
350        ScheduledEventManager::new(self, guild_id)
351    }
352
353    /// Returns the manager of a guild's live stages.
354    ///
355    /// discord.js counterpart: `Guild#stageInstances`.
356    #[must_use]
357    pub const fn stage_instances(&self, guild_id: GuildId) -> StageInstanceManager<'_, B> {
358        StageInstanceManager::new(self, guild_id)
359    }
360
361    /// Returns the manager of a guild's soundboard sounds.
362    ///
363    /// discord.js counterpart: `Guild#soundboardSounds`.
364    #[must_use]
365    pub const fn soundboard_sounds(&self, guild_id: GuildId) -> SoundboardSoundManager<'_, B> {
366        SoundboardSoundManager::new(self, guild_id)
367    }
368
369    /// Returns the manager of the threads of a parent channel (D-242).
370    ///
371    /// discord.js counterpart: `TextChannel#threads` / `ForumChannel#threads`.
372    #[must_use]
373    pub const fn threads(&self, channel_id: ChannelId) -> ThreadManager<'_, B> {
374        ThreadManager::new(self, channel_id)
375    }
376
377    /// Returns the manager of a thread's members (D-242).
378    ///
379    /// discord.js counterpart: `ThreadChannel#members`.
380    #[must_use]
381    pub const fn thread_members(&self, thread_id: ChannelId) -> ThreadMemberManager<'_, B> {
382        ThreadMemberManager::new(self, thread_id)
383    }
384
385    /// Discord's default soundboard sounds, available in every guild ([List Default
386    /// Soundboard Sounds](djs_rest::Rest::list_default_soundboard_sounds); D-243). They are
387    /// not cached.
388    ///
389    /// discord.js counterpart: `Client#fetchDefaultSoundboardSounds`.
390    ///
391    /// # Errors
392    ///
393    /// Returns the REST error if the request failed.
394    pub async fn default_soundboard_sounds(
395        &self,
396    ) -> Result<Collection<SoundboardSoundId, SoundboardSound>, Error> {
397        let sounds = self.rest().list_default_soundboard_sounds().await?;
398        Ok(sounds
399            .into_iter()
400            .map(|sound| (sound.sound_id, sound))
401            .collect())
402    }
403
404    /// Returns the manager of the bot's global application commands (D-244).
405    ///
406    /// discord.js counterpart: `client.application.commands`.
407    ///
408    /// # Panics
409    ///
410    /// Panics before the first `READY`, while the application ID is unknown (D-247): only in
411    /// `ShardError`, `Invalidated` or `ShardDisconnect` handlers running while logging in.
412    #[must_use]
413    #[track_caller]
414    pub fn commands(&self) -> CommandManager<'_, B> {
415        CommandManager::new(self, self.expect_application_id())
416    }
417
418    /// Returns the manager of the bot's application commands in a guild, and their
419    /// permissions there (D-244).
420    ///
421    /// discord.js counterpart: `Guild#commands`.
422    ///
423    /// # Panics
424    ///
425    /// Panics before the first `READY` (D-247), like [`commands`](Self::commands).
426    #[must_use]
427    #[track_caller]
428    pub fn guild_commands(&self, guild_id: GuildId) -> GuildCommandManager<'_, B> {
429        GuildCommandManager::new(self, self.expect_application_id(), guild_id)
430    }
431
432    /// Returns the manager of the application's own emojis.
433    ///
434    /// discord.js counterpart: `client.application.emojis`.
435    ///
436    /// # Panics
437    ///
438    /// Panics before the first `READY` (D-247), like [`commands`](Self::commands).
439    #[must_use]
440    #[track_caller]
441    pub fn application_emojis(&self) -> ApplicationEmojiManager<'_, B> {
442        ApplicationEmojiManager::new(self, self.expect_application_id())
443    }
444
445    /// Returns the manager of a guild's auto moderation rules.
446    ///
447    /// discord.js counterpart: `Guild#autoModerationRules`.
448    #[must_use]
449    pub const fn auto_moderation_rules(
450        &self,
451        guild_id: GuildId,
452    ) -> AutoModerationRuleManager<'_, B> {
453        AutoModerationRuleManager::new(self, guild_id)
454    }
455
456    /// A sticker by its ID, standard or from a guild ([Get Sticker](djs_rest::Rest::get_sticker)).
457    /// Not cached.
458    ///
459    /// discord.js counterpart: `Client#fetchSticker`.
460    ///
461    /// # Errors
462    ///
463    /// Returns the REST error if the request failed.
464    pub async fn sticker(&self, sticker_id: StickerId) -> Result<Sticker, Error> {
465        self.rest().get_sticker(sticker_id).await
466    }
467
468    /// Discord's standard sticker packs ([List Sticker
469    /// Packs](djs_rest::Rest::list_sticker_packs)). Not cached.
470    ///
471    /// discord.js counterpart: `Client#fetchStickerPacks`.
472    ///
473    /// # Errors
474    ///
475    /// Returns the REST error if the request failed.
476    pub async fn sticker_packs(&self) -> Result<Collection<StickerPackId, StickerPack>, Error> {
477        let packs = self.rest().list_sticker_packs().await?;
478        Ok(packs.into_iter().map(|pack| (pack.id, pack)).collect())
479    }
480
481    /// One standard sticker pack ([Get Sticker Pack](djs_rest::Rest::get_sticker_pack)). Not
482    /// cached.
483    ///
484    /// discord.js counterpart: `Client#fetchStickerPacks({ packId })`.
485    ///
486    /// # Errors
487    ///
488    /// Returns the REST error if the request failed.
489    pub async fn sticker_pack(&self, pack_id: StickerPackId) -> Result<StickerPack, Error> {
490        self.rest().get_sticker_pack(pack_id).await
491    }
492
493    /// Returns the invite manager (D-239).
494    ///
495    /// discord.js counterpart: `Guild#invites` and `Client#fetchInvite`.
496    #[must_use]
497    pub const fn invites(&self) -> InviteManager<'_, B> {
498        InviteManager::new(self)
499    }
500
501    /// Returns the webhook manager (D-237).
502    ///
503    /// discord.js counterpart: the webhook methods of `TextChannel`, `Guild` and `Client`.
504    #[must_use]
505    pub const fn webhooks(&self) -> WebhookManager<'_, B> {
506        WebhookManager::new(self)
507    }
508}