1
Fork 0
mirror of https://gitlab.com/Kwoth/nadekobot.git synced 2024-10-03 04:23:13 +00:00

- Updated editorconfig rules to hopefully look a bit nicer.

- Removed configureawait(false) from everywhere as it doesnt' do anything in a console app and just makes the code look ugly
- Started using .WhenAll extension instead of Task.WhenAll to make it look nicer when chaining methods
This commit is contained in:
Kwoth 2021-12-28 21:14:26 +01:00
parent d093f7eed7
commit 723447c7d4
171 changed files with 1523 additions and 1594 deletions

View file

@ -328,15 +328,18 @@ resharper_wrap_after_invocation_lpar = false
resharper_wrap_before_invocation_rpar = false
# ReSharper properties
resharper_align_multiline_calls_chain = true
resharper_csharp_wrap_after_declaration_lpar = true
resharper_csharp_wrap_before_invocation_rpar = true
resharper_csharp_wrap_after_invocation_lpar = false
resharper_csharp_wrap_before_binary_opsign = true
resharper_csharp_wrap_before_invocation_rpar = false
resharper_csharp_wrap_parameters_style = chop_if_long
resharper_force_chop_compound_if_expression = false
resharper_keep_existing_linebreaks = false
resharper_max_formal_parameters_on_line = 3
resharper_wrap_chained_binary_expressions = chop_if_long
resharper_wrap_chained_binary_patterns = chop_if_long
resharper_wrap_chained_method_calls = chop_always
resharper_wrap_chained_method_calls = wrap_if_long
resharper_csharp_wrap_before_first_type_parameter_constraint = true
resharper_csharp_place_type_constraints_on_same_line = false

View file

@ -169,7 +169,7 @@ public sealed class Bot
_ = LoadTypeReaders(typeof(Bot).Assembly);
sw.Stop();
Log.Information($"All services loaded in {sw.Elapsed.TotalSeconds:F2}s");
Log.Information("All services loaded in {ServiceLoadTime:F2}s", sw.Elapsed.TotalSeconds);
}
private void ApplyConfigMigrations()
@ -194,10 +194,10 @@ public sealed class Bot
Log.Warning(ex.LoaderExceptions[0], "Error getting types");
return Enumerable.Empty<object>();
}
var filteredTypes = allTypes
.Where(x => x.IsSubclassOf(typeof(TypeReader))
&& x.BaseType?.GetGenericArguments().Length > 0
&& !x.IsAbstract);
var filteredTypes = allTypes.Where(x => x.IsSubclassOf(typeof(TypeReader))
&& x.BaseType?.GetGenericArguments().Length > 0
&& !x.IsAbstract);
var toReturn = new List<object>();
foreach (var ft in filteredTypes)
@ -225,9 +225,9 @@ public sealed class Bot
clientReady.TrySetResult(true);
try
{
foreach (var chan in await Client.GetDMChannelsAsync().ConfigureAwait(false))
foreach (var chan in await Client.GetDMChannelsAsync())
{
await chan.CloseAsync().ConfigureAwait(false);
await chan.CloseAsync();
}
}
catch
@ -242,8 +242,8 @@ public sealed class Bot
Log.Information("Shard {ShardId} logging in ...", Client.ShardId);
try
{
await Client.LoginAsync(TokenType.Bot, token).ConfigureAwait(false);
await Client.StartAsync().ConfigureAwait(false);
await Client.LoginAsync(TokenType.Bot, token);
await Client.StartAsync();
}
catch (HttpException ex)
{
@ -257,24 +257,24 @@ public sealed class Bot
}
Client.Ready += SetClientReady;
await clientReady.Task.ConfigureAwait(false);
await clientReady.Task;
Client.Ready -= SetClientReady;
Client.JoinedGuild += Client_JoinedGuild;
Client.LeftGuild += Client_LeftGuild;
Log.Information("Shard {0} logged in.", Client.ShardId);
Log.Information("Shard {ShardId} logged in", Client.ShardId);
}
private Task Client_LeftGuild(SocketGuild arg)
{
Log.Information("Left server: {0} [{1}]", arg?.Name, arg?.Id);
Log.Information("Left server: {GuildName} [{GuildId}]", arg?.Name, arg?.Id);
return Task.CompletedTask;
}
private Task Client_JoinedGuild(SocketGuild arg)
{
Log.Information($"Joined server: {0} [{1}]", arg.Name, arg.Id);
Log.Information("Joined server: {GuildName} [{GuildId}]", arg.Name, arg.Id);
var _ = Task.Run(async () =>
{
GuildConfig gc;
@ -282,7 +282,7 @@ public sealed class Bot
{
gc = uow.GuildConfigsForId(arg.Id, null);
}
await JoinedGuild.Invoke(gc).ConfigureAwait(false);
await JoinedGuild.Invoke(gc);
});
return Task.CompletedTask;
}
@ -291,7 +291,7 @@ public sealed class Bot
{
var sw = Stopwatch.StartNew();
await LoginAsync(_creds.Token).ConfigureAwait(false);
await LoginAsync(_creds.Token);
Mention = Client.CurrentUser.Mention;
Log.Information("Shard {ShardId} loading services...", Client.ShardId);
@ -310,7 +310,7 @@ public sealed class Bot
var commandHandler = Services.GetRequiredService<CommandHandler>();
// start handling messages received in commandhandler
await commandHandler.StartHandling().ConfigureAwait(false);
await commandHandler.StartHandling();
await _commandService.AddModulesAsync(typeof(Bot).Assembly, Services);
await _interactionService.AddModulesAsync(typeof(Bot).Assembly, Services);
@ -338,22 +338,22 @@ public sealed class Bot
}
});
return Task.WhenAll(tasks);
return tasks.WhenAll();
}
private Task Client_Log(LogMessage arg)
{
if (arg.Exception != null)
Log.Warning(arg.Exception, arg.Source + " | " + arg.Message);
Log.Warning(arg.Exception, "{ErrorSource} | {ErrorMessage}", arg.Source, arg.Message);
else
Log.Warning(arg.Source + " | " + arg.Message);
Log.Warning("{ErrorSource} | {ErrorMessage}", arg.Source, arg.Message);
return Task.CompletedTask;
}
public async Task RunAndBlockAsync()
{
await RunAsync().ConfigureAwait(false);
await Task.Delay(-1).ConfigureAwait(false);
await RunAsync();
await Task.Delay(-1);
}
}

View file

@ -1,4 +1,4 @@
#nullable disable
#nullable disable
using System.Globalization;
// ReSharper disable InconsistentNaming
@ -84,12 +84,10 @@ public abstract class NadekoModule : ModuleBase
embed.WithPendingColor()
.WithFooter("yes/no");
var msg = await ctx.Channel.EmbedAsync(embed)
.ConfigureAwait(false);
var msg = await ctx.Channel.EmbedAsync(embed);
try
{
var input = await GetUserInputAsync(ctx.User.Id, ctx.Channel.Id)
.ConfigureAwait(false);
var input = await GetUserInputAsync(ctx.User.Id, ctx.Channel.Id);
input = input?.ToUpperInvariant();
if (input != "YES" &&
@ -115,14 +113,13 @@ public abstract class NadekoModule : ModuleBase
{
dsc.MessageReceived += MessageReceived;
if (await Task.WhenAny(userInputTask.Task, Task.Delay(10000))
.ConfigureAwait(false) !=
if (await Task.WhenAny(userInputTask.Task, Task.Delay(10000)) !=
userInputTask.Task)
{
return null;
}
return await userInputTask.Task.ConfigureAwait(false);
return await userInputTask.Task;
}
finally
{

View file

@ -36,8 +36,11 @@ public class EventPubSub : IPubSub
{
// if this class ever gets used, this needs to be properly implemented
// 1. ignore all valuetasks which are completed
// 2. return task.whenall all other tasks
return Task.WhenAll(actions.SelectMany(kvp => kvp.Value).Select(action => action(data).AsTask()));
// 2. run all other tasks in parallel
return actions
.SelectMany(kvp => kvp.Value)
.Select(action => action(data).AsTask())
.WhenAll();
}
return Task.CompletedTask;

View file

@ -1,4 +1,4 @@
#nullable disable
#nullable disable
using NadekoBot.Modules.CustomReactions.Services;
namespace NadekoBot.Common.TypeReaders;
@ -53,7 +53,7 @@ public sealed class CommandOrCrTypeReader : NadekoTypeReader<CommandOrCrInfo>
return TypeReaderResult.FromSuccess(new CommandOrCrInfo(input, CommandOrCrInfo.Type.Custom));
}
var cmd = await new CommandTypeReader(_commandHandler, _cmds).ReadAsync(context, input).ConfigureAwait(false);
var cmd = await new CommandTypeReader(_commandHandler, _cmds).ReadAsync(context, input);
if (cmd.IsSuccess)
{
return TypeReaderResult.FromSuccess(new CommandOrCrInfo(((CommandInfo)cmd.Values.First().Value).Name,

View file

@ -78,7 +78,7 @@ public partial class Administration : NadekoModule<AdministrationService>
embed.AddField(GetText(strs.channel_delmsgoncmd), str);
await ctx.Channel.EmbedAsync(embed).ConfigureAwait(false);
await ctx.Channel.EmbedAsync(embed);
}
public enum Server
@ -96,12 +96,12 @@ public partial class Administration : NadekoModule<AdministrationService>
if (_service.ToggleDeleteMessageOnCommand(ctx.Guild.Id))
{
_service.DeleteMessagesOnCommand.Add(ctx.Guild.Id);
await ReplyConfirmLocalizedAsync(strs.delmsg_on).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.delmsg_on);
}
else
{
_service.DeleteMessagesOnCommand.TryRemove(ctx.Guild.Id);
await ReplyConfirmLocalizedAsync(strs.delmsg_off).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.delmsg_off);
}
}
@ -136,19 +136,19 @@ public partial class Administration : NadekoModule<AdministrationService>
public async Task Delmsgoncmd(Channel _, State s, ulong? chId = null)
{
var actualChId = chId ?? ctx.Channel.Id;
await _service.SetDelMsgOnCmdState(ctx.Guild.Id, actualChId, s).ConfigureAwait(false);
await _service.SetDelMsgOnCmdState(ctx.Guild.Id, actualChId, s);
if (s == State.Disable)
{
await ReplyConfirmLocalizedAsync(strs.delmsg_channel_off).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.delmsg_channel_off);
}
else if (s == State.Enable)
{
await ReplyConfirmLocalizedAsync(strs.delmsg_channel_on).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.delmsg_channel_on);
}
else
{
await ReplyConfirmLocalizedAsync(strs.delmsg_channel_inherit).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.delmsg_channel_inherit);
}
}
@ -158,8 +158,8 @@ public partial class Administration : NadekoModule<AdministrationService>
[BotPerm(GuildPerm.DeafenMembers)]
public async Task Deafen(params IGuildUser[] users)
{
await _service.DeafenUsers(true, users).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.deafen).ConfigureAwait(false);
await _service.DeafenUsers(true, users);
await ReplyConfirmLocalizedAsync(strs.deafen);
}
[NadekoCommand, Aliases]
@ -168,8 +168,8 @@ public partial class Administration : NadekoModule<AdministrationService>
[BotPerm(GuildPerm.DeafenMembers)]
public async Task UnDeafen(params IGuildUser[] users)
{
await _service.DeafenUsers(false, users).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.undeafen).ConfigureAwait(false);
await _service.DeafenUsers(false, users);
await ReplyConfirmLocalizedAsync(strs.undeafen);
}
[NadekoCommand, Aliases]
@ -178,8 +178,8 @@ public partial class Administration : NadekoModule<AdministrationService>
[BotPerm(GuildPerm.ManageChannels)]
public async Task DelVoiChanl([Leftover] IVoiceChannel voiceChannel)
{
await voiceChannel.DeleteAsync().ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.delvoich(Format.Bold(voiceChannel.Name))).ConfigureAwait(false);
await voiceChannel.DeleteAsync();
await ReplyConfirmLocalizedAsync(strs.delvoich(Format.Bold(voiceChannel.Name)));
}
[NadekoCommand, Aliases]
@ -188,8 +188,8 @@ public partial class Administration : NadekoModule<AdministrationService>
[BotPerm(GuildPerm.ManageChannels)]
public async Task CreatVoiChanl([Leftover] string channelName)
{
var ch = await ctx.Guild.CreateVoiceChannelAsync(channelName).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.createvoich(Format.Bold(ch.Name))).ConfigureAwait(false);
var ch = await ctx.Guild.CreateVoiceChannelAsync(channelName);
await ReplyConfirmLocalizedAsync(strs.createvoich(Format.Bold(ch.Name)));
}
[NadekoCommand, Aliases]
@ -198,8 +198,8 @@ public partial class Administration : NadekoModule<AdministrationService>
[BotPerm(GuildPerm.ManageChannels)]
public async Task DelTxtChanl([Leftover] ITextChannel toDelete)
{
await toDelete.DeleteAsync().ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.deltextchan(Format.Bold(toDelete.Name))).ConfigureAwait(false);
await toDelete.DeleteAsync();
await ReplyConfirmLocalizedAsync(strs.deltextchan(Format.Bold(toDelete.Name)));
}
[NadekoCommand, Aliases]
@ -208,8 +208,8 @@ public partial class Administration : NadekoModule<AdministrationService>
[BotPerm(GuildPerm.ManageChannels)]
public async Task CreaTxtChanl([Leftover] string channelName)
{
var txtCh = await ctx.Guild.CreateTextChannelAsync(channelName).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.createtextchan(Format.Bold(txtCh.Name))).ConfigureAwait(false);
var txtCh = await ctx.Guild.CreateTextChannelAsync(channelName);
await ReplyConfirmLocalizedAsync(strs.createtextchan(Format.Bold(txtCh.Name)));
}
[NadekoCommand, Aliases]
@ -220,8 +220,8 @@ public partial class Administration : NadekoModule<AdministrationService>
{
var channel = (ITextChannel) ctx.Channel;
topic ??= "";
await channel.ModifyAsync(c => c.Topic = topic).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.set_topic).ConfigureAwait(false);
await channel.ModifyAsync(c => c.Topic = topic);
await ReplyConfirmLocalizedAsync(strs.set_topic);
}
[NadekoCommand, Aliases]
@ -231,8 +231,8 @@ public partial class Administration : NadekoModule<AdministrationService>
public async Task SetChanlName([Leftover] string name)
{
var channel = (ITextChannel) ctx.Channel;
await channel.ModifyAsync(c => c.Name = name).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.set_channel_name).ConfigureAwait(false);
await channel.ModifyAsync(c => c.Name = name);
await ReplyConfirmLocalizedAsync(strs.set_channel_name);
}
[NadekoCommand, Aliases]
@ -244,12 +244,12 @@ public partial class Administration : NadekoModule<AdministrationService>
var channel = (ITextChannel) ctx.Channel;
var isEnabled = channel.IsNsfw;
await channel.ModifyAsync(c => c.IsNsfw = !isEnabled).ConfigureAwait(false);
await channel.ModifyAsync(c => c.IsNsfw = !isEnabled);
if (isEnabled)
await ReplyConfirmLocalizedAsync(strs.nsfw_set_false).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.nsfw_set_false);
else
await ReplyConfirmLocalizedAsync(strs.nsfw_set_true).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.nsfw_set_true);
}
[NadekoCommand, Aliases]
@ -268,13 +268,13 @@ public partial class Administration : NadekoModule<AdministrationService>
var botPerms = ((SocketGuild) ctx.Guild).CurrentUser.GetPermissions(channel);
if (!userPerms.Has(ChannelPermission.ManageMessages))
{
await ReplyErrorLocalizedAsync(strs.insuf_perms_u).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.insuf_perms_u);
return;
}
if (!botPerms.Has(ChannelPermission.ViewChannel))
{
await ReplyErrorLocalizedAsync(strs.insuf_perms_i).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.insuf_perms_i);
return;
}
@ -300,39 +300,39 @@ public partial class Administration : NadekoModule<AdministrationService>
var botPerms = ((SocketGuild) ctx.Guild).CurrentUser.GetPermissions(channel);
if (!userPerms.Has(ChannelPermission.ManageMessages))
{
await ReplyErrorLocalizedAsync(strs.insuf_perms_u).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.insuf_perms_u);
return;
}
if (!botPerms.Has(ChannelPermission.ManageMessages))
{
await ReplyErrorLocalizedAsync(strs.insuf_perms_i).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.insuf_perms_i);
return;
}
var msg = await channel.GetMessageAsync(messageId).ConfigureAwait(false);
var msg = await channel.GetMessageAsync(messageId);
if (msg is null)
{
await ReplyErrorLocalizedAsync(strs.msg_not_found).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.msg_not_found);
return;
}
if (time is null)
{
await msg.DeleteAsync().ConfigureAwait(false);
await msg.DeleteAsync();
}
else if (time.Time <= TimeSpan.FromDays(7))
{
var _ = Task.Run(async () =>
{
await Task.Delay(time.Time).ConfigureAwait(false);
await msg.DeleteAsync().ConfigureAwait(false);
await Task.Delay(time.Time);
await msg.DeleteAsync();
});
}
else
{
await ReplyErrorLocalizedAsync(strs.time_too_long).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.time_too_long);
return;
}

View file

@ -1,4 +1,4 @@
#nullable disable
#nullable disable
using NadekoBot.Modules.Administration.Services;
#if !GLOBAL_NADEKO
@ -20,17 +20,17 @@ namespace NadekoBot.Modules.Administration
.WithTitle(GetText(strs.sql_confirm_exec))
.WithDescription(Format.Code(sql));
if (!await PromptUserConfirmAsync(embed).ConfigureAwait(false))
if (!await PromptUserConfirmAsync(embed))
{
return;
}
var res = await _service.ExecuteSql(sql).ConfigureAwait(false);
await SendConfirmAsync(res.ToString()).ConfigureAwait(false);
var res = await _service.ExecuteSql(sql);
await SendConfirmAsync(res.ToString());
}
catch (Exception ex)
{
await SendErrorAsync(ex.ToString()).ConfigureAwait(false);
await SendErrorAsync(ex.ToString());
}
}
@ -103,7 +103,7 @@ namespace NadekoBot.Modules.Administration
var embed = _eb.Create()
.WithDescription(GetText(strs.purge_user_confirm(Format.Bold(userId.ToString()))));
if (!await PromptUserConfirmAsync(embed).ConfigureAwait(false))
if (!await PromptUserConfirmAsync(embed))
{
return;
}

View file

@ -1,4 +1,4 @@
#nullable disable
#nullable disable
using NadekoBot.Modules.Administration.Services;
namespace NadekoBot.Modules.Administration;
@ -18,19 +18,19 @@ public partial class Administration
if (vch is null)
{
await ReplyErrorLocalizedAsync(strs.not_in_voice).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.not_in_voice);
return;
}
var id = _service.ToggleGameVoiceChannel(ctx.Guild.Id, vch.Id);
if (id is null)
{
await ReplyConfirmLocalizedAsync(strs.gvc_disabled).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.gvc_disabled);
}
else
{
_service.GameVoiceChannels.Add(vch.Id);
await ReplyConfirmLocalizedAsync(strs.gvc_enabled(Format.Bold(vch.Name))).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.gvc_enabled(Format.Bold(vch.Name)));
}
}
}

View file

@ -127,8 +127,7 @@ public class GreetSettingsService : INService
var groupClear = false;
while (!groupClear)
{
await Task.Delay(5000)
.ConfigureAwait(false);
await Task.Delay(5000);
groupClear = _byes.ClearGroup(guild.Id, 5, out var toBye);
await ByeUsers(conf, channel, toBye);
}
@ -217,8 +216,7 @@ public class GreetSettingsService : INService
text = rep.Replace(text);
try
{
var toDelete = await channel.SendAsync(text)
.ConfigureAwait(false);
var toDelete = await channel.SendAsync(text);
if (conf.AutoDeleteGreetMessagesTimer > 0)
{
toDelete.DeleteAfter(conf.AutoDeleteGreetMessagesTimer);
@ -243,8 +241,7 @@ public class GreetSettingsService : INService
rep.Replace(text);
try
{
await channel.SendAsync(text)
.ConfigureAwait(false);
await channel.SendAsync(text);
}
catch
{
@ -279,8 +276,7 @@ public class GreetSettingsService : INService
var groupClear = false;
while (!groupClear)
{
await Task.Delay(5000)
.ConfigureAwait(false);
await Task.Delay(5000);
groupClear = _greets.ClearGroup(user.GuildId, 5, out var toGreet);
await GreetUsers(conf, channel, toGreet);
}

View file

@ -1,4 +1,4 @@
#nullable disable
#nullable disable
using System.Globalization;
namespace NadekoBot.Modules.Administration;
@ -72,7 +72,7 @@ public partial class Administration
}
catch (Exception)
{
await ReplyErrorLocalizedAsync(strs.lang_set_fail).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.lang_set_fail);
}
}
@ -106,7 +106,7 @@ public partial class Administration
}
catch (Exception)
{
await ReplyErrorLocalizedAsync(strs.lang_set_fail).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.lang_set_fail);
}
}
@ -115,7 +115,7 @@ public partial class Administration
=> await ctx.Channel.EmbedAsync(_eb.Create().WithOkColor()
.WithTitle(GetText(strs.lang_list))
.WithDescription(string.Join("\n",
supportedLocales.Select(x => $"{Format.Code(x.Key),-10} => {x.Value}")))).ConfigureAwait(false);
supportedLocales.Select(x => $"{Format.Code(x.Key),-10} => {x.Value}"))));
}
}
/* list of language codes for reference.

View file

@ -1,4 +1,4 @@
#nullable disable
#nullable disable
using NadekoBot.Common.TypeReaders.Models;
using NadekoBot.Services.Database.Models;
using NadekoBot.Modules.Administration.Services;
@ -17,11 +17,11 @@ public partial class Administration
[OwnerOnly]
public async Task LogServer(PermissionAction action)
{
await _service.LogServer(ctx.Guild.Id, ctx.Channel.Id, action.Value).ConfigureAwait(false);
await _service.LogServer(ctx.Guild.Id, ctx.Channel.Id, action.Value);
if (action.Value)
await ReplyConfirmLocalizedAsync(strs.log_all).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.log_all);
else
await ReplyConfirmLocalizedAsync(strs.log_disabled).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.log_disabled);
}
[NadekoCommand, Aliases]
@ -58,9 +58,9 @@ public partial class Administration
var removed = _service.LogIgnore(ctx.Guild.Id, target.Id, IgnoredItemType.Channel);
if (!removed)
await ReplyConfirmLocalizedAsync(strs.log_ignore_chan(Format.Bold(target.Mention + "(" + target.Id + ")"))).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.log_ignore_chan(Format.Bold(target.Mention + "(" + target.Id + ")")));
else
await ReplyConfirmLocalizedAsync(strs.log_not_ignore_chan(Format.Bold(target.Mention + "(" + target.Id + ")"))).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.log_not_ignore_chan(Format.Bold(target.Mention + "(" + target.Id + ")")));
}
[NadekoCommand, Aliases]
@ -72,9 +72,9 @@ public partial class Administration
var removed = _service.LogIgnore(ctx.Guild.Id, target.Id, IgnoredItemType.User);
if (!removed)
await ReplyConfirmLocalizedAsync(strs.log_ignore_user(Format.Bold(target.Mention + "(" + target.Id + ")"))).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.log_ignore_user(Format.Bold(target.Mention + "(" + target.Id + ")")));
else
await ReplyConfirmLocalizedAsync(strs.log_not_ignore_user(Format.Bold(target.Mention + "(" + target.Id + ")"))).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.log_not_ignore_user(Format.Bold(target.Mention + "(" + target.Id + ")")));
}
[NadekoCommand, Aliases]
@ -94,8 +94,7 @@ public partial class Administration
}));
await SendConfirmAsync(Format.Bold(GetText(strs.log_events)) + "\n" +
str)
.ConfigureAwait(false);
str);
}
private static ulong? GetLogProperty(LogSetting l, LogType type)
@ -146,9 +145,9 @@ public partial class Administration
var val = _service.Log(ctx.Guild.Id, ctx.Channel.Id, type);
if (val)
await ReplyConfirmLocalizedAsync(strs.log(Format.Bold(type.ToString()))).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.log(Format.Bold(type.ToString())));
else
await ReplyConfirmLocalizedAsync(strs.log_stop(Format.Bold(type.ToString()))).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.log_stop(Format.Bold(type.ToString())));
}
}
}

View file

@ -1,4 +1,4 @@
#nullable disable
#nullable disable
using NadekoBot.Common.TypeReaders.Models;
using NadekoBot.Modules.Administration.Services;
@ -16,7 +16,7 @@ public partial class Administration
if (runnerUser.Id != ctx.Guild.OwnerId &&
runnerUserRoles.Max(x => x.Position) <= targetUserRoles.Max(x => x.Position))
{
await ReplyErrorLocalizedAsync(strs.mute_perms).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.mute_perms);
return false;
}
@ -30,21 +30,21 @@ public partial class Administration
{
if (role is null)
{
var muteRole = await _service.GetMuteRole(ctx.Guild).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.mute_role(Format.Code(muteRole.Name))).ConfigureAwait(false);
var muteRole = await _service.GetMuteRole(ctx.Guild);
await ReplyConfirmLocalizedAsync(strs.mute_role(Format.Code(muteRole.Name)));
return;
}
if (ctx.User.Id != ctx.Guild.OwnerId &&
role.Position >= ((SocketGuildUser) ctx.User).Roles.Max(x => x.Position))
{
await ReplyErrorLocalizedAsync(strs.insuf_perms_u).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.insuf_perms_u);
return;
}
await _service.SetMuteRoleAsync(ctx.Guild.Id, role.Name).ConfigureAwait(false);
await _service.SetMuteRoleAsync(ctx.Guild.Id, role.Name);
await ReplyConfirmLocalizedAsync(strs.mute_role_set).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.mute_role_set);
}
[NadekoCommand, Aliases]
@ -58,13 +58,13 @@ public partial class Administration
if (!await VerifyMutePermissions((IGuildUser)ctx.User, target))
return;
await _service.MuteUser(target, ctx.User, reason: reason).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.user_muted(Format.Bold(target.ToString()))).ConfigureAwait(false);
await _service.MuteUser(target, ctx.User, reason: reason);
await ReplyConfirmLocalizedAsync(strs.user_muted(Format.Bold(target.ToString())));
}
catch (Exception ex)
{
Log.Warning(ex.ToString());
await ReplyErrorLocalizedAsync(strs.mute_error).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.mute_error);
}
}
@ -81,13 +81,13 @@ public partial class Administration
if (!await VerifyMutePermissions((IGuildUser)ctx.User, user))
return;
await _service.TimedMute(user, ctx.User, time.Time, reason: reason).ConfigureAwait(false);
await _service.TimedMute(user, ctx.User, time.Time, reason: reason);
await ReplyConfirmLocalizedAsync(strs.user_muted_time(Format.Bold(user.ToString()), (int)time.Time.TotalMinutes));
}
catch (Exception ex)
{
Log.Warning(ex, "Error in mute command");
await ReplyErrorLocalizedAsync(strs.mute_error).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.mute_error);
}
}
@ -98,12 +98,12 @@ public partial class Administration
{
try
{
await _service.UnmuteUser(user.GuildId, user.Id, ctx.User, reason: reason).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.user_unmuted(Format.Bold(user.ToString()))).ConfigureAwait(false);
await _service.UnmuteUser(user.GuildId, user.Id, ctx.User, reason: reason);
await ReplyConfirmLocalizedAsync(strs.user_unmuted(Format.Bold(user.ToString())));
}
catch
{
await ReplyErrorLocalizedAsync(strs.mute_error).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.mute_error);
}
}
@ -118,13 +118,13 @@ public partial class Administration
if (!await VerifyMutePermissions((IGuildUser)ctx.User, user))
return;
await _service.MuteUser(user, ctx.User, MuteType.Chat, reason: reason).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.user_chat_mute(Format.Bold(user.ToString()))).ConfigureAwait(false);
await _service.MuteUser(user, ctx.User, MuteType.Chat, reason: reason);
await ReplyConfirmLocalizedAsync(strs.user_chat_mute(Format.Bold(user.ToString())));
}
catch (Exception ex)
{
Log.Warning(ex.ToString());
await ReplyErrorLocalizedAsync(strs.mute_error).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.mute_error);
}
}
@ -141,13 +141,13 @@ public partial class Administration
if (!await VerifyMutePermissions((IGuildUser)ctx.User, user))
return;
await _service.TimedMute(user, ctx.User, time.Time, MuteType.Chat, reason: reason).ConfigureAwait(false);
await _service.TimedMute(user, ctx.User, time.Time, MuteType.Chat, reason: reason);
await ReplyConfirmLocalizedAsync(strs.user_chat_mute_time(Format.Bold(user.ToString()), (int)time.Time.TotalMinutes));
}
catch (Exception ex)
{
Log.Warning(ex.ToString());
await ReplyErrorLocalizedAsync(strs.mute_error).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.mute_error);
}
}
@ -158,12 +158,12 @@ public partial class Administration
{
try
{
await _service.UnmuteUser(user.Guild.Id, user.Id, ctx.User, MuteType.Chat, reason: reason).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.user_chat_unmute(Format.Bold(user.ToString()))).ConfigureAwait(false);
await _service.UnmuteUser(user.Guild.Id, user.Id, ctx.User, MuteType.Chat, reason: reason);
await ReplyConfirmLocalizedAsync(strs.user_chat_unmute(Format.Bold(user.ToString())));
}
catch
{
await ReplyErrorLocalizedAsync(strs.mute_error).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.mute_error);
}
}
@ -178,12 +178,12 @@ public partial class Administration
if (!await VerifyMutePermissions((IGuildUser)ctx.User, user))
return;
await _service.MuteUser(user, ctx.User, MuteType.Voice, reason: reason).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.user_voice_mute(Format.Bold(user.ToString()))).ConfigureAwait(false);
await _service.MuteUser(user, ctx.User, MuteType.Voice, reason: reason);
await ReplyConfirmLocalizedAsync(strs.user_voice_mute(Format.Bold(user.ToString())));
}
catch
{
await ReplyErrorLocalizedAsync(strs.mute_error).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.mute_error);
}
}
@ -200,12 +200,12 @@ public partial class Administration
if (!await VerifyMutePermissions((IGuildUser)ctx.User, user))
return;
await _service.TimedMute(user, ctx.User, time.Time, MuteType.Voice, reason: reason).ConfigureAwait(false);
await _service.TimedMute(user, ctx.User, time.Time, MuteType.Voice, reason: reason);
await ReplyConfirmLocalizedAsync(strs.user_voice_mute_time(Format.Bold(user.ToString()), (int)time.Time.TotalMinutes));
}
catch
{
await ReplyErrorLocalizedAsync(strs.mute_error).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.mute_error);
}
}
@ -216,12 +216,12 @@ public partial class Administration
{
try
{
await _service.UnmuteUser(user.GuildId, user.Id, ctx.User, MuteType.Voice, reason: reason).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.user_voice_unmute(Format.Bold(user.ToString()))).ConfigureAwait(false);
await _service.UnmuteUser(user.GuildId, user.Id, ctx.User, MuteType.Voice, reason: reason);
await ReplyConfirmLocalizedAsync(strs.user_voice_unmute(Format.Bold(user.ToString())));
}
catch
{
await ReplyErrorLocalizedAsync(strs.mute_error).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.mute_error);
}
}
}

View file

@ -1,4 +1,4 @@
#nullable disable
#nullable disable
using NadekoBot.Modules.Administration.Services;
namespace NadekoBot.Modules.Administration;
@ -13,18 +13,18 @@ public partial class Administration
public async Task RotatePlaying()
{
if (_service.ToggleRotatePlaying())
await ReplyConfirmLocalizedAsync(strs.ropl_enabled).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.ropl_enabled);
else
await ReplyConfirmLocalizedAsync(strs.ropl_disabled).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.ropl_disabled);
}
[NadekoCommand, Aliases]
[OwnerOnly]
public async Task AddPlaying(ActivityType t, [Leftover] string status)
{
await _service.AddPlaying(t, status).ConfigureAwait(false);
await _service.AddPlaying(t, status);
await ReplyConfirmLocalizedAsync(strs.ropl_added).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.ropl_added);
}
[NadekoCommand, Aliases]
@ -35,7 +35,7 @@ public partial class Administration
if (!statuses.Any())
{
await ReplyErrorLocalizedAsync(strs.ropl_not_set).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.ropl_not_set);
}
else
{
@ -52,7 +52,7 @@ public partial class Administration
{
index -= 1;
var msg = await _service.RemovePlayingAsync(index).ConfigureAwait(false);
var msg = await _service.RemovePlayingAsync(index);
if (msg is null)
return;

View file

@ -1,4 +1,4 @@
#nullable disable
#nullable disable
namespace NadekoBot.Modules.Administration;
public partial class Administration
@ -9,7 +9,7 @@ public partial class Administration
[NadekoCommand, Aliases]
[Priority(1)]
public async Task PrefixCommand()
=> await ReplyConfirmLocalizedAsync(strs.prefix_current(Format.Code(CmdHandler.GetPrefix(ctx.Guild)))).ConfigureAwait(false);
=> await ReplyConfirmLocalizedAsync(strs.prefix_current(Format.Code(CmdHandler.GetPrefix(ctx.Guild))));
public enum Set
{
@ -35,7 +35,7 @@ public partial class Administration
var oldPrefix = base.Prefix;
var newPrefix = CmdHandler.SetPrefix(ctx.Guild, prefix);
await ReplyConfirmLocalizedAsync(strs.prefix_new(Format.Code(oldPrefix), Format.Code(newPrefix))).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.prefix_new(Format.Code(oldPrefix), Format.Code(newPrefix)));
}
[NadekoCommand, Aliases]
@ -44,14 +44,14 @@ public partial class Administration
{
if (string.IsNullOrWhiteSpace(prefix))
{
await ReplyConfirmLocalizedAsync(strs.defprefix_current(CmdHandler.GetPrefix())).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.defprefix_current(CmdHandler.GetPrefix()));
return;
}
var oldPrefix = CmdHandler.GetPrefix();
var newPrefix = CmdHandler.SetDefaultPrefix(prefix);
await ReplyConfirmLocalizedAsync(strs.defprefix_new(Format.Code(oldPrefix), Format.Code(newPrefix))).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.defprefix_new(Format.Code(oldPrefix), Format.Code(newPrefix)));
}
}
}

View file

@ -1,4 +1,4 @@
#nullable disable
#nullable disable
using NadekoBot.Services.Database.Models;
using NadekoBot.Modules.Administration.Common;
using NadekoBot.Modules.Administration.Services;
@ -120,7 +120,7 @@ public partial class Administration
return;
var stats = await _service.StartAntiRaidAsync(ctx.Guild.Id, userThreshold, seconds,
action, time).ConfigureAwait(false);
action, time);
if (stats is null)
{
@ -128,8 +128,7 @@ public partial class Administration
}
await SendConfirmAsync(GetText(strs.prot_enable("Anti-Raid")),
$"{ctx.User.Mention} {GetAntiRaidString(stats)}")
.ConfigureAwait(false);
$"{ctx.User.Mention} {GetAntiRaidString(stats)}");
}
[NadekoCommand, Aliases]
@ -191,10 +190,10 @@ public partial class Administration
if (time is < 0 or > 60 * 24)
return;
var stats = await _service.StartAntiSpamAsync(ctx.Guild.Id, messageCount, action, time, role?.Id).ConfigureAwait(false);
var stats = await _service.StartAntiSpamAsync(ctx.Guild.Id, messageCount, action, time, role?.Id);
await SendConfirmAsync(GetText(strs.prot_enable("Anti-Spam")),
$"{ctx.User.Mention} {GetAntiSpamString(stats)}").ConfigureAwait(false);
$"{ctx.User.Mention} {GetAntiSpamString(stats)}");
}
[NadekoCommand, Aliases]
@ -202,7 +201,7 @@ public partial class Administration
[UserPerm(GuildPerm.Administrator)]
public async Task AntispamIgnore()
{
var added = await _service.AntiSpamIgnoreAsync(ctx.Guild.Id, ctx.Channel.Id).ConfigureAwait(false);
var added = await _service.AntiSpamIgnoreAsync(ctx.Guild.Id, ctx.Channel.Id);
if(added is null)
{
@ -224,7 +223,7 @@ public partial class Administration
if (spam is null && raid is null && alt is null)
{
await ReplyConfirmLocalizedAsync(strs.prot_none).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.prot_none);
return;
}
@ -240,7 +239,7 @@ public partial class Administration
if (alt is not null)
embed.AddField("Anti-Alt", GetAntiAltString(alt), true);
await ctx.Channel.EmbedAsync(embed).ConfigureAwait(false);
await ctx.Channel.EmbedAsync(embed);
}
private string GetAntiAltString(AntiAltStats alt)

View file

@ -1,4 +1,4 @@
#nullable disable
#nullable disable
using NadekoBot.Modules.Administration.Services;
using ITextChannel = Discord.ITextChannel;
@ -16,12 +16,12 @@ public partial class Administration
[RequireContext(ContextType.Guild)]
public async Task Prune(string parameter = null)
{
var user = await ctx.Guild.GetCurrentUserAsync().ConfigureAwait(false);
var user = await ctx.Guild.GetCurrentUserAsync();
if (parameter is "-s" or "--safe")
await _service.PruneWhere((ITextChannel)ctx.Channel, 100, x => x.Author.Id == user.Id && !x.IsPinned).ConfigureAwait(false);
await _service.PruneWhere((ITextChannel)ctx.Channel, 100, x => x.Author.Id == user.Id && !x.IsPinned);
else
await _service.PruneWhere((ITextChannel)ctx.Channel, 100, x => x.Author.Id == user.Id).ConfigureAwait(false);
await _service.PruneWhere((ITextChannel)ctx.Channel, 100, x => x.Author.Id == user.Id);
ctx.Message.DeleteAfter(3);
}
// prune x
@ -39,9 +39,9 @@ public partial class Administration
count = 1000;
if (parameter is "-s" or "--safe")
await _service.PruneWhere((ITextChannel)ctx.Channel, count, x => !x.IsPinned).ConfigureAwait(false);
await _service.PruneWhere((ITextChannel)ctx.Channel, count, x => !x.IsPinned);
else
await _service.PruneWhere((ITextChannel)ctx.Channel, count, x => true).ConfigureAwait(false);
await _service.PruneWhere((ITextChannel)ctx.Channel, count, x => true);
}
//prune @user [x]
@ -71,9 +71,9 @@ public partial class Administration
count = 1000;
if (parameter is "-s" or "--safe")
await _service.PruneWhere((ITextChannel)ctx.Channel, count, m => m.Author.Id == userId && DateTime.UtcNow - m.CreatedAt < twoWeeks && !m.IsPinned).ConfigureAwait(false);
await _service.PruneWhere((ITextChannel)ctx.Channel, count, m => m.Author.Id == userId && DateTime.UtcNow - m.CreatedAt < twoWeeks && !m.IsPinned);
else
await _service.PruneWhere((ITextChannel)ctx.Channel, count, m => m.Author.Id == userId && DateTime.UtcNow - m.CreatedAt < twoWeeks).ConfigureAwait(false);
await _service.PruneWhere((ITextChannel)ctx.Channel, count, m => m.Author.Id == userId && DateTime.UtcNow - m.CreatedAt < twoWeeks);
}
}
}

View file

@ -1,4 +1,4 @@
#nullable disable
#nullable disable
using NadekoBot.Services.Database.Models;
using NadekoBot.Modules.Administration.Services;
using SixLabors.ImageSharp.PixelFormats;
@ -19,15 +19,15 @@ public partial class Administration
public async Task InternalReactionRoles(bool exclusive, ulong? messageId, params string[] input)
{
var target = messageId is { } msgId
? await ctx.Channel.GetMessageAsync(msgId).ConfigureAwait(false)
: (await ctx.Channel.GetMessagesAsync(2).FlattenAsync().ConfigureAwait(false))
? await ctx.Channel.GetMessageAsync(msgId)
: (await ctx.Channel.GetMessagesAsync(2).FlattenAsync())
.Skip(1)
.FirstOrDefault();
if (input.Length % 2 != 0)
return;
var results = input
var all = await input
.Chunk(input.Length / 2)
.Select(async x =>
{
@ -46,9 +46,8 @@ public partial class Administration
var emote = x.Last().ToIEmote();
return new { role, emote };
})
.Where(x => x != null);
var all = await Task.WhenAll(results);
.Where(x => x != null)
.WhenAll();
if (!all.Any())
return;
@ -60,7 +59,7 @@ public partial class Administration
await target.AddReactionAsync(x.emote, new()
{
RetryMode = RetryMode.Retry502 | RetryMode.RetryRatelimit
}).ConfigureAwait(false);
});
}
catch (Discord.Net.HttpException ex) when(ex.HttpCode == HttpStatusCode.BadRequest)
{
@ -68,7 +67,7 @@ public partial class Administration
return;
}
await Task.Delay(500).ConfigureAwait(false);
await Task.Delay(500);
}
if (_service.Add(ctx.Guild.Id, new()
@ -90,7 +89,7 @@ public partial class Administration
}
else
{
await ReplyErrorLocalizedAsync(strs.reaction_roles_full).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.reaction_roles_full);
}
}
@ -152,14 +151,14 @@ public partial class Administration
IUserMessage msg = null;
if (ch is not null)
{
msg = await ch.GetMessageAsync(rr.MessageId).ConfigureAwait(false) as IUserMessage;
msg = await ch.GetMessageAsync(rr.MessageId) as IUserMessage;
}
var content = msg?.Content.TrimTo(30) ?? "DELETED!";
embed.AddField($"**{rr.Index + 1}.** {ch?.Name ?? "DELETED!"}",
GetText(strs.reaction_roles_message(rr.ReactionRoles?.Count ?? 0, content)));
}
}
await ctx.Channel.EmbedAsync(embed).ConfigureAwait(false);
await ctx.Channel.EmbedAsync(embed);
}
[NadekoCommand, Aliases]
@ -192,16 +191,16 @@ public partial class Administration
return;
try
{
await targetUser.AddRoleAsync(roleToAdd).ConfigureAwait(false);
await targetUser.AddRoleAsync(roleToAdd);
await ReplyConfirmLocalizedAsync(
strs.setrole(Format.Bold(roleToAdd.Name),
Format.Bold(targetUser.ToString())));
strs.setrole(Format.Bold(roleToAdd.Name), Format.Bold(targetUser.ToString()))
);
}
catch (Exception ex)
{
Log.Warning(ex, "Error in setrole command");
await ReplyErrorLocalizedAsync(strs.setrole_err).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.setrole_err);
}
}
@ -216,12 +215,12 @@ public partial class Administration
return;
try
{
await targetUser.RemoveRoleAsync(roleToRemove).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.remrole(Format.Bold(roleToRemove.Name), Format.Bold(targetUser.ToString()))).ConfigureAwait(false);
await targetUser.RemoveRoleAsync(roleToRemove);
await ReplyConfirmLocalizedAsync(strs.remrole(Format.Bold(roleToRemove.Name), Format.Bold(targetUser.ToString())));
}
catch
{
await ReplyErrorLocalizedAsync(strs.remrole_err).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.remrole_err);
}
}
@ -236,17 +235,17 @@ public partial class Administration
return;
try
{
if (roleToEdit.Position > (await ctx.Guild.GetCurrentUserAsync().ConfigureAwait(false)).GetRoles().Max(r => r.Position))
if (roleToEdit.Position > (await ctx.Guild.GetCurrentUserAsync()).GetRoles().Max(r => r.Position))
{
await ReplyErrorLocalizedAsync(strs.renrole_perms).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.renrole_perms);
return;
}
await roleToEdit.ModifyAsync(g => g.Name = newname).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.renrole).ConfigureAwait(false);
await roleToEdit.ModifyAsync(g => g.Name = newname);
await ReplyConfirmLocalizedAsync(strs.renrole);
}
catch (Exception)
{
await ReplyErrorLocalizedAsync(strs.renrole_err).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.renrole_err);
}
}
@ -266,12 +265,12 @@ public partial class Administration
return;
try
{
await user.RemoveRolesAsync(userRoles).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.rar(Format.Bold(user.ToString()))).ConfigureAwait(false);
await user.RemoveRolesAsync(userRoles);
await ReplyConfirmLocalizedAsync(strs.rar(Format.Bold(user.ToString())));
}
catch (Exception)
{
await ReplyErrorLocalizedAsync(strs.rar_err).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.rar_err);
}
}
@ -284,8 +283,8 @@ public partial class Administration
if (string.IsNullOrWhiteSpace(roleName))
return;
var r = await ctx.Guild.CreateRoleAsync(roleName, isMentionable: false).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.cr(Format.Bold(r.Name))).ConfigureAwait(false);
var r = await ctx.Guild.CreateRoleAsync(roleName, isMentionable: false);
await ReplyConfirmLocalizedAsync(strs.cr(Format.Bold(r.Name)));
}
[NadekoCommand, Aliases]
@ -299,8 +298,8 @@ public partial class Administration
&& guser.GetRoles().Max(x => x.Position) <= role.Position)
return;
await role.DeleteAsync().ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.dr(Format.Bold(role.Name))).ConfigureAwait(false);
await role.DeleteAsync();
await ReplyConfirmLocalizedAsync(strs.dr(Format.Bold(role.Name)));
}
[NadekoCommand, Aliases]
@ -310,14 +309,14 @@ public partial class Administration
public async Task RoleHoist(IRole role)
{
var newHoisted = !role.IsHoisted;
await role.ModifyAsync(r => r.Hoist = newHoisted).ConfigureAwait(false);
await role.ModifyAsync(r => r.Hoist = newHoisted);
if (newHoisted)
{
await ReplyConfirmLocalizedAsync(strs.rolehoist_enabled(Format.Bold(role.Name))).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.rolehoist_enabled(Format.Bold(role.Name)));
}
else
{
await ReplyConfirmLocalizedAsync(strs.rolehoist_disabled(Format.Bold(role.Name))).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.rolehoist_disabled(Format.Bold(role.Name)));
}
}
@ -325,7 +324,7 @@ public partial class Administration
[RequireContext(ContextType.Guild)]
[Priority(1)]
public async Task RoleColor([Leftover] IRole role)
=> await SendConfirmAsync("Role Color", role.Color.RawValue.ToString("x6")).ConfigureAwait(false);
=> await SendConfirmAsync("Role Color", role.Color.RawValue.ToString("x6"));
[NadekoCommand, Aliases]
[RequireContext(ContextType.Guild)]
@ -337,12 +336,12 @@ public partial class Administration
try
{
var rgba32 = color.ToPixel<Rgba32>();
await role.ModifyAsync(r => r.Color = new Color(rgba32.R, rgba32.G, rgba32.B)).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.rc(Format.Bold(role.Name))).ConfigureAwait(false);
await role.ModifyAsync(r => r.Color = new Color(rgba32.R, rgba32.G, rgba32.B));
await ReplyConfirmLocalizedAsync(strs.rc(Format.Bold(role.Name)));
}
catch (Exception)
{
await ReplyErrorLocalizedAsync(strs.rc_perms).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.rc_perms);
}
}
}

View file

@ -1,4 +1,4 @@
#nullable disable
#nullable disable
using System.Text;
using NadekoBot.Modules.Administration.Services;
@ -50,11 +50,11 @@ public partial class Administration
if (succ)
{
await ReplyConfirmLocalizedAsync(strs.role_added(Format.Bold(role.Name), Format.Bold(group.ToString()))).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.role_added(Format.Bold(role.Name), Format.Bold(group.ToString())));
}
else
{
await ReplyErrorLocalizedAsync(strs.role_in_list(Format.Bold(role.Name))).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.role_in_list(Format.Bold(role.Name)));
}
}
@ -67,15 +67,15 @@ public partial class Administration
{
var guser = (IGuildUser)ctx.User;
var set = await _service.SetNameAsync(ctx.Guild.Id, group, name).ConfigureAwait(false);
var set = await _service.SetNameAsync(ctx.Guild.Id, group, name);
if (set)
{
await ReplyConfirmLocalizedAsync(strs.group_name_added(Format.Bold(group.ToString()), Format.Bold(name.ToString()))).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.group_name_added(Format.Bold(group.ToString()), Format.Bold(name.ToString())));
}
else
{
await ReplyConfirmLocalizedAsync(strs.group_name_removed(Format.Bold(group.ToString()))).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.group_name_removed(Format.Bold(group.ToString())));
}
}
@ -91,11 +91,11 @@ public partial class Administration
var success = _service.RemoveSar(role.Guild.Id, role.Id);
if (!success)
{
await ReplyErrorLocalizedAsync(strs.self_assign_not).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.self_assign_not);
}
else
{
await ReplyConfirmLocalizedAsync(strs.self_assign_rem(Format.Bold(role.Name))).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.self_assign_rem(Format.Bold(role.Name)));
}
}
@ -155,7 +155,7 @@ public partial class Administration
.WithFooter(exclusive
? GetText(strs.self_assign_are_exclusive)
: GetText(strs.self_assign_are_not_exclusive));
}, roles.Count(), 20).ConfigureAwait(false);
}, roles.Count(), 20);
}
[NadekoCommand, Aliases]
@ -166,9 +166,9 @@ public partial class Administration
{
var areExclusive = _service.ToggleEsar(ctx.Guild.Id);
if (areExclusive)
await ReplyConfirmLocalizedAsync(strs.self_assign_excl).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.self_assign_excl);
else
await ReplyConfirmLocalizedAsync(strs.self_assign_no_excl).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.self_assign_no_excl);
}
[NadekoCommand, Aliases]
@ -184,7 +184,7 @@ public partial class Administration
if (!succ)
{
await ReplyErrorLocalizedAsync(strs.self_assign_not).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.self_assign_not);
return;
}
@ -199,28 +199,28 @@ public partial class Administration
{
var guildUser = (IGuildUser)ctx.User;
var (result, autoDelete, extra) = await _service.Assign(guildUser, role).ConfigureAwait(false);
var (result, autoDelete, extra) = await _service.Assign(guildUser, role);
IUserMessage msg;
if (result == SelfAssignedRolesService.AssignResult.Err_Not_Assignable)
{
msg = await ReplyErrorLocalizedAsync(strs.self_assign_not).ConfigureAwait(false);
msg = await ReplyErrorLocalizedAsync(strs.self_assign_not);
}
else if (result == SelfAssignedRolesService.AssignResult.Err_Lvl_Req)
{
msg = await ReplyErrorLocalizedAsync(strs.self_assign_not_level(Format.Bold(extra.ToString()))).ConfigureAwait(false);
msg = await ReplyErrorLocalizedAsync(strs.self_assign_not_level(Format.Bold(extra.ToString())));
}
else if (result == SelfAssignedRolesService.AssignResult.Err_Already_Have)
{
msg = await ReplyErrorLocalizedAsync(strs.self_assign_already(Format.Bold(role.Name))).ConfigureAwait(false);
msg = await ReplyErrorLocalizedAsync(strs.self_assign_already(Format.Bold(role.Name)));
}
else if (result == SelfAssignedRolesService.AssignResult.Err_Not_Perms)
{
msg = await ReplyErrorLocalizedAsync(strs.self_assign_perms).ConfigureAwait(false);
msg = await ReplyErrorLocalizedAsync(strs.self_assign_perms);
}
else
{
msg = await ReplyConfirmLocalizedAsync(strs.self_assign_success(Format.Bold(role.Name))).ConfigureAwait(false);
msg = await ReplyConfirmLocalizedAsync(strs.self_assign_success(Format.Bold(role.Name)));
}
if (autoDelete)
@ -236,24 +236,24 @@ public partial class Administration
{
var guildUser = (IGuildUser)ctx.User;
var (result, autoDelete) = await _service.Remove(guildUser, role).ConfigureAwait(false);
var (result, autoDelete) = await _service.Remove(guildUser, role);
IUserMessage msg;
if (result == SelfAssignedRolesService.RemoveResult.Err_Not_Assignable)
{
msg = await ReplyErrorLocalizedAsync(strs.self_assign_not).ConfigureAwait(false);
msg = await ReplyErrorLocalizedAsync(strs.self_assign_not);
}
else if (result == SelfAssignedRolesService.RemoveResult.Err_Not_Have)
{
msg = await ReplyErrorLocalizedAsync(strs.self_assign_not_have(Format.Bold(role.Name))).ConfigureAwait(false);
msg = await ReplyErrorLocalizedAsync(strs.self_assign_not_have(Format.Bold(role.Name)));
}
else if (result == SelfAssignedRolesService.RemoveResult.Err_Not_Perms)
{
msg = await ReplyErrorLocalizedAsync(strs.self_assign_perms).ConfigureAwait(false);
msg = await ReplyErrorLocalizedAsync(strs.self_assign_perms);
}
else
{
msg = await ReplyConfirmLocalizedAsync(strs.self_assign_remove(Format.Bold(role.Name))).ConfigureAwait(false);
msg = await ReplyConfirmLocalizedAsync(strs.self_assign_remove(Format.Bold(role.Name)));
}
if (autoDelete)

View file

@ -94,7 +94,7 @@ public partial class Administration
if (scmds.Count == 0)
{
await ReplyErrorLocalizedAsync(strs.startcmdlist_none).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.startcmdlist_none);
}
else
{
@ -107,8 +107,7 @@ public partial class Administration
[{GetText(strs.channel)}]: {x.ChannelName} #{x.ChannelId}
[{GetText(strs.command_text)}]: {x.CommandText}```")),
title: string.Empty,
footer: GetText(strs.page(page + 1)))
.ConfigureAwait(false);
footer: GetText(strs.page(page + 1)));
}
}
@ -126,7 +125,7 @@ public partial class Administration
.ToList();
if (!scmds.Any())
{
await ReplyErrorLocalizedAsync(strs.autocmdlist_none).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.autocmdlist_none);
}
else
{
@ -140,8 +139,7 @@ public partial class Administration
{GetIntervalText(x.Interval)}
[{GetText(strs.command_text)}]: {x.CommandText}```")),
title: string.Empty,
footer: GetText(strs.page(page + 1)))
.ConfigureAwait(false);
footer: GetText(strs.page(page + 1)));
}
}
@ -157,13 +155,12 @@ public partial class Administration
ctx.Message.DeleteAfter(0);
try
{
var msg = await SendConfirmAsync($"⏲ {miliseconds}ms")
.ConfigureAwait(false);
var msg = await SendConfirmAsync($"⏲ {miliseconds}ms");
msg.DeleteAfter(miliseconds / 1000);
}
catch { }
await Task.Delay(miliseconds).ConfigureAwait(false);
await Task.Delay(miliseconds);
}
[NadekoCommand, Aliases]
@ -174,7 +171,7 @@ public partial class Administration
{
if (!_service.RemoveAutoCommand(--index, out _))
{
await ReplyErrorLocalizedAsync(strs.acrm_fail).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.acrm_fail);
return;
}
@ -187,9 +184,9 @@ public partial class Administration
public async Task StartupCommandRemove([Leftover] int index)
{
if (!_service.RemoveStartupCommand(--index, out _))
await ReplyErrorLocalizedAsync(strs.scrm_fail).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.scrm_fail);
else
await ReplyConfirmLocalizedAsync(strs.scrm).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.scrm);
}
[NadekoCommand, Aliases]
@ -200,7 +197,7 @@ public partial class Administration
{
_service.ClearStartupCommands();
await ReplyConfirmLocalizedAsync(strs.startcmds_cleared).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.startcmds_cleared);
}
[NadekoCommand, Aliases]
@ -210,9 +207,9 @@ public partial class Administration
var enabled = _service.ForwardMessages();
if (enabled)
await ReplyConfirmLocalizedAsync(strs.fwdm_start).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.fwdm_start);
else
await ReplyPendingLocalizedAsync(strs.fwdm_stop).ConfigureAwait(false);
await ReplyPendingLocalizedAsync(strs.fwdm_stop);
}
[NadekoCommand, Aliases]
@ -222,9 +219,9 @@ public partial class Administration
var enabled = _service.ForwardToAll();
if (enabled)
await ReplyConfirmLocalizedAsync(strs.fwall_start).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.fwall_start);
else
await ReplyPendingLocalizedAsync(strs.fwall_stop).ConfigureAwait(false);
await ReplyPendingLocalizedAsync(strs.fwall_stop);
}
@ -264,7 +261,7 @@ public partial class Administration
return _eb.Create()
.WithOkColor()
.WithDescription($"{status}\n\n{str}");
}, allShardStrings.Length, 25).ConfigureAwait(false);
}, allShardStrings.Length, 25);
}
private static string ConnectionStateToEmoji(ShardStatus status)
@ -286,11 +283,11 @@ public partial class Administration
var success = _coord.RestartShard(shardId);
if (success)
{
await ReplyConfirmLocalizedAsync(strs.shard_reconnecting(Format.Bold("#" + shardId))).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.shard_reconnecting(Format.Bold("#" + shardId)));
}
else
{
await ReplyErrorLocalizedAsync(strs.no_shard_id).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.no_shard_id);
}
}
@ -306,13 +303,13 @@ public partial class Administration
{
try
{
await ReplyConfirmLocalizedAsync(strs.shutting_down).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.shutting_down);
}
catch
{
// ignored
}
await Task.Delay(2000).ConfigureAwait(false);
await Task.Delay(2000);
_coord.Die(graceful);
}
@ -323,11 +320,11 @@ public partial class Administration
var success = _coord.RestartBot();
if (!success)
{
await ReplyErrorLocalizedAsync(strs.restart_fail).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.restart_fail);
return;
}
try { await ReplyConfirmLocalizedAsync(strs.restarting).ConfigureAwait(false); } catch { }
try { await ReplyConfirmLocalizedAsync(strs.restarting); } catch { }
}
[NadekoCommand, Aliases]
@ -339,14 +336,14 @@ public partial class Administration
try
{
await _client.CurrentUser.ModifyAsync(u => u.Username = newName).ConfigureAwait(false);
await _client.CurrentUser.ModifyAsync(u => u.Username = newName);
}
catch (RateLimitedException)
{
Log.Warning("You've been ratelimited. Wait 2 hours to change your name");
}
await ReplyConfirmLocalizedAsync(strs.bot_name(Format.Bold(newName))).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.bot_name(Format.Bold(newName)));
}
[NadekoCommand, Aliases]
@ -357,8 +354,8 @@ public partial class Administration
{
if (string.IsNullOrWhiteSpace(newNick))
return;
var curUser = await ctx.Guild.GetCurrentUserAsync().ConfigureAwait(false);
await curUser.ModifyAsync(u => u.Nickname = newNick).ConfigureAwait(false);
var curUser = await ctx.Guild.GetCurrentUserAsync();
await curUser.ModifyAsync(u => u.Nickname = newNick);
await ReplyConfirmLocalizedAsync(strs.bot_nick(Format.Bold(newNick) ?? "-"));
}
@ -377,7 +374,7 @@ public partial class Administration
return;
}
await gu.ModifyAsync(u => u.Nickname = newNick).ConfigureAwait(false);
await gu.ModifyAsync(u => u.Nickname = newNick);
await ReplyConfirmLocalizedAsync(strs.user_nick(Format.Bold(gu.ToString()), Format.Bold(newNick) ?? "-"));
}
@ -386,9 +383,9 @@ public partial class Administration
[OwnerOnly]
public async Task SetStatus([Leftover] SettableUserStatus status)
{
await _client.SetStatusAsync(SettableUserStatusToUserStatus(status)).ConfigureAwait(false);
await _client.SetStatusAsync(SettableUserStatusToUserStatus(status));
await ReplyConfirmLocalizedAsync(strs.bot_status(Format.Bold(status.ToString()))).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.bot_status(Format.Bold(status.ToString())));
}
[NadekoCommand, Aliases]
@ -399,7 +396,7 @@ public partial class Administration
if (success)
{
await ReplyConfirmLocalizedAsync(strs.set_avatar).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.set_avatar);
}
}
@ -411,9 +408,9 @@ public partial class Administration
.WithDefault(Context)
.Build();
await _service.SetGameAsync(game is null ? game : rep.Replace(game), type).ConfigureAwait(false);
await _service.SetGameAsync(game is null ? game : rep.Replace(game), type);
await ReplyConfirmLocalizedAsync(strs.set_game).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.set_game);
}
[NadekoCommand, Aliases]
@ -422,9 +419,9 @@ public partial class Administration
{
name ??= "";
await _service.SetStreamAsync(name, url).ConfigureAwait(false);
await _service.SetStreamAsync(name, url);
await ReplyConfirmLocalizedAsync(strs.set_stream).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.set_stream);
}
[NadekoCommand, Aliases]
@ -468,11 +465,11 @@ public partial class Administration
}
else
{
await ReplyErrorLocalizedAsync(strs.invalid_format).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.invalid_format);
return;
}
await ReplyConfirmLocalizedAsync(strs.message_sent).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.message_sent);
}
[NadekoCommand, Aliases]
@ -488,7 +485,7 @@ public partial class Administration
public async Task StringsReload()
{
_strings.Reload();
await ReplyConfirmLocalizedAsync(strs.bot_strings_reloaded).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.bot_strings_reloaded);
}
[NadekoCommand, Aliases]

View file

@ -1,4 +1,4 @@
#nullable disable
#nullable disable
using Microsoft.EntityFrameworkCore;
using NadekoBot.Services.Database.Models;
using NadekoBot.Db;
@ -52,14 +52,14 @@ public class AdministrationService : INService
if (state && cmd.Name != "prune" && cmd.Name != "pick")
{
_logService.AddDeleteIgnore(msg.Id);
try { await msg.DeleteAsync().ConfigureAwait(false); } catch { }
try { await msg.DeleteAsync(); } catch { }
}
//if state is false, that means do not do it
}
else if (DeleteMessagesOnCommand.Contains(channel.Guild.Id) && cmd.Name != "prune" && cmd.Name != "pick")
{
_logService.AddDeleteIgnore(msg.Id);
try { await msg.DeleteAsync().ConfigureAwait(false); } catch { }
try { await msg.DeleteAsync(); } catch { }
}
});
return Task.CompletedTask;
@ -128,7 +128,7 @@ public class AdministrationService : INService
{
try
{
await u.ModifyAsync(usr => usr.Deaf = value).ConfigureAwait(false);
await u.ModifyAsync(usr => usr.Deaf = value);
}
catch
{

View file

@ -1,4 +1,4 @@
#nullable disable
#nullable disable
using System.Threading.Channels;
using LinqToDB;
using Microsoft.EntityFrameworkCore;
@ -50,8 +50,8 @@ public sealed class AutoAssignRoleService : INService
if (roleIds.Any())
{
await user.AddRolesAsync(roleIds).ConfigureAwait(false);
await Task.Delay(250).ConfigureAwait(false);
await user.AddRolesAsync(roleIds);
await Task.Delay(250);
}
else
{

View file

@ -118,7 +118,7 @@ public class GameVoiceChannelService : INService
if (vch is null)
return;
await Task.Delay(1000).ConfigureAwait(false);
await gUser.ModifyAsync(gu => gu.Channel = vch).ConfigureAwait(false);
await Task.Delay(1000);
await gUser.ModifyAsync(gu => gu.Channel = vch);
}
}

View file

@ -90,7 +90,7 @@ public sealed class LogCommandService : ILogCommandService
{
var keys = PresenceUpdates.Keys.ToList();
await Task.WhenAll(keys.Select(key =>
await keys.Select(key =>
{
if (!((SocketGuild) key.Guild).CurrentUser.GetPermissions(key).SendMessages)
return Task.CompletedTask;
@ -102,7 +102,7 @@ public sealed class LogCommandService : ILogCommandService
}
return Task.CompletedTask;
})).ConfigureAwait(false);
}).WhenAll();
}, null, TimeSpan.FromSeconds(15), TimeSpan.FromSeconds(15));
//_client.MessageReceived += _client_MessageReceived;
@ -229,7 +229,7 @@ public sealed class LogCommandService : ILogCommandService
ITextChannel logChannel;
if ((logChannel =
await TryGetLogChannel(g, logSetting, LogType.UserUpdated).ConfigureAwait(false)) is null)
await TryGetLogChannel(g, logSetting, LogType.UserUpdated)) is null)
return;
var embed = _eb.Create();
@ -263,7 +263,7 @@ public sealed class LogCommandService : ILogCommandService
return;
}
await logChannel.EmbedAsync(embed).ConfigureAwait(false);
await logChannel.EmbedAsync(embed);
}
catch
{
@ -360,8 +360,7 @@ public sealed class LogCommandService : ILogCommandService
return;
ITextChannel logChannel;
if ((logChannel = await TryGetLogChannel(usr.Guild, logSetting, LogType.VoicePresenceTTS)
.ConfigureAwait(false)) is null)
if ((logChannel = await TryGetLogChannel(usr.Guild, logSetting, LogType.VoicePresenceTTS)) is null)
return;
var str = string.Empty;
@ -378,7 +377,7 @@ public sealed class LogCommandService : ILogCommandService
str = GetText(logChannel.Guild, strs.log_vc_left(usr.Username, beforeVch.Name));
}
var toDelete = await logChannel.SendMessageAsync(str, true).ConfigureAwait(false);
var toDelete = await logChannel.SendMessageAsync(str, true);
toDelete.DeleteAfter(5);
}
catch
@ -400,8 +399,7 @@ public sealed class LogCommandService : ILogCommandService
return;
ITextChannel logChannel;
if ((logChannel = await TryGetLogChannel(usr.Guild, logSetting, LogType.UserMuted)
.ConfigureAwait(false)) is null)
if ((logChannel = await TryGetLogChannel(usr.Guild, logSetting, LogType.UserMuted)) is null)
return;
var mutes = string.Empty;
var mutedLocalized = GetText(logChannel.Guild, strs.muted_sn);
@ -424,7 +422,7 @@ public sealed class LogCommandService : ILogCommandService
.WithFooter(CurrentTime(usr.Guild))
.WithOkColor();
await logChannel.EmbedAsync(embed).ConfigureAwait(false);
await logChannel.EmbedAsync(embed);
}
catch
{
@ -444,8 +442,7 @@ public sealed class LogCommandService : ILogCommandService
return;
ITextChannel logChannel;
if ((logChannel = await TryGetLogChannel(usr.Guild, logSetting, LogType.UserMuted)
.ConfigureAwait(false)) is null)
if ((logChannel = await TryGetLogChannel(usr.Guild, logSetting, LogType.UserMuted)) is null)
return;
var mutes = string.Empty;
@ -472,7 +469,7 @@ public sealed class LogCommandService : ILogCommandService
if (!string.IsNullOrWhiteSpace(reason))
embed.WithDescription(reason);
await logChannel.EmbedAsync(embed).ConfigureAwait(false);
await logChannel.EmbedAsync(embed);
}
catch
{
@ -495,8 +492,7 @@ public sealed class LogCommandService : ILogCommandService
|| logSetting.LogOtherId is null)
return;
ITextChannel logChannel;
if ((logChannel = await TryGetLogChannel(users.First().Guild, logSetting, LogType.Other)
.ConfigureAwait(false)) is null)
if ((logChannel = await TryGetLogChannel(users.First().Guild, logSetting, LogType.Other)) is null)
return;
var punishment = string.Empty;
@ -525,7 +521,7 @@ public sealed class LogCommandService : ILogCommandService
.WithFooter(CurrentTime(logChannel.Guild))
.WithOkColor();
await logChannel.EmbedAsync(embed).ConfigureAwait(false);
await logChannel.EmbedAsync(embed);
}
catch
{
@ -570,8 +566,7 @@ public sealed class LogCommandService : ILogCommandService
ITextChannel logChannel;
if (logSetting.UserUpdatedId != null &&
(logChannel = await TryGetLogChannel(before.Guild, logSetting, LogType.UserUpdated)
.ConfigureAwait(false)) != null)
(logChannel = await TryGetLogChannel(before.Guild, logSetting, LogType.UserUpdated)) != null)
{
var embed = _eb.Create().WithOkColor()
.WithFooter(CurrentTime(before.Guild))
@ -584,7 +579,7 @@ public sealed class LogCommandService : ILogCommandService
.AddField(GetText(logChannel.Guild, strs.new_nick)
, $"{after.Nickname}#{after.Discriminator}");
await logChannel.EmbedAsync(embed).ConfigureAwait(false);
await logChannel.EmbedAsync(embed);
}
else if (!before.Roles.SequenceEqual(after.Roles))
{
@ -594,7 +589,7 @@ public sealed class LogCommandService : ILogCommandService
embed.WithAuthor("⚔ " + GetText(logChannel.Guild, strs.user_role_add))
.WithDescription(string.Join(", ", diffRoles).SanitizeMentions());
await logChannel.EmbedAsync(embed).ConfigureAwait(false);
await logChannel.EmbedAsync(embed);
}
else if (before.Roles.Count > after.Roles.Count)
{
@ -609,7 +604,7 @@ public sealed class LogCommandService : ILogCommandService
embed.WithAuthor("⚔ " + GetText(logChannel.Guild, strs.user_role_rem))
.WithDescription(string.Join(", ", diffRoles).SanitizeMentions());
await logChannel.EmbedAsync(embed).ConfigureAwait(false);
await logChannel.EmbedAsync(embed);
}
}
}
@ -617,8 +612,7 @@ public sealed class LogCommandService : ILogCommandService
logChannel = null;
if (!before.IsBot && logSetting.LogUserPresenceId != null && (logChannel =
await TryGetLogChannel(before.Guild, logSetting, LogType.UserPresence)
.ConfigureAwait(false)) != null)
await TryGetLogChannel(before.Guild, logSetting, LogType.UserPresence)) != null)
{
if (before.Status != after.Status)
{
@ -671,8 +665,7 @@ public sealed class LogCommandService : ILogCommandService
return;
ITextChannel logChannel;
if ((logChannel = await TryGetLogChannel(before.Guild, logSetting, LogType.ChannelUpdated)
.ConfigureAwait(false)) is null)
if ((logChannel = await TryGetLogChannel(before.Guild, logSetting, LogType.ChannelUpdated)) is null)
return;
var embed = _eb.Create().WithOkColor()
@ -697,7 +690,7 @@ public sealed class LogCommandService : ILogCommandService
else
return;
await logChannel.EmbedAsync(embed).ConfigureAwait(false);
await logChannel.EmbedAsync(embed);
}
catch
{
@ -722,8 +715,7 @@ public sealed class LogCommandService : ILogCommandService
return;
ITextChannel logChannel;
if ((logChannel = await TryGetLogChannel(ch.Guild, logSetting, LogType.ChannelDestroyed)
.ConfigureAwait(false)) is null)
if ((logChannel = await TryGetLogChannel(ch.Guild, logSetting, LogType.ChannelDestroyed)) is null)
return;
string title;
if (ch is IVoiceChannel)
@ -737,7 +729,7 @@ public sealed class LogCommandService : ILogCommandService
.WithOkColor()
.WithTitle("🆕 " + title)
.WithDescription($"{ch.Name} | {ch.Id}")
.WithFooter(CurrentTime(ch.Guild))).ConfigureAwait(false);
.WithFooter(CurrentTime(ch.Guild)));
}
catch
{
@ -761,8 +753,7 @@ public sealed class LogCommandService : ILogCommandService
return;
ITextChannel logChannel;
if ((logChannel = await TryGetLogChannel(ch.Guild, logSetting, LogType.ChannelCreated)
.ConfigureAwait(false)) is null)
if ((logChannel = await TryGetLogChannel(ch.Guild, logSetting, LogType.ChannelCreated)) is null)
return;
string title;
if (ch is IVoiceChannel)
@ -776,7 +767,7 @@ public sealed class LogCommandService : ILogCommandService
.WithOkColor()
.WithTitle("🆕 " + title)
.WithDescription($"{ch.Name} | {ch.Id}")
.WithFooter(CurrentTime(ch.Guild))).ConfigureAwait(false);
.WithFooter(CurrentTime(ch.Guild)));
}
catch (Exception)
{
@ -807,8 +798,7 @@ public sealed class LogCommandService : ILogCommandService
return;
ITextChannel logChannel;
if ((logChannel = await TryGetLogChannel(usr.Guild, logSetting, LogType.VoicePresence)
.ConfigureAwait(false)) is null)
if ((logChannel = await TryGetLogChannel(usr.Guild, logSetting, LogType.VoicePresence)) is null)
return;
string str = null;
@ -860,8 +850,7 @@ public sealed class LogCommandService : ILogCommandService
return;
ITextChannel logChannel;
if ((logChannel = await TryGetLogChannel(guild, logSetting, LogType.UserLeft)
.ConfigureAwait(false)) is null)
if ((logChannel = await TryGetLogChannel(guild, logSetting, LogType.UserLeft)) is null)
return;
var embed = _eb.Create()
.WithOkColor()
@ -873,7 +862,7 @@ public sealed class LogCommandService : ILogCommandService
if (Uri.IsWellFormedUriString(usr.GetAvatarUrl(), UriKind.Absolute))
embed.WithThumbnailUrl(usr.GetAvatarUrl());
await logChannel.EmbedAsync(embed).ConfigureAwait(false);
await logChannel.EmbedAsync(embed);
}
catch
{
@ -894,8 +883,7 @@ public sealed class LogCommandService : ILogCommandService
return;
ITextChannel logChannel;
if ((logChannel = await TryGetLogChannel(usr.Guild, logSetting, LogType.UserJoined)
.ConfigureAwait(false)) is null)
if ((logChannel = await TryGetLogChannel(usr.Guild, logSetting, LogType.UserJoined)) is null)
return;
var embed = _eb.Create()
@ -914,7 +902,7 @@ public sealed class LogCommandService : ILogCommandService
if (Uri.IsWellFormedUriString(usr.GetAvatarUrl(), UriKind.Absolute))
embed.WithThumbnailUrl(usr.GetAvatarUrl());
await logChannel.EmbedAsync(embed).ConfigureAwait(false);
await logChannel.EmbedAsync(embed);
}
catch (Exception)
{
@ -936,8 +924,7 @@ public sealed class LogCommandService : ILogCommandService
return;
ITextChannel logChannel;
if ((logChannel = await TryGetLogChannel(guild, logSetting, LogType.UserUnbanned)
.ConfigureAwait(false)) is null)
if ((logChannel = await TryGetLogChannel(guild, logSetting, LogType.UserUnbanned)) is null)
return;
var embed = _eb.Create()
.WithOkColor()
@ -949,7 +936,7 @@ public sealed class LogCommandService : ILogCommandService
if (Uri.IsWellFormedUriString(usr.GetAvatarUrl(), UriKind.Absolute))
embed.WithThumbnailUrl(usr.GetAvatarUrl());
await logChannel.EmbedAsync(embed).ConfigureAwait(false);
await logChannel.EmbedAsync(embed);
}
catch (Exception)
{
@ -972,7 +959,7 @@ public sealed class LogCommandService : ILogCommandService
ITextChannel logChannel;
if ((logChannel =
await TryGetLogChannel(guild, logSetting, LogType.UserBanned).ConfigureAwait(false)) ==
await TryGetLogChannel(guild, logSetting, LogType.UserBanned)) ==
null)
return;
var embed = _eb.Create()
@ -987,7 +974,7 @@ public sealed class LogCommandService : ILogCommandService
if (Uri.IsWellFormedUriString(avatarUrl, UriKind.Absolute))
embed.WithThumbnailUrl(usr.GetAvatarUrl());
await logChannel.EmbedAsync(embed).ConfigureAwait(false);
await logChannel.EmbedAsync(embed);
}
catch (Exception)
{
@ -1019,8 +1006,7 @@ public sealed class LogCommandService : ILogCommandService
return;
ITextChannel logChannel;
if ((logChannel = await TryGetLogChannel(channel.Guild, logSetting, LogType.MessageDeleted)
.ConfigureAwait(false)) is null || logChannel.Id == msg.Id)
if ((logChannel = await TryGetLogChannel(channel.Guild, logSetting, LogType.MessageDeleted)) is null || logChannel.Id == msg.Id)
return;
var resolvedMessage = msg.Resolve(userHandling: TagHandling.FullName);
@ -1038,7 +1024,7 @@ public sealed class LogCommandService : ILogCommandService
string.Join(", ", msg.Attachments.Select(a => a.Url)),
false);
await logChannel.EmbedAsync(embed).ConfigureAwait(false);
await logChannel.EmbedAsync(embed);
}
catch (Exception)
{
@ -1076,8 +1062,7 @@ public sealed class LogCommandService : ILogCommandService
return;
ITextChannel logChannel;
if ((logChannel = await TryGetLogChannel(channel.Guild, logSetting, LogType.MessageUpdated)
.ConfigureAwait(false)) is null || logChannel.Id == after.Channel.Id)
if ((logChannel = await TryGetLogChannel(channel.Guild, logSetting, LogType.MessageUpdated)) is null || logChannel.Id == after.Channel.Id)
return;
var embed = _eb.Create()
@ -1098,7 +1083,7 @@ public sealed class LogCommandService : ILogCommandService
.AddField("Id", after.Id.ToString(), false)
.WithFooter(CurrentTime(channel.Guild));
await logChannel.EmbedAsync(embed).ConfigureAwait(false);
await logChannel.EmbedAsync(embed);
}
catch
{
@ -1166,7 +1151,7 @@ public sealed class LogCommandService : ILogCommandService
return null;
}
var channel = await guild.GetTextChannelAsync(id.Value).ConfigureAwait(false);
var channel = await guild.GetTextChannelAsync(id.Value);
if (channel is null)
{

View file

@ -1,4 +1,4 @@
#nullable disable
#nullable disable
using Microsoft.EntityFrameworkCore;
using NadekoBot.Services.Database.Models;
using NadekoBot.Db;
@ -152,7 +152,7 @@ public class MuteService : INService
if (muted is null || !muted.Contains(usr.Id))
return Task.CompletedTask;
var _ = Task.Run(() => MuteUser(usr, _client.CurrentUser, reason: "Sticky mute").ConfigureAwait(false));
var _ = Task.Run(() => MuteUser(usr, _client.CurrentUser, reason: "Sticky mute"));
}
catch (Exception ex)
{
@ -174,10 +174,10 @@ public class MuteService : INService
{
if (type == MuteType.All)
{
try { await usr.ModifyAsync(x => x.Mute = true).ConfigureAwait(false); } catch { }
var muteRole = await GetMuteRole(usr.Guild).ConfigureAwait(false);
try { await usr.ModifyAsync(x => x.Mute = true); } catch { }
var muteRole = await GetMuteRole(usr.Guild);
if (!usr.RoleIds.Contains(muteRole.Id))
await usr.AddRoleAsync(muteRole).ConfigureAwait(false);
await usr.AddRoleAsync(muteRole);
StopTimer(usr.GuildId, usr.Id, TimerType.Mute);
await using (var uow = _db.GetDbContext())
{
@ -201,14 +201,14 @@ public class MuteService : INService
{
try
{
await usr.ModifyAsync(x => x.Mute = true).ConfigureAwait(false);
await usr.ModifyAsync(x => x.Mute = true);
UserMuted(usr, mod, MuteType.Voice, reason);
}
catch { }
}
else if (type == MuteType.Chat)
{
await usr.AddRoleAsync(await GetMuteRole(usr.Guild).ConfigureAwait(false)).ConfigureAwait(false);
await usr.AddRoleAsync(await GetMuteRole(usr.Guild));
UserMuted(usr, mod, MuteType.Chat, reason);
}
}
@ -241,8 +241,8 @@ public class MuteService : INService
}
if (usr != null)
{
try { await usr.ModifyAsync(x => x.Mute = false).ConfigureAwait(false); } catch { }
try { await usr.RemoveRoleAsync(await GetMuteRole(usr.Guild).ConfigureAwait(false)).ConfigureAwait(false); } catch { /*ignore*/ }
try { await usr.ModifyAsync(x => x.Mute = false); } catch { }
try { await usr.RemoveRoleAsync(await GetMuteRole(usr.Guild)); } catch { /*ignore*/ }
UserUnmuted(usr, mod, MuteType.All, reason);
}
}
@ -252,7 +252,7 @@ public class MuteService : INService
return;
try
{
await usr.ModifyAsync(x => x.Mute = false).ConfigureAwait(false);
await usr.ModifyAsync(x => x.Mute = false);
UserUnmuted(usr, mod, MuteType.Voice, reason);
}
catch { }
@ -261,7 +261,7 @@ public class MuteService : INService
{
if (usr is null)
return;
await usr.RemoveRoleAsync(await GetMuteRole(usr.Guild).ConfigureAwait(false)).ConfigureAwait(false);
await usr.RemoveRoleAsync(await GetMuteRole(usr.Guild));
UserUnmuted(usr, mod, MuteType.Chat, reason);
}
}
@ -280,26 +280,25 @@ public class MuteService : INService
{
//if it doesn't exist, create it
try { muteRole = await guild.CreateRoleAsync(muteRoleName, isMentionable: false).ConfigureAwait(false); }
try { muteRole = await guild.CreateRoleAsync(muteRoleName, isMentionable: false); }
catch
{
//if creations fails, maybe the name is not correct, find default one, if doesn't work, create default one
muteRole = guild.Roles.FirstOrDefault(r => r.Name == muteRoleName) ??
await guild.CreateRoleAsync(defaultMuteRoleName, isMentionable: false).ConfigureAwait(false);
await guild.CreateRoleAsync(defaultMuteRoleName, isMentionable: false);
}
}
foreach (var toOverwrite in await guild.GetTextChannelsAsync().ConfigureAwait(false))
foreach (var toOverwrite in await guild.GetTextChannelsAsync())
{
try
{
if (!toOverwrite.PermissionOverwrites.Any(x => x.TargetId == muteRole.Id
&& x.TargetType == PermissionTarget.Role))
{
await toOverwrite.AddPermissionOverwriteAsync(muteRole, denyOverwrite)
.ConfigureAwait(false);
await toOverwrite.AddPermissionOverwriteAsync(muteRole, denyOverwrite);
await Task.Delay(200).ConfigureAwait(false);
await Task.Delay(200);
}
}
catch
@ -313,7 +312,7 @@ public class MuteService : INService
public async Task TimedMute(IGuildUser user, IUser mod, TimeSpan after, MuteType muteType = MuteType.All, string reason = "")
{
await MuteUser(user, mod, muteType, reason).ConfigureAwait(false); // mute the user. This will also remove any previous unmute timers
await MuteUser(user, mod, muteType, reason); // mute the user. This will also remove any previous unmute timers
await using (var uow = _db.GetDbContext())
{
var config = uow.GuildConfigsForId(user.GuildId, set => set.Include(x => x.UnmuteTimers));
@ -330,7 +329,7 @@ public class MuteService : INService
public async Task TimedBan(IGuild guild, IUser user, TimeSpan after, string reason)
{
await guild.AddBanAsync(user.Id, 0, reason).ConfigureAwait(false);
await guild.AddBanAsync(user.Id, 0, reason);
await using (var uow = _db.GetDbContext())
{
var config = uow.GuildConfigsForId(guild.Id, set => set.Include(x => x.UnbanTimer));
@ -347,7 +346,7 @@ public class MuteService : INService
public async Task TimedRole(IGuildUser user, TimeSpan after, string reason, IRole role)
{
await user.AddRoleAsync(role).ConfigureAwait(false);
await user.AddRoleAsync(role);
await using (var uow = _db.GetDbContext())
{
var config = uow.GuildConfigsForId(user.GuildId, set => set.Include(x => x.UnroleTimer));
@ -380,7 +379,7 @@ public class MuteService : INService
var guild = _client.GetGuild(guildId); // load the guild
if (guild != null)
{
await guild.RemoveBanAsync(userId).ConfigureAwait(false);
await guild.RemoveBanAsync(userId);
}
}
catch (Exception ex)
@ -399,7 +398,7 @@ public class MuteService : INService
var role = guild.GetRole(roleId.Value);
if (guild != null && user != null && user.Roles.Contains(role))
{
await user.RemoveRoleAsync(role).ConfigureAwait(false);
await user.RemoveRoleAsync(role);
}
}
catch (Exception ex)
@ -412,7 +411,7 @@ public class MuteService : INService
try
{
// unmute the user, this will also remove the timer from the db
await UnmuteUser(guildId, userId, _client.CurrentUser, reason: "Timed mute expired").ConfigureAwait(false);
await UnmuteUser(guildId, userId, _client.CurrentUser, reason: "Timed mute expired");
}
catch (Exception ex)
{

View file

@ -1,4 +1,4 @@
#nullable disable
#nullable disable
using System.Threading.Channels;
using NadekoBot.Modules.Administration.Common;
using NadekoBot.Services.Database.Models;
@ -181,9 +181,9 @@ public class ProtectionService : INService
var settings = stats.AntiRaidSettings;
await PunishUsers(settings.Action, ProtectionType.Raiding,
settings.PunishDuration, null, users).ConfigureAwait(false);
settings.PunishDuration, null, users);
}
await Task.Delay(1000 * stats.AntiRaidSettings.Seconds).ConfigureAwait(false);
await Task.Delay(1000 * stats.AntiRaidSettings.Seconds);
stats.RaidUsers.TryRemove(user);
--stats.UsersCount;
@ -228,8 +228,7 @@ public class ProtectionService : INService
stats.Dispose();
var settings = spamSettings.AntiSpamSettings;
await PunishUsers(settings.Action, ProtectionType.Spamming, settings.MuteTime,
settings.RoleId, (IGuildUser)msg.Author)
.ConfigureAwait(false);
settings.RoleId, (IGuildUser)msg.Author);
}
}
}
@ -270,7 +269,7 @@ public class ProtectionService : INService
PunishmentAction action, int minutesDuration)
{
var g = _client.GetGuild(guildId);
await _mute.GetMuteRole(g).ConfigureAwait(false);
await _mute.GetMuteRole(g);
if (action == PunishmentAction.AddRole)
return null;
@ -338,7 +337,7 @@ public class ProtectionService : INService
int punishDurationMinutes, ulong? roleId)
{
var g = _client.GetGuild(guildId);
await _mute.GetMuteRole(g).ConfigureAwait(false);
await _mute.GetMuteRole(g);
if (!IsDurationAllowed(action))
punishDurationMinutes = 0;

View file

@ -1,4 +1,4 @@
#nullable disable
#nullable disable
namespace NadekoBot.Modules.Administration.Services;
public class PruneService : INService
@ -25,7 +25,7 @@ public class PruneService : INService
{
IMessage[] msgs;
IMessage lastMessage = null;
msgs = (await channel.GetMessagesAsync(50).FlattenAsync().ConfigureAwait(false)).Where(predicate).Take(amount).ToArray();
msgs = (await channel.GetMessagesAsync(50).FlattenAsync()).Where(predicate).Take(amount).ToArray();
while (amount > 0 && msgs.Any())
{
lastMessage = msgs[msgs.Length - 1];
@ -43,16 +43,20 @@ public class PruneService : INService
}
if (bulkDeletable.Count > 0)
await Task.WhenAll(Task.Delay(1000), channel.DeleteMessagesAsync(bulkDeletable)).ConfigureAwait(false);
await Task.WhenAll(Task.Delay(1000), channel.DeleteMessagesAsync(bulkDeletable));
foreach (var group in singleDeletable.Chunk(5))
await Task.WhenAll(Task.Delay(1000), Task.WhenAll(group.Select(x => x.DeleteAsync()))).ConfigureAwait(false);
await Task.WhenAll(
Task.Delay(1000),
group.Select(x => x.DeleteAsync())
.WhenAll()
);
//this isn't good, because this still work as if i want to remove only specific user's messages from the last
//100 messages, Maybe this needs to be reduced by msgs.Length instead of 100
amount -= 50;
if(amount > 0)
msgs = (await channel.GetMessagesAsync(lastMessage, Direction.Before, 50).FlattenAsync().ConfigureAwait(false)).Where(predicate).Take(amount).ToArray();
msgs = (await channel.GetMessagesAsync(lastMessage, Direction.Before, 50).FlattenAsync()).Where(predicate).Take(amount).ToArray();
}
}
catch

View file

@ -1,4 +1,4 @@
#nullable disable
#nullable disable
using Microsoft.EntityFrameworkCore;
using NadekoBot.Common.Collections;
using NadekoBot.Services.Database.Models;
@ -72,7 +72,7 @@ public class RoleCommandsService : INService
var removeExclusiveTask = RemoveExclusiveReactionRoleAsync(msg, gusr, reaction, conf, reactionRole, CancellationToken.None);
var addRoleTask = AddReactionRoleAsync(gusr, reactionRole);
await Task.WhenAll(removeExclusiveTask, addRoleTask).ConfigureAwait(false);
await Task.WhenAll(removeExclusiveTask, addRoleTask);
}
finally
{
@ -82,12 +82,12 @@ public class RoleCommandsService : INService
}
else
{
var dl = await msg.GetOrDownloadAsync().ConfigureAwait(false);
var dl = await msg.GetOrDownloadAsync();
await dl.RemoveReactionAsync(reaction.Emote, dl.Author,
new()
{
RetryMode = RetryMode.RetryRatelimit | RetryMode.Retry502
}).ConfigureAwait(false);
});
Log.Warning("User {0} is adding unrelated reactions to the reaction roles message.", dl.Author);
}
});
@ -126,7 +126,7 @@ public class RoleCommandsService : INService
var role = gusr.Guild.GetRole(reactionRole.RoleId);
if (role is null)
return;
await gusr.RemoveRoleAsync(role).ConfigureAwait(false);
await gusr.RemoveRoleAsync(role);
}
}
catch { }
@ -231,13 +231,13 @@ public class RoleCommandsService : INService
//if the role is exclusive,
// remove all other reactions user added to the message
var dl = await reactionMessage.GetOrDownloadAsync().ConfigureAwait(false);
var dl = await reactionMessage.GetOrDownloadAsync();
foreach (var r in dl.Reactions)
{
if (r.Key.Name == reaction.Emote.Name)
continue;
try { await dl.RemoveReactionAsync(r.Key, user).ConfigureAwait(false); } catch { }
await Task.Delay(100, cToken).ConfigureAwait(false);
try { await dl.RemoveReactionAsync(r.Key, user); } catch { }
await Task.Delay(100, cToken);
}
}
}

View file

@ -1,4 +1,4 @@
#nullable disable
#nullable disable
using NadekoBot.Services.Database.Models;
using Microsoft.EntityFrameworkCore;
using NadekoBot.Db;
@ -99,8 +99,8 @@ public class SelfAssignedRolesService : INService
{
try
{
await guildUser.RemoveRoleAsync(sameRole).ConfigureAwait(false);
await Task.Delay(300).ConfigureAwait(false);
await guildUser.RemoveRoleAsync(sameRole);
await Task.Delay(300);
}
catch
{
@ -111,7 +111,7 @@ public class SelfAssignedRolesService : INService
}
try
{
await guildUser.AddRoleAsync(role).ConfigureAwait(false);
await guildUser.AddRoleAsync(role);
}
catch (Exception ex)
{
@ -167,7 +167,7 @@ public class SelfAssignedRolesService : INService
}
try
{
await guildUser.RemoveRoleAsync(role).ConfigureAwait(false);
await guildUser.RemoveRoleAsync(role);
}
catch (Exception)
{

View file

@ -1,4 +1,4 @@
#nullable disable
#nullable disable
using System.Collections.Immutable;
using NadekoBot.Common.ModuleBehaviors;
using Microsoft.EntityFrameworkCore;
@ -79,12 +79,12 @@ public sealed class SelfService : ILateExecutor, IReadyExecutor, INService
if (server.OwnerId != _client.CurrentUser.Id)
{
await server.LeaveAsync().ConfigureAwait(false);
await server.LeaveAsync();
Log.Information($"Left server {server.Name} [{server.Id}]");
}
else
{
await server.DeleteAsync().ConfigureAwait(false);
await server.DeleteAsync();
Log.Information($"Deleted server {server.Name} [{server.Id}]");
}
});
@ -110,7 +110,7 @@ public sealed class SelfService : ILateExecutor, IReadyExecutor, INService
{
try
{
await ExecuteCommand(cmd).ConfigureAwait(false);
await ExecuteCommand(cmd);
}
catch
{
@ -119,12 +119,12 @@ public sealed class SelfService : ILateExecutor, IReadyExecutor, INService
if (_client.ShardId == 0)
{
await LoadOwnerChannels().ConfigureAwait(false);
await LoadOwnerChannels();
}
}
private Timer TimerFromAutoCommand(AutoCommand x)
=> new(async obj => await ExecuteCommand((AutoCommand) obj).ConfigureAwait(false),
=> new(async obj => await ExecuteCommand((AutoCommand) obj),
x,
x.Interval * 1000,
x.Interval * 1000);
@ -143,7 +143,7 @@ public sealed class SelfService : ILateExecutor, IReadyExecutor, INService
//if someone already has .die as their startup command, ignore it
if (cmd.CommandText.StartsWith(prefix + "die", StringComparison.InvariantCulture))
return;
await _cmdHandler.ExecuteExternal(cmd.GuildId, cmd.ChannelId, cmd.CommandText).ConfigureAwait(false);
await _cmdHandler.ExecuteExternal(cmd.GuildId, cmd.ChannelId, cmd.CommandText);
}
catch (Exception ex)
{
@ -201,7 +201,7 @@ public sealed class SelfService : ILateExecutor, IReadyExecutor, INService
return Task.FromResult<IDMChannel>(null);
return user.CreateDMChannelAsync();
})).ConfigureAwait(false);
}));
ownerChannels = channels.Where(x => x != null)
.ToDictionary(x => x.Recipient.Id, x => x)
@ -244,7 +244,7 @@ public sealed class SelfService : ILateExecutor, IReadyExecutor, INService
{
try
{
await ownerCh.SendConfirmAsync(_eb, title, toSend).ConfigureAwait(false);
await ownerCh.SendConfirmAsync(_eb, title, toSend);
}
catch
{
@ -259,7 +259,7 @@ public sealed class SelfService : ILateExecutor, IReadyExecutor, INService
{
try
{
await firstOwnerChannel.SendConfirmAsync(_eb, title, toSend).ConfigureAwait(false);
await firstOwnerChannel.SendConfirmAsync(_eb, title, toSend);
}
catch
{
@ -322,14 +322,14 @@ public sealed class SelfService : ILateExecutor, IReadyExecutor, INService
var uri = new Uri(img);
using var http = _httpFactory.CreateClient();
using var sr = await http.GetAsync(uri, HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false);
using var sr = await http.GetAsync(uri, HttpCompletionOption.ResponseHeadersRead);
if (!sr.IsImage())
return false;
// i can't just do ReadAsStreamAsync because dicord.net's image poops itself
var imgData = await sr.Content.ReadAsByteArrayAsync().ConfigureAwait(false);
var imgData = await sr.Content.ReadAsByteArrayAsync();
await using var imgStream = imgData.ToStream();
await _client.CurrentUser.ModifyAsync(u => u.Avatar = new Image(imgStream)).ConfigureAwait(false);
await _client.CurrentUser.ModifyAsync(u => u.Avatar = new Image(imgStream));
return true;
}

View file

@ -73,7 +73,7 @@ public class UserPunishService : INService
if (p != null)
{
var user = await guild.GetUserAsync(userId).ConfigureAwait(false);
var user = await guild.GetUserAsync(userId);
if (user is null)
return null;
@ -95,50 +95,45 @@ public class UserPunishService : INService
{
case PunishmentAction.Mute:
if (minutes == 0)
await _mute.MuteUser(user, mod, reason: reason).ConfigureAwait(false);
await _mute.MuteUser(user, mod, reason: reason);
else
await _mute.TimedMute(user, mod, TimeSpan.FromMinutes(minutes), reason: reason)
.ConfigureAwait(false);
await _mute.TimedMute(user, mod, TimeSpan.FromMinutes(minutes), reason: reason);
break;
case PunishmentAction.VoiceMute:
if (minutes == 0)
await _mute.MuteUser(user, mod, MuteType.Voice, reason).ConfigureAwait(false);
await _mute.MuteUser(user, mod, MuteType.Voice, reason);
else
await _mute.TimedMute(user, mod, TimeSpan.FromMinutes(minutes), MuteType.Voice, reason)
.ConfigureAwait(false);
await _mute.TimedMute(user, mod, TimeSpan.FromMinutes(minutes), MuteType.Voice, reason);
break;
case PunishmentAction.ChatMute:
if (minutes == 0)
await _mute.MuteUser(user, mod, MuteType.Chat, reason).ConfigureAwait(false);
await _mute.MuteUser(user, mod, MuteType.Chat, reason);
else
await _mute.TimedMute(user, mod, TimeSpan.FromMinutes(minutes), MuteType.Chat, reason)
.ConfigureAwait(false);
await _mute.TimedMute(user, mod, TimeSpan.FromMinutes(minutes), MuteType.Chat, reason);
break;
case PunishmentAction.Kick:
await user.KickAsync(reason).ConfigureAwait(false);
await user.KickAsync(reason);
break;
case PunishmentAction.Ban:
if (minutes == 0)
await guild.AddBanAsync(user, reason: reason, pruneDays: 7).ConfigureAwait(false);
await guild.AddBanAsync(user, reason: reason, pruneDays: 7);
else
await _mute.TimedBan(user.Guild, user, TimeSpan.FromMinutes(minutes), reason)
.ConfigureAwait(false);
await _mute.TimedBan(user.Guild, user, TimeSpan.FromMinutes(minutes), reason);
break;
case PunishmentAction.Softban:
await guild.AddBanAsync(user, 7, reason: $"Softban | {reason}").ConfigureAwait(false);
await guild.AddBanAsync(user, 7, reason: $"Softban | {reason}");
try
{
await guild.RemoveBanAsync(user).ConfigureAwait(false);
await guild.RemoveBanAsync(user);
}
catch
{
await guild.RemoveBanAsync(user).ConfigureAwait(false);
await guild.RemoveBanAsync(user);
}
break;
case PunishmentAction.RemoveRoles:
await user.RemoveRolesAsync(user.GetRoles().Where(x => !x.IsManaged && x != x.Guild.EveryoneRole))
.ConfigureAwait(false);
await user.RemoveRolesAsync(user.GetRoles().Where(x => !x.IsManaged && x != x.Guild.EveryoneRole));
break;
case PunishmentAction.AddRole:
if (roleId is null)
@ -147,10 +142,9 @@ public class UserPunishService : INService
if (role is not null)
{
if (minutes == 0)
await user.AddRoleAsync(role).ConfigureAwait(false);
await user.AddRoleAsync(role);
else
await _mute.TimedRole(user, TimeSpan.FromMinutes(minutes), reason, role)
.ConfigureAwait(false);
await _mute.TimedRole(user, TimeSpan.FromMinutes(minutes), reason, role);
}
else
{

View file

@ -1,4 +1,4 @@
#nullable disable
#nullable disable
using Microsoft.EntityFrameworkCore;
using NadekoBot.Services.Database.Models;
using NadekoBot.Db;
@ -21,49 +21,60 @@ public class VcRoleService : INService
_client.UserVoiceStateUpdated += ClientOnUserVoiceStateUpdated;
VcRoles = new();
ToAssign = new();
var missingRoles = new ConcurrentBag<VcRoleInfo>();
using (var uow = db.GetDbContext())
{
var guildIds = client.Guilds.Select(x => x.Id).ToList();
var configs = uow.Set<GuildConfig>()
uow.Set<GuildConfig>()
.AsQueryable()
.Include(x => x.VcRoleInfos)
.Where(x => guildIds.Contains(x.GuildId))
.ToList();
Task.WhenAll(configs.Select(InitializeVcRole));
.AsEnumerable()
.Select(InitializeVcRole)
.WhenAll();
}
Task.Run(async () =>
{
while (true)
{
var tasks = ToAssign.Values.Select(queue => Task.Run(async () =>
{
while (queue.TryDequeue(out var item))
{
var (add, user, role) = item;
if (add)
Task Selector(ConcurrentQueue<(bool, IGuildUser, IRole)> queue)
=> Task.Run(async () =>
{
if (!user.RoleIds.Contains(role.Id))
while (queue.TryDequeue(out var item))
{
try { await user.AddRoleAsync(role).ConfigureAwait(false); } catch { }
}
}
else
{
if (user.RoleIds.Contains(role.Id))
{
try { await user.RemoveRoleAsync(role).ConfigureAwait(false); } catch { }
var (add, user, role) = item;
try
{
if (add)
{
if (!user.RoleIds.Contains(role.Id))
{
await user.AddRoleAsync(role);
}
}
else
{
if (user.RoleIds.Contains(role.Id))
{
await user.RemoveRoleAsync(role);
}
}
}
catch
{
}
await Task.Delay(250);
}
}
);
await Task.Delay(250).ConfigureAwait(false);
}
}));
await Task.WhenAll(tasks.Append(Task.Delay(1000))).ConfigureAwait(false);
await ToAssign.Values.Select(Selector)
.Append(Task.Delay(1000))
.WhenAll();
}
});
@ -119,7 +130,10 @@ public class VcRoleService : INService
if (missingRoles.Any())
{
await using var uow = _db.GetDbContext();
Log.Warning($"Removing {missingRoles.Count} missing roles from {nameof(VcRoleService)}");
Log.Warning("Removing {MissingRoleCount} missing roles from {ServiceName}",
missingRoles.Count,
nameof(VcRoleService)
);
uow.RemoveRange(missingRoles);
await uow.SaveChangesAsync();
}
@ -132,7 +146,7 @@ public class VcRoleService : INService
var guildVcRoles = VcRoles.GetOrAdd(guildId, new ConcurrentDictionary<ulong, IRole>());
guildVcRoles.AddOrUpdate(vcId, role, (key, old) => role);
guildVcRoles.AddOrUpdate(vcId, role, (_, _) => role);
using var uow = _db.GetDbContext();
var conf = uow.GuildConfigsForId(guildId, set => set.Include(x => x.VcRoleInfos));
var toDelete = conf.VcRoleInfos.FirstOrDefault(x => x.VoiceChannelId == vcId); // remove old one

View file

@ -1,4 +1,4 @@
#nullable disable
#nullable disable
using NadekoBot.Modules.Administration.Services;
namespace NadekoBot.Modules.Administration;
@ -51,13 +51,13 @@ public partial class Administration
.WithDescription(string.Join("\n", timezoneStrings
.Skip(curPage * timezonesPerPage)
.Take(timezonesPerPage))),
timezones.Length, timezonesPerPage).ConfigureAwait(false);
timezones.Length, timezonesPerPage);
}
[NadekoCommand, Aliases]
[RequireContext(ContextType.Guild)]
public async Task Timezone()
=> await ReplyConfirmLocalizedAsync(strs.timezone_guild(_service.GetTimeZoneOrUtc(ctx.Guild.Id))).ConfigureAwait(false);
=> await ReplyConfirmLocalizedAsync(strs.timezone_guild(_service.GetTimeZoneOrUtc(ctx.Guild.Id)));
[NadekoCommand, Aliases]
[RequireContext(ContextType.Guild)]
@ -70,12 +70,12 @@ public partial class Administration
if (tz is null)
{
await ReplyErrorLocalizedAsync(strs.timezone_not_found).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.timezone_not_found);
return;
}
_service.SetTimeZone(ctx.Guild.Id, tz);
await SendConfirmAsync(tz.ToString()).ConfigureAwait(false);
await SendConfirmAsync(tz.ToString());
}
}
}

View file

@ -64,8 +64,7 @@ public partial class Administration
await user.EmbedAsync(_eb.Create().WithErrorColor()
.WithDescription(GetText(strs.warned_on(ctx.Guild.ToString())))
.AddField(GetText(strs.moderator), ctx.User.ToString())
.AddField(GetText(strs.reason), reason ?? "-"))
.ConfigureAwait(false);
.AddField(GetText(strs.reason), reason ?? "-"));
}
catch
{
@ -75,7 +74,7 @@ public partial class Administration
WarningPunishment punishment;
try
{
punishment = await _service.Warn(ctx.Guild, user.Id, ctx.User, weight, reason).ConfigureAwait(false);
punishment = await _service.Warn(ctx.Guild, user.Id, ctx.User, weight, reason);
}
catch (Exception ex)
{
@ -150,22 +149,22 @@ public partial class Administration
var opts = OptionsParser.ParseFrom<WarnExpireOptions>(args);
await ctx.Channel.TriggerTypingAsync().ConfigureAwait(false);
await ctx.Channel.TriggerTypingAsync();
await _service.WarnExpireAsync(ctx.Guild.Id, days, opts.Delete).ConfigureAwait(false);
await _service.WarnExpireAsync(ctx.Guild.Id, days, opts.Delete);
if(days == 0)
{
await ReplyConfirmLocalizedAsync(strs.warn_expire_reset).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.warn_expire_reset);
return;
}
if (opts.Delete)
{
await ReplyConfirmLocalizedAsync(strs.warn_expire_set_delete(Format.Bold(days.ToString()))).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.warn_expire_set_delete(Format.Bold(days.ToString())));
}
else
{
await ReplyConfirmLocalizedAsync(strs.warn_expire_set_clear(Format.Bold(days.ToString()))).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.warn_expire_set_clear(Format.Bold(days.ToString())));
}
}
@ -285,7 +284,7 @@ public partial class Administration
return _eb.Create().WithOkColor()
.WithTitle(GetText(strs.warnings_list))
.WithDescription(string.Join("\n", ws));
}, warnings.Length, 15).ConfigureAwait(false);
}, warnings.Length, 15);
}
[NadekoCommand, Aliases]
@ -315,7 +314,7 @@ public partial class Administration
}
else
{
await ReplyErrorLocalizedAsync(strs.warning_clear_fail).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.warning_clear_fail);
}
}
}
@ -421,7 +420,7 @@ public partial class Administration
}
await SendConfirmAsync(
GetText(strs.warn_punish_list),
list).ConfigureAwait(false);
list);
}
[NadekoCommand, Aliases]
@ -458,7 +457,7 @@ public partial class Administration
}
}
await _mute.TimedBan(ctx.Guild, user, time.Time, (ctx.User.ToString() + " | " + msg).TrimTo(512)).ConfigureAwait(false);
await _mute.TimedBan(ctx.Guild, user, time.Time, (ctx.User.ToString() + " | " + msg).TrimTo(512));
var toSend = _eb.Create().WithOkColor()
.WithTitle("⛔️ " + GetText(strs.banned_user))
.AddField(GetText(strs.username), user.ToString(), true)
@ -474,8 +473,7 @@ public partial class Administration
toSend.WithFooter("⚠️ " + GetText(strs.unable_to_dm_user));
}
await ctx.Channel.EmbedAsync(toSend)
.ConfigureAwait(false);
await ctx.Channel.EmbedAsync(toSend);
}
[NadekoCommand, Aliases]
@ -492,8 +490,7 @@ public partial class Administration
await ctx.Channel.EmbedAsync(_eb.Create().WithOkColor()
.WithTitle("⛔️ " + GetText(strs.banned_user))
.AddField("ID", userId.ToString(), true))
.ConfigureAwait(false);
.AddField("ID", userId.ToString(), true));
}
else
{
@ -527,7 +524,7 @@ public partial class Administration
dmFailed = true;
}
await ctx.Guild.AddBanAsync(user, 7, (ctx.User.ToString() + " | " + msg).TrimTo(512)).ConfigureAwait(false);
await ctx.Guild.AddBanAsync(user, 7, (ctx.User.ToString() + " | " + msg).TrimTo(512));
var toSend = _eb.Create().WithOkColor()
.WithTitle("⛔️ " + GetText(strs.banned_user))
@ -539,8 +536,7 @@ public partial class Administration
toSend.WithFooter("⚠️ " + GetText(strs.unable_to_dm_user));
}
await ctx.Channel.EmbedAsync(toSend)
.ConfigureAwait(false);
await ctx.Channel.EmbedAsync(toSend);
}
[NadekoCommand, Aliases]
@ -627,17 +623,17 @@ public partial class Administration
[BotPerm(GuildPerm.BanMembers)]
public async Task Unban([Leftover] string user)
{
var bans = await ctx.Guild.GetBansAsync().ConfigureAwait(false);
var bans = await ctx.Guild.GetBansAsync();
var bun = bans.FirstOrDefault(x => x.User.ToString().ToLowerInvariant() == user.ToLowerInvariant());
if (bun is null)
{
await ReplyErrorLocalizedAsync(strs.user_not_found).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.user_not_found);
return;
}
await UnbanInternal(bun.User).ConfigureAwait(false);
await UnbanInternal(bun.User);
}
[NadekoCommand, Aliases]
@ -646,24 +642,24 @@ public partial class Administration
[BotPerm(GuildPerm.BanMembers)]
public async Task Unban(ulong userId)
{
var bans = await ctx.Guild.GetBansAsync().ConfigureAwait(false);
var bans = await ctx.Guild.GetBansAsync();
var bun = bans.FirstOrDefault(x => x.User.Id == userId);
if (bun is null)
{
await ReplyErrorLocalizedAsync(strs.user_not_found).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.user_not_found);
return;
}
await UnbanInternal(bun.User).ConfigureAwait(false);
await UnbanInternal(bun.User);
}
private async Task UnbanInternal(IUser user)
{
await ctx.Guild.RemoveBanAsync(user).ConfigureAwait(false);
await ctx.Guild.RemoveBanAsync(user);
await ReplyConfirmLocalizedAsync(strs.unbanned_user(Format.Bold(user.ToString()))).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.unbanned_user(Format.Bold(user.ToString())));
}
[NadekoCommand, Aliases]
@ -702,9 +698,9 @@ public partial class Administration
dmFailed = true;
}
await ctx.Guild.AddBanAsync(user, 7, ("Softban | " + ctx.User.ToString() + " | " + msg).TrimTo(512)).ConfigureAwait(false);
try { await ctx.Guild.RemoveBanAsync(user).ConfigureAwait(false); }
catch { await ctx.Guild.RemoveBanAsync(user).ConfigureAwait(false); }
await ctx.Guild.AddBanAsync(user, 7, ("Softban | " + ctx.User.ToString() + " | " + msg).TrimTo(512));
try { await ctx.Guild.RemoveBanAsync(user); }
catch { await ctx.Guild.RemoveBanAsync(user); }
var toSend = _eb.Create().WithOkColor()
.WithTitle("☣ " + GetText(strs.sb_user))
@ -716,8 +712,7 @@ public partial class Administration
toSend.WithFooter("⚠️ " + GetText(strs.unable_to_dm_user));
}
await ctx.Channel.EmbedAsync(toSend)
.ConfigureAwait(false);
await ctx.Channel.EmbedAsync(toSend);
}
[NadekoCommand, Aliases]
@ -751,15 +746,14 @@ public partial class Administration
try
{
await user.SendErrorAsync(_eb, GetText(strs.kickdm(Format.Bold(ctx.Guild.Name), msg)))
.ConfigureAwait(false);
await user.SendErrorAsync(_eb, GetText(strs.kickdm(Format.Bold(ctx.Guild.Name), msg)));
}
catch
{
dmFailed = true;
}
await user.KickAsync((ctx.User.ToString() + " | " + msg).TrimTo(512)).ConfigureAwait(false);
await user.KickAsync((ctx.User.ToString() + " | " + msg).TrimTo(512));
var toSend = _eb.Create().WithOkColor()
.WithTitle(GetText(strs.kicked_user))
@ -771,8 +765,7 @@ public partial class Administration
toSend.WithFooter("⚠️ " + GetText(strs.unable_to_dm_user));
}
await ctx.Channel.EmbedAsync(toSend)
.ConfigureAwait(false);
await ctx.Channel.EmbedAsync(toSend);
}
[NadekoCommand, Aliases]
@ -853,7 +846,7 @@ public partial class Administration
.WithDescription(GetText(strs.mass_ban_completed(banning.Count())))
.AddField(GetText(strs.invalid(missing.Count)), missStr)
.WithOkColor()
.Build()).ConfigureAwait(false);
.Build());
}
[NadekoCommand, Aliases]
@ -884,17 +877,16 @@ public partial class Administration
.Select(x => ctx.Guild.AddBanAsync(x.Id.Value, 7, x.Reason, new()
{
RetryMode = RetryMode.AlwaysRetry,
})))
.ConfigureAwait(false);
})));
//wait for the message and edit it
var banningMessage = await banningMessageTask.ConfigureAwait(false);
var banningMessage = await banningMessageTask;
await banningMessage.ModifyAsync(x => x.Embed = _eb.Create()
.WithDescription(GetText(strs.mass_kill_completed(bans.Count())))
.AddField(GetText(strs.invalid(missing)), missStr)
.WithOkColor()
.Build()).ConfigureAwait(false);
.Build());
}
}
}

View file

@ -1,4 +1,4 @@
#nullable disable
#nullable disable
using NadekoBot.Modules.Administration.Services;
namespace NadekoBot.Modules.Administration;
@ -16,11 +16,11 @@ public partial class Administration
{
if (_service.RemoveVcRole(ctx.Guild.Id, vcId))
{
await ReplyConfirmLocalizedAsync(strs.vcrole_removed(Format.Bold(vcId.ToString()))).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.vcrole_removed(Format.Bold(vcId.ToString())));
}
else
{
await ReplyErrorLocalizedAsync(strs.vcrole_not_found).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.vcrole_not_found);
}
}
@ -36,7 +36,7 @@ public partial class Administration
if (vc is null || vc.GuildId != user.GuildId)
{
await ReplyErrorLocalizedAsync(strs.must_be_in_voice).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.must_be_in_voice);
return;
}
@ -44,13 +44,13 @@ public partial class Administration
{
if (_service.RemoveVcRole(ctx.Guild.Id, vc.Id))
{
await ReplyConfirmLocalizedAsync(strs.vcrole_removed(Format.Bold(vc.Name))).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.vcrole_removed(Format.Bold(vc.Name)));
}
}
else
{
_service.AddVcRole(ctx.Guild.Id, role, vc.Id);
await ReplyConfirmLocalizedAsync(strs.vcrole_added(Format.Bold(vc.Name), Format.Bold(role.Name))).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.vcrole_added(Format.Bold(vc.Name), Format.Bold(role.Name)));
}
}
@ -78,8 +78,7 @@ public partial class Administration
}
await ctx.Channel.EmbedAsync(_eb.Create().WithOkColor()
.WithTitle(GetText(strs.vc_role_list))
.WithDescription(text))
.ConfigureAwait(false);
.WithDescription(text));
}
}
}

View file

@ -1,4 +1,4 @@
#nullable disable
#nullable disable
using NadekoBot.Modules.CustomReactions.Services;
namespace NadekoBot.Modules.CustomReactions;
@ -26,7 +26,7 @@ public class CustomReactions : NadekoModule<CustomReactionsService>
if (!AdminInGuildOrOwnerInDm())
{
await ReplyErrorLocalizedAsync(strs.insuff_perms).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.insuff_perms);
return;
}
@ -37,7 +37,7 @@ public class CustomReactions : NadekoModule<CustomReactionsService>
.WithDescription($"#{cr.Id}")
.AddField(GetText(strs.trigger), key)
.AddField(GetText(strs.response), message.Length > 1024 ? GetText(strs.redacted_too_long) : message)
).ConfigureAwait(false);
);
}
[NadekoCommand, Aliases]
@ -49,11 +49,11 @@ public class CustomReactions : NadekoModule<CustomReactionsService>
if ((channel is null && !_creds.IsOwner(ctx.User)) || (channel != null && !((IGuildUser)ctx.User).GuildPermissions.Administrator))
{
await ReplyErrorLocalizedAsync(strs.insuff_perms).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.insuff_perms);
return;
}
var cr = await _service.EditAsync(ctx.Guild?.Id, id, message).ConfigureAwait(false);
var cr = await _service.EditAsync(ctx.Guild?.Id, id, message);
if (cr != null)
{
await ctx.Channel.EmbedAsync(_eb.Create().WithOkColor()
@ -61,11 +61,11 @@ public class CustomReactions : NadekoModule<CustomReactionsService>
.WithDescription($"#{id}")
.AddField(GetText(strs.trigger), cr.Trigger)
.AddField(GetText(strs.response), message.Length > 1024 ? GetText(strs.redacted_too_long) : message)
).ConfigureAwait(false);
);
}
else
{
await ReplyErrorLocalizedAsync(strs.edit_fail).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.edit_fail);
}
}
@ -80,7 +80,7 @@ public class CustomReactions : NadekoModule<CustomReactionsService>
if (customReactions is null || !customReactions.Any())
{
await ReplyErrorLocalizedAsync(strs.no_found).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.no_found);
return;
}
@ -117,7 +117,7 @@ public class CustomReactions : NadekoModule<CustomReactionsService>
if (found is null)
{
await ReplyErrorLocalizedAsync(strs.no_found_id).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.no_found_id);
return;
}
else
@ -126,7 +126,7 @@ public class CustomReactions : NadekoModule<CustomReactionsService>
.WithDescription($"#{id}")
.AddField(GetText(strs.trigger), found.Trigger.TrimTo(1024))
.AddField(GetText(strs.response), found.Response.TrimTo(1000).Replace("](", "]\\("))
).ConfigureAwait(false);
);
}
}
@ -135,7 +135,7 @@ public class CustomReactions : NadekoModule<CustomReactionsService>
{
if (!AdminInGuildOrOwnerInDm())
{
await ReplyErrorLocalizedAsync(strs.insuff_perms).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.insuff_perms);
return;
}
@ -147,11 +147,11 @@ public class CustomReactions : NadekoModule<CustomReactionsService>
.WithTitle(GetText(strs.deleted))
.WithDescription($"#{id}")
.AddField(GetText(strs.trigger), cr.Trigger.TrimTo(1024))
.AddField(GetText(strs.response), cr.Response.TrimTo(1024))).ConfigureAwait(false);
.AddField(GetText(strs.response), cr.Response.TrimTo(1024)));
}
else
{
await ReplyErrorLocalizedAsync(strs.no_found_id).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.no_found_id);
}
}
@ -160,21 +160,21 @@ public class CustomReactions : NadekoModule<CustomReactionsService>
{
if (!AdminInGuildOrOwnerInDm())
{
await ReplyErrorLocalizedAsync(strs.insuff_perms).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.insuff_perms);
return;
}
var cr = _service.GetCustomReaction(ctx.Guild?.Id, id);
if (cr is null)
{
await ReplyErrorLocalizedAsync(strs.no_found).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.no_found);
return;
}
if (emojiStrs.Length == 0)
{
await _service.ResetCrReactions(ctx.Guild?.Id, id);
await ReplyConfirmLocalizedAsync(strs.crr_reset(Format.Bold(id.ToString()))).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.crr_reset(Format.Bold(id.ToString())));
return;
}
@ -187,8 +187,8 @@ public class CustomReactions : NadekoModule<CustomReactionsService>
// i should try adding these emojis right away to the message, to make sure the bot can react with these emojis. If it fails, skip that emoji
try
{
await ctx.Message.AddReactionAsync(emote).ConfigureAwait(false);
await Task.Delay(100).ConfigureAwait(false);
await ctx.Message.AddReactionAsync(emote);
await Task.Delay(100);
succ.Add(emojiStr);
if (succ.Count >= 3)
@ -199,14 +199,14 @@ public class CustomReactions : NadekoModule<CustomReactionsService>
if(succ.Count == 0)
{
await ReplyErrorLocalizedAsync(strs.invalid_emojis).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.invalid_emojis);
return;
}
await _service.SetCrReactions(ctx.Guild?.Id, id, succ);
await ReplyConfirmLocalizedAsync(strs.crr_set(Format.Bold(id.ToString()), string.Join(", ", succ.Select(x => x.ToString())))).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.crr_set(Format.Bold(id.ToString()), string.Join(", ", succ.Select(x => x.ToString()))));
}
@ -240,23 +240,23 @@ public class CustomReactions : NadekoModule<CustomReactionsService>
var cr = _service.GetCustomReaction(ctx.Guild?.Id, id);
if (!AdminInGuildOrOwnerInDm())
{
await ReplyErrorLocalizedAsync(strs.insuff_perms).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.insuff_perms);
return;
}
var (success, newVal) = await _service.ToggleCrOptionAsync(id, option).ConfigureAwait(false);
var (success, newVal) = await _service.ToggleCrOptionAsync(id, option);
if (!success)
{
await ReplyErrorLocalizedAsync(strs.no_found_id).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.no_found_id);
return;
}
if (newVal)
{
await ReplyConfirmLocalizedAsync(strs.option_enabled(Format.Code(option.ToString()), Format.Code(id.ToString()))).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.option_enabled(Format.Code(option.ToString()), Format.Code(id.ToString())));
}
else
{
await ReplyConfirmLocalizedAsync(strs.option_disabled(Format.Code(option.ToString()), Format.Code(id.ToString()))).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.option_disabled(Format.Code(option.ToString()), Format.Code(id.ToString())));
}
}
@ -267,7 +267,7 @@ public class CustomReactions : NadekoModule<CustomReactionsService>
{
if (await PromptUserConfirmAsync(_eb.Create()
.WithTitle("Custom reaction clear")
.WithDescription("This will delete all custom reactions on this server.")).ConfigureAwait(false))
.WithDescription("This will delete all custom reactions on this server.")))
{
var count = _service.DeleteAllCustomReactions(ctx.Guild.Id);
await ReplyConfirmLocalizedAsync(strs.cleared(count));
@ -279,7 +279,7 @@ public class CustomReactions : NadekoModule<CustomReactionsService>
{
if (!AdminInGuildOrOwnerInDm())
{
await ReplyErrorLocalizedAsync(strs.insuff_perms).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.insuff_perms);
return;
}
@ -298,7 +298,7 @@ public class CustomReactions : NadekoModule<CustomReactionsService>
{
if (!AdminInGuildOrOwnerInDm())
{
await ReplyErrorLocalizedAsync(strs.insuff_perms).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.insuff_perms);
return;
}

View file

@ -1,4 +1,4 @@
#nullable disable
#nullable disable
using NadekoBot.Services.Database.Models;
using System.Runtime.CompilerServices;
@ -13,7 +13,7 @@ public static class CustomReactionExtensions
DiscordSocketClient client, bool sanitize)
{
var channel = cr.DmResponse
? await ctx.Author.CreateDMChannelAsync().ConfigureAwait(false)
? await ctx.Author.CreateDMChannelAsync()
: ctx.Channel;
var trigger = cr.Trigger.ResolveTriggerString(client);

View file

@ -1,4 +1,4 @@
#nullable disable
#nullable disable
using NadekoBot.Common.ModuleBehaviors;
using NadekoBot.Services.Database.Models;
using NadekoBot.Modules.CustomReactions.Extensions;
@ -407,7 +407,7 @@ public sealed class CustomReactionsService : IEarlyBehavior, IReadyExecutor
try
{
await msg.Channel.SendErrorAsync(_eb, returnMsg).ConfigureAwait(false);
await msg.Channel.SendErrorAsync(_eb, returnMsg);
}
catch
{
@ -420,7 +420,7 @@ public sealed class CustomReactionsService : IEarlyBehavior, IReadyExecutor
}
}
var sentMsg = await cr.Send(msg, _client, false).ConfigureAwait(false);
var sentMsg = await cr.Send(msg, _client, false);
var reactions = cr.GetReactions();
foreach (var reaction in reactions)
@ -443,7 +443,7 @@ public sealed class CustomReactionsService : IEarlyBehavior, IReadyExecutor
{
try
{
await msg.DeleteAsync().ConfigureAwait(false);
await msg.DeleteAsync();
}
catch
{

View file

@ -1,4 +1,4 @@
#nullable disable
#nullable disable
using NadekoBot.Modules.Gambling.Common;
using NadekoBot.Modules.Gambling.Common.AnimalRacing;
using NadekoBot.Modules.Gambling.Services;
@ -112,15 +112,13 @@ public partial class Gambling
var msg = raceMessage;
if (msg is null)
raceMessage = await SendConfirmAsync(text)
.ConfigureAwait(false);
raceMessage = await SendConfirmAsync(text);
else
await msg.ModifyAsync(x => x.Embed = _eb.Create()
.WithTitle(GetText(strs.animal_race))
.WithDescription(text)
.WithOkColor()
.Build())
.ConfigureAwait(false);
.Build());
}
private Task Ar_OnStartingFailed(AnimalRace race)
@ -133,18 +131,17 @@ public partial class Gambling
[RequireContext(ContextType.Guild)]
public async Task JoinRace(ShmartNumber amount = default)
{
if (!await CheckBetOptional(amount).ConfigureAwait(false))
if (!await CheckBetOptional(amount))
return;
if (!_service.AnimalRaces.TryGetValue(ctx.Guild.Id, out var ar))
{
await ReplyErrorLocalizedAsync(strs.race_not_exist).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.race_not_exist);
return;
}
try
{
var user = await ar.JoinRace(ctx.User.Id, ctx.User.ToString(), amount)
.ConfigureAwait(false);
var user = await ar.JoinRace(ctx.User.Id, ctx.User.ToString(), amount);
if (amount > 0)
await SendConfirmAsync(GetText(strs.animal_race_join_bet(ctx.User.Mention, user.Animal.Icon, amount + CurrencySign)));
else
@ -164,8 +161,7 @@ public partial class Gambling
}
catch (AnimalRaceFullException)
{
await SendConfirmAsync(GetText(strs.animal_race), GetText(strs.animal_race_full))
.ConfigureAwait(false);
await SendConfirmAsync(GetText(strs.animal_race), GetText(strs.animal_race_full));
}
catch (NotEnoughFundsException)
{

View file

@ -1,4 +1,4 @@
#nullable disable
#nullable disable
using NadekoBot.Modules.Gambling.Common;
using NadekoBot.Modules.Gambling.Common.Blackjack;
using NadekoBot.Modules.Gambling.Services;
@ -31,14 +31,14 @@ public partial class Gambling
[RequireContext(ContextType.Guild)]
public async Task BlackJack(ShmartNumber amount)
{
if (!await CheckBetMandatory(amount).ConfigureAwait(false))
if (!await CheckBetMandatory(amount))
return;
var newBj = new Blackjack(_cs, _db);
Blackjack bj;
if (newBj == (bj = _service.Games.GetOrAdd(ctx.Channel.Id, newBj)))
{
if (!await bj.Join(ctx.User, amount).ConfigureAwait(false))
if (!await bj.Join(ctx.User, amount))
{
_service.Games.TryRemove(ctx.Channel.Id, out _);
await ReplyErrorLocalizedAsync(strs.not_enough(CurrencySign));
@ -48,19 +48,19 @@ public partial class Gambling
bj.GameEnded += Bj_GameEnded;
bj.Start();
await ReplyConfirmLocalizedAsync(strs.bj_created).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.bj_created);
}
else
{
if (await bj.Join(ctx.User, amount).ConfigureAwait(false))
await ReplyConfirmLocalizedAsync(strs.bj_joined).ConfigureAwait(false);
if (await bj.Join(ctx.User, amount))
await ReplyConfirmLocalizedAsync(strs.bj_joined);
else
{
Log.Information($"{ctx.User} can't join a blackjack game as it's in " + bj.State.ToString() + " state already.");
}
}
await ctx.Message.DeleteAsync().ConfigureAwait(false);
await ctx.Message.DeleteAsync();
}
private Task Bj_GameEnded(Blackjack arg)
@ -129,7 +129,7 @@ public partial class Gambling
full = "💰 " + full;
embed.AddField(full, cStr);
}
_msg = await ctx.Channel.EmbedAsync(embed).ConfigureAwait(false);
_msg = await ctx.Channel.EmbedAsync(embed);
}
catch
{
@ -167,18 +167,18 @@ public partial class Gambling
return;
if (a == BjAction.Hit)
await bj.Hit(ctx.User).ConfigureAwait(false);
await bj.Hit(ctx.User);
else if (a == BjAction.Stand)
await bj.Stand(ctx.User).ConfigureAwait(false);
await bj.Stand(ctx.User);
else if (a == BjAction.Double)
{
if (!await bj.Double(ctx.User).ConfigureAwait(false))
if (!await bj.Double(ctx.User))
{
await ReplyErrorLocalizedAsync(strs.not_enough(CurrencySign));
}
}
await ctx.Message.DeleteAsync().ConfigureAwait(false);
await ctx.Message.DeleteAsync();
}
}
}

View file

@ -1,4 +1,4 @@
#nullable disable
#nullable disable
using NadekoBot.Modules.Gambling.Common.AnimalRacing.Exceptions;
using NadekoBot.Modules.Games.Common;
@ -45,15 +45,15 @@ public sealed class AnimalRace : IDisposable
{
var _t = Task.Run(async () =>
{
await Task.Delay(_options.StartTime * 1000).ConfigureAwait(false);
await Task.Delay(_options.StartTime * 1000);
await _locker.WaitAsync().ConfigureAwait(false);
await _locker.WaitAsync();
try
{
if (CurrentPhase != Phase.WaitingForPlayers)
return;
await Start().ConfigureAwait(false);
await Start();
}
finally { _locker.Release(); }
});
@ -66,7 +66,7 @@ public sealed class AnimalRace : IDisposable
var user = new AnimalRacingUser(userName, userId, bet);
await _locker.WaitAsync().ConfigureAwait(false);
await _locker.WaitAsync();
try
{
if (_users.Count == MaxUsers)
@ -75,7 +75,7 @@ public sealed class AnimalRace : IDisposable
if (CurrentPhase != Phase.WaitingForPlayers)
throw new AlreadyStartedException();
if (!await _currency.RemoveAsync(userId, "BetRace", bet).ConfigureAwait(false))
if (!await _currency.RemoveAsync(userId, "BetRace", bet))
throw new NotEnoughFundsException();
if (_users.Contains(user))
@ -86,7 +86,7 @@ public sealed class AnimalRace : IDisposable
_users.Add(user);
if (_animalsQueue.Count == 0) //start if no more spots left
await Start().ConfigureAwait(false);
await Start();
return user;
}
@ -101,7 +101,7 @@ public sealed class AnimalRace : IDisposable
foreach (var user in _users)
{
if (user.Bet > 0)
await _currency.AddAsync(user.UserId, "Race refund", user.Bet).ConfigureAwait(false);
await _currency.AddAsync(user.UserId, "Race refund", user.Bet);
}
var _sf = OnStartingFailed?.Invoke(this);
@ -128,12 +128,11 @@ public sealed class AnimalRace : IDisposable
FinishedUsers.AddRange(finished);
var _ignore = OnStateUpdate?.Invoke(this);
await Task.Delay(2500).ConfigureAwait(false);
await Task.Delay(2500);
}
if (FinishedUsers[0].Bet > 0)
await _currency.AddAsync(FinishedUsers[0].UserId, "Won a Race", FinishedUsers[0].Bet * (_users.Count - 1))
.ConfigureAwait(false);
await _currency.AddAsync(FinishedUsers[0].UserId, "Won a Race", FinishedUsers[0].Bet * (_users.Count - 1));
var _ended = OnEnded?.Invoke(this);
});

View file

@ -1,4 +1,4 @@
#nullable disable
#nullable disable
namespace NadekoBot.Modules.Gambling.Common.Blackjack;
public class Blackjack
@ -44,8 +44,8 @@ public class Blackjack
try
{
//wait for players to join
await Task.Delay(20000).ConfigureAwait(false);
await locker.WaitAsync().ConfigureAwait(false);
await Task.Delay(20000);
await locker.WaitAsync();
try
{
State = GameState.Playing;
@ -54,7 +54,7 @@ public class Blackjack
{
locker.Release();
}
await PrintState().ConfigureAwait(false);
await PrintState();
//if no users joined the game, end it
if (!Players.Any())
{
@ -78,15 +78,15 @@ public class Blackjack
while (!usr.Done)
{
Log.Information($"Waiting for {usr.DiscordUser}'s move");
await PromptUserMove(usr).ConfigureAwait(false);
await PromptUserMove(usr);
}
}
await PrintState().ConfigureAwait(false);
await PrintState();
State = GameState.Ended;
await Task.Delay(2500).ConfigureAwait(false);
await Task.Delay(2500);
Log.Information("Dealer moves");
await DealerMoves().ConfigureAwait(false);
await PrintState().ConfigureAwait(false);
await DealerMoves();
await PrintState();
var _ = GameEnded?.Invoke(this);
}
catch (Exception ex)
@ -102,13 +102,13 @@ public class Blackjack
var pause = Task.Delay(20000); //10 seconds to decide
CurrentUser = usr;
_currentUserMove = new();
await PrintState().ConfigureAwait(false);
await PrintState();
// either wait for the user to make an action and
// if he doesn't - stand
var finished = await Task.WhenAny(pause, _currentUserMove.Task).ConfigureAwait(false);
var finished = await Task.WhenAny(pause, _currentUserMove.Task);
if (finished == pause)
{
await Stand(usr).ConfigureAwait(false);
await Stand(usr);
}
CurrentUser = null;
_currentUserMove = null;
@ -116,7 +116,7 @@ public class Blackjack
public async Task<bool> Join(IUser user, long bet)
{
await locker.WaitAsync().ConfigureAwait(false);
await locker.WaitAsync();
try
{
if (State != GameState.Starting)
@ -125,7 +125,7 @@ public class Blackjack
if (Players.Count >= 5)
return false;
if (!await _cs.RemoveAsync(user, "BlackJack-gamble", bet, gamble: true).ConfigureAwait(false))
if (!await _cs.RemoveAsync(user, "BlackJack-gamble", bet, gamble: true))
{
return false;
}
@ -145,14 +145,14 @@ public class Blackjack
var cu = CurrentUser;
if (cu != null && cu.DiscordUser == u)
return await Stand(cu).ConfigureAwait(false);
return await Stand(cu);
return false;
}
public async Task<bool> Stand(User u)
{
await locker.WaitAsync().ConfigureAwait(false);
await locker.WaitAsync();
try
{
if (State != GameState.Playing)
@ -229,7 +229,7 @@ public class Blackjack
{
if (usr.State is User.UserState.Won or User.UserState.Blackjack)
{
await _cs.AddAsync(usr.DiscordUser.Id, "BlackJack-win", usr.Bet * 2, gamble: true).ConfigureAwait(false);
await _cs.AddAsync(usr.DiscordUser.Id, "BlackJack-win", usr.Bet * 2, gamble: true);
}
}
}
@ -239,14 +239,14 @@ public class Blackjack
var cu = CurrentUser;
if (cu != null && cu.DiscordUser == u)
return await Double(cu).ConfigureAwait(false);
return await Double(cu);
return false;
}
public async Task<bool> Double(User u)
{
await locker.WaitAsync().ConfigureAwait(false);
await locker.WaitAsync();
try
{
if (State != GameState.Playing)
@ -255,7 +255,7 @@ public class Blackjack
if (CurrentUser != u)
return false;
if (!await _cs.RemoveAsync(u.DiscordUser.Id, "Blackjack-double", u.Bet).ConfigureAwait(false))
if (!await _cs.RemoveAsync(u.DiscordUser.Id, "Blackjack-double", u.Bet))
return false;
u.Bet *= 2;
@ -292,14 +292,14 @@ public class Blackjack
var cu = CurrentUser;
if (cu != null && cu.DiscordUser == u)
return await Hit(cu).ConfigureAwait(false);
return await Hit(cu);
return false;
}
public async Task<bool> Hit(User u)
{
await locker.WaitAsync().ConfigureAwait(false);
await locker.WaitAsync();
try
{
if (State != GameState.Playing)

View file

@ -1,4 +1,4 @@
#nullable disable
#nullable disable
using NadekoBot.Services.Database.Models;
namespace NadekoBot.Modules.Gambling.Common.Events;
@ -78,14 +78,14 @@ public class GameStatusEvent : ICurrencyEvent
await _cs.AddBulkAsync(toAward,
toAward.Select(x => "GameStatus Event"),
toAward.Select(x => _amount),
gamble: true).ConfigureAwait(false);
gamble: true);
if (_isPotLimited)
{
await _msg.ModifyAsync(m =>
{
m.Embed = GetEmbed(PotSize).Build();
}, new() { RetryMode = RetryMode.AlwaysRetry }).ConfigureAwait(false);
}, new() { RetryMode = RetryMode.AlwaysRetry });
}
Log.Information("Awarded {0} users {1} currency.{2}",
@ -107,8 +107,8 @@ public class GameStatusEvent : ICurrencyEvent
public async Task StartEvent()
{
_msg = await _channel.EmbedAsync(GetEmbed(_opts.PotSize)).ConfigureAwait(false);
await _client.SetGameAsync(_code).ConfigureAwait(false);
_msg = await _channel.EmbedAsync(GetEmbed(_opts.PotSize));
await _client.SetGameAsync(_code);
_client.MessageDeleted += OnMessageDeleted;
_client.MessageReceived += HandleMessage;
_t.Change(TimeSpan.FromSeconds(2), TimeSpan.FromSeconds(2));
@ -121,7 +121,7 @@ public class GameStatusEvent : ICurrencyEvent
{
if (msg.Id == _msg.Id)
{
await StopEvent().ConfigureAwait(false);
await StopEvent();
}
}

View file

@ -1,4 +1,4 @@
#nullable disable
#nullable disable
using NadekoBot.Services.Database.Models;
namespace NadekoBot.Modules.Gambling.Common.Events;
@ -74,14 +74,14 @@ public class ReactionEvent : ICurrencyEvent
await _cs.AddBulkAsync(toAward,
toAward.Select(x => "Reaction Event"),
toAward.Select(x => _amount),
gamble: true).ConfigureAwait(false);
gamble: true);
if (_isPotLimited)
{
await _msg.ModifyAsync(m =>
{
m.Embed = GetEmbed(PotSize).Build();
}, new() { RetryMode = RetryMode.AlwaysRetry }).ConfigureAwait(false);
}, new() { RetryMode = RetryMode.AlwaysRetry });
}
Log.Information("Awarded {0} users {1} currency.{2}",
@ -110,8 +110,8 @@ public class ReactionEvent : ICurrencyEvent
{
_emote = new Emoji(_config.Currency.Sign);
}
_msg = await _channel.EmbedAsync(GetEmbed(_opts.PotSize)).ConfigureAwait(false);
await _msg.AddReactionAsync(_emote).ConfigureAwait(false);
_msg = await _channel.EmbedAsync(GetEmbed(_opts.PotSize));
await _msg.AddReactionAsync(_emote);
_client.MessageDeleted += OnMessageDeleted;
_client.ReactionAdded += HandleReaction;
_t.Change(TimeSpan.FromSeconds(2), TimeSpan.FromSeconds(2));
@ -124,7 +124,7 @@ public class ReactionEvent : ICurrencyEvent
{
if (msg.Id == _msg.Id)
{
await StopEvent().ConfigureAwait(false);
await StopEvent();
}
}

View file

@ -1,4 +1,4 @@
#nullable disable
#nullable disable
namespace NadekoBot.Modules.Gambling.Common;
public class RollDuelGame
@ -47,13 +47,13 @@ public class RollDuelGame
_timeoutTimer = new(async delegate
{
await _locker.WaitAsync().ConfigureAwait(false);
await _locker.WaitAsync();
try
{
if (CurrentState != State.Waiting)
return;
CurrentState = State.Ended;
await (OnEnded?.Invoke(this, Reason.Timeout)).ConfigureAwait(false);
await (OnEnded?.Invoke(this, Reason.Timeout));
}
catch { }
finally
@ -65,7 +65,7 @@ public class RollDuelGame
public async Task StartGame()
{
await _locker.WaitAsync().ConfigureAwait(false);
await _locker.WaitAsync();
try
{
if (CurrentState != State.Waiting)
@ -78,16 +78,16 @@ public class RollDuelGame
_locker.Release();
}
if(!await _cs.RemoveAsync(P1, "Roll Duel", Amount).ConfigureAwait(false))
if(!await _cs.RemoveAsync(P1, "Roll Duel", Amount))
{
await (OnEnded?.Invoke(this, Reason.NoFunds)).ConfigureAwait(false);
await (OnEnded?.Invoke(this, Reason.NoFunds));
CurrentState = State.Ended;
return;
}
if(!await _cs.RemoveAsync(P2, "Roll Duel", Amount).ConfigureAwait(false))
if(!await _cs.RemoveAsync(P2, "Roll Duel", Amount))
{
await _cs.AddAsync(P1, "Roll Duel - refund", Amount).ConfigureAwait(false);
await (OnEnded?.Invoke(this, Reason.NoFunds)).ConfigureAwait(false);
await _cs.AddAsync(P1, "Roll Duel - refund", Amount);
await (OnEnded?.Invoke(this, Reason.NoFunds));
CurrentState = State.Ended;
return;
}
@ -109,20 +109,18 @@ public class RollDuelGame
Winner = P2;
}
var won = (long)(Amount * 2 * 0.98f);
await _cs.AddAsync(Winner, "Roll Duel win", won)
.ConfigureAwait(false);
await _cs.AddAsync(Winner, "Roll Duel win", won);
await _cs.AddAsync(_botId, "Roll Duel fee", (Amount * 2) - won)
.ConfigureAwait(false);
await _cs.AddAsync(_botId, "Roll Duel fee", (Amount * 2) - won);
}
try { await (OnGameTick?.Invoke(this)).ConfigureAwait(false); } catch { }
await Task.Delay(2500).ConfigureAwait(false);
try { await (OnGameTick?.Invoke(this)); } catch { }
await Task.Delay(2500);
if (n1 != n2)
break;
}
while (true);
CurrentState = State.Ended;
await (OnEnded?.Invoke(this, Reason.Normal)).ConfigureAwait(false);
await (OnEnded?.Invoke(this, Reason.Normal));
}
}

View file

@ -1,4 +1,4 @@
#nullable disable
#nullable disable
namespace NadekoBot.Modules.Gambling.Common.WheelOfFortune;
public class WheelOfFortuneGame
@ -31,7 +31,7 @@ public class WheelOfFortuneGame
var amount = (long)(_bet * _config.WheelOfFortune.Multipliers[result]);
if (amount > 0)
await _cs.AddAsync(_userId, "Wheel Of Fortune - won", amount, gamble: true).ConfigureAwait(false);
await _cs.AddAsync(_userId, "Wheel Of Fortune - won", amount, gamble: true);
return new()
{

View file

@ -1,4 +1,4 @@
#nullable disable
#nullable disable
using CommandLine;
using System.Collections.Immutable;
@ -88,15 +88,15 @@ public sealed class Connect4Game : IDisposable
return;
var _ = Task.Run(async () =>
{
await Task.Delay(15000).ConfigureAwait(false);
await _locker.WaitAsync().ConfigureAwait(false);
await Task.Delay(15000);
await _locker.WaitAsync();
try
{
if (_players[1] is null)
{
var __ = OnGameFailedToStart?.Invoke(this);
CurrentPhase = Phase.Ended;
await _cs.AddAsync(_players[0].Value.UserId, "Connect4-refund", _options.Bet, true).ConfigureAwait(false);
await _cs.AddAsync(_players[0].Value.UserId, "Connect4-refund", _options.Bet, true);
return;
}
}
@ -106,7 +106,7 @@ public sealed class Connect4Game : IDisposable
public async Task<bool> Join(ulong userId, string userName, int bet)
{
await _locker.WaitAsync().ConfigureAwait(false);
await _locker.WaitAsync();
try
{
if (CurrentPhase != Phase.Joining) //can't join if its not a joining phase
@ -118,7 +118,7 @@ public sealed class Connect4Game : IDisposable
if (bet != _options.Bet) // can't join if bet amount is not the same
return false;
if (!await _cs.RemoveAsync(userId, "Connect4-bet", bet, true).ConfigureAwait(false)) // user doesn't have enough money to gamble
if (!await _cs.RemoveAsync(userId, "Connect4-bet", bet, true)) // user doesn't have enough money to gamble
return false;
if (_rng.Next(0, 2) == 0) //rolling from 0-1, if number is 0, join as first player
@ -132,7 +132,7 @@ public sealed class Connect4Game : IDisposable
CurrentPhase = Phase.P1Move; //start the game
_playerTimeoutTimer = new(async state =>
{
await _locker.WaitAsync().ConfigureAwait(false);
await _locker.WaitAsync();
try
{
EndGame(Result.OtherPlayerWon, OtherPlayer.UserId);
@ -148,7 +148,7 @@ public sealed class Connect4Game : IDisposable
public async Task<bool> Input(ulong userId, int inputCol)
{
await _locker.WaitAsync().ConfigureAwait(false);
await _locker.WaitAsync();
try
{
inputCol -= 1;

View file

@ -1,4 +1,4 @@
#nullable disable
#nullable disable
using NadekoBot.Modules.Gambling.Common;
using NadekoBot.Modules.Gambling.Common.Connect4;
using NadekoBot.Modules.Gambling.Services;
@ -28,7 +28,7 @@ public partial class Gambling
public async Task Connect4(params string[] args)
{
var (options, _) = OptionsParser.ParseFrom(new Connect4Game.Options(), args);
if (!await CheckBetOptional(options.Bet).ConfigureAwait(false))
if (!await CheckBetOptional(options.Bet))
return;
var newGame = new Connect4Game(ctx.User.Id, ctx.User.ToString(), options, _cs);
@ -40,13 +40,13 @@ public partial class Gambling
newGame.Dispose();
//means game already exists, try to join
var joined = await game.Join(ctx.User.Id, ctx.User.ToString(), options.Bet).ConfigureAwait(false);
var joined = await game.Join(ctx.User.Id, ctx.User.ToString(), options.Bet);
return;
}
if (options.Bet > 0)
{
if (!await _cs.RemoveAsync(ctx.User.Id, "Connect4-bet", options.Bet, true).ConfigureAwait(false))
if (!await _cs.RemoveAsync(ctx.User.Id, "Connect4-bet", options.Bet, true))
{
await ReplyErrorLocalizedAsync(strs.not_enough(CurrencySign));
_service.Connect4Games.TryRemove(ctx.Channel.Id, out _);
@ -63,7 +63,7 @@ public partial class Gambling
game.Initialize();
if (options.Bet == 0)
{
await ReplyConfirmLocalizedAsync(strs.connect4_created).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.connect4_created);
}
else
{
@ -80,11 +80,11 @@ public partial class Gambling
var success = false;
if (int.TryParse(arg.Content, out var col))
{
success = await game.Input(arg.Author.Id, col).ConfigureAwait(false);
success = await game.Input(arg.Author.Id, col);
}
if (success)
try { await arg.DeleteAsync().ConfigureAwait(false); } catch { }
try { await arg.DeleteAsync(); } catch { }
else
{
if (game.CurrentPhase is Connect4Game.Phase.Joining or Connect4Game.Phase.Ended)
@ -93,7 +93,7 @@ public partial class Gambling
}
RepostCounter++;
if (RepostCounter == 0)
try { msg = await ctx.Channel.SendMessageAsync("", embed: (Embed)msg.Embeds.First()).ConfigureAwait(false); } catch { }
try { msg = await ctx.Channel.SendMessageAsync("", embed: (Embed)msg.Embeds.First()); } catch { }
}
});
return Task.CompletedTask;
@ -160,9 +160,9 @@ public partial class Gambling
if (msg is null)
msg = await ctx.Channel.EmbedAsync(embed).ConfigureAwait(false);
msg = await ctx.Channel.EmbedAsync(embed);
else
await msg.ModifyAsync(x => x.Embed = embed.Build()).ConfigureAwait(false);
await msg.ModifyAsync(x => x.Embed = embed.Build());
}
private string GetGameStateText(Connect4Game game)

View file

@ -1,4 +1,4 @@
#nullable disable
#nullable disable
using NadekoBot.Modules.Gambling.Services;
using NadekoBot.Modules.Gambling.Common.Events;
using NadekoBot.Services.Database.Models;
@ -28,7 +28,7 @@ public partial class Gambling
opts,
GetEmbed))
{
await ReplyErrorLocalizedAsync(strs.start_event_fail).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.start_event_fail);
}
}

View file

@ -1,4 +1,4 @@
#nullable disable
#nullable disable
using NadekoBot.Modules.Gambling.Services;
using NadekoBot.Modules.Gambling.Common;
@ -25,15 +25,14 @@ public partial class Gambling
[Priority(1)]
public async Task RaffleCur(ShmartNumber amount, bool mixed = false)
{
if (!await CheckBetMandatory(amount).ConfigureAwait(false))
if (!await CheckBetMandatory(amount))
return;
async Task OnEnded(IUser arg, long won)
{
await SendConfirmAsync(GetText(strs.rafflecur_ended(CurrencyName, Format.Bold(arg.ToString()), won + CurrencySign)));
}
var res = await _service.JoinOrCreateGame(ctx.Channel.Id,
ctx.User, amount, mixed, OnEnded)
.ConfigureAwait(false);
ctx.User, amount, mixed, OnEnded);
if (res.Item1 != null)
{
@ -44,7 +43,7 @@ public partial class Gambling
else
{
if (res.Item2 == CurrencyRaffleService.JoinErrorType.AlreadyJoinedOrInvalidAmount)
await ReplyErrorLocalizedAsync(strs.rafflecur_already_joined).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.rafflecur_already_joined);
else if (res.Item2 == CurrencyRaffleService.JoinErrorType.NotEnoughCurrency)
await ReplyErrorLocalizedAsync(strs.not_enough(CurrencySign));
}

View file

@ -41,23 +41,23 @@ public partial class Gambling
[NadekoCommand, Aliases]
[Priority(1)]
public async Task Roll(int num)
=> await InternalRoll(num, true).ConfigureAwait(false);
=> await InternalRoll(num, true);
[NadekoCommand, Aliases]
[Priority(1)]
public async Task Rolluo(int num = 1)
=> await InternalRoll(num, false).ConfigureAwait(false);
=> await InternalRoll(num, false);
[NadekoCommand, Aliases]
[Priority(0)]
public async Task Roll(string arg)
=> await InternallDndRoll(arg, true).ConfigureAwait(false);
=> await InternallDndRoll(arg, true);
[NadekoCommand, Aliases]
[Priority(0)]
public async Task Rolluo(string arg)
=> await InternallDndRoll(arg, false).ConfigureAwait(false);
=> await InternallDndRoll(arg, false);
private async Task InternalRoll(int num, bool ordered)
{
@ -132,7 +132,7 @@ public partial class Gambling
.WithDescription(ctx.User.Mention + " " + GetText(strs.dice_rolled_num(Format.Bold(n1.ToString()))))
.AddField(Format.Bold("Result"), string.Join(" ", rolls.Select(c => Format.Code($"[{c}]"))));
await ctx.Channel.EmbedAsync(embed).ConfigureAwait(false);
await ctx.Channel.EmbedAsync(embed);
}
else if ((match = dndRegex.Match(arg)).Length != 0)
{
@ -160,7 +160,7 @@ public partial class Gambling
Format.Code(x.ToString()))))
.AddField(Format.Bold("Sum"),
sum + " + " + add + " - " + sub + " = " + (sum + add - sub));
await ctx.Channel.EmbedAsync(embed).ConfigureAwait(false);
await ctx.Channel.EmbedAsync(embed);
}
}
}
@ -177,7 +177,7 @@ public partial class Gambling
.ToArray();
if (arr[0] > arr[1])
{
await ReplyErrorLocalizedAsync(strs.second_larger_than_first).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.second_larger_than_first);
return;
}
rolled = new NadekoRandom().Next(arr[0], arr[1] + 1);
@ -187,7 +187,7 @@ public partial class Gambling
rolled = new NadekoRandom().Next(0, int.Parse(range) + 1);
}
await ReplyConfirmLocalizedAsync(strs.dice_rolled(Format.Bold(rolled.ToString()))).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.dice_rolled(Format.Bold(rolled.ToString())));
}
private Image<Rgba32> GetDice(int num)

View file

@ -1,4 +1,4 @@
#nullable disable
#nullable disable
using NadekoBot.Modules.Gambling.Common;
using Image = SixLabors.ImageSharp.Image;
using SixLabors.ImageSharp;
@ -31,7 +31,7 @@ public partial class Gambling
{
try
{
await ReplyErrorLocalizedAsync(strs.no_more_cards).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.no_more_cards);
}
catch
{
@ -69,10 +69,10 @@ public partial class Gambling
if (num > 10)
num = 10;
var (ImageStream, ToSend) = await InternalDraw(num, ctx.Guild.Id).ConfigureAwait(false);
var (ImageStream, ToSend) = await InternalDraw(num, ctx.Guild.Id);
await using (ImageStream)
{
await ctx.Channel.SendFileAsync(ImageStream, num + " cards.jpg", ToSend).ConfigureAwait(false);
await ctx.Channel.SendFileAsync(ImageStream, num + " cards.jpg", ToSend);
}
}
@ -84,10 +84,10 @@ public partial class Gambling
if (num > 10)
num = 10;
var (ImageStream, ToSend) = await InternalDraw(num).ConfigureAwait(false);
var (ImageStream, ToSend) = await InternalDraw(num);
await using (ImageStream)
{
await ctx.Channel.SendFileAsync(ImageStream, num + " cards.jpg", ToSend).ConfigureAwait(false);
await ctx.Channel.SendFileAsync(ImageStream, num + " cards.jpg", ToSend);
}
}
@ -105,7 +105,7 @@ public partial class Gambling
return c;
});
await ReplyConfirmLocalizedAsync(strs.deck_reshuffled).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.deck_reshuffled);
}
}
}

View file

@ -60,7 +60,7 @@ public partial class Gambling
: Format.Bold(ctx.User.ToString()) + " " + GetText(strs.flipped(headCount > 0
? Format.Bold(GetText(strs.heads))
: Format.Bold(GetText(strs.tails))));
await ctx.Channel.SendFileAsync(stream, $"{count} coins.{format.FileExtensions.First()}", msg).ConfigureAwait(false);
await ctx.Channel.SendFileAsync(stream, $"{count} coins.{format.FileExtensions.First()}", msg);
}
public enum BetFlipGuess
@ -76,10 +76,10 @@ public partial class Gambling
[NadekoCommand, Aliases]
public async Task Betflip(ShmartNumber amount, BetFlipGuess guess)
{
if (!await CheckBetMandatory(amount).ConfigureAwait(false) || amount == 1)
if (!await CheckBetMandatory(amount) || amount == 1)
return;
var removed = await _cs.RemoveAsync(ctx.User, "Betflip Gamble", amount, false, gamble: true).ConfigureAwait(false);
var removed = await _cs.RemoveAsync(ctx.User, "Betflip Gamble", amount, false, gamble: true);
if (!removed)
{
await ReplyErrorLocalizedAsync(strs.not_enough(CurrencySign));
@ -104,7 +104,7 @@ public partial class Gambling
{
var toWin = (long)(amount * _config.BetFlip.Multiplier);
str = Format.Bold(ctx.User.ToString()) + " " + GetText(strs.flip_guess(toWin + CurrencySign));
await _cs.AddAsync(ctx.User, "Betflip Gamble", toWin, false, gamble: true).ConfigureAwait(false);
await _cs.AddAsync(ctx.User, "Betflip Gamble", toWin, false, gamble: true);
}
else
{
@ -114,7 +114,7 @@ public partial class Gambling
await ctx.Channel.EmbedAsync(_eb.Create()
.WithDescription(str)
.WithOkColor()
.WithImageUrl(imageToSend.ToString())).ConfigureAwait(false);
.WithImageUrl(imageToSend.ToString()));
}
}
}

View file

@ -68,7 +68,7 @@ public partial class Gambling : GamblingModule<GamblingService>
.AddField(GetText(strs.total), ((BigInteger)(ec.Cash + ec.Planted + ec.Waifus)).ToString("N", Culture) + CurrencySign)
.WithOkColor();
// ec.Cash already contains ec.Bot as it's the total of all values in the CurrencyAmount column of the DiscordUser table
await ctx.Channel.EmbedAsync(embed).ConfigureAwait(false);
await ctx.Channel.EmbedAsync(embed);
}
[NadekoCommand, Aliases]
@ -78,18 +78,18 @@ public partial class Gambling : GamblingModule<GamblingService>
var period = _config.Timely.Cooldown;
if (val <= 0 || period <= 0)
{
await ReplyErrorLocalizedAsync(strs.timely_none).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.timely_none);
return;
}
TimeSpan? rem;
if ((rem = _cache.AddTimelyClaim(ctx.User.Id, period)) != null)
{
await ReplyErrorLocalizedAsync(strs.timely_already_claimed(rem?.ToString(@"dd\d\ hh\h\ mm\m\ ss\s"))).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.timely_already_claimed(rem?.ToString(@"dd\d\ hh\h\ mm\m\ ss\s")));
return;
}
await _cs.AddAsync(ctx.User.Id, "Timely claim", val).ConfigureAwait(false);
await _cs.AddAsync(ctx.User.Id, "Timely claim", val);
await ReplyConfirmLocalizedAsync(strs.timely(n(val), period));
}
@ -99,7 +99,7 @@ public partial class Gambling : GamblingModule<GamblingService>
public async Task TimelyReset()
{
_cache.RemoveAllTimelyClaims();
await ReplyConfirmLocalizedAsync(strs.timely_reset).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.timely_reset);
}
[NadekoCommand, Aliases]
@ -116,9 +116,9 @@ public partial class Gambling : GamblingModule<GamblingService>
});
if (amount == 0)
await ReplyConfirmLocalizedAsync(strs.timely_set_none).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.timely_set_none);
else
await ReplyConfirmLocalizedAsync(strs.timely_set(Format.Bold(n(amount)), Format.Bold(period.ToString()))).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.timely_set(Format.Bold(n(amount)), Format.Bold(period.ToString())));
}
[NadekoCommand, Aliases]
@ -127,14 +127,14 @@ public partial class Gambling : GamblingModule<GamblingService>
{
role ??= ctx.Guild.EveryoneRole;
var members = (await role.GetMembersAsync().ConfigureAwait(false)).Where(u => u.Status != UserStatus.Offline);
var members = (await role.GetMembersAsync()).Where(u => u.Status != UserStatus.Offline);
var membersArray = members as IUser[] ?? members.ToArray();
if (membersArray.Length == 0)
{
return;
}
var usr = membersArray[new NadekoRandom().Next(0, membersArray.Length)];
await SendConfirmAsync("🎟 " + GetText(strs.raffled_user), $"**{usr.Username}#{usr.Discriminator}**", footer: $"ID: {usr.Id}").ConfigureAwait(false);
await SendConfirmAsync("🎟 " + GetText(strs.raffled_user), $"**{usr.Username}#{usr.Discriminator}**", footer: $"ID: {usr.Id}");
}
[NadekoCommand, Aliases]
@ -143,14 +143,14 @@ public partial class Gambling : GamblingModule<GamblingService>
{
role ??= ctx.Guild.EveryoneRole;
var members = await role.GetMembersAsync().ConfigureAwait(false);
var members = await role.GetMembersAsync();
var membersArray = members as IUser[] ?? members.ToArray();
if (membersArray.Length == 0)
{
return;
}
var usr = membersArray[new NadekoRandom().Next(0, membersArray.Length)];
await SendConfirmAsync("🎟 " + GetText(strs.raffled_user), $"**{usr.Username}#{usr.Discriminator}**", footer: $"ID: {usr.Id}").ConfigureAwait(false);
await SendConfirmAsync("🎟 " + GetText(strs.raffled_user), $"**{usr.Username}#{usr.Discriminator}**", footer: $"ID: {usr.Id}");
}
[NadekoCommand, Aliases]
@ -196,7 +196,7 @@ public partial class Gambling : GamblingModule<GamblingService>
embed.WithDescription(desc);
embed.WithFooter(GetText(strs.page(page + 1)));
await ctx.Channel.EmbedAsync(embed).ConfigureAwait(false);
await ctx.Channel.EmbedAsync(embed);
}
[NadekoCommand, Aliases]
@ -219,13 +219,13 @@ public partial class Gambling : GamblingModule<GamblingService>
{
if (amount <= 0 || ctx.User.Id == receiver.Id || receiver.IsBot)
return;
var success = await _cs.RemoveAsync((IGuildUser)ctx.User, $"Gift to {receiver.Username} ({receiver.Id}).", amount, false).ConfigureAwait(false);
var success = await _cs.RemoveAsync((IGuildUser)ctx.User, $"Gift to {receiver.Username} ({receiver.Id}).", amount, false);
if (!success)
{
await ReplyErrorLocalizedAsync(strs.not_enough(CurrencySign));
return;
}
await _cs.AddAsync(receiver, $"Gift from {ctx.User.Username} ({ctx.User.Id}) - {msg}.", amount, true).ConfigureAwait(false);
await _cs.AddAsync(receiver, $"Gift from {ctx.User.Username} ({ctx.User.Id}) - {msg}.", amount, true);
await ReplyConfirmLocalizedAsync(strs.gifted(n(amount), Format.Bold(receiver.ToString())));
}
@ -261,14 +261,14 @@ public partial class Gambling : GamblingModule<GamblingService>
if(usr is null)
{
await ReplyErrorLocalizedAsync(strs.user_not_found).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.user_not_found);
return;
}
await _cs.AddAsync(usr,
$"Awarded by bot owner. ({ctx.User.Username}/{ctx.User.Id}) {msg ?? ""}",
amount,
gamble: ctx.Client.CurrentUser.Id != usrId).ConfigureAwait(false);
gamble: ctx.Client.CurrentUser.Id != usrId);
await ReplyConfirmLocalizedAsync(strs.awarded(n(amount), $"<@{usrId}>"));
}
@ -278,15 +278,14 @@ public partial class Gambling : GamblingModule<GamblingService>
[Priority(3)]
public async Task Award(long amount, [Leftover] IRole role)
{
var users = (await ctx.Guild.GetUsersAsync().ConfigureAwait(false))
var users = (await ctx.Guild.GetUsersAsync())
.Where(u => u.GetRoles().Contains(role))
.ToList();
await _cs.AddBulkAsync(users.Select(x => x.Id),
users.Select(x => $"Awarded by bot owner to **{role.Name}** role. ({ctx.User.Username}/{ctx.User.Id})"),
users.Select(x => amount),
gamble: true)
.ConfigureAwait(false);
gamble: true);
await ReplyConfirmLocalizedAsync(strs.mass_award(
n(amount),
@ -305,8 +304,7 @@ public partial class Gambling : GamblingModule<GamblingService>
await _cs.RemoveBulkAsync(users.Select(x => x.Id),
users.Select(x => $"Taken by bot owner from **{role.Name}** role. ({ctx.User.Username}/{ctx.User.Id})"),
users.Select(x => amount),
gamble: true)
.ConfigureAwait(false);
gamble: true);
await ReplyConfirmLocalizedAsync(strs.mass_take(
n(amount),
@ -324,8 +322,8 @@ public partial class Gambling : GamblingModule<GamblingService>
return;
if (await _cs.RemoveAsync(user, $"Taken by bot owner.({ctx.User.Username}/{ctx.User.Id})", amount,
gamble: ctx.Client.CurrentUser.Id != user.Id).ConfigureAwait(false))
await ReplyConfirmLocalizedAsync(strs.take(n(amount), Format.Bold(user.ToString()))).ConfigureAwait(false);
gamble: ctx.Client.CurrentUser.Id != user.Id))
await ReplyConfirmLocalizedAsync(strs.take(n(amount), Format.Bold(user.ToString())));
else
await ReplyErrorLocalizedAsync(strs.take_fail(n(amount), Format.Bold(user.ToString()), CurrencySign));
}
@ -339,7 +337,7 @@ public partial class Gambling : GamblingModule<GamblingService>
return;
if (await _cs.RemoveAsync(usrId, $"Taken by bot owner.({ctx.User.Username}/{ctx.User.Id})", amount,
gamble: ctx.Client.CurrentUser.Id != usrId).ConfigureAwait(false))
gamble: ctx.Client.CurrentUser.Id != usrId))
await ReplyConfirmLocalizedAsync(strs.take(n(amount), $"<@{usrId}>"));
else
await ReplyErrorLocalizedAsync(strs.take_fail(n(amount), Format.Code(usrId.ToString()), CurrencySign));
@ -358,7 +356,7 @@ public partial class Gambling : GamblingModule<GamblingService>
//if it gets removed, means challenge is accepted
if (_service.Duels.TryRemove((ctx.User.Id, u.Id), out var game))
{
await game.StartGame().ConfigureAwait(false);
await game.StartGame();
}
}
@ -384,11 +382,11 @@ public partial class Gambling : GamblingModule<GamblingService>
{
if (other.Amount != amount)
{
await ReplyErrorLocalizedAsync(strs.roll_duel_already_challenged).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.roll_duel_already_challenged);
}
else
{
await RollDuel(u).ConfigureAwait(false);
await RollDuel(u);
}
return;
}
@ -414,15 +412,14 @@ public partial class Gambling : GamblingModule<GamblingService>
if (rdMsg is null)
{
rdMsg = await ctx.Channel.EmbedAsync(embed)
.ConfigureAwait(false);
rdMsg = await ctx.Channel.EmbedAsync(embed);
}
else
{
await rdMsg.ModifyAsync(x =>
{
x.Embed = embed.Build();
}).ConfigureAwait(false);
});
}
}
@ -439,16 +436,15 @@ public partial class Gambling : GamblingModule<GamblingService>
embed = embed.WithDescription(description);
await rdMsg.ModifyAsync(x => x.Embed = embed.Build())
.ConfigureAwait(false);
await rdMsg.ModifyAsync(x => x.Embed = embed.Build());
}
else if (reason == RollDuelGame.Reason.Timeout)
{
await ReplyErrorLocalizedAsync(strs.roll_duel_timeout).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.roll_duel_timeout);
}
else if (reason == RollDuelGame.Reason.NoFunds)
{
await ReplyErrorLocalizedAsync(strs.roll_duel_no_funds).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.roll_duel_no_funds);
}
}
finally
@ -460,10 +456,10 @@ public partial class Gambling : GamblingModule<GamblingService>
private async Task InternallBetroll(long amount)
{
if (!await CheckBetMandatory(amount).ConfigureAwait(false))
if (!await CheckBetMandatory(amount))
return;
if (!await _cs.RemoveAsync(ctx.User, "Betroll Gamble", amount, false, gamble: true).ConfigureAwait(false))
if (!await _cs.RemoveAsync(ctx.User, "Betroll Gamble", amount, false, gamble: true))
{
await ReplyErrorLocalizedAsync(strs.not_enough(CurrencySign));
return;
@ -482,14 +478,14 @@ public partial class Gambling : GamblingModule<GamblingService>
n(win),
result.Threshold + (result.Roll == 100 ? " 👑" : "")));
await _cs.AddAsync(ctx.User, "Betroll Gamble",
win, false, gamble: true).ConfigureAwait(false);
win, false, gamble: true);
}
else
{
str += GetText(strs.better_luck);
}
await SendConfirmAsync(str).ConfigureAwait(false);
await SendConfirmAsync(str);
}
[NadekoCommand, Aliases]
@ -528,8 +524,8 @@ public partial class Gambling : GamblingModule<GamblingService>
cleanRichest = uow.DiscordUser.GetTopRichest(_client.CurrentUser.Id, 10_000);
}
await ctx.Channel.TriggerTypingAsync().ConfigureAwait(false);
await _tracker.EnsureUsersDownloadedAsync(ctx.Guild).ConfigureAwait(false);
await ctx.Channel.TriggerTypingAsync();
await _tracker.EnsureUsersDownloadedAsync(ctx.Guild);
var sg = (SocketGuild)ctx.Guild;
cleanRichest = cleanRichest.Where(x => sg.GetUser(x.UserId) != null)
@ -600,7 +596,7 @@ public partial class Gambling : GamblingModule<GamblingService>
public async Task Rps(RpsPick pick, ShmartNumber amount = default)
{
long oldAmount = amount;
if (!await CheckBetOptional(amount).ConfigureAwait(false) || amount == 1)
if (!await CheckBetOptional(amount) || amount == 1)
return;
string getRpsPick(RpsPick p)
@ -622,7 +618,7 @@ public partial class Gambling : GamblingModule<GamblingService>
if (amount > 0)
{
if (!await _cs.RemoveAsync(ctx.User.Id,
"Rps-bet", amount, gamble: true).ConfigureAwait(false))
"Rps-bet", amount, gamble: true))
{
await ReplyErrorLocalizedAsync(strs.not_enough(CurrencySign));
return;
@ -633,7 +629,7 @@ public partial class Gambling : GamblingModule<GamblingService>
if (pick == nadekoPick)
{
await _cs.AddAsync(ctx.User.Id,
"Rps-draw", amount, gamble: true).ConfigureAwait(false);
"Rps-draw", amount, gamble: true);
embed.WithOkColor();
msg = GetText(strs.rps_draw(getRpsPick(pick)));
}
@ -643,7 +639,7 @@ public partial class Gambling : GamblingModule<GamblingService>
{
amount = (long)(amount * base._config.BetFlip.Multiplier);
await _cs.AddAsync(ctx.User.Id,
"Rps-win", amount, gamble: true).ConfigureAwait(false);
"Rps-win", amount, gamble: true);
embed.WithOkColor();
embed.AddField(GetText(strs.won), n(amount));
msg = GetText(strs.rps_win(ctx.User.Mention, getRpsPick(pick), getRpsPick(nadekoPick)));
@ -658,6 +654,6 @@ public partial class Gambling : GamblingModule<GamblingService>
embed
.WithDescription(msg);
await ctx.Channel.EmbedAsync(embed).ConfigureAwait(false);
await ctx.Channel.EmbedAsync(embed);
}
}

View file

@ -37,7 +37,7 @@ public partial class Gambling
try
{
logService.AddDeleteIgnore(ctx.Message.Id);
await ctx.Message.DeleteAsync().ConfigureAwait(false);
await ctx.Message.DeleteAsync();
}
catch { }
}
@ -58,7 +58,7 @@ public partial class Gambling
if (((SocketGuild)ctx.Guild).CurrentUser.GuildPermissions.ManageMessages)
{
logService.AddDeleteIgnore(ctx.Message.Id);
await ctx.Message.DeleteAsync().ConfigureAwait(false);
await ctx.Message.DeleteAsync();
}
var success = await _service.PlantAsync(ctx.Guild.Id, ctx.Channel, ctx.User.Id, ctx.User.ToString(), amount, pass);
@ -79,11 +79,11 @@ public partial class Gambling
var enabled = _service.ToggleCurrencyGeneration(ctx.Guild.Id, ctx.Channel.Id);
if (enabled)
{
await ReplyConfirmLocalizedAsync(strs.curgen_enabled).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.curgen_enabled);
}
else
{
await ReplyConfirmLocalizedAsync(strs.curgen_disabled).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.curgen_disabled);
}
}

View file

@ -1,4 +1,4 @@
#nullable disable
#nullable disable
using NadekoBot.Modules.Gambling.Common.Events;
using NadekoBot.Modules.Gambling.Common;
using NadekoBot.Services.Database.Models;
@ -52,7 +52,7 @@ public class CurrencyEventsService : INService
try
{
ce.OnEnded += OnEventEnded;
await ce.StartEvent().ConfigureAwait(false);
await ce.StartEvent();
}
catch (Exception ex)
{

View file

@ -1,4 +1,4 @@
#nullable disable
#nullable disable
using NadekoBot.Modules.Gambling.Common;
namespace NadekoBot.Modules.Gambling.Services;
@ -24,7 +24,7 @@ public class CurrencyRaffleService : INService
public async Task<(CurrencyRaffleGame, JoinErrorType?)> JoinOrCreateGame(ulong channelId, IUser user, long amount, bool mixed, Func<IUser, long, Task> onEnded)
{
await _locker.WaitAsync().ConfigureAwait(false);
await _locker.WaitAsync();
try
{
var newGame = false;
@ -39,7 +39,7 @@ public class CurrencyRaffleService : INService
//remove money, and stop the game if this
// user created it and doesn't have the money
if (!await _cs.RemoveAsync(user.Id, "Currency Raffle Join", amount).ConfigureAwait(false))
if (!await _cs.RemoveAsync(user.Id, "Currency Raffle Join", amount))
{
if (newGame)
Games.Remove(channelId);
@ -48,22 +48,22 @@ public class CurrencyRaffleService : INService
if (!crg.AddUser(user, amount))
{
await _cs.AddAsync(user.Id, "Curency Raffle Refund", amount).ConfigureAwait(false);
await _cs.AddAsync(user.Id, "Curency Raffle Refund", amount);
return (null, JoinErrorType.AlreadyJoinedOrInvalidAmount);
}
if (newGame)
{
var _t = Task.Run(async () =>
{
await Task.Delay(60000).ConfigureAwait(false);
await _locker.WaitAsync().ConfigureAwait(false);
await Task.Delay(60000);
await _locker.WaitAsync();
try
{
var winner = crg.GetWinner();
var won = crg.Users.Sum(x => x.Amount);
await _cs.AddAsync(winner.DiscordUser.Id, "Currency Raffle Win",
won).ConfigureAwait(false);
won);
Games.Remove(channelId, out _);
var oe = onEnded(winner.DiscordUser, won);
}

View file

@ -1,4 +1,4 @@
#nullable disable
#nullable disable
using NadekoBot.Common.Configs;
using NadekoBot.Modules.Gambling.Common;
@ -50,7 +50,7 @@ public sealed class GamblingConfigService : ConfigServiceBase<GamblingConfig>
public void Migrate()
{
if (_data.Version < 2)
if (data.Version < 2)
{
ModifyConfig(c =>
{
@ -59,7 +59,7 @@ public sealed class GamblingConfigService : ConfigServiceBase<GamblingConfig>
});
}
if (_data.Version < 3)
if (data.Version < 3)
{
ModifyConfig(c =>
{
@ -68,7 +68,7 @@ public sealed class GamblingConfigService : ConfigServiceBase<GamblingConfig>
});
}
if (_data.Version < 4)
if (data.Version < 4)
{
ModifyConfig(c =>
{

View file

@ -1,4 +1,4 @@
#nullable disable
#nullable disable
using Microsoft.EntityFrameworkCore;
using NadekoBot.Services.Database.Models;
using SixLabors.Fonts;
@ -203,7 +203,7 @@ public class PlantPickService : INService
IUserMessage sent;
await using (var stream = GetRandomCurrencyImage(pw, out var ext))
{
sent = await channel.SendFileAsync(stream, $"currency_image.{ext}", toSend).ConfigureAwait(false);
sent = await channel.SendFileAsync(stream, $"currency_image.{ext}", toSend);
}
await AddPlantToDatabase(channel.GuildId,
@ -211,7 +211,7 @@ public class PlantPickService : INService
_client.CurrentUser.Id,
sent.Id,
dropAmount,
pw).ConfigureAwait(false);
pw);
}
}
}
@ -302,7 +302,7 @@ public class PlantPickService : INService
//get the image
await using var stream = GetRandomCurrencyImage(pass, out var ext);
// send it
var msg = await ch.SendFileAsync(stream, $"img.{ext}", msgToSend).ConfigureAwait(false);
var msg = await ch.SendFileAsync(stream, $"img.{ext}", msgToSend);
// return sent message's id (in order to be able to delete it when it's picked)
return msg.Id;
}
@ -325,7 +325,7 @@ public class PlantPickService : INService
if (await _cs.RemoveAsync(uid, "Planted currency", amount, gamble: false))
{
// try to send the message with the currency image
var msgId = await SendPlantMessageAsync(gid, ch, user, amount, pass).ConfigureAwait(false);
var msgId = await SendPlantMessageAsync(gid, ch, user, amount, pass);
if (msgId is null)
{
// if it fails it will return null, if it returns null, refund
@ -333,7 +333,7 @@ public class PlantPickService : INService
return false;
}
// if it doesn't fail, put the plant in the database for other people to pick
await AddPlantToDatabase(gid, ch.Id, uid, msgId.Value, amount, pass).ConfigureAwait(false);
await AddPlantToDatabase(gid, ch.Id, uid, msgId.Value, amount, pass);
return true;
}
// if user doesn't have enough currency, fail

View file

@ -1,4 +1,4 @@
#nullable disable
#nullable disable
using Microsoft.EntityFrameworkCore;
using NadekoBot.Common.Collections;
using NadekoBot.Modules.Gambling.Common;
@ -95,7 +95,7 @@ public partial class Gambling
if (entry is null)
{
await ReplyErrorLocalizedAsync(strs.shop_item_not_found).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.shop_item_not_found);
return;
}
@ -106,33 +106,33 @@ public partial class Gambling
if (role is null)
{
await ReplyErrorLocalizedAsync(strs.shop_role_not_found).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.shop_role_not_found);
return;
}
if (guser.RoleIds.Any(id => id == role.Id))
{
await ReplyErrorLocalizedAsync(strs.shop_role_already_bought).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.shop_role_already_bought);
return;
}
if (await _cs.RemoveAsync(ctx.User.Id, $"Shop purchase - {entry.Type}", entry.Price).ConfigureAwait(false))
if (await _cs.RemoveAsync(ctx.User.Id, $"Shop purchase - {entry.Type}", entry.Price))
{
try
{
await guser.AddRoleAsync(role).ConfigureAwait(false);
await guser.AddRoleAsync(role);
}
catch (Exception ex)
{
Log.Warning(ex, "Error adding shop role");
await _cs.AddAsync(ctx.User.Id, $"Shop error refund", entry.Price).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.shop_role_purchase_error).ConfigureAwait(false);
await _cs.AddAsync(ctx.User.Id, $"Shop error refund", entry.Price);
await ReplyErrorLocalizedAsync(strs.shop_role_purchase_error);
return;
}
var profit = GetProfitAmount(entry.Price);
await _cs.AddAsync(entry.AuthorId, $"Shop sell item - {entry.Type}", profit).ConfigureAwait(false);
await _cs.AddAsync(ctx.Client.CurrentUser.Id, $"Shop sell item - cut", entry.Price - profit).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.shop_role_purchase(Format.Bold(role.Name))).ConfigureAwait(false);
await _cs.AddAsync(entry.AuthorId, $"Shop sell item - {entry.Type}", profit);
await _cs.AddAsync(ctx.Client.CurrentUser.Id, $"Shop sell item - cut", entry.Price - profit);
await ReplyConfirmLocalizedAsync(strs.shop_role_purchase(Format.Bold(role.Name)));
return;
}
else
@ -145,13 +145,13 @@ public partial class Gambling
{
if (entry.Items.Count == 0)
{
await ReplyErrorLocalizedAsync(strs.out_of_stock).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.out_of_stock);
return;
}
var item = entry.Items.ToArray()[new NadekoRandom().Next(0, entry.Items.Count)];
if (await _cs.RemoveAsync(ctx.User.Id, $"Shop purchase - {entry.Type}", entry.Price).ConfigureAwait(false))
if (await _cs.RemoveAsync(ctx.User.Id, $"Shop purchase - {entry.Type}", entry.Price))
{
await using (var uow = _db.GetDbContext())
{
@ -165,18 +165,17 @@ public partial class Gambling
.WithTitle(GetText(strs.shop_purchase(ctx.Guild.Name)))
.AddField(GetText(strs.item), item.Text, false)
.AddField(GetText(strs.price), entry.Price.ToString(), true)
.AddField(GetText(strs.name), entry.Name, true))
.ConfigureAwait(false);
.AddField(GetText(strs.name), entry.Name, true));
await _cs.AddAsync(entry.AuthorId,
$"Shop sell item - {entry.Name}",
GetProfitAmount(entry.Price)).ConfigureAwait(false);
GetProfitAmount(entry.Price));
}
catch
{
await _cs.AddAsync(ctx.User.Id,
$"Shop error refund - {entry.Name}",
entry.Price).ConfigureAwait(false);
entry.Price);
await using (var uow = _db.GetDbContext())
{
var entries = new IndexedCollection<ShopEntry>(uow.GuildConfigsForId(ctx.Guild.Id,
@ -191,10 +190,10 @@ public partial class Gambling
}
}
}
await ReplyErrorLocalizedAsync(strs.shop_buy_error).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.shop_buy_error);
return;
}
await ReplyConfirmLocalizedAsync(strs.shop_item_purchase).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.shop_item_purchase);
}
else
{
@ -238,7 +237,7 @@ public partial class Gambling
uow.SaveChanges();
}
await ctx.Channel.EmbedAsync(EntryToEmbed(entry)
.WithTitle(GetText(strs.shop_item_add))).ConfigureAwait(false);
.WithTitle(GetText(strs.shop_item_add)));
}
[NadekoCommand, Aliases]
@ -270,7 +269,7 @@ public partial class Gambling
}
await ctx.Channel.EmbedAsync(EntryToEmbed(entry)
.WithTitle(GetText(strs.shop_item_add))).ConfigureAwait(false);
.WithTitle(GetText(strs.shop_item_add)));
}
[NadekoCommand, Aliases]
@ -303,13 +302,13 @@ public partial class Gambling
}
}
if (entry is null)
await ReplyErrorLocalizedAsync(strs.shop_item_not_found).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.shop_item_not_found);
else if (!rightType)
await ReplyErrorLocalizedAsync(strs.shop_item_wrong_type).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.shop_item_wrong_type);
else if (added == false)
await ReplyErrorLocalizedAsync(strs.shop_list_item_not_unique).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.shop_list_item_not_unique);
else
await ReplyConfirmLocalizedAsync(strs.shop_list_item_added).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.shop_list_item_added);
}
[NadekoCommand, Aliases]
@ -338,10 +337,10 @@ public partial class Gambling
}
if (removed is null)
await ReplyErrorLocalizedAsync(strs.shop_item_not_found).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.shop_item_not_found);
else
await ctx.Channel.EmbedAsync(EntryToEmbed(removed)
.WithTitle(GetText(strs.shop_item_rm))).ConfigureAwait(false);
.WithTitle(GetText(strs.shop_item_rm)));
}
[NadekoCommand, Aliases]

View file

@ -1,4 +1,4 @@
#nullable disable
#nullable disable
using System.Text;
using NadekoBot.Db.Models;
using NadekoBot.Modules.Gambling.Services;
@ -106,7 +106,7 @@ public partial class Gambling
.AddField("Paid Out", paid.ToString(), true)
.WithFooter($"Payout Rate: {paid * 1.0 / bet * 100:f4}%");
await ctx.Channel.EmbedAsync(embed).ConfigureAwait(false);
await ctx.Channel.EmbedAsync(embed);
}
[NadekoCommand, Aliases]
@ -134,7 +134,7 @@ public partial class Gambling
payout += key * dict[key];
}
await SendConfirmAsync("Slot Test Results", sb.ToString(),
footer: $"Total Bet: {tests} | Payout: {payout} | {payout * 1.0f / tests * 100}%").ConfigureAwait(false);
footer: $"Total Bet: {tests} | Payout: {payout} | {payout * 1.0f / tests * 100}%");
}
[NadekoCommand, Aliases]
@ -145,10 +145,10 @@ public partial class Gambling
try
{
if (!await CheckBetMandatory(amount).ConfigureAwait(false))
if (!await CheckBetMandatory(amount))
return;
await ctx.Channel.TriggerTypingAsync().ConfigureAwait(false);
await ctx.Channel.TriggerTypingAsync();
var result = await _service.SlotAsync(ctx.User.Id, amount);
@ -239,7 +239,7 @@ public partial class Gambling
{
await ctx.Channel.SendFileAsync(imgStream,
filename: "result.png",
text: Format.Bold(ctx.User.ToString()) + " " + msg).ConfigureAwait(false);
text: Format.Bold(ctx.User.ToString()) + " " + msg);
}
}
}
@ -247,7 +247,7 @@ public partial class Gambling
{
var _ = Task.Run(async () =>
{
await Task.Delay(1000).ConfigureAwait(false);
await Task.Delay(1000);
_runningUsers.Remove(ctx.User.Id);
});
}

View file

@ -1,4 +1,4 @@
#nullable disable
#nullable disable
using Wof = NadekoBot.Modules.Gambling.Common.WheelOfFortune.WheelOfFortuneGame;
using NadekoBot.Modules.Gambling.Services;
using NadekoBot.Modules.Gambling.Common;
@ -33,16 +33,16 @@ public partial class Gambling
[NadekoCommand, Aliases]
public async Task WheelOfFortune(ShmartNumber amount)
{
if (!await CheckBetMandatory(amount).ConfigureAwait(false))
if (!await CheckBetMandatory(amount))
return;
if (!await _cs.RemoveAsync(ctx.User.Id, "Wheel Of Fortune - bet", amount, gamble: true).ConfigureAwait(false))
if (!await _cs.RemoveAsync(ctx.User.Id, "Wheel Of Fortune - bet", amount, gamble: true))
{
await ReplyErrorLocalizedAsync(strs.not_enough(CurrencySign));
return;
}
var result = await _service.WheelOfFortuneSpinAsync(ctx.User.Id, amount).ConfigureAwait(false);
var result = await _service.WheelOfFortuneSpinAsync(ctx.User.Id, amount);
var wofMultipliers = _config.WheelOfFortune.Multipliers;
await SendConfirmAsync(
@ -52,7 +52,7 @@ public partial class Gambling
{wofMultipliers[2]} {_emojis[result.Index]} {wofMultipliers[6]}
{wofMultipliers[3]} {wofMultipliers[4]} {wofMultipliers[5]}")).ConfigureAwait(false);
{wofMultipliers[3]} {wofMultipliers[4]} {wofMultipliers[5]}"));
}
}
}

View file

@ -1,4 +1,4 @@
#nullable disable
#nullable disable
using System.Collections.Immutable;
using NadekoBot.Modules.Games.Common.Acrophobia;
using NadekoBot.Modules.Games.Services;
@ -33,7 +33,7 @@ public partial class Games
game.OnVotingStarted += Game_OnVotingStarted;
game.OnUserVoted += Game_OnUserVoted;
_client.MessageReceived += _client_MessageReceived;
await game.Run().ConfigureAwait(false);
await game.Run();
}
finally
{
@ -44,7 +44,7 @@ public partial class Games
}
else
{
await ReplyErrorLocalizedAsync(strs.acro_running).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.acro_running);
}
Task _client_MessageReceived(SocketMessage msg)
@ -56,10 +56,9 @@ public partial class Games
{
try
{
var success = await game.UserInput(msg.Author.Id, msg.Author.ToString(), msg.Content)
.ConfigureAwait(false);
var success = await game.UserInput(msg.Author.Id, msg.Author.ToString(), msg.Content);
if (success)
await msg.DeleteAsync().ConfigureAwait(false);
await msg.DeleteAsync();
}
catch { }
});
@ -87,15 +86,14 @@ public partial class Games
{
if (submissions.Length == 0)
{
await SendErrorAsync(GetText(strs.acrophobia), GetText(strs.acro_ended_no_sub)).ConfigureAwait(false);
await SendErrorAsync(GetText(strs.acrophobia), GetText(strs.acro_ended_no_sub));
return;
}
if (submissions.Length == 1)
{
await ctx.Channel.EmbedAsync(_eb.Create().WithOkColor()
.WithDescription(GetText(strs.acro_winner_only(Format.Bold(submissions.First().Key.UserName))))
.WithFooter(submissions.First().Key.Input))
.ConfigureAwait(false);
.WithFooter(submissions.First().Key.Input));
return;
}
@ -110,14 +108,14 @@ public partial class Games
--")))
.WithFooter(GetText(strs.acro_vote));
await ctx.Channel.EmbedAsync(embed).ConfigureAwait(false);
await ctx.Channel.EmbedAsync(embed);
}
private async Task Game_OnEnded(AcrophobiaGame game, ImmutableArray<KeyValuePair<AcrophobiaUser, int>> votes)
{
if (!votes.Any() || votes.All(x => x.Value == 0))
{
await SendErrorAsync(GetText(strs.acrophobia), GetText(strs.acro_no_votes_cast)).ConfigureAwait(false);
await SendErrorAsync(GetText(strs.acrophobia), GetText(strs.acro_no_votes_cast));
return;
}
var table = votes.OrderByDescending(v => v.Value);
@ -128,7 +126,7 @@ public partial class Games
Format.Bold(winner.Value.ToString()))))
.WithFooter(winner.Key.Input);
await ctx.Channel.EmbedAsync(embed).ConfigureAwait(false);
await ctx.Channel.EmbedAsync(embed);
}
}
}

View file

@ -1,4 +1,4 @@
#nullable disable
#nullable disable
using NadekoBot.Db;
using NadekoBot.Modules.Games.Services;
@ -29,7 +29,7 @@ public partial class Games
uow.GuildConfigs.SetCleverbotEnabled(ctx.Guild.Id, false);
await uow.SaveChangesAsync();
}
await ReplyConfirmLocalizedAsync(strs.cleverbot_disabled).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.cleverbot_disabled);
return;
}
@ -41,7 +41,7 @@ public partial class Games
await uow.SaveChangesAsync();
}
await ReplyConfirmLocalizedAsync(strs.cleverbot_enabled).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.cleverbot_enabled);
}
}

View file

@ -1,4 +1,4 @@
#nullable disable
#nullable disable
using System.Collections.Immutable;
using CommandLine;
@ -63,36 +63,36 @@ public sealed class AcrophobiaGame : IDisposable
public async Task Run()
{
await OnStarted(this).ConfigureAwait(false);
await Task.Delay(Opts.SubmissionTime * 1000).ConfigureAwait(false);
await locker.WaitAsync().ConfigureAwait(false);
await OnStarted(this);
await Task.Delay(Opts.SubmissionTime * 1000);
await locker.WaitAsync();
try
{
if (submissions.Count == 0)
{
CurrentPhase = Phase.Ended;
await OnVotingStarted(this, ImmutableArray.Create<KeyValuePair<AcrophobiaUser, int>>()).ConfigureAwait(false);
await OnVotingStarted(this, ImmutableArray.Create<KeyValuePair<AcrophobiaUser, int>>());
return;
}
if (submissions.Count == 1)
{
CurrentPhase = Phase.Ended;
await OnVotingStarted(this, submissions.ToArray().ToImmutableArray()).ConfigureAwait(false);
await OnVotingStarted(this, submissions.ToArray().ToImmutableArray());
return;
}
CurrentPhase = Phase.Voting;
await OnVotingStarted(this, submissions.ToArray().ToImmutableArray()).ConfigureAwait(false);
await OnVotingStarted(this, submissions.ToArray().ToImmutableArray());
}
finally { locker.Release(); }
await Task.Delay(Opts.VoteTime * 1000).ConfigureAwait(false);
await locker.WaitAsync().ConfigureAwait(false);
await Task.Delay(Opts.VoteTime * 1000);
await locker.WaitAsync();
try
{
CurrentPhase = Phase.Ended;
await OnEnded(this, submissions.ToArray().ToImmutableArray()).ConfigureAwait(false);
await OnEnded(this, submissions.ToArray().ToImmutableArray());
}
finally { locker.Release(); }
}
@ -115,7 +115,7 @@ public sealed class AcrophobiaGame : IDisposable
{
var user = new AcrophobiaUser(userId, userName, input.ToLowerInvariant().ToTitleCase());
await locker.WaitAsync().ConfigureAwait(false);
await locker.WaitAsync();
try
{
switch (CurrentPhase)

View file

@ -1,4 +1,4 @@
#nullable disable
#nullable disable
using Newtonsoft.Json;
namespace NadekoBot.Modules.Games.Common.ChatterBot;
@ -26,7 +26,7 @@ public class ChatterBotSession : IChatterBotSession
public async Task<string> Think(string message)
{
using var http = _httpFactory.CreateClient();
var res = await http.GetStringAsync(string.Format(ApiEndpoint, message)).ConfigureAwait(false);
var res = await http.GetStringAsync(string.Format(ApiEndpoint, message));
var cbr = JsonConvert.DeserializeObject<ChatterBotResponse>(res);
return cbr.BotSay.Replace("<br/>", "\n", StringComparison.InvariantCulture);
}

View file

@ -1,4 +1,4 @@
#nullable disable
#nullable disable
using Newtonsoft.Json;
namespace NadekoBot.Modules.Games.Common.ChatterBot;
@ -23,7 +23,7 @@ public class OfficialCleverbotSession : IChatterBotSession
public async Task<string> Think(string input)
{
using var http = _httpFactory.CreateClient();
var dataString = await http.GetStringAsync(string.Format(QueryString, input, _cs ?? "")).ConfigureAwait(false);
var dataString = await http.GetStringAsync(string.Format(QueryString, input, _cs ?? ""));
try
{
var data = JsonConvert.DeserializeObject<CleverbotResponse>(dataString);
@ -67,8 +67,8 @@ public class CleverbotIOSession : IChatterBotSession
new KeyValuePair<string, string>("user", _user),
new KeyValuePair<string, string>("key", _key),
});
using var data = await _http.PostAsync(_createEndpoint, msg).ConfigureAwait(false);
var str = await data.Content.ReadAsStringAsync().ConfigureAwait(false);
using var data = await _http.PostAsync(_createEndpoint, msg);
var str = await data.Content.ReadAsStringAsync();
var obj = JsonConvert.DeserializeObject<CleverbotIOCreateResponse>(str);
if (obj.Status != "success")
throw new OperationCanceledException(obj.Status);
@ -86,8 +86,8 @@ public class CleverbotIOSession : IChatterBotSession
new KeyValuePair<string, string>("nick", await _nick),
new KeyValuePair<string, string>("text", input),
});
using var data = await _http.PostAsync(_askEndpoint, msg).ConfigureAwait(false);
var str = await data.Content.ReadAsStringAsync().ConfigureAwait(false);
using var data = await _http.PostAsync(_askEndpoint, msg);
var str = await data.Content.ReadAsStringAsync();
var obj = JsonConvert.DeserializeObject<CleverbotIOAskResponse>(str);
if (obj.Status != "success")
throw new OperationCanceledException(obj.Status);

View file

@ -1,4 +1,4 @@
#nullable disable
#nullable disable
using Image = SixLabors.ImageSharp.Image;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Processing;
@ -51,9 +51,9 @@ public class GirlRating
//{
// http.AddFakeHeaders();
// using (var reponse = await http.PutAsync("https://transfer.sh/img.png", byteContent).ConfigureAwait(false))
// using (var reponse = await http.PutAsync("https://transfer.sh/img.png", byteContent))
// {
// url = await reponse.Content.ReadAsStringAsync().ConfigureAwait(false);
// url = await reponse.Content.ReadAsStringAsync();
// }
//}
}

View file

@ -1,4 +1,4 @@
#nullable disable
#nullable disable
using System.Collections.Immutable;
namespace NadekoBot.Modules.Games.Common.Nunchi;
@ -39,7 +39,7 @@ public sealed class NunchiGame : IDisposable
public async Task<bool> Join(ulong userId, string userName)
{
await _locker.WaitAsync().ConfigureAwait(false);
await _locker.WaitAsync();
try
{
if (CurrentPhase != Phase.Joining)
@ -53,8 +53,8 @@ public sealed class NunchiGame : IDisposable
public async Task<bool> Initialize()
{
CurrentPhase = Phase.Joining;
await Task.Delay(30000).ConfigureAwait(false);
await _locker.WaitAsync().ConfigureAwait(false);
await Task.Delay(30000);
await _locker.WaitAsync();
try
{
if (_participants.Count < 3)
@ -65,7 +65,7 @@ public sealed class NunchiGame : IDisposable
_killTimer = new(async state =>
{
await _locker.WaitAsync().ConfigureAwait(false);
await _locker.WaitAsync();
try
{
if (CurrentPhase != Phase.Playing)
@ -88,7 +88,7 @@ public sealed class NunchiGame : IDisposable
public async Task Input(ulong userId, string userName, int input)
{
await _locker.WaitAsync().ConfigureAwait(false);
await _locker.WaitAsync();
try
{
if (CurrentPhase != Phase.Playing)
@ -159,7 +159,7 @@ public sealed class NunchiGame : IDisposable
CurrentPhase = Phase.WaitingForNextRound;
var throwawayDelay = Task.Run(async () =>
{
await Task.Delay(_nextRoundTimeout).ConfigureAwait(false);
await Task.Delay(_nextRoundTimeout);
CurrentPhase = Phase.Playing;
var ___ = OnRoundStarted?.Invoke(this, CurrentNumber);
});

View file

@ -1,4 +1,4 @@
#nullable disable
#nullable disable
using NadekoBot.Services.Database.Models;
namespace NadekoBot.Modules.Games.Common;
@ -21,7 +21,7 @@ public class PollRunner
public async Task<bool> TryVote(IUserMessage msg)
{
PollVote voteObj;
await _locker.WaitAsync().ConfigureAwait(false);
await _locker.WaitAsync();
try
{
// has to be a user message

View file

@ -1,4 +1,4 @@
#nullable disable
#nullable disable
using System.Text;
using CommandLine;
@ -130,12 +130,12 @@ public class TicTacToe
{
if (_phase is Phase.Started or Phase.Ended)
{
await _channel.SendErrorAsync(_eb, user.Mention + GetText(strs.ttt_already_running)).ConfigureAwait(false);
await _channel.SendErrorAsync(_eb, user.Mention + GetText(strs.ttt_already_running));
return;
}
else if (_users[0] == user)
{
await _channel.SendErrorAsync(_eb, user.Mention + GetText(strs.ttt_against_yourself)).ConfigureAwait(false);
await _channel.SendErrorAsync(_eb, user.Mention + GetText(strs.ttt_against_yourself));
return;
}
@ -145,7 +145,7 @@ public class TicTacToe
_timeoutTimer = new(async _ =>
{
await _moveLock.WaitAsync().ConfigureAwait(false);
await _moveLock.WaitAsync();
try
{
if (_phase == Phase.Ended)
@ -158,9 +158,9 @@ public class TicTacToe
var del = _previousMessage?.DeleteAsync();
try
{
await _channel.EmbedAsync(GetEmbed(GetText(strs.ttt_time_expired))).ConfigureAwait(false);
await _channel.EmbedAsync(GetEmbed(GetText(strs.ttt_time_expired)));
if (del != null)
await del.ConfigureAwait(false);
await del;
}
catch { }
}
@ -177,7 +177,7 @@ public class TicTacToe
_client.MessageReceived += Client_MessageReceived;
_previousMessage = await _channel.EmbedAsync(GetEmbed(GetText(strs.game_started))).ConfigureAwait(false);
_previousMessage = await _channel.EmbedAsync(GetEmbed(GetText(strs.game_started)));
}
private bool IsDraw()
@ -197,7 +197,7 @@ public class TicTacToe
{
var _ = Task.Run(async () =>
{
await _moveLock.WaitAsync().ConfigureAwait(false);
await _moveLock.WaitAsync();
try
{
var curUser = _users[_curUserIndex];
@ -265,9 +265,9 @@ public class TicTacToe
{
var del1 = msg.DeleteAsync();
var del2 = _previousMessage?.DeleteAsync();
try { _previousMessage = await _channel.EmbedAsync(GetEmbed(reason)).ConfigureAwait(false); } catch { }
try { await del1.ConfigureAwait(false); } catch { }
try { if (del2 != null) await del2.ConfigureAwait(false); } catch { }
try { _previousMessage = await _channel.EmbedAsync(GetEmbed(reason)); } catch { }
try { await del1; } catch { }
try { if (del2 != null) await del2; } catch { }
});
_curUserIndex ^= 1;

View file

@ -1,4 +1,4 @@
#nullable disable
#nullable disable
using System.Text;
namespace NadekoBot.Modules.Games.Common.Trivia;
@ -65,7 +65,7 @@ public class TriviaGame
CurrentQuestion = _questionPool.GetRandomQuestion(OldQuestions, _options.IsPokemon);
if (string.IsNullOrWhiteSpace(CurrentQuestion?.Answer) || string.IsNullOrWhiteSpace(CurrentQuestion.Question))
{
await Channel.SendErrorAsync(_eb, GetText(strs.trivia_game), GetText(strs.failed_loading_question)).ConfigureAwait(false);
await Channel.SendErrorAsync(_eb, GetText(strs.trivia_game), GetText(strs.failed_loading_question));
return;
}
OldQuestions.Add(CurrentQuestion); //add it to exclusion list so it doesn't show up again
@ -85,7 +85,7 @@ public class TriviaGame
if (Uri.IsWellFormedUriString(CurrentQuestion.ImageUrl, UriKind.Absolute))
questionEmbed.WithImageUrl(CurrentQuestion.ImageUrl);
questionMessage = await Channel.EmbedAsync(questionEmbed).ConfigureAwait(false);
questionMessage = await Channel.EmbedAsync(questionEmbed);
}
catch (HttpException ex) when (ex.HttpCode is System.Net.HttpStatusCode.NotFound or System.Net.HttpStatusCode.Forbidden or System.Net.HttpStatusCode.BadRequest)
{
@ -94,7 +94,7 @@ public class TriviaGame
catch (Exception ex)
{
Log.Warning(ex, "Error sending trivia embed");
await Task.Delay(2000).ConfigureAwait(false);
await Task.Delay(2000);
continue;
}
@ -108,12 +108,11 @@ public class TriviaGame
try
{
//hint
await Task.Delay(_options.QuestionTimer * 1000 / 2, _triviaCancelSource.Token).ConfigureAwait(false);
await Task.Delay(_options.QuestionTimer * 1000 / 2, _triviaCancelSource.Token);
if (!_options.NoHint)
try
{
await questionMessage.ModifyAsync(m => m.Embed = questionEmbed.WithFooter(CurrentQuestion.GetHint()).Build())
.ConfigureAwait(false);
await questionMessage.ModifyAsync(m => m.Embed = questionEmbed.WithFooter(CurrentQuestion.GetHint()).Build());
}
catch (HttpException ex) when (ex.HttpCode is System.Net.HttpStatusCode.NotFound or System.Net.HttpStatusCode.Forbidden)
{
@ -122,7 +121,7 @@ public class TriviaGame
catch (Exception ex) { Log.Warning(ex, "Error editing triva message"); }
//timeout
await Task.Delay(_options.QuestionTimer * 1000 / 2, _triviaCancelSource.Token).ConfigureAwait(false);
await Task.Delay(_options.QuestionTimer * 1000 / 2, _triviaCancelSource.Token);
}
catch (TaskCanceledException) { _timeoutCount = 0; } //means someone guessed the answer
@ -142,17 +141,17 @@ public class TriviaGame
if (Uri.IsWellFormedUriString(CurrentQuestion.AnswerImageUrl, UriKind.Absolute))
embed.WithImageUrl(CurrentQuestion.AnswerImageUrl);
await Channel.EmbedAsync(embed).ConfigureAwait(false);
await Channel.EmbedAsync(embed);
if (_options.Timeout != 0 && ++_timeoutCount >= _options.Timeout)
await StopGame().ConfigureAwait(false);
await StopGame();
}
catch (Exception ex)
{
Log.Warning(ex, "Error sending trivia time's up message");
}
}
await Task.Delay(5000).ConfigureAwait(false);
await Task.Delay(5000);
}
}
@ -163,7 +162,7 @@ public class TriviaGame
await Channel.EmbedAsync(_eb.Create().WithOkColor()
.WithAuthor("Trivia Game Ended")
.WithTitle("Final Results")
.WithDescription(GetLeaderboard())).ConfigureAwait(false);
.WithDescription(GetLeaderboard()));
}
public async Task StopGame()
@ -203,7 +202,7 @@ public class TriviaGame
var guildUser = (IGuildUser)umsg.Author;
var guess = false;
await _guessLock.WaitAsync().ConfigureAwait(false);
await _guessLock.WaitAsync();
try
{
if (GameActive && CurrentQuestion.IsAnswerCorrect(umsg.Content) && !_triviaCancelSource.IsCancellationRequested)
@ -229,7 +228,7 @@ public class TriviaGame
Format.Bold(CurrentQuestion.Answer))));
if (Uri.IsWellFormedUriString(CurrentQuestion.AnswerImageUrl, UriKind.Absolute))
embedS.WithImageUrl(CurrentQuestion.AnswerImageUrl);
await Channel.EmbedAsync(embedS).ConfigureAwait(false);
await Channel.EmbedAsync(embedS);
}
catch
{
@ -237,7 +236,7 @@ public class TriviaGame
}
var reward = _config.Trivia.CurrencyReward;
if (reward > 0)
await _cs.AddAsync(guildUser, "Won trivia", reward, true).ConfigureAwait(false);
await _cs.AddAsync(guildUser, "Won trivia", reward, true);
return;
}
var embed = _eb.Create().WithOkColor()
@ -245,7 +244,7 @@ public class TriviaGame
.WithDescription(GetText(strs.trivia_guess(guildUser.Mention, Format.Bold(CurrentQuestion.Answer))));
if (Uri.IsWellFormedUriString(CurrentQuestion.AnswerImageUrl, UriKind.Absolute))
embed.WithImageUrl(CurrentQuestion.AnswerImageUrl);
await Channel.EmbedAsync(embed).ConfigureAwait(false);
await Channel.EmbedAsync(embed);
}
catch (Exception ex) { Log.Warning(ex.ToString()); }
});

View file

@ -1,4 +1,4 @@
#nullable disable
#nullable disable
using System.Diagnostics;
using NadekoBot.Modules.Games.Services;
using CommandLine;
@ -83,24 +83,24 @@ public class TypingGame
var msg = await Channel.SendMessageAsync($"Starting new typing contest in **{time}**...", options: new()
{
RetryMode = RetryMode.AlwaysRetry
}).ConfigureAwait(false);
});
do
{
await Task.Delay(2000).ConfigureAwait(false);
await Task.Delay(2000);
time -= 2;
try { await msg.ModifyAsync(m => m.Content = $"Starting new typing contest in **{time}**..").ConfigureAwait(false); } catch { }
try { await msg.ModifyAsync(m => m.Content = $"Starting new typing contest in **{time}**.."); } catch { }
} while (time > 2);
await msg.ModifyAsync(m => {
m.Content = CurrentSentence.Replace(" ", " \x200B", StringComparison.InvariantCulture);
}).ConfigureAwait(false);
});
sw.Start();
HandleAnswers();
while (i > 0)
{
await Task.Delay(1000).ConfigureAwait(false);
await Task.Delay(1000);
i--;
if (!IsActive)
return;
@ -110,7 +110,7 @@ public class TypingGame
catch { }
finally
{
await Stop().ConfigureAwait(false);
await Stop();
}
}
@ -158,8 +158,7 @@ public class TypingGame
{
await this.Channel.SendConfirmAsync(_eb,
$":exclamation: A lot of people finished, here is the text for those still typing:" +
$"\n\n**{Format.Sanitize(CurrentSentence.Replace(" ", " \x200B", StringComparison.InvariantCulture)).SanitizeMentions(true)}**")
.ConfigureAwait(false);
$"\n\n**{Format.Sanitize(CurrentSentence.Replace(" ", " \x200B", StringComparison.InvariantCulture)).SanitizeMentions(true)}**");
}
}
}

View file

@ -1,4 +1,4 @@
#nullable disable
#nullable disable
using NadekoBot.Modules.Games.Common;
using NadekoBot.Modules.Games.Services;
@ -29,7 +29,7 @@ public partial class Games : NadekoModule<GamesService>
if (listArr.Length < 2)
return;
var rng = new NadekoRandom();
await SendConfirmAsync("🤔", listArr[rng.Next(0, listArr.Length)]).ConfigureAwait(false);
await SendConfirmAsync("🤔", listArr[rng.Next(0, listArr.Length)]);
}
[NadekoCommand, Aliases]
@ -54,7 +54,7 @@ public partial class Games : NadekoModule<GamesService>
if (originalStream is null)
{
await ReplyErrorLocalizedAsync(strs.something_went_wrong).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.something_went_wrong);
return;
}
@ -73,7 +73,7 @@ public partial class Games : NadekoModule<GamesService>
.AddField("Hot", gr.Hot.ToString("F2"), true)
.AddField("Crazy", gr.Crazy.ToString("F2"), true)
.AddField("Advice", gr.Advice, false)
.Build()).ConfigureAwait(false);
.Build());
}
private double NextDouble(double x, double y)
@ -144,5 +144,5 @@ public partial class Games : NadekoModule<GamesService>
Many computer users run a modified version of the {guhnoo} system every day, without realizing it. Through a peculiar turn of events, the version of {guhnoo} which is widely used today is often called {loonix}, and many of its users are not aware that it is basically the {guhnoo} system, developed by the {guhnoo} Project.
There really is a {loonix}, and these people are using it, but it is just a part of the system they use. {loonix} is the kernel: the program in the system that allocates the machine's resources to the other programs that you run. The kernel is an essential part of an operating system, but useless by itself; it can only function in the context of a complete operating system. {loonix} is normally used in combination with the {guhnoo} operating system: the whole system is basically {guhnoo} with {loonix} added, or {guhnoo}/{loonix}. All the so-called {loonix} distributions are really distributions of {guhnoo}/{loonix}."
).ConfigureAwait(false);
);
}

View file

@ -69,7 +69,7 @@ public partial class Games
{
if (await _service.StopHangman(ctx.Channel.Id))
{
await ReplyConfirmLocalizedAsync(strs.hangman_stopped).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.hangman_stopped);
}
}
}

View file

@ -1,4 +1,4 @@
#nullable disable
#nullable disable
using NadekoBot.Modules.Games.Common.Nunchi;
using NadekoBot.Modules.Games.Services;
@ -25,10 +25,10 @@ public partial class Games
if ((nunchi = _service.NunchiGames.GetOrAdd(ctx.Guild.Id, newNunchi)) != newNunchi)
{
// join it
if (!await nunchi.Join(ctx.User.Id, ctx.User.ToString()).ConfigureAwait(false))
if (!await nunchi.Join(ctx.User.Id, ctx.User.ToString()))
{
// if you failed joining, that means game is running or just ended
// await ReplyErrorLocalized("nunchi_already_started").ConfigureAwait(false);
// await ReplyErrorLocalized("nunchi_already_started");
return;
}
@ -46,12 +46,12 @@ public partial class Games
nunchi.OnRoundStarted += Nunchi_OnRoundStarted;
_client.MessageReceived += _client_MessageReceived;
var success = await nunchi.Initialize().ConfigureAwait(false);
var success = await nunchi.Initialize();
if (!success)
{
if (_service.NunchiGames.TryRemove(ctx.Guild.Id, out var game))
game.Dispose();
await ConfirmLocalizedAsync(strs.nunchi_failed_to_start).ConfigureAwait(false);
await ConfirmLocalizedAsync(strs.nunchi_failed_to_start);
}
Task _client_MessageReceived(SocketMessage arg)
@ -65,7 +65,7 @@ public partial class Games
return;
try
{
await nunchi.Input(arg.Author.Id, arg.Author.ToString(), number).ConfigureAwait(false);
await nunchi.Input(arg.Author.Id, arg.Author.ToString(), number);
}
catch
{

View file

@ -1,4 +1,4 @@
#nullable disable
#nullable disable
using NadekoBot.Modules.Games.Services;
using NadekoBot.Services.Database.Models;
using System.Text;
@ -27,7 +27,7 @@ public partial class Games
ctx.Channel.Id, arg);
if(poll is null)
{
await ReplyErrorLocalizedAsync(strs.poll_invalid_input).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.poll_invalid_input);
return;
}
if (_service.StartPoll(poll))
@ -39,12 +39,11 @@ public partial class Games
.WithDescription(
Format.Bold(poll.Question) + "\n\n" +
string.Join("\n", poll.Answers
.Select(x => $"`{x.Index + 1}.` {Format.Bold(x.Text)}"))))
.ConfigureAwait(false);
.Select(x => $"`{x.Index + 1}.` {Format.Bold(x.Text)}"))));
}
else
{
await ReplyErrorLocalizedAsync(strs.poll_already_running).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.poll_already_running);
}
}
@ -56,7 +55,7 @@ public partial class Games
if (!_service.ActivePolls.TryGetValue(ctx.Guild.Id, out var pr))
return;
await ctx.Channel.EmbedAsync(GetStats(pr.Poll, GetText(strs.current_poll_results))).ConfigureAwait(false);
await ctx.Channel.EmbedAsync(GetStats(pr.Poll, GetText(strs.current_poll_results)));
}
[NadekoCommand, Aliases]
@ -71,8 +70,7 @@ public partial class Games
return;
var embed = GetStats(p, GetText(strs.poll_closed));
await ctx.Channel.EmbedAsync(embed)
.ConfigureAwait(false);
await ctx.Channel.EmbedAsync(embed);
}
public IEmbedBuilder GetStats(Poll poll, string title)

View file

@ -1,4 +1,4 @@
#nullable disable
#nullable disable
using NadekoBot.Common.ModuleBehaviors;
using NadekoBot.Modules.Permissions.Common;
using NadekoBot.Modules.Permissions.Services;
@ -81,16 +81,16 @@ public class ChatterBotService : IEarlyBehavior
public async Task<bool> TryAsk(IChatterBotSession cleverbot, ITextChannel channel, string message)
{
await channel.TriggerTypingAsync().ConfigureAwait(false);
await channel.TriggerTypingAsync();
var response = await cleverbot.Think(message).ConfigureAwait(false);
var response = await cleverbot.Think(message);
try
{
await channel.SendConfirmAsync(_eb, response.SanitizeMentions(true)).ConfigureAwait(false);
await channel.SendConfirmAsync(_eb, response.SanitizeMentions(true));
}
catch
{
await channel.SendConfirmAsync(_eb, response.SanitizeMentions(true)).ConfigureAwait(false); // try twice :\
await channel.SendConfirmAsync(_eb, response.SanitizeMentions(true)); // try twice :\
}
return true;
}
@ -116,13 +116,13 @@ public class ChatterBotService : IEarlyBehavior
var returnMsg = _strings.GetText(strs.perm_prevent(index + 1,
Format.Bold(pc.Permissions[index].GetCommand(_cmd.GetPrefix(sg), sg))));
try { await usrMsg.Channel.SendErrorAsync(_eb, returnMsg).ConfigureAwait(false); } catch { }
try { await usrMsg.Channel.SendErrorAsync(_eb, returnMsg); } catch { }
Log.Information(returnMsg);
}
return true;
}
var cleverbotExecuted = await TryAsk(cbs, (ITextChannel)usrMsg.Channel, message).ConfigureAwait(false);
var cleverbotExecuted = await TryAsk(cbs, (ITextChannel)usrMsg.Channel, message);
if (cleverbotExecuted)
{
Log.Information($@"CleverBot Executed

View file

@ -1,4 +1,4 @@
#nullable disable
#nullable disable
using NadekoBot.Common.Configs;
using NadekoBot.Modules.Games.Common;
@ -25,7 +25,7 @@ public sealed class GamesConfigService : ConfigServiceBase<GamesConfig>
private void Migrate()
{
if (_data.Version < 1)
if (data.Version < 1)
{
ModifyConfig(c =>
{

View file

@ -1,4 +1,4 @@
#nullable disable
#nullable disable
using NadekoBot.Common.ModuleBehaviors;
using NadekoBot.Modules.Games.Common;
using NadekoBot.Common.Collections;
@ -90,10 +90,9 @@ public class PollService : IEarlyBehavior
private async Task Pr_OnVoted(IUserMessage msg, IGuildUser usr)
{
var toDelete = await msg.Channel.SendConfirmAsync(_eb,
_strs.GetText(strs.poll_voted(Format.Bold(usr.ToString())), usr.GuildId))
.ConfigureAwait(false);
_strs.GetText(strs.poll_voted(Format.Bold(usr.ToString())), usr.GuildId));
toDelete.DeleteAfter(5);
try { await msg.DeleteAsync().ConfigureAwait(false); } catch { }
try { await msg.DeleteAsync(); } catch { }
}
public async Task<bool> RunBehavior(IGuild guild, IUserMessage msg)
@ -106,7 +105,7 @@ public class PollService : IEarlyBehavior
try
{
var voted = await poll.TryVote(msg).ConfigureAwait(false);
var voted = await poll.TryVote(msg);
if (voted)
{

View file

@ -1,4 +1,4 @@
#nullable disable
#nullable disable
using NadekoBot.Modules.Games.Common;
using NadekoBot.Modules.Games.Services;
@ -34,7 +34,7 @@ public partial class Games
}
else
{
await game.Start().ConfigureAwait(false);
await game.Start();
}
}
@ -44,11 +44,11 @@ public partial class Games
{
if (_service.RunningContests.TryRemove(ctx.Guild.Id, out var game))
{
await game.Stop().ConfigureAwait(false);
await game.Stop();
return;
}
await SendErrorAsync("No contest to stop on this channel.").ConfigureAwait(false);
await SendErrorAsync("No contest to stop on this channel.");
}
@ -62,7 +62,7 @@ public partial class Games
_games.AddTypingArticle(ctx.User, text);
await SendConfirmAsync("Added new article for typing game.").ConfigureAwait(false);
await SendConfirmAsync("Added new article for typing game.");
}
[NadekoCommand, Aliases]
@ -76,12 +76,11 @@ public partial class Games
if (!articles.Any())
{
await SendErrorAsync($"{ctx.User.Mention} `No articles found on that page.`").ConfigureAwait(false);
await SendErrorAsync($"{ctx.User.Mention} `No articles found on that page.`");
return;
}
var i = (page - 1) * 15;
await SendConfirmAsync("List of articles for Type Race", string.Join("\n", articles.Select(a => $"`#{++i}` - {a.Text.TrimTo(50)}")))
.ConfigureAwait(false);
await SendConfirmAsync("List of articles for Type Race", string.Join("\n", articles.Select(a => $"`#{++i}` - {a.Text.TrimTo(50)}")));
}
[NadekoCommand, Aliases]

View file

@ -1,4 +1,4 @@
#nullable disable
#nullable disable
using NadekoBot.Modules.Games.Common;
using NadekoBot.Modules.Games.Services;
@ -23,20 +23,20 @@ public partial class Games
var (options, _) = OptionsParser.ParseFrom(new TicTacToe.Options(), args);
var channel = (ITextChannel)ctx.Channel;
await _sem.WaitAsync(1000).ConfigureAwait(false);
await _sem.WaitAsync(1000);
try
{
if (_service.TicTacToeGames.TryGetValue(channel.Id, out var game))
{
var _ = Task.Run(async () =>
{
await game.Start((IGuildUser)ctx.User).ConfigureAwait(false);
await game.Start((IGuildUser)ctx.User);
});
return;
}
game = new(base.Strings, this._client, channel, (IGuildUser)ctx.User, options, _eb);
_service.TicTacToeGames.Add(channel.Id, game);
await ReplyConfirmLocalizedAsync(strs.ttt_created).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.ttt_created);
game.OnEnded += g =>
{

View file

@ -1,4 +1,4 @@
#nullable disable
#nullable disable
using NadekoBot.Modules.Games.Common.Trivia;
using NadekoBot.Modules.Games.Services;
@ -48,18 +48,17 @@ public partial class Games
{
try
{
await trivia.StartGame().ConfigureAwait(false);
await trivia.StartGame();
}
finally
{
_service.RunningTrivias.TryRemove(channel.Guild.Id, out trivia);
await trivia.EnsureStopped().ConfigureAwait(false);
await trivia.EnsureStopped();
}
return;
}
await SendErrorAsync(GetText(strs.trivia_already_running) + "\n" + trivia.CurrentQuestion)
.ConfigureAwait(false);
await SendErrorAsync(GetText(strs.trivia_already_running) + "\n" + trivia.CurrentQuestion);
}
[NadekoCommand, Aliases]
@ -68,11 +67,11 @@ public partial class Games
{
if (_service.RunningTrivias.TryGetValue(ctx.Guild.Id, out var trivia))
{
await SendConfirmAsync(GetText(strs.leaderboard), trivia.GetLeaderboard()).ConfigureAwait(false);
await SendConfirmAsync(GetText(strs.leaderboard), trivia.GetLeaderboard());
return;
}
await ReplyErrorLocalizedAsync(strs.trivia_none).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.trivia_none);
}
[NadekoCommand, Aliases]
@ -83,11 +82,11 @@ public partial class Games
if (_service.RunningTrivias.TryGetValue(channel.Guild.Id, out var trivia))
{
await trivia.StopGame().ConfigureAwait(false);
await trivia.StopGame();
return;
}
await ReplyErrorLocalizedAsync(strs.trivia_none).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.trivia_none);
}
}
}

View file

@ -176,7 +176,8 @@ public class Help : NadekoModule<HelpService>
var cmds = _cmds.Commands.Where(c => c.Module.GetTopLevelModule().Name.ToUpperInvariant().StartsWith(module, StringComparison.InvariantCulture))
.Where(c => !_perms.BlockedCommands.Contains(c.Aliases[0].ToLowerInvariant()))
.OrderBy(c => c.Aliases[0])
.DistinctBy(x => x.Aliases[0]);
.DistinctBy(x => x.Aliases[0])
.ToList();
// check preconditions for all commands, but only if it's not 'all'
@ -184,18 +185,18 @@ public class Help : NadekoModule<HelpService>
var succ = new HashSet<CommandInfo>();
if (opts.View != CommandsOptions.ViewType.All)
{
succ = new((await Task.WhenAll(cmds.Select(async x =>
succ = new((await cmds.Select(async x =>
{
var pre = await x.CheckPreconditionsAsync(Context, _services).ConfigureAwait(false);
var pre = await x.CheckPreconditionsAsync(Context, _services);
return (Cmd: x, Succ: pre.IsSuccess);
})).ConfigureAwait(false))
}).WhenAll())
.Where(x => x.Succ)
.Select(x => x.Cmd));
if (opts.View == CommandsOptions.ViewType.Hide)
{
// if hidden is specified, completely remove these commands from the list
cmds = cmds.Where(x => succ.Contains(x));
cmds = cmds.Where(x => succ.Contains(x)).ToList();
}
}
var cmdsWithGroup = cmds.GroupBy(c => c.Module.Name.Replace("Commands", "", StringComparison.InvariantCulture))
@ -205,9 +206,9 @@ public class Help : NadekoModule<HelpService>
if (cmdsWithGroup.Count == 0)
{
if (opts.View != CommandsOptions.ViewType.Hide)
await ReplyErrorLocalizedAsync(strs.module_not_found).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.module_not_found);
else
await ReplyErrorLocalizedAsync(strs.module_not_found_or_cant_exec).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.module_not_found_or_cant_exec);
return;
}
@ -245,7 +246,7 @@ public class Help : NadekoModule<HelpService>
}
}
embed.WithFooter(GetText(strs.commands_instr(Prefix)));
await ctx.Channel.EmbedAsync(embed).ConfigureAwait(false);
await ctx.Channel.EmbedAsync(embed);
}
[NadekoCommand, Aliases]
@ -255,11 +256,11 @@ public class Help : NadekoModule<HelpService>
var prefixless = _cmds.Commands.FirstOrDefault(x => x.Aliases.Any(cmdName => cmdName.ToLowerInvariant() == fail));
if (prefixless != null)
{
await H(prefixless).ConfigureAwait(false);
await H(prefixless);
return;
}
await ReplyErrorLocalizedAsync(strs.command_not_found).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.command_not_found);
}
[NadekoCommand, Aliases]
@ -271,7 +272,7 @@ public class Help : NadekoModule<HelpService>
if (com is null)
{
var ch = channel is ITextChannel
? await ctx.User.CreateDMChannelAsync().ConfigureAwait(false)
? await ctx.User.CreateDMChannelAsync()
: channel;
try
{
@ -283,13 +284,13 @@ public class Help : NadekoModule<HelpService>
}
catch (Exception)
{
await ReplyErrorLocalizedAsync(strs.cant_dm).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.cant_dm);
}
return;
}
var embed = _service.GetCommandHelp(com, ctx.Guild);
await channel.EmbedAsync(embed).ConfigureAwait(false);
await channel.EmbedAsync(embed);
}
[NadekoCommand, Aliases]
@ -403,7 +404,7 @@ public class Help : NadekoModule<HelpService>
// also send the file, but indented one, to chat
await using var rDataStream = new MemoryStream(Encoding.ASCII.GetBytes(readableData));
await ctx.Channel.SendFileAsync(rDataStream, "cmds.json", GetText(strs.commandlist_regen)).ConfigureAwait(false);
await ctx.Channel.SendFileAsync(rDataStream, "cmds.json", GetText(strs.commandlist_regen));
}
[NadekoCommand, Aliases]

View file

@ -398,12 +398,12 @@ public sealed class MusicPlayer : IMusicPlayer
if (IsKilled)
break;
var queueTasks = chunk.Select(async data =>
await chunk.Select(async data =>
{
var (query, platform) = data;
try
{
await TryEnqueueTrackAsync(query, queuer, false, forcePlatform: platform).ConfigureAwait(false);
await TryEnqueueTrackAsync(query, queuer, false, forcePlatform: platform);
errorCount = 0;
}
catch (Exception ex)
@ -411,9 +411,8 @@ public sealed class MusicPlayer : IMusicPlayer
Log.Warning(ex, "Error resolving {MusicPlatform} Track {TrackQuery}", platform, query);
++errorCount;
}
});
}).WhenAll();
await Task.WhenAll(queueTasks);
await Task.Delay(1000);
// > 10 errors in a row = kill

View file

@ -60,8 +60,9 @@ public sealed class LocalTrackResolver : ILocalTrackResolver
var fileChunks = files.Skip(1).Chunk(10);
foreach (var chunk in fileChunks)
{
var part = await Task.WhenAll(chunk.Select(x => ResolveByQueryAsync(x.FullName)));
{
var part = await chunk.Select(x => ResolveByQueryAsync(x.FullName))
.WhenAll();
// nullable reference types being annoying
foreach (var p in part)

View file

@ -1,4 +1,4 @@
#nullable disable
#nullable disable
using System.Text.RegularExpressions;
namespace NadekoBot.Modules.Music.Resolvers;
@ -17,7 +17,7 @@ public class RadioResolver : IRadioResolver
public async Task<ITrackInfo> ResolveByQueryAsync(string query)
{
if (IsRadioLink(query))
query = await HandleStreamContainers(query).ConfigureAwait(false);
query = await HandleStreamContainers(query);
return new SimpleTrackInfo(
query.TrimTo(50),
@ -44,7 +44,7 @@ public class RadioResolver : IRadioResolver
try
{
using var http = new HttpClient();
file = await http.GetStringAsync(query).ConfigureAwait(false);
file = await http.GetStringAsync(query);
}
catch
{

View file

@ -37,7 +37,7 @@ public sealed class SoundcloudResolver : ISoundcloudResolver
.Select(VideoModelToCachedData)
.ToList();
await Task.WhenAll(cachableTracks.Select(_trackCacher.CacheTrackDataAsync));
await cachableTracks.Select(_trackCacher.CacheTrackDataAsync).WhenAll();
foreach(var info in cachableTracks.Select(CachableDataToTrackInfo))
{
yield return info;
@ -77,8 +77,8 @@ public sealed class SoundcloudResolver : ISoundcloudResolver
return CachableDataToTrackInfo(cached);
var svideo = !IsSoundCloudLink(query)
? await _sc.GetVideoByQueryAsync(query).ConfigureAwait(false)
: await _sc.ResolveVideoAsync(query).ConfigureAwait(false);
? await _sc.GetVideoByQueryAsync(query)
: await _sc.ResolveVideoAsync(query);
if (svideo is null)
return null;

View file

@ -110,7 +110,7 @@ public sealed partial class Music : NadekoModule<IMusicService>
if (!string.IsNullOrWhiteSpace(trackInfo.Thumbnail))
embed.WithThumbnailUrl(trackInfo.Thumbnail);
var queuedMessage = await _service.SendToOutputAsync(ctx.Guild.Id, embed).ConfigureAwait(false);
var queuedMessage = await _service.SendToOutputAsync(ctx.Guild.Id, embed);
queuedMessage?.DeleteAfter(10, _logService);
if (mp.IsStopped)
{
@ -346,7 +346,7 @@ public sealed partial class Music : NadekoModule<IMusicService>
if (videos is null || videos.Count == 0)
{
await ReplyErrorLocalizedAsync(strs.song_not_found).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.song_not_found);
return;
}
@ -358,7 +358,7 @@ public sealed partial class Music : NadekoModule<IMusicService>
try
{
var input = await GetUserInputAsync(ctx.User.Id, ctx.Channel.Id).ConfigureAwait(false);
var input = await GetUserInputAsync(ctx.User.Id, ctx.Channel.Id);
if (input is null
|| !int.TryParse(input, out var index)
|| (index -= 1) < 0
@ -367,7 +367,7 @@ public sealed partial class Music : NadekoModule<IMusicService>
_logService.AddDeleteIgnore(msg.Id);
try
{
await msg.DeleteAsync().ConfigureAwait(false);
await msg.DeleteAsync();
}
catch
{
@ -384,7 +384,7 @@ public sealed partial class Music : NadekoModule<IMusicService>
_logService.AddDeleteIgnore(msg.Id);
try
{
await msg.DeleteAsync().ConfigureAwait(false);
await msg.DeleteAsync();
}
catch
{
@ -399,7 +399,7 @@ public sealed partial class Music : NadekoModule<IMusicService>
{
if (index < 1)
{
await ReplyErrorLocalizedAsync(strs.removed_song_error).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.removed_song_error);
return;
}
@ -415,7 +415,7 @@ public sealed partial class Music : NadekoModule<IMusicService>
if (!mp.TryRemoveTrackAt(index - 1, out var song))
{
await ReplyErrorLocalizedAsync(strs.removed_song_error).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.removed_song_error);
return;
}
@ -445,7 +445,7 @@ public sealed partial class Music : NadekoModule<IMusicService>
}
mp.Clear();
await ReplyConfirmLocalizedAsync(strs.queue_cleared).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.queue_cleared);
}
[NadekoCommand, Aliases]
@ -563,7 +563,7 @@ public sealed partial class Music : NadekoModule<IMusicService>
await _service.EnqueueDirectoryAsync(mp, dirPath, ctx.User.ToString());
await ReplyConfirmLocalizedAsync(strs.dir_queue_complete).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.dir_queue_complete);
}
[NadekoCommand, Aliases]
@ -572,7 +572,7 @@ public sealed partial class Music : NadekoModule<IMusicService>
{
if (--from < 0 || --to < 0 || from == to)
{
await ReplyErrorLocalizedAsync(strs.invalid_input).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.invalid_input);
return;
}
@ -590,7 +590,7 @@ public sealed partial class Music : NadekoModule<IMusicService>
var track = mp.MoveTrack(from, to);
if (track is null)
{
await ReplyErrorLocalizedAsync(strs.invalid_input).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.invalid_input);
return;
}
@ -604,7 +604,7 @@ public sealed partial class Music : NadekoModule<IMusicService>
if (Uri.IsWellFormedUriString(track.Url, UriKind.Absolute))
embed.WithUrl(track.Url);
await ctx.Channel.EmbedAsync(embed).ConfigureAwait(false);
await ctx.Channel.EmbedAsync(embed);
}
[NadekoCommand, Aliases]
@ -661,7 +661,7 @@ public sealed partial class Music : NadekoModule<IMusicService>
var queuedCount = await _service.EnqueueYoutubePlaylistAsync(mp, playlistQuery, ctx.User.ToString());
if (queuedCount == 0)
{
await ReplyErrorLocalizedAsync(strs.no_search_results).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.no_search_results);
return;
}
await ctx.OkAsync();
@ -688,7 +688,7 @@ public sealed partial class Music : NadekoModule<IMusicService>
.WithThumbnailUrl(currentTrack.Thumbnail)
.WithFooter($"{mp.PrettyVolume()} | {mp.PrettyTotalTime()} | {currentTrack.Platform} | {currentTrack.Queuer}");
await ctx.Channel.EmbedAsync(embed).ConfigureAwait(false);
await ctx.Channel.EmbedAsync(embed);
}
[NadekoCommand, Aliases]

View file

@ -1,4 +1,4 @@
#nullable disable
#nullable disable
using NadekoBot.Services.Database.Models;
using NadekoBot.Db;
using NadekoBot.Modules.Music.Services;
@ -55,7 +55,7 @@ public sealed partial class Music
GetText(strs.playlists(r.Id, r.Name, r.Author, r.Songs.Count)))))
.WithOkColor();
await ctx.Channel.EmbedAsync(embed).ConfigureAwait(false);
await ctx.Channel.EmbedAsync(embed);
}
[NadekoCommand, Aliases]
@ -84,9 +84,9 @@ public sealed partial class Music
}
if (!success)
await ReplyErrorLocalizedAsync(strs.playlist_delete_fail).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.playlist_delete_fail);
else
await ReplyConfirmLocalizedAsync(strs.playlist_deleted).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.playlist_deleted);
}
[NadekoCommand, Aliases]
@ -113,7 +113,7 @@ public sealed partial class Music
.WithTitle($"\"{mpl.Name}\" by {mpl.Author}")
.WithOkColor()
.WithDescription(str);
}, mpl.Songs.Count, 20).ConfigureAwait(false);
}, mpl.Songs.Count, 20);
}
[NadekoCommand, Aliases]
@ -202,7 +202,7 @@ public sealed partial class Music
if (mpl is null)
{
await ReplyErrorLocalizedAsync(strs.playlist_id_not_found).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.playlist_id_not_found);
return;
}
@ -210,8 +210,7 @@ public sealed partial class Music
try
{
msg = await ctx.Channel
.SendMessageAsync(GetText(strs.attempting_to_queue(Format.Bold(mpl.Songs.Count.ToString()))))
.ConfigureAwait(false);
.SendMessageAsync(GetText(strs.attempting_to_queue(Format.Bold(mpl.Songs.Count.ToString()))));
}
catch (Exception)
{

View file

@ -1,4 +1,4 @@
#nullable disable
#nullable disable
using System.Reflection;
using Ayu.Discord.Voice;
@ -92,7 +92,7 @@ public sealed class AyuVoiceStateService : INService
public async Task LeaveVoiceChannel(ulong guildId)
{
var gwLock = GetVoiceGatewayLock(guildId);
await gwLock.WaitAsync().ConfigureAwait(false);
await gwLock.WaitAsync();
try
{
await LeaveVoiceChannelInternalAsync(guildId);
@ -198,7 +198,7 @@ public sealed class AyuVoiceStateService : INService
public async Task<IVoiceProxy> JoinVoiceChannel(ulong guildId, ulong channelId, bool forceReconnect = true)
{
var gwLock = GetVoiceGatewayLock(guildId);
await gwLock.WaitAsync().ConfigureAwait(false);
await gwLock.WaitAsync();
try
{
await LeaveVoiceChannelInternalAsync(guildId);

View file

@ -1,4 +1,4 @@
#nullable disable
#nullable disable
using System.Net.Http.Json;
namespace NadekoBot.Modules.Nsfw.Common;
@ -13,7 +13,7 @@ public abstract class DapiImageDownloader : ImageDownloader<DapiImageObject>
public abstract Task<bool> IsTagValid(string tag, CancellationToken cancel = default);
protected async Task<bool> AllTagsValid(string[] tags, CancellationToken cancel = default)
{
var results = await Task.WhenAll(tags.Select(tag => IsTagValid(tag, cancel)));
var results = await tags.Select(tag => IsTagValid(tag, cancel)).WhenAll();
// if any of the tags is not valid, the query is not valid
foreach (var result in results)
@ -32,14 +32,13 @@ public abstract class DapiImageDownloader : ImageDownloader<DapiImageObject>
if (tags.Length > 2)
return new();
if (!await AllTagsValid(tags, cancel).ConfigureAwait(false))
if (!await AllTagsValid(tags, cancel))
return new();
var tagString = ImageDownloaderHelper.GetTagString(tags, isExplicit);
var uri = $"{_baseUrl}/posts.json?limit=200&tags={tagString}&page={page}";
var imageObjects = await _http.GetFromJsonAsync<DapiImageObject[]>(uri, _serializerOptions, cancel)
.ConfigureAwait(false);
var imageObjects = await _http.GetFromJsonAsync<DapiImageObject[]>(uri, _serializerOptions, cancel);
if (imageObjects is null)
return new();
return imageObjects

View file

@ -1,4 +1,4 @@
#nullable disable
#nullable disable
using System.Net.Http.Json;
namespace NadekoBot.Modules.Nsfw.Common;
@ -15,10 +15,10 @@ public class DerpibooruImageDownloader : ImageDownloader<DerpiImageObject>
var uri = $"https://www.derpibooru.org/api/v1/json/search/images?q={tagString.Replace('+', ',')}&per_page=49&page={page}";
using var req = new HttpRequestMessage(HttpMethod.Get, uri);
req.Headers.AddFakeHeaders();
using var res = await _http.SendAsync(req, cancel).ConfigureAwait(false);
using var res = await _http.SendAsync(req, cancel);
res.EnsureSuccessStatusCode();
var container = await res.Content.ReadFromJsonAsync<DerpiContainer>(_serializerOptions, cancel).ConfigureAwait(false);
var container = await res.Content.ReadFromJsonAsync<DerpiContainer>(_serializerOptions, cancel);
if (container?.Images is null)
return new();

View file

@ -1,4 +1,4 @@
#nullable disable
#nullable disable
using System.Net.Http.Json;
namespace NadekoBot.Modules.Nsfw.Common;
@ -15,10 +15,10 @@ public class E621ImageDownloader : ImageDownloader<E621Object>
var uri = $"https://e621.net/posts.json?limit=32&tags={tagString}&page={page}";
using var req = new HttpRequestMessage(HttpMethod.Get, uri);
req.Headers.AddFakeHeaders();
using var res = await _http.SendAsync(req, cancel).ConfigureAwait(false);
using var res = await _http.SendAsync(req, cancel);
res.EnsureSuccessStatusCode();
var data = await res.Content.ReadFromJsonAsync<E621Response>(_serializerOptions, cancel).ConfigureAwait(false);
var data = await res.Content.ReadFromJsonAsync<E621Response>(_serializerOptions, cancel);
if (data?.Posts is null)
return new();

View file

@ -1,4 +1,4 @@
#nullable disable
#nullable disable
using System.Text.Json;
namespace NadekoBot.Modules.Nsfw.Common;
@ -15,7 +15,7 @@ public class GelbooruImageDownloader : ImageDownloader<DapiImageObject>
var uri = $"http://gelbooru.com/index.php?page=dapi&s=post&json=1&q=index&limit=100" +
$"&tags={tagString}&pid={page}";
using var req = new HttpRequestMessage(HttpMethod.Get, uri);
using var res = await _http.SendAsync(req, cancel).ConfigureAwait(false);
using var res = await _http.SendAsync(req, cancel);
res.EnsureSuccessStatusCode();
var resString = await res.Content.ReadAsStringAsync(cancel);
if (string.IsNullOrWhiteSpace(resString))

View file

@ -29,7 +29,7 @@ public abstract class ImageDownloader<T> : IImageDownloader
public async Task<List<ImageData>> DownloadImageDataAsync(string[] tags, int page, bool isExplicit = false,
CancellationToken cancel = default)
{
var images = await DownloadImagesAsync(tags, page, isExplicit, cancel).ConfigureAwait(false);
var images = await DownloadImagesAsync(tags, page, isExplicit, cancel);
return images.Select(x => x.ToCachedImageData(Booru)).ToList();
}
}

View file

@ -1,4 +1,4 @@
#nullable disable
#nullable disable
using System.Net.Http.Json;
namespace NadekoBot.Modules.Nsfw.Common;
@ -15,8 +15,7 @@ public sealed class KonachanImageDownloader : ImageDownloader<DapiImageObject>
{
var tagString = ImageDownloaderHelper.GetTagString(tags, isExplicit);
var uri = $"{_baseUrl}/post.json?s=post&q=index&limit=200&tags={tagString}&page={page}";
var imageObjects = await _http.GetFromJsonAsync<DapiImageObject[]>(uri, _serializerOptions, cancel)
.ConfigureAwait(false);
var imageObjects = await _http.GetFromJsonAsync<DapiImageObject[]>(uri, _serializerOptions, cancel);
if (imageObjects is null)
return new();
return imageObjects

View file

@ -1,4 +1,4 @@
#nullable disable
#nullable disable
using System.Net.Http.Json;
namespace NadekoBot.Modules.Nsfw.Common;
@ -14,7 +14,7 @@ public class Rule34ImageDownloader : ImageDownloader<Rule34Object>
var tagString = ImageDownloaderHelper.GetTagString(tags);
var uri = $"https://rule34.xxx/index.php?page=dapi&s=post&q=index&json=1&limit=100" +
$"&tags={tagString}&pid={page}";
var images = await _http.GetFromJsonAsync<List<Rule34Object>>(uri, _serializerOptions, cancel).ConfigureAwait(false);
var images = await _http.GetFromJsonAsync<List<Rule34Object>>(uri, _serializerOptions, cancel);
if (images is null)
return new();

View file

@ -20,7 +20,7 @@ public sealed class SankakuImageDownloader : ImageDownloader<SankakuImageObject>
var tagString = ImageDownloaderHelper.GetTagString(tags, false);
var uri = $"{_baseUrl}/posts?tags={tagString}&limit=50";
var data = await _http.GetStringAsync(uri).ConfigureAwait(false);
var data = await _http.GetStringAsync(uri);
return JsonSerializer.Deserialize<SankakuImageObject[]>(data, _serializerOptions)
.Where(x => !string.IsNullOrWhiteSpace(x.FileUrl) && x.FileType.StartsWith("image"))
.ToList();

View file

@ -1,4 +1,4 @@
#nullable disable
#nullable disable
using System.Net.Http.Json;
namespace NadekoBot.Modules.Nsfw.Common;
@ -16,8 +16,7 @@ public sealed class YandereImageDownloader : ImageDownloader<DapiImageObject>
var tagString = ImageDownloaderHelper.GetTagString(tags, isExplicit);
var uri = $"{_baseUrl}/post.json?limit=200&tags={tagString}&page={page}";
var imageObjects = await _http.GetFromJsonAsync<DapiImageObject[]>(uri, _serializerOptions, cancel)
.ConfigureAwait(false);
var imageObjects = await _http.GetFromJsonAsync<DapiImageObject[]>(uri, _serializerOptions, cancel);
if (imageObjects is null)
return new();
return imageObjects

View file

@ -1,4 +1,4 @@
#nullable disable
#nullable disable
using NadekoBot.Modules.Searches.Common;
using Newtonsoft.Json.Linq;
@ -25,15 +25,14 @@ public class NSFW : NadekoModule<ISearchImagesService>
using (var http = _httpFactory.CreateClient())
{
obj = JArray.Parse(await http
.GetStringAsync($"http://api.oboobs.ru/boobs/{new NadekoRandom().Next(0, 10330)}")
.ConfigureAwait(false))[0];
.GetStringAsync($"http://api.oboobs.ru/boobs/{new NadekoRandom().Next(0, 10330)}"))[0];
}
await ctx.Channel.SendMessageAsync($"http://media.oboobs.ru/{obj["preview"]}").ConfigureAwait(false);
await ctx.Channel.SendMessageAsync($"http://media.oboobs.ru/{obj["preview"]}");
}
catch (Exception ex)
{
await SendErrorAsync(ex.Message).ConfigureAwait(false);
await SendErrorAsync(ex.Message);
}
}
@ -45,15 +44,14 @@ public class NSFW : NadekoModule<ISearchImagesService>
using (var http = _httpFactory.CreateClient())
{
obj = JArray.Parse(await http
.GetStringAsync($"http://api.obutts.ru/butts/{new NadekoRandom().Next(0, 4335)}")
.ConfigureAwait(false))[0];
.GetStringAsync($"http://api.obutts.ru/butts/{new NadekoRandom().Next(0, 4335)}"))[0];
}
await Channel.SendMessageAsync($"http://media.obutts.ru/{obj["preview"]}").ConfigureAwait(false);
await Channel.SendMessageAsync($"http://media.obutts.ru/{obj["preview"]}");
}
catch (Exception ex)
{
await SendErrorAsync(ex.Message).ConfigureAwait(false);
await SendErrorAsync(ex.Message);
}
}
@ -70,7 +68,7 @@ public class NSFW : NadekoModule<ISearchImagesService>
if (!_service.AutoHentaiTimers.TryRemove(ctx.Channel.Id, out t)) return;
t.Change(Timeout.Infinite, Timeout.Infinite); //proper way to disable the timer
await ReplyConfirmLocalizedAsync(strs.stopped).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.stopped);
return;
}
@ -82,12 +80,12 @@ public class NSFW : NadekoModule<ISearchImagesService>
try
{
if (tags is null || tags.Length == 0)
await InternalDapiCommand(null, true, _service.Hentai).ConfigureAwait(false);
await InternalDapiCommand(null, true, _service.Hentai);
else
{
var groups = tags.Split('|');
var group = groups[_rng.Next(0, groups.Length)];
await InternalDapiCommand(group.Split(' '), true, _service.Hentai).ConfigureAwait(false);
await InternalDapiCommand(group.Split(' '), true, _service.Hentai);
}
}
catch
@ -120,7 +118,7 @@ public class NSFW : NadekoModule<ISearchImagesService>
if (!_service.AutoBoobTimers.TryRemove(ctx.Channel.Id, out t)) return;
t.Change(Timeout.Infinite, Timeout.Infinite);
await ReplyConfirmLocalizedAsync(strs.stopped).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.stopped);
return;
}
@ -131,7 +129,7 @@ public class NSFW : NadekoModule<ISearchImagesService>
{
try
{
await InternalBoobs().ConfigureAwait(false);
await InternalBoobs();
}
catch
{
@ -160,7 +158,7 @@ public class NSFW : NadekoModule<ISearchImagesService>
if (!_service.AutoButtTimers.TryRemove(ctx.Channel.Id, out t)) return;
t.Change(Timeout.Infinite, Timeout.Infinite); //proper way to disable the timer
await ReplyConfirmLocalizedAsync(strs.stopped).ConfigureAwait(false);
await ReplyConfirmLocalizedAsync(strs.stopped);
return;
}
@ -171,7 +169,7 @@ public class NSFW : NadekoModule<ISearchImagesService>
{
try
{
await InternalButts(ctx.Channel).ConfigureAwait(false);
await InternalButts(ctx.Channel);
}
catch
{
@ -206,15 +204,14 @@ public class NSFW : NadekoModule<ISearchImagesService>
_service.Konachan(ctx.Guild?.Id, true, tags),
_service.Gelbooru(ctx.Guild?.Id, true, tags));
var linksEnum = images?.Where(l => l != null).ToArray();
if (images is null || !linksEnum.Any())
var linksEnum = images.Where(l => l != null).ToArray();
if (!linksEnum.Any())
{
await ReplyErrorLocalizedAsync(strs.no_results).ConfigureAwait(false);
await ReplyErrorLocalizedAsync(strs.no_results);
return;
}
await ctx.Channel.SendMessageAsync(string.Join("\n\n", linksEnum.Select(x => x.Url)))
.ConfigureAwait(false);
await ctx.Channel.SendMessageAsync(string.Join("\n\n", linksEnum.Select(x => x.Url)));
}
finally
{
@ -277,15 +274,14 @@ public class NSFW : NadekoModule<ISearchImagesService>
using (var http = _httpFactory.CreateClient())
{
obj = JArray.Parse(await http
.GetStringAsync($"http://api.oboobs.ru/boobs/{new NadekoRandom().Next(0, 12000)}")
.ConfigureAwait(false))[0];
.GetStringAsync($"http://api.oboobs.ru/boobs/{new NadekoRandom().Next(0, 12000)}"))[0];
}
await ctx.Channel.SendMessageAsync($"http://media.oboobs.ru/{obj["preview"]}").ConfigureAwait(false);
await ctx.Channel.SendMessageAsync($"http://media.oboobs.ru/{obj["preview"]}");
}
catch (Exception ex)
{
await SendErrorAsync(ex.Message).ConfigureAwait(false);
await SendErrorAsync(ex.Message);
}
}
@ -299,15 +295,14 @@ public class NSFW : NadekoModule<ISearchImagesService>
using (var http = _httpFactory.CreateClient())
{
obj = JArray.Parse(await http
.GetStringAsync($"http://api.obutts.ru/butts/{new NadekoRandom().Next(0, 6100)}")
.ConfigureAwait(false))[0];
.GetStringAsync($"http://api.obutts.ru/butts/{new NadekoRandom().Next(0, 6100)}"))[0];
}
await ctx.Channel.SendMessageAsync($"http://media.obutts.ru/{obj["preview"]}").ConfigureAwait(false);
await ctx.Channel.SendMessageAsync($"http://media.obutts.ru/{obj["preview"]}");
}
catch (Exception ex)
{
await SendErrorAsync(ex.Message).ConfigureAwait(false);
await SendErrorAsync(ex.Message);
}
}
@ -322,7 +317,7 @@ public class NSFW : NadekoModule<ISearchImagesService>
await SendConfirmAsync(GetText(strs.blacklisted_tag_list),
blTags.Any()
? string.Join(", ", blTags)
: "-").ConfigureAwait(false);
: "-");
}
else
{

Some files were not shown because too many files have changed in this diff Show more