Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow specifying list of user ids in SocketGuild.DownloadUsersAsync #2676

Open
wants to merge 6 commits into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,11 @@ internal class GuildMembersChunkEvent
public ulong GuildId { get; set; }
[JsonProperty("members")]
public GuildMember[] Members { get; set; }
[JsonProperty("chunk_index")]
public int ChunkIndex { get; set; }
[JsonProperty("chunk_count")]
public int ChunkCount { get; set; }
[JsonProperty("nonce")]
public string Nonce { get; set; }
}
}
7 changes: 5 additions & 2 deletions src/Discord.Net.WebSocket/API/Gateway/RequestMembersParams.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,11 @@ internal class RequestMembersParams
public string Query { get; set; }
[JsonProperty("limit")]
public int Limit { get; set; }

[JsonProperty("guild_id")]
public IEnumerable<ulong> GuildIds { get; set; }
public ulong GuildId { get; set; }
[JsonProperty("user_ids")]
public IEnumerable<ulong> UserIds { get; set; }
[JsonProperty("nonce")]
public string Nonce { get; set; }
compujuckel marked this conversation as resolved.
Show resolved Hide resolved
}
}
10 changes: 8 additions & 2 deletions src/Discord.Net.WebSocket/DiscordSocketApiClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -379,11 +379,17 @@ public async Task SendPresenceUpdateAsync(UserStatus status, bool isAFK, long? s
options.BucketId = GatewayBucket.Get(GatewayBucketType.PresenceUpdate).Id;
await SendGatewayAsync(GatewayOpCode.PresenceUpdate, args, options: options).ConfigureAwait(false);
}
public async Task SendRequestMembersAsync(IEnumerable<ulong> guildIds, RequestOptions options = null)
public async Task SendRequestMembersAsync(ulong guildId, RequestOptions options = null)
{
options = RequestOptions.CreateOrClone(options);
await SendGatewayAsync(GatewayOpCode.RequestGuildMembers, new RequestMembersParams { GuildIds = guildIds, Query = "", Limit = 0 }, options: options).ConfigureAwait(false);
await SendGatewayAsync(GatewayOpCode.RequestGuildMembers, new RequestMembersParams { GuildId = guildId, Query = "", Limit = 0 }, options: options).ConfigureAwait(false);
}
public async Task SendRequestMembersAsync(ulong guildId, IEnumerable<ulong> userIds, string nonce, RequestOptions options = null)
{
options = RequestOptions.CreateOrClone(options);
await SendGatewayAsync(GatewayOpCode.RequestGuildMembers, new RequestMembersParams { GuildId = guildId, Limit = 0, UserIds = userIds, Nonce = nonce }, options: options).ConfigureAwait(false);
}

public async Task SendVoiceStateUpdateAsync(ulong guildId, ulong? channelId, bool selfDeaf, bool selfMute, RequestOptions options = null)
{
var payload = new VoiceStateUpdateParams
Expand Down
50 changes: 32 additions & 18 deletions src/Discord.Net.WebSocket/DiscordSocketClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ public partial class DiscordSocketClient : BaseSocketClient, IDiscordClient
private readonly ConnectionManager _connection;
private readonly Logger _gatewayLogger;
private readonly SemaphoreSlim _stateLock;
private readonly ConcurrentDictionary<string, TaskCompletionSource<bool>> _guildMembersRequestTasks;

private string _sessionId;
private int _lastSeq;
Expand All @@ -51,6 +52,7 @@ public partial class DiscordSocketClient : BaseSocketClient, IDiscordClient
private GatewayIntents _gatewayIntents;
private ImmutableArray<StickerPack<SocketSticker>> _defaultStickers;
private SocketSelfUser _previousSessionUser;
private long _guildMembersRequestCounter;

/// <summary>
/// Provides access to a REST-only client with a shared state from this client.
Expand Down Expand Up @@ -183,6 +185,8 @@ private DiscordSocketClient(DiscordSocketConfig config, API.DiscordSocketApiClie
e.ErrorContext.Handled = true;
};

_guildMembersRequestTasks = new ConcurrentDictionary<string, TaskCompletionSource<bool>>();

ApiClient.SentGatewayMessage += async opCode => await _gatewayLogger.DebugAsync($"Sent {opCode}").ConfigureAwait(false);
ApiClient.ReceivedGatewayEvent += ProcessMessageAsync;

Expand Down Expand Up @@ -627,30 +631,33 @@ 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;
foreach (var guild in cachedGuilds)
{
await ApiClient.SendRequestMembersAsync(guild.Id).ConfigureAwait(false);
await guild.DownloaderPromise.ConfigureAwait(false);
}
}

for (int i = 0, k = 0; i < batchCount; i++)
public async Task DownloadUsersAsync(IGuild guild, IEnumerable<ulong> userIds)
{
if (ConnectionState == ConnectionState.Connected)
{
bool isLast = i == batchCount - 1;
int count = isLast ? (cachedGuilds.Length - (batchCount - 1) * batchSize) : batchSize;
EnsureGatewayIntent(GatewayIntents.GuildMembers);

for (int j = 0; j < count; j++, k++)
var socketGuild = GetGuild(guild.Id);
if (socketGuild != null)
{
var guild = cachedGuilds[k];
batchIds[j] = guild.Id;
batchTasks[j] = guild.DownloaderPromise;
await ProcessUserDownloadsAsync(socketGuild, userIds).ConfigureAwait(false);
}
}
compujuckel marked this conversation as resolved.
Show resolved Hide resolved
}

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);
}
private async Task ProcessUserDownloadsAsync(SocketGuild guild, IEnumerable<ulong> userIds)
{
var nonce = Interlocked.Increment(ref _guildMembersRequestCounter).ToString();
_guildMembersRequestTasks.TryAdd(nonce, new TaskCompletionSource<bool>());
await ApiClient.SendRequestMembersAsync(guild.Id, userIds, nonce).ConfigureAwait(false);
}

/// <inheritdoc />
Expand Down Expand Up @@ -1410,6 +1417,13 @@ private async Task ProcessMessageAsync(GatewayOpCode opCode, int? seq, string ty
guild.CompleteDownloadUsers();
await TimedInvokeAsync(_guildMembersDownloadedEvent, nameof(GuildMembersDownloaded), guild).ConfigureAwait(false);
}

if (data.Nonce != null
&& data.ChunkIndex + 1 >= data.ChunkCount
&& _guildMembersRequestTasks.TryRemove(data.Nonce, out var tcs))
{
tcs.TrySetResult(true);
}
}
else
{
Expand Down Expand Up @@ -2904,7 +2918,7 @@ private async Task ProcessMessageAsync(GatewayOpCode opCode, int? seq, string ty
}
break;
#endregion

#region Auto Moderation

case "AUTO_MODERATION_RULE_CREATE":
Expand Down
8 changes: 7 additions & 1 deletion src/Discord.Net.WebSocket/Entities/Guilds/SocketGuild.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1260,6 +1260,12 @@ public async Task DownloadUsersAsync()
{
await Discord.DownloadUsersAsync(new[] { this }).ConfigureAwait(false);
}

public async Task DownloadUsersAsync(IEnumerable<ulong> userIds)
{
await Discord.DownloadUsersAsync(this, userIds).ConfigureAwait(false);
}

internal void CompleteDownloadUsers()
{
_downloaderPromise.TrySetResultAsync(true);
Expand Down Expand Up @@ -1406,7 +1412,7 @@ public Task<RestGuildEvent> CreateEventAsync(
/// <returns>
/// A task that represents the asynchronous get operation. The task result contains a read-only collection
/// of the requested audit log entries.
/// </returns>
/// </returns>
public IAsyncEnumerable<IReadOnlyCollection<RestAuditLogEntry>> GetAuditLogsAsync(int limit, RequestOptions options = null, ulong? beforeId = null, ulong? userId = null, ActionType? actionType = null, ulong? afterId = null)
=> GuildHelper.GetAuditLogsAsync(this, Discord, beforeId, limit, options, userId: userId, actionType: actionType, afterId: afterId);

Expand Down