-
Notifications
You must be signed in to change notification settings - Fork 598
/
Copy pathevent.rs
2064 lines (1953 loc) · 80 KB
/
event.rs
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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! All the events this library handles.
use std::collections::HashMap;
use std::convert::TryFrom;
use std::fmt;
use serde::de::{Error as DeError, IgnoredAny, MapAccess};
use super::prelude::*;
use super::utils::{emojis, roles, stickers};
use crate::constants::OpCode;
use crate::internal::prelude::*;
use crate::json::prelude::*;
use crate::model::application::command::CommandPermission;
use crate::model::application::interaction::Interaction;
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(transparent)]
#[non_exhaustive]
pub struct ApplicationCommandPermissionsUpdateEvent {
pub permission: CommandPermission,
}
/// Event data for the channel creation event.
///
/// This is fired when:
///
/// - A [`Channel`] is created in a [`Guild`]
/// - A [`PrivateChannel`] is created
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(transparent)]
#[non_exhaustive]
pub struct ChannelCreateEvent {
/// The channel that was created.
pub channel: Channel,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(transparent)]
#[non_exhaustive]
pub struct ChannelDeleteEvent {
pub channel: Channel,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[non_exhaustive]
pub struct ChannelPinsUpdateEvent {
pub guild_id: Option<GuildId>,
pub channel_id: ChannelId,
pub last_pin_timestamp: Option<Timestamp>,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(transparent)]
#[non_exhaustive]
pub struct ChannelUpdateEvent {
pub channel: Channel,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[non_exhaustive]
pub struct GuildBanAddEvent {
pub guild_id: GuildId,
pub user: User,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[non_exhaustive]
pub struct GuildBanRemoveEvent {
pub guild_id: GuildId,
pub user: User,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(transparent)]
#[non_exhaustive]
pub struct GuildCreateEvent {
pub guild: Guild,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(transparent)]
#[non_exhaustive]
pub struct GuildDeleteEvent {
pub guild: UnavailableGuild,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[non_exhaustive]
pub struct GuildEmojisUpdateEvent {
#[serde(with = "emojis")]
pub emojis: HashMap<EmojiId, Emoji>,
pub guild_id: GuildId,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[non_exhaustive]
pub struct GuildIntegrationsUpdateEvent {
pub guild_id: GuildId,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(transparent)]
#[non_exhaustive]
pub struct GuildMemberAddEvent {
pub member: Member,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[non_exhaustive]
pub struct GuildMemberRemoveEvent {
pub guild_id: GuildId,
pub user: User,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[non_exhaustive]
pub struct GuildMemberUpdateEvent {
pub guild_id: GuildId,
pub nick: Option<String>,
pub joined_at: Timestamp,
pub roles: Vec<RoleId>,
pub user: User,
pub premium_since: Option<Timestamp>,
#[serde(default)]
pub pending: bool,
#[serde(default)]
pub deaf: bool,
#[serde(default)]
pub mute: bool,
pub avatar: Option<String>,
pub communication_disabled_until: Option<Timestamp>,
}
#[derive(Clone, Debug, Serialize)]
#[non_exhaustive]
pub struct GuildMembersChunkEvent {
pub guild_id: GuildId,
pub members: HashMap<UserId, Member>,
pub chunk_index: u32,
pub chunk_count: u32,
pub nonce: Option<String>,
}
impl<'de> Deserialize<'de> for GuildMembersChunkEvent {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> StdResult<Self, D::Error> {
#[derive(Deserialize)]
#[serde(field_identifier, rename_all = "snake_case")]
enum Field {
GuildId,
ChunkIndex,
ChunkCount,
Members,
Nonce,
Unknown(String),
}
struct GuildMembersChunkVisitor;
impl<'de> Visitor<'de> for GuildMembersChunkVisitor {
type Value = GuildMembersChunkEvent;
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("struct GuildMembersChunkEvent")
}
fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> StdResult<Self::Value, A::Error> {
let mut guild_id = None;
let mut chunk_index = None;
let mut chunk_count = None;
let mut members = None;
let mut nonce = None;
while let Some(key) = map.next_key()? {
match key {
Field::GuildId => {
if guild_id.is_some() {
return Err(DeError::duplicate_field("guild_id"));
}
guild_id = Some(map.next_value()?);
},
Field::ChunkIndex => {
if chunk_index.is_some() {
return Err(DeError::duplicate_field("chunk_index"));
}
chunk_index = Some(map.next_value()?);
},
Field::ChunkCount => {
if chunk_count.is_some() {
return Err(DeError::duplicate_field("chunk_count"));
}
chunk_count = Some(map.next_value()?);
},
Field::Members => {
if members.is_some() {
return Err(DeError::duplicate_field("members"));
}
members = Some(map.next_value::<Vec<InterimMember>>()?);
},
Field::Nonce => {
if nonce.is_some() {
return Err(DeError::duplicate_field("nonce"));
}
nonce = Some(map.next_value()?);
},
Field::Unknown(_) => {
// ignore unknown keys
map.next_value::<IgnoredAny>()?;
},
}
}
let guild_id = guild_id.ok_or_else(|| DeError::missing_field("guild_id"))?;
let chunk_index =
chunk_index.ok_or_else(|| DeError::missing_field("chunk_index"))?;
let chunk_count =
chunk_count.ok_or_else(|| DeError::missing_field("chunk_count"))?;
let members = members.ok_or_else(|| DeError::missing_field("members"))?;
let members = members
.into_iter()
.map(|m| {
let mut m = Member::from(m);
m.guild_id = guild_id;
(m.user.id, m)
})
.collect();
Ok(GuildMembersChunkEvent {
guild_id,
members,
chunk_index,
chunk_count,
nonce,
})
}
}
const FIELDS: &[&str] = &["guild_id", "chunk_index", "chunk_count", "members", "nonce"];
deserializer.deserialize_struct("GuildMembersChunkEvent", FIELDS, GuildMembersChunkVisitor)
}
}
#[derive(Clone, Debug, Serialize)]
#[non_exhaustive]
pub struct GuildRoleCreateEvent {
pub role: Role,
}
impl<'de> Deserialize<'de> for GuildRoleCreateEvent {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> StdResult<Self, D::Error> {
Ok(Self {
role: roles::deserialize_event(deserializer)?,
})
}
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[non_exhaustive]
pub struct GuildRoleDeleteEvent {
pub guild_id: GuildId,
pub role_id: RoleId,
}
#[derive(Clone, Debug, Serialize)]
#[non_exhaustive]
pub struct GuildRoleUpdateEvent {
pub role: Role,
}
impl<'de> Deserialize<'de> for GuildRoleUpdateEvent {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> StdResult<Self, D::Error> {
Ok(Self {
role: roles::deserialize_event(deserializer)?,
})
}
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[non_exhaustive]
pub struct GuildStickersUpdateEvent {
#[serde(with = "stickers")]
pub stickers: HashMap<StickerId, Sticker>,
pub guild_id: GuildId,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[non_exhaustive]
pub struct InviteCreateEvent {
pub channel_id: ChannelId,
pub code: String,
pub guild_id: Option<GuildId>,
pub inviter: Option<User>,
pub max_age: u64,
pub max_uses: u64,
pub temporary: bool,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[non_exhaustive]
pub struct InviteDeleteEvent {
pub channel_id: ChannelId,
pub guild_id: Option<GuildId>,
pub code: String,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[non_exhaustive]
pub struct GuildUnavailableEvent {
#[serde(rename = "id")]
pub guild_id: GuildId,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(transparent)]
#[non_exhaustive]
pub struct GuildUpdateEvent {
pub guild: PartialGuild,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(transparent)]
#[non_exhaustive]
pub struct MessageCreateEvent {
pub message: Message,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[non_exhaustive]
pub struct MessageDeleteBulkEvent {
pub guild_id: Option<GuildId>,
pub channel_id: ChannelId,
pub ids: Vec<MessageId>,
}
#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
#[non_exhaustive]
pub struct MessageDeleteEvent {
pub guild_id: Option<GuildId>,
pub channel_id: ChannelId,
#[serde(rename = "id")]
pub message_id: MessageId,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[non_exhaustive]
pub struct MessageUpdateEvent {
pub id: MessageId,
pub guild_id: Option<GuildId>,
pub channel_id: ChannelId,
pub kind: Option<MessageType>,
pub content: Option<String>,
pub nonce: Option<String>,
pub tts: Option<bool>,
pub pinned: Option<bool>,
pub timestamp: Option<Timestamp>,
pub edited_timestamp: Option<Timestamp>,
pub author: Option<User>,
pub mention_everyone: Option<bool>,
pub mentions: Option<Vec<User>>,
pub mention_roles: Option<Vec<RoleId>>,
pub attachments: Option<Vec<Attachment>>,
pub embeds: Option<Vec<Embed>>,
pub flags: Option<MessageFlags>,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(transparent)]
#[non_exhaustive]
pub struct PresenceUpdateEvent {
pub presence: Presence,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(transparent)]
#[non_exhaustive]
pub struct PresencesReplaceEvent {
pub presences: Vec<Presence>,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(transparent)]
#[non_exhaustive]
pub struct ReactionAddEvent {
pub reaction: Reaction,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(transparent)]
#[non_exhaustive]
pub struct ReactionRemoveEvent {
pub reaction: Reaction,
}
#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
#[non_exhaustive]
pub struct ReactionRemoveAllEvent {
pub guild_id: Option<GuildId>,
pub channel_id: ChannelId,
pub message_id: MessageId,
}
/// The "Ready" event, containing initial ready cache
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(transparent)]
#[non_exhaustive]
pub struct ReadyEvent {
pub ready: Ready,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[non_exhaustive]
pub struct ResumedEvent {
#[serde(rename = "_trace")]
pub trace: Vec<Option<String>>,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[non_exhaustive]
pub struct TypingStartEvent {
pub guild_id: Option<GuildId>,
pub channel_id: ChannelId,
pub timestamp: u64,
pub user_id: UserId,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[non_exhaustive]
pub struct UnknownEvent {
pub kind: String,
pub value: Value,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(transparent)]
#[non_exhaustive]
pub struct UserUpdateEvent {
pub current_user: CurrentUser,
}
#[derive(Clone, Deserialize, Serialize)]
#[non_exhaustive]
pub struct VoiceServerUpdateEvent {
pub channel_id: Option<ChannelId>,
pub endpoint: Option<String>,
pub guild_id: Option<GuildId>,
pub token: String,
}
impl fmt::Debug for VoiceServerUpdateEvent {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("VoiceServerUpdateEvent")
.field("channel_id", &self.channel_id)
.field("endpoint", &self.endpoint)
.field("guild_id", &self.guild_id)
.finish()
}
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(transparent)]
#[non_exhaustive]
pub struct VoiceStateUpdateEvent {
pub voice_state: VoiceState,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[non_exhaustive]
pub struct WebhookUpdateEvent {
pub channel_id: ChannelId,
pub guild_id: GuildId,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(transparent)]
#[non_exhaustive]
pub struct InteractionCreateEvent {
pub interaction: Interaction,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(transparent)]
#[non_exhaustive]
pub struct IntegrationCreateEvent {
pub integration: Integration,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(transparent)]
#[non_exhaustive]
pub struct IntegrationUpdateEvent {
pub integration: Integration,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[non_exhaustive]
pub struct IntegrationDeleteEvent {
pub id: IntegrationId,
pub guild_id: GuildId,
pub application_id: Option<ApplicationId>,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(transparent)]
#[non_exhaustive]
pub struct StageInstanceCreateEvent {
pub stage_instance: StageInstance,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(transparent)]
#[non_exhaustive]
pub struct StageInstanceUpdateEvent {
pub stage_instance: StageInstance,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(transparent)]
#[non_exhaustive]
pub struct StageInstanceDeleteEvent {
pub stage_instance: StageInstance,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(transparent)]
#[non_exhaustive]
pub struct ThreadCreateEvent {
pub thread: GuildChannel,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(transparent)]
#[non_exhaustive]
pub struct ThreadUpdateEvent {
pub thread: GuildChannel,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(transparent)]
#[non_exhaustive]
pub struct ThreadDeleteEvent {
pub thread: PartialGuildChannel,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[non_exhaustive]
pub struct ThreadListSyncEvent {
/// The guild Id.
pub guild_id: GuildId,
/// The parent channel Id whose threads are being synced. If empty, then threads were synced for the entire guild.
/// This array may contain channel Ids that have no active threads as well, so you know to clear that data.
#[serde(default)]
pub channels_id: Vec<ChannelId>,
/// All active threads in the given channels that the current user can access.
pub threads: Vec<GuildChannel>,
/// All thread member objects from the synced threads for the current user,
/// indicating which threads the current user has been added to
pub members: Vec<ThreadMember>,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(transparent)]
#[non_exhaustive]
pub struct ThreadMemberUpdateEvent {
pub member: ThreadMember,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[non_exhaustive]
pub struct ThreadMembersUpdateEvent {
/// The id of the thread.
pub id: ChannelId,
/// The id of the Guild.
pub guild_id: GuildId,
/// The approximate number of members in the thread, capped at 50.
pub member_count: u8,
/// The users who were added to the thread.
#[serde(default)]
pub added_members: Vec<ThreadMember>,
/// The ids of the users who were removed from the thread.
#[serde(default)]
pub removed_members_ids: Vec<UserId>,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(transparent)]
#[non_exhaustive]
pub struct GuildScheduledEventCreateEvent {
pub event: ScheduledEvent,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(transparent)]
#[non_exhaustive]
pub struct GuildScheduledEventUpdateEvent {
pub event: ScheduledEvent,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(transparent)]
#[non_exhaustive]
pub struct GuildScheduledEventDeleteEvent {
pub event: ScheduledEvent,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[non_exhaustive]
pub struct GuildScheduledEventUserAddEvent {
#[serde(rename = "guild_scheduled_event_id")]
scheduled_event_id: ScheduledEventId,
guild_id: GuildId,
user_id: UserId,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[non_exhaustive]
pub struct GuildScheduledEventUserRemoveEvent {
#[serde(rename = "guild_scheduled_event_id")]
scheduled_event_id: ScheduledEventId,
guild_id: GuildId,
user_id: UserId,
}
#[allow(clippy::large_enum_variant)]
#[derive(Debug, Clone, Serialize)]
#[non_exhaustive]
#[serde(untagged)]
pub enum GatewayEvent {
Dispatch(u64, Event),
Heartbeat(u64),
Reconnect,
/// Whether the session can be resumed.
InvalidateSession(bool),
Hello(u64),
HeartbeatAck,
}
impl<'de> Deserialize<'de> for GatewayEvent {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> StdResult<Self, D::Error> {
let mut map = JsonMap::deserialize(deserializer)?;
let op = map
.remove("op")
.ok_or_else(|| DeError::custom("expected op"))
.and_then(OpCode::deserialize)
.map_err(DeError::custom)?;
Ok(match op {
OpCode::Event => {
let s = map
.remove("s")
.ok_or_else(|| DeError::custom("expected gateway event sequence"))
.and_then(u64::deserialize)
.map_err(DeError::custom)?;
let kind = map
.remove("t")
.ok_or_else(|| DeError::custom("expected gateway event type"))
.and_then(EventType::deserialize)
.map_err(DeError::custom)?;
let payload = map
.remove("d")
.ok_or_else(|| Error::Decode("expected gateway event d", Value::from(map)))
.map_err(DeError::custom)?;
let x = match deserialize_event_with_type(kind.clone(), payload) {
Ok(x) => x,
Err(why) => {
return Err(DeError::custom(format_args!("event {:?}: {}", kind, why)));
},
};
GatewayEvent::Dispatch(s, x)
},
OpCode::Heartbeat => {
let s = map
.remove("s")
.ok_or_else(|| DeError::custom("Expected heartbeat s"))
.and_then(u64::deserialize)
.map_err(DeError::custom)?;
GatewayEvent::Heartbeat(s)
},
OpCode::Reconnect => GatewayEvent::Reconnect,
OpCode::InvalidSession => {
let resumable = map
.remove("d")
.ok_or_else(|| DeError::custom("expected gateway invalid session d"))
.and_then(bool::deserialize)
.map_err(DeError::custom)?;
GatewayEvent::InvalidateSession(resumable)
},
OpCode::Hello => {
let mut d = map
.remove("d")
.ok_or_else(|| DeError::custom("expected gateway hello d"))
.and_then(JsonMap::deserialize)
.map_err(DeError::custom)?;
let interval = d
.remove("heartbeat_interval")
.ok_or_else(|| DeError::custom("expected gateway hello interval"))
.and_then(u64::deserialize)
.map_err(DeError::custom)?;
GatewayEvent::Hello(interval)
},
OpCode::HeartbeatAck => GatewayEvent::HeartbeatAck,
_ => return Err(DeError::custom("invalid opcode")),
})
}
}
/// Event received over a websocket connection
#[allow(clippy::large_enum_variant)]
#[derive(Clone, Debug, Deserialize, Serialize)]
#[non_exhaustive]
#[serde(untagged)]
pub enum Event {
/// The permissions of an [`Command`] was changed.
///
/// Fires the [`EventHandler::application_command_permissions_update`] event.
///
/// [`Command`]: crate::model::application::command::Command
/// [`EventHandler::application_command_permissions_update`]: crate::client::EventHandler::application_command_permissions_update
ApplicationCommandPermissionsUpdate(ApplicationCommandPermissionsUpdateEvent),
/// A [`Channel`] was created.
///
/// Fires the [`EventHandler::channel_create`] event.
///
/// [`EventHandler::channel_create`]: crate::client::EventHandler::channel_create
ChannelCreate(ChannelCreateEvent),
/// A [`Channel`] has been deleted.
///
/// Fires the [`EventHandler::channel_delete`] event.
///
/// [`EventHandler::channel_delete`]: crate::client::EventHandler::channel_delete
ChannelDelete(ChannelDeleteEvent),
/// The pins for a [`Channel`] have been updated.
///
/// Fires the [`EventHandler::channel_pins_update`] event.
///
/// [`EventHandler::channel_pins_update`]: crate::client::EventHandler::channel_pins_update
ChannelPinsUpdate(ChannelPinsUpdateEvent),
/// A [`Channel`] has been updated.
///
/// Fires the [`EventHandler::channel_update`] event.
///
/// [`EventHandler::channel_update`]: crate::client::EventHandler::channel_update
ChannelUpdate(ChannelUpdateEvent),
GuildBanAdd(GuildBanAddEvent),
GuildBanRemove(GuildBanRemoveEvent),
GuildCreate(GuildCreateEvent),
GuildDelete(GuildDeleteEvent),
GuildEmojisUpdate(GuildEmojisUpdateEvent),
GuildIntegrationsUpdate(GuildIntegrationsUpdateEvent),
GuildMemberAdd(GuildMemberAddEvent),
GuildMemberRemove(GuildMemberRemoveEvent),
/// A member's roles have changed
GuildMemberUpdate(GuildMemberUpdateEvent),
GuildMembersChunk(GuildMembersChunkEvent),
GuildRoleCreate(GuildRoleCreateEvent),
GuildRoleDelete(GuildRoleDeleteEvent),
GuildRoleUpdate(GuildRoleUpdateEvent),
/// A [`Sticker`] was created, updated, or deleted
GuildStickersUpdate(GuildStickersUpdateEvent),
/// When a guild is unavailable, such as due to a Discord server outage.
GuildUnavailable(GuildUnavailableEvent),
GuildUpdate(GuildUpdateEvent),
/// An [`Invite`] was created.
///
/// Fires the [`EventHandler::invite_create`] event handler.
///
/// [`EventHandler::invite_create`]: crate::client::EventHandler::invite_create
InviteCreate(InviteCreateEvent),
/// An [`Invite`] was deleted.
///
/// Fires the [`EventHandler::invite_delete`] event handler.
///
/// [`EventHandler::invite_delete`]: crate::client::EventHandler::invite_delete
InviteDelete(InviteDeleteEvent),
MessageCreate(MessageCreateEvent),
MessageDelete(MessageDeleteEvent),
MessageDeleteBulk(MessageDeleteBulkEvent),
/// A message has been edited, either by the user or the system
MessageUpdate(MessageUpdateEvent),
/// A member's presence state (or username or avatar) has changed
PresenceUpdate(PresenceUpdateEvent),
/// The presence list of the user's friends should be replaced entirely
PresencesReplace(PresencesReplaceEvent),
/// A reaction was added to a message.
///
/// Fires the [`EventHandler::reaction_add`] event handler.
///
/// [`EventHandler::reaction_add`]: crate::client::EventHandler::reaction_add
ReactionAdd(ReactionAddEvent),
/// A reaction was removed to a message.
///
/// Fires the [`EventHandler::reaction_remove`] event handler.
///
/// [`EventHandler::reaction_remove`]: crate::client::EventHandler::reaction_remove
ReactionRemove(ReactionRemoveEvent),
/// A request was issued to remove all [`Reaction`]s from a [`Message`].
///
/// Fires the [`EventHandler::reaction_remove_all`] event handler.
///
/// [`EventHandler::reaction_remove_all`]: crate::client::EventHandler::reaction_remove_all
ReactionRemoveAll(ReactionRemoveAllEvent),
/// The first event in a connection, containing the initial ready cache.
///
/// May also be received at a later time in the event of a reconnect.
Ready(ReadyEvent),
/// The connection has successfully resumed after a disconnect.
Resumed(ResumedEvent),
/// A user is typing; considered to last 5 seconds
TypingStart(TypingStartEvent),
/// Update to the logged-in user's information
UserUpdate(UserUpdateEvent),
/// A member's voice state has changed
VoiceStateUpdate(VoiceStateUpdateEvent),
/// Voice server information is available
VoiceServerUpdate(VoiceServerUpdateEvent),
/// A webhook for a [channel][`GuildChannel`] was updated in a [`Guild`].
WebhookUpdate(WebhookUpdateEvent),
/// An interaction was created.
InteractionCreate(InteractionCreateEvent),
/// A guild integration was created
IntegrationCreate(IntegrationCreateEvent),
/// A guild integration was updated
IntegrationUpdate(IntegrationUpdateEvent),
/// A guild integration was deleted
IntegrationDelete(IntegrationDeleteEvent),
/// A stage instance was created.
StageInstanceCreate(StageInstanceCreateEvent),
/// A stage instance was updated.
StageInstanceUpdate(StageInstanceUpdateEvent),
/// A stage instance was deleted.
StageInstanceDelete(StageInstanceDeleteEvent),
/// A thread was created or the current user was added
/// to a private thread.
ThreadCreate(ThreadCreateEvent),
/// A thread was updated.
ThreadUpdate(ThreadUpdateEvent),
/// A thread was deleted.
ThreadDelete(ThreadDeleteEvent),
/// The current user gains access to a channel.
ThreadListSync(ThreadListSyncEvent),
/// The [`ThreadMember`] object for the current user is updated.
ThreadMemberUpdate(ThreadMemberUpdateEvent),
/// Anyone is added to or removed from a thread. If the current user does not have the [`GatewayIntents::GUILDS`],
/// then this event will only be sent if the current user was added to or removed from the thread.
///
/// [`GatewayIntents::GUILDS`]: crate::model::gateway::GatewayIntents::GUILDS
ThreadMembersUpdate(ThreadMembersUpdateEvent),
/// A scheduled event was created.
GuildScheduledEventCreate(GuildScheduledEventCreateEvent),
/// A scheduled event was updated.
GuildScheduledEventUpdate(GuildScheduledEventUpdateEvent),
/// A scheduled event was deleted.
GuildScheduledEventDelete(GuildScheduledEventDeleteEvent),
/// A guild member has subscribed to a scheduled event.
GuildScheduledEventUserAdd(GuildScheduledEventUserAddEvent),
/// A guild member has unsubscribed from a scheduled event.
GuildScheduledEventUserRemove(GuildScheduledEventUserRemoveEvent),
/// An event type not covered by the above
Unknown(UnknownEvent),
}
#[cfg(feature = "model")]
fn gid_from_channel(c: &Channel) -> RelatedId<GuildId> {
match c {
Channel::Guild(g) => RelatedId::Some(g.guild_id),
_ => RelatedId::None,
}
}
macro_rules! with_related_ids_for_event_types {
($macro:ident) => {
$macro! {
Self::ApplicationCommandPermissionsUpdate, Self::ApplicationCommandPermissionsUpdate(e) => {
user_id: Never,
guild_id: Some(e.permission.guild_id),
channel_id: Never,
message_id: Never,
},
Self::ChannelCreate, Self::ChannelCreate(e) => {
user_id: Never,
guild_id: gid_from_channel(&e.channel),
channel_id: Some(e.channel.id()),
message_id: Never,
},
Self::ChannelDelete, Self::ChannelDelete(e) => {
user_id: Never,
guild_id: gid_from_channel(&e.channel),
channel_id: Some(e.channel.id()),
message_id: Never,
},
Self::ChannelPinsUpdate, Self::ChannelPinsUpdate(e) => {
user_id: Never,
guild_id: e.guild_id.into(),
channel_id: Some(e.channel_id),
message_id: Never,
},
Self::ChannelUpdate, Self::ChannelUpdate(e) => {
user_id: Never,
guild_id: gid_from_channel(&e.channel),
channel_id: Some(e.channel.id()),
message_id: Never,
},
Self::GuildBanAdd, Self::GuildBanAdd(e) => {
user_id: Some(e.user.id),
guild_id: Some(e.guild_id),
channel_id: Never,
message_id: Never,
},
Self::GuildBanRemove, Self::GuildBanRemove(e) => {
user_id: Some(e.user.id),
guild_id: Some(e.guild_id),
channel_id: Never,
message_id: Never,
},
Self::GuildCreate, Self::GuildCreate(e) => {
user_id: Never,
guild_id: Some(e.guild.id),
channel_id: Never,
message_id: Never,
},
Self::GuildDelete, Self::GuildDelete(e) => {
user_id: Never,
guild_id: Some(e.guild.id),
channel_id: Never,
message_id: Never,
},
Self::GuildEmojisUpdate, Self::GuildEmojisUpdate(e) => {
user_id: Never,
guild_id: Some(e.guild_id),
channel_id: Never,
message_id: Never,
},
Self::GuildIntegrationsUpdate, Self::GuildIntegrationsUpdate(e) => {
user_id: Never,
guild_id: Some(e.guild_id),
channel_id: Never,
message_id: Never,
},
Self::GuildMemberAdd, Self::GuildMemberAdd(e) => {
user_id: Some(e.member.user.id),
guild_id: Some(e.member.guild_id),
channel_id: Never,
message_id: Never,
},
Self::GuildMemberRemove, Self::GuildMemberRemove(e) => {
user_id: Some(e.user.id),
guild_id: Some(e.guild_id),
channel_id: Never,
message_id: Never,
},
Self::GuildMemberUpdate, Self::GuildMemberUpdate(e) => {
user_id: Some(e.user.id),
guild_id: Some(e.guild_id),
channel_id: Never,
message_id: Never,
},
Self::GuildMembersChunk, Self::GuildMembersChunk(e) => {
user_id: Multiple(e.members.keys().copied().collect()),
guild_id: Some(e.guild_id),
channel_id: Never,
message_id: Never,
},
Self::GuildRoleCreate, Self::GuildRoleCreate(e) => {
user_id: Never,
guild_id: Some(e.role.guild_id),
channel_id: Never,
message_id: Never,
},
Self::GuildRoleDelete, Self::GuildRoleDelete(e) => {
user_id: Never,
guild_id: Some(e.guild_id),
channel_id: Never,
message_id: Never,
},
Self::GuildRoleUpdate, Self::GuildRoleUpdate(e) => {
user_id: Never,
guild_id: Some(e.role.guild_id),
channel_id: Never,
message_id: Never,
},
Self::GuildScheduledEventCreate, Self::GuildScheduledEventCreate(e) => {
user_id: e.event.creator_id.into(),
guild_id: Some(e.event.guild_id),
channel_id: e.event.channel_id.into(),
message_id: Never,
},
Self::GuildScheduledEventUpdate, Self::GuildScheduledEventUpdate(e) => {
user_id: e.event.creator_id.into(),
guild_id: Some(e.event.guild_id),
channel_id: e.event.channel_id.into(),
message_id: Never,
},
Self::GuildScheduledEventDelete, Self::GuildScheduledEventDelete(e) => {
user_id: e.event.creator_id.into(),