[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();
}
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;
if (!searchResult.IsSuccess)
return ParseResult.FromError(searchResult);
return Task.FromResult(ParseResult.FromError(searchResult));
if (preconditionResult != null && !preconditionResult.IsSuccess)
return ParseResult.FromError(preconditionResult);
return Task.FromResult(ParseResult.FromError(preconditionResult));
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)

View File

@@ -87,10 +87,10 @@ namespace Discord.Commands
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;
return await _reader.ReadAsync(context, input, services).ConfigureAwait(false);
return _reader.ReadAsync(context, input, services);
}
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="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>
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,
Embed[] embeds = null, MessageFlags flags = MessageFlags.None)
{
return await Context.Channel.SendMessageAsync(message, isTTS, embed, options, allowedMentions, messageReference, components, stickers, embeds, flags).ConfigureAwait(false);
}
=> Context.Channel.SendMessageAsync(message, isTTS, embed, options, allowedMentions, messageReference, components, stickers, embeds, flags);
/// <summary>
/// The method to execute asynchronously before executing the command.
/// </summary>

View File

@@ -25,11 +25,11 @@ namespace Discord.Commands
}
/// <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))
return TypeReaderResult.FromSuccess(new T?());
return await _baseTypeReader.ReadAsync(context, input, services).ConfigureAwait(false);
return Task.FromResult(TypeReaderResult.FromSuccess(new T?()));
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
/// contains the sent message.
/// </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)
{
return await msg.Channel.SendMessageAsync(text, isTTS, embed, options, allowedMentions, new MessageReference(messageId: msg.Id), components, stickers, embeds, flags).ConfigureAwait(false);
}
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);
}
}

View File

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

View File

@@ -47,10 +47,8 @@ namespace Discord
/// A task that represents the asynchronous download operation. The task result contains the downloaded
/// entity.
/// </returns>
public async Task<TEntity> DownloadAsync()
{
return await DownloadFunc().ConfigureAwait(false);
}
public Task<TEntity> DownloadAsync()
=> DownloadFunc();
/// <summary>
/// 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
/// entity.
/// </returns>
public async Task<TDownloadableEntity> DownloadAsync()
public Task<TDownloadableEntity> DownloadAsync()
{
return await DownloadFunc().ConfigureAwait(false);
return DownloadFunc();
}
/// <summary>

View File

@@ -26,14 +26,14 @@ namespace Discord.Interactions
}
/// <inheritdoc/>
public async Task<IResult> ExecuteAsync(IInteractionContext context, IAutocompleteInteraction autocompleteInteraction, IParameterInfo parameter,
public Task<IResult> ExecuteAsync(IInteractionContext context, IAutocompleteInteraction autocompleteInteraction, IParameterInfo parameter,
IServiceProvider services)
{
switch (InteractionService._runMode)
{
case RunMode.Sync:
{
return await ExecuteInternalAsync(context, autocompleteInteraction, parameter, services).ConfigureAwait(false);
return ExecuteInternalAsync(context, autocompleteInteraction, parameter, services);
}
case RunMode.Async:
_ = Task.Run(async () =>
@@ -45,7 +45,7 @@ namespace Discord.Interactions
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,

View File

@@ -13,13 +13,13 @@ namespace Discord.Interactions
/// <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>
/// <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
{
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)}");
await SendModalResponseAsync(interaction, customId, modalInfo, options, modifyModal);
return SendModalResponseAsync(interaction, customId, modalInfo, options, modifyModal);
}
/// <summary>
@@ -35,13 +35,13 @@ namespace Discord.Interactions
/// <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>
/// <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)
where T : class, IModal
{
var modalInfo = ModalUtils.GetOrAdd<T>(interactionService);
await SendModalResponseAsync(interaction, customId, modalInfo, options, modifyModal);
return SendModalResponseAsync(interaction, customId, modalInfo, options, modifyModal);
}
/// <summary>
@@ -54,7 +54,7 @@ namespace Discord.Interactions
/// <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>
/// <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)
where T : class, IModal
{
@@ -79,13 +79,13 @@ namespace Discord.Interactions
if (modifyModal is not null)
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);
await interaction.RespondWithModalAsync(modal, options).ConfigureAwait(false);
return interaction.RespondWithModalAsync(modal, options);
}
}
}

View File

@@ -36,12 +36,12 @@ namespace Discord.Interactions
}
/// <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)
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)

View File

@@ -88,12 +88,12 @@ namespace Discord.Interactions
}
/// <inheritdoc/>
public virtual async Task<IResult> ExecuteAsync(IInteractionContext context, IServiceProvider services)
public virtual Task<IResult> ExecuteAsync(IInteractionContext context, IServiceProvider services)
{
switch (RunMode)
{
case RunMode.Sync:
return await ExecuteInternalAsync(context, services).ConfigureAwait(false);
return ExecuteInternalAsync(context, services);
case RunMode.Async:
_ = Task.Run(async () =>
{
@@ -104,7 +104,7 @@ namespace Discord.Interactions
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);

View File

@@ -24,12 +24,12 @@ namespace Discord.Interactions
}
/// <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)
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)

View File

@@ -12,12 +12,12 @@ namespace Discord.Interactions
: base(builder, module, commandService) { }
/// <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)
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)

View File

@@ -12,12 +12,12 @@ namespace Discord.Interactions
: base(builder, module, commandService) { }
/// <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)
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)

View File

@@ -28,12 +28,12 @@ namespace Discord.Interactions
}
/// <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)
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)

View File

@@ -64,12 +64,12 @@ namespace Discord.Interactions
}
/// <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)
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)

View File

@@ -41,13 +41,13 @@ namespace Discord.Interactions
}
/// <inheritdoc cref="IDiscordInteraction.DeferAsync(bool, RequestOptions)"/>
protected virtual async Task DeferAsync(bool ephemeral = false, RequestOptions options = null) =>
await Context.Interaction.DeferAsync(ephemeral, options).ConfigureAwait(false);
protected virtual Task DeferAsync(bool ephemeral = false, RequestOptions options = null)
=> Context.Interaction.DeferAsync(ephemeral, options);
/// <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,
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);
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)
=> 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)"/>
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);
/// <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,
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);
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)
=> 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)"/>
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);
/// <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,
Embed[] embeds = null, MessageFlags flags = MessageFlags.None) =>
await Context.Channel.SendMessageAsync(text, false, embed, options, allowedMentions, messageReference, components, stickers, embeds, flags).ConfigureAwait(false);
Embed[] embeds = null, MessageFlags flags = MessageFlags.None)
=> Context.Channel.SendMessageAsync(text, false, embed, options, allowedMentions, messageReference, components, stickers, embeds, flags);
/// <inheritdoc cref="IDiscordInteraction.GetOriginalResponseAsync(RequestOptions)"/>
protected virtual Task<IUserMessage> GetOriginalResponseAsync(RequestOptions options = null)
@@ -116,16 +116,16 @@ namespace Discord.Interactions
}
/// <inheritdoc cref="IDiscordInteraction.RespondWithModalAsync(Modal, RequestOptions)"/>
protected virtual async Task RespondWithModalAsync(Modal modal, RequestOptions options = null)
=> await Context.Interaction.RespondWithModalAsync(modal, options);
protected virtual Task RespondWithModalAsync(Modal modal, RequestOptions options = null)
=> Context.Interaction.RespondWithModalAsync(modal, options);
/// <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
=> await Context.Interaction.RespondWithModalAsync(customId, modal, options, modifyModal);
protected virtual Task RespondWithModalAsync<TModal>(string customId, TModal modal, RequestOptions options = null, Action<ModalBuilder> modifyModal = null) where TModal : class, IModal
=> Context.Interaction.RespondWithModalAsync(customId, modal, options, modifyModal);
/// <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
=> await Context.Interaction.RespondWithModalAsync<TModal>(customId, options, modifyModal);
protected virtual Task RespondWithModalAsync<TModal>(string customId, RequestOptions options = null, Action<ModalBuilder> modifyModal = null) where TModal : class, IModal
=> Context.Interaction.RespondWithModalAsync<TModal>(customId, options, modifyModal);
/// <inheritdoc cref="IDiscordInteraction.RespondWithPremiumRequiredAsync(RequestOptions)"/>
protected virtual Task RespondWithPremiumRequiredAsync(RequestOptions options = null)

View File

@@ -437,12 +437,12 @@ namespace Discord.Interactions
/// <returns>
/// A task representing the command registration process. The task result contains the active application commands of the target guild.
/// </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)
throw new ArgumentNullException(nameof(guild));
return await AddCommandsToGuildAsync(guild.Id, deleteMissing, commands).ConfigureAwait(false);
return AddCommandsToGuildAsync(guild.Id, deleteMissing, commands);
}
/// <summary>
@@ -498,12 +498,12 @@ namespace Discord.Interactions
/// <returns>
/// A task representing the command registration process. The task result contains the active application commands of the target guild.
/// </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)
throw new ArgumentNullException(nameof(guild));
return await AddModulesToGuildAsync(guild.Id, deleteMissing, modules).ConfigureAwait(false);
return AddModulesToGuildAsync(guild.Id, deleteMissing, modules);
}
/// <summary>
@@ -692,12 +692,12 @@ namespace Discord.Interactions
/// <returns>
/// A task representing the command de-registration process. The task result contains the active application commands of the target guild.
/// </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)
throw new ArgumentNullException(nameof(guild));
return await RemoveModulesFromGuildAsync(guild.Id, modules).ConfigureAwait(false);
return RemoveModulesFromGuildAsync(guild.Id, modules);
}
/// <summary>
@@ -1164,7 +1164,7 @@ namespace Discord.Interactions
/// <returns>
/// The active command permissions after the modification.
/// </returns>
public async Task<GuildApplicationCommandPermission> ModifySlashCommandPermissionsAsync(ModuleInfo module, IGuild guild,
public Task<GuildApplicationCommandPermission> ModifySlashCommandPermissionsAsync(ModuleInfo module, IGuild guild,
params ApplicationCommandPermission[] permissions)
{
if (module is null)
@@ -1173,7 +1173,7 @@ namespace Discord.Interactions
if (guild is null)
throw new ArgumentNullException(nameof(guild));
return await ModifySlashCommandPermissionsAsync(module, guild.Id, permissions).ConfigureAwait(false);
return ModifySlashCommandPermissionsAsync(module, guild.Id, permissions);
}
/// <summary>
@@ -1212,7 +1212,7 @@ namespace Discord.Interactions
/// <returns>
/// The active command permissions after the modification.
/// </returns>
public async Task<GuildApplicationCommandPermission> ModifySlashCommandPermissionsAsync(SlashCommandInfo command, IGuild guild,
public Task<GuildApplicationCommandPermission> ModifySlashCommandPermissionsAsync(SlashCommandInfo command, IGuild guild,
params ApplicationCommandPermission[] permissions)
{
if (command is null)
@@ -1221,7 +1221,7 @@ namespace Discord.Interactions
if (guild is null)
throw new ArgumentNullException(nameof(guild));
return await ModifyApplicationCommandPermissionsAsync(command, guild.Id, permissions).ConfigureAwait(false);
return ModifyApplicationCommandPermissionsAsync(command, guild.Id, permissions);
}
/// <summary>
@@ -1233,8 +1233,9 @@ namespace Discord.Interactions
/// <returns>
/// The active command permissions after the modification.
/// </returns>
public async Task<GuildApplicationCommandPermission> ModifySlashCommandPermissionsAsync(SlashCommandInfo command, ulong guildId,
params ApplicationCommandPermission[] permissions) => await ModifyApplicationCommandPermissionsAsync(command, guildId, permissions).ConfigureAwait(false);
public Task<GuildApplicationCommandPermission> ModifySlashCommandPermissionsAsync(SlashCommandInfo command, ulong guildId,
params ApplicationCommandPermission[] permissions)
=> ModifyApplicationCommandPermissionsAsync(command, guildId, permissions);
/// <summary>
/// Modify the command permissions of the matching Discord Slash Command.
@@ -1245,7 +1246,7 @@ namespace Discord.Interactions
/// <returns>
/// The active command permissions after the modification.
/// </returns>
public async Task<GuildApplicationCommandPermission> ModifyContextCommandPermissionsAsync(ContextCommandInfo command, IGuild guild,
public Task<GuildApplicationCommandPermission> ModifyContextCommandPermissionsAsync(ContextCommandInfo command, IGuild guild,
params ApplicationCommandPermission[] permissions)
{
if (command is null)
@@ -1254,7 +1255,7 @@ namespace Discord.Interactions
if (guild is null)
throw new ArgumentNullException(nameof(guild));
return await ModifyApplicationCommandPermissionsAsync(command, guild.Id, permissions).ConfigureAwait(false);
return ModifyApplicationCommandPermissionsAsync(command, guild.Id, permissions);
}
/// <summary>
@@ -1266,8 +1267,9 @@ namespace Discord.Interactions
/// <returns>
/// The active command permissions after the modification.
/// </returns>
public async Task<GuildApplicationCommandPermission> ModifyContextCommandPermissionsAsync(ContextCommandInfo command, ulong guildId,
params ApplicationCommandPermission[] permissions) => await ModifyApplicationCommandPermissionsAsync(command, guildId, permissions).ConfigureAwait(false);
public Task<GuildApplicationCommandPermission> ModifyContextCommandPermissionsAsync(ContextCommandInfo command, ulong guildId,
params ApplicationCommandPermission[] permissions)
=> ModifyApplicationCommandPermissionsAsync(command, guildId, permissions);
private async Task<GuildApplicationCommandPermission> ModifyApplicationCommandPermissionsAsync<T>(T command, ulong guildId,
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.
/// </returns>
/// <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)
=> await HandleInteractionAsync(x => x.Defer(ephemeral, options));
protected override Task DeferAsync(bool ephemeral = false, RequestOptions options = null)
=> HandleInteractionAsync(x => x.Defer(ephemeral, options));
/// <summary>
/// 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.
/// </returns>
/// <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)
=> await HandleInteractionAsync(x => x.Respond(text, embeds, isTTS, ephemeral, allowedMentions, components, embed, options));
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)
=> HandleInteractionAsync(x => x.Respond(text, embeds, isTTS, ephemeral, allowedMentions, components, embed, options));
/// <summary>
/// Responds to the interaction with a modal.
@@ -55,8 +55,8 @@ namespace Discord.Interactions
/// A Task representing the operation of creating the interaction response.
/// </returns>
/// <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)
=> await HandleInteractionAsync(x => x.RespondWithModal(modal, options));
protected override Task RespondWithModalAsync(Modal modal, RequestOptions options = null)
=> HandleInteractionAsync(x => x.RespondWithModal(modal, options));
/// <summary>
/// Responds to the interaction with a modal.
@@ -84,10 +84,10 @@ namespace Discord.Interactions
/// A Task representing the operation of creating the interaction response.
/// </returns>
/// <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)
=> await HandleInteractionAsync(x => x.RespondWithModal<TModal>(customId, options, modifyModal));
protected override Task RespondWithModalAsync<TModal>(string customId, RequestOptions options = null, Action<ModalBuilder> modifyModal = null)
=> 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)
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);
if (Context is IRestInteractionContext restContext && restContext.InteractionResponseCallback != null)
await restContext.InteractionResponseCallback.Invoke(payload).ConfigureAwait(false);
return restContext.InteractionResponseCallback.Invoke(payload);
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);
}
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();
func(args);
@@ -40,7 +40,7 @@ namespace Discord.Rest
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}");
return await client.ApiClient.ModifyCurrentBotApplicationAsync(new()
return client.ApiClient.ModifyCurrentBotApplicationAsync(new()
{
Description = args.Description,
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
{
#region General
public static async Task DeleteAsync(IChannel channel, BaseDiscordClient client,
RequestOptions options)
{
await client.ApiClient.DeleteChannelAsync(channel.Id, options).ConfigureAwait(false);
}
public static async Task<Model> ModifyAsync(IGuildChannel channel, BaseDiscordClient client,
public static Task DeleteAsync(IChannel channel, BaseDiscordClient client, RequestOptions options)
=> client.ApiClient.DeleteChannelAsync(channel.Id, options);
public static Task<Model> ModifyAsync(IGuildChannel channel, BaseDiscordClient client,
Action<GuildChannelProperties> func,
RequestOptions options)
{
@@ -40,9 +38,10 @@ namespace Discord.Rest
: Optional.Create<API.Overwrite[]>(),
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,
RequestOptions options)
{
@@ -67,9 +66,10 @@ namespace Discord.Rest
: Optional.Create<API.Overwrite[]>(),
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,
RequestOptions options)
{
@@ -95,10 +95,10 @@ namespace Discord.Rest
SlowModeInterval = args.SlowModeInterval,
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)
{
var args = new StageInstanceProperties();
@@ -110,7 +110,7 @@ namespace Discord.Rest
Topic = args.Topic
};
return await client.ApiClient.ModifyStageInstanceAsync(channel.Id, apiArgs, options);
return client.ApiClient.ModifyStageInstanceAsync(channel.Id, apiArgs, options);
}
#endregion
@@ -492,28 +492,27 @@ namespace Discord.Rest
#endregion
#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)
{
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)
{
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)
{
await client.ApiClient.DeleteChannelPermissionAsync(channel.Id, user.Id, options).ConfigureAwait(false);
}
public static async Task RemovePermissionOverwriteAsync(IGuildChannel channel, BaseDiscordClient client,
=> client.ApiClient.DeleteChannelPermissionAsync(channel.Id, user.Id, options);
public static Task RemovePermissionOverwriteAsync(IGuildChannel channel, BaseDiscordClient client,
IRole role, RequestOptions options)
{
await client.ApiClient.DeleteChannelPermissionAsync(channel.Id, role.Id, options).ConfigureAwait(false);
}
=> client.ApiClient.DeleteChannelPermissionAsync(channel.Id, role.Id, options);
#endregion
#region Users
@@ -564,11 +563,9 @@ namespace Discord.Rest
#endregion
#region Typing
public static async Task TriggerTypingAsync(IMessageChannel channel, BaseDiscordClient client,
RequestOptions options = null)
{
await client.ApiClient.TriggerTypingIndicatorAsync(channel.Id, options).ConfigureAwait(false);
}
public static Task TriggerTypingAsync(IMessageChannel channel, BaseDiscordClient client, RequestOptions options = null)
=> client.ApiClient.TriggerTypingIndicatorAsync(channel.Id, options);
public static IDisposable EnterTypingState(IMessageChannel channel, BaseDiscordClient client,
RequestOptions options)
=> new TypingNotifier(channel, options);

View File

@@ -8,7 +8,7 @@ namespace Discord.Rest;
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,
RequestOptions options)
{
@@ -59,6 +59,6 @@ internal static class ForumHelper
: Optional<ModifyForumReactionEmojiParams>.Unspecified,
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)
=> GetPermissionOverwrite(user);
/// <inheritdoc />
async Task IGuildChannel.AddPermissionOverwriteAsync(IRole role, OverwritePermissions permissions, RequestOptions options)
=> await AddPermissionOverwriteAsync(role, permissions, options).ConfigureAwait(false);
Task IGuildChannel.AddPermissionOverwriteAsync(IRole role, OverwritePermissions permissions, RequestOptions options)
=> AddPermissionOverwriteAsync(role, permissions, options);
/// <inheritdoc />
async Task IGuildChannel.AddPermissionOverwriteAsync(IUser user, OverwritePermissions permissions, RequestOptions options)
=> await AddPermissionOverwriteAsync(user, permissions, options).ConfigureAwait(false);
Task IGuildChannel.AddPermissionOverwriteAsync(IUser user, OverwritePermissions permissions, RequestOptions options)
=> AddPermissionOverwriteAsync(user, permissions, options);
/// <inheritdoc />
async Task IGuildChannel.RemovePermissionOverwriteAsync(IRole role, RequestOptions options)
=> await RemovePermissionOverwriteAsync(role, options).ConfigureAwait(false);
Task IGuildChannel.RemovePermissionOverwriteAsync(IRole role, RequestOptions options)
=> RemovePermissionOverwriteAsync(role, options);
/// <inheritdoc />
async Task IGuildChannel.RemovePermissionOverwriteAsync(IUser user, RequestOptions options)
=> await RemovePermissionOverwriteAsync(user, options).ConfigureAwait(false);
Task IGuildChannel.RemovePermissionOverwriteAsync(IUser user, RequestOptions options)
=> RemovePermissionOverwriteAsync(user, options);
/// <inheritdoc />
IAsyncEnumerable<IReadOnlyCollection<IGuildUser>> IGuildChannel.GetUsersAsync(CacheMode mode, RequestOptions options)

View File

@@ -11,7 +11,7 @@ namespace Discord.Rest
{
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)
{
if (channel is INewsChannel && type != ThreadType.NewsThread)
@@ -26,17 +26,13 @@ namespace Discord.Rest
Ratelimit = slowmode.HasValue ? slowmode.Value : Optional<int?>.Unspecified,
};
Model model;
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
model = await client.ApiClient.StartThreadAsync(channel.Id, args, options).ConfigureAwait(false);
return model;
return client.ApiClient.StartThreadAsync(channel.Id, args, options);
}
public static async Task<Model> ModifyAsync(IThreadChannel channel, BaseDiscordClient client,
public static Task<Model> ModifyAsync(IThreadChannel channel, BaseDiscordClient client,
Action<ThreadChannelProperties> func,
RequestOptions options)
{
@@ -55,7 +51,7 @@ namespace Discord.Rest
AppliedTags = args.AppliedTags,
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)

View File

@@ -20,7 +20,7 @@ namespace Discord.Rest
{
#region General
/// <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)
{
if (func == null)
@@ -91,10 +91,11 @@ namespace Discord.Rest
else if (args.PreferredCulture.IsSpecified)
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>
public static async Task<WidgetModel> ModifyWidgetAsync(IGuild guild, BaseDiscordClient client,
public static Task<WidgetModel> ModifyWidgetAsync(IGuild guild, BaseDiscordClient client,
Action<GuildWidgetProperties> func, RequestOptions options)
{
if (func == null)
@@ -112,30 +113,29 @@ namespace Discord.Rest
else if (args.ChannelId.IsSpecified)
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)
{
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)
{
var apiArgs = args.Select(x => new API.Rest.ModifyGuildRolesParams(x.Id, x.Position));
return await client.ApiClient.ModifyGuildRolesAsync(guild.Id, apiArgs, options).ConfigureAwait(false);
}
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);
return client.ApiClient.ModifyGuildRolesAsync(guild.Id, apiArgs, options);
}
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)
{
var tierFactor = guild.PremiumTier switch
@@ -223,17 +223,15 @@ namespace Discord.Rest
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)
{
var args = new CreateGuildBanParams { DeleteMessageDays = pruneDays, Reason = reason };
await client.ApiClient.CreateGuildBanAsync(guild.Id, userId, args, options).ConfigureAwait(false);
}
public static async Task RemoveBanAsync(IGuild guild, BaseDiscordClient client,
ulong userId, RequestOptions options)
{
await client.ApiClient.RemoveGuildBanAsync(guild.Id, userId, options).ConfigureAwait(false);
return client.ApiClient.CreateGuildBanAsync(guild.Id, userId, args, options);
}
public static Task RemoveBanAsync(IGuild guild, BaseDiscordClient client, ulong userId, RequestOptions options)
=> client.ApiClient.RemoveGuildBanAsync(guild.Id, userId, options);
#endregion
#region Channels
@@ -506,9 +504,9 @@ namespace Discord.Rest
var models = await client.ApiClient.GetIntegrationsAsync(guild.Id, options).ConfigureAwait(false);
return models.Select(x => RestIntegration.Create(client, guild, x)).ToImmutableArray();
}
public static async Task DeleteIntegrationAsync(IGuild guild, BaseDiscordClient client, ulong id,
RequestOptions options) =>
await client.ApiClient.DeleteIntegrationAsync(guild.Id, id, options).ConfigureAwait(false);
public static Task DeleteIntegrationAsync(IGuild guild, BaseDiscordClient client, ulong id, RequestOptions options)
=> client.ApiClient.DeleteIntegrationAsync(guild.Id, id, options);
#endregion
#region Interactions
@@ -611,7 +609,7 @@ namespace Discord.Rest
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)
{
var args = new AddGuildUserProperties();
@@ -635,7 +633,7 @@ namespace Discord.Rest
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,
@@ -646,11 +644,9 @@ namespace Discord.Rest
return RestGuildUser.Create(client, guild, model);
return null;
}
public static async Task<RestGuildUser> GetCurrentUserAsync(IGuild guild, BaseDiscordClient client,
RequestOptions options)
{
return await GetUserAsync(guild, client, client.CurrentUser.Id, options).ConfigureAwait(false);
}
public static Task<RestGuildUser> GetCurrentUserAsync(IGuild guild, BaseDiscordClient client, RequestOptions options)
=> GetUserAsync(guild, client, client.CurrentUser.Id, options);
public static IAsyncEnumerable<IReadOnlyCollection<RestGuildUser>> GetUsersAsync(IGuild guild, BaseDiscordClient client,
ulong? fromUserId, int? limit, RequestOptions options)
{
@@ -833,7 +829,7 @@ namespace Discord.Rest
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)
{
Preconditions.NotNull(name, nameof(name));
@@ -865,10 +861,10 @@ namespace Discord.Rest
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)
{
if (func == null)
@@ -886,11 +882,11 @@ namespace Discord.Rest
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)
=> await client.ApiClient.DeleteStickerAsync(guildId, sticker.Id, options).ConfigureAwait(false);
public static Task DeleteStickerAsync(BaseDiscordClient client, ulong guildId, ISticker sticker, RequestOptions options = null)
=> client.ApiClient.DeleteStickerAsync(guildId, sticker.Id, options);
#endregion
#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)
{
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)
@@ -1123,10 +1119,8 @@ namespace Discord.Rest
return RestGuildEvent.Create(client, guild, client.CurrentUser, model);
}
public static async Task DeleteEventAsync(BaseDiscordClient client, IGuildScheduledEvent guildEvent, RequestOptions options = null)
{
await client.ApiClient.DeleteGuildScheduledEventAsync(guildEvent.Id, guildEvent.Guild.Id, options).ConfigureAwait(false);
}
public static Task DeleteEventAsync(BaseDiscordClient client, IGuildScheduledEvent guildEvent, RequestOptions options = null)
=> client.ApiClient.DeleteGuildScheduledEventAsync(guildEvent.Id, guildEvent.Guild.Id, options);
#endregion
@@ -1180,7 +1174,7 @@ namespace Discord.Rest
#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();
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)
=> await client.ApiClient.GetGuildAutoModRuleAsync(guild.Id, ruleId, options);
public static Task<AutoModerationRule> GetAutoModRuleAsync(ulong ruleId, IGuild guild, BaseDiscordClient client, RequestOptions options)
=> client.ApiClient.GetGuildAutoModRuleAsync(guild.Id, ruleId, options);
public static async Task<AutoModerationRule[]> GetAutoModRulesAsync(IGuild guild, BaseDiscordClient client, RequestOptions options)
=> await client.ApiClient.GetGuildAutoModRulesAsync(guild.Id, options);
public static Task<AutoModerationRule[]> GetAutoModRulesAsync(IGuild guild, BaseDiscordClient client, RequestOptions options)
=> client.ApiClient.GetGuildAutoModRulesAsync(guild.Id, options);
public static Task<AutoModerationRule> ModifyRuleAsync(BaseDiscordClient client, IAutoModRule rule, Action<AutoModRuleProperties> func, RequestOptions options)
{
@@ -1354,10 +1348,10 @@ namespace Discord.Rest
#region Onboarding
public static async Task<GuildOnboarding> GetGuildOnboardingAsync(IGuild guild, BaseDiscordClient client, RequestOptions options)
=> await client.ApiClient.GetGuildOnboardingAsync(guild.Id, options);
public static Task<GuildOnboarding> GetGuildOnboardingAsync(IGuild guild, BaseDiscordClient client, RequestOptions 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();
func(props);
@@ -1394,7 +1388,7 @@ namespace Discord.Rest
: Optional<GuildOnboardingPromptParams[]>.Unspecified,
};
return await client.ApiClient.ModifyGuildOnboardingAsync(guild.Id, args, options);
return client.ApiClient.ModifyGuildOnboardingAsync(guild.Id, args, options);
}
#endregion

View File

@@ -296,10 +296,10 @@ namespace Discord.Rest
/// <inheritdoc />
/// <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();
await GuildHelper.ReorderChannelsAsync(this, Discord, arr, options).ConfigureAwait(false);
return GuildHelper.ReorderChannelsAsync(this, Discord, arr, options);
}
/// <inheritdoc />
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
/// within the server's widget settings; <see langword="null"/> if none is set.
/// </returns>
public async Task<RestGuildChannel> GetWidgetChannelAsync(RequestOptions options = null)
public Task<RestGuildChannel> GetWidgetChannelAsync(RequestOptions options = null)
{
var widgetChannelId = WidgetChannelId;
if (widgetChannelId.HasValue)
return await GuildHelper.GetChannelAsync(this, Discord, widgetChannelId.Value, options).ConfigureAwait(false);
return null;
return GuildHelper.GetChannelAsync(this, Discord, widgetChannelId.Value, options);
return Task.FromResult<RestGuildChannel>(null);
}
/// <summary>
@@ -1053,8 +1053,9 @@ namespace Discord.Rest
/// A task that represents the asynchronous get operation. The task result contains a read-only collection
/// of application commands found within the guild.
/// </returns>
public async Task<IReadOnlyCollection<RestGuildCommand>> GetApplicationCommandsAsync(bool withLocalizations = false, string locale = null, RequestOptions options = null)
=> await ClientHelper.GetGuildApplicationCommandsAsync(Discord, Id, withLocalizations, locale, options).ConfigureAwait(false);
public Task<IReadOnlyCollection<RestGuildCommand>> GetApplicationCommandsAsync(bool withLocalizations = false, string locale = null, RequestOptions options = null)
=> ClientHelper.GetGuildApplicationCommandsAsync(Discord, Id, withLocalizations, locale, options);
/// <summary>
/// Gets an application command within this guild with the specified id.
/// </summary>
@@ -1064,8 +1065,9 @@ namespace Discord.Rest
/// A ValueTask that represents the asynchronous get operation. The task result contains a <see cref="IApplicationCommand"/>
/// if found, otherwise <see langword="null"/>.
/// </returns>
public async Task<RestGuildCommand> GetApplicationCommandAsync(ulong id, RequestOptions options = null)
=> await ClientHelper.GetGuildApplicationCommandAsync(Discord, id, Id, options);
public Task<RestGuildCommand> GetApplicationCommandAsync(ulong id, RequestOptions options = null)
=> ClientHelper.GetGuildApplicationCommandAsync(Discord, id, Id, options);
/// <summary>
/// Creates an application command within this guild.
/// </summary>
@@ -1168,6 +1170,7 @@ namespace Discord.Rest
using var fs = File.OpenRead(path);
return await CreateStickerAsync(name, fs, Path.GetFileName(fs.Name), tags, description,options);
}
/// <summary>
/// Creates a new sticker in this guild
/// </summary>
@@ -1587,8 +1590,8 @@ namespace Discord.Rest
async Task<IReadOnlyCollection<IIntegration>> IGuild.GetIntegrationsAsync(RequestOptions options)
=> await GetIntegrationsAsync(options).ConfigureAwait(false);
/// <inheritdoc />
async Task IGuild.DeleteIntegrationAsync(ulong id, RequestOptions options)
=> await DeleteIntegrationAsync(id, options).ConfigureAwait(false);
Task IGuild.DeleteIntegrationAsync(ulong id, RequestOptions options)
=> DeleteIntegrationAsync(id, options);
/// <inheritdoc />
async Task<IReadOnlyCollection<IInviteMetadata>> IGuild.GetInvitesAsync(RequestOptions options)
@@ -1616,7 +1619,8 @@ namespace Discord.Rest
/// </summary>
/// <param name="user">The user to disconnect.</param>
/// <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 />
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;
}
public async Task LeaveAsync(RequestOptions options = null)
{
await Discord.ApiClient.LeaveGuildAsync(Id, options).ConfigureAwait(false);
}
public Task LeaveAsync(RequestOptions options = null)
=> Discord.ApiClient.LeaveGuildAsync(Id, options);
public async Task<RestGuildUser> GetCurrentUserGuildMemberAsync(RequestOptions options = null)
{
@@ -64,10 +62,8 @@ namespace Discord.Rest
}
/// <inheritdoc />
public async Task DeleteAsync(RequestOptions options = null)
{
await Discord.ApiClient.DeleteGuildAsync(Id, options).ConfigureAwait(false);
}
public Task DeleteAsync(RequestOptions options = null)
=> Discord.ApiClient.DeleteGuildAsync(Id, options);
public override string ToString() => Name;
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;
}
public async Task DeleteAsync()
{
await Discord.ApiClient.DeleteIntegrationAsync(GuildId, Id).ConfigureAwait(false);
}
public Task DeleteAsync()
=> Discord.ApiClient.DeleteIntegrationAsync(GuildId, Id);
public override string ToString() => Name;
private string DebuggerDisplay => $"{Name} ({Id}{(IsEnabled ? ", Enabled" : "")})";

View File

@@ -138,7 +138,7 @@ namespace Discord.Rest
}
/// <inheritdoc/>
public override async Task<RestFollowupMessage> FollowupAsync(
public override Task<RestFollowupMessage> FollowupAsync(
string text = null,
Embed[] embeds = null,
bool isTTS = false,
@@ -171,7 +171,7 @@ namespace Discord.Rest
if (ephemeral)
args.Flags = MessageFlags.Ephemeral;
return await InteractionHelper.SendFollowupAsync(Discord, args, Token, Channel, options);
return InteractionHelper.SendFollowupAsync(Discord, args, Token, Channel, options);
}
/// <inheritdoc/>
@@ -235,7 +235,7 @@ namespace Discord.Rest
}
/// <inheritdoc/>
public override async Task<RestFollowupMessage> FollowupWithFilesAsync(
public override Task<RestFollowupMessage> FollowupWithFilesAsync(
IEnumerable<FileAttachment> attachments,
string text = null,
Embed[] embeds = null,
@@ -284,7 +284,7 @@ namespace Discord.Rest
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 };
return await InteractionHelper.SendFollowupAsync(Discord, args, Token, Channel, options).ConfigureAwait(false);
return InteractionHelper.SendFollowupAsync(Discord, args, Token, Channel, options);
}
/// <summary>

View File

@@ -34,14 +34,15 @@ namespace Discord.Rest
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;
if (model.Resolved.IsSpecified && ResolvableData == null)
{
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

View File

@@ -35,17 +35,13 @@ namespace Discord.Rest
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)
{
await client.ApiClient.CreateInteractionResponseAsync(response, interaction.Id, interaction.Token, options).ConfigureAwait(false);
}
=> client.ApiClient.CreateInteractionResponseAsync(response, interaction.Id, interaction.Token, options);
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)
{
await client.ApiClient.CreateInteractionResponseAsync(response, interaction.Id, interaction.Token, options).ConfigureAwait(false);
}
=> client.ApiClient.CreateInteractionResponseAsync(response, interaction.Id, interaction.Token, options);
public static async Task<RestInteractionMessage> GetOriginalResponseAsync(BaseDiscordClient client, IMessageChannel channel,
IDiscordInteraction interaction, RequestOptions options = null)
@@ -90,7 +86,8 @@ namespace Discord.Rest
func((TArg)args);
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)
{
Preconditions.NotNullOrEmpty(arg.Name, nameof(arg.Name));
@@ -122,10 +119,10 @@ namespace Discord.Rest
: 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)
{
Preconditions.NotNull(args, nameof(args));
@@ -166,7 +163,7 @@ namespace Discord.Rest
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,
@@ -239,7 +236,7 @@ namespace Discord.Rest
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)
{
if (args.Name.IsSpecified)
@@ -281,15 +278,15 @@ namespace Discord.Rest
: 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.NotEqual(command.Id, 0, nameof(command.Id));
await client.ApiClient.DeleteGlobalApplicationCommandAsync(command.Id, options).ConfigureAwait(false);
return client.ApiClient.DeleteGlobalApplicationCommandAsync(command.Id, options);
}
#endregion
@@ -302,7 +299,7 @@ namespace Discord.Rest
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)
{
var model = new CreateApplicationCommandParams
@@ -332,7 +329,7 @@ namespace Discord.Rest
: 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,
@@ -343,7 +340,7 @@ namespace Discord.Rest
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)
{
var model = new ModifyApplicationCommandParams
@@ -369,15 +366,15 @@ namespace Discord.Rest
: 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.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)
@@ -389,7 +386,7 @@ namespace Discord.Rest
#endregion
#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)
{
var args = new MessageProperties();
@@ -429,11 +426,13 @@ namespace Discord.Rest
: 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 async Task<API.Message> ModifyInteractionResponseAsync(BaseDiscordClient client, string token, Action<MessageProperties> func,
public static Task DeleteFollowupMessageAsync(BaseDiscordClient client, RestFollowupMessage message, RequestOptions options = null)
=> client.ApiClient.DeleteInteractionFollowupMessageAsync(message.Id, message.Token, options);
public static Task<API.Message> ModifyInteractionResponseAsync(BaseDiscordClient client, string token, Action<MessageProperties> func,
RequestOptions options = null)
{
var args = new MessageProperties();
@@ -476,7 +475,7 @@ namespace Discord.Rest
Flags = args.Flags
};
return await client.ApiClient.ModifyInteractionResponseAsync(apiArgs, token, options).ConfigureAwait(false);
return client.ApiClient.ModifyInteractionResponseAsync(apiArgs, token, options);
}
else
{
@@ -492,15 +491,15 @@ namespace Discord.Rest
: 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)
=> await client.ApiClient.DeleteInteractionResponseAsync(message.Token, options);
public static Task DeleteInteractionResponseAsync(BaseDiscordClient client, RestInteractionMessage message, RequestOptions options = null)
=> client.ApiClient.DeleteInteractionResponseAsync(message.Token, options);
public static async Task DeleteInteractionResponseAsync(BaseDiscordClient client, IDiscordInteraction interaction, RequestOptions options = null)
=> await client.ApiClient.DeleteInteractionResponseAsync(interaction.Token, options);
public static Task DeleteInteractionResponseAsync(BaseDiscordClient client, IDiscordInteraction interaction, RequestOptions options = null)
=> client.ApiClient.DeleteInteractionResponseAsync(interaction.Token, options);
public static Task SendAutocompleteResultAsync(BaseDiscordClient client, IEnumerable<AutocompleteResult> result, ulong interactionId,
string interactionToken, RequestOptions options)
@@ -523,10 +522,10 @@ namespace Discord.Rest
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)
{
await client.ApiClient.CreateInteractionResponseAsync(new InteractionResponse
return client.ApiClient.CreateInteractionResponseAsync(new InteractionResponse
{
Type = InteractionResponseType.PremiumRequired,
Data = Optional<InteractionCallbackData>.Unspecified

View File

@@ -243,7 +243,7 @@ namespace Discord.Rest
}
/// <inheritdoc/>
public override async Task<RestFollowupMessage> FollowupAsync(
public override Task<RestFollowupMessage> FollowupAsync(
string text = null,
Embed[] embeds = null,
bool isTTS = false,
@@ -276,7 +276,7 @@ namespace Discord.Rest
if (ephemeral)
args.Flags = MessageFlags.Ephemeral;
return await InteractionHelper.SendFollowupAsync(Discord, args, Token, Channel, options);
return InteractionHelper.SendFollowupAsync(Discord, args, Token, Channel, options);
}
/// <inheritdoc/>
@@ -340,7 +340,7 @@ namespace Discord.Rest
}
/// <inheritdoc/>
public override async Task<RestFollowupMessage> FollowupWithFilesAsync(
public override Task<RestFollowupMessage> FollowupWithFilesAsync(
IEnumerable<FileAttachment> attachments,
string text = null,
Embed[] embeds = null,
@@ -389,7 +389,7 @@ namespace Discord.Rest
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 };
return await InteractionHelper.SendFollowupAsync(Discord, args, Token, Channel, options).ConfigureAwait(false);
return InteractionHelper.SendFollowupAsync(Discord, args, Token, Channel, options);
}
/// <summary>

View File

@@ -128,7 +128,7 @@ namespace Discord.Rest
/// <returns>
/// The sent message.
/// </returns>
public override async Task<RestFollowupMessage> FollowupAsync(
public override Task<RestFollowupMessage> FollowupAsync(
string text = null,
Embed[] embeds = null,
bool isTTS = false,
@@ -161,7 +161,7 @@ namespace Discord.Rest
if (ephemeral)
args.Flags = MessageFlags.Ephemeral;
return await InteractionHelper.SendFollowupAsync(Discord, args, Token, Channel, options);
return InteractionHelper.SendFollowupAsync(Discord, args, Token, Channel, options);
}
/// <summary>
@@ -180,7 +180,7 @@ namespace Discord.Rest
/// <returns>
/// The sent message.
/// </returns>
public override async Task<RestFollowupMessage> FollowupWithFileAsync(
public override Task<RestFollowupMessage> FollowupWithFileAsync(
Stream fileStream,
string fileName,
string text = null,
@@ -218,7 +218,7 @@ namespace Discord.Rest
if (ephemeral)
args.Flags = MessageFlags.Ephemeral;
return await InteractionHelper.SendFollowupAsync(Discord, args, Token, Channel, options);
return InteractionHelper.SendFollowupAsync(Discord, args, Token, Channel, options);
}
/// <summary>
@@ -368,7 +368,7 @@ namespace Discord.Rest
}
/// <inheritdoc/>
public override async Task<RestFollowupMessage> FollowupWithFilesAsync(
public override Task<RestFollowupMessage> FollowupWithFilesAsync(
IEnumerable<FileAttachment> attachments,
string text = null,
Embed[] embeds = null,
@@ -417,7 +417,7 @@ namespace Discord.Rest
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 };
return await InteractionHelper.SendFollowupAsync(Discord, args, Token, Channel, options).ConfigureAwait(false);
return InteractionHelper.SendFollowupAsync(Discord, args, Token, Channel, options);
}
/// <inheritdoc/>

View File

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

View File

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

View File

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

View File

@@ -29,7 +29,7 @@ namespace Discord.Rest
RequestOptions 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)
{
var args = new MessageProperties();
@@ -95,7 +95,7 @@ namespace Discord.Rest
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,
};
return await client.ApiClient.ModifyMessageAsync(channelId, msgId, apiArgs, options).ConfigureAwait(false);
return client.ApiClient.ModifyMessageAsync(channelId, msgId, apiArgs, options);
}
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
};
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)
=> DeleteAsync(msg.Channel.Id, msg.Id, client, options);
public static async Task DeleteAsync(ulong channelId, ulong msgId, BaseDiscordClient client,
RequestOptions options)
{
await client.ApiClient.DeleteMessageAsync(channelId, msgId, options).ConfigureAwait(false);
}
public static Task DeleteAsync(ulong channelId, ulong msgId, BaseDiscordClient client, RequestOptions options)
=> client.ApiClient.DeleteMessageAsync(channelId, msgId, options);
public static async Task AddReactionAsync(ulong channelId, ulong messageId, IEmote emote, BaseDiscordClient client, RequestOptions options)
{
await client.ApiClient.AddReactionAsync(channelId, messageId, emote is Emote e ? $"{e.Name}:{e.Id}" : UrlEncode(emote.Name), options).ConfigureAwait(false);
}
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);
public static async Task AddReactionAsync(IMessage msg, IEmote emote, BaseDiscordClient client, RequestOptions 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 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);
public static async Task RemoveReactionAsync(ulong channelId, ulong messageId, ulong userId, IEmote emote, BaseDiscordClient client, RequestOptions options)
{
await client.ApiClient.RemoveReactionAsync(channelId, messageId, userId, emote is Emote e ? $"{e.Name}:{e.Id}" : UrlEncode(emote.Name), options).ConfigureAwait(false);
}
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);
public static async Task RemoveReactionAsync(IMessage msg, ulong userId, IEmote emote, BaseDiscordClient client, RequestOptions 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 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);
public static async Task RemoveAllReactionsAsync(ulong channelId, ulong messageId, BaseDiscordClient client, RequestOptions options)
{
await client.ApiClient.RemoveAllReactionsAsync(channelId, messageId, options).ConfigureAwait(false);
}
public static Task RemoveAllReactionsAsync(ulong channelId, ulong messageId, BaseDiscordClient client, RequestOptions options)
=> client.ApiClient.RemoveAllReactionsAsync(channelId, messageId, options);
public static async Task RemoveAllReactionsAsync(IMessage msg, BaseDiscordClient client, RequestOptions options)
{
await client.ApiClient.RemoveAllReactionsAsync(msg.Channel.Id, msg.Id, options).ConfigureAwait(false);
}
public static Task RemoveAllReactionsAsync(IMessage msg, BaseDiscordClient client, RequestOptions options)
=> client.ApiClient.RemoveAllReactionsAsync(msg.Channel.Id, msg.Id, options);
public static async Task RemoveAllReactionsForEmoteAsync(ulong channelId, ulong messageId, IEmote emote, BaseDiscordClient client, RequestOptions options)
{
await client.ApiClient.RemoveAllReactionsForEmoteAsync(channelId, messageId, emote is Emote e ? $"{e.Name}:{e.Id}" : UrlEncode(emote.Name), options).ConfigureAwait(false);
}
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);
public static async Task RemoveAllReactionsForEmoteAsync(IMessage msg, IEmote emote, BaseDiscordClient client, RequestOptions 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 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);
public static IAsyncEnumerable<IReadOnlyCollection<IUser>> GetReactionUsersAsync(IMessage msg, IEmote emote,
int? limit, BaseDiscordClient client, ReactionType reactionType, RequestOptions options)
@@ -211,19 +192,15 @@ namespace Discord.Rest
return newContent;
}
public static async Task PinAsync(IMessage msg, BaseDiscordClient client,
RequestOptions options)
public static Task PinAsync(IMessage msg, BaseDiscordClient client, RequestOptions options)
{
if (msg.Channel is IVoiceChannel)
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,
RequestOptions options)
{
await client.ApiClient.RemovePinAsync(msg.Channel.Id, msg.Id, options).ConfigureAwait(false);
}
public static Task UnpinAsync(IMessage msg, BaseDiscordClient client, RequestOptions options)
=> client.ApiClient.RemovePinAsync(msg.Channel.Id, msg.Id, options);
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)
=> CrosspostAsync(msg.Channel.Id, msg.Id, client, options);
public static async Task CrosspostAsync(ulong channelId, ulong msgId, BaseDiscordClient client,
RequestOptions options)
{
await client.ApiClient.CrosspostAsync(channelId, msgId, options).ConfigureAwait(false);
}
public static Task CrosspostAsync(ulong channelId, ulong msgId, BaseDiscordClient client, RequestOptions options)
=> client.ApiClient.CrosspostAsync(channelId, msgId, options);
public static IUser GetAuthor(BaseDiscordClient client, IGuild guild, UserModel model, ulong? webhookId)
{

View File

@@ -188,14 +188,14 @@ namespace Discord.Rest
/// <inheritdoc />
/// <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))
{
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" : "")})";

View File

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

View File

@@ -10,8 +10,7 @@ namespace Discord.Rest
{
internal static class UserHelper
{
public static async Task<Model> ModifyAsync(ISelfUser user, BaseDiscordClient client, Action<SelfUserProperties> func,
RequestOptions options)
public static Task<Model> ModifyAsync(ISelfUser user, BaseDiscordClient client, Action<SelfUserProperties> func, RequestOptions options)
{
var args = new SelfUserProperties();
func(args);
@@ -24,7 +23,7 @@ namespace Discord.Rest
if (!apiArgs.Avatar.IsSpecified && user.AvatarId != null)
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,
RequestOptions options)
@@ -66,11 +65,8 @@ namespace Discord.Rest
return args;
}
public static async Task KickAsync(IGuildUser user, BaseDiscordClient client,
string reason, RequestOptions options)
{
await client.ApiClient.RemoveGuildMemberAsync(user.GuildId, user.Id, reason, options).ConfigureAwait(false);
}
public static Task KickAsync(IGuildUser user, BaseDiscordClient client, string reason, RequestOptions options)
=> client.ApiClient.RemoveGuildMemberAsync(user.GuildId, user.Id, reason, options);
public static async Task<RestDMChannel> CreateDMChannelAsync(IUser user, BaseDiscordClient client,
RequestOptions options)
@@ -91,7 +87,7 @@ namespace Discord.Rest
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.
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)
};
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()
{
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
{
public static async Task<Model> ModifyAsync(IWebhook webhook, BaseDiscordClient client,
public static Task<Model> ModifyAsync(IWebhook webhook, BaseDiscordClient client,
Action<WebhookProperties> func, RequestOptions options)
{
var args = new WebhookProperties();
@@ -27,11 +27,10 @@ namespace Discord.Rest
else if (args.ChannelId.IsSpecified)
apiArgs.ChannelId = args.ChannelId.Value;
return await client.ApiClient.ModifyWebhookAsync(webhook.Id, apiArgs, options).ConfigureAwait(false);
}
public static async Task DeleteAsync(IWebhook webhook, BaseDiscordClient client, RequestOptions options)
{
await client.ApiClient.DeleteWebhookAsync(webhook.Id, options).ConfigureAwait(false);
return client.ApiClient.ModifyWebhookAsync(webhook.Id, apiArgs, options);
}
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>
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)
{
string uri = Path.Combine(_baseUrl, endpoint);
@@ -162,7 +162,7 @@ namespace Discord.Net.Rest
}
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)

View File

@@ -99,7 +99,7 @@ namespace Discord.Net.Queue
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);
if (millis > 0)
@@ -107,19 +107,23 @@ namespace Discord.Net.Queue
#if DEBUG_LIMITS
Debug.WriteLine($"[{id}] Sleeping {millis} ms (Pre-emptive) [Global]");
#endif
await Task.Delay(millis).ConfigureAwait(false);
return Task.Delay(millis);
}
return Task.CompletedTask;
}
internal void PauseGlobal(RateLimitInfo info)
{
_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
var requestBucket = GatewayBucket.Get(request.Options.BucketId);
if (requestBucket.Type == GatewayBucketType.Unbucketed)
return;
return Task.CompletedTask;
//It's not a global request, so need to remove one from global (per-session)
var globalBucketType = GatewayBucket.Get(GatewayBucketType.Unbucketed);
@@ -127,7 +131,7 @@ namespace Discord.Net.Queue
options.BucketId = globalBucketType.Id;
var globalRequest = new WebSocketRequest(null, null, false, false, options);
var globalBucket = GetOrCreateBucket(options, globalRequest);
await globalBucket.TriggerAsync(id, globalRequest);
return globalBucket.TriggerAsync(id, globalRequest);
}
private RequestBucket GetOrCreateBucket(RequestOptions options, IRequest request)
@@ -141,10 +145,9 @@ namespace Discord.Net.Queue
}
return (RequestBucket)obj;
}
internal async Task RaiseRateLimitTriggered(BucketId bucketId, RateLimitInfo? info, string endpoint)
{
await RateLimitTriggered(bucketId, info, endpoint).ConfigureAwait(false);
}
internal Task RaiseRateLimitTriggered(BucketId bucketId, RateLimitInfo? info, string endpoint)
=> RateLimitTriggered(bucketId, info, endpoint);
internal (RequestBucket, BucketId) UpdateBucketHash(BucketId id, string discordHash)
{
if (!id.IsHashBucket)

View File

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

View File

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

View File

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

View File

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

View File

@@ -95,13 +95,13 @@ namespace Discord.Audio
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;
_userId = userId;
_sessionId = sessionId;
_token = token;
await _connection.StartAsync().ConfigureAwait(false);
return _connection.StartAsync();
}
public IReadOnlyDictionary<ulong, AudioInStream> GetStreams()
@@ -109,10 +109,8 @@ namespace Discord.Audio
return _streams.ToDictionary(pair => pair.Key, pair => pair.Value.Reader);
}
public async Task StopAsync()
{
await _connection.StopAsync().ConfigureAwait(false);
}
public Task StopAsync()
=> _connection.StopAsync();
private async Task OnConnectingAsync()
{

View File

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

View File

@@ -103,14 +103,11 @@ namespace Discord.Audio.Streams
await base.FlushAsync(cancelToken).ConfigureAwait(false);
}*/
public override async Task FlushAsync(CancellationToken cancelToken)
{
await _next.FlushAsync(cancelToken).ConfigureAwait(false);
}
public override async Task ClearAsync(CancellationToken cancelToken)
{
await _next.ClearAsync(cancelToken).ConfigureAwait(false);
}
public override Task FlushAsync(CancellationToken cancelToken)
=> _next.FlushAsync(cancelToken);
public override Task ClearAsync(CancellationToken cancelToken)
=> _next.ClearAsync(cancelToken);
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 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();
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="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();
@@ -38,7 +38,7 @@ namespace Discord.Audio.Streams
(buffer[offset + 7] << 0));
_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)

View File

@@ -38,7 +38,7 @@ namespace Discord.Audio.Streams
_nextSeq = seq;
_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();
if (!_hasHeader)
@@ -58,17 +58,14 @@ namespace Discord.Audio.Streams
Buffer.BlockCopy(buffer, offset, _buffer, 12, count);
_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)
{
await _next.FlushAsync(cancelToken).ConfigureAwait(false);
}
public override async Task ClearAsync(CancellationToken cancelToken)
{
await _next.ClearAsync(cancelToken).ConfigureAwait(false);
}
public override Task FlushAsync(CancellationToken cancelToken)
=> _next.FlushAsync(cancelToken);
public override Task ClearAsync(CancellationToken cancelToken)
=> _next.ClearAsync(cancelToken);
protected override void Dispose(bool disposing)
{

View File

@@ -24,26 +24,23 @@ namespace Discord.Audio.Streams
_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();
if (_client.SecretKey == null)
return;
return Task.CompletedTask;
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);
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)
{
await _next.FlushAsync(cancelToken).ConfigureAwait(false);
}
public override async Task ClearAsync(CancellationToken cancelToken)
{
await _next.ClearAsync(cancelToken).ConfigureAwait(false);
}
public override Task FlushAsync(CancellationToken cancelToken)
=> _next.FlushAsync(cancelToken);
public override Task ClearAsync(CancellationToken cancelToken)
=> _next.ClearAsync(cancelToken);
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);
}
public override async Task FlushAsync(CancellationToken cancelToken)
{
await _next.FlushAsync(cancelToken).ConfigureAwait(false);
}
public override async Task ClearAsync(CancellationToken cancelToken)
{
await _next.ClearAsync(cancelToken).ConfigureAwait(false);
}
public override Task FlushAsync(CancellationToken cancelToken)
=> _next.FlushAsync(cancelToken);
public override Task ClearAsync(CancellationToken cancelToken)
=> _next.ClearAsync(cancelToken);
protected override void Dispose(bool disposing)
{

View File

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

View File

@@ -110,10 +110,10 @@ namespace Discord.WebSocket
=> new DiscordSocketApiClient(config.RestClientProvider, config.WebSocketProvider, DiscordRestConfig.UserAgent, config.GatewayHost,
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;
await _identifySemaphores[semaphoreIdx].WaitAsync(token).ConfigureAwait(false);
return _identifySemaphores[semaphoreIdx].WaitAsync(token);
}
internal void ReleaseIdentifyLock()
@@ -198,11 +198,12 @@ namespace Discord.WebSocket
}
/// <inheritdoc />
public override async Task StartAsync()
=> await Task.WhenAll(_shards.Select(x => x.StartAsync())).ConfigureAwait(false);
public override Task StartAsync()
=> Task.WhenAll(_shards.Select(x => x.StartAsync()));
/// <inheritdoc />
public override async Task StopAsync()
=> await Task.WhenAll(_shards.Select(x => x.StopAsync())).ConfigureAwait(false);
public override Task StopAsync()
=> Task.WhenAll(_shards.Select(x => x.StopAsync()));
public DiscordSocketClient GetShard(int id)
{
@@ -220,8 +221,8 @@ namespace Discord.WebSocket
=> GetShardFor(guild?.Id ?? 0);
/// <inheritdoc />
public override async Task<RestApplication> GetApplicationInfoAsync(RequestOptions options = null)
=> await _shards[0].GetApplicationInfoAsync(options).ConfigureAwait(false);
public override Task<RestApplication> GetApplicationInfoAsync(RequestOptions options = null)
=> _shards[0].GetApplicationInfoAsync(options);
/// <inheritdoc />
public override SocketGuild GetGuild(ulong id)
@@ -355,16 +356,12 @@ namespace Discord.WebSocket
}
/// <inheritdoc />
public override async ValueTask<IReadOnlyCollection<RestVoiceRegion>> GetVoiceRegionsAsync(RequestOptions options = null)
{
return await _shards[0].GetVoiceRegionsAsync().ConfigureAwait(false);
}
public override ValueTask<IReadOnlyCollection<RestVoiceRegion>> GetVoiceRegionsAsync(RequestOptions options = null)
=> _shards[0].GetVoiceRegionsAsync();
/// <inheritdoc />
public override async ValueTask<RestVoiceRegion> GetVoiceRegionAsync(string id, RequestOptions options = null)
{
return await _shards[0].GetVoiceRegionAsync(id, options).ConfigureAwait(false);
}
public override ValueTask<RestVoiceRegion> GetVoiceRegionAsync(string id, RequestOptions options = null)
=> _shards[0].GetVoiceRegionAsync(id, options);
/// <inheritdoc />
/// <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);
}
/// <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;
if (!string.IsNullOrEmpty(streamUrl))
activity = new StreamingGame(name, streamUrl);
else if (!string.IsNullOrEmpty(name))
activity = new Game(name, type);
await SetActivityAsync(activity).ConfigureAwait(false);
return SetActivityAsync(activity);
}
/// <inheritdoc />
public override async Task SetActivityAsync(IActivity activity)

View File

@@ -317,7 +317,7 @@ namespace Discord.API
#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);
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);
var msg = new ResumeParams()
@@ -361,14 +362,16 @@ namespace Discord.API
SessionId = sessionId,
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);
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);
var args = new PresenceUpdateParams
@@ -379,14 +382,16 @@ namespace Discord.API
Activities = new object[] { game }
};
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);
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
{
@@ -396,17 +401,19 @@ namespace Discord.API
SelfMute = selfMute
};
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);
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);
await SendGatewayAsync(GatewayOpCode.GuildSync, guildIds, options: options).ConfigureAwait(false);
return SendGatewayAsync(GatewayOpCode.GuildSync, guildIds, options: options);
}
#endregion
}

View File

@@ -284,11 +284,12 @@ namespace Discord.WebSocket
}
/// <inheritdoc />
public override async Task StartAsync()
=> await _connection.StartAsync().ConfigureAwait(false);
public override Task StartAsync()
=> _connection.StartAsync();
/// <inheritdoc />
public override async Task StopAsync()
=> await _connection.StopAsync().ConfigureAwait(false);
public override Task StopAsync()
=> _connection.StopAsync();
private async Task OnConnectingAsync()
{
@@ -642,16 +643,18 @@ namespace Discord.WebSocket
}
/// <inheritdoc />
public override async Task DownloadUsersAsync(IEnumerable<IGuild> guilds)
public override Task DownloadUsersAsync(IEnumerable<IGuild> guilds)
{
if (ConnectionState == ConnectionState.Connected)
{
EnsureGatewayIntent(GatewayIntents.GuildMembers);
//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)
{
var cachedGuilds = guilds.ToImmutableArray();
@@ -689,15 +692,16 @@ namespace Discord.WebSocket
/// await client.SetStatusAsync(UserStatus.DoNotDisturb);
/// </code>
/// </example>
public override async Task SetStatusAsync(UserStatus status)
public override Task SetStatusAsync(UserStatus status)
{
Status = status;
if (status == UserStatus.AFK)
_statusSince = DateTimeOffset.UtcNow;
else
_statusSince = null;
await SendStatusAsync().ConfigureAwait(false);
return SendStatusAsync();
}
/// <inheritdoc />
/// <example>
/// <para>
@@ -713,7 +717,7 @@ namespace Discord.WebSocket
/// </code>
/// </para>
/// </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))
Activity = new StreamingGame(name, streamUrl);
@@ -721,27 +725,27 @@ namespace Discord.WebSocket
Activity = new Game(name, type);
else
Activity = null;
await SendStatusAsync().ConfigureAwait(false);
return SendStatusAsync();
}
/// <inheritdoc />
public override async Task SetActivityAsync(IActivity activity)
public override Task SetActivityAsync(IActivity activity)
{
Activity = activity;
await SendStatusAsync().ConfigureAwait(false);
return SendStatusAsync();
}
/// <inheritdoc />
public override async Task SetCustomStatusAsync(string status)
public override Task SetCustomStatusAsync(string status)
{
var statusGame = new CustomStatusGame(status);
await SetActivityAsync(statusGame);
return SetActivityAsync(statusGame);
}
private async Task SendStatusAsync()
private Task SendStatusAsync()
{
if (CurrentUser == null)
return;
return Task.CompletedTask;
var activities = _activity.IsSpecified
? ImmutableList.Create(_activity.Value)
: null;
@@ -749,11 +753,11 @@ namespace Discord.WebSocket
var presence = BuildCurrentStatus() ?? (UserStatus.Online, false, null, null);
await ApiClient.SendPresenceUpdateAsync(
return ApiClient.SendPresenceUpdateAsync(
status: presence.Item1,
isAFK: presence.Item2,
since: presence.Item3,
game: presence.Item4).ConfigureAwait(false);
game: presence.Item4);
}
private (UserStatus, bool, long?, GameModel)? BuildCurrentStatus()
@@ -3268,11 +3272,14 @@ namespace Discord.WebSocket
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();
if (guildIds.Length > 0)
await ApiClient.SendGuildSyncAsync(guildIds).ConfigureAwait(false);
return ApiClient.SendGuildSyncAsync(guildIds);
return Task.CompletedTask;
}
internal SocketGuild AddGuild(ExtendedGuild model, ClientState state)
@@ -3334,83 +3341,106 @@ namespace Discord.WebSocket
internal bool HasGatewayIntent(GatewayIntents intents)
=> _gatewayIntents.HasFlag(intents);
private async Task GuildAvailableAsync(SocketGuild guild)
private Task GuildAvailableAsync(SocketGuild guild)
{
if (!guild.IsConnected)
{
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)
{
guild.IsConnected = false;
await TimedInvokeAsync(_guildUnavailableEvent, nameof(GuildUnavailable), guild).ConfigureAwait(false);
}
return TimedInvokeAsync(_guildUnavailableEvent, nameof(GuildUnavailable), guild);
}
private async Task TimedInvokeAsync(AsyncEvent<Func<Task>> eventHandler, string name)
return Task.CompletedTask;
}
private Task TimedInvokeAsync(AsyncEvent<Func<Task>> eventHandler, string name)
{
if (eventHandler.HasSubscribers)
{
if (HandlerTimeout.HasValue)
await TimeoutWrap(name, eventHandler.InvokeAsync).ConfigureAwait(false);
return TimeoutWrap(name, eventHandler.InvokeAsync);
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 (HandlerTimeout.HasValue)
await TimeoutWrap(name, () => eventHandler.InvokeAsync(arg)).ConfigureAwait(false);
return TimeoutWrap(name, () => eventHandler.InvokeAsync(arg));
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 (HandlerTimeout.HasValue)
await TimeoutWrap(name, () => eventHandler.InvokeAsync(arg1, arg2)).ConfigureAwait(false);
return TimeoutWrap(name, () => eventHandler.InvokeAsync(arg1, arg2));
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 (HandlerTimeout.HasValue)
await TimeoutWrap(name, () => eventHandler.InvokeAsync(arg1, arg2, arg3)).ConfigureAwait(false);
return TimeoutWrap(name, () => eventHandler.InvokeAsync(arg1, arg2, arg3));
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 (HandlerTimeout.HasValue)
await TimeoutWrap(name, () => eventHandler.InvokeAsync(arg1, arg2, arg3, arg4)).ConfigureAwait(false);
return TimeoutWrap(name, () => eventHandler.InvokeAsync(arg1, arg2, arg3, arg4));
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 (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
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)
{
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}";
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}";
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}";
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}";
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}";
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)
{
await UnknownChannelAsync(evnt, channelId).ConfigureAwait(false);
return;
return UnknownChannelAsync(evnt, channelId);
}
string details = $"{evnt} Channel={channelId} Guild={guildId}";
await _gatewayLogger.WarningAsync($"Unknown Channel ({details}).").ConfigureAwait(false);
}
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);
return _gatewayLogger.WarningAsync($"Unknown Channel ({details}).");
}
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}";
await _gatewayLogger.WarningAsync($"Unknown Guild Event ({details}).").ConfigureAwait(false);
string details = $"{evnt} Role={roleId} Guild={guildId}";
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}";
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++;
@@ -3558,11 +3595,12 @@ namespace Discord.WebSocket
=> await BulkOverwriteGlobalApplicationCommandsAsync(properties, options);
/// <inheritdoc />
async Task IDiscordClient.StartAsync()
=> await StartAsync().ConfigureAwait(false);
Task IDiscordClient.StartAsync()
=> StartAsync();
/// <inheritdoc />
async Task IDiscordClient.StopAsync()
=> await StopAsync().ConfigureAwait(false);
Task IDiscordClient.StopAsync()
=> StopAsync();
#endregion
}
}

View File

@@ -55,7 +55,7 @@ namespace Discord.Audio
GuildId = guildId;
_connectionLock = new SemaphoreSlim(1, 1);
_udp = udpSocketProvider();
_udp.ReceivedDatagram += async (data, index, count) =>
_udp.ReceivedDatagram += (data, index, count) =>
{
if (index != 0 || count != data.Length)
{
@@ -63,7 +63,7 @@ namespace Discord.Audio
Buffer.BlockCopy(data, index, newData, 0, count);
data = newData;
}
await _receivedPacketEvent.InvokeAsync(data).ConfigureAwait(false);
return _receivedPacketEvent.InvokeAsync(data);
};
WebSocketClient = webSocketProvider();
@@ -83,10 +83,10 @@ namespace Discord.Audio
}
}
};
WebSocketClient.TextMessage += async text =>
WebSocketClient.TextMessage += 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 =>
{
@@ -129,23 +129,23 @@ namespace Discord.Audio
#endregion
#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);
}
public async Task SendIdentityAsync(ulong userId, string sessionId, string token)
{
await SendAsync(VoiceOpCode.Identify, new IdentifyParams
return SendAsync(VoiceOpCode.Identify, new IdentifyParams
{
GuildId = GuildId,
UserId = userId,
SessionId = sessionId,
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",
Data = new UdpProtocolInfo
@@ -154,15 +154,16 @@ namespace Discord.Audio
Port = externalPort,
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,
Delay = 0
}).ConfigureAwait(false);
});
}
public async Task ConnectAsync(string url)
@@ -174,6 +175,7 @@ namespace Discord.Audio
}
finally { _connectionLock.Release(); }
}
private async Task ConnectInternalAsync(string url)
{
ConnectionState = ConnectionState.Connecting;

View File

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

View File

@@ -330,12 +330,12 @@ namespace Discord.WebSocket
#region IMessageChannel
/// <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)
return await GetMessageAsync(id, options).ConfigureAwait(false);
return GetMessageAsync(id, options);
else
return GetCachedMessage(id);
return Task.FromResult((IMessage)GetCachedMessage(id));
}
/// <inheritdoc />
IAsyncEnumerable<IReadOnlyCollection<IMessage>> IMessageChannel.GetMessagesAsync(int limit, CacheMode mode, RequestOptions options)

View File

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

View File

@@ -413,12 +413,12 @@ namespace Discord.WebSocket
#region IMessageChannel
/// <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)
return await GetMessageAsync(id, options).ConfigureAwait(false);
return GetMessageAsync(id, options);
else
return GetCachedMessage(id);
return Task.FromResult((IMessage)GetCachedMessage(id));
}
/// <inheritdoc />
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);
/// <inheritdoc />
public async Task<IAudioClient> ConnectAsync(bool selfDeaf = false, bool selfMute = false, bool external = false)
{
return await Guild.ConnectAudioAsync(Id, selfDeaf, selfMute, external).ConfigureAwait(false);
}
public Task<IAudioClient> ConnectAsync(bool selfDeaf = false, bool selfMute = false, bool external = false)
=> Guild.ConnectAudioAsync(Id, selfDeaf, selfMute, external);
/// <inheritdoc />
public async Task DisconnectAsync()
=> await Guild.DisconnectAudioAsync();
public Task DisconnectAsync()
=> Guild.DisconnectAudioAsync();
/// <inheritdoc />
public async Task ModifyAsync(Action<AudioChannelProperties> func, RequestOptions options = null)
{
await Guild.ModifyAudioAsync(Id, func, options).ConfigureAwait(false);
}
public Task ModifyAsync(Action<AudioChannelProperties> func, RequestOptions options = null)
=> Guild.ModifyAudioAsync(Id, func, options);
/// <inheritdoc />
public override SocketGuildUser GetUser(ulong id)

View File

@@ -1307,10 +1307,9 @@ namespace Discord.WebSocket
}
/// <inheritdoc />
public async Task DownloadUsersAsync()
{
await Discord.DownloadUsersAsync(new[] { this }).ConfigureAwait(false);
}
public Task DownloadUsersAsync()
=> Discord.DownloadUsersAsync(new[] { this });
internal void CompleteDownloadUsers()
{
_downloaderPromise.TrySetResultAsync(true);
@@ -1545,7 +1544,8 @@ namespace Discord.WebSocket
/// </summary>
/// <param name="user">The user to disconnect.</param>
/// <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
#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)
throw new InvalidOperationException("Cannot modify properties of not connected audio channel");
@@ -1863,7 +1863,7 @@ namespace Discord.WebSocket
if (props.SelfMute.IsSpecified)
_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)

View File

@@ -305,7 +305,7 @@ namespace Discord.WebSocket
}
/// <inheritdoc/>
public override async Task<RestFollowupMessage> FollowupAsync(
public override Task<RestFollowupMessage> FollowupAsync(
string text = null,
Embed[] embeds = null,
bool isTTS = false,
@@ -338,11 +338,11 @@ namespace Discord.WebSocket
if (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/>
public override async Task<RestFollowupMessage> FollowupWithFilesAsync(
public override Task<RestFollowupMessage> FollowupWithFilesAsync(
IEnumerable<FileAttachment> attachments,
string text = null,
Embed[] embeds = null,
@@ -391,7 +391,7 @@ namespace Discord.WebSocket
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 };
return await InteractionHelper.SendFollowupAsync(Discord, args, Token, Channel, options).ConfigureAwait(false);
return InteractionHelper.SendFollowupAsync(Discord, args, Token, Channel, options);
}
/// <inheritdoc/>

View File

@@ -302,7 +302,7 @@ namespace Discord.WebSocket
}
/// <inheritdoc/>
public override async Task<RestFollowupMessage> FollowupAsync(
public override Task<RestFollowupMessage> FollowupAsync(
string text = null,
Embed[] embeds = null,
bool isTTS = false,
@@ -335,11 +335,11 @@ namespace Discord.WebSocket
if (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/>
public override async Task<RestFollowupMessage> FollowupWithFilesAsync(
public override Task<RestFollowupMessage> FollowupWithFilesAsync(
IEnumerable<FileAttachment> attachments,
string text = null,
Embed[] embeds = null,
@@ -388,7 +388,7 @@ namespace Discord.WebSocket
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 };
return await InteractionHelper.SendFollowupAsync(Discord, args, Token, Channel, options).ConfigureAwait(false);
return InteractionHelper.SendFollowupAsync(Discord, args, Token, Channel, options);
}
/// <inheritdoc/>

View File

@@ -234,7 +234,7 @@ namespace Discord.WebSocket
}
/// <inheritdoc/>
public override async Task<RestFollowupMessage> FollowupAsync(
public override Task<RestFollowupMessage> FollowupAsync(
string text = null,
Embed[] embeds = null,
bool isTTS = false,
@@ -267,11 +267,11 @@ namespace Discord.WebSocket
if (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/>
public override async Task<RestFollowupMessage> FollowupWithFilesAsync(
public override Task<RestFollowupMessage> FollowupWithFilesAsync(
IEnumerable<FileAttachment> attachments,
string text = null,
Embed[] embeds = null,
@@ -320,7 +320,7 @@ namespace Discord.WebSocket
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 };
return await InteractionHelper.SendFollowupAsync(Discord, args, Token, Channel, options).ConfigureAwait(false);
return InteractionHelper.SendFollowupAsync(Discord, args, Token, Channel, options);
}
/// <summary>

View File

@@ -228,14 +228,14 @@ namespace Discord.WebSocket
/// <inheritdoc />
/// <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))
{
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" : "")})";

View File

@@ -116,7 +116,7 @@ namespace Discord.Net.Udp
_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?
{
@@ -124,7 +124,7 @@ namespace Discord.Net.Udp
Buffer.BlockCopy(data, index, newData, 0, count);
data = newData;
}
await _udp.SendAsync(data, count, _destination).ConfigureAwait(false);
return _udp.SendAsync(data, count, _destination);
}
private async Task RunAsync(CancellationToken cancelToken)

View File

@@ -56,7 +56,7 @@ namespace Discord.Webhook
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)
{
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,
};
await client.ApiClient.ModifyWebhookMessageAsync(client.Webhook.Id, messageId, apiArgs, options, threadId)
.ConfigureAwait(false);
return client.ApiClient.ModifyWebhookMessageAsync(client.Webhook.Id, messageId, apiArgs, options, threadId);
}
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,
};
await client.ApiClient.ModifyWebhookMessageAsync(client.Webhook.Id, messageId, apiArgs, options, threadId)
.ConfigureAwait(false);
return client.ApiClient.ModifyWebhookMessageAsync(client.Webhook.Id, messageId, apiArgs, options, threadId);
}
}
public static async Task DeleteMessageAsync(DiscordWebhookClient client, ulong messageId, RequestOptions options, ulong? threadId)
{
await client.ApiClient.DeleteWebhookMessageAsync(client.Webhook.Id, messageId, options, threadId).ConfigureAwait(false);
}
public static Task DeleteMessageAsync(DiscordWebhookClient client, ulong messageId, RequestOptions options, ulong? threadId)
=> client.ApiClient.DeleteWebhookMessageAsync(client.Webhook.Id, messageId, options, threadId);
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,
@@ -206,7 +202,7 @@ namespace Discord.Webhook
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();
func(args);
@@ -219,12 +215,10 @@ namespace Discord.Webhook
if (!apiArgs.Avatar.IsSpecified && client.Webhook.AvatarId != null)
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)
{
await client.ApiClient.DeleteWebhookAsync(client.Webhook.Id, options).ConfigureAwait(false);
}
public static Task DeleteAsync(DiscordWebhookClient client, RequestOptions options)
=> client.ApiClient.DeleteWebhookAsync(client.Webhook.Id, options);
}
}