Skip to main content

djs_rs/
webhook.rs

1//! Webhooks without a bot: [`WebhookClient`] (D-238), and the errors of the webhook methods.
2//!
3//! ```no_run
4//! use djs_rs::WebhookClient;
5//!
6//! # async fn run() -> Result<(), Box<dyn std::error::Error>> {
7//! let webhook = WebhookClient::from_url(&std::env::var("WEBHOOK_URL")?)?;
8//! let message = webhook.send("Deployed!").await?;
9//! println!("sent {}", message.id);
10//! # Ok(())
11//! # }
12//! ```
13
14use core::fmt;
15use std::future::Future;
16
17use djs_model::{
18    id::{ChannelId, MessageId, WebhookId},
19    message::Message,
20    rest::{EditWebhookMessage, ExecuteWebhook, ModifyWebhook},
21    webhook::Webhook,
22};
23use djs_rest::{Error, Rest};
24
25/// A webhook used through its ID and token, without a bot token or a gateway connection:
26/// sending messages to a channel from a script, a CI job or a server.
27///
28/// The token is the webhook's password: keep it out of logs and repositories. `Debug`
29/// redacts it.
30///
31/// discord.js counterpart: `WebhookClient`.
32#[derive(Clone)]
33pub struct WebhookClient {
34    rest: Rest,
35    id: WebhookId,
36    token: String,
37}
38
39impl WebhookClient {
40    /// A client for the webhook `id` with its `token`.
41    ///
42    /// discord.js counterpart: `new WebhookClient({ id, token })`.
43    #[must_use]
44    pub fn new(id: WebhookId, token: impl Into<String>) -> Self {
45        Self {
46            rest: Rest::builder().build(),
47            id,
48            token: token.into(),
49        }
50    }
51
52    /// A client for a webhook URL as Discord shows it,
53    /// `https://discord.com/api/webhooks/{id}/{token}` (D-241). The `discordapp.com`, `canary.`
54    /// and `ptb.` hosts and a versioned path (`/api/v10/webhooks/…`) are accepted too; a query
55    /// string is ignored.
56    ///
57    /// discord.js counterpart: `new WebhookClient({ url })`.
58    ///
59    /// # Errors
60    ///
61    /// Returns [`InvalidWebhookUrl`] if `url` is not a Discord webhook URL.
62    ///
63    /// # Examples
64    ///
65    /// ```
66    /// use djs_rs::{WebhookClient, model::id::WebhookId};
67    ///
68    /// let webhook = WebhookClient::from_url("https://discord.com/api/webhooks/123/abc-DEF_9").unwrap();
69    /// assert_eq!(webhook.id(), WebhookId::new(123));
70    /// assert!(WebhookClient::from_url("https://example.com/api/webhooks/123/abc").is_err());
71    /// ```
72    pub fn from_url(url: &str) -> Result<Self, InvalidWebhookUrl> {
73        let (id, token) = parse_url(url).ok_or(InvalidWebhookUrl(()))?;
74        Ok(Self::new(id, token))
75    }
76
77    /// Sends the requests through `rest` instead of a default client, for example one with a
78    /// proxy or another API base. A bot token it holds is not sent: webhook routes are
79    /// authorized by the webhook's token.
80    ///
81    /// discord.js counterpart: the `rest` option of `WebhookClientOptions`.
82    #[must_use]
83    pub fn rest(mut self, rest: Rest) -> Self {
84        self.rest = rest;
85        self
86    }
87
88    /// The webhook's ID.
89    ///
90    /// discord.js counterpart: `WebhookClient#id`.
91    #[must_use]
92    pub const fn id(&self) -> WebhookId {
93        self.id
94    }
95
96    /// Sends a message ([Execute Webhook](djs_rest::Rest::execute_webhook_and_wait), waiting
97    /// for the message); accepts anything that converts into an [`ExecuteWebhook`], such as
98    /// `&str`.
99    ///
100    /// discord.js counterpart: `WebhookClient#send`.
101    ///
102    /// # Errors
103    ///
104    /// Returns the REST error if the request failed.
105    pub fn send(
106        &self,
107        body: impl Into<ExecuteWebhook>,
108    ) -> impl Future<Output = Result<Message, Error>> + Send + '_ {
109        let body = body.into();
110        async move {
111            self.rest
112                .execute_webhook_and_wait(self.id, &self.token, &body)
113                .await
114        }
115    }
116
117    /// A message the webhook sent (`thread` for one in a thread).
118    ///
119    /// discord.js counterpart: `WebhookClient#fetchMessage`.
120    ///
121    /// # Errors
122    ///
123    /// Returns the REST error if the request failed.
124    pub async fn fetch_message(
125        &self,
126        message_id: MessageId,
127        thread: Option<ChannelId>,
128    ) -> Result<Message, Error> {
129        self.rest
130            .get_webhook_message(self.id, &self.token, message_id, thread)
131            .await
132    }
133
134    /// Edits a message the webhook sent.
135    ///
136    /// discord.js counterpart: `WebhookClient#editMessage`.
137    ///
138    /// # Errors
139    ///
140    /// Returns the REST error if the request failed.
141    pub async fn edit_message(
142        &self,
143        message_id: MessageId,
144        body: &EditWebhookMessage,
145    ) -> Result<Message, Error> {
146        self.rest
147            .edit_webhook_message(self.id, &self.token, message_id, body)
148            .await
149    }
150
151    /// Deletes a message the webhook sent (`thread` for one in a thread).
152    ///
153    /// discord.js counterpart: `WebhookClient#deleteMessage`.
154    ///
155    /// # Errors
156    ///
157    /// Returns the REST error if the request failed.
158    pub async fn delete_message(
159        &self,
160        message_id: MessageId,
161        thread: Option<ChannelId>,
162    ) -> Result<(), Error> {
163        self.rest
164            .delete_webhook_message(self.id, &self.token, message_id, thread)
165            .await
166    }
167
168    /// The webhook itself ([Get Webhook with Token](djs_rest::Rest::get_webhook_with_token)).
169    ///
170    /// discord.js counterpart: none (`WebhookClient` cannot fetch its webhook; `Client#fetchWebhook` can).
171    ///
172    /// # Errors
173    ///
174    /// Returns the REST error if the request failed.
175    pub async fn fetch(&self) -> Result<Webhook, Error> {
176        self.rest.get_webhook_with_token(self.id, &self.token).await
177    }
178
179    /// Changes the webhook's name or avatar (not its channel, which needs a bot).
180    ///
181    /// discord.js counterpart: `WebhookClient#edit`.
182    ///
183    /// # Errors
184    ///
185    /// Returns the REST error if the request failed.
186    pub async fn edit(&self, body: &ModifyWebhook) -> Result<Webhook, Error> {
187        self.rest
188            .modify_webhook_with_token(self.id, &self.token, body)
189            .await
190    }
191
192    /// Deletes the webhook; the client is unusable afterwards.
193    ///
194    /// discord.js counterpart: `WebhookClient#delete`.
195    ///
196    /// # Errors
197    ///
198    /// Returns the REST error if the request failed.
199    pub async fn delete(&self) -> Result<(), Error> {
200        self.rest
201            .delete_webhook_with_token(self.id, &self.token)
202            .await
203    }
204}
205
206impl fmt::Debug for WebhookClient {
207    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
208        f.debug_struct("WebhookClient")
209            .field("id", &self.id)
210            .field("token", &"<redacted>")
211            .finish_non_exhaustive()
212    }
213}
214
215/// `https://{canary.|ptb.}discord{app}.com/api{/vN}/webhooks/{id}/{token}`, ignoring a query
216/// string, a fragment and a trailing slash.
217fn parse_url(url: &str) -> Option<(WebhookId, &str)> {
218    let url = url.strip_prefix("https://")?;
219    let url = url.split(['?', '#']).next()?;
220    let (host, path) = url.split_once('/')?;
221    let host = host
222        .strip_prefix("canary.")
223        .or_else(|| host.strip_prefix("ptb."))
224        .unwrap_or(host);
225    if host != "discord.com" && host != "discordapp.com" {
226        return None;
227    }
228    let path = path.strip_prefix("api/")?;
229    let path = match path.split_once('/') {
230        Some((version, rest))
231            if version.len() > 1
232                && version.starts_with('v')
233                && version[1..].bytes().all(|byte| byte.is_ascii_digit()) =>
234        {
235            rest
236        }
237        _ => path,
238    };
239    let path = path.strip_prefix("webhooks/")?;
240    let path = path.strip_suffix('/').unwrap_or(path);
241    let (id, token) = path.split_once('/')?;
242    let id = WebhookId::new_checked(id.parse().ok()?)?;
243    let valid = |byte: u8| byte.is_ascii_alphanumeric() || byte == b'-' || byte == b'_';
244    (!token.is_empty() && token.bytes().all(valid)).then_some((id, token))
245}
246
247/// The URL given to [`WebhookClient::from_url`] is not a Discord webhook URL (D-241).
248///
249/// discord.js counterpart: none (`new WebhookClient({ url })` throws an `Error`).
250#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
251#[error("not a Discord webhook URL (https://discord.com/api/webhooks/{{id}}/{{token}})")]
252pub struct InvalidWebhookUrl(());
253
254/// An error of a webhook method that needs the webhook's token (D-240).
255///
256/// discord.js counterpart: the `WebhookTokenUnavailable` error.
257#[derive(Debug, thiserror::Error)]
258#[non_exhaustive]
259pub enum WebhookError {
260    /// The webhook has no token: channel-follower and application webhooks cannot be used to
261    /// send messages.
262    #[error("the webhook has no token")]
263    MissingToken,
264    /// The REST request failed.
265    #[error("a REST request failed")]
266    Rest(#[from] Error),
267}
268
269#[cfg(test)]
270mod tests {
271    use super::*;
272
273    #[test]
274    fn webhook_urls_are_parsed() {
275        let id = WebhookId::new(123);
276        for url in [
277            "https://discord.com/api/webhooks/123/abc-DEF_9",
278            "https://discord.com/api/webhooks/123/abc-DEF_9/",
279            "https://discordapp.com/api/webhooks/123/abc-DEF_9",
280            "https://canary.discord.com/api/webhooks/123/abc-DEF_9",
281            "https://ptb.discord.com/api/v10/webhooks/123/abc-DEF_9",
282            "https://discord.com/api/webhooks/123/abc-DEF_9?thread_id=5",
283        ] {
284            assert_eq!(parse_url(url), Some((id, "abc-DEF_9")), "{url}");
285        }
286        for url in [
287            "http://discord.com/api/webhooks/123/abc",
288            "https://example.com/api/webhooks/123/abc",
289            "https://discord.com.evil.example/api/webhooks/123/abc",
290            "https://discord.com/webhooks/123/abc",
291            "https://discord.com/api/webhooks/123",
292            "https://discord.com/api/webhooks/123/",
293            "https://discord.com/api/webhooks/0/abc",
294            "https://discord.com/api/webhooks/abc/abc",
295            "https://discord.com/api/webhooks/123/ab%2Fc",
296            "https://discord.com/api/webhooks/123/abc/extra",
297            "https://discord.com/api/vx/webhooks/123/abc",
298            "",
299        ] {
300            assert_eq!(parse_url(url), None, "{url}");
301        }
302    }
303
304    #[test]
305    fn the_token_is_redacted() {
306        let client = WebhookClient::new(WebhookId::new(1), "secret-token-value");
307        let debug = format!("{client:?}");
308        assert!(!debug.contains("secret"), "{debug}");
309    }
310}