Skip to main content

djs_rest/endpoints/
webhook.rs

1//! [Webhook endpoints](https://docs.discord.com/developers/resources/webhook): creating and
2//! managing webhooks, executing them, and their messages.
3//!
4//! Routes with the webhook's token in the path need no bot token and are sent without it
5//! (D-121), so a client built without a token can use them. Execute Slack-Compatible and
6//! GitHub-Compatible Webhook are not modelled (D-120).
7
8use djs_model::{
9    id::{ChannelId, GuildId, MessageId, WebhookId},
10    message::Message,
11    rest::{CreateWebhook, EditWebhookMessage, ExecuteWebhook, ModifyWebhook},
12    webhook::Webhook,
13};
14
15use crate::client::boxed;
16use crate::{
17    Error, Request, Rest, Route,
18    query::{Query, QueryWriter},
19};
20
21/// The query parameters of the webhook message endpoints (D-119), also used by the
22/// interaction endpoints that edit webhook messages.
23#[derive(Clone, Copy, Debug, Default)]
24pub(crate) struct WebhookQuery {
25    /// Execute Webhook only: whether to wait for and return the message.
26    pub(crate) wait: Option<bool>,
27    pub(crate) thread_id: Option<ChannelId>,
28    pub(crate) with_components: Option<bool>,
29}
30
31impl WebhookQuery {
32    /// The query fields of an edit body.
33    pub(crate) const fn of_edit(body: &EditWebhookMessage) -> Self {
34        Self {
35            wait: None,
36            thread_id: body.thread_id,
37            with_components: body.with_components,
38        }
39    }
40
41    /// The query fields of an execute body.
42    const fn of_execute(body: &ExecuteWebhook, wait: bool) -> Self {
43        Self {
44            wait: if wait { Some(true) } else { None },
45            thread_id: body.thread_id,
46            with_components: body.with_components,
47        }
48    }
49
50    /// Only a thread.
51    const fn thread(thread_id: Option<ChannelId>) -> Self {
52        Self {
53            wait: None,
54            thread_id,
55            with_components: None,
56        }
57    }
58}
59
60impl Query for WebhookQuery {
61    fn write(&self, query: &mut QueryWriter<'_>) {
62        query.optional("wait", self.wait.as_ref());
63        query.optional("thread_id", self.thread_id.as_ref());
64        query.optional("with_components", self.with_components.as_ref());
65    }
66}
67
68/// Managing webhooks.
69impl Rest {
70    /// [Create Webhook](https://docs.discord.com/developers/resources/webhook#create-webhook):
71    /// creates a webhook in a channel; its [`token`](Webhook::token) is in the response.
72    /// Needs `MANAGE_WEBHOOKS`.
73    ///
74    /// `reason` is shown in the audit log (D-086).
75    ///
76    /// discord.js counterpart: `TextChannel#createWebhook`.
77    ///
78    /// # Errors
79    ///
80    /// See [`Rest::request`]; `30007` at the maximum number of webhooks (15), `50035` for an
81    /// invalid name.
82    pub fn create_webhook<'a>(
83        &'a self,
84        channel_id: ChannelId,
85        body: &'a CreateWebhook,
86        reason: Option<&'a str>,
87    ) -> impl Future<Output = Result<Webhook, Error>> + Send + 'a {
88        boxed(async move {
89            self.call(
90                Request::new(Route::CreateWebhook { channel_id })
91                    .json(body)?
92                    .reason(reason),
93            )
94            .await
95        })
96    }
97
98    /// [Get Channel Webhooks](https://docs.discord.com/developers/resources/webhook#get-channel-webhooks):
99    /// returns the webhooks of a channel. Needs `MANAGE_WEBHOOKS`.
100    ///
101    /// discord.js counterpart: `TextChannel#fetchWebhooks`.
102    ///
103    /// # Errors
104    ///
105    /// See [`Rest::request`].
106    pub fn get_channel_webhooks(
107        &self,
108        channel_id: ChannelId,
109    ) -> impl Future<Output = Result<Vec<Webhook>, Error>> + Send + '_ {
110        boxed(async move {
111            self.call(Request::new(Route::GetChannelWebhooks { channel_id }))
112                .await
113        })
114    }
115
116    /// [Get Guild Webhooks](https://docs.discord.com/developers/resources/webhook#get-guild-webhooks):
117    /// returns the webhooks of a guild. Needs `MANAGE_WEBHOOKS`.
118    ///
119    /// discord.js counterpart: `Guild#fetchWebhooks`.
120    ///
121    /// # Errors
122    ///
123    /// See [`Rest::request`].
124    pub fn get_guild_webhooks(
125        &self,
126        guild_id: GuildId,
127    ) -> impl Future<Output = Result<Vec<Webhook>, Error>> + Send + '_ {
128        boxed(async move {
129            self.call(Request::new(Route::GetGuildWebhooks { guild_id }))
130                .await
131        })
132    }
133
134    /// [Get Webhook](https://docs.discord.com/developers/resources/webhook#get-webhook):
135    /// returns a webhook. Needs `MANAGE_WEBHOOKS`, unless the application owns the webhook.
136    ///
137    /// discord.js counterpart: `Client#fetchWebhook(id)`.
138    ///
139    /// # Errors
140    ///
141    /// See [`Rest::request`]; `10015` Unknown Webhook.
142    pub fn get_webhook(
143        &self,
144        webhook_id: WebhookId,
145    ) -> impl Future<Output = Result<Webhook, Error>> + Send + '_ {
146        boxed(async move {
147            self.call(Request::new(Route::GetWebhook { webhook_id }))
148                .await
149        })
150    }
151
152    /// [Get Webhook with Token](https://docs.discord.com/developers/resources/webhook#get-webhook-with-token):
153    /// returns a webhook (without its [`user`](Webhook::user)), authenticated by its token.
154    ///
155    /// discord.js counterpart: `Client#fetchWebhook(id, token)`.
156    ///
157    /// # Errors
158    ///
159    /// See [`Rest::request`]; `50027` Invalid Webhook Token.
160    pub fn get_webhook_with_token<'a>(
161        &'a self,
162        webhook_id: WebhookId,
163        webhook_token: &'a str,
164    ) -> impl Future<Output = Result<Webhook, Error>> + Send + 'a {
165        boxed(async move {
166            self.call(Request::new(Route::GetWebhookWithToken {
167                webhook_id,
168                webhook_token,
169            }))
170            .await
171        })
172    }
173
174    /// [Modify Webhook](https://docs.discord.com/developers/resources/webhook#modify-webhook):
175    /// changes a webhook's default name or avatar, or moves it to another channel. Needs
176    /// `MANAGE_WEBHOOKS`.
177    ///
178    /// `reason` is shown in the audit log (D-086).
179    ///
180    /// discord.js counterpart: `Webhook#edit`.
181    ///
182    /// # Errors
183    ///
184    /// See [`Rest::request`].
185    pub fn modify_webhook<'a>(
186        &'a self,
187        webhook_id: WebhookId,
188        body: &'a ModifyWebhook,
189        reason: Option<&'a str>,
190    ) -> impl Future<Output = Result<Webhook, Error>> + Send + 'a {
191        boxed(async move {
192            self.call(
193                Request::new(Route::ModifyWebhook { webhook_id })
194                    .json(body)?
195                    .reason(reason),
196            )
197            .await
198        })
199    }
200
201    /// [Modify Webhook with Token](https://docs.discord.com/developers/resources/webhook#modify-webhook-with-token):
202    /// like [`modify_webhook`](Self::modify_webhook), authenticated by the token; the
203    /// [`channel_id`](ModifyWebhook::channel_id) cannot be changed.
204    ///
205    /// discord.js counterpart: `WebhookClient#edit`.
206    ///
207    /// # Errors
208    ///
209    /// See [`Rest::request`].
210    pub fn modify_webhook_with_token<'a>(
211        &'a self,
212        webhook_id: WebhookId,
213        webhook_token: &'a str,
214        body: &'a ModifyWebhook,
215    ) -> impl Future<Output = Result<Webhook, Error>> + Send + 'a {
216        boxed(async move {
217            self.call(
218                Request::new(Route::ModifyWebhookWithToken {
219                    webhook_id,
220                    webhook_token,
221                })
222                .json(body)?,
223            )
224            .await
225        })
226    }
227
228    /// [Delete Webhook](https://docs.discord.com/developers/resources/webhook#delete-webhook):
229    /// deletes a webhook for good. Needs `MANAGE_WEBHOOKS`.
230    ///
231    /// `reason` is shown in the audit log (D-086).
232    ///
233    /// discord.js counterpart: `Webhook#delete`.
234    ///
235    /// # Errors
236    ///
237    /// See [`Rest::request`]; `10015` Unknown Webhook.
238    pub fn delete_webhook<'a>(
239        &'a self,
240        webhook_id: WebhookId,
241        reason: Option<&'a str>,
242    ) -> impl Future<Output = Result<(), Error>> + Send + 'a {
243        boxed(async move {
244            self.call(Request::new(Route::DeleteWebhook { webhook_id }).reason(reason))
245                .await
246        })
247    }
248
249    /// [Delete Webhook with Token](https://docs.discord.com/developers/resources/webhook#delete-webhook-with-token):
250    /// deletes a webhook, authenticated by its token.
251    ///
252    /// discord.js counterpart: `WebhookClient#delete`.
253    ///
254    /// # Errors
255    ///
256    /// See [`Rest::request`].
257    pub fn delete_webhook_with_token<'a>(
258        &'a self,
259        webhook_id: WebhookId,
260        webhook_token: &'a str,
261    ) -> impl Future<Output = Result<(), Error>> + Send + 'a {
262        boxed(async move {
263            self.call(Request::new(Route::DeleteWebhookWithToken {
264                webhook_id,
265                webhook_token,
266            }))
267            .await
268        })
269    }
270}
271
272/// Executing webhooks and their messages.
273impl Rest {
274    /// [Execute Webhook](https://docs.discord.com/developers/resources/webhook#execute-webhook):
275    /// sends a message through a webhook without waiting for it to be saved. Files of the
276    /// body are uploaded with it.
277    ///
278    /// To get the created message (and errors of messages that could not be saved), use
279    /// [`execute_webhook_and_wait`](Self::execute_webhook_and_wait) (D-119, like D-106).
280    ///
281    /// discord.js counterpart: `WebhookClient#send` / `Webhook#send`.
282    ///
283    /// # Examples
284    ///
285    /// ```no_run
286    /// # async fn example(webhook_id: djs_model::id::WebhookId, token: &str) -> Result<(), djs_rest::Error> {
287    /// use djs_model::rest::ExecuteWebhook;
288    /// use djs_rest::Rest;
289    ///
290    /// // Webhook routes need no bot token (D-121).
291    /// let rest = Rest::builder().build();
292    /// let body = ExecuteWebhook::from("Deploy finished").username("CI");
293    /// rest.execute_webhook(webhook_id, token, &body).await?;
294    /// # Ok(())
295    /// # }
296    /// ```
297    ///
298    /// # Errors
299    ///
300    /// See [`Rest::request`]; `50027` Invalid Webhook Token.
301    pub fn execute_webhook<'a>(
302        &'a self,
303        webhook_id: WebhookId,
304        webhook_token: &'a str,
305        body: &'a ExecuteWebhook,
306    ) -> impl Future<Output = Result<(), Error>> + Send + 'a {
307        boxed(async move {
308            let query = WebhookQuery::of_execute(body, false);
309            self.request_ignoring_body(
310                Request::new(Route::ExecuteWebhook {
311                    webhook_id,
312                    webhook_token,
313                })
314                .query(&query)
315                .json(body)?
316                .files(&body.files),
317            )
318            .await
319        })
320    }
321
322    /// [Execute Webhook](https://docs.discord.com/developers/resources/webhook#execute-webhook)
323    /// with `wait=true`: sends a message through a webhook and returns it once saved.
324    ///
325    /// discord.js counterpart: `WebhookClient#send` (which always waits).
326    ///
327    /// # Errors
328    ///
329    /// See [`Rest::request`]; `50006` for an empty message, `50027` Invalid Webhook Token.
330    pub fn execute_webhook_and_wait<'a>(
331        &'a self,
332        webhook_id: WebhookId,
333        webhook_token: &'a str,
334        body: &'a ExecuteWebhook,
335    ) -> impl Future<Output = Result<Message, Error>> + Send + 'a {
336        boxed(async move {
337            let query = WebhookQuery::of_execute(body, true);
338            self.call(
339                Request::new(Route::ExecuteWebhook {
340                    webhook_id,
341                    webhook_token,
342                })
343                .query(&query)
344                .json(body)?
345                .files(&body.files),
346            )
347            .await
348        })
349    }
350
351    /// [Get Webhook Message](https://docs.discord.com/developers/resources/webhook#get-webhook-message):
352    /// returns a message the webhook sent (`thread_id`: the thread it is in).
353    ///
354    /// discord.js counterpart: `WebhookClient#fetchMessage`.
355    ///
356    /// # Errors
357    ///
358    /// See [`Rest::request`]; `10008` Unknown Message.
359    pub fn get_webhook_message<'a>(
360        &'a self,
361        webhook_id: WebhookId,
362        webhook_token: &'a str,
363        message_id: MessageId,
364        thread_id: Option<ChannelId>,
365    ) -> impl Future<Output = Result<Message, Error>> + Send + 'a {
366        boxed(async move {
367            let query = WebhookQuery::thread(thread_id);
368            self.call(
369                Request::new(Route::GetWebhookMessage {
370                    webhook_id,
371                    webhook_token,
372                    message_id,
373                })
374                .query(&query),
375            )
376            .await
377        })
378    }
379
380    /// [Edit Webhook Message](https://docs.discord.com/developers/resources/webhook#edit-webhook-message):
381    /// edits a message the webhook sent; new files are uploaded and added to the kept
382    /// attachments.
383    ///
384    /// discord.js counterpart: `WebhookClient#editMessage`.
385    ///
386    /// # Errors
387    ///
388    /// See [`Rest::request`]; `10008` Unknown Message.
389    pub fn edit_webhook_message<'a>(
390        &'a self,
391        webhook_id: WebhookId,
392        webhook_token: &'a str,
393        message_id: MessageId,
394        body: &'a EditWebhookMessage,
395    ) -> impl Future<Output = Result<Message, Error>> + Send + 'a {
396        boxed(async move {
397            let query = WebhookQuery::of_edit(body);
398            self.call(
399                Request::new(Route::EditWebhookMessage {
400                    webhook_id,
401                    webhook_token,
402                    message_id,
403                })
404                .query(&query)
405                .json(body)?
406                .files(&body.files),
407            )
408            .await
409        })
410    }
411
412    /// [Delete Webhook Message](https://docs.discord.com/developers/resources/webhook#delete-webhook-message):
413    /// deletes a message the webhook sent (`thread_id`: the thread it is in).
414    ///
415    /// discord.js counterpart: `WebhookClient#deleteMessage`.
416    ///
417    /// # Errors
418    ///
419    /// See [`Rest::request`]; `10008` Unknown Message.
420    pub fn delete_webhook_message<'a>(
421        &'a self,
422        webhook_id: WebhookId,
423        webhook_token: &'a str,
424        message_id: MessageId,
425        thread_id: Option<ChannelId>,
426    ) -> impl Future<Output = Result<(), Error>> + Send + 'a {
427        boxed(async move {
428            let query = WebhookQuery::thread(thread_id);
429            self.call(
430                Request::new(Route::DeleteWebhookMessage {
431                    webhook_id,
432                    webhook_token,
433                    message_id,
434                })
435                .query(&query),
436            )
437            .await
438        })
439    }
440}