[Refactor] Remove some unnecessary async/await (#2739)

* Remove some unnecessary async/await

* More not-so-async stuff

* More not-so-async stuff

* Fix merge issue
This commit is contained in:
Dmitry
2023-11-19 00:29:14 +03:00
committed by GitHub
parent 699554ad11
commit 86655a8157
73 changed files with 1020 additions and 1020 deletions

View File

@@ -162,18 +162,18 @@ namespace Discord.Commands
return PreconditionResult.FromSuccess(); return PreconditionResult.FromSuccess();
} }
public async Task<ParseResult> ParseAsync(ICommandContext context, int startIndex, SearchResult searchResult, PreconditionResult preconditionResult = null, IServiceProvider services = null) public Task<ParseResult> ParseAsync(ICommandContext context, int startIndex, SearchResult searchResult, PreconditionResult preconditionResult = null, IServiceProvider services = null)
{ {
services ??= EmptyServiceProvider.Instance; services ??= EmptyServiceProvider.Instance;
if (!searchResult.IsSuccess) if (!searchResult.IsSuccess)
return ParseResult.FromError(searchResult); return Task.FromResult(ParseResult.FromError(searchResult));
if (preconditionResult != null && !preconditionResult.IsSuccess) if (preconditionResult != null && !preconditionResult.IsSuccess)
return ParseResult.FromError(preconditionResult); return Task.FromResult(ParseResult.FromError(preconditionResult));
string input = searchResult.Text.Substring(startIndex); string input = searchResult.Text.Substring(startIndex);
return await CommandParser.ParseArgsAsync(this, context, _commandService._ignoreExtraArgs, services, input, 0, _commandService._quotationMarkAliasMap).ConfigureAwait(false); return CommandParser.ParseArgsAsync(this, context, _commandService._ignoreExtraArgs, services, input, 0, _commandService._quotationMarkAliasMap);
} }
public Task<IResult> ExecuteAsync(ICommandContext context, ParseResult parseResult, IServiceProvider services) public Task<IResult> ExecuteAsync(ICommandContext context, ParseResult parseResult, IServiceProvider services)

View File

@@ -87,10 +87,10 @@ namespace Discord.Commands
return PreconditionResult.FromSuccess(); return PreconditionResult.FromSuccess();
} }
public async Task<TypeReaderResult> ParseAsync(ICommandContext context, string input, IServiceProvider services = null) public Task<TypeReaderResult> ParseAsync(ICommandContext context, string input, IServiceProvider services = null)
{ {
services ??= EmptyServiceProvider.Instance; services ??= EmptyServiceProvider.Instance;
return await _reader.ReadAsync(context, input, services).ConfigureAwait(false); return _reader.ReadAsync(context, input, services);
} }
public override string ToString() => Name; public override string ToString() => Name;

View File

@@ -42,12 +42,11 @@ namespace Discord.Commands
/// <param name="stickers">A collection of stickers to send with the file.</param> /// <param name="stickers">A collection of stickers to send with the file.</param>
/// <param name="embeds">A array of <see cref="Embed"/>s to send with this response. Max 10.</param> /// <param name="embeds">A array of <see cref="Embed"/>s to send with this response. Max 10.</param>
/// <param name="flags">Message flags combined as a bitfield.</param> /// <param name="flags">Message flags combined as a bitfield.</param>
protected virtual async Task<IUserMessage> ReplyAsync(string message = null, bool isTTS = false, Embed embed = null, RequestOptions options = null, protected virtual Task<IUserMessage> ReplyAsync(string message = null, bool isTTS = false, Embed embed = null, RequestOptions options = null,
AllowedMentions allowedMentions = null, MessageReference messageReference = null, MessageComponent components = null, ISticker[] stickers = null, AllowedMentions allowedMentions = null, MessageReference messageReference = null, MessageComponent components = null, ISticker[] stickers = null,
Embed[] embeds = null, MessageFlags flags = MessageFlags.None) Embed[] embeds = null, MessageFlags flags = MessageFlags.None)
{ => Context.Channel.SendMessageAsync(message, isTTS, embed, options, allowedMentions, messageReference, components, stickers, embeds, flags);
return await Context.Channel.SendMessageAsync(message, isTTS, embed, options, allowedMentions, messageReference, components, stickers, embeds, flags).ConfigureAwait(false);
}
/// <summary> /// <summary>
/// The method to execute asynchronously before executing the command. /// The method to execute asynchronously before executing the command.
/// </summary> /// </summary>

View File

@@ -25,11 +25,11 @@ namespace Discord.Commands
} }
/// <inheritdoc /> /// <inheritdoc />
public override async Task<TypeReaderResult> ReadAsync(ICommandContext context, string input, IServiceProvider services) public override Task<TypeReaderResult> ReadAsync(ICommandContext context, string input, IServiceProvider services)
{ {
if (string.Equals(input, "null", StringComparison.OrdinalIgnoreCase) || string.Equals(input, "nothing", StringComparison.OrdinalIgnoreCase)) if (string.Equals(input, "null", StringComparison.OrdinalIgnoreCase) || string.Equals(input, "nothing", StringComparison.OrdinalIgnoreCase))
return TypeReaderResult.FromSuccess(new T?()); return Task.FromResult(TypeReaderResult.FromSuccess(new T?()));
return await _baseTypeReader.ReadAsync(context, input, services).ConfigureAwait(false); return _baseTypeReader.ReadAsync(context, input, services);
} }
} }
} }

View File

@@ -94,9 +94,7 @@ namespace Discord
/// A task that represents an asynchronous send operation for delivering the message. The task result /// A task that represents an asynchronous send operation for delivering the message. The task result
/// contains the sent message. /// contains the sent message.
/// </returns> /// </returns>
public static async Task<IUserMessage> ReplyAsync(this IUserMessage msg, string text = null, bool isTTS = false, Embed embed = null, AllowedMentions allowedMentions = null, RequestOptions options = null, MessageComponent components = null, ISticker[] stickers = null, Embed[] embeds = null, MessageFlags flags = MessageFlags.None) public static Task<IUserMessage> ReplyAsync(this IUserMessage msg, string text = null, bool isTTS = false, Embed embed = null, AllowedMentions allowedMentions = null, RequestOptions options = null, MessageComponent components = null, ISticker[] stickers = null, Embed[] embeds = null, MessageFlags flags = MessageFlags.None)
{ => msg.Channel.SendMessageAsync(text, isTTS, embed, options, allowedMentions, new MessageReference(messageId: msg.Id), components, stickers, embeds, flags);
return await msg.Channel.SendMessageAsync(text, isTTS, embed, options, allowedMentions, new MessageReference(messageId: msg.Id), components, stickers, embeds, flags).ConfigureAwait(false);
}
} }
} }

View File

@@ -97,9 +97,7 @@ namespace Discord.Logging
public Logger CreateLogger(string name) => new Logger(this, name); public Logger CreateLogger(string name) => new Logger(this, name);
public async Task WriteInitialLog() public Task WriteInitialLog()
{ => ClientLogger.InfoAsync($"Discord.Net v{DiscordConfig.Version} (API v{DiscordConfig.APIVersion})");
await ClientLogger.InfoAsync($"Discord.Net v{DiscordConfig.Version} (API v{DiscordConfig.APIVersion})").ConfigureAwait(false);
}
} }
} }

View File

@@ -47,10 +47,8 @@ namespace Discord
/// A task that represents the asynchronous download operation. The task result contains the downloaded /// A task that represents the asynchronous download operation. The task result contains the downloaded
/// entity. /// entity.
/// </returns> /// </returns>
public async Task<TEntity> DownloadAsync() public Task<TEntity> DownloadAsync()
{ => DownloadFunc();
return await DownloadFunc().ConfigureAwait(false);
}
/// <summary> /// <summary>
/// Returns the cached entity if it exists; otherwise downloads it. /// Returns the cached entity if it exists; otherwise downloads it.
@@ -103,9 +101,9 @@ namespace Discord
/// A task that represents the asynchronous download operation. The task result contains the downloaded /// A task that represents the asynchronous download operation. The task result contains the downloaded
/// entity. /// entity.
/// </returns> /// </returns>
public async Task<TDownloadableEntity> DownloadAsync() public Task<TDownloadableEntity> DownloadAsync()
{ {
return await DownloadFunc().ConfigureAwait(false); return DownloadFunc();
} }
/// <summary> /// <summary>

View File

@@ -26,14 +26,14 @@ namespace Discord.Interactions
} }
/// <inheritdoc/> /// <inheritdoc/>
public async Task<IResult> ExecuteAsync(IInteractionContext context, IAutocompleteInteraction autocompleteInteraction, IParameterInfo parameter, public Task<IResult> ExecuteAsync(IInteractionContext context, IAutocompleteInteraction autocompleteInteraction, IParameterInfo parameter,
IServiceProvider services) IServiceProvider services)
{ {
switch (InteractionService._runMode) switch (InteractionService._runMode)
{ {
case RunMode.Sync: case RunMode.Sync:
{ {
return await ExecuteInternalAsync(context, autocompleteInteraction, parameter, services).ConfigureAwait(false); return ExecuteInternalAsync(context, autocompleteInteraction, parameter, services);
} }
case RunMode.Async: case RunMode.Async:
_ = Task.Run(async () => _ = Task.Run(async () =>
@@ -45,7 +45,7 @@ namespace Discord.Interactions
throw new InvalidOperationException($"RunMode {InteractionService._runMode} is not supported."); throw new InvalidOperationException($"RunMode {InteractionService._runMode} is not supported.");
} }
return ExecuteResult.FromSuccess(); return Task.FromResult((IResult)ExecuteResult.FromSuccess());
} }
private async Task<IResult> ExecuteInternalAsync(IInteractionContext context, IAutocompleteInteraction autocompleteInteraction, IParameterInfo parameter, private async Task<IResult> ExecuteInternalAsync(IInteractionContext context, IAutocompleteInteraction autocompleteInteraction, IParameterInfo parameter,

View File

@@ -13,13 +13,13 @@ namespace Discord.Interactions
/// <param name="modifyModal">Delegate that can be used to modify the modal.</param> /// <param name="modifyModal">Delegate that can be used to modify the modal.</param>
/// <param name="options">The request options for this <see langword="async"/> request.</param> /// <param name="options">The request options for this <see langword="async"/> request.</param>
/// <returns>A task that represents the asynchronous operation of responding to the interaction.</returns> /// <returns>A task that represents the asynchronous operation of responding to the interaction.</returns>
public static async Task RespondWithModalAsync<T>(this IDiscordInteraction interaction, string customId, RequestOptions options = null, Action<ModalBuilder> modifyModal = null) public static Task RespondWithModalAsync<T>(this IDiscordInteraction interaction, string customId, RequestOptions options = null, Action<ModalBuilder> modifyModal = null)
where T : class, IModal where T : class, IModal
{ {
if (!ModalUtils.TryGet<T>(out var modalInfo)) if (!ModalUtils.TryGet<T>(out var modalInfo))
throw new ArgumentException($"{typeof(T).FullName} isn't referenced by any registered Modal Interaction Command and doesn't have a cached {typeof(ModalInfo)}"); throw new ArgumentException($"{typeof(T).FullName} isn't referenced by any registered Modal Interaction Command and doesn't have a cached {typeof(ModalInfo)}");
await SendModalResponseAsync(interaction, customId, modalInfo, options, modifyModal); return SendModalResponseAsync(interaction, customId, modalInfo, options, modifyModal);
} }
/// <summary> /// <summary>
@@ -35,13 +35,13 @@ namespace Discord.Interactions
/// <param name="options">The request options for this <see langword="async"/> request.</param> /// <param name="options">The request options for this <see langword="async"/> request.</param>
/// <param name="modifyModal">Delegate that can be used to modify the modal.</param> /// <param name="modifyModal">Delegate that can be used to modify the modal.</param>
/// <returns></returns> /// <returns></returns>
public static async Task RespondWithModalAsync<T>(this IDiscordInteraction interaction, string customId, InteractionService interactionService, public static Task RespondWithModalAsync<T>(this IDiscordInteraction interaction, string customId, InteractionService interactionService,
RequestOptions options = null, Action<ModalBuilder> modifyModal = null) RequestOptions options = null, Action<ModalBuilder> modifyModal = null)
where T : class, IModal where T : class, IModal
{ {
var modalInfo = ModalUtils.GetOrAdd<T>(interactionService); var modalInfo = ModalUtils.GetOrAdd<T>(interactionService);
await SendModalResponseAsync(interaction, customId, modalInfo, options, modifyModal); return SendModalResponseAsync(interaction, customId, modalInfo, options, modifyModal);
} }
/// <summary> /// <summary>
@@ -54,7 +54,7 @@ namespace Discord.Interactions
/// <param name="options">The request options for this <see langword="async"/> request.</param> /// <param name="options">The request options for this <see langword="async"/> request.</param>
/// <param name="modifyModal">Delegate that can be used to modify the modal.</param> /// <param name="modifyModal">Delegate that can be used to modify the modal.</param>
/// <returns></returns> /// <returns></returns>
public static async Task RespondWithModalAsync<T>(this IDiscordInteraction interaction, string customId, T modal, RequestOptions options = null, public static Task RespondWithModalAsync<T>(this IDiscordInteraction interaction, string customId, T modal, RequestOptions options = null,
Action<ModalBuilder> modifyModal = null) Action<ModalBuilder> modifyModal = null)
where T : class, IModal where T : class, IModal
{ {
@@ -79,13 +79,13 @@ namespace Discord.Interactions
if (modifyModal is not null) if (modifyModal is not null)
modifyModal(builder); modifyModal(builder);
await interaction.RespondWithModalAsync(builder.Build(), options).ConfigureAwait(false); return interaction.RespondWithModalAsync(builder.Build(), options);
} }
private static async Task SendModalResponseAsync(IDiscordInteraction interaction, string customId, ModalInfo modalInfo, RequestOptions options = null, Action<ModalBuilder> modifyModal = null) private static Task SendModalResponseAsync(IDiscordInteraction interaction, string customId, ModalInfo modalInfo, RequestOptions options = null, Action<ModalBuilder> modifyModal = null)
{ {
var modal = modalInfo.ToModal(customId, modifyModal); var modal = modalInfo.ToModal(customId, modifyModal);
await interaction.RespondWithModalAsync(modal, options).ConfigureAwait(false); return interaction.RespondWithModalAsync(modal, options);
} }
} }
} }

View File

@@ -36,12 +36,12 @@ namespace Discord.Interactions
} }
/// <inheritdoc/> /// <inheritdoc/>
public override async Task<IResult> ExecuteAsync(IInteractionContext context, IServiceProvider services) public override Task<IResult> ExecuteAsync(IInteractionContext context, IServiceProvider services)
{ {
if (context.Interaction is not IAutocompleteInteraction) if (context.Interaction is not IAutocompleteInteraction)
return ExecuteResult.FromError(InteractionCommandError.ParseFailed, $"Provided {nameof(IInteractionContext)} doesn't belong to a Autocomplete Interaction"); return Task.FromResult((IResult)ExecuteResult.FromError(InteractionCommandError.ParseFailed, $"Provided {nameof(IInteractionContext)} doesn't belong to a Autocomplete Interaction"));
return await base.ExecuteAsync(context, services).ConfigureAwait(false); return base.ExecuteAsync(context, services);
} }
protected override Task<IResult> ParseArgumentsAsync(IInteractionContext context, IServiceProvider services) protected override Task<IResult> ParseArgumentsAsync(IInteractionContext context, IServiceProvider services)

View File

@@ -88,12 +88,12 @@ namespace Discord.Interactions
} }
/// <inheritdoc/> /// <inheritdoc/>
public virtual async Task<IResult> ExecuteAsync(IInteractionContext context, IServiceProvider services) public virtual Task<IResult> ExecuteAsync(IInteractionContext context, IServiceProvider services)
{ {
switch (RunMode) switch (RunMode)
{ {
case RunMode.Sync: case RunMode.Sync:
return await ExecuteInternalAsync(context, services).ConfigureAwait(false); return ExecuteInternalAsync(context, services);
case RunMode.Async: case RunMode.Async:
_ = Task.Run(async () => _ = Task.Run(async () =>
{ {
@@ -104,7 +104,7 @@ namespace Discord.Interactions
throw new InvalidOperationException($"RunMode {RunMode} is not supported."); throw new InvalidOperationException($"RunMode {RunMode} is not supported.");
} }
return ExecuteResult.FromSuccess(); return Task.FromResult((IResult)ExecuteResult.FromSuccess());
} }
protected abstract Task<IResult> ParseArgumentsAsync(IInteractionContext context, IServiceProvider services); protected abstract Task<IResult> ParseArgumentsAsync(IInteractionContext context, IServiceProvider services);

View File

@@ -24,12 +24,12 @@ namespace Discord.Interactions
} }
/// <inheritdoc/> /// <inheritdoc/>
public override async Task<IResult> ExecuteAsync(IInteractionContext context, IServiceProvider services) public override Task<IResult> ExecuteAsync(IInteractionContext context, IServiceProvider services)
{ {
if (context.Interaction is not IComponentInteraction) if (context.Interaction is not IComponentInteraction)
return ExecuteResult.FromError(InteractionCommandError.ParseFailed, $"Provided {nameof(IInteractionContext)} doesn't belong to a Message Component Interaction"); return Task.FromResult((IResult)ExecuteResult.FromError(InteractionCommandError.ParseFailed, $"Provided {nameof(IInteractionContext)} doesn't belong to a Message Component Interaction"));
return await base.ExecuteAsync(context, services).ConfigureAwait(false); return base.ExecuteAsync(context, services);
} }
protected override async Task<IResult> ParseArgumentsAsync(IInteractionContext context, IServiceProvider services) protected override async Task<IResult> ParseArgumentsAsync(IInteractionContext context, IServiceProvider services)

View File

@@ -12,12 +12,12 @@ namespace Discord.Interactions
: base(builder, module, commandService) { } : base(builder, module, commandService) { }
/// <inheritdoc/> /// <inheritdoc/>
public override async Task<IResult> ExecuteAsync(IInteractionContext context, IServiceProvider services) public override Task<IResult> ExecuteAsync(IInteractionContext context, IServiceProvider services)
{ {
if (context.Interaction is not IMessageCommandInteraction) if (context.Interaction is not IMessageCommandInteraction)
return ExecuteResult.FromError(InteractionCommandError.ParseFailed, $"Provided {nameof(IInteractionContext)} doesn't belong to a Message Command Interation"); return Task.FromResult((IResult)ExecuteResult.FromError(InteractionCommandError.ParseFailed, $"Provided {nameof(IInteractionContext)} doesn't belong to a Message Command Interation"));
return await base.ExecuteAsync(context, services).ConfigureAwait(false); return base.ExecuteAsync(context, services);
} }
protected override Task<IResult> ParseArgumentsAsync(IInteractionContext context, IServiceProvider services) protected override Task<IResult> ParseArgumentsAsync(IInteractionContext context, IServiceProvider services)

View File

@@ -12,12 +12,12 @@ namespace Discord.Interactions
: base(builder, module, commandService) { } : base(builder, module, commandService) { }
/// <inheritdoc/> /// <inheritdoc/>
public override async Task<IResult> ExecuteAsync(IInteractionContext context, IServiceProvider services) public override Task<IResult> ExecuteAsync(IInteractionContext context, IServiceProvider services)
{ {
if (context.Interaction is not IUserCommandInteraction userCommand) if (context.Interaction is not IUserCommandInteraction userCommand)
return ExecuteResult.FromError(InteractionCommandError.ParseFailed, $"Provided {nameof(IInteractionContext)} doesn't belong to a Message Command Interation"); return Task.FromResult((IResult)ExecuteResult.FromError(InteractionCommandError.ParseFailed, $"Provided {nameof(IInteractionContext)} doesn't belong to a Message Command Interation"));
return await base.ExecuteAsync(context, services).ConfigureAwait(false); return base.ExecuteAsync(context, services);
} }
protected override Task<IResult> ParseArgumentsAsync(IInteractionContext context, IServiceProvider services) protected override Task<IResult> ParseArgumentsAsync(IInteractionContext context, IServiceProvider services)

View File

@@ -28,12 +28,12 @@ namespace Discord.Interactions
} }
/// <inheritdoc/> /// <inheritdoc/>
public override async Task<IResult> ExecuteAsync(IInteractionContext context, IServiceProvider services) public override Task<IResult> ExecuteAsync(IInteractionContext context, IServiceProvider services)
{ {
if (context.Interaction is not IModalInteraction modalInteraction) if (context.Interaction is not IModalInteraction modalInteraction)
return ExecuteResult.FromError(InteractionCommandError.ParseFailed, $"Provided {nameof(IInteractionContext)} doesn't belong to a Modal Interaction."); return Task.FromResult((IResult)ExecuteResult.FromError(InteractionCommandError.ParseFailed, $"Provided {nameof(IInteractionContext)} doesn't belong to a Modal Interaction."));
return await base.ExecuteAsync(context, services).ConfigureAwait(false); return base.ExecuteAsync(context, services);
} }
protected override async Task<IResult> ParseArgumentsAsync(IInteractionContext context, IServiceProvider services) protected override async Task<IResult> ParseArgumentsAsync(IInteractionContext context, IServiceProvider services)

View File

@@ -64,12 +64,12 @@ namespace Discord.Interactions
} }
/// <inheritdoc/> /// <inheritdoc/>
public override async Task<IResult> ExecuteAsync(IInteractionContext context, IServiceProvider services) public override Task<IResult> ExecuteAsync(IInteractionContext context, IServiceProvider services)
{ {
if (context.Interaction is not ISlashCommandInteraction) if (context.Interaction is not ISlashCommandInteraction)
return ExecuteResult.FromError(InteractionCommandError.ParseFailed, $"Provided {nameof(IInteractionContext)} doesn't belong to a Slash Command Interaction"); return Task.FromResult((IResult)ExecuteResult.FromError(InteractionCommandError.ParseFailed, $"Provided {nameof(IInteractionContext)} doesn't belong to a Slash Command Interaction"));
return await base.ExecuteAsync(context, services); return base.ExecuteAsync(context, services);
} }
protected override async Task<IResult> ParseArgumentsAsync(IInteractionContext context, IServiceProvider services) protected override async Task<IResult> ParseArgumentsAsync(IInteractionContext context, IServiceProvider services)

View File

@@ -41,13 +41,13 @@ namespace Discord.Interactions
} }
/// <inheritdoc cref="IDiscordInteraction.DeferAsync(bool, RequestOptions)"/> /// <inheritdoc cref="IDiscordInteraction.DeferAsync(bool, RequestOptions)"/>
protected virtual async Task DeferAsync(bool ephemeral = false, RequestOptions options = null) => protected virtual Task DeferAsync(bool ephemeral = false, RequestOptions options = null)
await Context.Interaction.DeferAsync(ephemeral, options).ConfigureAwait(false); => Context.Interaction.DeferAsync(ephemeral, options);
/// <inheritdoc cref="IDiscordInteraction.RespondAsync(string, Embed[], bool, bool, AllowedMentions, MessageComponent, Embed, RequestOptions)"/> /// <inheritdoc cref="IDiscordInteraction.RespondAsync(string, Embed[], bool, bool, AllowedMentions, MessageComponent, Embed, RequestOptions)"/>
protected virtual async Task RespondAsync(string text = null, Embed[] embeds = null, bool isTTS = false, bool ephemeral = false, protected virtual Task RespondAsync(string text = null, Embed[] embeds = null, bool isTTS = false, bool ephemeral = false,
AllowedMentions allowedMentions = null, RequestOptions options = null, MessageComponent components = null, Embed embed = null) => AllowedMentions allowedMentions = null, RequestOptions options = null, MessageComponent components = null, Embed embed = null)
await Context.Interaction.RespondAsync(text, embeds, isTTS, ephemeral, allowedMentions, components, embed, options).ConfigureAwait(false); => Context.Interaction.RespondAsync(text, embeds, isTTS, ephemeral, allowedMentions, components, embed, options);
/// <inheritdoc cref="IDiscordInteraction.RespondWithFileAsync(Stream, string, string, Embed[], bool, bool, AllowedMentions, MessageComponent, Embed, RequestOptions)"/> /// <inheritdoc cref="IDiscordInteraction.RespondWithFileAsync(Stream, string, string, Embed[], bool, bool, AllowedMentions, MessageComponent, Embed, RequestOptions)"/>
protected virtual Task RespondWithFileAsync(Stream fileStream, string fileName, string text = null, Embed[] embeds = null, bool isTTS = false, bool ephemeral = false, protected virtual Task RespondWithFileAsync(Stream fileStream, string fileName, string text = null, Embed[] embeds = null, bool isTTS = false, bool ephemeral = false,
@@ -70,9 +70,9 @@ namespace Discord.Interactions
=> Context.Interaction.RespondWithFilesAsync(attachments, text, embeds, isTTS, ephemeral, allowedMentions, components, embed, options); => Context.Interaction.RespondWithFilesAsync(attachments, text, embeds, isTTS, ephemeral, allowedMentions, components, embed, options);
/// <inheritdoc cref="IDiscordInteraction.FollowupAsync(string, Embed[], bool, bool, AllowedMentions, MessageComponent, Embed, RequestOptions)"/> /// <inheritdoc cref="IDiscordInteraction.FollowupAsync(string, Embed[], bool, bool, AllowedMentions, MessageComponent, Embed, RequestOptions)"/>
protected virtual async Task<IUserMessage> FollowupAsync(string text = null, Embed[] embeds = null, bool isTTS = false, bool ephemeral = false, protected virtual Task<IUserMessage> FollowupAsync(string text = null, Embed[] embeds = null, bool isTTS = false, bool ephemeral = false,
AllowedMentions allowedMentions = null, RequestOptions options = null, MessageComponent components = null, Embed embed = null) => AllowedMentions allowedMentions = null, RequestOptions options = null, MessageComponent components = null, Embed embed = null)
await Context.Interaction.FollowupAsync(text, embeds, isTTS, ephemeral, allowedMentions, components, embed, options).ConfigureAwait(false); => Context.Interaction.FollowupAsync(text, embeds, isTTS, ephemeral, allowedMentions, components, embed, options);
/// <inheritdoc cref="IDiscordInteraction.FollowupWithFileAsync(Stream, string, string, Embed[], bool, bool, AllowedMentions, MessageComponent, Embed, RequestOptions)"/> /// <inheritdoc cref="IDiscordInteraction.FollowupWithFileAsync(Stream, string, string, Embed[], bool, bool, AllowedMentions, MessageComponent, Embed, RequestOptions)"/>
protected virtual Task<IUserMessage> FollowupWithFileAsync(Stream fileStream, string fileName, string text = null, Embed[] embeds = null, bool isTTS = false, bool ephemeral = false, protected virtual Task<IUserMessage> FollowupWithFileAsync(Stream fileStream, string fileName, string text = null, Embed[] embeds = null, bool isTTS = false, bool ephemeral = false,
@@ -95,10 +95,10 @@ namespace Discord.Interactions
=> Context.Interaction.FollowupWithFilesAsync(attachments, text, embeds, isTTS, ephemeral, allowedMentions, components, embed, options); => Context.Interaction.FollowupWithFilesAsync(attachments, text, embeds, isTTS, ephemeral, allowedMentions, components, embed, options);
/// <inheritdoc cref="IMessageChannel.SendMessageAsync(string, bool, Embed, RequestOptions, AllowedMentions, MessageReference, MessageComponent, ISticker[], Embed[], MessageFlags)"/> /// <inheritdoc cref="IMessageChannel.SendMessageAsync(string, bool, Embed, RequestOptions, AllowedMentions, MessageReference, MessageComponent, ISticker[], Embed[], MessageFlags)"/>
protected virtual async Task<IUserMessage> ReplyAsync(string text = null, bool isTTS = false, Embed embed = null, RequestOptions options = null, protected virtual Task<IUserMessage> ReplyAsync(string text = null, bool isTTS = false, Embed embed = null, RequestOptions options = null,
AllowedMentions allowedMentions = null, MessageReference messageReference = null, MessageComponent components = null, ISticker[] stickers = null, AllowedMentions allowedMentions = null, MessageReference messageReference = null, MessageComponent components = null, ISticker[] stickers = null,
Embed[] embeds = null, MessageFlags flags = MessageFlags.None) => Embed[] embeds = null, MessageFlags flags = MessageFlags.None)
await Context.Channel.SendMessageAsync(text, false, embed, options, allowedMentions, messageReference, components, stickers, embeds, flags).ConfigureAwait(false); => Context.Channel.SendMessageAsync(text, false, embed, options, allowedMentions, messageReference, components, stickers, embeds, flags);
/// <inheritdoc cref="IDiscordInteraction.GetOriginalResponseAsync(RequestOptions)"/> /// <inheritdoc cref="IDiscordInteraction.GetOriginalResponseAsync(RequestOptions)"/>
protected virtual Task<IUserMessage> GetOriginalResponseAsync(RequestOptions options = null) protected virtual Task<IUserMessage> GetOriginalResponseAsync(RequestOptions options = null)
@@ -116,16 +116,16 @@ namespace Discord.Interactions
} }
/// <inheritdoc cref="IDiscordInteraction.RespondWithModalAsync(Modal, RequestOptions)"/> /// <inheritdoc cref="IDiscordInteraction.RespondWithModalAsync(Modal, RequestOptions)"/>
protected virtual async Task RespondWithModalAsync(Modal modal, RequestOptions options = null) protected virtual Task RespondWithModalAsync(Modal modal, RequestOptions options = null)
=> await Context.Interaction.RespondWithModalAsync(modal, options); => Context.Interaction.RespondWithModalAsync(modal, options);
/// <inheritdoc cref="IDiscordInteractionExtentions.RespondWithModalAsync{T}(IDiscordInteraction, string, T, RequestOptions, Action{ModalBuilder})"/> /// <inheritdoc cref="IDiscordInteractionExtentions.RespondWithModalAsync{T}(IDiscordInteraction, string, T, RequestOptions, Action{ModalBuilder})"/>
protected virtual async Task RespondWithModalAsync<TModal>(string customId, TModal modal, RequestOptions options = null, Action<ModalBuilder> modifyModal = null) where TModal : class, IModal protected virtual Task RespondWithModalAsync<TModal>(string customId, TModal modal, RequestOptions options = null, Action<ModalBuilder> modifyModal = null) where TModal : class, IModal
=> await Context.Interaction.RespondWithModalAsync(customId, modal, options, modifyModal); => Context.Interaction.RespondWithModalAsync(customId, modal, options, modifyModal);
/// <inheritdoc cref="IDiscordInteractionExtentions.RespondWithModalAsync{T}(IDiscordInteraction, string, RequestOptions, Action{ModalBuilder})"/> /// <inheritdoc cref="IDiscordInteractionExtentions.RespondWithModalAsync{T}(IDiscordInteraction, string, RequestOptions, Action{ModalBuilder})"/>
protected virtual async Task RespondWithModalAsync<TModal>(string customId, RequestOptions options = null, Action<ModalBuilder> modifyModal = null) where TModal : class, IModal protected virtual Task RespondWithModalAsync<TModal>(string customId, RequestOptions options = null, Action<ModalBuilder> modifyModal = null) where TModal : class, IModal
=> await Context.Interaction.RespondWithModalAsync<TModal>(customId, options, modifyModal); => Context.Interaction.RespondWithModalAsync<TModal>(customId, options, modifyModal);
/// <inheritdoc cref="IDiscordInteraction.RespondWithPremiumRequiredAsync(RequestOptions)"/> /// <inheritdoc cref="IDiscordInteraction.RespondWithPremiumRequiredAsync(RequestOptions)"/>
protected virtual Task RespondWithPremiumRequiredAsync(RequestOptions options = null) protected virtual Task RespondWithPremiumRequiredAsync(RequestOptions options = null)

View File

@@ -437,12 +437,12 @@ namespace Discord.Interactions
/// <returns> /// <returns>
/// A task representing the command registration process. The task result contains the active application commands of the target guild. /// A task representing the command registration process. The task result contains the active application commands of the target guild.
/// </returns> /// </returns>
public async Task<IReadOnlyCollection<RestGuildCommand>> AddCommandsToGuildAsync(IGuild guild, bool deleteMissing = false, params ICommandInfo[] commands) public Task<IReadOnlyCollection<RestGuildCommand>> AddCommandsToGuildAsync(IGuild guild, bool deleteMissing = false, params ICommandInfo[] commands)
{ {
if (guild is null) if (guild is null)
throw new ArgumentNullException(nameof(guild)); throw new ArgumentNullException(nameof(guild));
return await AddCommandsToGuildAsync(guild.Id, deleteMissing, commands).ConfigureAwait(false); return AddCommandsToGuildAsync(guild.Id, deleteMissing, commands);
} }
/// <summary> /// <summary>
@@ -498,12 +498,12 @@ namespace Discord.Interactions
/// <returns> /// <returns>
/// A task representing the command registration process. The task result contains the active application commands of the target guild. /// A task representing the command registration process. The task result contains the active application commands of the target guild.
/// </returns> /// </returns>
public async Task<IReadOnlyCollection<RestGuildCommand>> AddModulesToGuildAsync(IGuild guild, bool deleteMissing = false, params ModuleInfo[] modules) public Task<IReadOnlyCollection<RestGuildCommand>> AddModulesToGuildAsync(IGuild guild, bool deleteMissing = false, params ModuleInfo[] modules)
{ {
if (guild is null) if (guild is null)
throw new ArgumentNullException(nameof(guild)); throw new ArgumentNullException(nameof(guild));
return await AddModulesToGuildAsync(guild.Id, deleteMissing, modules).ConfigureAwait(false); return AddModulesToGuildAsync(guild.Id, deleteMissing, modules);
} }
/// <summary> /// <summary>
@@ -692,12 +692,12 @@ namespace Discord.Interactions
/// <returns> /// <returns>
/// A task representing the command de-registration process. The task result contains the active application commands of the target guild. /// A task representing the command de-registration process. The task result contains the active application commands of the target guild.
/// </returns> /// </returns>
public async Task<IReadOnlyCollection<RestGuildCommand>> RemoveModulesFromGuildAsync(IGuild guild, params ModuleInfo[] modules) public Task<IReadOnlyCollection<RestGuildCommand>> RemoveModulesFromGuildAsync(IGuild guild, params ModuleInfo[] modules)
{ {
if (guild is null) if (guild is null)
throw new ArgumentNullException(nameof(guild)); throw new ArgumentNullException(nameof(guild));
return await RemoveModulesFromGuildAsync(guild.Id, modules).ConfigureAwait(false); return RemoveModulesFromGuildAsync(guild.Id, modules);
} }
/// <summary> /// <summary>
@@ -1164,7 +1164,7 @@ namespace Discord.Interactions
/// <returns> /// <returns>
/// The active command permissions after the modification. /// The active command permissions after the modification.
/// </returns> /// </returns>
public async Task<GuildApplicationCommandPermission> ModifySlashCommandPermissionsAsync(ModuleInfo module, IGuild guild, public Task<GuildApplicationCommandPermission> ModifySlashCommandPermissionsAsync(ModuleInfo module, IGuild guild,
params ApplicationCommandPermission[] permissions) params ApplicationCommandPermission[] permissions)
{ {
if (module is null) if (module is null)
@@ -1173,7 +1173,7 @@ namespace Discord.Interactions
if (guild is null) if (guild is null)
throw new ArgumentNullException(nameof(guild)); throw new ArgumentNullException(nameof(guild));
return await ModifySlashCommandPermissionsAsync(module, guild.Id, permissions).ConfigureAwait(false); return ModifySlashCommandPermissionsAsync(module, guild.Id, permissions);
} }
/// <summary> /// <summary>
@@ -1212,7 +1212,7 @@ namespace Discord.Interactions
/// <returns> /// <returns>
/// The active command permissions after the modification. /// The active command permissions after the modification.
/// </returns> /// </returns>
public async Task<GuildApplicationCommandPermission> ModifySlashCommandPermissionsAsync(SlashCommandInfo command, IGuild guild, public Task<GuildApplicationCommandPermission> ModifySlashCommandPermissionsAsync(SlashCommandInfo command, IGuild guild,
params ApplicationCommandPermission[] permissions) params ApplicationCommandPermission[] permissions)
{ {
if (command is null) if (command is null)
@@ -1221,7 +1221,7 @@ namespace Discord.Interactions
if (guild is null) if (guild is null)
throw new ArgumentNullException(nameof(guild)); throw new ArgumentNullException(nameof(guild));
return await ModifyApplicationCommandPermissionsAsync(command, guild.Id, permissions).ConfigureAwait(false); return ModifyApplicationCommandPermissionsAsync(command, guild.Id, permissions);
} }
/// <summary> /// <summary>
@@ -1233,8 +1233,9 @@ namespace Discord.Interactions
/// <returns> /// <returns>
/// The active command permissions after the modification. /// The active command permissions after the modification.
/// </returns> /// </returns>
public async Task<GuildApplicationCommandPermission> ModifySlashCommandPermissionsAsync(SlashCommandInfo command, ulong guildId, public Task<GuildApplicationCommandPermission> ModifySlashCommandPermissionsAsync(SlashCommandInfo command, ulong guildId,
params ApplicationCommandPermission[] permissions) => await ModifyApplicationCommandPermissionsAsync(command, guildId, permissions).ConfigureAwait(false); params ApplicationCommandPermission[] permissions)
=> ModifyApplicationCommandPermissionsAsync(command, guildId, permissions);
/// <summary> /// <summary>
/// Modify the command permissions of the matching Discord Slash Command. /// Modify the command permissions of the matching Discord Slash Command.
@@ -1245,7 +1246,7 @@ namespace Discord.Interactions
/// <returns> /// <returns>
/// The active command permissions after the modification. /// The active command permissions after the modification.
/// </returns> /// </returns>
public async Task<GuildApplicationCommandPermission> ModifyContextCommandPermissionsAsync(ContextCommandInfo command, IGuild guild, public Task<GuildApplicationCommandPermission> ModifyContextCommandPermissionsAsync(ContextCommandInfo command, IGuild guild,
params ApplicationCommandPermission[] permissions) params ApplicationCommandPermission[] permissions)
{ {
if (command is null) if (command is null)
@@ -1254,7 +1255,7 @@ namespace Discord.Interactions
if (guild is null) if (guild is null)
throw new ArgumentNullException(nameof(guild)); throw new ArgumentNullException(nameof(guild));
return await ModifyApplicationCommandPermissionsAsync(command, guild.Id, permissions).ConfigureAwait(false); return ModifyApplicationCommandPermissionsAsync(command, guild.Id, permissions);
} }
/// <summary> /// <summary>
@@ -1266,8 +1267,9 @@ namespace Discord.Interactions
/// <returns> /// <returns>
/// The active command permissions after the modification. /// The active command permissions after the modification.
/// </returns> /// </returns>
public async Task<GuildApplicationCommandPermission> ModifyContextCommandPermissionsAsync(ContextCommandInfo command, ulong guildId, public Task<GuildApplicationCommandPermission> ModifyContextCommandPermissionsAsync(ContextCommandInfo command, ulong guildId,
params ApplicationCommandPermission[] permissions) => await ModifyApplicationCommandPermissionsAsync(command, guildId, permissions).ConfigureAwait(false); params ApplicationCommandPermission[] permissions)
=> ModifyApplicationCommandPermissionsAsync(command, guildId, permissions);
private async Task<GuildApplicationCommandPermission> ModifyApplicationCommandPermissionsAsync<T>(T command, ulong guildId, private async Task<GuildApplicationCommandPermission> ModifyApplicationCommandPermissionsAsync<T>(T command, ulong guildId,
params ApplicationCommandPermission[] permissions) where T : class, IApplicationCommandInfo, ICommandInfo params ApplicationCommandPermission[] permissions) where T : class, IApplicationCommandInfo, ICommandInfo

View File

@@ -25,8 +25,8 @@ namespace Discord.Interactions
/// A Task representing the operation of creating the interaction response. /// A Task representing the operation of creating the interaction response.
/// </returns> /// </returns>
/// <exception cref="InvalidOperationException">Thrown if the interaction isn't a type of <see cref="RestInteraction"/>.</exception> /// <exception cref="InvalidOperationException">Thrown if the interaction isn't a type of <see cref="RestInteraction"/>.</exception>
protected override async Task DeferAsync(bool ephemeral = false, RequestOptions options = null) protected override Task DeferAsync(bool ephemeral = false, RequestOptions options = null)
=> await HandleInteractionAsync(x => x.Defer(ephemeral, options)); => HandleInteractionAsync(x => x.Defer(ephemeral, options));
/// <summary> /// <summary>
/// Respond to a Rest based Discord Interaction using the <see cref="InteractionServiceConfig.RestResponseCallback"/> delegate. /// Respond to a Rest based Discord Interaction using the <see cref="InteractionServiceConfig.RestResponseCallback"/> delegate.
@@ -43,8 +43,8 @@ namespace Discord.Interactions
/// A Task representing the operation of creating the interaction response. /// A Task representing the operation of creating the interaction response.
/// </returns> /// </returns>
/// <exception cref="InvalidOperationException">Thrown if the interaction isn't a type of <see cref="RestInteraction"/>.</exception> /// <exception cref="InvalidOperationException">Thrown if the interaction isn't a type of <see cref="RestInteraction"/>.</exception>
protected override async Task RespondAsync(string text = null, Embed[] embeds = null, bool isTTS = false, bool ephemeral = false, AllowedMentions allowedMentions = null, RequestOptions options = null, MessageComponent components = null, Embed embed = null) protected override Task RespondAsync(string text = null, Embed[] embeds = null, bool isTTS = false, bool ephemeral = false, AllowedMentions allowedMentions = null, RequestOptions options = null, MessageComponent components = null, Embed embed = null)
=> await HandleInteractionAsync(x => x.Respond(text, embeds, isTTS, ephemeral, allowedMentions, components, embed, options)); => HandleInteractionAsync(x => x.Respond(text, embeds, isTTS, ephemeral, allowedMentions, components, embed, options));
/// <summary> /// <summary>
/// Responds to the interaction with a modal. /// Responds to the interaction with a modal.
@@ -55,8 +55,8 @@ namespace Discord.Interactions
/// A Task representing the operation of creating the interaction response. /// A Task representing the operation of creating the interaction response.
/// </returns> /// </returns>
/// <exception cref="InvalidOperationException">Thrown if the interaction isn't a type of <see cref="RestInteraction"/>.</exception> /// <exception cref="InvalidOperationException">Thrown if the interaction isn't a type of <see cref="RestInteraction"/>.</exception>
protected override async Task RespondWithModalAsync(Modal modal, RequestOptions options = null) protected override Task RespondWithModalAsync(Modal modal, RequestOptions options = null)
=> await HandleInteractionAsync(x => x.RespondWithModal(modal, options)); => HandleInteractionAsync(x => x.RespondWithModal(modal, options));
/// <summary> /// <summary>
/// Responds to the interaction with a modal. /// Responds to the interaction with a modal.
@@ -84,10 +84,10 @@ namespace Discord.Interactions
/// A Task representing the operation of creating the interaction response. /// A Task representing the operation of creating the interaction response.
/// </returns> /// </returns>
/// <exception cref="InvalidOperationException">Thrown if the interaction isn't a type of <see cref="RestInteraction"/>.</exception> /// <exception cref="InvalidOperationException">Thrown if the interaction isn't a type of <see cref="RestInteraction"/>.</exception>
protected override async Task RespondWithModalAsync<TModal>(string customId, RequestOptions options = null, Action<ModalBuilder> modifyModal = null) protected override Task RespondWithModalAsync<TModal>(string customId, RequestOptions options = null, Action<ModalBuilder> modifyModal = null)
=> await HandleInteractionAsync(x => x.RespondWithModal<TModal>(customId, options, modifyModal)); => HandleInteractionAsync(x => x.RespondWithModal<TModal>(customId, options, modifyModal));
private async Task HandleInteractionAsync(Func<RestInteraction, string> action) private Task HandleInteractionAsync(Func<RestInteraction, string> action)
{ {
if (Context.Interaction is not RestInteraction restInteraction) if (Context.Interaction is not RestInteraction restInteraction)
throw new InvalidOperationException($"Interaction must be a type of {nameof(RestInteraction)} in order to execute this method."); throw new InvalidOperationException($"Interaction must be a type of {nameof(RestInteraction)} in order to execute this method.");
@@ -95,9 +95,9 @@ namespace Discord.Interactions
var payload = action(restInteraction); var payload = action(restInteraction);
if (Context is IRestInteractionContext restContext && restContext.InteractionResponseCallback != null) if (Context is IRestInteractionContext restContext && restContext.InteractionResponseCallback != null)
await restContext.InteractionResponseCallback.Invoke(payload).ConfigureAwait(false); return restContext.InteractionResponseCallback.Invoke(payload);
else else
await InteractionService._restResponseCallback(Context, payload).ConfigureAwait(false); return InteractionService._restResponseCallback(Context, payload);
} }
} }
} }

View File

@@ -25,7 +25,7 @@ namespace Discord.Rest
return RestApplication.Create(client, model); return RestApplication.Create(client, model);
} }
public static async Task<API.Application> ModifyCurrentBotApplicationAsync(BaseDiscordClient client, Action<ModifyApplicationProperties> func, RequestOptions options) public static Task<API.Application> ModifyCurrentBotApplicationAsync(BaseDiscordClient client, Action<ModifyApplicationProperties> func, RequestOptions options)
{ {
var args = new ModifyApplicationProperties(); var args = new ModifyApplicationProperties();
func(args); func(args);
@@ -40,7 +40,7 @@ namespace Discord.Rest
if (args.Description.IsSpecified) if (args.Description.IsSpecified)
Preconditions.AtMost(args.Description.Value.Length, DiscordConfig.MaxApplicationDescriptionLength, nameof(args.Description), $"An application description tag mus have length less or equal to {DiscordConfig.MaxApplicationDescriptionLength}"); Preconditions.AtMost(args.Description.Value.Length, DiscordConfig.MaxApplicationDescriptionLength, nameof(args.Description), $"An application description tag mus have length less or equal to {DiscordConfig.MaxApplicationDescriptionLength}");
return await client.ApiClient.ModifyCurrentBotApplicationAsync(new() return client.ApiClient.ModifyCurrentBotApplicationAsync(new()
{ {
Description = args.Description, Description = args.Description,
Tags = args.Tags, Tags = args.Tags,

File diff suppressed because it is too large Load Diff

View File

@@ -13,12 +13,10 @@ namespace Discord.Rest
internal static class ChannelHelper internal static class ChannelHelper
{ {
#region General #region General
public static async Task DeleteAsync(IChannel channel, BaseDiscordClient client, public static Task DeleteAsync(IChannel channel, BaseDiscordClient client, RequestOptions options)
RequestOptions options) => client.ApiClient.DeleteChannelAsync(channel.Id, options);
{
await client.ApiClient.DeleteChannelAsync(channel.Id, options).ConfigureAwait(false); public static Task<Model> ModifyAsync(IGuildChannel channel, BaseDiscordClient client,
}
public static async Task<Model> ModifyAsync(IGuildChannel channel, BaseDiscordClient client,
Action<GuildChannelProperties> func, Action<GuildChannelProperties> func,
RequestOptions options) RequestOptions options)
{ {
@@ -40,9 +38,10 @@ namespace Discord.Rest
: Optional.Create<API.Overwrite[]>(), : Optional.Create<API.Overwrite[]>(),
Flags = args.Flags.GetValueOrDefault(), Flags = args.Flags.GetValueOrDefault(),
}; };
return await client.ApiClient.ModifyGuildChannelAsync(channel.Id, apiArgs, options).ConfigureAwait(false); return client.ApiClient.ModifyGuildChannelAsync(channel.Id, apiArgs, options);
} }
public static async Task<Model> ModifyAsync(ITextChannel channel, BaseDiscordClient client,
public static Task<Model> ModifyAsync(ITextChannel channel, BaseDiscordClient client,
Action<TextChannelProperties> func, Action<TextChannelProperties> func,
RequestOptions options) RequestOptions options)
{ {
@@ -67,9 +66,10 @@ namespace Discord.Rest
: Optional.Create<API.Overwrite[]>(), : Optional.Create<API.Overwrite[]>(),
DefaultSlowModeInterval = args.DefaultSlowModeInterval DefaultSlowModeInterval = args.DefaultSlowModeInterval
}; };
return await client.ApiClient.ModifyGuildChannelAsync(channel.Id, apiArgs, options).ConfigureAwait(false); return client.ApiClient.ModifyGuildChannelAsync(channel.Id, apiArgs, options);
} }
public static async Task<Model> ModifyAsync(IVoiceChannel channel, BaseDiscordClient client,
public static Task<Model> ModifyAsync(IVoiceChannel channel, BaseDiscordClient client,
Action<VoiceChannelProperties> func, Action<VoiceChannelProperties> func,
RequestOptions options) RequestOptions options)
{ {
@@ -95,10 +95,10 @@ namespace Discord.Rest
SlowModeInterval = args.SlowModeInterval, SlowModeInterval = args.SlowModeInterval,
IsNsfw = args.IsNsfw, IsNsfw = args.IsNsfw,
}; };
return await client.ApiClient.ModifyGuildChannelAsync(channel.Id, apiArgs, options).ConfigureAwait(false); return client.ApiClient.ModifyGuildChannelAsync(channel.Id, apiArgs, options);
} }
public static async Task<StageInstance> ModifyAsync(IStageChannel channel, BaseDiscordClient client, public static Task<StageInstance> ModifyAsync(IStageChannel channel, BaseDiscordClient client,
Action<StageInstanceProperties> func, RequestOptions options = null) Action<StageInstanceProperties> func, RequestOptions options = null)
{ {
var args = new StageInstanceProperties(); var args = new StageInstanceProperties();
@@ -110,7 +110,7 @@ namespace Discord.Rest
Topic = args.Topic Topic = args.Topic
}; };
return await client.ApiClient.ModifyStageInstanceAsync(channel.Id, apiArgs, options); return client.ApiClient.ModifyStageInstanceAsync(channel.Id, apiArgs, options);
} }
#endregion #endregion
@@ -492,28 +492,27 @@ namespace Discord.Rest
#endregion #endregion
#region Permission Overwrites #region Permission Overwrites
public static async Task AddPermissionOverwriteAsync(IGuildChannel channel, BaseDiscordClient client, public static Task AddPermissionOverwriteAsync(IGuildChannel channel, BaseDiscordClient client,
IUser user, OverwritePermissions perms, RequestOptions options) IUser user, OverwritePermissions perms, RequestOptions options)
{ {
var args = new ModifyChannelPermissionsParams((int)PermissionTarget.User, perms.AllowValue.ToString(), perms.DenyValue.ToString()); var args = new ModifyChannelPermissionsParams((int)PermissionTarget.User, perms.AllowValue.ToString(), perms.DenyValue.ToString());
await client.ApiClient.ModifyChannelPermissionsAsync(channel.Id, user.Id, args, options).ConfigureAwait(false); return client.ApiClient.ModifyChannelPermissionsAsync(channel.Id, user.Id, args, options);
} }
public static async Task AddPermissionOverwriteAsync(IGuildChannel channel, BaseDiscordClient client,
public static Task AddPermissionOverwriteAsync(IGuildChannel channel, BaseDiscordClient client,
IRole role, OverwritePermissions perms, RequestOptions options) IRole role, OverwritePermissions perms, RequestOptions options)
{ {
var args = new ModifyChannelPermissionsParams((int)PermissionTarget.Role, perms.AllowValue.ToString(), perms.DenyValue.ToString()); var args = new ModifyChannelPermissionsParams((int)PermissionTarget.Role, perms.AllowValue.ToString(), perms.DenyValue.ToString());
await client.ApiClient.ModifyChannelPermissionsAsync(channel.Id, role.Id, args, options).ConfigureAwait(false); return client.ApiClient.ModifyChannelPermissionsAsync(channel.Id, role.Id, args, options);
} }
public static async Task RemovePermissionOverwriteAsync(IGuildChannel channel, BaseDiscordClient client,
public static Task RemovePermissionOverwriteAsync(IGuildChannel channel, BaseDiscordClient client,
IUser user, RequestOptions options) IUser user, RequestOptions options)
{ => client.ApiClient.DeleteChannelPermissionAsync(channel.Id, user.Id, options);
await client.ApiClient.DeleteChannelPermissionAsync(channel.Id, user.Id, options).ConfigureAwait(false);
} public static Task RemovePermissionOverwriteAsync(IGuildChannel channel, BaseDiscordClient client,
public static async Task RemovePermissionOverwriteAsync(IGuildChannel channel, BaseDiscordClient client,
IRole role, RequestOptions options) IRole role, RequestOptions options)
{ => client.ApiClient.DeleteChannelPermissionAsync(channel.Id, role.Id, options);
await client.ApiClient.DeleteChannelPermissionAsync(channel.Id, role.Id, options).ConfigureAwait(false);
}
#endregion #endregion
#region Users #region Users
@@ -564,11 +563,9 @@ namespace Discord.Rest
#endregion #endregion
#region Typing #region Typing
public static async Task TriggerTypingAsync(IMessageChannel channel, BaseDiscordClient client, public static Task TriggerTypingAsync(IMessageChannel channel, BaseDiscordClient client, RequestOptions options = null)
RequestOptions options = null) => client.ApiClient.TriggerTypingIndicatorAsync(channel.Id, options);
{
await client.ApiClient.TriggerTypingIndicatorAsync(channel.Id, options).ConfigureAwait(false);
}
public static IDisposable EnterTypingState(IMessageChannel channel, BaseDiscordClient client, public static IDisposable EnterTypingState(IMessageChannel channel, BaseDiscordClient client,
RequestOptions options) RequestOptions options)
=> new TypingNotifier(channel, options); => new TypingNotifier(channel, options);

View File

@@ -8,7 +8,7 @@ namespace Discord.Rest;
internal static class ForumHelper internal static class ForumHelper
{ {
public static async Task<Model> ModifyAsync(IForumChannel channel, BaseDiscordClient client, public static Task<Model> ModifyAsync(IForumChannel channel, BaseDiscordClient client,
Action<ForumChannelProperties> func, Action<ForumChannelProperties> func,
RequestOptions options) RequestOptions options)
{ {
@@ -59,6 +59,6 @@ internal static class ForumHelper
: Optional<ModifyForumReactionEmojiParams>.Unspecified, : Optional<ModifyForumReactionEmojiParams>.Unspecified,
DefaultSortOrder = args.DefaultSortOrder DefaultSortOrder = args.DefaultSortOrder
}; };
return await client.ApiClient.ModifyGuildChannelAsync(channel.Id, apiArgs, options).ConfigureAwait(false); return client.ApiClient.ModifyGuildChannelAsync(channel.Id, apiArgs, options);
} }
} }

View File

@@ -220,17 +220,17 @@ namespace Discord.Rest
OverwritePermissions? IGuildChannel.GetPermissionOverwrite(IUser user) OverwritePermissions? IGuildChannel.GetPermissionOverwrite(IUser user)
=> GetPermissionOverwrite(user); => GetPermissionOverwrite(user);
/// <inheritdoc /> /// <inheritdoc />
async Task IGuildChannel.AddPermissionOverwriteAsync(IRole role, OverwritePermissions permissions, RequestOptions options) Task IGuildChannel.AddPermissionOverwriteAsync(IRole role, OverwritePermissions permissions, RequestOptions options)
=> await AddPermissionOverwriteAsync(role, permissions, options).ConfigureAwait(false); => AddPermissionOverwriteAsync(role, permissions, options);
/// <inheritdoc /> /// <inheritdoc />
async Task IGuildChannel.AddPermissionOverwriteAsync(IUser user, OverwritePermissions permissions, RequestOptions options) Task IGuildChannel.AddPermissionOverwriteAsync(IUser user, OverwritePermissions permissions, RequestOptions options)
=> await AddPermissionOverwriteAsync(user, permissions, options).ConfigureAwait(false); => AddPermissionOverwriteAsync(user, permissions, options);
/// <inheritdoc /> /// <inheritdoc />
async Task IGuildChannel.RemovePermissionOverwriteAsync(IRole role, RequestOptions options) Task IGuildChannel.RemovePermissionOverwriteAsync(IRole role, RequestOptions options)
=> await RemovePermissionOverwriteAsync(role, options).ConfigureAwait(false); => RemovePermissionOverwriteAsync(role, options);
/// <inheritdoc /> /// <inheritdoc />
async Task IGuildChannel.RemovePermissionOverwriteAsync(IUser user, RequestOptions options) Task IGuildChannel.RemovePermissionOverwriteAsync(IUser user, RequestOptions options)
=> await RemovePermissionOverwriteAsync(user, options).ConfigureAwait(false); => RemovePermissionOverwriteAsync(user, options);
/// <inheritdoc /> /// <inheritdoc />
IAsyncEnumerable<IReadOnlyCollection<IGuildUser>> IGuildChannel.GetUsersAsync(CacheMode mode, RequestOptions options) IAsyncEnumerable<IReadOnlyCollection<IGuildUser>> IGuildChannel.GetUsersAsync(CacheMode mode, RequestOptions options)

View File

@@ -11,7 +11,7 @@ namespace Discord.Rest
{ {
internal static class ThreadHelper internal static class ThreadHelper
{ {
public static async Task<Model> CreateThreadAsync(BaseDiscordClient client, ITextChannel channel, string name, ThreadType type = ThreadType.PublicThread, public static Task<Model> CreateThreadAsync(BaseDiscordClient client, ITextChannel channel, string name, ThreadType type = ThreadType.PublicThread,
ThreadArchiveDuration autoArchiveDuration = ThreadArchiveDuration.OneDay, IMessage message = null, bool? invitable = null, int? slowmode = null, RequestOptions options = null) ThreadArchiveDuration autoArchiveDuration = ThreadArchiveDuration.OneDay, IMessage message = null, bool? invitable = null, int? slowmode = null, RequestOptions options = null)
{ {
if (channel is INewsChannel && type != ThreadType.NewsThread) if (channel is INewsChannel && type != ThreadType.NewsThread)
@@ -26,17 +26,13 @@ namespace Discord.Rest
Ratelimit = slowmode.HasValue ? slowmode.Value : Optional<int?>.Unspecified, Ratelimit = slowmode.HasValue ? slowmode.Value : Optional<int?>.Unspecified,
}; };
Model model;
if (message != null) if (message != null)
model = await client.ApiClient.StartThreadAsync(channel.Id, message.Id, args, options).ConfigureAwait(false); return client.ApiClient.StartThreadAsync(channel.Id, message.Id, args, options);
else else
model = await client.ApiClient.StartThreadAsync(channel.Id, args, options).ConfigureAwait(false); return client.ApiClient.StartThreadAsync(channel.Id, args, options);
return model;
} }
public static async Task<Model> ModifyAsync(IThreadChannel channel, BaseDiscordClient client, public static Task<Model> ModifyAsync(IThreadChannel channel, BaseDiscordClient client,
Action<ThreadChannelProperties> func, Action<ThreadChannelProperties> func,
RequestOptions options) RequestOptions options)
{ {
@@ -55,7 +51,7 @@ namespace Discord.Rest
AppliedTags = args.AppliedTags, AppliedTags = args.AppliedTags,
Flags = args.Flags, Flags = args.Flags,
}; };
return await client.ApiClient.ModifyThreadAsync(channel.Id, apiArgs, options).ConfigureAwait(false); return client.ApiClient.ModifyThreadAsync(channel.Id, apiArgs, options);
} }
public static async Task<IReadOnlyCollection<RestThreadChannel>> GetActiveThreadsAsync(IGuild guild, ulong channelId, BaseDiscordClient client, RequestOptions options) public static async Task<IReadOnlyCollection<RestThreadChannel>> GetActiveThreadsAsync(IGuild guild, ulong channelId, BaseDiscordClient client, RequestOptions options)

View File

@@ -20,7 +20,7 @@ namespace Discord.Rest
{ {
#region General #region General
/// <exception cref="ArgumentNullException"><paramref name="func"/> is <see langword="null" />.</exception> /// <exception cref="ArgumentNullException"><paramref name="func"/> is <see langword="null" />.</exception>
public static async Task<Model> ModifyAsync(IGuild guild, BaseDiscordClient client, public static Task<Model> ModifyAsync(IGuild guild, BaseDiscordClient client,
Action<GuildProperties> func, RequestOptions options) Action<GuildProperties> func, RequestOptions options)
{ {
if (func == null) if (func == null)
@@ -91,10 +91,11 @@ namespace Discord.Rest
else if (args.PreferredCulture.IsSpecified) else if (args.PreferredCulture.IsSpecified)
apiArgs.PreferredLocale = args.PreferredCulture.Value.Name; apiArgs.PreferredLocale = args.PreferredCulture.Value.Name;
return await client.ApiClient.ModifyGuildAsync(guild.Id, apiArgs, options).ConfigureAwait(false); return client.ApiClient.ModifyGuildAsync(guild.Id, apiArgs, options);
} }
/// <exception cref="ArgumentNullException"><paramref name="func"/> is <see langword="null" />.</exception> /// <exception cref="ArgumentNullException"><paramref name="func"/> is <see langword="null" />.</exception>
public static async Task<WidgetModel> ModifyWidgetAsync(IGuild guild, BaseDiscordClient client, public static Task<WidgetModel> ModifyWidgetAsync(IGuild guild, BaseDiscordClient client,
Action<GuildWidgetProperties> func, RequestOptions options) Action<GuildWidgetProperties> func, RequestOptions options)
{ {
if (func == null) if (func == null)
@@ -112,30 +113,29 @@ namespace Discord.Rest
else if (args.ChannelId.IsSpecified) else if (args.ChannelId.IsSpecified)
apiArgs.ChannelId = args.ChannelId.Value; apiArgs.ChannelId = args.ChannelId.Value;
return await client.ApiClient.ModifyGuildWidgetAsync(guild.Id, apiArgs, options).ConfigureAwait(false); return client.ApiClient.ModifyGuildWidgetAsync(guild.Id, apiArgs, options);
} }
public static async Task ReorderChannelsAsync(IGuild guild, BaseDiscordClient client,
public static Task ReorderChannelsAsync(IGuild guild, BaseDiscordClient client,
IEnumerable<ReorderChannelProperties> args, RequestOptions options) IEnumerable<ReorderChannelProperties> args, RequestOptions options)
{ {
var apiArgs = args.Select(x => new API.Rest.ModifyGuildChannelsParams(x.Id, x.Position)); var apiArgs = args.Select(x => new API.Rest.ModifyGuildChannelsParams(x.Id, x.Position));
await client.ApiClient.ModifyGuildChannelsAsync(guild.Id, apiArgs, options).ConfigureAwait(false); return client.ApiClient.ModifyGuildChannelsAsync(guild.Id, apiArgs, options);
} }
public static async Task<IReadOnlyCollection<RoleModel>> ReorderRolesAsync(IGuild guild, BaseDiscordClient client,
public static Task<IReadOnlyCollection<RoleModel>> ReorderRolesAsync(IGuild guild, BaseDiscordClient client,
IEnumerable<ReorderRoleProperties> args, RequestOptions options) IEnumerable<ReorderRoleProperties> args, RequestOptions options)
{ {
var apiArgs = args.Select(x => new API.Rest.ModifyGuildRolesParams(x.Id, x.Position)); var apiArgs = args.Select(x => new API.Rest.ModifyGuildRolesParams(x.Id, x.Position));
return await client.ApiClient.ModifyGuildRolesAsync(guild.Id, apiArgs, options).ConfigureAwait(false); return client.ApiClient.ModifyGuildRolesAsync(guild.Id, apiArgs, options);
}
public static async Task LeaveAsync(IGuild guild, BaseDiscordClient client,
RequestOptions options)
{
await client.ApiClient.LeaveGuildAsync(guild.Id, options).ConfigureAwait(false);
}
public static async Task DeleteAsync(IGuild guild, BaseDiscordClient client,
RequestOptions options)
{
await client.ApiClient.DeleteGuildAsync(guild.Id, options).ConfigureAwait(false);
} }
public static Task LeaveAsync(IGuild guild, BaseDiscordClient client, RequestOptions options)
=> client.ApiClient.LeaveGuildAsync(guild.Id, options);
public static Task DeleteAsync(IGuild guild, BaseDiscordClient client, RequestOptions options)
=> client.ApiClient.DeleteGuildAsync(guild.Id, options);
public static ulong GetUploadLimit(IGuild guild) public static ulong GetUploadLimit(IGuild guild)
{ {
var tierFactor = guild.PremiumTier switch var tierFactor = guild.PremiumTier switch
@@ -223,17 +223,15 @@ namespace Discord.Rest
return model == null ? null : RestBan.Create(client, model); return model == null ? null : RestBan.Create(client, model);
} }
public static async Task AddBanAsync(IGuild guild, BaseDiscordClient client, public static Task AddBanAsync(IGuild guild, BaseDiscordClient client,
ulong userId, int pruneDays, string reason, RequestOptions options) ulong userId, int pruneDays, string reason, RequestOptions options)
{ {
var args = new CreateGuildBanParams { DeleteMessageDays = pruneDays, Reason = reason }; var args = new CreateGuildBanParams { DeleteMessageDays = pruneDays, Reason = reason };
await client.ApiClient.CreateGuildBanAsync(guild.Id, userId, args, options).ConfigureAwait(false); return client.ApiClient.CreateGuildBanAsync(guild.Id, userId, args, options);
}
public static async Task RemoveBanAsync(IGuild guild, BaseDiscordClient client,
ulong userId, RequestOptions options)
{
await client.ApiClient.RemoveGuildBanAsync(guild.Id, userId, options).ConfigureAwait(false);
} }
public static Task RemoveBanAsync(IGuild guild, BaseDiscordClient client, ulong userId, RequestOptions options)
=> client.ApiClient.RemoveGuildBanAsync(guild.Id, userId, options);
#endregion #endregion
#region Channels #region Channels
@@ -506,9 +504,9 @@ namespace Discord.Rest
var models = await client.ApiClient.GetIntegrationsAsync(guild.Id, options).ConfigureAwait(false); var models = await client.ApiClient.GetIntegrationsAsync(guild.Id, options).ConfigureAwait(false);
return models.Select(x => RestIntegration.Create(client, guild, x)).ToImmutableArray(); return models.Select(x => RestIntegration.Create(client, guild, x)).ToImmutableArray();
} }
public static async Task DeleteIntegrationAsync(IGuild guild, BaseDiscordClient client, ulong id,
RequestOptions options) => public static Task DeleteIntegrationAsync(IGuild guild, BaseDiscordClient client, ulong id, RequestOptions options)
await client.ApiClient.DeleteIntegrationAsync(guild.Id, id, options).ConfigureAwait(false); => client.ApiClient.DeleteIntegrationAsync(guild.Id, id, options);
#endregion #endregion
#region Interactions #region Interactions
@@ -611,7 +609,7 @@ namespace Discord.Rest
return model is null ? null : RestGuildUser.Create(client, guild, model); return model is null ? null : RestGuildUser.Create(client, guild, model);
} }
public static async Task AddGuildUserAsync(ulong guildId, BaseDiscordClient client, ulong userId, string accessToken, public static Task AddGuildUserAsync(ulong guildId, BaseDiscordClient client, ulong userId, string accessToken,
Action<AddGuildUserProperties> func, RequestOptions options) Action<AddGuildUserProperties> func, RequestOptions options)
{ {
var args = new AddGuildUserProperties(); var args = new AddGuildUserProperties();
@@ -635,7 +633,7 @@ namespace Discord.Rest
RoleIds = args.RoleIds.IsSpecified ? args.RoleIds.Value.Distinct().ToArray() : Optional.Create<ulong[]>() RoleIds = args.RoleIds.IsSpecified ? args.RoleIds.Value.Distinct().ToArray() : Optional.Create<ulong[]>()
}; };
await client.ApiClient.AddGuildMemberAsync(guildId, userId, apiArgs, options); return client.ApiClient.AddGuildMemberAsync(guildId, userId, apiArgs, options);
} }
public static async Task<RestGuildUser> GetUserAsync(IGuild guild, BaseDiscordClient client, public static async Task<RestGuildUser> GetUserAsync(IGuild guild, BaseDiscordClient client,
@@ -646,11 +644,9 @@ namespace Discord.Rest
return RestGuildUser.Create(client, guild, model); return RestGuildUser.Create(client, guild, model);
return null; return null;
} }
public static async Task<RestGuildUser> GetCurrentUserAsync(IGuild guild, BaseDiscordClient client, public static Task<RestGuildUser> GetCurrentUserAsync(IGuild guild, BaseDiscordClient client, RequestOptions options)
RequestOptions options) => GetUserAsync(guild, client, client.CurrentUser.Id, options);
{
return await GetUserAsync(guild, client, client.CurrentUser.Id, options).ConfigureAwait(false);
}
public static IAsyncEnumerable<IReadOnlyCollection<RestGuildUser>> GetUsersAsync(IGuild guild, BaseDiscordClient client, public static IAsyncEnumerable<IReadOnlyCollection<RestGuildUser>> GetUsersAsync(IGuild guild, BaseDiscordClient client,
ulong? fromUserId, int? limit, RequestOptions options) ulong? fromUserId, int? limit, RequestOptions options)
{ {
@@ -833,7 +829,7 @@ namespace Discord.Rest
return await client.ApiClient.CreateGuildStickerAsync(apiArgs, guild.Id, options).ConfigureAwait(false); return await client.ApiClient.CreateGuildStickerAsync(apiArgs, guild.Id, options).ConfigureAwait(false);
} }
public static async Task<API.Sticker> CreateStickerAsync(BaseDiscordClient client, IGuild guild, string name, Stream file, string filename, IEnumerable<string> tags, public static Task<API.Sticker> CreateStickerAsync(BaseDiscordClient client, IGuild guild, string name, Stream file, string filename, IEnumerable<string> tags,
string description = null, RequestOptions options = null) string description = null, RequestOptions options = null)
{ {
Preconditions.NotNull(name, nameof(name)); Preconditions.NotNull(name, nameof(name));
@@ -865,10 +861,10 @@ namespace Discord.Rest
FileName = filename FileName = filename
}; };
return await client.ApiClient.CreateGuildStickerAsync(apiArgs, guild.Id, options).ConfigureAwait(false); return client.ApiClient.CreateGuildStickerAsync(apiArgs, guild.Id, options);
} }
public static async Task<API.Sticker> ModifyStickerAsync(BaseDiscordClient client, ulong guildId, ISticker sticker, Action<StickerProperties> func, public static Task<API.Sticker> ModifyStickerAsync(BaseDiscordClient client, ulong guildId, ISticker sticker, Action<StickerProperties> func,
RequestOptions options = null) RequestOptions options = null)
{ {
if (func == null) if (func == null)
@@ -886,11 +882,11 @@ namespace Discord.Rest
Optional<string>.Unspecified Optional<string>.Unspecified
}; };
return await client.ApiClient.ModifyStickerAsync(apiArgs, guildId, sticker.Id, options).ConfigureAwait(false); return client.ApiClient.ModifyStickerAsync(apiArgs, guildId, sticker.Id, options);
} }
public static async Task DeleteStickerAsync(BaseDiscordClient client, ulong guildId, ISticker sticker, RequestOptions options = null) public static Task DeleteStickerAsync(BaseDiscordClient client, ulong guildId, ISticker sticker, RequestOptions options = null)
=> await client.ApiClient.DeleteStickerAsync(guildId, sticker.Id, options).ConfigureAwait(false); => client.ApiClient.DeleteStickerAsync(guildId, sticker.Id, options);
#endregion #endregion
#region Events #region Events
@@ -981,7 +977,7 @@ namespace Discord.Rest
); );
} }
public static async Task<API.GuildScheduledEvent> ModifyGuildEventAsync(BaseDiscordClient client, Action<GuildScheduledEventsProperties> func, public static Task<API.GuildScheduledEvent> ModifyGuildEventAsync(BaseDiscordClient client, Action<GuildScheduledEventsProperties> func,
IGuildScheduledEvent guildEvent, RequestOptions options = null) IGuildScheduledEvent guildEvent, RequestOptions options = null)
{ {
var args = new GuildScheduledEventsProperties(); var args = new GuildScheduledEventsProperties();
@@ -1042,7 +1038,7 @@ namespace Discord.Rest
}; };
} }
return await client.ApiClient.ModifyGuildScheduledEventAsync(apiArgs, guildEvent.Id, guildEvent.Guild.Id, options).ConfigureAwait(false); return client.ApiClient.ModifyGuildScheduledEventAsync(apiArgs, guildEvent.Id, guildEvent.Guild.Id, options);
} }
public static async Task<RestGuildEvent> GetGuildEventAsync(BaseDiscordClient client, ulong id, IGuild guild, RequestOptions options = null) public static async Task<RestGuildEvent> GetGuildEventAsync(BaseDiscordClient client, ulong id, IGuild guild, RequestOptions options = null)
@@ -1123,10 +1119,8 @@ namespace Discord.Rest
return RestGuildEvent.Create(client, guild, client.CurrentUser, model); return RestGuildEvent.Create(client, guild, client.CurrentUser, model);
} }
public static async Task DeleteEventAsync(BaseDiscordClient client, IGuildScheduledEvent guildEvent, RequestOptions options = null) public static Task DeleteEventAsync(BaseDiscordClient client, IGuildScheduledEvent guildEvent, RequestOptions options = null)
{ => client.ApiClient.DeleteGuildScheduledEventAsync(guildEvent.Id, guildEvent.Guild.Id, options);
await client.ApiClient.DeleteGuildScheduledEventAsync(guildEvent.Id, guildEvent.Guild.Id, options).ConfigureAwait(false);
}
#endregion #endregion
@@ -1180,7 +1174,7 @@ namespace Discord.Rest
#region Auto Mod #region Auto Mod
public static async Task<AutoModerationRule> CreateAutoModRuleAsync(IGuild guild, Action<AutoModRuleProperties> func, BaseDiscordClient client, RequestOptions options) public static Task<AutoModerationRule> CreateAutoModRuleAsync(IGuild guild, Action<AutoModRuleProperties> func, BaseDiscordClient client, RequestOptions options)
{ {
var args = new AutoModRuleProperties(); var args = new AutoModRuleProperties();
func(args); func(args);
@@ -1299,14 +1293,14 @@ namespace Discord.Rest
}, },
}; };
return await client.ApiClient.CreateGuildAutoModRuleAsync(guild.Id, props, options); return client.ApiClient.CreateGuildAutoModRuleAsync(guild.Id, props, options);
} }
public static async Task<AutoModerationRule> GetAutoModRuleAsync(ulong ruleId, IGuild guild, BaseDiscordClient client, RequestOptions options) public static Task<AutoModerationRule> GetAutoModRuleAsync(ulong ruleId, IGuild guild, BaseDiscordClient client, RequestOptions options)
=> await client.ApiClient.GetGuildAutoModRuleAsync(guild.Id, ruleId, options); => client.ApiClient.GetGuildAutoModRuleAsync(guild.Id, ruleId, options);
public static async Task<AutoModerationRule[]> GetAutoModRulesAsync(IGuild guild, BaseDiscordClient client, RequestOptions options) public static Task<AutoModerationRule[]> GetAutoModRulesAsync(IGuild guild, BaseDiscordClient client, RequestOptions options)
=> await client.ApiClient.GetGuildAutoModRulesAsync(guild.Id, options); => client.ApiClient.GetGuildAutoModRulesAsync(guild.Id, options);
public static Task<AutoModerationRule> ModifyRuleAsync(BaseDiscordClient client, IAutoModRule rule, Action<AutoModRuleProperties> func, RequestOptions options) public static Task<AutoModerationRule> ModifyRuleAsync(BaseDiscordClient client, IAutoModRule rule, Action<AutoModRuleProperties> func, RequestOptions options)
{ {
@@ -1354,10 +1348,10 @@ namespace Discord.Rest
#region Onboarding #region Onboarding
public static async Task<GuildOnboarding> GetGuildOnboardingAsync(IGuild guild, BaseDiscordClient client, RequestOptions options) public static Task<GuildOnboarding> GetGuildOnboardingAsync(IGuild guild, BaseDiscordClient client, RequestOptions options)
=> await client.ApiClient.GetGuildOnboardingAsync(guild.Id, options); => client.ApiClient.GetGuildOnboardingAsync(guild.Id, options);
public static async Task<GuildOnboarding> ModifyGuildOnboardingAsync(IGuild guild, Action<GuildOnboardingProperties> func, BaseDiscordClient client, RequestOptions options) public static Task<GuildOnboarding> ModifyGuildOnboardingAsync(IGuild guild, Action<GuildOnboardingProperties> func, BaseDiscordClient client, RequestOptions options)
{ {
var props = new GuildOnboardingProperties(); var props = new GuildOnboardingProperties();
func(props); func(props);
@@ -1394,7 +1388,7 @@ namespace Discord.Rest
: Optional<GuildOnboardingPromptParams[]>.Unspecified, : Optional<GuildOnboardingPromptParams[]>.Unspecified,
}; };
return await client.ApiClient.ModifyGuildOnboardingAsync(guild.Id, args, options); return client.ApiClient.ModifyGuildOnboardingAsync(guild.Id, args, options);
} }
#endregion #endregion

View File

@@ -296,10 +296,10 @@ namespace Discord.Rest
/// <inheritdoc /> /// <inheritdoc />
/// <exception cref="ArgumentNullException"><paramref name="args" /> is <see langword="null"/>.</exception> /// <exception cref="ArgumentNullException"><paramref name="args" /> is <see langword="null"/>.</exception>
public async Task ReorderChannelsAsync(IEnumerable<ReorderChannelProperties> args, RequestOptions options = null) public Task ReorderChannelsAsync(IEnumerable<ReorderChannelProperties> args, RequestOptions options = null)
{ {
var arr = args.ToArray(); var arr = args.ToArray();
await GuildHelper.ReorderChannelsAsync(this, Discord, arr, options).ConfigureAwait(false); return GuildHelper.ReorderChannelsAsync(this, Discord, arr, options);
} }
/// <inheritdoc /> /// <inheritdoc />
public async Task ReorderRolesAsync(IEnumerable<ReorderRoleProperties> args, RequestOptions options = null) public async Task ReorderRolesAsync(IEnumerable<ReorderRoleProperties> args, RequestOptions options = null)
@@ -670,12 +670,12 @@ namespace Discord.Rest
/// A task that represents the asynchronous get operation. The task result contains the widget channel set /// A task that represents the asynchronous get operation. The task result contains the widget channel set
/// within the server's widget settings; <see langword="null"/> if none is set. /// within the server's widget settings; <see langword="null"/> if none is set.
/// </returns> /// </returns>
public async Task<RestGuildChannel> GetWidgetChannelAsync(RequestOptions options = null) public Task<RestGuildChannel> GetWidgetChannelAsync(RequestOptions options = null)
{ {
var widgetChannelId = WidgetChannelId; var widgetChannelId = WidgetChannelId;
if (widgetChannelId.HasValue) if (widgetChannelId.HasValue)
return await GuildHelper.GetChannelAsync(this, Discord, widgetChannelId.Value, options).ConfigureAwait(false); return GuildHelper.GetChannelAsync(this, Discord, widgetChannelId.Value, options);
return null; return Task.FromResult<RestGuildChannel>(null);
} }
/// <summary> /// <summary>
@@ -1053,8 +1053,9 @@ namespace Discord.Rest
/// A task that represents the asynchronous get operation. The task result contains a read-only collection /// A task that represents the asynchronous get operation. The task result contains a read-only collection
/// of application commands found within the guild. /// of application commands found within the guild.
/// </returns> /// </returns>
public async Task<IReadOnlyCollection<RestGuildCommand>> GetApplicationCommandsAsync(bool withLocalizations = false, string locale = null, RequestOptions options = null) public Task<IReadOnlyCollection<RestGuildCommand>> GetApplicationCommandsAsync(bool withLocalizations = false, string locale = null, RequestOptions options = null)
=> await ClientHelper.GetGuildApplicationCommandsAsync(Discord, Id, withLocalizations, locale, options).ConfigureAwait(false); => ClientHelper.GetGuildApplicationCommandsAsync(Discord, Id, withLocalizations, locale, options);
/// <summary> /// <summary>
/// Gets an application command within this guild with the specified id. /// Gets an application command within this guild with the specified id.
/// </summary> /// </summary>
@@ -1064,8 +1065,9 @@ namespace Discord.Rest
/// A ValueTask that represents the asynchronous get operation. The task result contains a <see cref="IApplicationCommand"/> /// A ValueTask that represents the asynchronous get operation. The task result contains a <see cref="IApplicationCommand"/>
/// if found, otherwise <see langword="null"/>. /// if found, otherwise <see langword="null"/>.
/// </returns> /// </returns>
public async Task<RestGuildCommand> GetApplicationCommandAsync(ulong id, RequestOptions options = null) public Task<RestGuildCommand> GetApplicationCommandAsync(ulong id, RequestOptions options = null)
=> await ClientHelper.GetGuildApplicationCommandAsync(Discord, id, Id, options); => ClientHelper.GetGuildApplicationCommandAsync(Discord, id, Id, options);
/// <summary> /// <summary>
/// Creates an application command within this guild. /// Creates an application command within this guild.
/// </summary> /// </summary>
@@ -1168,6 +1170,7 @@ namespace Discord.Rest
using var fs = File.OpenRead(path); using var fs = File.OpenRead(path);
return await CreateStickerAsync(name, fs, Path.GetFileName(fs.Name), tags, description,options); return await CreateStickerAsync(name, fs, Path.GetFileName(fs.Name), tags, description,options);
} }
/// <summary> /// <summary>
/// Creates a new sticker in this guild /// Creates a new sticker in this guild
/// </summary> /// </summary>
@@ -1587,8 +1590,8 @@ namespace Discord.Rest
async Task<IReadOnlyCollection<IIntegration>> IGuild.GetIntegrationsAsync(RequestOptions options) async Task<IReadOnlyCollection<IIntegration>> IGuild.GetIntegrationsAsync(RequestOptions options)
=> await GetIntegrationsAsync(options).ConfigureAwait(false); => await GetIntegrationsAsync(options).ConfigureAwait(false);
/// <inheritdoc /> /// <inheritdoc />
async Task IGuild.DeleteIntegrationAsync(ulong id, RequestOptions options) Task IGuild.DeleteIntegrationAsync(ulong id, RequestOptions options)
=> await DeleteIntegrationAsync(id, options).ConfigureAwait(false); => DeleteIntegrationAsync(id, options);
/// <inheritdoc /> /// <inheritdoc />
async Task<IReadOnlyCollection<IInviteMetadata>> IGuild.GetInvitesAsync(RequestOptions options) async Task<IReadOnlyCollection<IInviteMetadata>> IGuild.GetInvitesAsync(RequestOptions options)
@@ -1616,7 +1619,8 @@ namespace Discord.Rest
/// </summary> /// </summary>
/// <param name="user">The user to disconnect.</param> /// <param name="user">The user to disconnect.</param>
/// <returns>A task that represents the asynchronous operation for disconnecting a user.</returns> /// <returns>A task that represents the asynchronous operation for disconnecting a user.</returns>
async Task IGuild.DisconnectAsync(IGuildUser user) => await user.ModifyAsync(x => x.Channel = null); Task IGuild.DisconnectAsync(IGuildUser user)
=> user.ModifyAsync(x => x.Channel = null);
/// <inheritdoc /> /// <inheritdoc />
async Task<IGuildUser> IGuild.GetUserAsync(ulong id, CacheMode mode, RequestOptions options) async Task<IGuildUser> IGuild.GetUserAsync(ulong id, CacheMode mode, RequestOptions options)

View File

@@ -52,10 +52,8 @@ namespace Discord.Rest
ApproximatePresenceCount = model.ApproximatePresenceCount.IsSpecified ? model.ApproximatePresenceCount.Value : null; ApproximatePresenceCount = model.ApproximatePresenceCount.IsSpecified ? model.ApproximatePresenceCount.Value : null;
} }
public async Task LeaveAsync(RequestOptions options = null) public Task LeaveAsync(RequestOptions options = null)
{ => Discord.ApiClient.LeaveGuildAsync(Id, options);
await Discord.ApiClient.LeaveGuildAsync(Id, options).ConfigureAwait(false);
}
public async Task<RestGuildUser> GetCurrentUserGuildMemberAsync(RequestOptions options = null) public async Task<RestGuildUser> GetCurrentUserGuildMemberAsync(RequestOptions options = null)
{ {
@@ -64,10 +62,8 @@ namespace Discord.Rest
} }
/// <inheritdoc /> /// <inheritdoc />
public async Task DeleteAsync(RequestOptions options = null) public Task DeleteAsync(RequestOptions options = null)
{ => Discord.ApiClient.DeleteGuildAsync(Id, options);
await Discord.ApiClient.DeleteGuildAsync(Id, options).ConfigureAwait(false);
}
public override string ToString() => Name; public override string ToString() => Name;
private string DebuggerDisplay => $"{Name} ({Id}{(IsOwner ? ", Owned" : "")})"; private string DebuggerDisplay => $"{Name} ({Id}{(IsOwner ? ", Owned" : "")})";

View File

@@ -77,10 +77,8 @@ namespace Discord.Rest
_syncedAtTicks = model.SyncedAt.IsSpecified ? model.SyncedAt.Value.UtcTicks : null; _syncedAtTicks = model.SyncedAt.IsSpecified ? model.SyncedAt.Value.UtcTicks : null;
} }
public async Task DeleteAsync() public Task DeleteAsync()
{ => Discord.ApiClient.DeleteIntegrationAsync(GuildId, Id);
await Discord.ApiClient.DeleteIntegrationAsync(GuildId, Id).ConfigureAwait(false);
}
public override string ToString() => Name; public override string ToString() => Name;
private string DebuggerDisplay => $"{Name} ({Id}{(IsEnabled ? ", Enabled" : "")})"; private string DebuggerDisplay => $"{Name} ({Id}{(IsEnabled ? ", Enabled" : "")})";

View File

@@ -138,7 +138,7 @@ namespace Discord.Rest
} }
/// <inheritdoc/> /// <inheritdoc/>
public override async Task<RestFollowupMessage> FollowupAsync( public override Task<RestFollowupMessage> FollowupAsync(
string text = null, string text = null,
Embed[] embeds = null, Embed[] embeds = null,
bool isTTS = false, bool isTTS = false,
@@ -171,7 +171,7 @@ namespace Discord.Rest
if (ephemeral) if (ephemeral)
args.Flags = MessageFlags.Ephemeral; args.Flags = MessageFlags.Ephemeral;
return await InteractionHelper.SendFollowupAsync(Discord, args, Token, Channel, options); return InteractionHelper.SendFollowupAsync(Discord, args, Token, Channel, options);
} }
/// <inheritdoc/> /// <inheritdoc/>
@@ -235,7 +235,7 @@ namespace Discord.Rest
} }
/// <inheritdoc/> /// <inheritdoc/>
public override async Task<RestFollowupMessage> FollowupWithFilesAsync( public override Task<RestFollowupMessage> FollowupWithFilesAsync(
IEnumerable<FileAttachment> attachments, IEnumerable<FileAttachment> attachments,
string text = null, string text = null,
Embed[] embeds = null, Embed[] embeds = null,
@@ -284,7 +284,7 @@ namespace Discord.Rest
flags |= MessageFlags.Ephemeral; flags |= MessageFlags.Ephemeral;
var args = new API.Rest.UploadWebhookFileParams(attachments.ToArray()) { Flags = flags, Content = text, IsTTS = isTTS, Embeds = embeds.Any() ? embeds.Select(x => x.ToModel()).ToArray() : Optional<API.Embed[]>.Unspecified, AllowedMentions = allowedMentions?.ToModel() ?? Optional<API.AllowedMentions>.Unspecified, MessageComponents = components?.Components.Select(x => new API.ActionRowComponent(x)).ToArray() ?? Optional<API.ActionRowComponent[]>.Unspecified }; var args = new API.Rest.UploadWebhookFileParams(attachments.ToArray()) { Flags = flags, Content = text, IsTTS = isTTS, Embeds = embeds.Any() ? embeds.Select(x => x.ToModel()).ToArray() : Optional<API.Embed[]>.Unspecified, AllowedMentions = allowedMentions?.ToModel() ?? Optional<API.AllowedMentions>.Unspecified, MessageComponents = components?.Components.Select(x => new API.ActionRowComponent(x)).ToArray() ?? Optional<API.ActionRowComponent[]>.Unspecified };
return await InteractionHelper.SendFollowupAsync(Discord, args, Token, Channel, options).ConfigureAwait(false); return InteractionHelper.SendFollowupAsync(Discord, args, Token, Channel, options);
} }
/// <summary> /// <summary>

View File

@@ -34,14 +34,15 @@ namespace Discord.Rest
return entity; return entity;
} }
internal virtual async Task UpdateAsync(DiscordRestClient client, Model model, RestGuild guild, IRestMessageChannel channel, bool doApiCall) internal virtual Task UpdateAsync(DiscordRestClient client, Model model, RestGuild guild, IRestMessageChannel channel, bool doApiCall)
{ {
Name = model.Name; Name = model.Name;
if (model.Resolved.IsSpecified && ResolvableData == null) if (model.Resolved.IsSpecified && ResolvableData == null)
{ {
ResolvableData = new RestResolvableData<Model>(); ResolvableData = new RestResolvableData<Model>();
await ResolvableData.PopulateAsync(client, guild, channel, model, doApiCall).ConfigureAwait(false); return ResolvableData.PopulateAsync(client, guild, channel, model, doApiCall);
} }
return Task.CompletedTask;
} }
IReadOnlyCollection<IApplicationCommandInteractionDataOption> IApplicationCommandInteractionData.Options IReadOnlyCollection<IApplicationCommandInteractionDataOption> IApplicationCommandInteractionData.Options

View File

@@ -35,17 +35,13 @@ namespace Discord.Rest
return client.ApiClient.BulkOverwriteGlobalApplicationCommandsAsync(Array.Empty<CreateApplicationCommandParams>(), options); return client.ApiClient.BulkOverwriteGlobalApplicationCommandsAsync(Array.Empty<CreateApplicationCommandParams>(), options);
} }
public static async Task SendInteractionResponseAsync(BaseDiscordClient client, InteractionResponse response, public static Task SendInteractionResponseAsync(BaseDiscordClient client, InteractionResponse response,
IDiscordInteraction interaction, IMessageChannel channel = null, RequestOptions options = null) IDiscordInteraction interaction, IMessageChannel channel = null, RequestOptions options = null)
{ => client.ApiClient.CreateInteractionResponseAsync(response, interaction.Id, interaction.Token, options);
await client.ApiClient.CreateInteractionResponseAsync(response, interaction.Id, interaction.Token, options).ConfigureAwait(false);
}
public static async Task SendInteractionResponseAsync(BaseDiscordClient client, UploadInteractionFileParams response, public static Task SendInteractionResponseAsync(BaseDiscordClient client, UploadInteractionFileParams response,
IDiscordInteraction interaction, IMessageChannel channel = null, RequestOptions options = null) IDiscordInteraction interaction, IMessageChannel channel = null, RequestOptions options = null)
{ => client.ApiClient.CreateInteractionResponseAsync(response, interaction.Id, interaction.Token, options);
await client.ApiClient.CreateInteractionResponseAsync(response, interaction.Id, interaction.Token, options).ConfigureAwait(false);
}
public static async Task<RestInteractionMessage> GetOriginalResponseAsync(BaseDiscordClient client, IMessageChannel channel, public static async Task<RestInteractionMessage> GetOriginalResponseAsync(BaseDiscordClient client, IMessageChannel channel,
IDiscordInteraction interaction, RequestOptions options = null) IDiscordInteraction interaction, RequestOptions options = null)
@@ -90,7 +86,8 @@ namespace Discord.Rest
func((TArg)args); func((TArg)args);
return CreateGlobalCommandAsync(client, (TArg)args, options); return CreateGlobalCommandAsync(client, (TArg)args, options);
} }
public static async Task<ApplicationCommand> CreateGlobalCommandAsync(BaseDiscordClient client,
public static Task<ApplicationCommand> CreateGlobalCommandAsync(BaseDiscordClient client,
ApplicationCommandProperties arg, RequestOptions options = null) ApplicationCommandProperties arg, RequestOptions options = null)
{ {
Preconditions.NotNullOrEmpty(arg.Name, nameof(arg.Name)); Preconditions.NotNullOrEmpty(arg.Name, nameof(arg.Name));
@@ -122,10 +119,10 @@ namespace Discord.Rest
: Optional<ApplicationCommandOption[]>.Unspecified; : Optional<ApplicationCommandOption[]>.Unspecified;
} }
return await client.ApiClient.CreateGlobalApplicationCommandAsync(model, options).ConfigureAwait(false); return client.ApiClient.CreateGlobalApplicationCommandAsync(model, options);
} }
public static async Task<ApplicationCommand[]> BulkOverwriteGlobalCommandsAsync(BaseDiscordClient client, public static Task<ApplicationCommand[]> BulkOverwriteGlobalCommandsAsync(BaseDiscordClient client,
ApplicationCommandProperties[] args, RequestOptions options = null) ApplicationCommandProperties[] args, RequestOptions options = null)
{ {
Preconditions.NotNull(args, nameof(args)); Preconditions.NotNull(args, nameof(args));
@@ -166,7 +163,7 @@ namespace Discord.Rest
models.Add(model); models.Add(model);
} }
return await client.ApiClient.BulkOverwriteGlobalApplicationCommandsAsync(models.ToArray(), options).ConfigureAwait(false); return client.ApiClient.BulkOverwriteGlobalApplicationCommandsAsync(models.ToArray(), options);
} }
public static async Task<IReadOnlyCollection<ApplicationCommand>> BulkOverwriteGuildCommandsAsync(BaseDiscordClient client, ulong guildId, public static async Task<IReadOnlyCollection<ApplicationCommand>> BulkOverwriteGuildCommandsAsync(BaseDiscordClient client, ulong guildId,
@@ -239,7 +236,7 @@ namespace Discord.Rest
return ModifyGlobalCommandAsync(client, command, arg, options); return ModifyGlobalCommandAsync(client, command, arg, options);
} }
public static async Task<ApplicationCommand> ModifyGlobalCommandAsync(BaseDiscordClient client, IApplicationCommand command, public static Task<ApplicationCommand> ModifyGlobalCommandAsync(BaseDiscordClient client, IApplicationCommand command,
ApplicationCommandProperties args, RequestOptions options = null) ApplicationCommandProperties args, RequestOptions options = null)
{ {
if (args.Name.IsSpecified) if (args.Name.IsSpecified)
@@ -281,15 +278,15 @@ namespace Discord.Rest
: Optional<ApplicationCommandOption[]>.Unspecified; : Optional<ApplicationCommandOption[]>.Unspecified;
} }
return await client.ApiClient.ModifyGlobalApplicationCommandAsync(model, command.Id, options).ConfigureAwait(false); return client.ApiClient.ModifyGlobalApplicationCommandAsync(model, command.Id, options);
} }
public static async Task DeleteGlobalCommandAsync(BaseDiscordClient client, IApplicationCommand command, RequestOptions options = null) public static Task DeleteGlobalCommandAsync(BaseDiscordClient client, IApplicationCommand command, RequestOptions options = null)
{ {
Preconditions.NotNull(command, nameof(command)); Preconditions.NotNull(command, nameof(command));
Preconditions.NotEqual(command.Id, 0, nameof(command.Id)); Preconditions.NotEqual(command.Id, 0, nameof(command.Id));
await client.ApiClient.DeleteGlobalApplicationCommandAsync(command.Id, options).ConfigureAwait(false); return client.ApiClient.DeleteGlobalApplicationCommandAsync(command.Id, options);
} }
#endregion #endregion
@@ -302,7 +299,7 @@ namespace Discord.Rest
return CreateGuildCommandAsync(client, guildId, (TArg)args, options); return CreateGuildCommandAsync(client, guildId, (TArg)args, options);
} }
public static async Task<ApplicationCommand> CreateGuildCommandAsync(BaseDiscordClient client, ulong guildId, public static Task<ApplicationCommand> CreateGuildCommandAsync(BaseDiscordClient client, ulong guildId,
ApplicationCommandProperties arg, RequestOptions options = null) ApplicationCommandProperties arg, RequestOptions options = null)
{ {
var model = new CreateApplicationCommandParams var model = new CreateApplicationCommandParams
@@ -332,7 +329,7 @@ namespace Discord.Rest
: Optional<ApplicationCommandOption[]>.Unspecified; : Optional<ApplicationCommandOption[]>.Unspecified;
} }
return await client.ApiClient.CreateGuildApplicationCommandAsync(model, guildId, options).ConfigureAwait(false); return client.ApiClient.CreateGuildApplicationCommandAsync(model, guildId, options);
} }
public static Task<ApplicationCommand> ModifyGuildCommandAsync<TArg>(BaseDiscordClient client, IApplicationCommand command, ulong guildId, public static Task<ApplicationCommand> ModifyGuildCommandAsync<TArg>(BaseDiscordClient client, IApplicationCommand command, ulong guildId,
@@ -343,7 +340,7 @@ namespace Discord.Rest
return ModifyGuildCommandAsync(client, command, guildId, arg, options); return ModifyGuildCommandAsync(client, command, guildId, arg, options);
} }
public static async Task<ApplicationCommand> ModifyGuildCommandAsync(BaseDiscordClient client, IApplicationCommand command, ulong guildId, public static Task<ApplicationCommand> ModifyGuildCommandAsync(BaseDiscordClient client, IApplicationCommand command, ulong guildId,
ApplicationCommandProperties arg, RequestOptions options = null) ApplicationCommandProperties arg, RequestOptions options = null)
{ {
var model = new ModifyApplicationCommandParams var model = new ModifyApplicationCommandParams
@@ -369,15 +366,15 @@ namespace Discord.Rest
: Optional<ApplicationCommandOption[]>.Unspecified; : Optional<ApplicationCommandOption[]>.Unspecified;
} }
return await client.ApiClient.ModifyGuildApplicationCommandAsync(model, guildId, command.Id, options).ConfigureAwait(false); return client.ApiClient.ModifyGuildApplicationCommandAsync(model, guildId, command.Id, options);
} }
public static async Task DeleteGuildCommandAsync(BaseDiscordClient client, ulong guildId, IApplicationCommand command, RequestOptions options = null) public static Task DeleteGuildCommandAsync(BaseDiscordClient client, ulong guildId, IApplicationCommand command, RequestOptions options = null)
{ {
Preconditions.NotNull(command, nameof(command)); Preconditions.NotNull(command, nameof(command));
Preconditions.NotEqual(command.Id, 0, nameof(command.Id)); Preconditions.NotEqual(command.Id, 0, nameof(command.Id));
await client.ApiClient.DeleteGuildApplicationCommandAsync(guildId, command.Id, options).ConfigureAwait(false); return client.ApiClient.DeleteGuildApplicationCommandAsync(guildId, command.Id, options);
} }
public static Task DeleteUnknownApplicationCommandAsync(BaseDiscordClient client, ulong? guildId, IApplicationCommand command, RequestOptions options = null) public static Task DeleteUnknownApplicationCommandAsync(BaseDiscordClient client, ulong? guildId, IApplicationCommand command, RequestOptions options = null)
@@ -389,7 +386,7 @@ namespace Discord.Rest
#endregion #endregion
#region Responses #region Responses
public static async Task<Discord.API.Message> ModifyFollowupMessageAsync(BaseDiscordClient client, RestFollowupMessage message, Action<MessageProperties> func, public static Task<Discord.API.Message> ModifyFollowupMessageAsync(BaseDiscordClient client, RestFollowupMessage message, Action<MessageProperties> func,
RequestOptions options = null) RequestOptions options = null)
{ {
var args = new MessageProperties(); var args = new MessageProperties();
@@ -429,11 +426,13 @@ namespace Discord.Rest
: Optional<API.ActionRowComponent[]>.Unspecified, : Optional<API.ActionRowComponent[]>.Unspecified,
}; };
return await client.ApiClient.ModifyInteractionFollowupMessageAsync(apiArgs, message.Id, message.Token, options).ConfigureAwait(false); return client.ApiClient.ModifyInteractionFollowupMessageAsync(apiArgs, message.Id, message.Token, options);
} }
public static async Task DeleteFollowupMessageAsync(BaseDiscordClient client, RestFollowupMessage message, RequestOptions options = null)
=> await client.ApiClient.DeleteInteractionFollowupMessageAsync(message.Id, message.Token, options); public static Task DeleteFollowupMessageAsync(BaseDiscordClient client, RestFollowupMessage message, RequestOptions options = null)
public static async Task<API.Message> ModifyInteractionResponseAsync(BaseDiscordClient client, string token, Action<MessageProperties> func, => client.ApiClient.DeleteInteractionFollowupMessageAsync(message.Id, message.Token, options);
public static Task<API.Message> ModifyInteractionResponseAsync(BaseDiscordClient client, string token, Action<MessageProperties> func,
RequestOptions options = null) RequestOptions options = null)
{ {
var args = new MessageProperties(); var args = new MessageProperties();
@@ -476,7 +475,7 @@ namespace Discord.Rest
Flags = args.Flags Flags = args.Flags
}; };
return await client.ApiClient.ModifyInteractionResponseAsync(apiArgs, token, options).ConfigureAwait(false); return client.ApiClient.ModifyInteractionResponseAsync(apiArgs, token, options);
} }
else else
{ {
@@ -492,15 +491,15 @@ namespace Discord.Rest
: Optional<API.ActionRowComponent[]>.Unspecified : Optional<API.ActionRowComponent[]>.Unspecified
}; };
return await client.ApiClient.ModifyInteractionResponseAsync(apiArgs, token, options).ConfigureAwait(false); return client.ApiClient.ModifyInteractionResponseAsync(apiArgs, token, options);
} }
} }
public static async Task DeleteInteractionResponseAsync(BaseDiscordClient client, RestInteractionMessage message, RequestOptions options = null) public static Task DeleteInteractionResponseAsync(BaseDiscordClient client, RestInteractionMessage message, RequestOptions options = null)
=> await client.ApiClient.DeleteInteractionResponseAsync(message.Token, options); => client.ApiClient.DeleteInteractionResponseAsync(message.Token, options);
public static async Task DeleteInteractionResponseAsync(BaseDiscordClient client, IDiscordInteraction interaction, RequestOptions options = null) public static Task DeleteInteractionResponseAsync(BaseDiscordClient client, IDiscordInteraction interaction, RequestOptions options = null)
=> await client.ApiClient.DeleteInteractionResponseAsync(interaction.Token, options); => client.ApiClient.DeleteInteractionResponseAsync(interaction.Token, options);
public static Task SendAutocompleteResultAsync(BaseDiscordClient client, IEnumerable<AutocompleteResult> result, ulong interactionId, public static Task SendAutocompleteResultAsync(BaseDiscordClient client, IEnumerable<AutocompleteResult> result, ulong interactionId,
string interactionToken, RequestOptions options) string interactionToken, RequestOptions options)
@@ -523,10 +522,10 @@ namespace Discord.Rest
return client.ApiClient.CreateInteractionResponseAsync(apiArgs, interactionId, interactionToken, options); return client.ApiClient.CreateInteractionResponseAsync(apiArgs, interactionId, interactionToken, options);
} }
public static async Task RespondWithPremiumRequiredAsync(BaseDiscordClient client, ulong interactionId, public static Task RespondWithPremiumRequiredAsync(BaseDiscordClient client, ulong interactionId,
string interactionToken, RequestOptions options = null) string interactionToken, RequestOptions options = null)
{ {
await client.ApiClient.CreateInteractionResponseAsync(new InteractionResponse return client.ApiClient.CreateInteractionResponseAsync(new InteractionResponse
{ {
Type = InteractionResponseType.PremiumRequired, Type = InteractionResponseType.PremiumRequired,
Data = Optional<InteractionCallbackData>.Unspecified Data = Optional<InteractionCallbackData>.Unspecified

View File

@@ -243,7 +243,7 @@ namespace Discord.Rest
} }
/// <inheritdoc/> /// <inheritdoc/>
public override async Task<RestFollowupMessage> FollowupAsync( public override Task<RestFollowupMessage> FollowupAsync(
string text = null, string text = null,
Embed[] embeds = null, Embed[] embeds = null,
bool isTTS = false, bool isTTS = false,
@@ -276,7 +276,7 @@ namespace Discord.Rest
if (ephemeral) if (ephemeral)
args.Flags = MessageFlags.Ephemeral; args.Flags = MessageFlags.Ephemeral;
return await InteractionHelper.SendFollowupAsync(Discord, args, Token, Channel, options); return InteractionHelper.SendFollowupAsync(Discord, args, Token, Channel, options);
} }
/// <inheritdoc/> /// <inheritdoc/>
@@ -340,7 +340,7 @@ namespace Discord.Rest
} }
/// <inheritdoc/> /// <inheritdoc/>
public override async Task<RestFollowupMessage> FollowupWithFilesAsync( public override Task<RestFollowupMessage> FollowupWithFilesAsync(
IEnumerable<FileAttachment> attachments, IEnumerable<FileAttachment> attachments,
string text = null, string text = null,
Embed[] embeds = null, Embed[] embeds = null,
@@ -389,7 +389,7 @@ namespace Discord.Rest
flags |= MessageFlags.Ephemeral; flags |= MessageFlags.Ephemeral;
var args = new API.Rest.UploadWebhookFileParams(attachments.ToArray()) { Flags = flags, Content = text, IsTTS = isTTS, Embeds = embeds.Any() ? embeds.Select(x => x.ToModel()).ToArray() : Optional<API.Embed[]>.Unspecified, AllowedMentions = allowedMentions?.ToModel() ?? Optional<API.AllowedMentions>.Unspecified, MessageComponents = components?.Components.Select(x => new API.ActionRowComponent(x)).ToArray() ?? Optional<API.ActionRowComponent[]>.Unspecified }; var args = new API.Rest.UploadWebhookFileParams(attachments.ToArray()) { Flags = flags, Content = text, IsTTS = isTTS, Embeds = embeds.Any() ? embeds.Select(x => x.ToModel()).ToArray() : Optional<API.Embed[]>.Unspecified, AllowedMentions = allowedMentions?.ToModel() ?? Optional<API.AllowedMentions>.Unspecified, MessageComponents = components?.Components.Select(x => new API.ActionRowComponent(x)).ToArray() ?? Optional<API.ActionRowComponent[]>.Unspecified };
return await InteractionHelper.SendFollowupAsync(Discord, args, Token, Channel, options).ConfigureAwait(false); return InteractionHelper.SendFollowupAsync(Discord, args, Token, Channel, options);
} }
/// <summary> /// <summary>

View File

@@ -128,7 +128,7 @@ namespace Discord.Rest
/// <returns> /// <returns>
/// The sent message. /// The sent message.
/// </returns> /// </returns>
public override async Task<RestFollowupMessage> FollowupAsync( public override Task<RestFollowupMessage> FollowupAsync(
string text = null, string text = null,
Embed[] embeds = null, Embed[] embeds = null,
bool isTTS = false, bool isTTS = false,
@@ -161,7 +161,7 @@ namespace Discord.Rest
if (ephemeral) if (ephemeral)
args.Flags = MessageFlags.Ephemeral; args.Flags = MessageFlags.Ephemeral;
return await InteractionHelper.SendFollowupAsync(Discord, args, Token, Channel, options); return InteractionHelper.SendFollowupAsync(Discord, args, Token, Channel, options);
} }
/// <summary> /// <summary>
@@ -180,7 +180,7 @@ namespace Discord.Rest
/// <returns> /// <returns>
/// The sent message. /// The sent message.
/// </returns> /// </returns>
public override async Task<RestFollowupMessage> FollowupWithFileAsync( public override Task<RestFollowupMessage> FollowupWithFileAsync(
Stream fileStream, Stream fileStream,
string fileName, string fileName,
string text = null, string text = null,
@@ -218,7 +218,7 @@ namespace Discord.Rest
if (ephemeral) if (ephemeral)
args.Flags = MessageFlags.Ephemeral; args.Flags = MessageFlags.Ephemeral;
return await InteractionHelper.SendFollowupAsync(Discord, args, Token, Channel, options); return InteractionHelper.SendFollowupAsync(Discord, args, Token, Channel, options);
} }
/// <summary> /// <summary>
@@ -368,7 +368,7 @@ namespace Discord.Rest
} }
/// <inheritdoc/> /// <inheritdoc/>
public override async Task<RestFollowupMessage> FollowupWithFilesAsync( public override Task<RestFollowupMessage> FollowupWithFilesAsync(
IEnumerable<FileAttachment> attachments, IEnumerable<FileAttachment> attachments,
string text = null, string text = null,
Embed[] embeds = null, Embed[] embeds = null,
@@ -417,7 +417,7 @@ namespace Discord.Rest
flags |= MessageFlags.Ephemeral; flags |= MessageFlags.Ephemeral;
var args = new API.Rest.UploadWebhookFileParams(attachments.ToArray()) { Flags = flags, Content = text, IsTTS = isTTS, Embeds = embeds.Any() ? embeds.Select(x => x.ToModel()).ToArray() : Optional<API.Embed[]>.Unspecified, AllowedMentions = allowedMentions?.ToModel() ?? Optional<API.AllowedMentions>.Unspecified, MessageComponents = components?.Components.Select(x => new API.ActionRowComponent(x)).ToArray() ?? Optional<API.ActionRowComponent[]>.Unspecified }; var args = new API.Rest.UploadWebhookFileParams(attachments.ToArray()) { Flags = flags, Content = text, IsTTS = isTTS, Embeds = embeds.Any() ? embeds.Select(x => x.ToModel()).ToArray() : Optional<API.Embed[]>.Unspecified, AllowedMentions = allowedMentions?.ToModel() ?? Optional<API.AllowedMentions>.Unspecified, MessageComponents = components?.Components.Select(x => new API.ActionRowComponent(x)).ToArray() ?? Optional<API.ActionRowComponent[]>.Unspecified };
return await InteractionHelper.SendFollowupAsync(Discord, args, Token, Channel, options).ConfigureAwait(false); return InteractionHelper.SendFollowupAsync(Discord, args, Token, Channel, options);
} }
/// <inheritdoc/> /// <inheritdoc/>

View File

@@ -20,8 +20,8 @@ namespace Discord.Rest
} }
/// <inheritdoc/> /// <inheritdoc/>
public override async Task DeleteAsync(RequestOptions options = null) public override Task DeleteAsync(RequestOptions options = null)
=> await InteractionHelper.DeleteGlobalCommandAsync(Discord, this).ConfigureAwait(false); => InteractionHelper.DeleteGlobalCommandAsync(Discord, this);
/// <summary> /// <summary>
/// Modifies this <see cref="RestApplicationCommand"/>. /// Modifies this <see cref="RestApplicationCommand"/>.

View File

@@ -28,8 +28,8 @@ namespace Discord.Rest
} }
/// <inheritdoc/> /// <inheritdoc/>
public override async Task DeleteAsync(RequestOptions options = null) public override Task DeleteAsync(RequestOptions options = null)
=> await InteractionHelper.DeleteGuildCommandAsync(Discord, GuildId, this).ConfigureAwait(false); => InteractionHelper.DeleteGuildCommandAsync(Discord, GuildId, this);
/// <summary> /// <summary>
/// Modifies this <see cref="RestApplicationCommand"/>. /// Modifies this <see cref="RestApplicationCommand"/>.

View File

@@ -4,10 +4,7 @@ namespace Discord.Rest
{ {
internal static class InviteHelper internal static class InviteHelper
{ {
public static async Task DeleteAsync(IInvite invite, BaseDiscordClient client, public static Task DeleteAsync(IInvite invite, BaseDiscordClient client, RequestOptions options)
RequestOptions options) => client.ApiClient.DeleteInviteAsync(invite.Code, options);
{
await client.ApiClient.DeleteInviteAsync(invite.Code, options).ConfigureAwait(false);
}
} }
} }

View File

@@ -29,7 +29,7 @@ namespace Discord.Rest
RequestOptions options) RequestOptions options)
=> ModifyAsync(msg.Channel.Id, msg.Id, client, func, options); => ModifyAsync(msg.Channel.Id, msg.Id, client, func, options);
public static async Task<Model> ModifyAsync(ulong channelId, ulong msgId, BaseDiscordClient client, Action<MessageProperties> func, public static Task<Model> ModifyAsync(ulong channelId, ulong msgId, BaseDiscordClient client, Action<MessageProperties> func,
RequestOptions options) RequestOptions options)
{ {
var args = new MessageProperties(); var args = new MessageProperties();
@@ -95,7 +95,7 @@ namespace Discord.Rest
AllowedMentions = args.AllowedMentions.IsSpecified ? args.AllowedMentions.Value.ToModel() : Optional.Create<API.AllowedMentions>(), AllowedMentions = args.AllowedMentions.IsSpecified ? args.AllowedMentions.Value.ToModel() : Optional.Create<API.AllowedMentions>(),
Components = args.Components.IsSpecified ? args.Components.Value?.Components.Select(x => new API.ActionRowComponent(x)).ToArray() ?? Array.Empty<API.ActionRowComponent>() : Optional<API.ActionRowComponent[]>.Unspecified, Components = args.Components.IsSpecified ? args.Components.Value?.Components.Select(x => new API.ActionRowComponent(x)).ToArray() ?? Array.Empty<API.ActionRowComponent>() : Optional<API.ActionRowComponent[]>.Unspecified,
}; };
return await client.ApiClient.ModifyMessageAsync(channelId, msgId, apiArgs, options).ConfigureAwait(false); return client.ApiClient.ModifyMessageAsync(channelId, msgId, apiArgs, options);
} }
else else
{ {
@@ -110,58 +110,39 @@ namespace Discord.Rest
MessageComponent = args.Components.IsSpecified ? args.Components.Value?.Components.Select(x => new API.ActionRowComponent(x)).ToArray() ?? Array.Empty<API.ActionRowComponent>() : Optional<API.ActionRowComponent[]>.Unspecified MessageComponent = args.Components.IsSpecified ? args.Components.Value?.Components.Select(x => new API.ActionRowComponent(x)).ToArray() ?? Array.Empty<API.ActionRowComponent>() : Optional<API.ActionRowComponent[]>.Unspecified
}; };
return await client.ApiClient.ModifyMessageAsync(channelId, msgId, apiArgs, options).ConfigureAwait(false); return client.ApiClient.ModifyMessageAsync(channelId, msgId, apiArgs, options);
} }
} }
public static Task DeleteAsync(IMessage msg, BaseDiscordClient client, RequestOptions options) public static Task DeleteAsync(IMessage msg, BaseDiscordClient client, RequestOptions options)
=> DeleteAsync(msg.Channel.Id, msg.Id, client, options); => DeleteAsync(msg.Channel.Id, msg.Id, client, options);
public static async Task DeleteAsync(ulong channelId, ulong msgId, BaseDiscordClient client, public static Task DeleteAsync(ulong channelId, ulong msgId, BaseDiscordClient client, RequestOptions options)
RequestOptions options) => client.ApiClient.DeleteMessageAsync(channelId, msgId, options);
{
await client.ApiClient.DeleteMessageAsync(channelId, msgId, options).ConfigureAwait(false);
}
public static async Task AddReactionAsync(ulong channelId, ulong messageId, IEmote emote, BaseDiscordClient client, RequestOptions options) public static Task AddReactionAsync(ulong channelId, ulong messageId, IEmote emote, BaseDiscordClient client, RequestOptions options)
{ => client.ApiClient.AddReactionAsync(channelId, messageId, emote is Emote e ? $"{e.Name}:{e.Id}" : UrlEncode(emote.Name), options);
await client.ApiClient.AddReactionAsync(channelId, messageId, emote is Emote e ? $"{e.Name}:{e.Id}" : UrlEncode(emote.Name), options).ConfigureAwait(false);
}
public static async Task AddReactionAsync(IMessage msg, IEmote emote, BaseDiscordClient client, RequestOptions options) public static Task AddReactionAsync(IMessage msg, IEmote emote, BaseDiscordClient client, RequestOptions options)
{ => client.ApiClient.AddReactionAsync(msg.Channel.Id, msg.Id, emote is Emote e ? $"{e.Name}:{e.Id}" : UrlEncode(emote.Name), options);
await client.ApiClient.AddReactionAsync(msg.Channel.Id, msg.Id, emote is Emote e ? $"{e.Name}:{e.Id}" : UrlEncode(emote.Name), options).ConfigureAwait(false);
}
public static async Task RemoveReactionAsync(ulong channelId, ulong messageId, ulong userId, IEmote emote, BaseDiscordClient client, RequestOptions options) public static Task RemoveReactionAsync(ulong channelId, ulong messageId, ulong userId, IEmote emote, BaseDiscordClient client, RequestOptions options)
{ => client.ApiClient.RemoveReactionAsync(channelId, messageId, userId, emote is Emote e ? $"{e.Name}:{e.Id}" : UrlEncode(emote.Name), options);
await client.ApiClient.RemoveReactionAsync(channelId, messageId, userId, emote is Emote e ? $"{e.Name}:{e.Id}" : UrlEncode(emote.Name), options).ConfigureAwait(false);
}
public static async Task RemoveReactionAsync(IMessage msg, ulong userId, IEmote emote, BaseDiscordClient client, RequestOptions options) public static Task RemoveReactionAsync(IMessage msg, ulong userId, IEmote emote, BaseDiscordClient client, RequestOptions options)
{ => client.ApiClient.RemoveReactionAsync(msg.Channel.Id, msg.Id, userId, emote is Emote e ? $"{e.Name}:{e.Id}" : UrlEncode(emote.Name), options);
await client.ApiClient.RemoveReactionAsync(msg.Channel.Id, msg.Id, userId, emote is Emote e ? $"{e.Name}:{e.Id}" : UrlEncode(emote.Name), options).ConfigureAwait(false);
}
public static async Task RemoveAllReactionsAsync(ulong channelId, ulong messageId, BaseDiscordClient client, RequestOptions options) public static Task RemoveAllReactionsAsync(ulong channelId, ulong messageId, BaseDiscordClient client, RequestOptions options)
{ => client.ApiClient.RemoveAllReactionsAsync(channelId, messageId, options);
await client.ApiClient.RemoveAllReactionsAsync(channelId, messageId, options).ConfigureAwait(false);
}
public static async Task RemoveAllReactionsAsync(IMessage msg, BaseDiscordClient client, RequestOptions options) public static Task RemoveAllReactionsAsync(IMessage msg, BaseDiscordClient client, RequestOptions options)
{ => client.ApiClient.RemoveAllReactionsAsync(msg.Channel.Id, msg.Id, options);
await client.ApiClient.RemoveAllReactionsAsync(msg.Channel.Id, msg.Id, options).ConfigureAwait(false);
}
public static async Task RemoveAllReactionsForEmoteAsync(ulong channelId, ulong messageId, IEmote emote, BaseDiscordClient client, RequestOptions options) public static Task RemoveAllReactionsForEmoteAsync(ulong channelId, ulong messageId, IEmote emote, BaseDiscordClient client, RequestOptions options)
{ => client.ApiClient.RemoveAllReactionsForEmoteAsync(channelId, messageId, emote is Emote e ? $"{e.Name}:{e.Id}" : UrlEncode(emote.Name), options);
await client.ApiClient.RemoveAllReactionsForEmoteAsync(channelId, messageId, emote is Emote e ? $"{e.Name}:{e.Id}" : UrlEncode(emote.Name), options).ConfigureAwait(false);
}
public static async Task RemoveAllReactionsForEmoteAsync(IMessage msg, IEmote emote, BaseDiscordClient client, RequestOptions options) public static Task RemoveAllReactionsForEmoteAsync(IMessage msg, IEmote emote, BaseDiscordClient client, RequestOptions options)
{ => client.ApiClient.RemoveAllReactionsForEmoteAsync(msg.Channel.Id, msg.Id, emote is Emote e ? $"{e.Name}:{e.Id}" : UrlEncode(emote.Name), options);
await client.ApiClient.RemoveAllReactionsForEmoteAsync(msg.Channel.Id, msg.Id, emote is Emote e ? $"{e.Name}:{e.Id}" : UrlEncode(emote.Name), options).ConfigureAwait(false);
}
public static IAsyncEnumerable<IReadOnlyCollection<IUser>> GetReactionUsersAsync(IMessage msg, IEmote emote, public static IAsyncEnumerable<IReadOnlyCollection<IUser>> GetReactionUsersAsync(IMessage msg, IEmote emote,
int? limit, BaseDiscordClient client, ReactionType reactionType, RequestOptions options) int? limit, BaseDiscordClient client, ReactionType reactionType, RequestOptions options)
@@ -211,19 +192,15 @@ namespace Discord.Rest
return newContent; return newContent;
} }
public static async Task PinAsync(IMessage msg, BaseDiscordClient client, public static Task PinAsync(IMessage msg, BaseDiscordClient client, RequestOptions options)
RequestOptions options)
{ {
if (msg.Channel is IVoiceChannel) if (msg.Channel is IVoiceChannel)
throw new NotSupportedException("Pinned messages are not supported in text-in-voice channels."); throw new NotSupportedException("Pinned messages are not supported in text-in-voice channels.");
await client.ApiClient.AddPinAsync(msg.Channel.Id, msg.Id, options).ConfigureAwait(false); return client.ApiClient.AddPinAsync(msg.Channel.Id, msg.Id, options);
} }
public static async Task UnpinAsync(IMessage msg, BaseDiscordClient client, public static Task UnpinAsync(IMessage msg, BaseDiscordClient client, RequestOptions options)
RequestOptions options) => client.ApiClient.RemovePinAsync(msg.Channel.Id, msg.Id, options);
{
await client.ApiClient.RemovePinAsync(msg.Channel.Id, msg.Id, options).ConfigureAwait(false);
}
public static ImmutableArray<ITag> ParseTags(string text, IMessageChannel channel, IGuild guild, IReadOnlyCollection<IUser> userMentions) public static ImmutableArray<ITag> ParseTags(string text, IMessageChannel channel, IGuild guild, IReadOnlyCollection<IUser> userMentions)
{ {
@@ -397,11 +374,8 @@ namespace Discord.Rest
public static Task CrosspostAsync(IMessage msg, BaseDiscordClient client, RequestOptions options) public static Task CrosspostAsync(IMessage msg, BaseDiscordClient client, RequestOptions options)
=> CrosspostAsync(msg.Channel.Id, msg.Id, client, options); => CrosspostAsync(msg.Channel.Id, msg.Id, client, options);
public static async Task CrosspostAsync(ulong channelId, ulong msgId, BaseDiscordClient client, public static Task CrosspostAsync(ulong channelId, ulong msgId, BaseDiscordClient client, RequestOptions options)
RequestOptions options) => client.ApiClient.CrosspostAsync(channelId, msgId, options);
{
await client.ApiClient.CrosspostAsync(channelId, msgId, options).ConfigureAwait(false);
}
public static IUser GetAuthor(BaseDiscordClient client, IGuild guild, UserModel model, ulong? webhookId) public static IUser GetAuthor(BaseDiscordClient client, IGuild guild, UserModel model, ulong? webhookId)
{ {

View File

@@ -188,14 +188,14 @@ namespace Discord.Rest
/// <inheritdoc /> /// <inheritdoc />
/// <exception cref="InvalidOperationException">This operation may only be called on a <see cref="INewsChannel"/> channel.</exception> /// <exception cref="InvalidOperationException">This operation may only be called on a <see cref="INewsChannel"/> channel.</exception>
public async Task CrosspostAsync(RequestOptions options = null) public Task CrosspostAsync(RequestOptions options = null)
{ {
if (!(Channel is INewsChannel)) if (!(Channel is INewsChannel))
{ {
throw new InvalidOperationException("Publishing (crossposting) is only valid in news channels."); throw new InvalidOperationException("Publishing (crossposting) is only valid in news channels.");
} }
await MessageHelper.CrosspostAsync(this, Discord, options); return MessageHelper.CrosspostAsync(this, Discord, options);
} }
private string DebuggerDisplay => $"{Author}: {Content} ({Id}{(Attachments.Count > 0 ? $", {Attachments.Count} Attachments" : "")})"; private string DebuggerDisplay => $"{Author}: {Content} ({Id}{(Attachments.Count > 0 ? $", {Attachments.Count} Attachments" : "")})";

View File

@@ -8,11 +8,9 @@ namespace Discord.Rest
internal static class RoleHelper internal static class RoleHelper
{ {
#region General #region General
public static async Task DeleteAsync(IRole role, BaseDiscordClient client, public static Task DeleteAsync(IRole role, BaseDiscordClient client, RequestOptions options)
RequestOptions options) => client.ApiClient.DeleteGuildRoleAsync(role.Guild.Id, role.Id, options);
{
await client.ApiClient.DeleteGuildRoleAsync(role.Guild.Id, role.Id, options).ConfigureAwait(false);
}
public static async Task<Model> ModifyAsync(IRole role, BaseDiscordClient client, public static async Task<Model> ModifyAsync(IRole role, BaseDiscordClient client,
Action<RoleProperties> func, RequestOptions options) Action<RoleProperties> func, RequestOptions options)
{ {

View File

@@ -10,8 +10,7 @@ namespace Discord.Rest
{ {
internal static class UserHelper internal static class UserHelper
{ {
public static async Task<Model> ModifyAsync(ISelfUser user, BaseDiscordClient client, Action<SelfUserProperties> func, public static Task<Model> ModifyAsync(ISelfUser user, BaseDiscordClient client, Action<SelfUserProperties> func, RequestOptions options)
RequestOptions options)
{ {
var args = new SelfUserProperties(); var args = new SelfUserProperties();
func(args); func(args);
@@ -24,7 +23,7 @@ namespace Discord.Rest
if (!apiArgs.Avatar.IsSpecified && user.AvatarId != null) if (!apiArgs.Avatar.IsSpecified && user.AvatarId != null)
apiArgs.Avatar = new ImageModel(user.AvatarId); apiArgs.Avatar = new ImageModel(user.AvatarId);
return await client.ApiClient.ModifySelfAsync(apiArgs, options).ConfigureAwait(false); return client.ApiClient.ModifySelfAsync(apiArgs, options);
} }
public static async Task<GuildUserProperties> ModifyAsync(IGuildUser user, BaseDiscordClient client, Action<GuildUserProperties> func, public static async Task<GuildUserProperties> ModifyAsync(IGuildUser user, BaseDiscordClient client, Action<GuildUserProperties> func,
RequestOptions options) RequestOptions options)
@@ -66,11 +65,8 @@ namespace Discord.Rest
return args; return args;
} }
public static async Task KickAsync(IGuildUser user, BaseDiscordClient client, public static Task KickAsync(IGuildUser user, BaseDiscordClient client, string reason, RequestOptions options)
string reason, RequestOptions options) => client.ApiClient.RemoveGuildMemberAsync(user.GuildId, user.Id, reason, options);
{
await client.ApiClient.RemoveGuildMemberAsync(user.GuildId, user.Id, reason, options).ConfigureAwait(false);
}
public static async Task<RestDMChannel> CreateDMChannelAsync(IUser user, BaseDiscordClient client, public static async Task<RestDMChannel> CreateDMChannelAsync(IUser user, BaseDiscordClient client,
RequestOptions options) RequestOptions options)
@@ -91,7 +87,7 @@ namespace Discord.Rest
await client.ApiClient.RemoveRoleAsync(user.Guild.Id, user.Id, roleId, options).ConfigureAwait(false); await client.ApiClient.RemoveRoleAsync(user.Guild.Id, user.Id, roleId, options).ConfigureAwait(false);
} }
public static async Task SetTimeoutAsync(IGuildUser user, BaseDiscordClient client, TimeSpan span, RequestOptions options) public static Task SetTimeoutAsync(IGuildUser user, BaseDiscordClient client, TimeSpan span, RequestOptions options)
{ {
if (span.TotalDays > 28) // As its double, an exact value of 28 can be accepted. if (span.TotalDays > 28) // As its double, an exact value of 28 can be accepted.
throw new ArgumentOutOfRangeException(nameof(span), "Offset cannot be more than 28 days from the current date."); throw new ArgumentOutOfRangeException(nameof(span), "Offset cannot be more than 28 days from the current date.");
@@ -101,16 +97,16 @@ namespace Discord.Rest
{ {
TimedOutUntil = DateTimeOffset.UtcNow.Add(span) TimedOutUntil = DateTimeOffset.UtcNow.Add(span)
}; };
await client.ApiClient.ModifyGuildMemberAsync(user.Guild.Id, user.Id, apiArgs, options).ConfigureAwait(false); return client.ApiClient.ModifyGuildMemberAsync(user.Guild.Id, user.Id, apiArgs, options);
} }
public static async Task RemoveTimeOutAsync(IGuildUser user, BaseDiscordClient client, RequestOptions options) public static Task RemoveTimeOutAsync(IGuildUser user, BaseDiscordClient client, RequestOptions options)
{ {
var apiArgs = new API.Rest.ModifyGuildMemberParams() var apiArgs = new API.Rest.ModifyGuildMemberParams()
{ {
TimedOutUntil = null TimedOutUntil = null
}; };
await client.ApiClient.ModifyGuildMemberAsync(user.Guild.Id, user.Id, apiArgs, options).ConfigureAwait(false); return client.ApiClient.ModifyGuildMemberAsync(user.Guild.Id, user.Id, apiArgs, options);
} }
} }
} }

View File

@@ -8,7 +8,7 @@ namespace Discord.Rest
{ {
internal static class WebhookHelper internal static class WebhookHelper
{ {
public static async Task<Model> ModifyAsync(IWebhook webhook, BaseDiscordClient client, public static Task<Model> ModifyAsync(IWebhook webhook, BaseDiscordClient client,
Action<WebhookProperties> func, RequestOptions options) Action<WebhookProperties> func, RequestOptions options)
{ {
var args = new WebhookProperties(); var args = new WebhookProperties();
@@ -27,11 +27,10 @@ namespace Discord.Rest
else if (args.ChannelId.IsSpecified) else if (args.ChannelId.IsSpecified)
apiArgs.ChannelId = args.ChannelId.Value; apiArgs.ChannelId = args.ChannelId.Value;
return await client.ApiClient.ModifyWebhookAsync(webhook.Id, apiArgs, options).ConfigureAwait(false); return client.ApiClient.ModifyWebhookAsync(webhook.Id, apiArgs, options);
}
public static async Task DeleteAsync(IWebhook webhook, BaseDiscordClient client, RequestOptions options)
{
await client.ApiClient.DeleteWebhookAsync(webhook.Id, options).ConfigureAwait(false);
} }
public static Task DeleteAsync(IWebhook webhook, BaseDiscordClient client, RequestOptions options)
=> client.ApiClient.DeleteWebhookAsync(webhook.Id, options);
} }
} }

View File

@@ -97,7 +97,7 @@ namespace Discord.Net.Rest
} }
/// <exception cref="InvalidOperationException">Unsupported param type.</exception> /// <exception cref="InvalidOperationException">Unsupported param type.</exception>
public async Task<RestResponse> SendAsync(string method, string endpoint, IReadOnlyDictionary<string, object> multipartParams, CancellationToken cancelToken, bool headerOnly, string reason = null, public Task<RestResponse> SendAsync(string method, string endpoint, IReadOnlyDictionary<string, object> multipartParams, CancellationToken cancelToken, bool headerOnly, string reason = null,
IEnumerable<KeyValuePair<string, IEnumerable<string>>> requestHeaders = null) IEnumerable<KeyValuePair<string, IEnumerable<string>>> requestHeaders = null)
{ {
string uri = Path.Combine(_baseUrl, endpoint); string uri = Path.Combine(_baseUrl, endpoint);
@@ -162,7 +162,7 @@ namespace Discord.Net.Rest
} }
restRequest.Content = content; restRequest.Content = content;
return await SendInternalAsync(restRequest, cancelToken, headerOnly).ConfigureAwait(false); return SendInternalAsync(restRequest, cancelToken, headerOnly);
} }
private async Task<RestResponse> SendInternalAsync(HttpRequestMessage request, CancellationToken cancelToken, bool headerOnly) private async Task<RestResponse> SendInternalAsync(HttpRequestMessage request, CancellationToken cancelToken, bool headerOnly)

View File

@@ -99,7 +99,7 @@ namespace Discord.Net.Queue
createdTokenSource?.Dispose(); createdTokenSource?.Dispose();
} }
internal async Task EnterGlobalAsync(int id, RestRequest request) internal Task EnterGlobalAsync(int id, RestRequest request)
{ {
int millis = (int)Math.Ceiling((_waitUntil - DateTimeOffset.UtcNow).TotalMilliseconds); int millis = (int)Math.Ceiling((_waitUntil - DateTimeOffset.UtcNow).TotalMilliseconds);
if (millis > 0) if (millis > 0)
@@ -107,19 +107,23 @@ namespace Discord.Net.Queue
#if DEBUG_LIMITS #if DEBUG_LIMITS
Debug.WriteLine($"[{id}] Sleeping {millis} ms (Pre-emptive) [Global]"); Debug.WriteLine($"[{id}] Sleeping {millis} ms (Pre-emptive) [Global]");
#endif #endif
await Task.Delay(millis).ConfigureAwait(false); return Task.Delay(millis);
} }
return Task.CompletedTask;
} }
internal void PauseGlobal(RateLimitInfo info) internal void PauseGlobal(RateLimitInfo info)
{ {
_waitUntil = DateTimeOffset.UtcNow.AddMilliseconds(info.RetryAfter.Value + (info.Lag?.TotalMilliseconds ?? 0.0)); _waitUntil = DateTimeOffset.UtcNow.AddMilliseconds(info.RetryAfter.Value + (info.Lag?.TotalMilliseconds ?? 0.0));
} }
internal async Task EnterGlobalAsync(int id, WebSocketRequest request)
internal Task EnterGlobalAsync(int id, WebSocketRequest request)
{ {
//If this is a global request (unbucketed), it'll be dealt in EnterAsync //If this is a global request (unbucketed), it'll be dealt in EnterAsync
var requestBucket = GatewayBucket.Get(request.Options.BucketId); var requestBucket = GatewayBucket.Get(request.Options.BucketId);
if (requestBucket.Type == GatewayBucketType.Unbucketed) if (requestBucket.Type == GatewayBucketType.Unbucketed)
return; return Task.CompletedTask;
//It's not a global request, so need to remove one from global (per-session) //It's not a global request, so need to remove one from global (per-session)
var globalBucketType = GatewayBucket.Get(GatewayBucketType.Unbucketed); var globalBucketType = GatewayBucket.Get(GatewayBucketType.Unbucketed);
@@ -127,7 +131,7 @@ namespace Discord.Net.Queue
options.BucketId = globalBucketType.Id; options.BucketId = globalBucketType.Id;
var globalRequest = new WebSocketRequest(null, null, false, false, options); var globalRequest = new WebSocketRequest(null, null, false, false, options);
var globalBucket = GetOrCreateBucket(options, globalRequest); var globalBucket = GetOrCreateBucket(options, globalRequest);
await globalBucket.TriggerAsync(id, globalRequest); return globalBucket.TriggerAsync(id, globalRequest);
} }
private RequestBucket GetOrCreateBucket(RequestOptions options, IRequest request) private RequestBucket GetOrCreateBucket(RequestOptions options, IRequest request)
@@ -141,10 +145,9 @@ namespace Discord.Net.Queue
} }
return (RequestBucket)obj; return (RequestBucket)obj;
} }
internal async Task RaiseRateLimitTriggered(BucketId bucketId, RateLimitInfo? info, string endpoint) internal Task RaiseRateLimitTriggered(BucketId bucketId, RateLimitInfo? info, string endpoint)
{ => RateLimitTriggered(bucketId, info, endpoint);
await RateLimitTriggered(bucketId, info, endpoint).ConfigureAwait(false);
}
internal (RequestBucket, BucketId) UpdateBucketHash(BucketId id, string discordHash) internal (RequestBucket, BucketId) UpdateBucketHash(BucketId id, string discordHash)
{ {
if (!id.IsHashBucket) if (!id.IsHashBucket)

View File

@@ -13,9 +13,7 @@ namespace Discord.Net.Queue
Json = json; Json = json;
} }
public override async Task<RestResponse> SendAsync() public override Task<RestResponse> SendAsync()
{ => Client.SendAsync(Method, Endpoint, Json, Options.CancelToken, Options.HeaderOnly, Options.AuditLogReason);
return await Client.SendAsync(Method, Endpoint, Json, Options.CancelToken, Options.HeaderOnly, Options.AuditLogReason).ConfigureAwait(false);
}
} }
} }

View File

@@ -14,9 +14,7 @@ namespace Discord.Net.Queue
MultipartParams = multipartParams; MultipartParams = multipartParams;
} }
public override async Task<RestResponse> SendAsync() public override Task<RestResponse> SendAsync()
{ => Client.SendAsync(Method, Endpoint, MultipartParams, Options.CancelToken, Options.HeaderOnly, Options.AuditLogReason);
return await Client.SendAsync(Method, Endpoint, MultipartParams, Options.CancelToken, Options.HeaderOnly, Options.AuditLogReason).ConfigureAwait(false);
}
} }
} }

View File

@@ -29,9 +29,7 @@ namespace Discord.Net.Queue
Promise = new TaskCompletionSource<Stream>(); Promise = new TaskCompletionSource<Stream>();
} }
public virtual async Task<RestResponse> SendAsync() public virtual Task<RestResponse> SendAsync()
{ => Client.SendAsync(Method, Endpoint, Options.CancelToken, Options.HeaderOnly, Options.AuditLogReason, Options.RequestHeaders);
return await Client.SendAsync(Method, Endpoint, Options.CancelToken, Options.HeaderOnly, Options.AuditLogReason, Options.RequestHeaders).ConfigureAwait(false);
}
} }
} }

View File

@@ -30,9 +30,7 @@ namespace Discord.Net.Queue
Promise = new TaskCompletionSource<Stream>(); Promise = new TaskCompletionSource<Stream>();
} }
public async Task SendAsync() public Task SendAsync()
{ => Client.SendAsync(Data, 0, Data.Length, IsText);
await Client.SendAsync(Data, 0, Data.Length, IsText).ConfigureAwait(false);
}
} }
} }

View File

@@ -95,13 +95,13 @@ namespace Discord.Audio
UdpLatencyUpdated += async (old, val) => await _audioLogger.DebugAsync($"UDP Latency = {val} ms").ConfigureAwait(false); UdpLatencyUpdated += async (old, val) => await _audioLogger.DebugAsync($"UDP Latency = {val} ms").ConfigureAwait(false);
} }
internal async Task StartAsync(string url, ulong userId, string sessionId, string token) internal Task StartAsync(string url, ulong userId, string sessionId, string token)
{ {
_url = url; _url = url;
_userId = userId; _userId = userId;
_sessionId = sessionId; _sessionId = sessionId;
_token = token; _token = token;
await _connection.StartAsync().ConfigureAwait(false); return _connection.StartAsync();
} }
public IReadOnlyDictionary<ulong, AudioInStream> GetStreams() public IReadOnlyDictionary<ulong, AudioInStream> GetStreams()
@@ -109,10 +109,8 @@ namespace Discord.Audio
return _streams.ToDictionary(pair => pair.Key, pair => pair.Value.Reader); return _streams.ToDictionary(pair => pair.Key, pair => pair.Value.Reader);
} }
public async Task StopAsync() public Task StopAsync()
{ => _connection.StopAsync();
await _connection.StopAsync().ConfigureAwait(false);
}
private async Task OnConnectingAsync() private async Task OnConnectingAsync()
{ {

View File

@@ -47,14 +47,11 @@ namespace Discord.Audio.Streams
return _next.WriteAsync(_buffer, 0, count, cancelToken); return _next.WriteAsync(_buffer, 0, count, cancelToken);
} }
public override async Task FlushAsync(CancellationToken cancelToken) public override Task FlushAsync(CancellationToken cancelToken)
{ => _next.FlushAsync(cancelToken);
await _next.FlushAsync(cancelToken).ConfigureAwait(false);
} public override Task ClearAsync(CancellationToken cancelToken)
public override async Task ClearAsync(CancellationToken cancelToken) => _next.ClearAsync(cancelToken);
{
await _next.ClearAsync(cancelToken).ConfigureAwait(false);
}
protected override void Dispose(bool disposing) protected override void Dispose(bool disposing)
{ {

View File

@@ -103,14 +103,11 @@ namespace Discord.Audio.Streams
await base.FlushAsync(cancelToken).ConfigureAwait(false); await base.FlushAsync(cancelToken).ConfigureAwait(false);
}*/ }*/
public override async Task FlushAsync(CancellationToken cancelToken) public override Task FlushAsync(CancellationToken cancelToken)
{ => _next.FlushAsync(cancelToken);
await _next.FlushAsync(cancelToken).ConfigureAwait(false);
} public override Task ClearAsync(CancellationToken cancelToken)
public override async Task ClearAsync(CancellationToken cancelToken) => _next.ClearAsync(cancelToken);
{
await _next.ClearAsync(cancelToken).ConfigureAwait(false);
}
protected override void Dispose(bool disposing) protected override void Dispose(bool disposing)
{ {

View File

@@ -15,10 +15,10 @@ namespace Discord.Audio.Streams
} }
public override void WriteHeader(ushort seq, uint timestamp, bool missed) { } //Ignore public override void WriteHeader(ushort seq, uint timestamp, bool missed) { } //Ignore
public override async Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancelToken) public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancelToken)
{ {
cancelToken.ThrowIfCancellationRequested(); cancelToken.ThrowIfCancellationRequested();
await _client.SendAsync(buffer, offset, count).ConfigureAwait(false); return _client.SendAsync(buffer, offset, count);
} }
} }
} }

View File

@@ -23,7 +23,7 @@ namespace Discord.Audio.Streams
/// <exception cref="OperationCanceledException">The token has had cancellation requested.</exception> /// <exception cref="OperationCanceledException">The token has had cancellation requested.</exception>
/// <exception cref="ObjectDisposedException">The associated <see cref="T:System.Threading.CancellationTokenSource" /> has been disposed.</exception> /// <exception cref="ObjectDisposedException">The associated <see cref="T:System.Threading.CancellationTokenSource" /> has been disposed.</exception>
public override async Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancelToken) public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancelToken)
{ {
cancelToken.ThrowIfCancellationRequested(); cancelToken.ThrowIfCancellationRequested();
@@ -38,7 +38,7 @@ namespace Discord.Audio.Streams
(buffer[offset + 7] << 0)); (buffer[offset + 7] << 0));
_next.WriteHeader(seq, timestamp, false); _next.WriteHeader(seq, timestamp, false);
await _next.WriteAsync(buffer, offset + headerSize, count - headerSize, cancelToken).ConfigureAwait(false); return _next.WriteAsync(buffer, offset + headerSize, count - headerSize, cancelToken);
} }
public static bool TryReadSsrc(byte[] buffer, int offset, out uint ssrc) public static bool TryReadSsrc(byte[] buffer, int offset, out uint ssrc)

View File

@@ -38,7 +38,7 @@ namespace Discord.Audio.Streams
_nextSeq = seq; _nextSeq = seq;
_nextTimestamp = timestamp; _nextTimestamp = timestamp;
} }
public override async Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancelToken) public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancelToken)
{ {
cancelToken.ThrowIfCancellationRequested(); cancelToken.ThrowIfCancellationRequested();
if (!_hasHeader) if (!_hasHeader)
@@ -58,17 +58,14 @@ namespace Discord.Audio.Streams
Buffer.BlockCopy(buffer, offset, _buffer, 12, count); Buffer.BlockCopy(buffer, offset, _buffer, 12, count);
_next.WriteHeader(_nextSeq, _nextTimestamp, false); _next.WriteHeader(_nextSeq, _nextTimestamp, false);
await _next.WriteAsync(_buffer, 0, count + 12).ConfigureAwait(false); return _next.WriteAsync(_buffer, 0, count + 12);
} }
public override async Task FlushAsync(CancellationToken cancelToken) public override Task FlushAsync(CancellationToken cancelToken)
{ => _next.FlushAsync(cancelToken);
await _next.FlushAsync(cancelToken).ConfigureAwait(false);
} public override Task ClearAsync(CancellationToken cancelToken)
public override async Task ClearAsync(CancellationToken cancelToken) => _next.ClearAsync(cancelToken);
{
await _next.ClearAsync(cancelToken).ConfigureAwait(false);
}
protected override void Dispose(bool disposing) protected override void Dispose(bool disposing)
{ {

View File

@@ -24,26 +24,23 @@ namespace Discord.Audio.Streams
_nonce = new byte[24]; _nonce = new byte[24];
} }
public override async Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancelToken) public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancelToken)
{ {
cancelToken.ThrowIfCancellationRequested(); cancelToken.ThrowIfCancellationRequested();
if (_client.SecretKey == null) if (_client.SecretKey == null)
return; return Task.CompletedTask;
Buffer.BlockCopy(buffer, 0, _nonce, 0, 12); //Copy RTP header to nonce Buffer.BlockCopy(buffer, 0, _nonce, 0, 12); //Copy RTP header to nonce
count = SecretBox.Decrypt(buffer, offset + 12, count - 12, buffer, offset + 12, _nonce, _client.SecretKey); count = SecretBox.Decrypt(buffer, offset + 12, count - 12, buffer, offset + 12, _nonce, _client.SecretKey);
await _next.WriteAsync(buffer, 0, count + 12, cancelToken).ConfigureAwait(false); return _next.WriteAsync(buffer, 0, count + 12, cancelToken);
} }
public override async Task FlushAsync(CancellationToken cancelToken) public override Task FlushAsync(CancellationToken cancelToken)
{ => _next.FlushAsync(cancelToken);
await _next.FlushAsync(cancelToken).ConfigureAwait(false);
} public override Task ClearAsync(CancellationToken cancelToken)
public override async Task ClearAsync(CancellationToken cancelToken) => _next.ClearAsync(cancelToken);
{
await _next.ClearAsync(cancelToken).ConfigureAwait(false);
}
protected override void Dispose(bool disposing) protected override void Dispose(bool disposing)
{ {

View File

@@ -52,14 +52,11 @@ namespace Discord.Audio.Streams
await _next.WriteAsync(buffer, 0, count + 12, cancelToken).ConfigureAwait(false); await _next.WriteAsync(buffer, 0, count + 12, cancelToken).ConfigureAwait(false);
} }
public override async Task FlushAsync(CancellationToken cancelToken) public override Task FlushAsync(CancellationToken cancelToken)
{ => _next.FlushAsync(cancelToken);
await _next.FlushAsync(cancelToken).ConfigureAwait(false);
} public override Task ClearAsync(CancellationToken cancelToken)
public override async Task ClearAsync(CancellationToken cancelToken) => _next.ClearAsync(cancelToken);
{
await _next.ClearAsync(cancelToken).ConfigureAwait(false);
}
protected override void Dispose(bool disposing) protected override void Dispose(bool disposing)
{ {

View File

@@ -177,14 +177,11 @@ namespace Discord
await _logger.InfoAsync("Disconnected").ConfigureAwait(false); await _logger.InfoAsync("Disconnected").ConfigureAwait(false);
} }
public async Task CompleteAsync() public Task CompleteAsync()
{ => _readyPromise.TrySetResultAsync(true);
await _readyPromise.TrySetResultAsync(true).ConfigureAwait(false);
} public Task WaitAsync()
public async Task WaitAsync() => _readyPromise.Task;
{
await _readyPromise.Task.ConfigureAwait(false);
}
public void Cancel() public void Cancel()
{ {

View File

@@ -110,10 +110,10 @@ namespace Discord.WebSocket
=> new DiscordSocketApiClient(config.RestClientProvider, config.WebSocketProvider, DiscordRestConfig.UserAgent, config.GatewayHost, => new DiscordSocketApiClient(config.RestClientProvider, config.WebSocketProvider, DiscordRestConfig.UserAgent, config.GatewayHost,
useSystemClock: config.UseSystemClock, defaultRatelimitCallback: config.DefaultRatelimitCallback); useSystemClock: config.UseSystemClock, defaultRatelimitCallback: config.DefaultRatelimitCallback);
internal async Task AcquireIdentifyLockAsync(int shardId, CancellationToken token) internal Task AcquireIdentifyLockAsync(int shardId, CancellationToken token)
{ {
int semaphoreIdx = shardId % _baseConfig.IdentifyMaxConcurrency; int semaphoreIdx = shardId % _baseConfig.IdentifyMaxConcurrency;
await _identifySemaphores[semaphoreIdx].WaitAsync(token).ConfigureAwait(false); return _identifySemaphores[semaphoreIdx].WaitAsync(token);
} }
internal void ReleaseIdentifyLock() internal void ReleaseIdentifyLock()
@@ -198,11 +198,12 @@ namespace Discord.WebSocket
} }
/// <inheritdoc /> /// <inheritdoc />
public override async Task StartAsync() public override Task StartAsync()
=> await Task.WhenAll(_shards.Select(x => x.StartAsync())).ConfigureAwait(false); => Task.WhenAll(_shards.Select(x => x.StartAsync()));
/// <inheritdoc /> /// <inheritdoc />
public override async Task StopAsync() public override Task StopAsync()
=> await Task.WhenAll(_shards.Select(x => x.StopAsync())).ConfigureAwait(false); => Task.WhenAll(_shards.Select(x => x.StopAsync()));
public DiscordSocketClient GetShard(int id) public DiscordSocketClient GetShard(int id)
{ {
@@ -220,8 +221,8 @@ namespace Discord.WebSocket
=> GetShardFor(guild?.Id ?? 0); => GetShardFor(guild?.Id ?? 0);
/// <inheritdoc /> /// <inheritdoc />
public override async Task<RestApplication> GetApplicationInfoAsync(RequestOptions options = null) public override Task<RestApplication> GetApplicationInfoAsync(RequestOptions options = null)
=> await _shards[0].GetApplicationInfoAsync(options).ConfigureAwait(false); => _shards[0].GetApplicationInfoAsync(options);
/// <inheritdoc /> /// <inheritdoc />
public override SocketGuild GetGuild(ulong id) public override SocketGuild GetGuild(ulong id)
@@ -355,16 +356,12 @@ namespace Discord.WebSocket
} }
/// <inheritdoc /> /// <inheritdoc />
public override async ValueTask<IReadOnlyCollection<RestVoiceRegion>> GetVoiceRegionsAsync(RequestOptions options = null) public override ValueTask<IReadOnlyCollection<RestVoiceRegion>> GetVoiceRegionsAsync(RequestOptions options = null)
{ => _shards[0].GetVoiceRegionsAsync();
return await _shards[0].GetVoiceRegionsAsync().ConfigureAwait(false);
}
/// <inheritdoc /> /// <inheritdoc />
public override async ValueTask<RestVoiceRegion> GetVoiceRegionAsync(string id, RequestOptions options = null) public override ValueTask<RestVoiceRegion> GetVoiceRegionAsync(string id, RequestOptions options = null)
{ => _shards[0].GetVoiceRegionAsync(id, options);
return await _shards[0].GetVoiceRegionAsync(id, options).ConfigureAwait(false);
}
/// <inheritdoc /> /// <inheritdoc />
/// <exception cref="ArgumentNullException"><paramref name="guilds"/> is <see langword="null"/></exception> /// <exception cref="ArgumentNullException"><paramref name="guilds"/> is <see langword="null"/></exception>
@@ -396,14 +393,14 @@ namespace Discord.WebSocket
await _shards[i].SetStatusAsync(status).ConfigureAwait(false); await _shards[i].SetStatusAsync(status).ConfigureAwait(false);
} }
/// <inheritdoc /> /// <inheritdoc />
public override async Task SetGameAsync(string name, string streamUrl = null, ActivityType type = ActivityType.Playing) public override Task SetGameAsync(string name, string streamUrl = null, ActivityType type = ActivityType.Playing)
{ {
IActivity activity = null; IActivity activity = null;
if (!string.IsNullOrEmpty(streamUrl)) if (!string.IsNullOrEmpty(streamUrl))
activity = new StreamingGame(name, streamUrl); activity = new StreamingGame(name, streamUrl);
else if (!string.IsNullOrEmpty(name)) else if (!string.IsNullOrEmpty(name))
activity = new Game(name, type); activity = new Game(name, type);
await SetActivityAsync(activity).ConfigureAwait(false); return SetActivityAsync(activity);
} }
/// <inheritdoc /> /// <inheritdoc />
public override async Task SetActivityAsync(IActivity activity) public override async Task SetActivityAsync(IActivity activity)

View File

@@ -317,7 +317,7 @@ namespace Discord.API
#endif #endif
} }
public async Task SendIdentifyAsync(int largeThreshold = 100, int shardID = 0, int totalShards = 1, GatewayIntents gatewayIntents = GatewayIntents.AllUnprivileged, (UserStatus, bool, long?, GameModel)? presence = null, RequestOptions options = null) public Task SendIdentifyAsync(int largeThreshold = 100, int shardID = 0, int totalShards = 1, GatewayIntents gatewayIntents = GatewayIntents.AllUnprivileged, (UserStatus, bool, long?, GameModel)? presence = null, RequestOptions options = null)
{ {
options = RequestOptions.CreateOrClone(options); options = RequestOptions.CreateOrClone(options);
var props = new Dictionary<string, string> var props = new Dictionary<string, string>
@@ -350,9 +350,10 @@ namespace Discord.API
}; };
} }
await SendGatewayAsync(GatewayOpCode.Identify, msg, options: options).ConfigureAwait(false); return SendGatewayAsync(GatewayOpCode.Identify, msg, options: options);
} }
public async Task SendResumeAsync(string sessionId, int lastSeq, RequestOptions options = null)
public Task SendResumeAsync(string sessionId, int lastSeq, RequestOptions options = null)
{ {
options = RequestOptions.CreateOrClone(options); options = RequestOptions.CreateOrClone(options);
var msg = new ResumeParams() var msg = new ResumeParams()
@@ -361,14 +362,16 @@ namespace Discord.API
SessionId = sessionId, SessionId = sessionId,
Sequence = lastSeq Sequence = lastSeq
}; };
await SendGatewayAsync(GatewayOpCode.Resume, msg, options: options).ConfigureAwait(false); return SendGatewayAsync(GatewayOpCode.Resume, msg, options: options);
} }
public async Task SendHeartbeatAsync(int lastSeq, RequestOptions options = null)
public Task SendHeartbeatAsync(int lastSeq, RequestOptions options = null)
{ {
options = RequestOptions.CreateOrClone(options); options = RequestOptions.CreateOrClone(options);
await SendGatewayAsync(GatewayOpCode.Heartbeat, lastSeq, options: options).ConfigureAwait(false); return SendGatewayAsync(GatewayOpCode.Heartbeat, lastSeq, options: options);
} }
public async Task SendPresenceUpdateAsync(UserStatus status, bool isAFK, long? since, GameModel game, RequestOptions options = null)
public Task SendPresenceUpdateAsync(UserStatus status, bool isAFK, long? since, GameModel game, RequestOptions options = null)
{ {
options = RequestOptions.CreateOrClone(options); options = RequestOptions.CreateOrClone(options);
var args = new PresenceUpdateParams var args = new PresenceUpdateParams
@@ -379,14 +382,16 @@ namespace Discord.API
Activities = new object[] { game } Activities = new object[] { game }
}; };
options.BucketId = GatewayBucket.Get(GatewayBucketType.PresenceUpdate).Id; options.BucketId = GatewayBucket.Get(GatewayBucketType.PresenceUpdate).Id;
await SendGatewayAsync(GatewayOpCode.PresenceUpdate, args, options: options).ConfigureAwait(false); return SendGatewayAsync(GatewayOpCode.PresenceUpdate, args, options: options);
} }
public async Task SendRequestMembersAsync(IEnumerable<ulong> guildIds, RequestOptions options = null)
public Task SendRequestMembersAsync(IEnumerable<ulong> guildIds, RequestOptions options = null)
{ {
options = RequestOptions.CreateOrClone(options); options = RequestOptions.CreateOrClone(options);
await SendGatewayAsync(GatewayOpCode.RequestGuildMembers, new RequestMembersParams { GuildIds = guildIds, Query = "", Limit = 0 }, options: options).ConfigureAwait(false); return SendGatewayAsync(GatewayOpCode.RequestGuildMembers, new RequestMembersParams { GuildIds = guildIds, Query = "", Limit = 0 }, options: options);
} }
public async Task SendVoiceStateUpdateAsync(ulong guildId, ulong? channelId, bool selfDeaf, bool selfMute, RequestOptions options = null)
public Task SendVoiceStateUpdateAsync(ulong guildId, ulong? channelId, bool selfDeaf, bool selfMute, RequestOptions options = null)
{ {
var payload = new VoiceStateUpdateParams var payload = new VoiceStateUpdateParams
{ {
@@ -396,17 +401,19 @@ namespace Discord.API
SelfMute = selfMute SelfMute = selfMute
}; };
options = RequestOptions.CreateOrClone(options); options = RequestOptions.CreateOrClone(options);
await SendGatewayAsync(GatewayOpCode.VoiceStateUpdate, payload, options: options).ConfigureAwait(false); return SendGatewayAsync(GatewayOpCode.VoiceStateUpdate, payload, options: options);
} }
public async Task SendVoiceStateUpdateAsync(VoiceStateUpdateParams payload, RequestOptions options = null)
public Task SendVoiceStateUpdateAsync(VoiceStateUpdateParams payload, RequestOptions options = null)
{ {
options = RequestOptions.CreateOrClone(options); options = RequestOptions.CreateOrClone(options);
await SendGatewayAsync(GatewayOpCode.VoiceStateUpdate, payload, options: options).ConfigureAwait(false); return SendGatewayAsync(GatewayOpCode.VoiceStateUpdate, payload, options: options);
} }
public async Task SendGuildSyncAsync(IEnumerable<ulong> guildIds, RequestOptions options = null)
public Task SendGuildSyncAsync(IEnumerable<ulong> guildIds, RequestOptions options = null)
{ {
options = RequestOptions.CreateOrClone(options); options = RequestOptions.CreateOrClone(options);
await SendGatewayAsync(GatewayOpCode.GuildSync, guildIds, options: options).ConfigureAwait(false); return SendGatewayAsync(GatewayOpCode.GuildSync, guildIds, options: options);
} }
#endregion #endregion
} }

View File

@@ -284,11 +284,12 @@ namespace Discord.WebSocket
} }
/// <inheritdoc /> /// <inheritdoc />
public override async Task StartAsync() public override Task StartAsync()
=> await _connection.StartAsync().ConfigureAwait(false); => _connection.StartAsync();
/// <inheritdoc /> /// <inheritdoc />
public override async Task StopAsync() public override Task StopAsync()
=> await _connection.StopAsync().ConfigureAwait(false); => _connection.StopAsync();
private async Task OnConnectingAsync() private async Task OnConnectingAsync()
{ {
@@ -642,16 +643,18 @@ namespace Discord.WebSocket
} }
/// <inheritdoc /> /// <inheritdoc />
public override async Task DownloadUsersAsync(IEnumerable<IGuild> guilds) public override Task DownloadUsersAsync(IEnumerable<IGuild> guilds)
{ {
if (ConnectionState == ConnectionState.Connected) if (ConnectionState == ConnectionState.Connected)
{ {
EnsureGatewayIntent(GatewayIntents.GuildMembers); EnsureGatewayIntent(GatewayIntents.GuildMembers);
//Race condition leads to guilds being requested twice, probably okay //Race condition leads to guilds being requested twice, probably okay
await ProcessUserDownloadsAsync(guilds.Select(x => GetGuild(x.Id)).Where(x => x != null)).ConfigureAwait(false); return ProcessUserDownloadsAsync(guilds.Select(x => GetGuild(x.Id)).Where(x => x != null));
} }
return Task.CompletedTask;
} }
private async Task ProcessUserDownloadsAsync(IEnumerable<SocketGuild> guilds) private async Task ProcessUserDownloadsAsync(IEnumerable<SocketGuild> guilds)
{ {
var cachedGuilds = guilds.ToImmutableArray(); var cachedGuilds = guilds.ToImmutableArray();
@@ -689,15 +692,16 @@ namespace Discord.WebSocket
/// await client.SetStatusAsync(UserStatus.DoNotDisturb); /// await client.SetStatusAsync(UserStatus.DoNotDisturb);
/// </code> /// </code>
/// </example> /// </example>
public override async Task SetStatusAsync(UserStatus status) public override Task SetStatusAsync(UserStatus status)
{ {
Status = status; Status = status;
if (status == UserStatus.AFK) if (status == UserStatus.AFK)
_statusSince = DateTimeOffset.UtcNow; _statusSince = DateTimeOffset.UtcNow;
else else
_statusSince = null; _statusSince = null;
await SendStatusAsync().ConfigureAwait(false); return SendStatusAsync();
} }
/// <inheritdoc /> /// <inheritdoc />
/// <example> /// <example>
/// <para> /// <para>
@@ -713,7 +717,7 @@ namespace Discord.WebSocket
/// </code> /// </code>
/// </para> /// </para>
/// </example> /// </example>
public override async Task SetGameAsync(string name, string streamUrl = null, ActivityType type = ActivityType.Playing) public override Task SetGameAsync(string name, string streamUrl = null, ActivityType type = ActivityType.Playing)
{ {
if (!string.IsNullOrEmpty(streamUrl)) if (!string.IsNullOrEmpty(streamUrl))
Activity = new StreamingGame(name, streamUrl); Activity = new StreamingGame(name, streamUrl);
@@ -721,27 +725,27 @@ namespace Discord.WebSocket
Activity = new Game(name, type); Activity = new Game(name, type);
else else
Activity = null; Activity = null;
await SendStatusAsync().ConfigureAwait(false); return SendStatusAsync();
} }
/// <inheritdoc /> /// <inheritdoc />
public override async Task SetActivityAsync(IActivity activity) public override Task SetActivityAsync(IActivity activity)
{ {
Activity = activity; Activity = activity;
await SendStatusAsync().ConfigureAwait(false); return SendStatusAsync();
} }
/// <inheritdoc /> /// <inheritdoc />
public override async Task SetCustomStatusAsync(string status) public override Task SetCustomStatusAsync(string status)
{ {
var statusGame = new CustomStatusGame(status); var statusGame = new CustomStatusGame(status);
await SetActivityAsync(statusGame); return SetActivityAsync(statusGame);
} }
private async Task SendStatusAsync() private Task SendStatusAsync()
{ {
if (CurrentUser == null) if (CurrentUser == null)
return; return Task.CompletedTask;
var activities = _activity.IsSpecified var activities = _activity.IsSpecified
? ImmutableList.Create(_activity.Value) ? ImmutableList.Create(_activity.Value)
: null; : null;
@@ -749,11 +753,11 @@ namespace Discord.WebSocket
var presence = BuildCurrentStatus() ?? (UserStatus.Online, false, null, null); var presence = BuildCurrentStatus() ?? (UserStatus.Online, false, null, null);
await ApiClient.SendPresenceUpdateAsync( return ApiClient.SendPresenceUpdateAsync(
status: presence.Item1, status: presence.Item1,
isAFK: presence.Item2, isAFK: presence.Item2,
since: presence.Item3, since: presence.Item3,
game: presence.Item4).ConfigureAwait(false); game: presence.Item4);
} }
private (UserStatus, bool, long?, GameModel)? BuildCurrentStatus() private (UserStatus, bool, long?, GameModel)? BuildCurrentStatus()
@@ -3268,11 +3272,14 @@ namespace Discord.WebSocket
await logger.ErrorAsync("GuildDownloader Errored", ex).ConfigureAwait(false); await logger.ErrorAsync("GuildDownloader Errored", ex).ConfigureAwait(false);
} }
} }
private async Task SyncGuildsAsync()
private Task SyncGuildsAsync()
{ {
var guildIds = Guilds.Where(x => !x.IsSynced).Select(x => x.Id).ToImmutableArray(); var guildIds = Guilds.Where(x => !x.IsSynced).Select(x => x.Id).ToImmutableArray();
if (guildIds.Length > 0) if (guildIds.Length > 0)
await ApiClient.SendGuildSyncAsync(guildIds).ConfigureAwait(false); return ApiClient.SendGuildSyncAsync(guildIds);
return Task.CompletedTask;
} }
internal SocketGuild AddGuild(ExtendedGuild model, ClientState state) internal SocketGuild AddGuild(ExtendedGuild model, ClientState state)
@@ -3334,83 +3341,106 @@ namespace Discord.WebSocket
internal bool HasGatewayIntent(GatewayIntents intents) internal bool HasGatewayIntent(GatewayIntents intents)
=> _gatewayIntents.HasFlag(intents); => _gatewayIntents.HasFlag(intents);
private async Task GuildAvailableAsync(SocketGuild guild) private Task GuildAvailableAsync(SocketGuild guild)
{ {
if (!guild.IsConnected) if (!guild.IsConnected)
{ {
guild.IsConnected = true; guild.IsConnected = true;
await TimedInvokeAsync(_guildAvailableEvent, nameof(GuildAvailable), guild).ConfigureAwait(false); return TimedInvokeAsync(_guildAvailableEvent, nameof(GuildAvailable), guild);
} }
return Task.CompletedTask;
} }
private async Task GuildUnavailableAsync(SocketGuild guild)
private Task GuildUnavailableAsync(SocketGuild guild)
{ {
if (guild.IsConnected) if (guild.IsConnected)
{ {
guild.IsConnected = false; guild.IsConnected = false;
await TimedInvokeAsync(_guildUnavailableEvent, nameof(GuildUnavailable), guild).ConfigureAwait(false); return TimedInvokeAsync(_guildUnavailableEvent, nameof(GuildUnavailable), guild);
} }
return Task.CompletedTask;
} }
private async Task TimedInvokeAsync(AsyncEvent<Func<Task>> eventHandler, string name) private Task TimedInvokeAsync(AsyncEvent<Func<Task>> eventHandler, string name)
{ {
if (eventHandler.HasSubscribers) if (eventHandler.HasSubscribers)
{ {
if (HandlerTimeout.HasValue) if (HandlerTimeout.HasValue)
await TimeoutWrap(name, eventHandler.InvokeAsync).ConfigureAwait(false); return TimeoutWrap(name, eventHandler.InvokeAsync);
else else
await eventHandler.InvokeAsync().ConfigureAwait(false); return eventHandler.InvokeAsync();
} }
return Task.CompletedTask;
} }
private async Task TimedInvokeAsync<T>(AsyncEvent<Func<T, Task>> eventHandler, string name, T arg)
private Task TimedInvokeAsync<T>(AsyncEvent<Func<T, Task>> eventHandler, string name, T arg)
{ {
if (eventHandler.HasSubscribers) if (eventHandler.HasSubscribers)
{ {
if (HandlerTimeout.HasValue) if (HandlerTimeout.HasValue)
await TimeoutWrap(name, () => eventHandler.InvokeAsync(arg)).ConfigureAwait(false); return TimeoutWrap(name, () => eventHandler.InvokeAsync(arg));
else else
await eventHandler.InvokeAsync(arg).ConfigureAwait(false); return eventHandler.InvokeAsync(arg);
} }
return Task.CompletedTask;
} }
private async Task TimedInvokeAsync<T1, T2>(AsyncEvent<Func<T1, T2, Task>> eventHandler, string name, T1 arg1, T2 arg2)
private Task TimedInvokeAsync<T1, T2>(AsyncEvent<Func<T1, T2, Task>> eventHandler, string name, T1 arg1, T2 arg2)
{ {
if (eventHandler.HasSubscribers) if (eventHandler.HasSubscribers)
{ {
if (HandlerTimeout.HasValue) if (HandlerTimeout.HasValue)
await TimeoutWrap(name, () => eventHandler.InvokeAsync(arg1, arg2)).ConfigureAwait(false); return TimeoutWrap(name, () => eventHandler.InvokeAsync(arg1, arg2));
else else
await eventHandler.InvokeAsync(arg1, arg2).ConfigureAwait(false); return eventHandler.InvokeAsync(arg1, arg2);
} }
return Task.CompletedTask;
} }
private async Task TimedInvokeAsync<T1, T2, T3>(AsyncEvent<Func<T1, T2, T3, Task>> eventHandler, string name, T1 arg1, T2 arg2, T3 arg3)
private Task TimedInvokeAsync<T1, T2, T3>(AsyncEvent<Func<T1, T2, T3, Task>> eventHandler, string name, T1 arg1, T2 arg2, T3 arg3)
{ {
if (eventHandler.HasSubscribers) if (eventHandler.HasSubscribers)
{ {
if (HandlerTimeout.HasValue) if (HandlerTimeout.HasValue)
await TimeoutWrap(name, () => eventHandler.InvokeAsync(arg1, arg2, arg3)).ConfigureAwait(false); return TimeoutWrap(name, () => eventHandler.InvokeAsync(arg1, arg2, arg3));
else else
await eventHandler.InvokeAsync(arg1, arg2, arg3).ConfigureAwait(false); return eventHandler.InvokeAsync(arg1, arg2, arg3);
} }
return Task.CompletedTask;
} }
private async Task TimedInvokeAsync<T1, T2, T3, T4>(AsyncEvent<Func<T1, T2, T3, T4, Task>> eventHandler, string name, T1 arg1, T2 arg2, T3 arg3, T4 arg4)
private Task TimedInvokeAsync<T1, T2, T3, T4>(AsyncEvent<Func<T1, T2, T3, T4, Task>> eventHandler, string name, T1 arg1, T2 arg2, T3 arg3, T4 arg4)
{ {
if (eventHandler.HasSubscribers) if (eventHandler.HasSubscribers)
{ {
if (HandlerTimeout.HasValue) if (HandlerTimeout.HasValue)
await TimeoutWrap(name, () => eventHandler.InvokeAsync(arg1, arg2, arg3, arg4)).ConfigureAwait(false); return TimeoutWrap(name, () => eventHandler.InvokeAsync(arg1, arg2, arg3, arg4));
else else
await eventHandler.InvokeAsync(arg1, arg2, arg3, arg4).ConfigureAwait(false); return eventHandler.InvokeAsync(arg1, arg2, arg3, arg4);
} }
return Task.CompletedTask;
} }
private async Task TimedInvokeAsync<T1, T2, T3, T4, T5>(AsyncEvent<Func<T1, T2, T3, T4, T5, Task>> eventHandler, string name, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5)
private Task TimedInvokeAsync<T1, T2, T3, T4, T5>(AsyncEvent<Func<T1, T2, T3, T4, T5, Task>> eventHandler, string name, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5)
{ {
if (eventHandler.HasSubscribers) if (eventHandler.HasSubscribers)
{ {
if (HandlerTimeout.HasValue) if (HandlerTimeout.HasValue)
await TimeoutWrap(name, () => eventHandler.InvokeAsync(arg1, arg2, arg3, arg4, arg5)).ConfigureAwait(false); return TimeoutWrap(name, () => eventHandler.InvokeAsync(arg1, arg2, arg3, arg4, arg5));
else else
await eventHandler.InvokeAsync(arg1, arg2, arg3, arg4, arg5).ConfigureAwait(false); return eventHandler.InvokeAsync(arg1, arg2, arg3, arg4, arg5);
} }
return Task.CompletedTask;
} }
private async Task TimeoutWrap(string name, Func<Task> action) private async Task TimeoutWrap(string name, Func<Task> action)
{ {
try try
@@ -3429,61 +3459,68 @@ namespace Discord.WebSocket
} }
} }
private async Task UnknownGlobalUserAsync(string evnt, ulong userId) private Task UnknownGlobalUserAsync(string evnt, ulong userId)
{ {
string details = $"{evnt} User={userId}"; string details = $"{evnt} User={userId}";
await _gatewayLogger.WarningAsync($"Unknown User ({details}).").ConfigureAwait(false); return _gatewayLogger.WarningAsync($"Unknown User ({details}).");
} }
private async Task UnknownChannelUserAsync(string evnt, ulong userId, ulong channelId)
private Task UnknownChannelUserAsync(string evnt, ulong userId, ulong channelId)
{ {
string details = $"{evnt} User={userId} Channel={channelId}"; string details = $"{evnt} User={userId} Channel={channelId}";
await _gatewayLogger.WarningAsync($"Unknown User ({details}).").ConfigureAwait(false); return _gatewayLogger.WarningAsync($"Unknown User ({details}).");
} }
private async Task UnknownGuildUserAsync(string evnt, ulong userId, ulong guildId)
private Task UnknownGuildUserAsync(string evnt, ulong userId, ulong guildId)
{ {
string details = $"{evnt} User={userId} Guild={guildId}"; string details = $"{evnt} User={userId} Guild={guildId}";
await _gatewayLogger.WarningAsync($"Unknown User ({details}).").ConfigureAwait(false); return _gatewayLogger.WarningAsync($"Unknown User ({details}).");
} }
private async Task IncompleteGuildUserAsync(string evnt, ulong userId, ulong guildId)
private Task IncompleteGuildUserAsync(string evnt, ulong userId, ulong guildId)
{ {
string details = $"{evnt} User={userId} Guild={guildId}"; string details = $"{evnt} User={userId} Guild={guildId}";
await _gatewayLogger.DebugAsync($"User has not been downloaded ({details}).").ConfigureAwait(false); return _gatewayLogger.DebugAsync($"User has not been downloaded ({details}).");
} }
private async Task UnknownChannelAsync(string evnt, ulong channelId)
private Task UnknownChannelAsync(string evnt, ulong channelId)
{ {
string details = $"{evnt} Channel={channelId}"; string details = $"{evnt} Channel={channelId}";
await _gatewayLogger.WarningAsync($"Unknown Channel ({details}).").ConfigureAwait(false); return _gatewayLogger.WarningAsync($"Unknown Channel ({details}).");
} }
private async Task UnknownChannelAsync(string evnt, ulong channelId, ulong guildId)
private Task UnknownChannelAsync(string evnt, ulong channelId, ulong guildId)
{ {
if (guildId == 0) if (guildId == 0)
{ {
await UnknownChannelAsync(evnt, channelId).ConfigureAwait(false); return UnknownChannelAsync(evnt, channelId);
return;
} }
string details = $"{evnt} Channel={channelId} Guild={guildId}"; string details = $"{evnt} Channel={channelId} Guild={guildId}";
await _gatewayLogger.WarningAsync($"Unknown Channel ({details}).").ConfigureAwait(false); return _gatewayLogger.WarningAsync($"Unknown Channel ({details}).");
}
private async Task UnknownRoleAsync(string evnt, ulong roleId, ulong guildId)
{
string details = $"{evnt} Role={roleId} Guild={guildId}";
await _gatewayLogger.WarningAsync($"Unknown Role ({details}).").ConfigureAwait(false);
}
private async Task UnknownGuildAsync(string evnt, ulong guildId)
{
string details = $"{evnt} Guild={guildId}";
await _gatewayLogger.WarningAsync($"Unknown Guild ({details}).").ConfigureAwait(false);
} }
private async Task UnknownGuildEventAsync(string evnt, ulong eventId, ulong guildId) private Task UnknownRoleAsync(string evnt, ulong roleId, ulong guildId)
{ {
string details = $"{evnt} Event={eventId} Guild={guildId}"; string details = $"{evnt} Role={roleId} Guild={guildId}";
await _gatewayLogger.WarningAsync($"Unknown Guild Event ({details}).").ConfigureAwait(false); return _gatewayLogger.WarningAsync($"Unknown Role ({details}).");
} }
private async Task UnsyncedGuildAsync(string evnt, ulong guildId)
private Task UnknownGuildAsync(string evnt, ulong guildId)
{ {
string details = $"{evnt} Guild={guildId}"; string details = $"{evnt} Guild={guildId}";
await _gatewayLogger.DebugAsync($"Unsynced Guild ({details}).").ConfigureAwait(false); return _gatewayLogger.WarningAsync($"Unknown Guild ({details}).");
}
private Task UnknownGuildEventAsync(string evnt, ulong eventId, ulong guildId)
{
string details = $"{evnt} Event={eventId} Guild={guildId}";
return _gatewayLogger.WarningAsync($"Unknown Guild Event ({details}).");
}
private Task UnsyncedGuildAsync(string evnt, ulong guildId)
{
string details = $"{evnt} Guild={guildId}";
return _gatewayLogger.DebugAsync($"Unsynced Guild ({details}).");
} }
internal int GetAudioId() => _nextAudioId++; internal int GetAudioId() => _nextAudioId++;
@@ -3558,11 +3595,12 @@ namespace Discord.WebSocket
=> await BulkOverwriteGlobalApplicationCommandsAsync(properties, options); => await BulkOverwriteGlobalApplicationCommandsAsync(properties, options);
/// <inheritdoc /> /// <inheritdoc />
async Task IDiscordClient.StartAsync() Task IDiscordClient.StartAsync()
=> await StartAsync().ConfigureAwait(false); => StartAsync();
/// <inheritdoc /> /// <inheritdoc />
async Task IDiscordClient.StopAsync() Task IDiscordClient.StopAsync()
=> await StopAsync().ConfigureAwait(false); => StopAsync();
#endregion #endregion
} }
} }

View File

@@ -55,7 +55,7 @@ namespace Discord.Audio
GuildId = guildId; GuildId = guildId;
_connectionLock = new SemaphoreSlim(1, 1); _connectionLock = new SemaphoreSlim(1, 1);
_udp = udpSocketProvider(); _udp = udpSocketProvider();
_udp.ReceivedDatagram += async (data, index, count) => _udp.ReceivedDatagram += (data, index, count) =>
{ {
if (index != 0 || count != data.Length) if (index != 0 || count != data.Length)
{ {
@@ -63,7 +63,7 @@ namespace Discord.Audio
Buffer.BlockCopy(data, index, newData, 0, count); Buffer.BlockCopy(data, index, newData, 0, count);
data = newData; data = newData;
} }
await _receivedPacketEvent.InvokeAsync(data).ConfigureAwait(false); return _receivedPacketEvent.InvokeAsync(data);
}; };
WebSocketClient = webSocketProvider(); WebSocketClient = webSocketProvider();
@@ -83,10 +83,10 @@ namespace Discord.Audio
} }
} }
}; };
WebSocketClient.TextMessage += async text => WebSocketClient.TextMessage += text =>
{ {
var msg = JsonConvert.DeserializeObject<SocketFrame>(text); var msg = JsonConvert.DeserializeObject<SocketFrame>(text);
await _receivedEvent.InvokeAsync((VoiceOpCode)msg.Operation, msg.Payload).ConfigureAwait(false); return _receivedEvent.InvokeAsync((VoiceOpCode)msg.Operation, msg.Payload);
}; };
WebSocketClient.Closed += async ex => WebSocketClient.Closed += async ex =>
{ {
@@ -129,23 +129,23 @@ namespace Discord.Audio
#endregion #endregion
#region WebSocket #region WebSocket
public async Task SendHeartbeatAsync(RequestOptions options = null) public Task SendHeartbeatAsync(RequestOptions options = null)
=> SendAsync(VoiceOpCode.Heartbeat, DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), options: options);
public Task SendIdentityAsync(ulong userId, string sessionId, string token)
{ {
await SendAsync(VoiceOpCode.Heartbeat, DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), options: options).ConfigureAwait(false); return SendAsync(VoiceOpCode.Identify, new IdentifyParams
}
public async Task SendIdentityAsync(ulong userId, string sessionId, string token)
{
await SendAsync(VoiceOpCode.Identify, new IdentifyParams
{ {
GuildId = GuildId, GuildId = GuildId,
UserId = userId, UserId = userId,
SessionId = sessionId, SessionId = sessionId,
Token = token Token = token
}).ConfigureAwait(false); });
} }
public async Task SendSelectProtocol(string externalIp, int externalPort)
public Task SendSelectProtocol(string externalIp, int externalPort)
{ {
await SendAsync(VoiceOpCode.SelectProtocol, new SelectProtocolParams return SendAsync(VoiceOpCode.SelectProtocol, new SelectProtocolParams
{ {
Protocol = "udp", Protocol = "udp",
Data = new UdpProtocolInfo Data = new UdpProtocolInfo
@@ -154,15 +154,16 @@ namespace Discord.Audio
Port = externalPort, Port = externalPort,
Mode = Mode Mode = Mode
} }
}).ConfigureAwait(false); });
} }
public async Task SendSetSpeaking(bool value)
public Task SendSetSpeaking(bool value)
{ {
await SendAsync(VoiceOpCode.Speaking, new SpeakingParams return SendAsync(VoiceOpCode.Speaking, new SpeakingParams
{ {
IsSpeaking = value, IsSpeaking = value,
Delay = 0 Delay = 0
}).ConfigureAwait(false); });
} }
public async Task ConnectAsync(string url) public async Task ConnectAsync(string url)
@@ -174,6 +175,7 @@ namespace Discord.Audio
} }
finally { _connectionLock.Release(); } finally { _connectionLock.Release(); }
} }
private async Task ConnectInternalAsync(string url) private async Task ConnectInternalAsync(string url)
{ {
ConnectionState = ConnectionState.Connecting; ConnectionState = ConnectionState.Connecting;

View File

@@ -259,13 +259,14 @@ namespace Discord.WebSocket
#region IMessageChannel #region IMessageChannel
/// <inheritdoc /> /// <inheritdoc />
async Task<IMessage> IMessageChannel.GetMessageAsync(ulong id, CacheMode mode, RequestOptions options) Task<IMessage> IMessageChannel.GetMessageAsync(ulong id, CacheMode mode, RequestOptions options)
{ {
if (mode == CacheMode.AllowDownload) if (mode == CacheMode.AllowDownload)
return await GetMessageAsync(id, options).ConfigureAwait(false); return GetMessageAsync(id, options);
else else
return GetCachedMessage(id); return Task.FromResult((IMessage)GetCachedMessage(id));
} }
/// <inheritdoc /> /// <inheritdoc />
IAsyncEnumerable<IReadOnlyCollection<IMessage>> IMessageChannel.GetMessagesAsync(int limit, CacheMode mode, RequestOptions options) IAsyncEnumerable<IReadOnlyCollection<IMessage>> IMessageChannel.GetMessagesAsync(int limit, CacheMode mode, RequestOptions options)
=> mode == CacheMode.CacheOnly ? null : GetMessagesAsync(limit, options); => mode == CacheMode.CacheOnly ? null : GetMessagesAsync(limit, options);

View File

@@ -330,12 +330,12 @@ namespace Discord.WebSocket
#region IMessageChannel #region IMessageChannel
/// <inheritdoc /> /// <inheritdoc />
async Task<IMessage> IMessageChannel.GetMessageAsync(ulong id, CacheMode mode, RequestOptions options) Task<IMessage> IMessageChannel.GetMessageAsync(ulong id, CacheMode mode, RequestOptions options)
{ {
if (mode == CacheMode.AllowDownload) if (mode == CacheMode.AllowDownload)
return await GetMessageAsync(id, options).ConfigureAwait(false); return GetMessageAsync(id, options);
else else
return GetCachedMessage(id); return Task.FromResult((IMessage)GetCachedMessage(id));
} }
/// <inheritdoc /> /// <inheritdoc />
IAsyncEnumerable<IReadOnlyCollection<IMessage>> IMessageChannel.GetMessagesAsync(int limit, CacheMode mode, RequestOptions options) IAsyncEnumerable<IReadOnlyCollection<IMessage>> IMessageChannel.GetMessagesAsync(int limit, CacheMode mode, RequestOptions options)

View File

@@ -131,10 +131,8 @@ namespace Discord.WebSocket
/// <returns> /// <returns>
/// A task representing the asynchronous permission operation for adding the specified permissions to the channel. /// A task representing the asynchronous permission operation for adding the specified permissions to the channel.
/// </returns> /// </returns>
public virtual async Task AddPermissionOverwriteAsync(IUser user, OverwritePermissions permissions, RequestOptions options = null) public virtual Task AddPermissionOverwriteAsync(IUser user, OverwritePermissions permissions, RequestOptions options = null)
{ => ChannelHelper.AddPermissionOverwriteAsync(this, Discord, user, permissions, options);
await ChannelHelper.AddPermissionOverwriteAsync(this, Discord, user, permissions, options).ConfigureAwait(false);
}
/// <summary> /// <summary>
/// Adds or updates the permission overwrite for the given role. /// Adds or updates the permission overwrite for the given role.
@@ -145,10 +143,9 @@ namespace Discord.WebSocket
/// <returns> /// <returns>
/// A task representing the asynchronous permission operation for adding the specified permissions to the channel. /// A task representing the asynchronous permission operation for adding the specified permissions to the channel.
/// </returns> /// </returns>
public virtual async Task AddPermissionOverwriteAsync(IRole role, OverwritePermissions permissions, RequestOptions options = null) public virtual Task AddPermissionOverwriteAsync(IRole role, OverwritePermissions permissions, RequestOptions options = null)
{ => ChannelHelper.AddPermissionOverwriteAsync(this, Discord, role, permissions, options);
await ChannelHelper.AddPermissionOverwriteAsync(this, Discord, role, permissions, options).ConfigureAwait(false);
}
/// <summary> /// <summary>
/// Removes the permission overwrite for the given user, if one exists. /// Removes the permission overwrite for the given user, if one exists.
/// </summary> /// </summary>
@@ -157,10 +154,9 @@ namespace Discord.WebSocket
/// <returns> /// <returns>
/// A task representing the asynchronous operation for removing the specified permissions from the channel. /// A task representing the asynchronous operation for removing the specified permissions from the channel.
/// </returns> /// </returns>
public virtual async Task RemovePermissionOverwriteAsync(IUser user, RequestOptions options = null) public virtual Task RemovePermissionOverwriteAsync(IUser user, RequestOptions options = null)
{ => ChannelHelper.RemovePermissionOverwriteAsync(this, Discord, user, options);
await ChannelHelper.RemovePermissionOverwriteAsync(this, Discord, user, options).ConfigureAwait(false);
}
/// <summary> /// <summary>
/// Removes the permission overwrite for the given role, if one exists. /// Removes the permission overwrite for the given role, if one exists.
/// </summary> /// </summary>
@@ -169,10 +165,8 @@ namespace Discord.WebSocket
/// <returns> /// <returns>
/// A task representing the asynchronous operation for removing the specified permissions from the channel. /// A task representing the asynchronous operation for removing the specified permissions from the channel.
/// </returns> /// </returns>
public virtual async Task RemovePermissionOverwriteAsync(IRole role, RequestOptions options = null) public virtual Task RemovePermissionOverwriteAsync(IRole role, RequestOptions options = null)
{ => ChannelHelper.RemovePermissionOverwriteAsync(this, Discord, role, options);
await ChannelHelper.RemovePermissionOverwriteAsync(this, Discord, role, options).ConfigureAwait(false);
}
public new virtual SocketGuildUser GetUser(ulong id) => null; public new virtual SocketGuildUser GetUser(ulong id) => null;
@@ -207,17 +201,20 @@ namespace Discord.WebSocket
OverwritePermissions? IGuildChannel.GetPermissionOverwrite(IUser user) OverwritePermissions? IGuildChannel.GetPermissionOverwrite(IUser user)
=> GetPermissionOverwrite(user); => GetPermissionOverwrite(user);
/// <inheritdoc /> /// <inheritdoc />
async Task IGuildChannel.AddPermissionOverwriteAsync(IRole role, OverwritePermissions permissions, RequestOptions options) Task IGuildChannel.AddPermissionOverwriteAsync(IRole role, OverwritePermissions permissions, RequestOptions options)
=> await AddPermissionOverwriteAsync(role, permissions, options).ConfigureAwait(false); => AddPermissionOverwriteAsync(role, permissions, options);
/// <inheritdoc /> /// <inheritdoc />
async Task IGuildChannel.AddPermissionOverwriteAsync(IUser user, OverwritePermissions permissions, RequestOptions options) Task IGuildChannel.AddPermissionOverwriteAsync(IUser user, OverwritePermissions permissions, RequestOptions options)
=> await AddPermissionOverwriteAsync(user, permissions, options).ConfigureAwait(false); => AddPermissionOverwriteAsync(user, permissions, options);
/// <inheritdoc /> /// <inheritdoc />
async Task IGuildChannel.RemovePermissionOverwriteAsync(IRole role, RequestOptions options) Task IGuildChannel.RemovePermissionOverwriteAsync(IRole role, RequestOptions options)
=> await RemovePermissionOverwriteAsync(role, options).ConfigureAwait(false); => RemovePermissionOverwriteAsync(role, options);
/// <inheritdoc /> /// <inheritdoc />
async Task IGuildChannel.RemovePermissionOverwriteAsync(IUser user, RequestOptions options) Task IGuildChannel.RemovePermissionOverwriteAsync(IUser user, RequestOptions options)
=> await RemovePermissionOverwriteAsync(user, options).ConfigureAwait(false); => RemovePermissionOverwriteAsync(user, options);
/// <inheritdoc /> /// <inheritdoc />
IAsyncEnumerable<IReadOnlyCollection<IGuildUser>> IGuildChannel.GetUsersAsync(CacheMode mode, RequestOptions options) IAsyncEnumerable<IReadOnlyCollection<IGuildUser>> IGuildChannel.GetUsersAsync(CacheMode mode, RequestOptions options)

View File

@@ -413,12 +413,12 @@ namespace Discord.WebSocket
#region IMessageChannel #region IMessageChannel
/// <inheritdoc /> /// <inheritdoc />
async Task<IMessage> IMessageChannel.GetMessageAsync(ulong id, CacheMode mode, RequestOptions options) Task<IMessage> IMessageChannel.GetMessageAsync(ulong id, CacheMode mode, RequestOptions options)
{ {
if (mode == CacheMode.AllowDownload) if (mode == CacheMode.AllowDownload)
return await GetMessageAsync(id, options).ConfigureAwait(false); return GetMessageAsync(id, options);
else else
return GetCachedMessage(id); return Task.FromResult((IMessage)GetCachedMessage(id));
} }
/// <inheritdoc /> /// <inheritdoc />
IAsyncEnumerable<IReadOnlyCollection<IMessage>> IMessageChannel.GetMessagesAsync(int limit, CacheMode mode, RequestOptions options) IAsyncEnumerable<IReadOnlyCollection<IMessage>> IMessageChannel.GetMessagesAsync(int limit, CacheMode mode, RequestOptions options)

View File

@@ -89,20 +89,17 @@ namespace Discord.WebSocket
=> ChannelHelper.ModifyAsync(this, Discord, func, options); => ChannelHelper.ModifyAsync(this, Discord, func, options);
/// <inheritdoc /> /// <inheritdoc />
public async Task<IAudioClient> ConnectAsync(bool selfDeaf = false, bool selfMute = false, bool external = false) public Task<IAudioClient> ConnectAsync(bool selfDeaf = false, bool selfMute = false, bool external = false)
{ => Guild.ConnectAudioAsync(Id, selfDeaf, selfMute, external);
return await Guild.ConnectAudioAsync(Id, selfDeaf, selfMute, external).ConfigureAwait(false);
}
/// <inheritdoc /> /// <inheritdoc />
public async Task DisconnectAsync() public Task DisconnectAsync()
=> await Guild.DisconnectAudioAsync(); => Guild.DisconnectAudioAsync();
/// <inheritdoc /> /// <inheritdoc />
public async Task ModifyAsync(Action<AudioChannelProperties> func, RequestOptions options = null) public Task ModifyAsync(Action<AudioChannelProperties> func, RequestOptions options = null)
{ => Guild.ModifyAudioAsync(Id, func, options);
await Guild.ModifyAudioAsync(Id, func, options).ConfigureAwait(false);
}
/// <inheritdoc /> /// <inheritdoc />
public override SocketGuildUser GetUser(ulong id) public override SocketGuildUser GetUser(ulong id)

View File

@@ -1307,10 +1307,9 @@ namespace Discord.WebSocket
} }
/// <inheritdoc /> /// <inheritdoc />
public async Task DownloadUsersAsync() public Task DownloadUsersAsync()
{ => Discord.DownloadUsersAsync(new[] { this });
await Discord.DownloadUsersAsync(new[] { this }).ConfigureAwait(false);
}
internal void CompleteDownloadUsers() internal void CompleteDownloadUsers()
{ {
_downloaderPromise.TrySetResultAsync(true); _downloaderPromise.TrySetResultAsync(true);
@@ -1545,7 +1544,8 @@ namespace Discord.WebSocket
/// </summary> /// </summary>
/// <param name="user">The user to disconnect.</param> /// <param name="user">The user to disconnect.</param>
/// <returns>A task that represents the asynchronous operation for disconnecting a user.</returns> /// <returns>A task that represents the asynchronous operation for disconnecting a user.</returns>
async Task IGuild.DisconnectAsync(IGuildUser user) => await user.ModifyAsync(x => x.Channel = null); Task IGuild.DisconnectAsync(IGuildUser user)
=> user.ModifyAsync(x => x.Channel = null);
#endregion #endregion
#region Stickers #region Stickers
@@ -1850,7 +1850,7 @@ namespace Discord.WebSocket
} }
} }
private async Task ModifyAudioInternalAsync(ulong channelId, Action<AudioChannelProperties> func, RequestOptions options) private Task ModifyAudioInternalAsync(ulong channelId, Action<AudioChannelProperties> func, RequestOptions options)
{ {
if (_voiceStateUpdateParams == null || _voiceStateUpdateParams.ChannelId != channelId) if (_voiceStateUpdateParams == null || _voiceStateUpdateParams.ChannelId != channelId)
throw new InvalidOperationException("Cannot modify properties of not connected audio channel"); throw new InvalidOperationException("Cannot modify properties of not connected audio channel");
@@ -1863,7 +1863,7 @@ namespace Discord.WebSocket
if (props.SelfMute.IsSpecified) if (props.SelfMute.IsSpecified)
_voiceStateUpdateParams.SelfMute = props.SelfMute.Value; _voiceStateUpdateParams.SelfMute = props.SelfMute.Value;
await Discord.ApiClient.SendVoiceStateUpdateAsync(_voiceStateUpdateParams, options).ConfigureAwait(false); return Discord.ApiClient.SendVoiceStateUpdateAsync(_voiceStateUpdateParams, options);
} }
internal async Task FinishConnectAudio(string url, string token) internal async Task FinishConnectAudio(string url, string token)

View File

@@ -305,7 +305,7 @@ namespace Discord.WebSocket
} }
/// <inheritdoc/> /// <inheritdoc/>
public override async Task<RestFollowupMessage> FollowupAsync( public override Task<RestFollowupMessage> FollowupAsync(
string text = null, string text = null,
Embed[] embeds = null, Embed[] embeds = null,
bool isTTS = false, bool isTTS = false,
@@ -338,11 +338,11 @@ namespace Discord.WebSocket
if (ephemeral) if (ephemeral)
args.Flags = MessageFlags.Ephemeral; args.Flags = MessageFlags.Ephemeral;
return await InteractionHelper.SendFollowupAsync(Discord.Rest, args, Token, Channel, options); return InteractionHelper.SendFollowupAsync(Discord.Rest, args, Token, Channel, options);
} }
/// <inheritdoc/> /// <inheritdoc/>
public override async Task<RestFollowupMessage> FollowupWithFilesAsync( public override Task<RestFollowupMessage> FollowupWithFilesAsync(
IEnumerable<FileAttachment> attachments, IEnumerable<FileAttachment> attachments,
string text = null, string text = null,
Embed[] embeds = null, Embed[] embeds = null,
@@ -391,7 +391,7 @@ namespace Discord.WebSocket
flags |= MessageFlags.Ephemeral; flags |= MessageFlags.Ephemeral;
var args = new API.Rest.UploadWebhookFileParams(attachments.ToArray()) { Flags = flags, Content = text, IsTTS = isTTS, Embeds = embeds.Any() ? embeds.Select(x => x.ToModel()).ToArray() : Optional<API.Embed[]>.Unspecified, AllowedMentions = allowedMentions?.ToModel() ?? Optional<API.AllowedMentions>.Unspecified, MessageComponents = components?.Components.Select(x => new API.ActionRowComponent(x)).ToArray() ?? Optional<API.ActionRowComponent[]>.Unspecified }; var args = new API.Rest.UploadWebhookFileParams(attachments.ToArray()) { Flags = flags, Content = text, IsTTS = isTTS, Embeds = embeds.Any() ? embeds.Select(x => x.ToModel()).ToArray() : Optional<API.Embed[]>.Unspecified, AllowedMentions = allowedMentions?.ToModel() ?? Optional<API.AllowedMentions>.Unspecified, MessageComponents = components?.Components.Select(x => new API.ActionRowComponent(x)).ToArray() ?? Optional<API.ActionRowComponent[]>.Unspecified };
return await InteractionHelper.SendFollowupAsync(Discord, args, Token, Channel, options).ConfigureAwait(false); return InteractionHelper.SendFollowupAsync(Discord, args, Token, Channel, options);
} }
/// <inheritdoc/> /// <inheritdoc/>

View File

@@ -302,7 +302,7 @@ namespace Discord.WebSocket
} }
/// <inheritdoc/> /// <inheritdoc/>
public override async Task<RestFollowupMessage> FollowupAsync( public override Task<RestFollowupMessage> FollowupAsync(
string text = null, string text = null,
Embed[] embeds = null, Embed[] embeds = null,
bool isTTS = false, bool isTTS = false,
@@ -335,11 +335,11 @@ namespace Discord.WebSocket
if (ephemeral) if (ephemeral)
args.Flags = MessageFlags.Ephemeral; args.Flags = MessageFlags.Ephemeral;
return await InteractionHelper.SendFollowupAsync(Discord.Rest, args, Token, Channel, options); return InteractionHelper.SendFollowupAsync(Discord.Rest, args, Token, Channel, options);
} }
/// <inheritdoc/> /// <inheritdoc/>
public override async Task<RestFollowupMessage> FollowupWithFilesAsync( public override Task<RestFollowupMessage> FollowupWithFilesAsync(
IEnumerable<FileAttachment> attachments, IEnumerable<FileAttachment> attachments,
string text = null, string text = null,
Embed[] embeds = null, Embed[] embeds = null,
@@ -388,7 +388,7 @@ namespace Discord.WebSocket
flags |= MessageFlags.Ephemeral; flags |= MessageFlags.Ephemeral;
var args = new API.Rest.UploadWebhookFileParams(attachments.ToArray()) { Flags = flags, Content = text, IsTTS = isTTS, Embeds = embeds.Any() ? embeds.Select(x => x.ToModel()).ToArray() : Optional<API.Embed[]>.Unspecified, AllowedMentions = allowedMentions?.ToModel() ?? Optional<API.AllowedMentions>.Unspecified, MessageComponents = components?.Components.Select(x => new API.ActionRowComponent(x)).ToArray() ?? Optional<API.ActionRowComponent[]>.Unspecified }; var args = new API.Rest.UploadWebhookFileParams(attachments.ToArray()) { Flags = flags, Content = text, IsTTS = isTTS, Embeds = embeds.Any() ? embeds.Select(x => x.ToModel()).ToArray() : Optional<API.Embed[]>.Unspecified, AllowedMentions = allowedMentions?.ToModel() ?? Optional<API.AllowedMentions>.Unspecified, MessageComponents = components?.Components.Select(x => new API.ActionRowComponent(x)).ToArray() ?? Optional<API.ActionRowComponent[]>.Unspecified };
return await InteractionHelper.SendFollowupAsync(Discord, args, Token, Channel, options).ConfigureAwait(false); return InteractionHelper.SendFollowupAsync(Discord, args, Token, Channel, options);
} }
/// <inheritdoc/> /// <inheritdoc/>

View File

@@ -234,7 +234,7 @@ namespace Discord.WebSocket
} }
/// <inheritdoc/> /// <inheritdoc/>
public override async Task<RestFollowupMessage> FollowupAsync( public override Task<RestFollowupMessage> FollowupAsync(
string text = null, string text = null,
Embed[] embeds = null, Embed[] embeds = null,
bool isTTS = false, bool isTTS = false,
@@ -267,11 +267,11 @@ namespace Discord.WebSocket
if (ephemeral) if (ephemeral)
args.Flags = MessageFlags.Ephemeral; args.Flags = MessageFlags.Ephemeral;
return await InteractionHelper.SendFollowupAsync(Discord.Rest, args, Token, Channel, options); return InteractionHelper.SendFollowupAsync(Discord.Rest, args, Token, Channel, options);
} }
/// <inheritdoc/> /// <inheritdoc/>
public override async Task<RestFollowupMessage> FollowupWithFilesAsync( public override Task<RestFollowupMessage> FollowupWithFilesAsync(
IEnumerable<FileAttachment> attachments, IEnumerable<FileAttachment> attachments,
string text = null, string text = null,
Embed[] embeds = null, Embed[] embeds = null,
@@ -320,7 +320,7 @@ namespace Discord.WebSocket
flags |= MessageFlags.Ephemeral; flags |= MessageFlags.Ephemeral;
var args = new API.Rest.UploadWebhookFileParams(attachments.ToArray()) { Flags = flags, Content = text, IsTTS = isTTS, Embeds = embeds.Any() ? embeds.Select(x => x.ToModel()).ToArray() : Optional<API.Embed[]>.Unspecified, AllowedMentions = allowedMentions?.ToModel() ?? Optional<API.AllowedMentions>.Unspecified, MessageComponents = components?.Components.Select(x => new API.ActionRowComponent(x)).ToArray() ?? Optional<API.ActionRowComponent[]>.Unspecified }; var args = new API.Rest.UploadWebhookFileParams(attachments.ToArray()) { Flags = flags, Content = text, IsTTS = isTTS, Embeds = embeds.Any() ? embeds.Select(x => x.ToModel()).ToArray() : Optional<API.Embed[]>.Unspecified, AllowedMentions = allowedMentions?.ToModel() ?? Optional<API.AllowedMentions>.Unspecified, MessageComponents = components?.Components.Select(x => new API.ActionRowComponent(x)).ToArray() ?? Optional<API.ActionRowComponent[]>.Unspecified };
return await InteractionHelper.SendFollowupAsync(Discord, args, Token, Channel, options).ConfigureAwait(false); return InteractionHelper.SendFollowupAsync(Discord, args, Token, Channel, options);
} }
/// <summary> /// <summary>

View File

@@ -228,14 +228,14 @@ namespace Discord.WebSocket
/// <inheritdoc /> /// <inheritdoc />
/// <exception cref="InvalidOperationException">This operation may only be called on a <see cref="INewsChannel"/> channel.</exception> /// <exception cref="InvalidOperationException">This operation may only be called on a <see cref="INewsChannel"/> channel.</exception>
public async Task CrosspostAsync(RequestOptions options = null) public Task CrosspostAsync(RequestOptions options = null)
{ {
if (!(Channel is INewsChannel)) if (!(Channel is INewsChannel))
{ {
throw new InvalidOperationException("Publishing (crossposting) is only valid in news channels."); throw new InvalidOperationException("Publishing (crossposting) is only valid in news channels.");
} }
await MessageHelper.CrosspostAsync(this, Discord, options); return MessageHelper.CrosspostAsync(this, Discord, options);
} }
private string DebuggerDisplay => $"{Author}: {Content} ({Id}{(Attachments.Count > 0 ? $", {Attachments.Count} Attachments" : "")})"; private string DebuggerDisplay => $"{Author}: {Content} ({Id}{(Attachments.Count > 0 ? $", {Attachments.Count} Attachments" : "")})";

View File

@@ -116,7 +116,7 @@ namespace Discord.Net.Udp
_cancelToken = _cancelTokenSource.Token; _cancelToken = _cancelTokenSource.Token;
} }
public async Task SendAsync(byte[] data, int index, int count) public Task SendAsync(byte[] data, int index, int count)
{ {
if (index != 0) //Should never happen? if (index != 0) //Should never happen?
{ {
@@ -124,7 +124,7 @@ namespace Discord.Net.Udp
Buffer.BlockCopy(data, index, newData, 0, count); Buffer.BlockCopy(data, index, newData, 0, count);
data = newData; data = newData;
} }
await _udp.SendAsync(data, count, _destination).ConfigureAwait(false); return _udp.SendAsync(data, count, _destination);
} }
private async Task RunAsync(CancellationToken cancelToken) private async Task RunAsync(CancellationToken cancelToken)

View File

@@ -56,7 +56,7 @@ namespace Discord.Webhook
return model.Id; return model.Id;
} }
public static async Task ModifyMessageAsync(DiscordWebhookClient client, ulong messageId, public static Task ModifyMessageAsync(DiscordWebhookClient client, ulong messageId,
Action<WebhookMessageProperties> func, RequestOptions options, ulong? threadId) Action<WebhookMessageProperties> func, RequestOptions options, ulong? threadId)
{ {
var args = new WebhookMessageProperties(); var args = new WebhookMessageProperties();
@@ -104,8 +104,7 @@ namespace Discord.Webhook
Components = args.Components.IsSpecified ? args.Components.Value?.Components.Select(x => new API.ActionRowComponent(x)).ToArray() : Optional<API.ActionRowComponent[]>.Unspecified, Components = args.Components.IsSpecified ? args.Components.Value?.Components.Select(x => new API.ActionRowComponent(x)).ToArray() : Optional<API.ActionRowComponent[]>.Unspecified,
}; };
await client.ApiClient.ModifyWebhookMessageAsync(client.Webhook.Id, messageId, apiArgs, options, threadId) return client.ApiClient.ModifyWebhookMessageAsync(client.Webhook.Id, messageId, apiArgs, options, threadId);
.ConfigureAwait(false);
} }
else else
{ {
@@ -124,15 +123,12 @@ namespace Discord.Webhook
MessageComponents = args.Components.IsSpecified ? args.Components.Value?.Components.Select(x => new API.ActionRowComponent(x)).ToArray() : Optional<API.ActionRowComponent[]>.Unspecified, MessageComponents = args.Components.IsSpecified ? args.Components.Value?.Components.Select(x => new API.ActionRowComponent(x)).ToArray() : Optional<API.ActionRowComponent[]>.Unspecified,
}; };
await client.ApiClient.ModifyWebhookMessageAsync(client.Webhook.Id, messageId, apiArgs, options, threadId) return client.ApiClient.ModifyWebhookMessageAsync(client.Webhook.Id, messageId, apiArgs, options, threadId);
.ConfigureAwait(false);
} }
} }
public static async Task DeleteMessageAsync(DiscordWebhookClient client, ulong messageId, RequestOptions options, ulong? threadId) public static Task DeleteMessageAsync(DiscordWebhookClient client, ulong messageId, RequestOptions options, ulong? threadId)
{ => client.ApiClient.DeleteWebhookMessageAsync(client.Webhook.Id, messageId, options, threadId);
await client.ApiClient.DeleteWebhookMessageAsync(client.Webhook.Id, messageId, options, threadId).ConfigureAwait(false);
}
public static async Task<ulong> SendFileAsync(DiscordWebhookClient client, string filePath, string text, bool isTTS, public static async Task<ulong> SendFileAsync(DiscordWebhookClient client, string filePath, string text, bool isTTS,
IEnumerable<Embed> embeds, string username, string avatarUrl, AllowedMentions allowedMentions, RequestOptions options, IEnumerable<Embed> embeds, string username, string avatarUrl, AllowedMentions allowedMentions, RequestOptions options,
@@ -206,7 +202,7 @@ namespace Discord.Webhook
return msg.Id; return msg.Id;
} }
public static async Task<WebhookModel> ModifyAsync(DiscordWebhookClient client, Action<WebhookProperties> func, RequestOptions options) public static Task<WebhookModel> ModifyAsync(DiscordWebhookClient client, Action<WebhookProperties> func, RequestOptions options)
{ {
var args = new WebhookProperties(); var args = new WebhookProperties();
func(args); func(args);
@@ -219,12 +215,10 @@ namespace Discord.Webhook
if (!apiArgs.Avatar.IsSpecified && client.Webhook.AvatarId != null) if (!apiArgs.Avatar.IsSpecified && client.Webhook.AvatarId != null)
apiArgs.Avatar = new ImageModel(client.Webhook.AvatarId); apiArgs.Avatar = new ImageModel(client.Webhook.AvatarId);
return await client.ApiClient.ModifyWebhookAsync(client.Webhook.Id, apiArgs, options).ConfigureAwait(false); return client.ApiClient.ModifyWebhookAsync(client.Webhook.Id, apiArgs, options);
} }
public static async Task DeleteAsync(DiscordWebhookClient client, RequestOptions options) public static Task DeleteAsync(DiscordWebhookClient client, RequestOptions options)
{ => client.ApiClient.DeleteWebhookAsync(client.Webhook.Id, options);
await client.ApiClient.DeleteWebhookAsync(client.Webhook.Id, options).ConfigureAwait(false);
}
} }
} }