Skip to main content

djs_model/
webhook.rs

1//! [Webhooks](https://docs.discord.com/developers/resources/webhook): post messages to a
2//! channel without a bot user.
3
4use compact_str::CompactString;
5use serde::{Deserialize, Serialize};
6
7use crate::{
8    id::{ApplicationId, ChannelId, GuildId, WebhookId},
9    macros::int_enum,
10    user::User,
11    util::ImageHash,
12};
13
14/// A [webhook](https://docs.discord.com/developers/resources/webhook#webhook-object).
15///
16/// The `Debug` output hides the [`token`](Self::token) (C-011).
17///
18/// discord.js counterpart: `Webhook`.
19#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
20#[non_exhaustive]
21pub struct Webhook {
22    /// The webhook's ID.
23    pub id: WebhookId,
24    /// What kind of webhook this is.
25    #[serde(rename = "type")]
26    pub kind: WebhookType,
27    /// The guild the webhook belongs to.
28    #[serde(default, skip_serializing_if = "Option::is_none")]
29    pub guild_id: Option<GuildId>,
30    /// The channel the webhook posts to.
31    pub channel_id: Option<ChannelId>,
32    /// Who created the webhook (absent when the webhook is fetched with its token).
33    #[serde(default, skip_serializing_if = "Option::is_none")]
34    pub user: Option<Box<User>>,
35    /// The default name of the webhook's messages.
36    pub name: Option<CompactString>,
37    /// The default [avatar hash](https://docs.discord.com/developers/reference#image-formatting).
38    pub avatar: Option<ImageHash>,
39    /// The secret token used to execute the webhook (incoming webhooks only).
40    #[serde(default, skip_serializing_if = "Option::is_none")]
41    pub token: Option<CompactString>,
42    /// The application that created the webhook.
43    pub application_id: Option<ApplicationId>,
44    /// The guild of the followed channel (channel follower webhooks only).
45    #[serde(default, skip_serializing_if = "Option::is_none")]
46    pub source_guild: Option<SourceGuild>,
47    /// The followed channel (channel follower webhooks only).
48    #[serde(default, skip_serializing_if = "Option::is_none")]
49    pub source_channel: Option<SourceChannel>,
50    /// The URL to execute the webhook (from the `webhook.incoming` `OAuth2` flow).
51    #[serde(default, skip_serializing_if = "Option::is_none")]
52    pub url: Option<CompactString>,
53}
54
55impl core::fmt::Debug for Webhook {
56    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
57        f.debug_struct("Webhook")
58            .field("id", &self.id)
59            .field("kind", &self.kind)
60            .field("guild_id", &self.guild_id)
61            .field("channel_id", &self.channel_id)
62            .field("user", &self.user)
63            .field("name", &self.name)
64            .field("avatar", &self.avatar)
65            .field("token", &self.token.as_ref().map(|_| "<redacted>"))
66            .field("application_id", &self.application_id)
67            .field("source_guild", &self.source_guild)
68            .field("source_channel", &self.source_channel)
69            .field("url", &self.url.as_ref().map(|_| "<redacted>"))
70            .finish()
71    }
72}
73
74int_enum! {
75    /// The [kind of a webhook](https://docs.discord.com/developers/resources/webhook#webhook-object-webhook-types).
76    ///
77    /// discord.js counterpart: `WebhookType`.
78    pub enum WebhookType: u8 {
79        /// Posts messages with a generated token.
80        Incoming = 1,
81        /// Internal webhook that posts messages of a followed announcement channel.
82        ChannelFollower = 2,
83        /// Used by interactions.
84        Application = 3,
85    }
86}
87
88/// The guild of the channel a channel follower webhook follows.
89///
90/// discord.js counterpart: `APIWebhookSourceGuild` (discord-api-types).
91#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
92#[non_exhaustive]
93pub struct SourceGuild {
94    /// The guild's ID.
95    pub id: GuildId,
96    /// The guild's name.
97    pub name: CompactString,
98    /// The guild's [icon hash](https://docs.discord.com/developers/reference#image-formatting).
99    pub icon: Option<ImageHash>,
100}
101
102/// The channel a channel follower webhook follows.
103///
104/// discord.js counterpart: `APIWebhookSourceChannel` (discord-api-types).
105#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
106#[non_exhaustive]
107pub struct SourceChannel {
108    /// The channel's ID.
109    pub id: ChannelId,
110    /// The channel's name.
111    pub name: CompactString,
112}
113
114#[cfg(test)]
115mod tests {
116    use super::*;
117
118    #[test]
119    fn token_is_redacted_in_debug() {
120        let webhook: Webhook = serde_json::from_str(
121            r#"{"id":"1","type":1,"channel_id":"2","name":"hook","avatar":null,
122                "token":"secret-token","application_id":null}"#,
123        )
124        .unwrap();
125        let debug = format!("{webhook:?}");
126        assert!(!debug.contains("secret-token"));
127        assert!(debug.contains("<redacted>"));
128        assert_eq!(webhook.kind, WebhookType::Incoming);
129    }
130}