spectacles-model 0.2.0

Discord types and structures for Spectacles.rs.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
//! Structs representing the various elements of the Discord gateway.
use std::fmt::{Display, Formatter, Result as FmtResult};

use serde_json::{
    Error as JsonError,
    value::RawValue,
};
use serde_repr::{Deserialize_repr, Serialize_repr};

use crate::{
    guild::UnavailableGuild,
    presence::{ClientActivity, ClientPresence},
    Snowflake,
    User
};
use crate::presence::Status;

/// Denotes structs that can be sent to the gateway.
pub trait SendablePacket {
    fn to_json(self) -> Result<String, JsonError>;
    fn bytes(self) -> Result<Vec<u8>, JsonError>;
}

/// Returns useful information about the application from the gateway.
#[derive(Serialize, Deserialize, Debug)]
pub struct GatewayBot {
    /// The websocket URL that can be used to begin connecting to this gateway.
    pub url: String,
    /// The recommended number of shards to spawn when connecting.
    pub shards: usize,
    /// Information regarding the current session start limit.
    pub session_start_limit: SessionStartLimit
}
/// Useful information about a bot's session start limit.
#[derive(Serialize, Deserialize, Debug)]
pub struct SessionStartLimit {
    /// The total number of session starts the current user is allowed.
    pub total: i32,
    /// The remaining number of session starts the current user is allowed.
    pub remaining: i32,
    /// The time until the limit resets.
    pub reset_after: i32,
}

/// A JSON packet that the client would receive over the Discord gateway.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct ReceivePacket {
    /// The opcode for this payload.
    pub op: Opcodes,
    /// The JSON value for this payload.
    pub d: Box<RawValue>,
    pub s: Option<u64>,
    /// The name of the event that was fired, if applicable.
    pub t: Option<GatewayEvent>
}

#[derive(Serialize, Deserialize, Debug)]
/// A JSON packet that the client would send to the Discord Gateway.
pub struct SendPacket<T: SendablePacket> {
    /// The opcode for this packet.
    pub op: Opcodes,
    /// The JSON data for this packet.
    pub d: T
}

/// A message, sent to a message broker, which contains the packet to be sent to the Discord gateway.
#[derive(Serialize, Deserialize, Debug)]
pub struct GatewayBrokerMessage {
    /// The guild ID of which to calculate the shard ID from.
    pub guild_id: Snowflake,
    /// The packet, as a raw JSON value.
    pub packet: Box<RawValue>,
}

impl GatewayBrokerMessage {
    /// Creates a new gateway broker message.
    pub fn new<T: SendablePacket>(guild_id: Snowflake, packet: T) -> Result<Self, JsonError> {
        let raw = RawValue::from_string(packet.to_json()?)?;

        Ok(Self {
            guild_id,
            packet: raw,
        })
    }
    /// Converts the message to a byte vector, suitable for publishing to most message brokers.
    pub fn as_bytes(&self) -> Result<Vec<u8>, JsonError> {
        let json = serde_json::to_string(self)?;

        Ok(json.as_bytes().to_vec())
    }
}

/// Used for identifying a shard with the gateway.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct IdentifyPacket {
    /// The token this shard will use.
    pub token: String,
    /// The properties of the client.
    pub properties: IdentifyProperties,
    /// The version of the gateway to use.
    #[serde(rename = "v")]
    pub version: u8,
    /// Whether or not to compress packets.
    pub compress: bool,
    /// The total number of members where the gateway will stop sending offline members in the guild member list.
    pub large_threshold: i32,
    /// Holds the sharding information for this shard.
    pub shard: [usize; 2],
    /// The initial presence of this shard.
    pub presence: Option<ClientPresence>
}


#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct IdentifyProperties {
    /// The client's operating system.
    #[serde(rename = "$os")]
    pub os: String,
    /// The current name of the library.
    #[serde(rename = "$browser")]
    pub browser: String,
    /// The current name of the library.
    #[serde(rename = "$device")]
    pub device: String
}

/// A JSON packet which defines the heartbeat the client should adhere to.
#[derive(Serialize, Deserialize, Debug)]
pub struct HelloPacket {
    /// The heartbeat interval that the shard should follow.
    pub heartbeat_interval: u64,
    /// An array of servers that the client is connected to.
    pub _trace: Vec<String>
}

/// A packet used to resume a gateway connection.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct ResumeSessionPacket {
    /// The client's session ID>
    pub session_id: String,
    /// The current sequence.
    pub seq: u64,
    /// The token of the client.
    pub token: String
}
/// A JSON packet used to send a heartbeat to the gateway.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct HeartbeatPacket {
    /// The shard's last sequence number.
    pub seq: u64
}

#[derive(Serialize, Deserialize, Debug, Clone)]
/// A Request guild members packet.
pub struct RequestGuildMembers {
    /// The guild ID to get members for.
    pub guild_id: Snowflake,
    /// A string that the username starts with. If omitted, returns all members.
    pub query: String,
    /// The maximum number of members to send. If omitted, requests all members.
    pub limit: i32
}


/// An Update Voice State packet.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct UpdateVoiceState {
    /// The guild ID of the guild.
    pub guild_id: Snowflake,
    /// The channel ID of the voice channel.
    pub channel_id: Snowflake,
    /// Whether or not to mute the current user.
    pub self_mute: bool,
    /// Whether or not to deafen the current user.
    pub self_deaf: bool
}

/// A packet sent to change the current status of the connected client.
#[derive(Serialize, Deserialize, Debug, Clone, Default)]
pub struct UpdateStatus {
    /// Milliseconds since the client went idle.
    pub since: Option<i32>,
    /// The activity object to set.
    pub game: Option<ClientActivity>,
    /// The status object to set.
    pub status: Status,
    /// Whether or not the client is AFK.
    pub afk: bool
}

impl UpdateStatus {
    /// Sets the activity for this packet.
    pub fn game(mut self, activity: ClientActivity) -> Self {
        self.game = Some(activity);

        self
    }

    /// Sets the status for this packet.
    pub fn status(mut self, status: Status) -> Self {
        self.status = status;

        self
    }

    /// Sets the AFK flag for this packet.
    pub fn afk(mut self, afk: bool) -> Self {
        self.afk = afk;

        self
    }
}

impl SendablePacket for UpdateStatus {
    fn to_json(self) -> Result<String, JsonError> {
        serde_json::to_string(&SendPacket {
            op: Opcodes::StatusUpdate,
            d: self
        })
    }

    fn bytes(self) -> Result<Vec<u8>, JsonError> {
        let json = self.to_json()?;

        Ok(json.as_bytes().to_vec())
    }
}


impl SendablePacket for IdentifyPacket {
    fn to_json(self) -> Result<String, JsonError> {
        serde_json::to_string(&SendPacket {
            op: Opcodes::Identify,
            d: self
        })
    }

    fn bytes(self) -> Result<Vec<u8>, JsonError> {
        let json = self.to_json()?;

        Ok(json.as_bytes().to_vec())
    }
}


impl SendablePacket for UpdateVoiceState {
    fn to_json(self) -> Result<String, JsonError> {
        serde_json::to_string(&SendPacket {
            op: Opcodes::VoiceStatusUpdate,
            d: self,
        })
    }

    fn bytes(self) -> Result<Vec<u8>, JsonError> {
        let json = self.to_json()?;

        Ok(json.as_bytes().to_vec())
    }
}
impl SendablePacket for RequestGuildMembers {
    fn to_json(self) -> Result<String, JsonError> {
        serde_json::to_string(&SendPacket {
            op: Opcodes::RequestGuildMembers,
            d: self
        })
    }

    fn bytes(self) -> Result<Vec<u8>, JsonError> {
        let json = self.to_json()?;

        Ok(json.as_bytes().to_vec())
    }
}

impl SendablePacket for HeartbeatPacket {
    fn to_json(self) -> Result<String, JsonError> {
        serde_json::to_string(&SendPacket {
            op: Opcodes::Heartbeat,
            d: self
        })
    }

    fn bytes(self) -> Result<Vec<u8>, JsonError> {
        let json = self.to_json()?;

        Ok(json.as_bytes().to_vec())
    }
}

impl SendablePacket for ResumeSessionPacket {
    fn to_json(self) -> Result<String, JsonError> {
        serde_json::to_string(&SendPacket {
            op: Opcodes::Resume,
            d: self
        })
    }

    fn bytes(self) -> Result<Vec<u8>, JsonError> {
        let json = self.to_json()?;

        Ok(json.as_bytes().to_vec())
    }
}

/// The packet received when a client completes a handshake with the Discord gateway.
/// This packet is considered the largest and most complex packet sent.
#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct ReadyPacket {
    /// The current gateway version,
    pub v: i32,
    /// Information about the current user.
    pub user: User,
    /// An empty array of private channels.
    pub private_channels: [String; 0],
    /// The guilds that the user is currently in.
    /// This will be an array of UnavailableGuild objects.
    pub guilds: Vec<UnavailableGuild>,
    /// The session ID that is used to resume a gateway connection.
    pub session_id: String,
    /// The guilds that a user is in, used for debugging.
    pub _trace: Vec<String>,
    /// Information about the current shard, if applicable.
    #[serde(default)]
    pub shard: [u64; 2]
}

/// This packet is received when the client resumes an existing session.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct ResumedPacket {
    /// The servers that the client is connected to.
    pub _trace: Vec<String>

}
#[derive(Debug, Deserialize, Serialize, Clone)]
#[allow(non_camel_case_types)]
/// An organized list of Discord gateway events.
pub enum GatewayEvent {
    HELLO,
    READY,
    RESUMED,
    INVALID_SESSION,
    CHANNEL_CREATE,
    CHANNEL_UPDATE,
    CHANNEL_DELETE,
    CHANNEL_PINS_UPDATE,
    GUILD_CREATE,
    GUILD_UPDATE,
    GUILD_DELETE,
    GUILD_BAN_ADD,
    GUILD_BAN_REMOVE,
    GUILD_EMOJIS_UPDATE,
    GUILD_INTEGRATIONS_UPDATE,
    GUILD_MEMBER_ADD,
    GUILD_MEMBER_REMOVE,
    GUILD_MEMBER_UPDATE,
    GUILD_MEMBERS_CHUNK,
    GUILD_ROLE_CREATE,
    GUILD_ROLE_UPDATE,
    GUILD_ROLE_DELETE,
    MESSAGE_CREATE,
    MESSAGE_UPDATE,
    MESSAGE_DELETE,
    MESSAGE_DELETE_BULK,
    MESSAGE_REACTION_ADD,
    MESSAGE_REACTION_REMOVE,
    MESSAGE_REACTION_REMOVE_ALL,
    PRESENCE_UPDATE,
    PRESENCES_REPLACE,
    TYPING_START,
    USER_UPDATE,
    VOICE_STATE_UPDATE,
    VOICE_SERVER_UPDATE,
    WEBHOOKS_UPDATE
}

impl Display for GatewayEvent {
    fn fmt(&self, f: &mut Formatter) -> FmtResult {
        write!(f, "{:?}", self)
    }
}
/// A set of possible Discord gateway opcodes.
#[derive(Serialize_repr, Deserialize_repr, Debug, Clone)]
#[repr(u8)]
pub enum Opcodes {
    /// Dispatches a gateway event.
    Dispatch,
    /// Used for sending ping and heartbeats.
    Heartbeat,
    /// Used for obtaining a client handshake.
    Identify,
    /// Used to update the shard's status.
    StatusUpdate,
    /// Used to join and leave voice channels.
    VoiceStatusUpdate,
    /// Used to resume a closed connection.
    Resume = 6,
    /// Tells clients to reconnect to the gateway.
    Reconnect,
    /// used to request guild members.
    RequestGuildMembers,
    /// Used to notify the client of an invlaid session.
    InvalidSession,
    /// Sent immediately after connecting, contains heartbeat information.
    Hello,
    /// Sent immediately after receiving a heartbeat.
    HeartbeatAck
}

/// Codes that denote the cause of the gateway closing.
#[derive(Debug, Copy, Deserialize_repr, Clone)]
#[repr(u16)]
pub enum CloseCodes {
    /// The cause of the error is unknown.
    UnknownError = 4000,
    /// The opcode or the payload for an opcode sent was invalid.
    UnknownOpcode,
    /// An invalid payload was sent.
    DecodeError,
    /// A payload was sent prior to identifying.
    NotAuthenticated,
    /// The token sent with the payload was invalid.
    AuthenticationFailed,
    /// More than one identify payload was sent.
    AlreadyAuthenticated,
    /// The sequence sent when resuming the session was invalid.
    InvalidSeq,
    /// A ratelimit caused by sending payloads too quickly.
    Ratelimited,
    /// The session timed out, a reconnect is required.
    SessionTimeout,
    /// An invalid shard was sent when identifying.
    InvalidShard,
    /// The session would have had too many guilds, which indicated that sharding is required.
    ShardingRequired,
}