djs_rs/manager/webhook.rs
1//! [`WebhookManager`].
2
3use std::{future::Future, sync::Arc};
4
5use djs_cache::{Backend, CachedMessage};
6use djs_collection::Collection;
7use djs_model::{
8 id::{ChannelId, GuildId, MessageId, WebhookId},
9 rest::{CreateWebhook, EditWebhookMessage, ExecuteWebhook, ModifyWebhook},
10 webhook::Webhook,
11};
12use djs_rest::Error;
13
14use super::Fetch;
15use crate::Context;
16
17/// Webhooks, by ID (D-237). Returned by [`Context::webhooks`].
18///
19/// The cache does not keep webhooks, so the [`djs-model`](djs_model) [`Webhook`] is returned;
20/// the messages a webhook sends are cached like the bot's own. The methods taking a
21/// `token` use the webhook's token instead of the bot's (and work for webhooks of other
22/// applications); the others need `MANAGE_WEBHOOKS`. For a webhook without a bot, see
23/// [`WebhookClient`](crate::webhook::WebhookClient).
24///
25/// discord.js counterpart: `TextChannel#createWebhook` / `#fetchWebhooks`,
26/// `Guild#fetchWebhooks`, `Client#fetchWebhook` and the `Webhook` methods.
27#[derive(Debug)]
28pub struct WebhookManager<'a, B: Backend> {
29 ctx: &'a Context<B>,
30}
31
32impl<B: Backend> Clone for WebhookManager<'_, B> {
33 fn clone(&self) -> Self {
34 *self
35 }
36}
37
38impl<B: Backend> Copy for WebhookManager<'_, B> {}
39
40impl<'a, B: Backend> WebhookManager<'a, B> {
41 pub(crate) const fn new(ctx: &'a Context<B>) -> Self {
42 Self { ctx }
43 }
44
45 /// A webhook ([Get Webhook](djs_rest::Rest::get_webhook)).
46 ///
47 /// discord.js counterpart: `Client#fetchWebhook(id)`.
48 ///
49 /// # Errors
50 ///
51 /// Returns the REST error if the request failed.
52 pub fn fetch(
53 self,
54 webhook_id: WebhookId,
55 ) -> Fetch<Webhook, impl Future<Output = Result<Webhook, Error>> + Send + 'a> {
56 let ctx = self.ctx;
57 Fetch::new(
58 None,
59 async move { ctx.rest().get_webhook(webhook_id).await },
60 )
61 }
62
63 /// A webhook, authorized by its token ([Get Webhook with
64 /// Token](djs_rest::Rest::get_webhook_with_token)).
65 ///
66 /// discord.js counterpart: `Client#fetchWebhook(id, token)`.
67 ///
68 /// # Errors
69 ///
70 /// Returns the REST error if the request failed.
71 pub async fn fetch_with_token(
72 self,
73 webhook_id: WebhookId,
74 token: &str,
75 ) -> Result<Webhook, Error> {
76 self.ctx
77 .rest()
78 .get_webhook_with_token(webhook_id, token)
79 .await
80 }
81
82 /// Creates a webhook in a channel ([Create Webhook](djs_rest::Rest::create_webhook)).
83 ///
84 /// discord.js counterpart: `TextChannel#createWebhook`.
85 ///
86 /// # Errors
87 ///
88 /// Returns the REST error if the request failed.
89 pub async fn create(
90 self,
91 channel_id: ChannelId,
92 body: &CreateWebhook,
93 reason: Option<&str>,
94 ) -> Result<Webhook, Error> {
95 self.ctx
96 .rest()
97 .create_webhook(channel_id, body, reason)
98 .await
99 }
100
101 /// The webhooks of a channel ([Get Channel
102 /// Webhooks](djs_rest::Rest::get_channel_webhooks)).
103 ///
104 /// discord.js counterpart: `TextChannel#fetchWebhooks`.
105 ///
106 /// # Errors
107 ///
108 /// Returns the REST error if the request failed.
109 pub async fn list_channel(
110 self,
111 channel_id: ChannelId,
112 ) -> Result<Collection<WebhookId, Webhook>, Error> {
113 let webhooks = self.ctx.rest().get_channel_webhooks(channel_id).await?;
114 Ok(by_id(webhooks))
115 }
116
117 /// The webhooks of a guild ([Get Guild Webhooks](djs_rest::Rest::get_guild_webhooks)).
118 ///
119 /// discord.js counterpart: `Guild#fetchWebhooks`.
120 ///
121 /// # Errors
122 ///
123 /// Returns the REST error if the request failed.
124 pub async fn list_guild(
125 self,
126 guild_id: GuildId,
127 ) -> Result<Collection<WebhookId, Webhook>, Error> {
128 let webhooks = self.ctx.rest().get_guild_webhooks(guild_id).await?;
129 Ok(by_id(webhooks))
130 }
131
132 /// Edits a webhook: its name, avatar or channel ([Modify
133 /// Webhook](djs_rest::Rest::modify_webhook)).
134 ///
135 /// discord.js counterpart: `Webhook#edit`.
136 ///
137 /// # Errors
138 ///
139 /// Returns the REST error if the request failed.
140 pub async fn edit(
141 self,
142 webhook_id: WebhookId,
143 body: &ModifyWebhook,
144 reason: Option<&str>,
145 ) -> Result<Webhook, Error> {
146 self.ctx
147 .rest()
148 .modify_webhook(webhook_id, body, reason)
149 .await
150 }
151
152 /// Deletes a webhook ([Delete Webhook](djs_rest::Rest::delete_webhook)).
153 ///
154 /// discord.js counterpart: `Webhook#delete`.
155 ///
156 /// # Errors
157 ///
158 /// Returns the REST error if the request failed.
159 pub async fn delete(self, webhook_id: WebhookId, reason: Option<&str>) -> Result<(), Error> {
160 self.ctx.rest().delete_webhook(webhook_id, reason).await
161 }
162
163 /// Sends a message through a webhook ([Execute Webhook](djs_rest::Rest::execute_webhook_and_wait),
164 /// waiting for the message); accepts anything that converts into an [`ExecuteWebhook`],
165 /// such as `&str`. The message is cached.
166 ///
167 /// discord.js counterpart: `Webhook#send`.
168 ///
169 /// # Errors
170 ///
171 /// Returns the REST error if the request failed.
172 pub fn send<'t>(
173 self,
174 webhook_id: WebhookId,
175 token: &'t str,
176 body: impl Into<ExecuteWebhook>,
177 ) -> impl Future<Output = Result<Arc<CachedMessage>, Error>> + Send + 't
178 where
179 'a: 't,
180 {
181 let body = body.into();
182 let ctx = self.ctx;
183 async move {
184 let message = ctx
185 .rest()
186 .execute_webhook_and_wait(webhook_id, token, &body)
187 .await?;
188 Ok(ctx.store_message(&message))
189 }
190 }
191
192 /// A message the webhook sent ([Get Webhook Message](djs_rest::Rest::get_webhook_message);
193 /// `thread` for one in a thread); it is cached.
194 ///
195 /// discord.js counterpart: `Webhook#fetchMessage`.
196 ///
197 /// # Errors
198 ///
199 /// Returns the REST error if the request failed.
200 pub async fn fetch_message(
201 self,
202 webhook_id: WebhookId,
203 token: &str,
204 message_id: MessageId,
205 thread: Option<ChannelId>,
206 ) -> Result<Arc<CachedMessage>, Error> {
207 let message = self
208 .ctx
209 .rest()
210 .get_webhook_message(webhook_id, token, message_id, thread)
211 .await?;
212 Ok(self.ctx.store_message(&message))
213 }
214
215 /// Edits a message the webhook sent ([Edit Webhook
216 /// Message](djs_rest::Rest::edit_webhook_message)); the result is cached.
217 ///
218 /// discord.js counterpart: `Webhook#editMessage`.
219 ///
220 /// # Errors
221 ///
222 /// Returns the REST error if the request failed.
223 pub async fn edit_message(
224 self,
225 webhook_id: WebhookId,
226 token: &str,
227 message_id: MessageId,
228 body: &EditWebhookMessage,
229 ) -> Result<Arc<CachedMessage>, Error> {
230 let message = self
231 .ctx
232 .rest()
233 .edit_webhook_message(webhook_id, token, message_id, body)
234 .await?;
235 Ok(self.ctx.store_message(&message))
236 }
237
238 /// Deletes a message the webhook sent ([Delete Webhook
239 /// Message](djs_rest::Rest::delete_webhook_message); `thread` for one in a thread).
240 ///
241 /// discord.js counterpart: `Webhook#deleteMessage`.
242 ///
243 /// # Errors
244 ///
245 /// Returns the REST error if the request failed.
246 pub async fn delete_message(
247 self,
248 webhook_id: WebhookId,
249 token: &str,
250 message_id: MessageId,
251 thread: Option<ChannelId>,
252 ) -> Result<(), Error> {
253 self.ctx
254 .rest()
255 .delete_webhook_message(webhook_id, token, message_id, thread)
256 .await
257 }
258}
259
260fn by_id(webhooks: Vec<Webhook>) -> Collection<WebhookId, Webhook> {
261 webhooks
262 .into_iter()
263 .map(|webhook| (webhook.id, webhook))
264 .collect()
265}