djs_rs/manager/guild.rs
1//! [`GuildManager`].
2
3use std::{future::Future, sync::Arc, time::Duration};
4
5use djs_cache::{Backend, CacheView, CachedGuild};
6use djs_collection::Collection;
7use djs_model::{
8 audit_log::AuditLog,
9 guild::Integration,
10 id::{GuildId, IntegrationId},
11 rest::{GetGuild, GetGuildAuditLog, ModifyGuild},
12};
13use djs_rest::Error;
14
15use super::Fetch;
16#[cfg(feature = "gateway")]
17use super::{GatewayRequestError, GuildSoundboardSounds};
18use crate::Context;
19
20/// The guilds of the bot. Returned by [`Context::guilds`].
21///
22/// discord.js counterpart: `GuildManager` (`client.guilds`).
23#[derive(Debug)]
24pub struct GuildManager<'a, B: Backend> {
25 ctx: &'a Context<B>,
26}
27
28impl<B: Backend> Clone for GuildManager<'_, B> {
29 fn clone(&self) -> Self {
30 *self
31 }
32}
33
34impl<B: Backend> Copy for GuildManager<'_, B> {}
35
36impl<'a, B: Backend> GuildManager<'a, B> {
37 pub(crate) const fn new(ctx: &'a Context<B>) -> Self {
38 Self { ctx }
39 }
40
41 /// The cached guilds, if the client has a cache.
42 ///
43 /// discord.js counterpart: `GuildManager#cache`.
44 #[must_use]
45 pub fn cache(self) -> Option<CacheView<'a, GuildId, CachedGuild, B>> {
46 self.ctx.cache().map(djs_cache::Cache::guilds)
47 }
48
49 #[cfg(feature = "gateway")]
50 #[cfg_attr(docsrs, doc(cfg(feature = "gateway")))]
51 /// The soundboard sounds of `guild_ids`, through the gateway (D-265): sends [Request
52 /// Soundboard Sounds](djs_model::gateway::payload::RequestSoundboardSounds) on the shards
53 /// of the guilds and waits up to `time` for every guild's answer (discord.js waits 10
54 /// seconds). The sounds are cached. A single guild's sounds can also be listed over REST
55 /// ([`SoundboardSoundManager::list`](super::SoundboardSoundManager::list)).
56 ///
57 /// discord.js counterpart: `GuildManager#fetchSoundboardSounds`.
58 ///
59 /// # Errors
60 ///
61 /// [`GatewayRequestError`] if a guild's shard does not run here, the request could not
62 /// be sent, or not every guild answered in time.
63 pub async fn fetch_soundboard_sounds(
64 self,
65 guild_ids: impl IntoIterator<Item = GuildId>,
66 time: Duration,
67 ) -> Result<GuildSoundboardSounds, GatewayRequestError> {
68 super::gateway::fetch_soundboard_sounds(
69 self.ctx.core(),
70 guild_ids.into_iter().collect(),
71 time,
72 )
73 .await
74 }
75
76 /// A guild: the cached one, or [Get Guild](djs_rest::Rest::get_guild) (with the
77 /// approximate member and presence counts), whose result is cached.
78 ///
79 /// discord.js counterpart: `GuildManager#fetch(id)`.
80 ///
81 /// # Errors
82 ///
83 /// Returns the REST error if Discord was asked and the request failed (for example, the
84 /// bot is not in the guild).
85 pub fn fetch(
86 self,
87 guild_id: GuildId,
88 ) -> Fetch<Arc<CachedGuild>, impl Future<Output = Result<Arc<CachedGuild>, Error>> + Send + 'a>
89 {
90 let cached = self.ctx.ops().guild(guild_id);
91 let ctx = self.ctx;
92 Fetch::new(cached, async move {
93 let mut query = GetGuild::default();
94 query.with_counts = Some(true);
95 let guild = ctx.rest().get_guild(guild_id, &query).await?;
96 Ok(ctx.store_guild(&guild))
97 })
98 }
99 /// Edits a guild's settings ([Modify Guild](djs_rest::Rest::modify_guild)); the result is
100 /// cached.
101 ///
102 /// discord.js counterpart: `GuildManager#edit` / `Guild#edit`.
103 ///
104 /// # Errors
105 ///
106 /// Returns the REST error if the request failed (it needs `MANAGE_GUILD`).
107 pub async fn edit(
108 self,
109 guild_id: GuildId,
110 body: &ModifyGuild,
111 reason: Option<&str>,
112 ) -> Result<Arc<CachedGuild>, Error> {
113 let guild = self.ctx.rest().modify_guild(guild_id, body, reason).await?;
114 Ok(self.ctx.store_guild(&guild))
115 }
116
117 /// Makes the bot leave a guild ([Leave Guild](djs_rest::Rest::leave_guild)). The cache is
118 /// updated by the `GUILD_DELETE` event that follows (D-236).
119 ///
120 /// discord.js counterpart: `Guild#leave`.
121 ///
122 /// # Errors
123 ///
124 /// Returns the REST error if the request failed (an owner cannot leave its guild).
125 pub async fn leave(self, guild_id: GuildId) -> Result<(), Error> {
126 self.ctx.rest().leave_guild(guild_id).await
127 }
128 /// A page of the guild's audit log, newest first ([Get Guild Audit
129 /// Log](djs_rest::Rest::get_guild_audit_log)), with the users, webhooks, threads, … its
130 /// entries mention.
131 ///
132 /// discord.js counterpart: `Guild#fetchAuditLogs`.
133 ///
134 /// # Errors
135 ///
136 /// Returns the REST error if the request failed (it needs `VIEW_AUDIT_LOG`).
137 pub async fn audit_log(
138 self,
139 guild_id: GuildId,
140 query: &GetGuildAuditLog,
141 ) -> Result<AuditLog, Error> {
142 self.ctx.rest().get_guild_audit_log(guild_id, query).await
143 }
144
145 /// The guild's integrations: bots, Twitch, YouTube, … ([Get Guild
146 /// Integrations](djs_rest::Rest::get_guild_integrations)).
147 ///
148 /// discord.js counterpart: `Guild#fetchIntegrations`.
149 ///
150 /// # Errors
151 ///
152 /// Returns the REST error if the request failed (it needs `MANAGE_GUILD`).
153 pub async fn integrations(
154 self,
155 guild_id: GuildId,
156 ) -> Result<Collection<IntegrationId, Integration>, Error> {
157 let integrations = self.ctx.rest().get_guild_integrations(guild_id).await?;
158 Ok(integrations
159 .into_iter()
160 .map(|integration| (integration.id, integration))
161 .collect())
162 }
163
164 /// Removes an integration, kicking its bot if it has one ([Delete Guild
165 /// Integration](djs_rest::Rest::delete_guild_integration)).
166 ///
167 /// discord.js counterpart: `Integration#delete`.
168 ///
169 /// # Errors
170 ///
171 /// Returns the REST error if the request failed (it needs `MANAGE_GUILD`).
172 pub async fn delete_integration(
173 self,
174 guild_id: GuildId,
175 integration_id: IntegrationId,
176 reason: Option<&str>,
177 ) -> Result<(), Error> {
178 self.ctx
179 .rest()
180 .delete_guild_integration(guild_id, integration_id, reason)
181 .await
182 }
183}