Skip to main content

djs_rs/manager/
user.rs

1//! [`UserManager`].
2
3use std::{future::Future, sync::Arc};
4
5use djs_cache::{Backend, CacheView, CachedMessage, CachedUser};
6use djs_model::{
7    channel::Channel,
8    id::UserId,
9    rest::{CreateDm, CreateMessage},
10};
11use djs_rest::Error;
12
13use super::Fetch;
14use crate::Context;
15
16/// The users the bot knows. Returned by [`Context::users`].
17///
18/// discord.js counterpart: `UserManager` (`client.users`).
19#[derive(Debug)]
20pub struct UserManager<'a, B: Backend> {
21    ctx: &'a Context<B>,
22}
23
24impl<B: Backend> Clone for UserManager<'_, B> {
25    fn clone(&self) -> Self {
26        *self
27    }
28}
29
30impl<B: Backend> Copy for UserManager<'_, B> {}
31
32impl<'a, B: Backend> UserManager<'a, B> {
33    pub(crate) const fn new(ctx: &'a Context<B>) -> Self {
34        Self { ctx }
35    }
36
37    /// The cached users, if the client has a cache.
38    ///
39    /// discord.js counterpart: `UserManager#cache`.
40    #[must_use]
41    pub fn cache(self) -> Option<CacheView<'a, UserId, CachedUser, B>> {
42        self.ctx.cache().map(djs_cache::Cache::users)
43    }
44
45    /// A user: the cached one, or [Get User](djs_rest::Rest::get_user), whose result is
46    /// cached.
47    ///
48    /// discord.js counterpart: `UserManager#fetch`.
49    ///
50    /// # Errors
51    ///
52    /// Returns the REST error if Discord was asked and the request failed.
53    pub fn fetch(
54        self,
55        user_id: UserId,
56    ) -> Fetch<Arc<CachedUser>, impl Future<Output = Result<Arc<CachedUser>, Error>> + Send + 'a>
57    {
58        let cached = self.ctx.ops().user(user_id);
59        let ctx = self.ctx;
60        Fetch::new(cached, async move {
61            let user = ctx.rest().get_user(user_id).await?;
62            Ok(ctx.store_user(&user))
63        })
64    }
65
66    /// The DM channel with a user ([Create DM](djs_rest::Rest::create_dm); Discord returns
67    /// the existing one).
68    ///
69    /// discord.js counterpart: `UserManager#createDM`.
70    ///
71    /// # Errors
72    ///
73    /// Returns the REST error if the request failed.
74    pub async fn create_dm(self, user_id: UserId) -> Result<Arc<Channel>, Error> {
75        let channel = self.ctx.rest().create_dm(&CreateDm::new(user_id)).await?;
76        Ok(self.ctx.store_channel(&channel))
77    }
78
79    /// Sends a direct message: opens the DM channel, then sends `body` to it.
80    ///
81    /// discord.js counterpart: `UserManager#send`.
82    ///
83    /// # Errors
84    ///
85    /// Returns the REST error if a request failed (Discord refuses DMs to users who share no
86    /// guild with the bot or closed their DMs).
87    pub fn send(
88        self,
89        user_id: UserId,
90        body: impl Into<CreateMessage>,
91    ) -> impl Future<Output = Result<Arc<CachedMessage>, Error>> + Send + 'a {
92        let body = body.into();
93        async move {
94            let channel = self.create_dm(user_id).await?;
95            self.ctx.messages(channel.id()).send(body).await
96        }
97    }
98}