-
-
Notifications
You must be signed in to change notification settings - Fork 739
/
Copy pathDiscordSocketClient.cs
2228 lines (2016 loc) · 123 KB
/
DiscordSocketClient.cs
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
using Discord.API;
using Discord.API.Gateway;
using Discord.Logging;
using Discord.Net.Converters;
using Discord.Net.Udp;
using Discord.Net.WebSockets;
using Discord.Rest;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using GameModel = Discord.API.Game;
namespace Discord.WebSocket
{
/// <summary>
/// Represents a WebSocket-based Discord client.
/// </summary>
public partial class DiscordSocketClient : BaseSocketClient, IDiscordClient
{
private readonly ConcurrentQueue<ulong> _largeGuilds;
private readonly JsonSerializer _serializer;
private readonly DiscordShardedClient _shardedClient;
private readonly DiscordSocketClient _parentClient;
private readonly ConcurrentQueue<long> _heartbeatTimes;
private readonly ConnectionManager _connection;
private readonly Logger _gatewayLogger;
private readonly SemaphoreSlim _stateLock;
private string _sessionId;
private int _lastSeq;
private ImmutableDictionary<string, RestVoiceRegion> _voiceRegions;
private Task _heartbeatTask, _guildDownloadTask;
private int _unavailableGuildCount;
private long _lastGuildAvailableTime, _lastMessageTime;
private int _nextAudioId;
private DateTimeOffset? _statusSince;
private RestApplication _applicationInfo;
private bool _isDisposed;
private GatewayIntents _gatewayIntents;
/// <summary>
/// Provides access to a REST-only client with a shared state from this client.
/// </summary>
public override DiscordSocketRestClient Rest { get; }
/// <summary> Gets the shard of of this client. </summary>
public int ShardId { get; }
/// <summary> Gets the current connection state of this client. </summary>
public ConnectionState ConnectionState => _connection.State;
/// <inheritdoc />
public override int Latency { get; protected set; }
/// <inheritdoc />
public override UserStatus Status { get => _status ?? UserStatus.Online; protected set => _status = value; }
private UserStatus? _status;
/// <inheritdoc />
public override IActivity Activity { get => _activity.GetValueOrDefault(); protected set => _activity = Optional.Create(value); }
private Optional<IActivity> _activity;
//From DiscordSocketConfig
internal int TotalShards { get; private set; }
internal int MessageCacheSize { get; private set; }
internal int LargeThreshold { get; private set; }
internal ClientState State { get; private set; }
internal UdpSocketProvider UdpSocketProvider { get; private set; }
internal WebSocketProvider WebSocketProvider { get; private set; }
internal bool AlwaysDownloadUsers { get; private set; }
internal int? HandlerTimeout { get; private set; }
internal new DiscordSocketApiClient ApiClient => base.ApiClient as DiscordSocketApiClient;
/// <inheritdoc />
public override IReadOnlyCollection<SocketGuild> Guilds => State.Guilds;
/// <inheritdoc />
public override IReadOnlyCollection<ISocketPrivateChannel> PrivateChannels => State.PrivateChannels;
/// <summary>
/// Gets a collection of direct message channels opened in this session.
/// </summary>
/// <remarks>
/// This method returns a collection of currently opened direct message channels.
/// <note type="warning">
/// This method will not return previously opened DM channels outside of the current session! If you
/// have just started the client, this may return an empty collection.
/// </note>
/// </remarks>
/// <returns>
/// A collection of DM channels that have been opened in this session.
/// </returns>
public IReadOnlyCollection<SocketDMChannel> DMChannels
=> State.PrivateChannels.OfType<SocketDMChannel>().ToImmutableArray();
/// <summary>
/// Gets a collection of group channels opened in this session.
/// </summary>
/// <remarks>
/// This method returns a collection of currently opened group channels.
/// <note type="warning">
/// This method will not return previously opened group channels outside of the current session! If you
/// have just started the client, this may return an empty collection.
/// </note>
/// </remarks>
/// <returns>
/// A collection of group channels that have been opened in this session.
/// </returns>
public IReadOnlyCollection<SocketGroupChannel> GroupChannels
=> State.PrivateChannels.OfType<SocketGroupChannel>().ToImmutableArray();
/// <summary>
/// Initializes a new REST/WebSocket-based Discord client.
/// </summary>
public DiscordSocketClient() : this(new DiscordSocketConfig()) { }
/// <summary>
/// Initializes a new REST/WebSocket-based Discord client with the provided configuration.
/// </summary>
/// <param name="config">The configuration to be used with the client.</param>
#pragma warning disable IDISP004
public DiscordSocketClient(DiscordSocketConfig config) : this(config, CreateApiClient(config), null, null) { }
internal DiscordSocketClient(DiscordSocketConfig config, DiscordShardedClient shardedClient, DiscordSocketClient parentClient) : this(config, CreateApiClient(config), shardedClient, parentClient) { }
#pragma warning restore IDISP004
private DiscordSocketClient(DiscordSocketConfig config, API.DiscordSocketApiClient client, DiscordShardedClient shardedClient, DiscordSocketClient parentClient)
: base(config, client)
{
ShardId = config.ShardId ?? 0;
TotalShards = config.TotalShards ?? 1;
MessageCacheSize = config.MessageCacheSize;
LargeThreshold = config.LargeThreshold;
UdpSocketProvider = config.UdpSocketProvider;
WebSocketProvider = config.WebSocketProvider;
AlwaysDownloadUsers = config.AlwaysDownloadUsers;
HandlerTimeout = config.HandlerTimeout;
State = new ClientState(0, 0);
Rest = new DiscordSocketRestClient(config, ApiClient);
_heartbeatTimes = new ConcurrentQueue<long>();
_gatewayIntents = config.GatewayIntents;
_stateLock = new SemaphoreSlim(1, 1);
_gatewayLogger = LogManager.CreateLogger(ShardId == 0 && TotalShards == 1 ? "Gateway" : $"Shard #{ShardId}");
_connection = new ConnectionManager(_stateLock, _gatewayLogger, config.ConnectionTimeout,
OnConnectingAsync, OnDisconnectingAsync, x => ApiClient.Disconnected += x);
_connection.Connected += () => TimedInvokeAsync(_connectedEvent, nameof(Connected));
_connection.Disconnected += (ex, recon) => TimedInvokeAsync(_disconnectedEvent, nameof(Disconnected), ex);
_nextAudioId = 1;
_shardedClient = shardedClient;
_parentClient = parentClient;
_serializer = new JsonSerializer { ContractResolver = new DiscordContractResolver() };
_serializer.Error += (s, e) =>
{
_gatewayLogger.WarningAsync("Serializer Error", e.ErrorContext.Error).GetAwaiter().GetResult();
e.ErrorContext.Handled = true;
};
ApiClient.SentGatewayMessage += async opCode => await _gatewayLogger.DebugAsync($"Sent {opCode}").ConfigureAwait(false);
ApiClient.ReceivedGatewayEvent += ProcessMessageAsync;
LeftGuild += async g => await _gatewayLogger.InfoAsync($"Left {g.Name}").ConfigureAwait(false);
JoinedGuild += async g => await _gatewayLogger.InfoAsync($"Joined {g.Name}").ConfigureAwait(false);
GuildAvailable += async g => await _gatewayLogger.VerboseAsync($"Connected to {g.Name}").ConfigureAwait(false);
GuildUnavailable += async g => await _gatewayLogger.VerboseAsync($"Disconnected from {g.Name}").ConfigureAwait(false);
LatencyUpdated += async (old, val) => await _gatewayLogger.DebugAsync($"Latency = {val} ms").ConfigureAwait(false);
GuildAvailable += g =>
{
if (_guildDownloadTask?.IsCompleted == true && ConnectionState == ConnectionState.Connected && AlwaysDownloadUsers && !g.HasAllMembers)
{
var _ = g.DownloadUsersAsync();
}
return Task.Delay(0);
};
_largeGuilds = new ConcurrentQueue<ulong>();
}
private static API.DiscordSocketApiClient CreateApiClient(DiscordSocketConfig config)
=> new API.DiscordSocketApiClient(config.RestClientProvider, config.WebSocketProvider, DiscordRestConfig.UserAgent, config.GatewayHost);
/// <inheritdoc />
internal override void Dispose(bool disposing)
{
if (!_isDisposed)
{
if (disposing)
{
StopAsync().GetAwaiter().GetResult();
ApiClient?.Dispose();
_stateLock?.Dispose();
}
_isDisposed = true;
}
base.Dispose(disposing);
}
/// <inheritdoc />
internal override async Task OnLogoutAsync()
{
await StopAsync().ConfigureAwait(false);
_applicationInfo = null;
_voiceRegions = null;
await Rest.OnLogoutAsync();
}
/// <inheritdoc />
public override async Task StartAsync()
=> await _connection.StartAsync().ConfigureAwait(false);
/// <inheritdoc />
public override async Task StopAsync()
=> await _connection.StopAsync().ConfigureAwait(false);
private async Task OnConnectingAsync()
{
bool locked = false;
if (_shardedClient != null && _sessionId == null)
{
await _shardedClient.AcquireIdentifyLockAsync(ShardId, _connection.CancelToken).ConfigureAwait(false);
locked = true;
}
try
{
await _gatewayLogger.DebugAsync("Connecting ApiClient").ConfigureAwait(false);
await ApiClient.ConnectAsync().ConfigureAwait(false);
if (_sessionId != null)
{
await _gatewayLogger.DebugAsync("Resuming").ConfigureAwait(false);
await ApiClient.SendResumeAsync(_sessionId, _lastSeq).ConfigureAwait(false);
}
else
{
await _gatewayLogger.DebugAsync("Identifying").ConfigureAwait(false);
await ApiClient.SendIdentifyAsync(shardID: ShardId, totalShards: TotalShards, gatewayIntents: _gatewayIntents, presence: BuildCurrentStatus()).ConfigureAwait(false);
}
}
finally
{
if (locked)
_shardedClient.ReleaseIdentifyLock();
}
//Wait for READY
await _connection.WaitAsync().ConfigureAwait(false);
}
private async Task OnDisconnectingAsync(Exception ex)
{
await _gatewayLogger.DebugAsync("Disconnecting ApiClient").ConfigureAwait(false);
await ApiClient.DisconnectAsync(ex).ConfigureAwait(false);
//Wait for tasks to complete
await _gatewayLogger.DebugAsync("Waiting for heartbeater").ConfigureAwait(false);
var heartbeatTask = _heartbeatTask;
if (heartbeatTask != null)
await heartbeatTask.ConfigureAwait(false);
_heartbeatTask = null;
while (_heartbeatTimes.TryDequeue(out _)) { }
_lastMessageTime = 0;
await _gatewayLogger.DebugAsync("Waiting for guild downloader").ConfigureAwait(false);
var guildDownloadTask = _guildDownloadTask;
if (guildDownloadTask != null)
await guildDownloadTask.ConfigureAwait(false);
_guildDownloadTask = null;
//Clear large guild queue
await _gatewayLogger.DebugAsync("Clearing large guild queue").ConfigureAwait(false);
while (_largeGuilds.TryDequeue(out _)) { }
//Raise virtual GUILD_UNAVAILABLEs
await _gatewayLogger.DebugAsync("Raising virtual GuildUnavailables").ConfigureAwait(false);
foreach (var guild in State.Guilds)
{
if (guild.IsAvailable)
await GuildUnavailableAsync(guild).ConfigureAwait(false);
}
}
/// <inheritdoc />
public override async Task<RestApplication> GetApplicationInfoAsync(RequestOptions options = null)
=> _applicationInfo ?? (_applicationInfo = await ClientHelper.GetApplicationInfoAsync(this, options ?? RequestOptions.Default).ConfigureAwait(false));
/// <inheritdoc />
public override SocketGuild GetGuild(ulong id)
=> State.GetGuild(id);
/// <inheritdoc />
public override SocketChannel GetChannel(ulong id)
=> State.GetChannel(id);
/// <summary>
/// Gets a generic channel from the cache or does a rest request if unavailable.
/// </summary>
/// <example>
/// <code language="cs" title="Example method">
/// var channel = await _client.GetChannelAsync(381889909113225237);
/// if (channel != null && channel is IMessageChannel msgChannel)
/// {
/// await msgChannel.SendMessageAsync($"{msgChannel} is created at {msgChannel.CreatedAt}");
/// }
/// </code>
/// </example>
/// <param name="id">The snowflake identifier of the channel (e.g. `381889909113225237`).</param>
/// <param name="options">The options to be used when sending the request.</param>
/// <returns>
/// A task that represents the asynchronous get operation. The task result contains the channel associated
/// with the snowflake identifier; <c>null</c> when the channel cannot be found.
/// </returns>
public async ValueTask<IChannel> GetChannelAsync(ulong id, RequestOptions options = null)
=> GetChannel(id) ?? (IChannel)await ClientHelper.GetChannelAsync(this, id, options).ConfigureAwait(false);
/// <summary>
/// Gets a user from the cache or does a rest request if unavailable.
/// </summary>
/// <example>
/// <code language="cs" title="Example method">
/// var user = await _client.GetUserAsync(168693960628371456);
/// if (user != null)
/// Console.WriteLine($"{user} is created at {user.CreatedAt}.";
/// </code>
/// </example>
/// <param name="id">The snowflake identifier of the user (e.g. `168693960628371456`).</param>
/// <param name="options">The options to be used when sending the request.</param>
/// <returns>
/// A task that represents the asynchronous get operation. The task result contains the user associated with
/// the snowflake identifier; <c>null</c> if the user is not found.
/// </returns>
public async ValueTask<IUser> GetUserAsync(ulong id, RequestOptions options = null)
=> await ClientHelper.GetUserAsync(this, id, options).ConfigureAwait(false);
/// <summary>
/// Clears all cached channels from the client.
/// </summary>
public void PurgeChannelCache() => State.PurgeAllChannels();
/// <summary>
/// Clears cached DM channels from the client.
/// </summary>
public void PurgeDMChannelCache() => RemoveDMChannels();
/// <inheritdoc />
public override SocketUser GetUser(ulong id)
=> State.GetUser(id);
/// <inheritdoc />
public override SocketUser GetUser(string username, string discriminator)
=> State.Users.FirstOrDefault(x => x.Discriminator == discriminator && x.Username == username);
/// <summary>
/// Clears cached users from the client.
/// </summary>
public void PurgeUserCache() => State.PurgeUsers();
internal SocketGlobalUser GetOrCreateUser(ClientState state, Discord.API.User model)
{
return state.GetOrAddUser(model.Id, x => SocketGlobalUser.Create(this, state, model));
}
internal SocketUser GetOrCreateTemporaryUser(ClientState state, Discord.API.User model)
{
return state.GetUser(model.Id) ?? (SocketUser)SocketUnknownUser.Create(this, state, model);
}
internal SocketGlobalUser GetOrCreateSelfUser(ClientState state, Discord.API.User model)
{
return state.GetOrAddUser(model.Id, x =>
{
var user = SocketGlobalUser.Create(this, state, model);
user.GlobalUser.AddRef();
user.Presence = new SocketPresence(UserStatus.Online, null, null);
return user;
});
}
internal void RemoveUser(ulong id)
=> State.RemoveUser(id);
/// <inheritdoc />
public override async ValueTask<IReadOnlyCollection<RestVoiceRegion>> GetVoiceRegionsAsync(RequestOptions options = null)
{
if (_parentClient == null)
{
if (_voiceRegions == null)
{
options = RequestOptions.CreateOrClone(options);
options.IgnoreState = true;
var voiceRegions = await ApiClient.GetVoiceRegionsAsync(options).ConfigureAwait(false);
_voiceRegions = voiceRegions.Select(x => RestVoiceRegion.Create(this, x)).ToImmutableDictionary(x => x.Id);
}
return _voiceRegions.ToReadOnlyCollection();
}
return await _parentClient.GetVoiceRegionsAsync().ConfigureAwait(false);
}
/// <inheritdoc />
public override async ValueTask<RestVoiceRegion> GetVoiceRegionAsync(string id, RequestOptions options = null)
{
if (_parentClient == null)
{
if (_voiceRegions == null)
await GetVoiceRegionsAsync().ConfigureAwait(false);
if (_voiceRegions.TryGetValue(id, out RestVoiceRegion region))
return region;
return null;
}
return await _parentClient.GetVoiceRegionAsync(id, options).ConfigureAwait(false);
}
/// <inheritdoc />
public override async Task DownloadUsersAsync(IEnumerable<IGuild> guilds)
{
if (ConnectionState == ConnectionState.Connected)
{
//Race condition leads to guilds being requested twice, probably okay
await ProcessUserDownloadsAsync(guilds.Select(x => GetGuild(x.Id)).Where(x => x != null)).ConfigureAwait(false);
}
}
private async Task ProcessUserDownloadsAsync(IEnumerable<SocketGuild> guilds)
{
var cachedGuilds = guilds.ToImmutableArray();
const short batchSize = 1;
ulong[] batchIds = new ulong[Math.Min(batchSize, cachedGuilds.Length)];
Task[] batchTasks = new Task[batchIds.Length];
int batchCount = (cachedGuilds.Length + (batchSize - 1)) / batchSize;
for (int i = 0, k = 0; i < batchCount; i++)
{
bool isLast = i == batchCount - 1;
int count = isLast ? (cachedGuilds.Length - (batchCount - 1) * batchSize) : batchSize;
for (int j = 0; j < count; j++, k++)
{
var guild = cachedGuilds[k];
batchIds[j] = guild.Id;
batchTasks[j] = guild.DownloaderPromise;
}
await ApiClient.SendRequestMembersAsync(batchIds).ConfigureAwait(false);
if (isLast && batchCount > 1)
await Task.WhenAll(batchTasks.Take(count)).ConfigureAwait(false);
else
await Task.WhenAll(batchTasks).ConfigureAwait(false);
}
}
/// <inheritdoc />
/// <example>
/// The following example sets the status of the current user to Do Not Disturb.
/// <code language="cs">
/// await client.SetStatusAsync(UserStatus.DoNotDisturb);
/// </code>
/// </example>
public override async Task SetStatusAsync(UserStatus status)
{
Status = status;
if (status == UserStatus.AFK)
_statusSince = DateTimeOffset.UtcNow;
else
_statusSince = null;
await SendStatusAsync().ConfigureAwait(false);
}
/// <inheritdoc />
/// <example>
/// <para>
/// The following example sets the activity of the current user to the specified game name.
/// <code language="cs">
/// await client.SetGameAsync("A Strange Game");
/// </code>
/// </para>
/// <para>
/// The following example sets the activity of the current user to a streaming status.
/// <code language="cs">
/// await client.SetGameAsync("Great Stream 10/10", "https://twitch.tv/MyAmazingStream1337", ActivityType.Streaming);
/// </code>
/// </para>
/// </example>
public override async Task SetGameAsync(string name, string streamUrl = null, ActivityType type = ActivityType.Playing)
{
if (!string.IsNullOrEmpty(streamUrl))
Activity = new StreamingGame(name, streamUrl);
else if (!string.IsNullOrEmpty(name))
Activity = new Game(name, type);
else
Activity = null;
await SendStatusAsync().ConfigureAwait(false);
}
/// <inheritdoc />
public override async Task SetActivityAsync(IActivity activity)
{
Activity = activity;
await SendStatusAsync().ConfigureAwait(false);
}
private async Task SendStatusAsync()
{
if (CurrentUser == null)
return;
var activities = _activity.IsSpecified ? ImmutableList.Create(_activity.Value) : null;
CurrentUser.Presence = new SocketPresence(Status, null, activities);
var presence = BuildCurrentStatus() ?? (UserStatus.Online, false, null, null);
await ApiClient.SendStatusUpdateAsync(
status: presence.Item1,
isAFK: presence.Item2,
since: presence.Item3,
game: presence.Item4).ConfigureAwait(false);
}
private (UserStatus, bool, long?, GameModel)? BuildCurrentStatus()
{
var status = _status;
var statusSince = _statusSince;
var activity = _activity;
if (status == null && !activity.IsSpecified)
return null;
GameModel game = null;
// Discord only accepts rich presence over RPC, don't even bother building a payload
if (activity.GetValueOrDefault() != null)
{
var gameModel = new GameModel();
if (activity.Value is RichGame)
throw new NotSupportedException("Outgoing Rich Presences are not supported via WebSocket.");
gameModel.Name = Activity.Name;
gameModel.Type = Activity.Type;
if (Activity is StreamingGame streamGame)
gameModel.StreamUrl = streamGame.Url;
game = gameModel;
}
else if (activity.IsSpecified)
game = null;
return (status ?? UserStatus.Online,
status == UserStatus.AFK,
statusSince != null ? _statusSince.Value.ToUnixTimeMilliseconds() : (long?)null,
game);
}
private async Task ProcessMessageAsync(GatewayOpCode opCode, int? seq, string type, object payload)
{
if (seq != null)
_lastSeq = seq.Value;
_lastMessageTime = Environment.TickCount;
try
{
switch (opCode)
{
case GatewayOpCode.Hello:
{
await _gatewayLogger.DebugAsync("Received Hello").ConfigureAwait(false);
var data = (payload as JToken).ToObject<HelloEvent>(_serializer);
_heartbeatTask = RunHeartbeatAsync(data.HeartbeatInterval, _connection.CancelToken);
}
break;
case GatewayOpCode.Heartbeat:
{
await _gatewayLogger.DebugAsync("Received Heartbeat").ConfigureAwait(false);
await ApiClient.SendHeartbeatAsync(_lastSeq).ConfigureAwait(false);
}
break;
case GatewayOpCode.HeartbeatAck:
{
await _gatewayLogger.DebugAsync("Received HeartbeatAck").ConfigureAwait(false);
if (_heartbeatTimes.TryDequeue(out long time))
{
int latency = (int)(Environment.TickCount - time);
int before = Latency;
Latency = latency;
await TimedInvokeAsync(_latencyUpdatedEvent, nameof(LatencyUpdated), before, latency).ConfigureAwait(false);
}
}
break;
case GatewayOpCode.InvalidSession:
{
await _gatewayLogger.DebugAsync("Received InvalidSession").ConfigureAwait(false);
await _gatewayLogger.WarningAsync("Failed to resume previous session").ConfigureAwait(false);
_sessionId = null;
_lastSeq = 0;
if (_shardedClient != null)
{
await _shardedClient.AcquireIdentifyLockAsync(ShardId, _connection.CancelToken).ConfigureAwait(false);
try
{
await ApiClient.SendIdentifyAsync(shardID: ShardId, totalShards: TotalShards, gatewayIntents: _gatewayIntents, presence: BuildCurrentStatus()).ConfigureAwait(false);
}
finally
{
_shardedClient.ReleaseIdentifyLock();
}
}
else
await ApiClient.SendIdentifyAsync(shardID: ShardId, totalShards: TotalShards, gatewayIntents: _gatewayIntents, presence: BuildCurrentStatus()).ConfigureAwait(false);
}
break;
case GatewayOpCode.Reconnect:
{
await _gatewayLogger.DebugAsync("Received Reconnect").ConfigureAwait(false);
_connection.Error(new GatewayReconnectException("Server requested a reconnect"));
}
break;
case GatewayOpCode.Dispatch:
switch (type)
{
//Connection
case "READY":
{
try
{
await _gatewayLogger.DebugAsync("Received Dispatch (READY)").ConfigureAwait(false);
var data = (payload as JToken).ToObject<ReadyEvent>(_serializer);
var state = new ClientState(data.Guilds.Length, data.PrivateChannels.Length);
var currentUser = SocketSelfUser.Create(this, state, data.User);
var activities = _activity.IsSpecified ? ImmutableList.Create(_activity.Value) : null;
currentUser.Presence = new SocketPresence(Status, null, activities);
ApiClient.CurrentUserId = currentUser.Id;
Rest.CurrentUser = RestSelfUser.Create(this, data.User);
int unavailableGuilds = 0;
for (int i = 0; i < data.Guilds.Length; i++)
{
var model = data.Guilds[i];
var guild = AddGuild(model, state);
if (!guild.IsAvailable)
unavailableGuilds++;
else
await GuildAvailableAsync(guild).ConfigureAwait(false);
}
for (int i = 0; i < data.PrivateChannels.Length; i++)
AddPrivateChannel(data.PrivateChannels[i], state);
_sessionId = data.SessionId;
_unavailableGuildCount = unavailableGuilds;
CurrentUser = currentUser;
State = state;
}
catch (Exception ex)
{
_connection.CriticalError(new Exception("Processing READY failed", ex));
return;
}
_lastGuildAvailableTime = Environment.TickCount;
_guildDownloadTask = WaitForGuildsAsync(_connection.CancelToken, _gatewayLogger)
.ContinueWith(async x =>
{
if (x.IsFaulted)
{
_connection.Error(x.Exception);
return;
}
else if (_connection.CancelToken.IsCancellationRequested)
return;
if (BaseConfig.AlwaysDownloadUsers)
_ = DownloadUsersAsync(Guilds.Where(x => x.IsAvailable && !x.HasAllMembers));
await TimedInvokeAsync(_readyEvent, nameof(Ready)).ConfigureAwait(false);
await _gatewayLogger.InfoAsync("Ready").ConfigureAwait(false);
});
_ = _connection.CompleteAsync();
}
break;
case "RESUMED":
{
await _gatewayLogger.DebugAsync("Received Dispatch (RESUMED)").ConfigureAwait(false);
_ = _connection.CompleteAsync();
//Notify the client that these guilds are available again
foreach (var guild in State.Guilds)
{
if (guild.IsAvailable)
await GuildAvailableAsync(guild).ConfigureAwait(false);
}
await _gatewayLogger.InfoAsync("Resumed previous session").ConfigureAwait(false);
}
break;
//Guilds
case "GUILD_CREATE":
{
var data = (payload as JToken).ToObject<ExtendedGuild>(_serializer);
if (data.Unavailable == false)
{
type = "GUILD_AVAILABLE";
_lastGuildAvailableTime = Environment.TickCount;
await _gatewayLogger.DebugAsync("Received Dispatch (GUILD_AVAILABLE)").ConfigureAwait(false);
var guild = State.GetGuild(data.Id);
if (guild != null)
{
guild.Update(State, data);
if (_unavailableGuildCount != 0)
_unavailableGuildCount--;
await GuildAvailableAsync(guild).ConfigureAwait(false);
if (guild.DownloadedMemberCount >= guild.MemberCount && !guild.DownloaderPromise.IsCompleted)
{
guild.CompleteDownloadUsers();
await TimedInvokeAsync(_guildMembersDownloadedEvent, nameof(GuildMembersDownloaded), guild).ConfigureAwait(false);
}
}
else
{
await UnknownGuildAsync(type, data.Id).ConfigureAwait(false);
return;
}
}
else
{
await _gatewayLogger.DebugAsync("Received Dispatch (GUILD_CREATE)").ConfigureAwait(false);
var guild = AddGuild(data, State);
if (guild != null)
{
await TimedInvokeAsync(_joinedGuildEvent, nameof(JoinedGuild), guild).ConfigureAwait(false);
await GuildAvailableAsync(guild).ConfigureAwait(false);
}
else
{
await UnknownGuildAsync(type, data.Id).ConfigureAwait(false);
return;
}
}
}
break;
case "GUILD_UPDATE":
{
await _gatewayLogger.DebugAsync("Received Dispatch (GUILD_UPDATE)").ConfigureAwait(false);
var data = (payload as JToken).ToObject<API.Guild>(_serializer);
var guild = State.GetGuild(data.Id);
if (guild != null)
{
var before = guild.Clone();
guild.Update(State, data);
await TimedInvokeAsync(_guildUpdatedEvent, nameof(GuildUpdated), before, guild).ConfigureAwait(false);
}
else
{
await UnknownGuildAsync(type, data.Id).ConfigureAwait(false);
return;
}
}
break;
case "GUILD_EMOJIS_UPDATE":
{
await _gatewayLogger.DebugAsync("Received Dispatch (GUILD_EMOJIS_UPDATE)").ConfigureAwait(false);
var data = (payload as JToken).ToObject<API.Gateway.GuildEmojiUpdateEvent>(_serializer);
var guild = State.GetGuild(data.GuildId);
if (guild != null)
{
var before = guild.Clone();
guild.Update(State, data);
await TimedInvokeAsync(_guildUpdatedEvent, nameof(GuildUpdated), before, guild).ConfigureAwait(false);
}
else
{
await UnknownGuildAsync(type, data.GuildId).ConfigureAwait(false);
return;
}
}
break;
case "GUILD_SYNC":
{
await _gatewayLogger.DebugAsync("Ignored Dispatch (GUILD_SYNC)").ConfigureAwait(false);
/*await _gatewayLogger.DebugAsync("Received Dispatch (GUILD_SYNC)").ConfigureAwait(false); //TODO remove? userbot related
var data = (payload as JToken).ToObject<GuildSyncEvent>(_serializer);
var guild = State.GetGuild(data.Id);
if (guild != null)
{
var before = guild.Clone();
guild.Update(State, data);
//This is treated as an extension of GUILD_AVAILABLE
_unavailableGuildCount--;
_lastGuildAvailableTime = Environment.TickCount;
await GuildAvailableAsync(guild).ConfigureAwait(false);
await TimedInvokeAsync(_guildUpdatedEvent, nameof(GuildUpdated), before, guild).ConfigureAwait(false);
}
else
{
await UnknownGuildAsync(type, data.Id).ConfigureAwait(false);
return;
}*/
}
break;
case "GUILD_DELETE":
{
var data = (payload as JToken).ToObject<ExtendedGuild>(_serializer);
if (data.Unavailable == true)
{
type = "GUILD_UNAVAILABLE";
await _gatewayLogger.DebugAsync("Received Dispatch (GUILD_UNAVAILABLE)").ConfigureAwait(false);
var guild = State.GetGuild(data.Id);
if (guild != null)
{
await GuildUnavailableAsync(guild).ConfigureAwait(false);
_unavailableGuildCount++;
}
else
{
await UnknownGuildAsync(type, data.Id).ConfigureAwait(false);
return;
}
}
else
{
await _gatewayLogger.DebugAsync("Received Dispatch (GUILD_DELETE)").ConfigureAwait(false);
var guild = RemoveGuild(data.Id);
if (guild != null)
{
await GuildUnavailableAsync(guild).ConfigureAwait(false);
await TimedInvokeAsync(_leftGuildEvent, nameof(LeftGuild), guild).ConfigureAwait(false);
(guild as IDisposable).Dispose();
}
else
{
await UnknownGuildAsync(type, data.Id).ConfigureAwait(false);
return;
}
}
}
break;
//Channels
case "CHANNEL_CREATE":
{
await _gatewayLogger.DebugAsync("Received Dispatch (CHANNEL_CREATE)").ConfigureAwait(false);
var data = (payload as JToken).ToObject<API.Channel>(_serializer);
SocketChannel channel = null;
if (data.GuildId.IsSpecified)
{
var guild = State.GetGuild(data.GuildId.Value);
if (guild != null)
{
channel = guild.AddChannel(State, data);
if (!guild.IsSynced)
{
await UnsyncedGuildAsync(type, guild.Id).ConfigureAwait(false);
return;
}
}
else
{
await UnknownGuildAsync(type, data.GuildId.Value).ConfigureAwait(false);
return;
}
}
else
{
channel = State.GetChannel(data.Id);
if (channel != null)
return; //Discord may send duplicate CHANNEL_CREATEs for DMs
channel = AddPrivateChannel(data, State) as SocketChannel;
}
if (channel != null)
await TimedInvokeAsync(_channelCreatedEvent, nameof(ChannelCreated), channel).ConfigureAwait(false);
}
break;
case "CHANNEL_UPDATE":
{
await _gatewayLogger.DebugAsync("Received Dispatch (CHANNEL_UPDATE)").ConfigureAwait(false);
var data = (payload as JToken).ToObject<API.Channel>(_serializer);
var channel = State.GetChannel(data.Id);
if (channel != null)
{
var before = channel.Clone();
channel.Update(State, data);
var guild = (channel as SocketGuildChannel)?.Guild;
if (!(guild?.IsSynced ?? true))
{
await UnsyncedGuildAsync(type, guild.Id).ConfigureAwait(false);
return;
}
await TimedInvokeAsync(_channelUpdatedEvent, nameof(ChannelUpdated), before, channel).ConfigureAwait(false);
}
else
{
await UnknownChannelAsync(type, data.Id).ConfigureAwait(false);
return;
}
}
break;
case "CHANNEL_DELETE":
{
await _gatewayLogger.DebugAsync("Received Dispatch (CHANNEL_DELETE)").ConfigureAwait(false);
SocketChannel channel = null;
var data = (payload as JToken).ToObject<API.Channel>(_serializer);
if (data.GuildId.IsSpecified)
{
var guild = State.GetGuild(data.GuildId.Value);
if (guild != null)
{
channel = guild.RemoveChannel(State, data.Id);
if (!guild.IsSynced)
{
await UnsyncedGuildAsync(type, guild.Id).ConfigureAwait(false);
return;
}
}
else
{
await UnknownGuildAsync(type, data.GuildId.Value).ConfigureAwait(false);
return;
}
}
else
channel = RemovePrivateChannel(data.Id) as SocketChannel;
if (channel != null)
await TimedInvokeAsync(_channelDestroyedEvent, nameof(ChannelDestroyed), channel).ConfigureAwait(false);
else
{
await UnknownChannelAsync(type, data.Id, data.GuildId.GetValueOrDefault(0)).ConfigureAwait(false);
return;
}
}
break;
//Members
case "GUILD_MEMBER_ADD":
{
await _gatewayLogger.DebugAsync("Received Dispatch (GUILD_MEMBER_ADD)").ConfigureAwait(false);
var data = (payload as JToken).ToObject<GuildMemberAddEvent>(_serializer);
var guild = State.GetGuild(data.GuildId);
if (guild != null)
{
var user = guild.AddOrUpdateUser(data);
guild.MemberCount++;
if (!guild.IsSynced)
{
await UnsyncedGuildAsync(type, guild.Id).ConfigureAwait(false);
return;
}
await TimedInvokeAsync(_userJoinedEvent, nameof(UserJoined), user).ConfigureAwait(false);
}
else
{
await UnknownGuildAsync(type, data.GuildId).ConfigureAwait(false);
return;
}
}
break;
case "GUILD_MEMBER_UPDATE":
{
await _gatewayLogger.DebugAsync("Received Dispatch (GUILD_MEMBER_UPDATE)").ConfigureAwait(false);
var data = (payload as JToken).ToObject<GuildMemberUpdateEvent>(_serializer);
var guild = State.GetGuild(data.GuildId);
if (guild != null)
{
var user = guild.GetUser(data.User.Id);
if (!guild.IsSynced)
{
await UnsyncedGuildAsync(type, guild.Id).ConfigureAwait(false);
return;
}
if (user != null)
{
var globalBefore = user.GlobalUser.Clone();
if (user.GlobalUser.Update(State, data.User))
{
//Global data was updated, trigger UserUpdated
await TimedInvokeAsync(_userUpdatedEvent, nameof(UserUpdated), globalBefore, user).ConfigureAwait(false);
}
var before = user.Clone();
user.Update(State, data);
var cacheableBefore = new Cacheable<SocketGuildUser, ulong>(before, user.Id, true, () => Task.FromResult((SocketGuildUser)null));
await TimedInvokeAsync(_guildMemberUpdatedEvent, nameof(GuildMemberUpdated), cacheableBefore, user).ConfigureAwait(false);
}
else
{
user = guild.AddOrUpdateUser(data);
var cacheableBefore = new Cacheable<SocketGuildUser, ulong>(null, user.Id, false, () => Task.FromResult((SocketGuildUser)null));
await TimedInvokeAsync(_guildMemberUpdatedEvent, nameof(GuildMemberUpdated), cacheableBefore, user).ConfigureAwait(false);