/
SocketGuild.cs
1134 lines (1071 loc) · 53.2 KB
/
SocketGuild.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.Audio;
using Discord.Rest;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using ChannelModel = Discord.API.Channel;
using EmojiUpdateModel = Discord.API.Gateway.GuildEmojiUpdateEvent;
using ExtendedModel = Discord.API.Gateway.ExtendedGuild;
using GuildSyncModel = Discord.API.Gateway.GuildSyncEvent;
using MemberModel = Discord.API.GuildMember;
using Model = Discord.API.Guild;
using PresenceModel = Discord.API.Presence;
using RoleModel = Discord.API.Role;
using UserModel = Discord.API.User;
using VoiceStateModel = Discord.API.VoiceState;
namespace Discord.WebSocket
{
/// <summary>
/// Represents a WebSocket-based guild object.
/// </summary>
[DebuggerDisplay(@"{DebuggerDisplay,nq}")]
public class SocketGuild : SocketEntity<ulong>, IGuild
{
private readonly SemaphoreSlim _audioLock;
private TaskCompletionSource<bool> _syncPromise, _downloaderPromise;
private TaskCompletionSource<AudioClient> _audioConnectPromise;
private ConcurrentHashSet<ulong> _channels;
private ConcurrentDictionary<ulong, SocketGuildUser> _members;
private ConcurrentDictionary<ulong, SocketRole> _roles;
private ConcurrentDictionary<ulong, SocketVoiceState> _voiceStates;
private ImmutableArray<GuildEmote> _emotes;
private ImmutableArray<string> _features;
private AudioClient _audioClient;
/// <inheritdoc />
public string Name { get; private set; }
/// <inheritdoc />
public int AFKTimeout { get; private set; }
/// <inheritdoc />
public bool IsEmbeddable { get; private set; }
/// <inheritdoc />
public VerificationLevel VerificationLevel { get; private set; }
/// <inheritdoc />
public MfaLevel MfaLevel { get; private set; }
/// <inheritdoc />
public DefaultMessageNotifications DefaultMessageNotifications { get; private set; }
/// <inheritdoc />
public ExplicitContentFilterLevel ExplicitContentFilter { get; private set; }
/// <summary>
/// Gets the number of members.
/// </summary>
/// <remarks>
/// This property retrieves the number of members returned by Discord.
/// <note type="tip">
/// <para>
/// Due to how this property is returned by Discord instead of relying on the WebSocket cache, the
/// number here is the most accurate in terms of counting the number of users within this guild.
/// </para>
/// <para>
/// Use this instead of enumerating the count of the
/// <see cref="Discord.WebSocket.SocketGuild.Users" /> collection, as you may see discrepancy
/// between that and this property.
/// </para>
/// </note>
/// </remarks>
public int MemberCount { get; internal set; }
/// <summary> Gets the number of members downloaded to the local guild cache. </summary>
public int DownloadedMemberCount { get; private set; }
internal bool IsAvailable { get; private set; }
/// <summary> Indicates whether the client is connected to this guild. </summary>
public bool IsConnected { get; internal set; }
/// <inheritdoc />
public ulong? ApplicationId { get; internal set; }
internal ulong? AFKChannelId { get; private set; }
internal ulong? EmbedChannelId { get; private set; }
internal ulong? SystemChannelId { get; private set; }
/// <inheritdoc />
public ulong OwnerId { get; private set; }
/// <summary> Gets the user that owns this guild. </summary>
public SocketGuildUser Owner => GetUser(OwnerId);
/// <inheritdoc />
public string VoiceRegionId { get; private set; }
/// <inheritdoc />
public string IconId { get; private set; }
/// <inheritdoc />
public string SplashId { get; private set; }
/// <inheritdoc />
public DateTimeOffset CreatedAt => SnowflakeUtils.FromSnowflake(Id);
/// <inheritdoc />
public string IconUrl => CDN.GetGuildIconUrl(Id, IconId);
/// <inheritdoc />
public string SplashUrl => CDN.GetGuildSplashUrl(Id, SplashId);
/// <summary> Indicates whether the client has all the members downloaded to the local guild cache. </summary>
public bool HasAllMembers => MemberCount == DownloadedMemberCount;// _downloaderPromise.Task.IsCompleted;
/// <summary> Indicates whether the guild cache is synced to this guild. </summary>
public bool IsSynced => _syncPromise.Task.IsCompleted;
public Task SyncPromise => _syncPromise.Task;
public Task DownloaderPromise => _downloaderPromise.Task;
/// <summary>
/// Gets the <see cref="IAudioClient" /> associated with this guild.
/// </summary>
public IAudioClient AudioClient => _audioClient;
/// <summary>
/// Gets the default channel in this guild.
/// </summary>
/// <remarks>
/// This property retrieves the first viewable text channel for this guild.
/// <note type="warning">
/// This channel does not guarantee the user can send message to it, as it only looks for the first viewable
/// text channel.
/// </note>
/// </remarks>
/// <returns>
/// A <see cref="SocketTextChannel"/> representing the first viewable channel that the user has access to.
/// </returns>
public SocketTextChannel DefaultChannel => TextChannels
.Where(c => CurrentUser.GetPermissions(c).ViewChannel)
.OrderBy(c => c.Position)
.FirstOrDefault();
/// <summary>
/// Gets the AFK voice channel in this guild.
/// </summary>
/// <returns>
/// A <see cref="SocketVoiceChannel" /> that the AFK users will be moved to after they have idled for too
/// long; <c>null</c> if none is set.
/// </returns>
public SocketVoiceChannel AFKChannel
{
get
{
var id = AFKChannelId;
return id.HasValue ? GetVoiceChannel(id.Value) : null;
}
}
/// <summary>
/// Gets the embed channel (i.e. the channel set in the guild's widget settings) in this guild.
/// </summary>
/// <returns>
/// A channel set within the server's widget settings; <c>null</c> if none is set.
/// </returns>
public SocketGuildChannel EmbedChannel
{
get
{
var id = EmbedChannelId;
return id.HasValue ? GetChannel(id.Value) : null;
}
}
/// <summary>
/// Gets the system channel where randomized welcome messages are sent in this guild.
/// </summary>
/// <returns>
/// A text channel where randomized welcome messages will be sent to; <c>null</c> if none is set.
/// </returns>
public SocketTextChannel SystemChannel
{
get
{
var id = SystemChannelId;
return id.HasValue ? GetTextChannel(id.Value) : null;
}
}
/// <summary>
/// Gets a collection of all text channels in this guild.
/// </summary>
/// <returns>
/// A read-only collection of message channels found within this guild.
/// </returns>
public IReadOnlyCollection<SocketTextChannel> TextChannels
=> Channels.OfType<SocketTextChannel>().ToImmutableArray();
/// <summary>
/// Gets a collection of all voice channels in this guild.
/// </summary>
/// <returns>
/// A read-only collection of voice channels found within this guild.
/// </returns>
public IReadOnlyCollection<SocketVoiceChannel> VoiceChannels
=> Channels.OfType<SocketVoiceChannel>().ToImmutableArray();
/// <summary>
/// Gets a collection of all category channels in this guild.
/// </summary>
/// <returns>
/// A read-only collection of category channels found within this guild.
/// </returns>
public IReadOnlyCollection<SocketCategoryChannel> CategoryChannels
=> Channels.OfType<SocketCategoryChannel>().ToImmutableArray();
/// <summary>
/// Gets the current logged-in user.
/// </summary>
public SocketGuildUser CurrentUser => _members.TryGetValue(Discord.CurrentUser.Id, out SocketGuildUser member) ? member : null;
/// <summary>
/// Gets the built-in role containing all users in this guild.
/// </summary>
/// <returns>
/// A role object that represents an <c>@everyone</c> role in this guild.
/// </returns>
public SocketRole EveryoneRole => GetRole(Id);
/// <summary>
/// Gets a collection of all channels in this guild.
/// </summary>
/// <returns>
/// A read-only collection of generic channels found within this guild.
/// </returns>
public IReadOnlyCollection<SocketGuildChannel> Channels
{
get
{
var channels = _channels;
var state = Discord.State;
return channels.Select(x => state.GetChannel(x) as SocketGuildChannel).Where(x => x != null).ToReadOnlyCollection(channels);
}
}
/// <inheritdoc />
public IReadOnlyCollection<GuildEmote> Emotes => _emotes;
/// <inheritdoc />
public IReadOnlyCollection<string> Features => _features;
/// <summary>
/// Gets a collection of users in this guild.
/// </summary>
/// <remarks>
/// This property retrieves all users found within this guild.
/// <note type="warning">
/// <para>
/// This property may not always return all the members for large guilds (i.e. guilds containing
/// 100+ users). If you are simply looking to get the number of users present in this guild,
/// consider using <see cref="MemberCount"/> instead.
/// </para>
/// <para>
/// Otherwise, you may need to enable <see cref="DiscordSocketConfig.AlwaysDownloadUsers"/> to fetch
/// the full user list upon startup, or use <see cref="DownloadUsersAsync"/> to manually download
/// the users.
/// </para>
/// </note>
/// </remarks>
/// <returns>
/// A collection of guild users found within this guild.
/// </returns>
public IReadOnlyCollection<SocketGuildUser> Users => _members.ToReadOnlyCollection();
/// <summary>
/// Gets a collection of all roles in this guild.
/// </summary>
/// <returns>
/// A read-only collection of roles found within this guild.
/// </returns>
public IReadOnlyCollection<SocketRole> Roles => _roles.ToReadOnlyCollection();
internal SocketGuild(DiscordSocketClient client, ulong id)
: base(client, id)
{
_audioLock = new SemaphoreSlim(1, 1);
_emotes = ImmutableArray.Create<GuildEmote>();
_features = ImmutableArray.Create<string>();
}
internal static SocketGuild Create(DiscordSocketClient discord, ClientState state, ExtendedModel model)
{
var entity = new SocketGuild(discord, model.Id);
entity.Update(state, model);
return entity;
}
internal void Update(ClientState state, ExtendedModel model)
{
IsAvailable = !(model.Unavailable ?? false);
if (!IsAvailable)
{
if (_channels == null)
_channels = new ConcurrentHashSet<ulong>();
if (_members == null)
_members = new ConcurrentDictionary<ulong, SocketGuildUser>();
if (_roles == null)
_roles = new ConcurrentDictionary<ulong, SocketRole>();
/*if (Emojis == null)
_emojis = ImmutableArray.Create<Emoji>();
if (Features == null)
_features = ImmutableArray.Create<string>();*/
_syncPromise = new TaskCompletionSource<bool>();
_downloaderPromise = new TaskCompletionSource<bool>();
return;
}
Update(state, model as Model);
var channels = new ConcurrentHashSet<ulong>(ConcurrentHashSet.DefaultConcurrencyLevel, (int)(model.Channels.Length * 1.05));
{
for (int i = 0; i < model.Channels.Length; i++)
{
var channel = SocketGuildChannel.Create(this, state, model.Channels[i]);
state.AddChannel(channel);
channels.TryAdd(channel.Id);
}
}
_channels = channels;
var members = new ConcurrentDictionary<ulong, SocketGuildUser>(ConcurrentHashSet.DefaultConcurrencyLevel, (int)(model.Members.Length * 1.05));
{
for (int i = 0; i < model.Members.Length; i++)
{
var member = SocketGuildUser.Create(this, state, model.Members[i]);
members.TryAdd(member.Id, member);
}
DownloadedMemberCount = members.Count;
for (int i = 0; i < model.Presences.Length; i++)
{
if (members.TryGetValue(model.Presences[i].User.Id, out SocketGuildUser member))
member.Update(state, model.Presences[i], true);
}
}
_members = members;
MemberCount = model.MemberCount;
var voiceStates = new ConcurrentDictionary<ulong, SocketVoiceState>(ConcurrentHashSet.DefaultConcurrencyLevel, (int)(model.VoiceStates.Length * 1.05));
{
for (int i = 0; i < model.VoiceStates.Length; i++)
{
SocketVoiceChannel channel = null;
if (model.VoiceStates[i].ChannelId.HasValue)
channel = state.GetChannel(model.VoiceStates[i].ChannelId.Value) as SocketVoiceChannel;
var voiceState = SocketVoiceState.Create(channel, model.VoiceStates[i]);
voiceStates.TryAdd(model.VoiceStates[i].UserId, voiceState);
}
}
_voiceStates = voiceStates;
_syncPromise = new TaskCompletionSource<bool>();
_downloaderPromise = new TaskCompletionSource<bool>();
var _ = _syncPromise.TrySetResultAsync(true);
/*if (!model.Large)
_ = _downloaderPromise.TrySetResultAsync(true);*/
}
internal void Update(ClientState state, Model model)
{
AFKChannelId = model.AFKChannelId;
EmbedChannelId = model.EmbedChannelId;
SystemChannelId = model.SystemChannelId;
AFKTimeout = model.AFKTimeout;
IsEmbeddable = model.EmbedEnabled;
IconId = model.Icon;
Name = model.Name;
OwnerId = model.OwnerId;
VoiceRegionId = model.Region;
SplashId = model.Splash;
VerificationLevel = model.VerificationLevel;
MfaLevel = model.MfaLevel;
DefaultMessageNotifications = model.DefaultMessageNotifications;
ExplicitContentFilter = model.ExplicitContentFilter;
ApplicationId = model.ApplicationId;
if (model.Emojis != null)
{
var emojis = ImmutableArray.CreateBuilder<GuildEmote>(model.Emojis.Length);
for (int i = 0; i < model.Emojis.Length; i++)
emojis.Add(model.Emojis[i].ToEntity());
_emotes = emojis.ToImmutable();
}
else
_emotes = ImmutableArray.Create<GuildEmote>();
if (model.Features != null)
_features = model.Features.ToImmutableArray();
else
_features = ImmutableArray.Create<string>();
var roles = new ConcurrentDictionary<ulong, SocketRole>(ConcurrentHashSet.DefaultConcurrencyLevel, (int)(model.Roles.Length * 1.05));
if (model.Roles != null)
{
for (int i = 0; i < model.Roles.Length; i++)
{
var role = SocketRole.Create(this, state, model.Roles[i]);
roles.TryAdd(role.Id, role);
}
}
_roles = roles;
}
internal void Update(ClientState state, GuildSyncModel model)
{
var members = new ConcurrentDictionary<ulong, SocketGuildUser>(ConcurrentHashSet.DefaultConcurrencyLevel, (int)(model.Members.Length * 1.05));
{
for (int i = 0; i < model.Members.Length; i++)
{
var member = SocketGuildUser.Create(this, state, model.Members[i]);
members.TryAdd(member.Id, member);
}
DownloadedMemberCount = members.Count;
for (int i = 0; i < model.Presences.Length; i++)
{
if (members.TryGetValue(model.Presences[i].User.Id, out SocketGuildUser member))
member.Update(state, model.Presences[i], true);
}
}
_members = members;
var _ = _syncPromise.TrySetResultAsync(true);
/*if (!model.Large)
_ = _downloaderPromise.TrySetResultAsync(true);*/
}
internal void Update(ClientState state, EmojiUpdateModel model)
{
var emotes = ImmutableArray.CreateBuilder<GuildEmote>(model.Emojis.Length);
for (int i = 0; i < model.Emojis.Length; i++)
emotes.Add(model.Emojis[i].ToEntity());
_emotes = emotes.ToImmutable();
}
//General
/// <inheritdoc />
public Task DeleteAsync(RequestOptions options = null)
=> GuildHelper.DeleteAsync(this, Discord, options);
/// <inheritdoc />
/// <exception cref="ArgumentNullException"><paramref name="func"/> is <c>null</c>.</exception>
public Task ModifyAsync(Action<GuildProperties> func, RequestOptions options = null)
=> GuildHelper.ModifyAsync(this, Discord, func, options);
/// <inheritdoc />
/// <exception cref="ArgumentNullException"><paramref name="func"/> is <c>null</c>.</exception>
public Task ModifyEmbedAsync(Action<GuildEmbedProperties> func, RequestOptions options = null)
=> GuildHelper.ModifyEmbedAsync(this, Discord, func, options);
/// <inheritdoc />
public Task ReorderChannelsAsync(IEnumerable<ReorderChannelProperties> args, RequestOptions options = null)
=> GuildHelper.ReorderChannelsAsync(this, Discord, args, options);
/// <inheritdoc />
public Task ReorderRolesAsync(IEnumerable<ReorderRoleProperties> args, RequestOptions options = null)
=> GuildHelper.ReorderRolesAsync(this, Discord, args, options);
/// <inheritdoc />
public Task LeaveAsync(RequestOptions options = null)
=> GuildHelper.LeaveAsync(this, Discord, options);
//Bans
/// <summary>
/// Gets a collection of all users banned in this guild.
/// </summary>
/// <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 a read-only collection of
/// ban objects that this guild currently possesses, with each object containing the user banned and reason
/// behind the ban.
/// </returns>
public Task<IReadOnlyCollection<RestBan>> GetBansAsync(RequestOptions options = null)
=> GuildHelper.GetBansAsync(this, Discord, options);
/// <summary>
/// Gets a ban object for a banned user.
/// </summary>
/// <param name="user">The banned user.</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 a ban object, which
/// contains the user information and the reason for the ban; <c>null</c> if the ban entry cannot be found.
/// </returns>
public Task<RestBan> GetBanAsync(IUser user, RequestOptions options = null)
=> GuildHelper.GetBanAsync(this, Discord, user.Id, options);
/// <summary>
/// Gets a ban object for a banned user.
/// </summary>
/// <param name="userId">The snowflake identifier for the banned user.</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 a ban object, which
/// contains the user information and the reason for the ban; <c>null</c> if the ban entry cannot be found.
/// </returns>
public Task<RestBan> GetBanAsync(ulong userId, RequestOptions options = null)
=> GuildHelper.GetBanAsync(this, Discord, userId, options);
/// <inheritdoc />
public Task AddBanAsync(IUser user, int pruneDays = 0, string reason = null, RequestOptions options = null)
=> GuildHelper.AddBanAsync(this, Discord, user.Id, pruneDays, reason, options);
/// <inheritdoc />
public Task AddBanAsync(ulong userId, int pruneDays = 0, string reason = null, RequestOptions options = null)
=> GuildHelper.AddBanAsync(this, Discord, userId, pruneDays, reason, options);
/// <inheritdoc />
public Task RemoveBanAsync(IUser user, RequestOptions options = null)
=> GuildHelper.RemoveBanAsync(this, Discord, user.Id, options);
/// <inheritdoc />
public Task RemoveBanAsync(ulong userId, RequestOptions options = null)
=> GuildHelper.RemoveBanAsync(this, Discord, userId, options);
//Channels
/// <summary>
/// Gets a channel in this guild.
/// </summary>
/// <param name="id">The snowflake identifier for the channel.</param>
/// <returns>
/// A generic channel associated with the specified <paramref name="id" />; <c>null</c> if none is found.
/// </returns>
public SocketGuildChannel GetChannel(ulong id)
{
var channel = Discord.State.GetChannel(id) as SocketGuildChannel;
if (channel?.Guild.Id == Id)
return channel;
return null;
}
/// <summary>
/// Gets a text channel in this guild.
/// </summary>
/// <param name="id">The snowflake identifier for the text channel.</param>
/// <returns>
/// A text channel associated with the specified <paramref name="id" />; <c>null</c> if none is found.
/// </returns>
public SocketTextChannel GetTextChannel(ulong id)
=> GetChannel(id) as SocketTextChannel;
/// <summary>
/// Gets a voice channel in this guild.
/// </summary>
/// <param name="id">The snowflake identifier for the voice channel.</param>
/// <returns>
/// A voice channel associated with the specified <paramref name="id" />; <c>null</c> if none is found.
/// </returns>
public SocketVoiceChannel GetVoiceChannel(ulong id)
=> GetChannel(id) as SocketVoiceChannel;
/// <summary>
/// Creates a new text channel in this guild.
/// </summary>
/// <example>
/// The following example creates a new text channel under an existing category named <c>Wumpus</c> with a set topic.
/// <code lang="cs">
/// var categories = await guild.GetCategoriesAsync();
/// var targetCategory = categories.FirstOrDefault(x => x.Name == "wumpus");
/// if (targetCategory == null) return;
/// await Context.Guild.CreateTextChannelAsync(name, x =>
/// {
/// x.CategoryId = targetCategory.Id;
/// x.Topic = $"This channel was created at {DateTimeOffset.UtcNow} by {user}.";
/// });
/// </code>
/// </example>
/// <param name="name">The new name for the text channel.</param>
/// <param name="func">The delegate containing the properties to be applied to the channel upon its creation.</param>
/// <param name="options">The options to be used when sending the request.</param>
/// <returns>
/// A task that represents the asynchronous creation operation. The task result contains the newly created
/// text channel.
/// </returns>
public Task<RestTextChannel> CreateTextChannelAsync(string name, Action<TextChannelProperties> func = null, RequestOptions options = null)
=> GuildHelper.CreateTextChannelAsync(this, Discord, name, options, func);
/// <summary>
/// Creates a new voice channel in this guild.
/// </summary>
/// <param name="name">The new name for the voice channel.</param>
/// <param name="func">The delegate containing the properties to be applied to the channel upon its creation.</param>
/// <param name="options">The options to be used when sending the request.</param>
/// <exception cref="ArgumentNullException"><paramref name="name"/> is <c>null</c>.</exception>
/// <returns>
/// A task that represents the asynchronous creation operation. The task result contains the newly created
/// voice channel.
/// </returns>
public Task<RestVoiceChannel> CreateVoiceChannelAsync(string name, Action<VoiceChannelProperties> func = null, RequestOptions options = null)
=> GuildHelper.CreateVoiceChannelAsync(this, Discord, name, options, func);
/// <summary>
/// Creates a new channel category in this guild.
/// </summary>
/// <param name="name">The new name for the category.</param>
/// <param name="func">The delegate containing the properties to be applied to the channel upon its creation.</param>
/// <param name="options">The options to be used when sending the request.</param>
/// <exception cref="ArgumentNullException"><paramref name="name"/> is <c>null</c>.</exception>
/// <returns>
/// A task that represents the asynchronous creation operation. The task result contains the newly created
/// category channel.
/// </returns>
public Task<RestCategoryChannel> CreateCategoryChannelAsync(string name, Action<GuildChannelProperties> func = null, RequestOptions options = null)
=> GuildHelper.CreateCategoryChannelAsync(this, Discord, name, options, func);
internal SocketGuildChannel AddChannel(ClientState state, ChannelModel model)
{
var channel = SocketGuildChannel.Create(this, state, model);
_channels.TryAdd(model.Id);
state.AddChannel(channel);
return channel;
}
internal SocketGuildChannel RemoveChannel(ClientState state, ulong id)
{
if (_channels.TryRemove(id))
return state.RemoveChannel(id) as SocketGuildChannel;
return null;
}
//Voice Regions
/// <summary>
/// Gets a collection of all the voice regions this guild can access.
/// </summary>
/// <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 a read-only collection of
/// voice regions the guild can access.
/// </returns>
public Task<IReadOnlyCollection<RestVoiceRegion>> GetVoiceRegionsAsync(RequestOptions options = null)
=> GuildHelper.GetVoiceRegionsAsync(this, Discord, options);
//Integrations
public Task<IReadOnlyCollection<RestGuildIntegration>> GetIntegrationsAsync(RequestOptions options = null)
=> GuildHelper.GetIntegrationsAsync(this, Discord, options);
public Task<RestGuildIntegration> CreateIntegrationAsync(ulong id, string type, RequestOptions options = null)
=> GuildHelper.CreateIntegrationAsync(this, Discord, id, type, options);
//Invites
/// <summary>
/// Gets a collection of all invites in this guild.
/// </summary>
/// <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 a read-only collection of
/// invite metadata, each representing information for an invite found within this guild.
/// </returns>
public Task<IReadOnlyCollection<RestInviteMetadata>> GetInvitesAsync(RequestOptions options = null)
=> GuildHelper.GetInvitesAsync(this, Discord, options);
/// <summary>
/// Gets the vanity invite URL of this guild.
/// </summary>
/// <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 partial metadata of
/// the vanity invite found within this guild; <c>null</c> if none is found.
/// </returns>
public Task<RestInviteMetadata> GetVanityInviteAsync(RequestOptions options = null)
=> GuildHelper.GetVanityInviteAsync(this, Discord, options);
//Roles
/// <summary>
/// Gets a role in this guild.
/// </summary>
/// <param name="id">The snowflake identifier for the role.</param>
/// <returns>
/// A role that is associated with the specified <paramref name="id"/>; <c>null</c> if none is found.
/// </returns>
public SocketRole GetRole(ulong id)
{
if (_roles.TryGetValue(id, out SocketRole value))
return value;
return null;
}
/// <summary>
/// Creates a new role with the provided name.
/// </summary>
/// <param name="name">The new name for the role.</param>
/// <param name="permissions">The guild permission that the role should possess.</param>
/// <param name="color">The color of the role.</param>
/// <param name="isHoisted">Whether the role is separated from others on the sidebar.</param>
/// <param name="options">The options to be used when sending the request.</param>
/// <exception cref="ArgumentNullException"><paramref name="name"/> is <c>null</c>.</exception>
/// <returns>
/// A task that represents the asynchronous creation operation. The task result contains the newly created
/// role.
/// </returns>
public Task<RestRole> CreateRoleAsync(string name, GuildPermissions? permissions = default(GuildPermissions?), Color? color = default(Color?),
bool isHoisted = false, RequestOptions options = null)
=> GuildHelper.CreateRoleAsync(this, Discord, name, permissions, color, isHoisted, options);
internal SocketRole AddRole(RoleModel model)
{
var role = SocketRole.Create(this, Discord.State, model);
_roles[model.Id] = role;
return role;
}
internal SocketRole RemoveRole(ulong id)
{
if (_roles.TryRemove(id, out SocketRole role))
return role;
return null;
}
//Users
/// <inheritdoc />
public Task<RestGuildUser> AddGuildUserAsync(ulong id, string accessToken, Action<AddGuildUserProperties> func = null, RequestOptions options = null)
=> GuildHelper.AddGuildUserAsync(this, Discord, id, accessToken, func, options);
/// <summary>
/// Gets a user from this guild.
/// </summary>
/// <remarks>
/// This method retrieves a user found within this guild.
/// <note>
/// This may return <c>null</c> in the WebSocket implementation due to incomplete user collection in
/// large guilds.
/// </note>
/// </remarks>
/// <param name="id">The snowflake identifier of the user.</param>
/// <returns>
/// A guild user associated with the specified <paramref name="id"/>; <c>null</c> if none is found.
/// </returns>
public SocketGuildUser GetUser(ulong id)
{
if (_members.TryGetValue(id, out SocketGuildUser member))
return member;
return null;
}
/// <inheritdoc />
public Task<int> PruneUsersAsync(int days = 30, bool simulate = false, RequestOptions options = null)
=> GuildHelper.PruneUsersAsync(this, Discord, days, simulate, options);
internal SocketGuildUser AddOrUpdateUser(UserModel model)
{
if (_members.TryGetValue(model.Id, out SocketGuildUser member))
member.GlobalUser?.Update(Discord.State, model);
else
{
member = SocketGuildUser.Create(this, Discord.State, model);
member.GlobalUser.AddRef();
_members[member.Id] = member;
DownloadedMemberCount++;
}
return member;
}
internal SocketGuildUser AddOrUpdateUser(MemberModel model)
{
if (_members.TryGetValue(model.User.Id, out SocketGuildUser member))
member.Update(Discord.State, model);
else
{
member = SocketGuildUser.Create(this, Discord.State, model);
member.GlobalUser.AddRef();
_members[member.Id] = member;
DownloadedMemberCount++;
}
return member;
}
internal SocketGuildUser AddOrUpdateUser(PresenceModel model)
{
if (_members.TryGetValue(model.User.Id, out SocketGuildUser member))
member.Update(Discord.State, model, false);
else
{
member = SocketGuildUser.Create(this, Discord.State, model);
member.GlobalUser.AddRef();
_members[member.Id] = member;
DownloadedMemberCount++;
}
return member;
}
internal SocketGuildUser RemoveUser(ulong id)
{
if (_members.TryRemove(id, out SocketGuildUser member))
{
DownloadedMemberCount--;
member.GlobalUser.RemoveRef(Discord);
return member;
}
return null;
}
/// <inheritdoc />
public async Task DownloadUsersAsync()
{
await Discord.DownloadUsersAsync(new[] { this }).ConfigureAwait(false);
}
internal void CompleteDownloadUsers()
{
_downloaderPromise.TrySetResultAsync(true);
}
//Audit logs
/// <summary>
/// Gets the specified number of audit log entries for this guild.
/// </summary>
/// <param name="limit">The number of audit log entries to fetch.</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 a read-only collection
/// of the requested audit log entries.
/// </returns>
public IAsyncEnumerable<IReadOnlyCollection<RestAuditLogEntry>> GetAuditLogsAsync(int limit, RequestOptions options = null)
=> GuildHelper.GetAuditLogsAsync(this, Discord, null, limit, options);
//Webhooks
/// <summary>
/// Gets a webhook found within this guild.
/// </summary>
/// <param name="id">The identifier for the webhook.</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 webhook with the
/// specified <paramref name="id"/>; <c>null</c> if none is found.
/// </returns>
public Task<RestWebhook> GetWebhookAsync(ulong id, RequestOptions options = null)
=> GuildHelper.GetWebhookAsync(this, Discord, id, options);
/// <summary>
/// Gets a collection of all webhook from this guild.
/// </summary>
/// <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 a read-only collection
/// of webhooks found within the guild.
/// </returns>
public Task<IReadOnlyCollection<RestWebhook>> GetWebhooksAsync(RequestOptions options = null)
=> GuildHelper.GetWebhooksAsync(this, Discord, options);
//Emotes
/// <inheritdoc />
public Task<GuildEmote> GetEmoteAsync(ulong id, RequestOptions options = null)
=> GuildHelper.GetEmoteAsync(this, Discord, id, options);
/// <inheritdoc />
public Task<GuildEmote> CreateEmoteAsync(string name, Image image, Optional<IEnumerable<IRole>> roles = default(Optional<IEnumerable<IRole>>), RequestOptions options = null)
=> GuildHelper.CreateEmoteAsync(this, Discord, name, image, roles, options);
/// <inheritdoc />
/// <exception cref="ArgumentNullException"><paramref name="func"/> is <c>null</c>.</exception>
public Task<GuildEmote> ModifyEmoteAsync(GuildEmote emote, Action<EmoteProperties> func, RequestOptions options = null)
=> GuildHelper.ModifyEmoteAsync(this, Discord, emote.Id, func, options);
/// <inheritdoc />
public Task DeleteEmoteAsync(GuildEmote emote, RequestOptions options = null)
=> GuildHelper.DeleteEmoteAsync(this, Discord, emote.Id, options);
//Voice States
internal async Task<SocketVoiceState> AddOrUpdateVoiceStateAsync(ClientState state, VoiceStateModel model)
{
var voiceChannel = state.GetChannel(model.ChannelId.Value) as SocketVoiceChannel;
var before = GetVoiceState(model.UserId) ?? SocketVoiceState.Default;
var after = SocketVoiceState.Create(voiceChannel, model);
_voiceStates[model.UserId] = after;
if (_audioClient != null && before.VoiceChannel?.Id != after.VoiceChannel?.Id)
{
if (model.UserId == CurrentUser.Id)
{
if (after.VoiceChannel != null && _audioClient.ChannelId != after.VoiceChannel?.Id)
{
_audioClient.ChannelId = after.VoiceChannel.Id;
await RepopulateAudioStreamsAsync().ConfigureAwait(false);
}
}
else
{
await _audioClient.RemoveInputStreamAsync(model.UserId).ConfigureAwait(false); //User changed channels, end their stream
if (CurrentUser.VoiceChannel != null && after.VoiceChannel?.Id == CurrentUser.VoiceChannel?.Id)
await _audioClient.CreateInputStreamAsync(model.UserId).ConfigureAwait(false);
}
}
return after;
}
internal SocketVoiceState? GetVoiceState(ulong id)
{
if (_voiceStates.TryGetValue(id, out SocketVoiceState voiceState))
return voiceState;
return null;
}
internal async Task<SocketVoiceState?> RemoveVoiceStateAsync(ulong id)
{
if (_voiceStates.TryRemove(id, out SocketVoiceState voiceState))
{
if (_audioClient != null)
await _audioClient.RemoveInputStreamAsync(id).ConfigureAwait(false); //User changed channels, end their stream
return voiceState;
}
return null;
}
//Audio
internal AudioInStream GetAudioStream(ulong userId)
{
return _audioClient?.GetInputStream(userId);
}
internal async Task<IAudioClient> ConnectAudioAsync(ulong channelId, bool selfDeaf, bool selfMute, bool external)
{
TaskCompletionSource<AudioClient> promise;
await _audioLock.WaitAsync().ConfigureAwait(false);
try
{
await DisconnectAudioInternalAsync().ConfigureAwait(false);
promise = new TaskCompletionSource<AudioClient>();
_audioConnectPromise = promise;
if (external)
{
var _ = promise.TrySetResultAsync(null);
await Discord.ApiClient.SendVoiceStateUpdateAsync(Id, channelId, selfDeaf, selfMute).ConfigureAwait(false);
return null;
}
if (_audioClient == null)
{
var audioClient = new AudioClient(this, Discord.GetAudioId(), channelId);
audioClient.Disconnected += async ex =>
{
if (!promise.Task.IsCompleted)
{
try
{ audioClient.Dispose(); }
catch { }
_audioClient = null;
if (ex != null)
await promise.TrySetExceptionAsync(ex);
else
await promise.TrySetCanceledAsync();
return;
}
};
audioClient.Connected += () =>
{
var _ = promise.TrySetResultAsync(_audioClient);
return Task.Delay(0);
};
_audioClient = audioClient;
}
await Discord.ApiClient.SendVoiceStateUpdateAsync(Id, channelId, selfDeaf, selfMute).ConfigureAwait(false);
}
catch
{
await DisconnectAudioInternalAsync().ConfigureAwait(false);
throw;
}
finally
{
_audioLock.Release();
}
try
{
var timeoutTask = Task.Delay(15000);
if (await Task.WhenAny(promise.Task, timeoutTask).ConfigureAwait(false) == timeoutTask)
throw new TimeoutException();
return await promise.Task.ConfigureAwait(false);
}
catch
{
await DisconnectAudioAsync().ConfigureAwait(false);
throw;
}
}
internal async Task DisconnectAudioAsync()
{
await _audioLock.WaitAsync().ConfigureAwait(false);
try
{
await DisconnectAudioInternalAsync().ConfigureAwait(false);
}
finally
{
_audioLock.Release();
}
}
private async Task DisconnectAudioInternalAsync()
{
_audioConnectPromise?.TrySetCanceledAsync(); //Cancel any previous audio connection
_audioConnectPromise = null;
if (_audioClient != null)
await _audioClient.StopAsync().ConfigureAwait(false);
await Discord.ApiClient.SendVoiceStateUpdateAsync(Id, null, false, false).ConfigureAwait(false);
_audioClient = null;
}
internal async Task FinishConnectAudio(string url, string token)
{
//TODO: Mem Leak: Disconnected/Connected handlers arent cleaned up
var voiceState = GetVoiceState(Discord.CurrentUser.Id).Value;
await _audioLock.WaitAsync().ConfigureAwait(false);
try
{
if (_audioClient != null)
{
await RepopulateAudioStreamsAsync().ConfigureAwait(false);
await _audioClient.StartAsync(url, Discord.CurrentUser.Id, voiceState.VoiceSessionId, token).ConfigureAwait(false);
}
}
catch (OperationCanceledException)
{
await DisconnectAudioInternalAsync().ConfigureAwait(false);
}
catch (Exception e)
{
await _audioConnectPromise.SetExceptionAsync(e).ConfigureAwait(false);
await DisconnectAudioInternalAsync().ConfigureAwait(false);
}
finally
{
_audioLock.Release();
}
}
internal async Task RepopulateAudioStreamsAsync()
{
await _audioClient.ClearInputStreamsAsync().ConfigureAwait(false); //We changed channels, end all current streams
if (CurrentUser.VoiceChannel != null)
{
foreach (var pair in _voiceStates)
{
if (pair.Value.VoiceChannel?.Id == CurrentUser.VoiceChannel?.Id && pair.Key != CurrentUser.Id)
await _audioClient.CreateInputStreamAsync(pair.Key).ConfigureAwait(false);
}
}
}
/// <summary>
/// Gets the name of the guild.
/// </summary>
/// <returns>
/// A string that resolves to <see cref="Discord.WebSocket.SocketGuild.Name"/>.
/// </returns>