- More code cleanup and codestyle updates

- Fixed some possible nullref exceptions
- Methods signatures now have up to 3 parameters before breakaing down each parameter in a separate line
- Method invocations have the same rule, except the first parameter will be in the same line as the invocation to prevent some ugliness when passing lambas as arguments
- Applied many more codestyles
- Extensions folder fully reformatted
This commit is contained in:
Kwoth
2021-12-26 17:28:39 +01:00
parent b85ba177cd
commit d5fd6aae8e
217 changed files with 1017 additions and 1494 deletions

View File

@@ -8,10 +8,8 @@ public partial class Administration : NadekoModule<AdministrationService>
private readonly ImageOnlyChannelService _imageOnly;
public Administration(ImageOnlyChannelService imageOnly)
{
_imageOnly = imageOnly;
}
=> _imageOnly = imageOnly;
public enum List
{
List = 0,
@@ -292,9 +290,7 @@ public partial class Administration : NadekoModule<AdministrationService>
[NadekoCommand, Aliases]
[RequireContext(ContextType.Guild)]
public async Task Delete(ITextChannel channel, ulong messageId, StoopidTime time = null)
{
await InternalMessageAction(channel, messageId, time, msg => msg.DeleteAsync());
}
=> await InternalMessageAction(channel, messageId, time, msg => msg.DeleteAsync());
private async Task InternalMessageAction(ITextChannel channel, ulong messageId, StoopidTime time,
Func<IMessage, Task> func)

View File

@@ -61,7 +61,7 @@ public partial class Administration
await ReplyConfirmLocalizedAsync(strs.aar_roles(
'\n' + existing.Select(x => Format.Bold(x.ToString()))
.JoinWith(",\n")));
.Join(",\n")));
}
}
}

View File

@@ -1,5 +1,4 @@
using NadekoBot.Common.Collections;
using NadekoBot.Services.Database.Models;
using NadekoBot.Services.Database.Models;
namespace NadekoBot.Modules.Administration.Common;
@@ -35,10 +34,8 @@ public class AntiAltStats
public int Counter => _counter;
public AntiAltStats(AntiAltSetting setting)
{
_setting = setting;
}
=> _setting = setting;
public void Increment() => Interlocked.Increment(ref _counter);
}

View File

@@ -42,11 +42,9 @@ public partial class Administration
[RequireContext(ContextType.Guild)]
[Priority(0)]
public async Task LanguageSet()
{
await ReplyConfirmLocalizedAsync(strs.lang_set_show(
=> await ReplyConfirmLocalizedAsync(strs.lang_set_show(
Format.Bold(_cultureInfo.ToString()),
Format.Bold(_cultureInfo.NativeName)));
}
[NadekoCommand, Aliases]
[RequireContext(ContextType.Guild)]
@@ -113,12 +111,10 @@ public partial class Administration
[NadekoCommand, Aliases]
public async Task LanguagesList()
{
await ctx.Channel.EmbedAsync(_eb.Create().WithOkColor()
=> 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);
}
}
}
/* list of language codes for reference.

View File

@@ -8,9 +8,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)))).ConfigureAwait(false);
public enum Set
{

View File

@@ -94,13 +94,13 @@ public partial class Administration
return;
}
if (userThreshold < 2 || userThreshold > 30)
if (userThreshold is < 2 or > 30)
{
await ReplyErrorLocalizedAsync(strs.raid_cnt(2, 30));
return;
}
if (seconds < 2 || seconds > 300)
if (seconds is < 2 or > 300)
{
await ReplyErrorLocalizedAsync(strs.raid_time(2, 300));
return;
@@ -115,7 +115,7 @@ public partial class Administration
}
var time = (int?) punishTime?.Time.TotalMinutes ?? 0;
if (time < 0 || time > 60 * 24)
if (time is < 0 or > 60 * 24)
return;
var stats = await _service.StartAntiRaidAsync(ctx.Guild.Id, userThreshold, seconds,
@@ -175,7 +175,7 @@ public partial class Administration
public async Task InternalAntiSpam(int messageCount, PunishmentAction action,
StoopidTime timeData = null, IRole role = null)
{
if (messageCount < 2 || messageCount > 10)
if (messageCount is < 2 or > 10)
return;
if (timeData is not null)
@@ -187,7 +187,7 @@ public partial class Administration
}
var time = (int?) timeData?.Time.TotalMinutes ?? 0;
if (time < 0 || time > 60 * 24)
if (time is < 0 or > 60 * 24)
return;
var stats = await _service.StartAntiSpamAsync(ctx.Guild.Id, messageCount, action, time, role?.Id).ConfigureAwait(false);

View File

@@ -17,7 +17,7 @@ public partial class Administration
{
var user = await ctx.Guild.GetCurrentUserAsync().ConfigureAwait(false);
if (parameter == "-s" || parameter == "--safe")
if (parameter is "-s" or "--safe")
await _service.PruneWhere((ITextChannel)ctx.Channel, 100, x => x.Author.Id == user.Id && !x.IsPinned).ConfigureAwait(false);
else
await _service.PruneWhere((ITextChannel)ctx.Channel, 100, x => x.Author.Id == user.Id).ConfigureAwait(false);
@@ -37,7 +37,7 @@ public partial class Administration
if (count > 1000)
count = 1000;
if (parameter == "-s" || parameter == "--safe")
if (parameter is "-s" or "--safe")
await _service.PruneWhere((ITextChannel)ctx.Channel, count, x => !x.IsPinned).ConfigureAwait(false);
else
await _service.PruneWhere((ITextChannel)ctx.Channel, count, x => true).ConfigureAwait(false);
@@ -69,7 +69,7 @@ public partial class Administration
if (count > 1000)
count = 1000;
if (parameter == "-s" || parameter == "--safe")
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);
else
await _service.PruneWhere((ITextChannel)ctx.Channel, count, m => m.Author.Id == userId && DateTime.UtcNow - m.CreatedAt < twoWeeks).ConfigureAwait(false);

View File

@@ -13,9 +13,7 @@ public partial class Administration
public enum Exclude { Excl }
public RoleCommands(IServiceProvider services)
{
_services = services;
}
=> _services = services;
public async Task InternalReactionRoles(bool exclusive, ulong? messageId, params string[] input)
{
@@ -326,9 +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")).ConfigureAwait(false);
[NadekoCommand, Aliases]
[RequireContext(ContextType.Guild)]

View File

@@ -145,9 +145,7 @@ public partial class Administration
}
private string GetIntervalText(int interval)
{
return $"[{GetText(strs.interval)}]: {interval}";
}
=> $"[{GetText(strs.interval)}]: {interval}";
[NadekoCommand, Aliases]
[OwnerOnly]
@@ -298,9 +296,7 @@ public partial class Administration
[NadekoCommand, Aliases]
[OwnerOnly]
public Task Leave([Leftover] string guildStr)
{
return _service.LeaveGuild(guildStr);
}
=> _service.LeaveGuild(guildStr);
[NadekoCommand, Aliases]
@@ -450,7 +446,7 @@ public partial class Administration
if (ids[1].ToUpperInvariant().StartsWith("C:", StringComparison.InvariantCulture))
{
var cid = ulong.Parse(ids[1].Substring(2));
var cid = ulong.Parse(ids[1][2..]);
var ch = server.TextChannels.FirstOrDefault(c => c.Id == cid);
if (ch is null)
return;
@@ -460,7 +456,7 @@ public partial class Administration
}
else if (ids[1].ToUpperInvariant().StartsWith("U:", StringComparison.InvariantCulture))
{
var uid = ulong.Parse(ids[1].Substring(2));
var uid = ulong.Parse(ids[1][2..]);
var user = server.Users.FirstOrDefault(u => u.Id == uid);
if (user is null)
return;

View File

@@ -23,7 +23,7 @@ public partial class Administration
[UserPerm(GuildPerm.ManageGuild)]
public async Task BoostDel(int timer = 30)
{
if (timer < 0 || timer > 600)
if (timer is < 0 or > 600)
return;
await _service.SetBoostDel(ctx.Guild.Id, timer);
@@ -66,7 +66,7 @@ public partial class Administration
[UserPerm(GuildPerm.ManageGuild)]
public async Task GreetDel(int timer = 30)
{
if (timer < 0 || timer > 600)
if (timer is < 0 or > 600)
return;
await _service.SetGreetDel(ctx.Guild.Id, timer).ConfigureAwait(false);

View File

@@ -1,5 +1,4 @@
using Microsoft.EntityFrameworkCore;
using NadekoBot.Common.Collections;
using NadekoBot.Services.Database.Models;
using NadekoBot.Db;

View File

@@ -155,7 +155,5 @@ public static class GuildConfigExtensions
}
public static void SetAutoAssignableRoles(this GuildConfig gc, IEnumerable<ulong> roles)
{
gc.AutoAssignRoleIds = roles.JoinWith(',');
}
=> gc.AutoAssignRoleIds = roles.Join(',');
}

View File

@@ -33,9 +33,7 @@ DELETE FROM Clubs;";
private readonly DbService _db;
public DangerousCommandsService(DbService db)
{
_db = db;
}
=> _db = db;
public async Task<int> ExecuteSql(string sql)
{

View File

@@ -1,5 +1,4 @@
using NadekoBot.Common.Collections;
using NadekoBot.Db;
using NadekoBot.Db;
namespace NadekoBot.Modules.Administration.Services;

View File

@@ -2,7 +2,6 @@
using System.Threading.Channels;
using LinqToDB;
using Microsoft.Extensions.Caching.Memory;
using NadekoBot.Common.Collections;
using NadekoBot.Common.ModuleBehaviors;
namespace NadekoBot.Modules.Administration.Services;

View File

@@ -1,6 +1,5 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Memory;
using NadekoBot.Common.Collections;
using NadekoBot.Services.Database.Models;
using NadekoBot.Db;
using NadekoBot.Modules.Administration.Common;
@@ -23,24 +22,16 @@ public sealed class DummyLogCommandService : ILogCommandService
}
public Task LogServer(ulong guildId, ulong channelId, bool actionValue)
{
return Task.CompletedTask;
}
=> Task.CompletedTask;
public bool LogIgnore(ulong guildId, ulong itemId, IgnoredItemType itemType)
{
return false;
}
=> false;
public LogSetting GetGuildLogSettings(ulong guildId)
{
return default;
}
=> default;
public bool Log(ulong guildId, ulong? channelId, LogType type)
{
return false;
}
=> false;
}
public sealed class LogCommandService : ILogCommandService
@@ -150,9 +141,7 @@ public sealed class LogCommandService : ILogCommandService
}
public void AddDeleteIgnore(ulong messageId)
{
_ignoreMessageIds.Add(messageId);
}
=> _ignoreMessageIds.Add(messageId);
public bool LogIgnore(ulong gid, ulong itemId, IgnoredItemType itemType)
{
@@ -1172,7 +1161,7 @@ public sealed class LogCommandService : ILogCommandService
break;
}
if (!id.HasValue || id == 0)
if (id is null or 0)
{
UnsetLogSetting(guild.Id, logChannelType);
return null;

View File

@@ -1,5 +1,4 @@
using Microsoft.EntityFrameworkCore;
using NadekoBot.Common.Collections;
using NadekoBot.Services.Database.Models;
using NadekoBot.Db;

View File

@@ -317,7 +317,11 @@ public class ProtectionService : INService
{
if (_antiSpamGuilds.TryRemove(guildId, out var removed))
{
removed.UserStats.ForEach(x => x.Value.Dispose());
foreach (var (_, val) in removed.UserStats)
{
val.Dispose();
}
using var uow = _db.GetDbContext();
var gc = uow.GuildConfigsForId(guildId, set => set.Include(x => x.AntiSpamSetting)
.ThenInclude(x => x.IgnoredChannels));

View File

@@ -1,22 +1,19 @@
using NadekoBot.Common.Collections;
namespace NadekoBot.Modules.Administration.Services;
namespace NadekoBot.Modules.Administration.Services;
public class PruneService : INService
{
//channelids where prunes are currently occuring
private readonly ConcurrentHashSet<ulong> _pruningGuilds = new();
private readonly TimeSpan twoWeeks = TimeSpan.FromDays(14);
private readonly TimeSpan _twoWeeks = TimeSpan.FromDays(14);
private readonly ILogCommandService _logService;
public PruneService(ILogCommandService logService)
{
this._logService = logService;
}
=> this._logService = logService;
public async Task PruneWhere(ITextChannel channel, int amount, Func<IMessage, bool> predicate)
{
channel.ThrowIfNull(nameof(channel));
ArgumentNullException.ThrowIfNull(channel, nameof(channel));
if (amount <= 0)
throw new ArgumentOutOfRangeException(nameof(amount));
@@ -38,7 +35,7 @@ public class PruneService : INService
{
_logService.AddDeleteIgnore(x.Id);
if (DateTime.UtcNow - x.CreatedAt < twoWeeks)
if (DateTime.UtcNow - x.CreatedAt < _twoWeeks)
bulkDeletable.Add(x);
else
singleDeletable.Add(x);

View File

@@ -135,9 +135,7 @@ public class RoleCommandsService : INService
}
public bool Get(ulong id, out IndexedCollection<ReactionRoleMessage> rrs)
{
return _models.TryGetValue(id, out rrs);
}
=> _models.TryGetValue(id, out rrs);
public bool Add(ulong id, ReactionRoleMessage rrm)
{

View File

@@ -27,9 +27,7 @@ public class SelfAssignedRolesService : INService
}
public SelfAssignedRolesService(DbService db)
{
_db = db;
}
=> _db = db;
public bool AddNew(ulong guildId, IRole role, int group)
{

View File

@@ -123,12 +123,10 @@ public sealed class SelfService : ILateExecutor, IReadyExecutor, INService
}
private Timer TimerFromAutoCommand(AutoCommand x)
{
return new(async obj => await ExecuteCommand((AutoCommand) obj).ConfigureAwait(false),
=> new(async obj => await ExecuteCommand((AutoCommand) obj).ConfigureAwait(false),
x,
x.Interval * 1000,
x.Interval * 1000);
}
private async Task ExecuteCommand(AutoCommand cmd)
{
@@ -366,8 +364,7 @@ public sealed class SelfService : ILateExecutor, IReadyExecutor, INService
}
private void HandleStatusChanges()
{
_pubSub.Sub(_activitySetKey, async data =>
=> _pubSub.Sub(_activitySetKey, async data =>
{
try
{
@@ -378,7 +375,6 @@ public sealed class SelfService : ILateExecutor, IReadyExecutor, INService
Log.Warning(ex, "Error setting activity");
}
});
}
public Task SetGameAsync(string game, ActivityType type)
=> _pubSub.Pub(_activitySetKey, new() {Name = game, Link = null, Type = type});

View File

@@ -300,7 +300,7 @@ WHERE GuildId={guildId}
public bool WarnPunish(ulong guildId, int number, PunishmentAction punish, StoopidTime time, IRole role = null)
{
// these 3 don't make sense with time
if ((punish == PunishmentAction.Softban || punish == PunishmentAction.Kick || punish == PunishmentAction.RemoveRoles) && time != null)
if (punish is PunishmentAction.Softban or PunishmentAction.Kick or PunishmentAction.RemoveRoles && time != null)
return false;
if (number <= 0 || (time != null && time.Time > TimeSpan.FromDays(49)))
return false;
@@ -427,8 +427,7 @@ WHERE GuildId={guildId}
public SmartText GetBanUserDmEmbed(ICommandContext context, IGuildUser target, string defaultMessage,
string banReason, TimeSpan? duration)
{
return GetBanUserDmEmbed(
=> GetBanUserDmEmbed(
(DiscordSocketClient) context.Client,
(SocketGuild) context.Guild,
(IGuildUser) context.User,
@@ -436,7 +435,6 @@ WHERE GuildId={guildId}
defaultMessage,
banReason,
duration);
}
public SmartText GetBanUserDmEmbed(DiscordSocketClient client, SocketGuild guild,
IGuildUser moderator, IGuildUser target, string defaultMessage, string banReason, TimeSpan? duration)

View File

@@ -13,7 +13,7 @@ public partial class Administration
{
page--;
if (page < 0 || page > 20)
if (page is < 0 or > 20)
return;
var timezones = TimeZoneInfo.GetSystemTimeZones()
@@ -56,9 +56,7 @@ public partial class Administration
[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))).ConfigureAwait(false);
[NadekoCommand, Aliases]
[RequireContext(ContextType.Guild)]

View File

@@ -144,7 +144,7 @@ public partial class Administration
[Priority(2)]
public async Task WarnExpire(int days, params string[] args)
{
if (days < 0 || days > 366)
if (days is < 0 or > 366)
return;
var opts = OptionsParser.ParseFrom<WarnExpireOptions>(args);