Skip to main content

djs_model/gateway/payload/
outgoing.rs

1//! Payloads (commands) sent to the gateway.
2
3use core::fmt;
4
5use compact_str::CompactString;
6use serde::{Serialize, Serializer, ser::SerializeStruct};
7
8use crate::{
9    gateway::{Activity, Intents, OpCode, ShardId, Status},
10    id::{ChannelId, GuildId, UserId},
11    macros::{int_flags, str_enum},
12    util::Timestamp,
13};
14
15/// A payload that can be sent to the gateway.
16///
17/// Each command knows its [opcode](Self::OPCODE). Wrap a command in [`CommandPayload`] to get
18/// the `{"op": …, "d": …}` envelope the gateway expects.
19///
20/// discord.js counterpart: `GatewaySendPayload` (discord-api-types).
21pub trait GatewayCommand: Serialize {
22    /// The opcode of the command.
23    const OPCODE: OpCode;
24}
25
26/// The `{"op": …, "d": …}` envelope around a [`GatewayCommand`], ready to be serialized.
27///
28/// discord.js counterpart: `GatewaySendPayload` (discord-api-types), with its `op`.
29///
30/// # Examples
31///
32/// ```
33/// use djs_model::gateway::payload::{CommandPayload, Heartbeat};
34///
35/// let json = serde_json::to_string(&CommandPayload::new(&Heartbeat(Some(251)))).unwrap();
36/// assert_eq!(json, r#"{"op":1,"d":251}"#);
37/// ```
38#[derive(Debug)]
39pub struct CommandPayload<'a, T> {
40    command: &'a T,
41}
42
43impl<'a, T: GatewayCommand> CommandPayload<'a, T> {
44    /// Wraps a command.
45    ///
46    /// discord.js counterpart: none (`WebSocketShard#send` takes the `GatewaySendPayload`).
47    #[must_use]
48    pub const fn new(command: &'a T) -> Self {
49        Self { command }
50    }
51}
52
53impl<T: GatewayCommand> Serialize for CommandPayload<'_, T> {
54    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
55        let mut payload = serializer.serialize_struct("CommandPayload", 2)?;
56        payload.serialize_field("op", &T::OPCODE)?;
57        payload.serialize_field("d", self.command)?;
58        payload.end()
59    }
60}
61
62/// A [Heartbeat](https://docs.discord.com/developers/events/gateway-events#heartbeat)
63/// (opcode 1): the last sequence number received, or `None` if no dispatch has been received
64/// yet.
65///
66/// discord.js counterpart: `GatewayHeartbeat` (discord-api-types).
67#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize)]
68#[serde(transparent)]
69pub struct Heartbeat(pub Option<u64>);
70
71impl GatewayCommand for Heartbeat {
72    const OPCODE: OpCode = OpCode::Heartbeat;
73}
74
75/// An [Identify](https://docs.discord.com/developers/events/gateway-events#identify)
76/// (opcode 2): starts a new session.
77///
78/// Identifying is limited to `max_concurrency` sessions per 5 seconds and 1000 per day; exceeding
79/// the daily limit resets the bot token.
80///
81/// The [`Debug`] implementation redacts the token.
82///
83/// discord.js counterpart: `GatewayIdentify` (discord-api-types).
84#[derive(Clone, PartialEq, Eq, Serialize)]
85pub struct Identify {
86    /// The bot token, **without** the `Bot ` prefix.
87    pub token: CompactString,
88    /// Connection properties describing the client.
89    pub properties: IdentifyProperties,
90    /// The member count above which offline members are not sent in a guild's member list
91    /// (50–250, Discord's default is 50).
92    #[serde(skip_serializing_if = "Option::is_none")]
93    pub large_threshold: Option<u8>,
94    /// The shard this session handles. Omit for unsharded bots.
95    #[serde(skip_serializing_if = "Option::is_none")]
96    pub shard: Option<ShardId>,
97    /// The gateway intents to subscribe to.
98    pub intents: Intents,
99    /// The presence to start with.
100    #[serde(skip_serializing_if = "Option::is_none")]
101    pub presence: Option<UpdatePresence>,
102    /// Opt-in gateway behaviours.
103    #[serde(skip_serializing_if = "GatewayCapabilities::is_empty")]
104    pub capabilities: GatewayCapabilities,
105}
106
107int_flags! {
108    /// [Gateway capabilities](https://docs.discord.com/developers/events/gateway-events#identify-gateway-capabilities)
109    /// a client opts into with [`Identify::capabilities`].
110    ///
111    /// discord.js counterpart: `GatewayCapabilityBits` (discord-api-types).
112    pub struct GatewayCapabilities: u64 {
113        /// Receive obfuscated metadata for channels the bot cannot view.
114        const CHANNEL_OBFUSCATION = 1 << 15;
115    }
116}
117
118impl GatewayCommand for Identify {
119    const OPCODE: OpCode = OpCode::Identify;
120}
121
122impl fmt::Debug for Identify {
123    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
124        f.debug_struct("Identify")
125            .field("token", &"<redacted>")
126            .field("properties", &self.properties)
127            .field("large_threshold", &self.large_threshold)
128            .field("shard", &self.shard)
129            .field("intents", &self.intents)
130            .field("presence", &self.presence)
131            .field("capabilities", &self.capabilities)
132            .finish()
133    }
134}
135
136/// The [connection properties](https://docs.discord.com/developers/events/gateway-events#identify-identify-connection-properties)
137/// sent in [`Identify`].
138///
139/// discord.js counterpart: `GatewayIdentifyProperties` (discord-api-types).
140#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
141pub struct IdentifyProperties {
142    /// The operating system, e.g. `linux`.
143    pub os: CompactString,
144    /// The library name.
145    pub browser: CompactString,
146    /// The library name.
147    pub device: CompactString,
148}
149
150impl IdentifyProperties {
151    /// Creates properties with the given library name and the current operating system
152    /// ([`std::env::consts::OS`]).
153    ///
154    /// discord.js counterpart: the `identifyProperties` option of `WebSocketManagerOptions` (`@discordjs/ws`).
155    ///
156    /// # Examples
157    ///
158    /// ```
159    /// use djs_model::gateway::payload::IdentifyProperties;
160    ///
161    /// let properties = IdentifyProperties::new("djs-rs");
162    /// assert_eq!(properties.browser, "djs-rs");
163    /// assert_eq!(properties.os, std::env::consts::OS);
164    /// ```
165    #[must_use]
166    pub fn new(library: &str) -> Self {
167        Self {
168            os: CompactString::const_new(std::env::consts::OS),
169            browser: library.into(),
170            device: library.into(),
171        }
172    }
173}
174
175/// A [Resume](https://docs.discord.com/developers/events/gateway-events#resume) (opcode 6):
176/// continues a disconnected session and replays missed events.
177///
178/// The [`Debug`] implementation redacts the token.
179///
180/// discord.js counterpart: `GatewayResume` (discord-api-types).
181#[derive(Clone, PartialEq, Eq, Serialize)]
182pub struct Resume {
183    /// The bot token, **without** the `Bot ` prefix.
184    pub token: CompactString,
185    /// The session ID from [`Ready`](super::Ready).
186    pub session_id: CompactString,
187    /// The last sequence number received.
188    pub seq: u64,
189}
190
191impl GatewayCommand for Resume {
192    const OPCODE: OpCode = OpCode::Resume;
193}
194
195impl fmt::Debug for Resume {
196    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
197        f.debug_struct("Resume")
198            .field("token", &"<redacted>")
199            .field("session_id", &self.session_id)
200            .field("seq", &self.seq)
201            .finish()
202    }
203}
204
205/// [Request Guild Members](https://docs.discord.com/developers/events/gateway-events#request-guild-members)
206/// (opcode 8): asks for members of a guild; they arrive in
207/// [`GuildMembersChunk`](super::GuildMembersChunk) events.
208///
209/// Requesting all members (or presences) requires the `GUILD_MEMBERS` (or `GUILD_PRESENCES`)
210/// intent; it is rate limited ([`RateLimited`](super::RateLimited)).
211///
212/// discord.js counterpart: `GuildMemberManager#fetch` (over the gateway).
213///
214/// # Examples
215///
216/// ```
217/// use djs_model::{gateway::payload::{CommandPayload, RequestGuildMembers}, id::GuildId};
218///
219/// let request = RequestGuildMembers::query(GuildId::new(41771983423143937), "mix", 10);
220/// assert_eq!(
221///     serde_json::to_string(&CommandPayload::new(&request)).unwrap(),
222///     r#"{"op":8,"d":{"guild_id":"41771983423143937","query":"mix","limit":10}}"#
223/// );
224/// ```
225#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
226#[non_exhaustive]
227pub struct RequestGuildMembers {
228    /// The guild.
229    pub guild_id: GuildId,
230    /// The prefix usernames must start with (`""` for all members).
231    #[serde(skip_serializing_if = "Option::is_none")]
232    pub query: Option<CompactString>,
233    /// The maximum number of members for a query (`0` with an empty query: all members).
234    #[serde(skip_serializing_if = "Option::is_none")]
235    pub limit: Option<u32>,
236    /// Whether to include the members' presences.
237    #[serde(skip_serializing_if = "core::ops::Not::not")]
238    pub presences: bool,
239    /// The users to fetch (instead of a query).
240    #[serde(skip_serializing_if = "Vec::is_empty")]
241    pub user_ids: Vec<UserId>,
242    /// A nonce returned in the chunks (max 32 bytes).
243    #[serde(skip_serializing_if = "Option::is_none")]
244    pub nonce: Option<CompactString>,
245}
246
247impl RequestGuildMembers {
248    /// Requests the members whose username starts with `query`, at most `limit`.
249    ///
250    /// discord.js counterpart: the `query` and `limit` options of `GuildMemberManager#fetch`.
251    #[must_use]
252    pub fn query(guild_id: GuildId, query: impl Into<CompactString>, limit: u32) -> Self {
253        Self {
254            guild_id,
255            query: Some(query.into()),
256            limit: Some(limit),
257            presences: false,
258            user_ids: Vec::new(),
259            nonce: None,
260        }
261    }
262
263    /// Requests all members (requires the `GUILD_MEMBERS` intent).
264    ///
265    /// discord.js counterpart: `GuildMemberManager#fetch` without options.
266    #[must_use]
267    pub fn all(guild_id: GuildId) -> Self {
268        Self::query(guild_id, "", 0)
269    }
270
271    /// Requests the given users (up to 100).
272    ///
273    /// discord.js counterpart: the `user` option of `GuildMemberManager#fetch`.
274    #[must_use]
275    pub fn users(guild_id: GuildId, user_ids: impl IntoIterator<Item = UserId>) -> Self {
276        Self {
277            guild_id,
278            query: None,
279            limit: None,
280            presences: false,
281            user_ids: user_ids.into_iter().collect(),
282            nonce: None,
283        }
284    }
285}
286
287impl GatewayCommand for RequestGuildMembers {
288    const OPCODE: OpCode = OpCode::RequestGuildMembers;
289}
290
291/// [Request Soundboard Sounds](https://docs.discord.com/developers/events/gateway-events#request-soundboard-sounds)
292/// (opcode 31): asks for the soundboard sounds of guilds; they arrive in
293/// [`SoundboardSounds`](super::SoundboardSounds) events.
294///
295/// discord.js counterpart: `GatewayRequestSoundboardSounds` (discord-api-types).
296#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
297#[non_exhaustive]
298pub struct RequestSoundboardSounds {
299    /// The guilds.
300    pub guild_ids: Vec<GuildId>,
301}
302
303impl RequestSoundboardSounds {
304    /// Requests the sounds of the given guilds.
305    ///
306    /// discord.js counterpart: `GuildManager#fetchSoundboardSounds`.
307    #[must_use]
308    pub fn new(guild_ids: impl IntoIterator<Item = GuildId>) -> Self {
309        Self {
310            guild_ids: guild_ids.into_iter().collect(),
311        }
312    }
313}
314
315impl GatewayCommand for RequestSoundboardSounds {
316    const OPCODE: OpCode = OpCode::RequestSoundboardSounds;
317}
318
319/// [Request Channel Info](https://docs.discord.com/developers/events/gateway-events#request-channel-info)
320/// (opcode 43): asks for ephemeral data of a guild's channels; it arrives in a
321/// [`ChannelInfo`](super::ChannelInfo) event.
322///
323/// discord.js counterpart: `GatewayRequestChannelInfo` (discord-api-types).
324#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
325#[non_exhaustive]
326pub struct RequestChannelInfo {
327    /// The guild.
328    pub guild_id: GuildId,
329    /// The fields to request.
330    pub fields: Vec<ChannelInfoField>,
331}
332
333impl RequestChannelInfo {
334    /// Requests the given fields of the guild's channels.
335    ///
336    /// discord.js counterpart: `GatewayRequestChannelInfoData` (discord-api-types).
337    #[must_use]
338    pub fn new(guild_id: GuildId, fields: impl IntoIterator<Item = ChannelInfoField>) -> Self {
339        Self {
340            guild_id,
341            fields: fields.into_iter().collect(),
342        }
343    }
344}
345
346impl GatewayCommand for RequestChannelInfo {
347    const OPCODE: OpCode = OpCode::RequestChannelInfo;
348}
349
350str_enum! {
351    /// A field that [`RequestChannelInfo`] can request.
352    ///
353    /// discord.js counterpart: `GatewayRequestChannelInfoField` (discord-api-types).
354    pub enum ChannelInfoField {
355        /// The voice channel status.
356        Status = "status",
357        /// When the voice session started.
358        VoiceStartTime = "voice_start_time",
359    }
360}
361
362/// [Update Voice State](https://docs.discord.com/developers/events/gateway-events#update-voice-state)
363/// (opcode 4): joins, moves between or leaves voice channels.
364///
365/// discord.js counterpart: what `@discordjs/voice` sends through the guild's shard.
366#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize)]
367#[non_exhaustive]
368pub struct UpdateVoiceState {
369    /// The guild.
370    pub guild_id: GuildId,
371    /// The voice channel to join (`None` to disconnect).
372    pub channel_id: Option<ChannelId>,
373    /// Whether the bot is muted.
374    pub self_mute: bool,
375    /// Whether the bot is deafened.
376    pub self_deaf: bool,
377}
378
379impl UpdateVoiceState {
380    /// Joins `channel_id` (or disconnects with `None`).
381    ///
382    /// discord.js counterpart: `joinVoiceChannel` (`@discordjs/voice`).
383    #[must_use]
384    pub const fn new(
385        guild_id: GuildId,
386        channel_id: Option<ChannelId>,
387        self_mute: bool,
388        self_deaf: bool,
389    ) -> Self {
390        Self {
391            guild_id,
392            channel_id,
393            self_mute,
394            self_deaf,
395        }
396    }
397}
398
399impl GatewayCommand for UpdateVoiceState {
400    const OPCODE: OpCode = OpCode::VoiceStateUpdate;
401}
402
403/// [Update Presence](https://docs.discord.com/developers/events/gateway-events#update-presence)
404/// (opcode 3): sets the bot's status and activities (5 updates per 20 seconds).
405///
406/// discord.js counterpart: `ClientUser#setPresence`.
407///
408/// # Examples
409///
410/// ```
411/// use djs_model::gateway::{Activity, ActivityType, Status, payload::UpdatePresence};
412///
413/// let presence = UpdatePresence::new(Status::Online, [Activity::new(ActivityType::Watching, "you")]);
414/// assert_eq!(
415///     serde_json::to_string(&presence).unwrap(),
416///     r#"{"since":null,"activities":[{"name":"you","type":3}],"status":"online","afk":false}"#
417/// );
418/// ```
419#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
420#[non_exhaustive]
421pub struct UpdatePresence {
422    /// When the bot went idle (sent as Unix milliseconds, D-075), `None` if not idle.
423    #[serde(with = "crate::serde_util::option_unix_millis")]
424    pub since: Option<Timestamp>,
425    /// The activities (bots can set the name, state, type and URL).
426    pub activities: Vec<Activity>,
427    /// The status.
428    pub status: Status,
429    /// Whether the bot is AFK.
430    pub afk: bool,
431}
432
433impl UpdatePresence {
434    /// Sets the status and activities (not idle, not AFK).
435    ///
436    /// discord.js counterpart: `ClientUser#setPresence`.
437    #[must_use]
438    pub fn new(status: Status, activities: impl IntoIterator<Item = Activity>) -> Self {
439        Self {
440            since: None,
441            activities: activities.into_iter().collect(),
442            status,
443            afk: false,
444        }
445    }
446}
447
448impl GatewayCommand for UpdatePresence {
449    const OPCODE: OpCode = OpCode::PresenceUpdate;
450}
451
452#[cfg(test)]
453mod tests {
454    use super::*;
455
456    #[test]
457    fn identify_json() {
458        let identify = Identify {
459            token: "secret".into(),
460            properties: IdentifyProperties {
461                os: "linux".into(),
462                browser: "djs-rs".into(),
463                device: "djs-rs".into(),
464            },
465            large_threshold: None,
466            shard: Some(ShardId::ONE),
467            intents: Intents::GUILDS | Intents::GUILD_MESSAGES,
468            presence: None,
469            capabilities: GatewayCapabilities::empty(),
470        };
471        let json = serde_json::to_string(&CommandPayload::new(&identify)).unwrap();
472        assert_eq!(
473            json,
474            r#"{"op":2,"d":{"token":"secret","properties":{"os":"linux","browser":"djs-rs","device":"djs-rs"},"shard":[0,1],"intents":513}}"#
475        );
476        assert!(!format!("{identify:?}").contains("secret"));
477    }
478
479    #[test]
480    fn resume_json() {
481        let resume = Resume {
482            token: "secret".into(),
483            session_id: "abc".into(),
484            seq: 1337,
485        };
486        let json = serde_json::to_string(&CommandPayload::new(&resume)).unwrap();
487        assert_eq!(
488            json,
489            r#"{"op":6,"d":{"token":"secret","session_id":"abc","seq":1337}}"#
490        );
491        assert!(!format!("{resume:?}").contains("secret"));
492    }
493
494    #[test]
495    fn first_heartbeat_is_null() {
496        let json = serde_json::to_string(&CommandPayload::new(&Heartbeat(None))).unwrap();
497        assert_eq!(json, r#"{"op":1,"d":null}"#);
498    }
499}