Skip to main content

djs_model/gateway/payload/incoming/
mod.rs

1//! Payloads received from the gateway: the connection events and the data of every dispatch
2//! event.
3//!
4//! Each dispatch event has its own payload type (D-073). An event whose data is exactly one
5//! object is a newtype that dereferences to it (e.g. [`ChannelCreate`] →
6//! [`Channel`](crate::channel::Channel)); an event with extra fields holds the object and the
7//! extras, decoded in one pass.
8
9mod channel;
10mod guild;
11mod message;
12
13use compact_str::CompactString;
14use serde::{Deserialize, Serialize};
15
16pub use self::{channel::*, guild::*, message::*};
17use crate::{
18    application::ApplicationFlags,
19    gateway::{OpCode, ShardId},
20    guild::UnavailableGuild,
21    id::{ApplicationId, GuildId},
22    user::CurrentUser,
23};
24
25/// Defines a dispatch event whose data is exactly one object: a transparent newtype that
26/// dereferences to it.
27macro_rules! newtype_event {
28    ($(#[$meta:meta])* $name:ident($inner:ty)) => {
29        $(#[$meta])*
30        ///
31        #[doc = concat!("Dereferences to the contained [`", stringify!($inner), "`].")]
32        #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
33        #[serde(transparent)]
34        pub struct $name(pub $inner);
35
36        impl core::ops::Deref for $name {
37            type Target = $inner;
38
39            fn deref(&self) -> &$inner {
40                &self.0
41            }
42        }
43
44        impl core::ops::DerefMut for $name {
45            fn deref_mut(&mut self) -> &mut $inner {
46                &mut self.0
47            }
48        }
49
50        impl From<$name> for $inner {
51            fn from(event: $name) -> Self {
52                event.0
53            }
54        }
55    };
56}
57
58use newtype_event;
59
60/// Collects the `guild_id` that some events add to an object (D-073).
61#[derive(Default)]
62struct GuildIdExtra {
63    guild_id: Option<GuildId>,
64}
65
66impl<'de> crate::serde_util::extras::Extras<'de> for GuildIdExtra {
67    fn visit<A: serde::de::MapAccess<'de>>(
68        &mut self,
69        key: &str,
70        map: &mut A,
71    ) -> Result<crate::serde_util::extras::Visit, A::Error> {
72        if key == "guild_id" {
73            self.guild_id = Some(map.next_value()?);
74            Ok(crate::serde_util::extras::Visit::Consumed)
75        } else {
76            Ok(crate::serde_util::extras::Visit::Pass)
77        }
78    }
79}
80
81/// Defines a dispatch event whose data is an object plus a `guild_id` (D-073): a struct with
82/// both that dereferences to the object, decoded in one pass.
83macro_rules! guild_id_event {
84    ($(#[$meta:meta])* $name:ident { $(#[$field_meta:meta])* $field:ident: $inner:ty }) => {
85        $(#[$meta])*
86        ///
87        #[doc = concat!("Dereferences to the contained [`", stringify!($inner), "`].")]
88        #[derive(Clone, Debug, PartialEq)]
89        #[non_exhaustive]
90        pub struct $name {
91            /// The guild.
92            pub guild_id: crate::id::GuildId,
93            $(#[$field_meta])*
94            pub $field: $inner,
95        }
96
97        impl core::ops::Deref for $name {
98            type Target = $inner;
99
100            fn deref(&self) -> &$inner {
101                &self.$field
102            }
103        }
104
105        impl core::ops::DerefMut for $name {
106            fn deref_mut(&mut self) -> &mut $inner {
107                &mut self.$field
108            }
109        }
110
111        impl<'de> serde::Deserialize<'de> for $name {
112            fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
113                use serde::de::Error as _;
114
115                let (base, extra) = crate::serde_util::extras::deserialize::<
116                    $inner,
117                    super::GuildIdExtra,
118                    D,
119                >(deserializer)?;
120                Ok(Self {
121                    guild_id: extra
122                        .guild_id
123                        .ok_or_else(|| D::Error::missing_field("guild_id"))?,
124                    $field: base.ok_or_else(|| D::Error::custom("missing event data"))?,
125                })
126            }
127        }
128
129        impl serde::Serialize for $name {
130            fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
131                #[derive(serde::Serialize)]
132                struct Flat<'a> {
133                    guild_id: crate::id::GuildId,
134                    #[serde(flatten)]
135                    $field: &'a $inner,
136                }
137
138                Flat {
139                    guild_id: self.guild_id,
140                    $field: &self.$field,
141                }
142                .serialize(serializer)
143            }
144        }
145    };
146}
147
148use guild_id_event;
149
150/// The data of a [Hello](https://docs.discord.com/developers/events/gateway-events#hello) event
151/// (opcode 10), sent immediately after the WebSocket connection opens.
152///
153/// discord.js counterpart: `GatewayHello` (discord-api-types).
154#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
155#[non_exhaustive]
156pub struct Hello {
157    /// How often to send heartbeats, in milliseconds.
158    pub heartbeat_interval: u64,
159}
160
161/// The data of the [Ready](https://docs.discord.com/developers/events/gateway-events#ready)
162/// dispatch event, sent after a successful identify.
163///
164/// It contains the information needed to resume the session later
165/// ([`session_id`](Self::session_id) and [`resume_gateway_url`](Self::resume_gateway_url)).
166///
167/// discord.js counterpart: the `ClientReady` event.
168#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
169#[non_exhaustive]
170pub struct Ready {
171    /// The [API version](https://docs.discord.com/developers/reference#api-versioning).
172    #[serde(rename = "v")]
173    pub version: u8,
174    /// The bot's own user.
175    pub user: CurrentUser,
176    /// The guilds the bot is in, all initially unavailable. With sharding, only the guilds of
177    /// this shard are listed.
178    pub guilds: Vec<UnavailableGuild>,
179    /// The session ID, used for resuming.
180    pub session_id: CompactString,
181    /// The gateway URL to use when resuming this session.
182    pub resume_gateway_url: CompactString,
183    /// The shard this session belongs to, if one was sent when identifying.
184    #[serde(default, skip_serializing_if = "Option::is_none")]
185    pub shard: Option<ShardId>,
186    /// The bot's application.
187    pub application: ReadyApplication,
188}
189
190/// The partial application included in [`Ready`]: its ID and flags.
191///
192/// discord.js counterpart: the `application` of `GatewayReadyDispatchData` (discord-api-types).
193#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
194#[non_exhaustive]
195pub struct ReadyApplication {
196    /// The application's ID.
197    pub id: ApplicationId,
198    /// The application's flags, e.g. which privileged intents it may use.
199    #[serde(default)]
200    pub flags: ApplicationFlags,
201    /// The flags as a decimal string (for flags beyond 32 bits).
202    #[serde(
203        default,
204        skip_serializing_if = "Option::is_none",
205        with = "crate::serde_util::option_flags_string"
206    )]
207    pub flags_new: Option<ApplicationFlags>,
208}
209
210/// The data of the [Rate Limited](https://docs.discord.com/developers/events/gateway-events#rate-limited)
211/// dispatch event: a gateway command was rate limited.
212///
213/// discord.js counterpart: `GatewayRateLimitedDispatchData` (discord-api-types).
214#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
215#[non_exhaustive]
216pub struct RateLimited {
217    /// The opcode of the rate-limited command.
218    pub opcode: OpCode,
219    /// How long to wait before sending it again, in seconds.
220    pub retry_after: f64,
221    /// Details for the opcode ([`RequestGuildMembers`](OpCode::RequestGuildMembers): the guild
222    /// and nonce).
223    #[serde(default, skip_serializing_if = "Option::is_none")]
224    pub meta: Option<RateLimitMetadata>,
225}
226
227/// The [metadata of a rate-limited `REQUEST_GUILD_MEMBERS`](https://docs.discord.com/developers/events/gateway-events#rate-limited-request-guild-member-rate-limit-metadata-structure).
228///
229/// discord.js counterpart: `GatewayRateLimitedMetadata` (discord-api-types).
230#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
231#[non_exhaustive]
232pub struct RateLimitMetadata {
233    /// The guild whose members were requested.
234    pub guild_id: GuildId,
235    /// The nonce of the request.
236    #[serde(default, skip_serializing_if = "Option::is_none")]
237    pub nonce: Option<CompactString>,
238}