Skip to main content

djs_model/
webhook_event.rs

1//! [Webhook events](https://docs.discord.com/developers/events/webhook-events): events Discord
2//! sends over HTTP to an app's webhook events URL (D-076).
3//!
4//! Each request body is a [`WebhookEventPayload`]: either a `PING` (sent when the URL is
5//! configured) or an [event](WebhookEvent) whose [data](WebhookEventData) depends on its type.
6//! Unlike [gateway events](crate::gateway), webhook events are not realtime and may arrive out
7//! of order. Every request must be verified with its `X-Signature-Ed25519` and
8//! `X-Signature-Timestamp` headers (answer `401` when the signature is invalid) and acknowledged
9//! with `204 No Content` within 3 seconds, otherwise Discord retries it.
10//!
11//! The events are chosen in the app's settings or with the application's
12//! [`event_webhooks_types`](crate::application::Application::event_webhooks_types).
13//!
14//! # Examples
15//!
16//! ```
17//! use djs_model::webhook_event::{PayloadType, WebhookEventData, WebhookEventPayload};
18//!
19//! let body = r#"{
20//!     "version": 1, "application_id": "1234560123453231555", "type": 1,
21//!     "event": {
22//!         "type": "APPLICATION_DEAUTHORIZED", "timestamp": "2024-10-18T14:42:53.064834",
23//!         "data": { "user": { "id": "111178765189277770", "username": "nelly",
24//!                             "discriminator": "0", "global_name": null, "avatar": null } }
25//!     }
26//! }"#;
27//! let payload: WebhookEventPayload = serde_json::from_str(body)?;
28//! assert_eq!(payload.kind, PayloadType::Event);
29//! let event = payload.event.expect("events carry a body");
30//! let WebhookEventData::ApplicationDeauthorized(data) = &event.data else {
31//!     panic!("expected APPLICATION_DEAUTHORIZED");
32//! };
33//! assert_eq!(data.user.username, "nelly");
34//! # Ok::<(), serde_json::Error>(())
35//! ```
36
37use core::fmt;
38
39use compact_str::CompactString;
40use serde::{
41    Deserialize, Deserializer, Serialize, Serializer,
42    de::{Error as DeError, Visitor},
43};
44
45use crate::{
46    application::{IntegrationType, PartialApplication},
47    channel::Channel,
48    component::Component,
49    entitlement::Entitlement,
50    guild::Guild,
51    id::{ApplicationId, ChannelId, GenericId, LobbyId, MessageId},
52    lobby::LobbyMessage,
53    macros::{int_enum, str_enum},
54    message::{Attachment, Embed, MessageActivity, MessageFlags, MessageType},
55    oauth2::Scope,
56    user::User,
57    util::{JsonValue, JsonValueError, Timestamp},
58};
59
60/// The [outer payload](https://docs.discord.com/developers/events/webhook-events#payload-structure)
61/// of a webhook event request.
62///
63/// Answer a [`PayloadType::Ping`] with `204 No Content` (and an empty body) to validate the URL.
64///
65/// discord.js counterpart: `APIWebhookEvent` (discord-api-types).
66#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
67#[non_exhaustive]
68pub struct WebhookEventPayload {
69    /// The payload's version scheme (currently always `1`).
70    pub version: u8,
71    /// Your app's ID.
72    pub application_id: ApplicationId,
73    /// Whether this is a `PING` or an event.
74    #[serde(rename = "type")]
75    pub kind: PayloadType,
76    /// The event (for [`PayloadType::Event`]).
77    #[serde(default, skip_serializing_if = "Option::is_none")]
78    pub event: Option<WebhookEvent>,
79}
80
81int_enum! {
82    /// The [type of a webhook event payload](https://docs.discord.com/developers/events/webhook-events#webhook-types).
83    ///
84    /// discord.js counterpart: `ApplicationWebhookType` (discord-api-types).
85    pub enum PayloadType: u8 {
86        /// Sent to check that the URL is active; answer with `204 No Content`.
87        Ping = 0,
88        /// An event, in [`WebhookEventPayload::event`].
89        Event = 1,
90    }
91}
92
93str_enum! {
94    /// A [webhook event type](https://docs.discord.com/developers/events/webhook-events#event-types)
95    /// an app can subscribe to.
96    ///
97    /// discord.js counterpart: `ApplicationWebhookEventType`.
98    pub enum WebhookEventType {
99        /// The app was authorized by a user or in a guild.
100        ApplicationAuthorized = "APPLICATION_AUTHORIZED",
101        /// The app was deauthorized by a user.
102        ApplicationDeauthorized = "APPLICATION_DEAUTHORIZED",
103        /// An entitlement was created.
104        EntitlementCreate = "ENTITLEMENT_CREATE",
105        /// An entitlement was updated.
106        EntitlementUpdate = "ENTITLEMENT_UPDATE",
107        /// An entitlement was deleted.
108        EntitlementDelete = "ENTITLEMENT_DELETE",
109        /// A user was added to a Quest.
110        QuestUserEnrollment = "QUEST_USER_ENROLLMENT",
111        /// A message was created in a lobby.
112        LobbyMessageCreate = "LOBBY_MESSAGE_CREATE",
113        /// A message was updated in a lobby.
114        LobbyMessageUpdate = "LOBBY_MESSAGE_UPDATE",
115        /// A message was deleted from a lobby.
116        LobbyMessageDelete = "LOBBY_MESSAGE_DELETE",
117        /// A direct message was created during a game session.
118        GameDirectMessageCreate = "GAME_DIRECT_MESSAGE_CREATE",
119        /// A direct message was updated during a game session.
120        GameDirectMessageUpdate = "GAME_DIRECT_MESSAGE_UPDATE",
121        /// A direct message was deleted during a game session.
122        GameDirectMessageDelete = "GAME_DIRECT_MESSAGE_DELETE",
123    }
124}
125
126/// The [event body](https://docs.discord.com/developers/events/webhook-events#event-body-object)
127/// of a webhook event: when it happened and its data.
128///
129/// discord.js counterpart: `APIWebhookEvent` (discord-api-types).
130#[derive(Clone, Debug, PartialEq)]
131#[non_exhaustive]
132pub struct WebhookEvent {
133    /// When the event occurred. Discord sends it without an offset; it is read as UTC.
134    pub timestamp: Timestamp,
135    /// The event's data, by [type](WebhookEventData::kind).
136    pub data: WebhookEventData,
137}
138
139impl WebhookEvent {
140    /// Returns the event's type.
141    ///
142    /// discord.js counterpart: `ApplicationWebhookEventType` (discord-api-types).
143    #[must_use]
144    pub fn kind(&self) -> WebhookEventType {
145        self.data.kind()
146    }
147}
148
149/// The data of a [`WebhookEvent`], by [event type](https://docs.discord.com/developers/events/webhook-events#event-types).
150///
151/// discord.js counterpart: `APIWebhookEventBody` (discord-api-types).
152#[derive(Clone, Debug, PartialEq)]
153#[non_exhaustive]
154pub enum WebhookEventData {
155    /// [`APPLICATION_AUTHORIZED`](https://docs.discord.com/developers/events/webhook-events#application-authorized):
156    /// the app was added to a guild or a user account.
157    ApplicationAuthorized(Box<ApplicationAuthorized>),
158    /// [`APPLICATION_DEAUTHORIZED`](https://docs.discord.com/developers/events/webhook-events#application-deauthorized):
159    /// a user deauthorized the app. For Social SDK apps this is the only signal outside the game
160    /// that the user's account link was removed.
161    ApplicationDeauthorized(Box<ApplicationDeauthorized>),
162    /// [`ENTITLEMENT_CREATE`](https://docs.discord.com/developers/events/webhook-events#entitlement-create):
163    /// a user purchased or was granted one of the app's SKUs.
164    EntitlementCreate(Box<Entitlement>),
165    /// [`ENTITLEMENT_UPDATE`](https://docs.discord.com/developers/events/webhook-events#entitlement-update).
166    EntitlementUpdate(Box<Entitlement>),
167    /// [`ENTITLEMENT_DELETE`](https://docs.discord.com/developers/events/webhook-events#entitlement-delete).
168    EntitlementDelete(Box<Entitlement>),
169    /// [`QUEST_USER_ENROLLMENT`](https://docs.discord.com/developers/events/webhook-events#quest-user-enrollment):
170    /// a user was added to a Quest. Apps cannot receive it yet; it has no documented data.
171    QuestUserEnrollment,
172    /// [`LOBBY_MESSAGE_CREATE`](https://docs.discord.com/developers/events/webhook-events#lobby-message-create).
173    LobbyMessageCreate(Box<LobbyMessage>),
174    /// [`LOBBY_MESSAGE_UPDATE`](https://docs.discord.com/developers/events/webhook-events#lobby-message-update).
175    LobbyMessageUpdate(Box<LobbyMessage>),
176    /// [`LOBBY_MESSAGE_DELETE`](https://docs.discord.com/developers/events/webhook-events#lobby-message-delete).
177    LobbyMessageDelete(LobbyMessageDelete),
178    /// [`GAME_DIRECT_MESSAGE_CREATE`](https://docs.discord.com/developers/events/webhook-events#game-direct-message-create):
179    /// a direct message was sent while a participant had an active Social SDK session.
180    GameDirectMessageCreate(Box<GameDirectMessage>),
181    /// [`GAME_DIRECT_MESSAGE_UPDATE`](https://docs.discord.com/developers/events/webhook-events#game-direct-message-update).
182    GameDirectMessageUpdate(Box<GameDirectMessage>),
183    /// [`GAME_DIRECT_MESSAGE_DELETE`](https://docs.discord.com/developers/events/webhook-events#game-direct-message-delete).
184    GameDirectMessageDelete(Box<GameDirectMessage>),
185    /// An event type this version does not know; its data is not kept.
186    Unknown(WebhookEventType),
187}
188
189impl WebhookEventData {
190    /// Returns the event's type.
191    ///
192    /// discord.js counterpart: `ApplicationWebhookEventType` (discord-api-types).
193    #[must_use]
194    pub fn kind(&self) -> WebhookEventType {
195        match self {
196            Self::ApplicationAuthorized(_) => WebhookEventType::ApplicationAuthorized,
197            Self::ApplicationDeauthorized(_) => WebhookEventType::ApplicationDeauthorized,
198            Self::EntitlementCreate(_) => WebhookEventType::EntitlementCreate,
199            Self::EntitlementUpdate(_) => WebhookEventType::EntitlementUpdate,
200            Self::EntitlementDelete(_) => WebhookEventType::EntitlementDelete,
201            Self::QuestUserEnrollment => WebhookEventType::QuestUserEnrollment,
202            Self::LobbyMessageCreate(_) => WebhookEventType::LobbyMessageCreate,
203            Self::LobbyMessageUpdate(_) => WebhookEventType::LobbyMessageUpdate,
204            Self::LobbyMessageDelete(_) => WebhookEventType::LobbyMessageDelete,
205            Self::GameDirectMessageCreate(_) => WebhookEventType::GameDirectMessageCreate,
206            Self::GameDirectMessageUpdate(_) => WebhookEventType::GameDirectMessageUpdate,
207            Self::GameDirectMessageDelete(_) => WebhookEventType::GameDirectMessageDelete,
208            Self::Unknown(kind) => kind.clone(),
209        }
210    }
211}
212
213/// The data of an [Application Authorized](https://docs.discord.com/developers/events/webhook-events#application-authorized)
214/// webhook event.
215///
216/// discord.js counterpart: `APIWebhookEventApplicationAuthorizedData` (discord-api-types).
217#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
218#[non_exhaustive]
219pub struct ApplicationAuthorized {
220    /// Where the app was installed: [`IntegrationType::GuildInstall`] (a guild) or
221    /// [`IntegrationType::UserInstall`] (the user's account).
222    #[serde(default, skip_serializing_if = "Option::is_none")]
223    pub integration_type: Option<IntegrationType>,
224    /// The user who authorized the app.
225    pub user: User,
226    /// The `OAuth2` [scopes](Scope) the user authorized.
227    #[serde(default)]
228    pub scopes: Vec<Scope>,
229    /// The guild the app was authorized in (guild installs).
230    #[serde(default, skip_serializing_if = "Option::is_none")]
231    pub guild: Option<Box<Guild>>,
232}
233
234/// The data of an [Application Deauthorized](https://docs.discord.com/developers/events/webhook-events#application-deauthorized)
235/// webhook event.
236///
237/// discord.js counterpart: `APIWebhookEventApplicationDeauthorizedData` (discord-api-types).
238#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
239#[non_exhaustive]
240pub struct ApplicationDeauthorized {
241    /// The user who deauthorized the app.
242    pub user: User,
243}
244
245/// The data of a [Lobby Message Delete](https://docs.discord.com/developers/events/webhook-events#lobby-message-delete)
246/// webhook event.
247///
248/// discord.js counterpart: none (lobbies are not in discord.js v14 or discord-api-types).
249#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
250#[non_exhaustive]
251pub struct LobbyMessageDelete {
252    /// The deleted message.
253    pub id: MessageId,
254    /// The lobby it was deleted from.
255    pub lobby_id: LobbyId,
256}
257
258/// A direct message in a `GAME_DIRECT_MESSAGE_*` webhook event (D-079).
259///
260/// Covers both kinds of messages the docs describe: a regular
261/// [message](https://docs.discord.com/developers/events/webhook-events#message-object) (with
262/// `channel` and, in linked channels, `lobby_id`) and an
263/// [SDK DM message](https://docs.discord.com/developers/events/webhook-events#sdk-dm-message-object)
264/// between provisional accounts, which exists only in the game. Only `id`, `content` and
265/// `author` are required; message fields not listed here are ignored.
266///
267/// Contains floats (attachment durations), so it is `PartialEq` but not `Eq` (D-064).
268///
269/// discord.js counterpart: none (not in discord.js v14 or discord-api-types).
270#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
271#[non_exhaustive]
272pub struct GameDirectMessage {
273    /// The message's ID.
274    pub id: MessageId,
275    /// The message's type.
276    #[serde(default, rename = "type", skip_serializing_if = "Option::is_none")]
277    pub kind: Option<MessageType>,
278    /// The message's text.
279    pub content: CompactString,
280    /// The DM channel.
281    #[serde(default, skip_serializing_if = "Option::is_none")]
282    pub channel_id: Option<ChannelId>,
283    /// The DM channel, with its recipients.
284    #[serde(default, skip_serializing_if = "Option::is_none")]
285    pub channel: Option<Box<Channel>>,
286    /// The lobby the message was sent in (linked channel messages).
287    #[serde(default, skip_serializing_if = "Option::is_none")]
288    pub lobby_id: Option<LobbyId>,
289    /// The author.
290    pub author: User,
291    /// The recipient, as shown in the docs' update example (not documented further).
292    #[serde(default, skip_serializing_if = "Option::is_none")]
293    pub recipient_id: Option<GenericId>,
294    /// When the message was sent.
295    #[serde(default, skip_serializing_if = "Option::is_none")]
296    pub timestamp: Option<Timestamp>,
297    /// When the message was last edited.
298    #[serde(default, skip_serializing_if = "Option::is_none")]
299    pub edited_timestamp: Option<Timestamp>,
300    /// The message's flags.
301    #[serde(default)]
302    pub flags: MessageFlags,
303    /// The application that created the message (SDK DM messages).
304    #[serde(default, skip_serializing_if = "Option::is_none")]
305    pub application_id: Option<ApplicationId>,
306    /// The attached files.
307    #[serde(default, skip_serializing_if = "Vec::is_empty")]
308    pub attachments: Vec<Attachment>,
309    /// The embeds.
310    #[serde(default, skip_serializing_if = "Vec::is_empty")]
311    pub embeds: Vec<Embed>,
312    /// The message components.
313    #[serde(default, skip_serializing_if = "Vec::is_empty")]
314    pub components: Vec<Component>,
315    /// Sent with Rich Presence-related chat embeds.
316    #[serde(default, skip_serializing_if = "Option::is_none")]
317    pub activity: Option<MessageActivity>,
318    /// Sent with Rich Presence-related chat embeds.
319    #[serde(default, skip_serializing_if = "Option::is_none")]
320    pub application: Option<Box<PartialApplication>>,
321}
322
323/// Reads an event body timestamp, which has no offset (read as UTC).
324fn naive_timestamp<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Timestamp, D::Error> {
325    struct NaiveVisitor;
326
327    impl Visitor<'_> for NaiveVisitor {
328        type Value = Timestamp;
329
330        fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
331            f.write_str("an ISO 8601 timestamp")
332        }
333
334        fn visit_str<E: DeError>(self, value: &str) -> Result<Timestamp, E> {
335            Timestamp::parse_assume_utc(value).map_err(E::custom)
336        }
337    }
338
339    deserializer.deserialize_str(NaiveVisitor)
340}
341
342#[derive(Deserialize)]
343struct RawEvent {
344    #[serde(rename = "type")]
345    kind: WebhookEventType,
346    #[serde(deserialize_with = "naive_timestamp")]
347    timestamp: Timestamp,
348    // Buffered: `data` may come before `type`. Webhook events are rare, so the second pass is
349    // cheap.
350    #[serde(default)]
351    data: Option<JsonValue>,
352}
353
354impl<'de> Deserialize<'de> for WebhookEvent {
355    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
356        let raw = RawEvent::deserialize(deserializer)?;
357        let convert = |error: JsonValueError| D::Error::custom(format_args!("data: {error}"));
358        let data = || {
359            raw.data
360                .as_ref()
361                .ok_or_else(|| D::Error::missing_field("data"))
362        };
363        let data = match &raw.kind {
364            WebhookEventType::QuestUserEnrollment => WebhookEventData::QuestUserEnrollment,
365            WebhookEventType::Unknown(_) => WebhookEventData::Unknown(raw.kind.clone()),
366            WebhookEventType::ApplicationAuthorized => {
367                WebhookEventData::ApplicationAuthorized(data()?.to_type().map_err(convert)?)
368            }
369            WebhookEventType::ApplicationDeauthorized => {
370                WebhookEventData::ApplicationDeauthorized(data()?.to_type().map_err(convert)?)
371            }
372            WebhookEventType::EntitlementCreate => {
373                WebhookEventData::EntitlementCreate(data()?.to_type().map_err(convert)?)
374            }
375            WebhookEventType::EntitlementUpdate => {
376                WebhookEventData::EntitlementUpdate(data()?.to_type().map_err(convert)?)
377            }
378            WebhookEventType::EntitlementDelete => {
379                WebhookEventData::EntitlementDelete(data()?.to_type().map_err(convert)?)
380            }
381            WebhookEventType::LobbyMessageCreate => {
382                WebhookEventData::LobbyMessageCreate(data()?.to_type().map_err(convert)?)
383            }
384            WebhookEventType::LobbyMessageUpdate => {
385                WebhookEventData::LobbyMessageUpdate(data()?.to_type().map_err(convert)?)
386            }
387            WebhookEventType::LobbyMessageDelete => {
388                WebhookEventData::LobbyMessageDelete(data()?.to_type().map_err(convert)?)
389            }
390            WebhookEventType::GameDirectMessageCreate => {
391                WebhookEventData::GameDirectMessageCreate(data()?.to_type().map_err(convert)?)
392            }
393            WebhookEventType::GameDirectMessageUpdate => {
394                WebhookEventData::GameDirectMessageUpdate(data()?.to_type().map_err(convert)?)
395            }
396            WebhookEventType::GameDirectMessageDelete => {
397                WebhookEventData::GameDirectMessageDelete(data()?.to_type().map_err(convert)?)
398            }
399        };
400        Ok(Self {
401            timestamp: raw.timestamp,
402            data,
403        })
404    }
405}
406
407impl Serialize for WebhookEvent {
408    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
409        #[derive(Serialize)]
410        #[serde(untagged)]
411        enum DataRef<'a> {
412            Authorized(&'a ApplicationAuthorized),
413            Deauthorized(&'a ApplicationDeauthorized),
414            Entitlement(&'a Entitlement),
415            LobbyMessage(&'a LobbyMessage),
416            LobbyMessageDelete(&'a LobbyMessageDelete),
417            GameDirectMessage(&'a GameDirectMessage),
418        }
419
420        #[derive(Serialize)]
421        struct Flat<'a> {
422            #[serde(rename = "type")]
423            kind: WebhookEventType,
424            timestamp: Timestamp,
425            #[serde(skip_serializing_if = "Option::is_none")]
426            data: Option<DataRef<'a>>,
427        }
428
429        let data = match &self.data {
430            WebhookEventData::ApplicationAuthorized(data) => Some(DataRef::Authorized(data)),
431            WebhookEventData::ApplicationDeauthorized(data) => Some(DataRef::Deauthorized(data)),
432            WebhookEventData::EntitlementCreate(data)
433            | WebhookEventData::EntitlementUpdate(data)
434            | WebhookEventData::EntitlementDelete(data) => Some(DataRef::Entitlement(data)),
435            WebhookEventData::LobbyMessageCreate(data)
436            | WebhookEventData::LobbyMessageUpdate(data) => Some(DataRef::LobbyMessage(data)),
437            WebhookEventData::LobbyMessageDelete(data) => Some(DataRef::LobbyMessageDelete(data)),
438            WebhookEventData::GameDirectMessageCreate(data)
439            | WebhookEventData::GameDirectMessageUpdate(data)
440            | WebhookEventData::GameDirectMessageDelete(data) => {
441                Some(DataRef::GameDirectMessage(data))
442            }
443            WebhookEventData::QuestUserEnrollment | WebhookEventData::Unknown(_) => None,
444        };
445        Flat {
446            kind: self.kind(),
447            timestamp: self.timestamp,
448            data,
449        }
450        .serialize(serializer)
451    }
452}
453
454#[cfg(test)]
455mod tests {
456    use super::*;
457
458    fn event(kind: &str, data: &str) -> Result<WebhookEvent, serde_json::Error> {
459        serde_json::from_str(&format!(
460            r#"{{"data":{data},"type":"{kind}","timestamp":"2024-10-18T14:42:53.064834"}}"#
461        ))
462    }
463
464    #[test]
465    fn data_before_type_and_timestamp_as_utc() {
466        let event = event("LOBBY_MESSAGE_DELETE", r#"{"id":"1","lobby_id":"2"}"#).unwrap();
467        assert_eq!(event.kind(), WebhookEventType::LobbyMessageDelete);
468        assert_eq!(
469            event.timestamp,
470            "2024-10-18T14:42:53.064834+00:00".parse().unwrap()
471        );
472        assert_eq!(
473            serde_json::to_string(&event).unwrap(),
474            r#"{"type":"LOBBY_MESSAGE_DELETE","timestamp":"2024-10-18T14:42:53.064834+00:00","data":{"id":"1","lobby_id":"2"}}"#
475        );
476    }
477
478    #[test]
479    fn unknown_and_dataless_events() {
480        let unknown = event("FUTURE_EVENT", r#"{"anything":[1,2]}"#).unwrap();
481        assert_eq!(
482            unknown.data,
483            WebhookEventData::Unknown(WebhookEventType::Unknown("FUTURE_EVENT".into()))
484        );
485        let quest = event("QUEST_USER_ENROLLMENT", "null").unwrap();
486        assert_eq!(quest.data, WebhookEventData::QuestUserEnrollment);
487        assert!(!serde_json::to_string(&quest).unwrap().contains("data"));
488    }
489
490    #[test]
491    fn missing_or_invalid_data_is_an_error() {
492        let missing = event("APPLICATION_DEAUTHORIZED", "null").unwrap_err();
493        assert!(
494            missing.to_string().contains("missing field `data`"),
495            "{missing}"
496        );
497        let invalid = event("LOBBY_MESSAGE_DELETE", r#"{"id":"1"}"#).unwrap_err();
498        assert!(invalid.to_string().starts_with("data: "), "{invalid}");
499    }
500}