Using pattern matching for nulls where applicable, discarded unused lambda parameters, cleaned up some classes. Unignored ServerLog commands which was mistakenly ignored due to a .gitignore rule

This commit is contained in:
Kwoth
2022-01-01 08:44:51 +01:00
parent f81f9fadd3
commit 9b4eb21321
91 changed files with 1591 additions and 224 deletions

View File

@@ -16,7 +16,7 @@ public class GameVoiceChannelService : INService
_db = db;
_client = client;
GameVoiceChannels = new(bot.AllGuildConfigs.Where(gc => gc.GameVoiceChannel != null)
GameVoiceChannels = new(bot.AllGuildConfigs.Where(gc => gc.GameVoiceChannel is not null)
.Select(gc => gc.GameVoiceChannel.Value));
_client.UserVoiceStateUpdated += Client_UserVoiceStateUpdated;
@@ -62,7 +62,7 @@ public class GameVoiceChannelService : INService
}
else
{
if (gc.GameVoiceChannel != null)
if (gc.GameVoiceChannel is not null)
GameVoiceChannels.TryRemove(gc.GameVoiceChannel.Value);
GameVoiceChannels.Add(vchId);
id = gc.GameVoiceChannel = vchId;

View File

@@ -240,7 +240,7 @@ public class GreetService : INService
if (conf.SendChannelGreetMessage)
{
var channel = await user.Guild.GetTextChannelAsync(conf.GreetMessageChannelId);
if (channel != null)
if (channel is not null)
{
if (GroupGreets)
{

View File

@@ -176,7 +176,7 @@ public class MuteService : INService
await using var uow = _db.GetDbContext();
var config = uow.GuildConfigsForId(guildId, set => set);
config.MuteRoleName = name;
GuildMuteRoles.AddOrUpdate(guildId, name, (id, old) => name);
GuildMuteRoles.AddOrUpdate(guildId, name, (_, _) => name);
await uow.SaveChangesAsync();
}
@@ -243,7 +243,7 @@ public class MuteService : INService
set => set.Include(gc => gc.MutedUsers).Include(gc => gc.UnmuteTimers));
var match = new MutedUserId { UserId = usrId };
var toRemove = config.MutedUsers.FirstOrDefault(x => x.Equals(match));
if (toRemove != null) uow.Remove(toRemove);
if (toRemove is not null) uow.Remove(toRemove);
if (MutedUsers.TryGetValue(guildId, out var muted))
muted.TryRemove(usrId);
@@ -252,7 +252,7 @@ public class MuteService : INService
await uow.SaveChangesAsync();
}
if (usr != null)
if (usr is not null)
{
try { await usr.ModifyAsync(x => x.Mute = false); }
catch { }
@@ -405,7 +405,7 @@ public class MuteService : INService
RemoveTimerFromDb(guildId, userId, type);
StopTimer(guildId, userId, type);
var guild = _client.GetGuild(guildId); // load the guild
if (guild != null) await guild.RemoveBanAsync(userId);
if (guild is not null) await guild.RemoveBanAsync(userId);
}
catch (Exception ex)
{
@@ -419,7 +419,7 @@ public class MuteService : INService
var guild = _client.GetGuild(guildId);
var user = guild?.GetUser(userId);
var role = guild.GetRole(roleId.Value);
if (guild != null && user != null && user.Roles.Contains(role))
if (guild is not null && user is not null && user.Roles.Contains(role))
await user.RemoveRoleAsync(role);
}
catch (Exception ex)
@@ -444,8 +444,8 @@ public class MuteService : INService
//add it, or stop the old one and add this one
userUnTimers.AddOrUpdate((userId, type),
key => toAdd,
(key, old) =>
_ => toAdd,
(_, old) =>
{
old.Change(Timeout.Infinite, Timeout.Infinite);
return toAdd;
@@ -475,7 +475,7 @@ public class MuteService : INService
toDelete = config.UnbanTimer.FirstOrDefault(x => x.UserId == userId);
}
if (toDelete != null) uow.Remove(toDelete);
if (toDelete is not null) uow.Remove(toDelete);
uow.SaveChanges();
}
}

View File

@@ -219,10 +219,10 @@ public partial class Administration
var embed = _eb.Create().WithOkColor().WithTitle(GetText(strs.prot_active));
if (spam != null)
if (spam is not null)
embed.AddField("Anti-Spam", GetAntiSpamString(spam).TrimTo(1024), true);
if (raid != null)
if (raid is not null)
embed.AddField("Anti-Raid", GetAntiRaidString(raid).TrimTo(1024), true);
if (alt is not null)

View File

@@ -122,13 +122,13 @@ public class ProtectionService : INService
var raid = gc.AntiRaidSetting;
var spam = gc.AntiSpamSetting;
if (raid != null)
if (raid is not null)
{
var raidStats = new AntiRaidStats { AntiRaidSettings = raid };
_antiRaidGuilds[gc.GuildId] = raidStats;
}
if (spam != null)
if (spam is not null)
_antiSpamGuilds[gc.GuildId] = new() { AntiSpamSettings = spam };
var alt = gc.AntiAltSetting;
@@ -212,8 +212,8 @@ public class ProtectionService : INService
return;
var stats = spamSettings.UserStats.AddOrUpdate(msg.Author.Id,
id => new(msg),
(id, old) =>
_ => new(msg),
(_, old) =>
{
old.ApplyNextMessage(msg);
return old;
@@ -292,7 +292,7 @@ public class ProtectionService : INService
}
};
_antiRaidGuilds.AddOrUpdate(guildId, stats, (key, old) => stats);
_antiRaidGuilds.AddOrUpdate(guildId, stats, (_, _) => stats);
await using var uow = _db.GetDbContext();
var gc = uow.GuildConfigsForId(guildId, set => set.Include(x => x.AntiRaidSetting));
@@ -362,7 +362,7 @@ public class ProtectionService : INService
stats = _antiSpamGuilds.AddOrUpdate(guildId,
stats,
(key, old) =>
(_, old) =>
{
stats.AntiSpamSettings.IgnoredChannels = old.AntiSpamSettings.IgnoredChannels;
return stats;
@@ -371,7 +371,7 @@ public class ProtectionService : INService
await using var uow = _db.GetDbContext();
var gc = uow.GuildConfigsForId(guildId, set => set.Include(x => x.AntiSpamSetting));
if (gc.AntiSpamSetting != null)
if (gc.AntiSpamSetting is not null)
{
gc.AntiSpamSetting.Action = stats.AntiSpamSettings.Action;
gc.AntiSpamSetting.MessageThreshold = stats.AntiSpamSettings.MessageThreshold;

View File

@@ -41,7 +41,7 @@ public partial class Administration
if (parameter is "-s" or "--safe")
await _service.PruneWhere((ITextChannel)ctx.Channel, count, x => !x.IsPinned);
else
await _service.PruneWhere((ITextChannel)ctx.Channel, count, x => true);
await _service.PruneWhere((ITextChannel)ctx.Channel, count, _ => true);
}
//prune @user [x]

View File

@@ -46,7 +46,7 @@ public partial class Administration
var emote = x.Last().ToIEmote();
return new { role, emote };
})
.Where(x => x != null)
.Where(x => x is not null)
.WhenAll();
if (!all.Any())

View File

@@ -54,7 +54,7 @@ public class RoleCommandsService : INService
var reactionRole = conf.ReactionRoles.FirstOrDefault(x
=> x.EmoteName == reaction.Emote.Name || x.EmoteName == reaction.Emote.ToString());
if (reactionRole != null)
if (reactionRole is not null)
{
if (!conf.Exclusive)
{
@@ -125,7 +125,7 @@ public class RoleCommandsService : INService
var reactionRole = conf.ReactionRoles.FirstOrDefault(x
=> x.EmoteName == reaction.Emote.Name || x.EmoteName == reaction.Emote.ToString());
if (reactionRole != null)
if (reactionRole is not null)
{
var role = gusr.Guild.GetRole(reactionRole.RoleId);
if (role is null)
@@ -181,7 +181,7 @@ public class RoleCommandsService : INService
{
var toAdd = user.Guild.GetRole(dbRero.RoleId);
return toAdd != null && !user.Roles.Contains(toAdd) ? user.AddRoleAsync(toAdd) : Task.CompletedTask;
return toAdd is not null && !user.Roles.Contains(toAdd) ? user.AddRoleAsync(toAdd) : Task.CompletedTask;
}
/// <summary>
@@ -208,7 +208,7 @@ public class RoleCommandsService : INService
var roleIds = dbReroMsg.ReactionRoles.Select(x => x.RoleId)
.Where(x => x != dbRero.RoleId)
.Select(x => user.Guild.GetRole(x))
.Where(x => x != null);
.Where(x => x is not null);
var removeReactionsTask = RemoveOldReactionsAsync(reactionMessage, user, reaction, cToken);

View File

@@ -147,8 +147,8 @@ public sealed class SelfService : ILateExecutor, IReadyExecutor, INService
{
var autos = _autoCommands.GetOrAdd(cmd.GuildId, new ConcurrentDictionary<int, Timer>());
autos.AddOrUpdate(cmd.Id,
key => TimerFromAutoCommand(cmd),
(key, old) =>
_ => TimerFromAutoCommand(cmd),
(_, old) =>
{
old.Change(Timeout.Infinite, Timeout.Infinite);
return TimerFromAutoCommand(cmd);
@@ -179,7 +179,7 @@ public sealed class SelfService : ILateExecutor, IReadyExecutor, INService
return user.CreateDMChannelAsync();
}));
ownerChannels = channels.Where(x => x != null)
ownerChannels = channels.Where(x => x is not null)
.ToDictionary(x => x.Recipient.Id, x => x)
.ToImmutableDictionary();
@@ -244,7 +244,7 @@ public sealed class SelfService : ILateExecutor, IReadyExecutor, INService
using var uow = _db.GetDbContext();
cmd = uow.AutoCommands.AsNoTracking().Where(x => x.Interval == 0).Skip(index).FirstOrDefault();
if (cmd != null)
if (cmd is not null)
{
uow.Remove(cmd);
uow.SaveChanges();
@@ -259,7 +259,7 @@ public sealed class SelfService : ILateExecutor, IReadyExecutor, INService
using var uow = _db.GetDbContext();
cmd = uow.AutoCommands.AsNoTracking().Where(x => x.Interval >= 5).Skip(index).FirstOrDefault();
if (cmd != null)
if (cmd is not null)
{
uow.Remove(cmd);
if (_autoCommands.TryGetValue(cmd.GuildId, out var autos))

View File

@@ -77,7 +77,7 @@ public class SelfAssignedRolesService : INService
foreach (var roleId in sameRoles)
{
var sameRole = guildUser.Guild.GetRole(roleId);
if (sameRole != null)
if (sameRole is not null)
try
{
await guildUser.RemoveRoleAsync(sameRole);
@@ -111,7 +111,7 @@ public class SelfAssignedRolesService : INService
if (string.IsNullOrWhiteSpace(name))
{
if (toUpdate != null)
if (toUpdate is not null)
gc.SelfAssignableRoleGroupNames.Remove(toUpdate);
}
else if (toUpdate is null)
@@ -174,7 +174,7 @@ public class SelfAssignedRolesService : INService
using var uow = _db.GetDbContext();
var roles = uow.SelfAssignableRoles.GetFromGuild(guildId);
var sar = roles.FirstOrDefault(x => x.RoleId == role.Id);
if (sar != null)
if (sar is not null)
{
sar.LevelRequirement = level;
uow.SaveChanges();
@@ -216,6 +216,6 @@ public class SelfAssignedRolesService : INService
uow.SaveChanges();
}
return (exclusive, roles.Where(x => x.Role != null), groupNames);
return (exclusive, roles.Where(x => x.Role is not null), groupNames);
}
}

View File

@@ -0,0 +1,22 @@
using NadekoBot.Services.Database.Models;
namespace NadekoBot.Modules.Administration;
public sealed class DummyLogCommandService : ILogCommandService
{
public void AddDeleteIgnore(ulong xId)
{
}
public Task LogServer(ulong guildId, ulong channelId, bool actionValue)
=> Task.CompletedTask;
public bool LogIgnore(ulong guildId, ulong itemId, IgnoredItemType itemType)
=> false;
public LogSetting? GetGuildLogSettings(ulong guildId)
=> default;
public bool Log(ulong guildId, ulong? channelId, LogType type)
=> false;
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,157 @@
using NadekoBot.Common.TypeReaders.Models;
using NadekoBot.Services.Database.Models;
namespace NadekoBot.Modules.Administration;
public partial class Administration
{
[Group]
[NoPublicBot]
public partial class LogCommands : NadekoSubmodule<ILogCommandService>
{
[Cmd]
[RequireContext(ContextType.Guild)]
[UserPerm(GuildPerm.Administrator)]
[OwnerOnly]
public async partial Task LogServer(PermissionAction action)
{
await _service.LogServer(ctx.Guild.Id, ctx.Channel.Id, action.Value);
if (action.Value)
await ReplyConfirmLocalizedAsync(strs.log_all);
else
await ReplyConfirmLocalizedAsync(strs.log_disabled);
}
[Cmd]
[RequireContext(ContextType.Guild)]
[UserPerm(GuildPerm.Administrator)]
[OwnerOnly]
public async partial Task LogIgnore()
{
var settings = _service.GetGuildLogSettings(ctx.Guild.Id);
var chs = settings?.LogIgnores.Where(x => x.ItemType == IgnoredItemType.Channel).ToList()
?? new List<IgnoredLogItem>();
var usrs = settings?.LogIgnores.Where(x => x.ItemType == IgnoredItemType.User).ToList()
?? new List<IgnoredLogItem>();
var eb = _eb.Create(ctx)
.WithOkColor()
.AddField(GetText(strs.log_ignored_channels),
chs.Count == 0
? "-"
: string.Join('\n', chs.Select(x => $"{x.LogItemId} | <#{x.LogItemId}>")))
.AddField(GetText(strs.log_ignored_users),
usrs.Count == 0
? "-"
: string.Join('\n', usrs.Select(x => $"{x.LogItemId} | <@{x.LogItemId}>")));
await ctx.Channel.EmbedAsync(eb);
}
[Cmd]
[RequireContext(ContextType.Guild)]
[UserPerm(GuildPerm.Administrator)]
[OwnerOnly]
public async partial Task LogIgnore([Leftover] ITextChannel target)
{
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 + ")")));
else
await ReplyConfirmLocalizedAsync(
strs.log_not_ignore_chan(Format.Bold(target.Mention + "(" + target.Id + ")")));
}
[Cmd]
[RequireContext(ContextType.Guild)]
[UserPerm(GuildPerm.Administrator)]
[OwnerOnly]
public async partial Task LogIgnore([Leftover] IUser target)
{
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 + ")")));
else
await ReplyConfirmLocalizedAsync(
strs.log_not_ignore_user(Format.Bold(target.Mention + "(" + target.Id + ")")));
}
[Cmd]
[RequireContext(ContextType.Guild)]
[UserPerm(GuildPerm.Administrator)]
[OwnerOnly]
public async partial Task LogEvents()
{
var logSetting = _service.GetGuildLogSettings(ctx.Guild.Id);
var str = string.Join("\n",
Enum.GetNames(typeof(LogType))
.Select(x =>
{
var val = logSetting is null ? null : GetLogProperty(logSetting, Enum.Parse<LogType>(x));
if (val is not null)
return $"{Format.Bold(x)} <#{val}>";
return Format.Bold(x);
}));
await SendConfirmAsync(Format.Bold(GetText(strs.log_events)) + "\n" + str);
}
private static ulong? GetLogProperty(LogSetting l, LogType type)
{
switch (type)
{
case LogType.Other:
return l.LogOtherId;
case LogType.MessageUpdated:
return l.MessageUpdatedId;
case LogType.MessageDeleted:
return l.MessageDeletedId;
case LogType.UserJoined:
return l.UserJoinedId;
case LogType.UserLeft:
return l.UserLeftId;
case LogType.UserBanned:
return l.UserBannedId;
case LogType.UserUnbanned:
return l.UserUnbannedId;
case LogType.UserUpdated:
return l.UserUpdatedId;
case LogType.ChannelCreated:
return l.ChannelCreatedId;
case LogType.ChannelDestroyed:
return l.ChannelDestroyedId;
case LogType.ChannelUpdated:
return l.ChannelUpdatedId;
case LogType.UserPresence:
return l.LogUserPresenceId;
case LogType.VoicePresence:
return l.LogVoicePresenceId;
case LogType.VoicePresenceTTS:
return l.LogVoicePresenceTTSId;
case LogType.UserMuted:
return l.UserMutedId;
default:
return null;
}
}
[Cmd]
[RequireContext(ContextType.Guild)]
[UserPerm(GuildPerm.Administrator)]
[OwnerOnly]
public async partial Task Log(LogType type)
{
var val = _service.Log(ctx.Guild.Id, ctx.Channel.Id, type);
if (val)
await ReplyConfirmLocalizedAsync(strs.log(Format.Bold(type.ToString())));
else
await ReplyConfirmLocalizedAsync(strs.log_stop(Format.Bold(type.ToString())));
}
}
}

View File

@@ -13,12 +13,12 @@ public class GuildTimezoneService : INService
public GuildTimezoneService(DiscordSocketClient client, Bot bot, DbService db)
{
_timezones = bot.AllGuildConfigs.Select(GetTimzezoneTuple)
.Where(x => x.Timezone != null)
.Where(x => x.Timezone is not null)
.ToDictionary(x => x.GuildId, x => x.Timezone)
.ToConcurrent();
var curUser = client.CurrentUser;
if (curUser != null)
if (curUser is not null)
AllServices.TryAdd(curUser.Id, this);
_db = db;
@@ -28,7 +28,7 @@ public class GuildTimezoneService : INService
private Task Bot_JoinedGuild(GuildConfig arg)
{
var (guildId, tz) = GetTimzezoneTuple(arg);
if (tz != null)
if (tz is not null)
_timezones.TryAdd(guildId, tz);
return Task.CompletedTask;
}
@@ -69,7 +69,7 @@ public class GuildTimezoneService : INService
if (tz is null)
_timezones.TryRemove(guildId, out tz);
else
_timezones.AddOrUpdate(guildId, tz, (key, old) => tz);
_timezones.AddOrUpdate(guildId, tz, (_, _) => tz);
}
public TimeZoneInfo GetTimeZoneOrUtc(ulong guildId)

View File

@@ -392,12 +392,12 @@ public partial class Administration
var guildUser = await ((DiscordSocketClient)Context.Client).Rest.GetGuildUserAsync(ctx.Guild.Id, user.Id);
if (guildUser != null && !await CheckRoleHierarchy(guildUser))
if (guildUser is not null && !await CheckRoleHierarchy(guildUser))
return;
var dmFailed = false;
if (guildUser != null)
if (guildUser is not null)
try
{
var defaultMessage = GetText(strs.bandm(Format.Bold(ctx.Guild.Name), msg));

View File

@@ -80,7 +80,7 @@ public class UserPunishService : INService
var p = ps.FirstOrDefault(x => x.Count == warnings);
if (p != null)
if (p is not null)
{
var user = await guild.GetUserAsync(userId);
if (user is null)
@@ -305,9 +305,9 @@ WHERE GuildId={guildId}
IRole role = null)
{
// these 3 don't make sense with time
if (punish is PunishmentAction.Softban or PunishmentAction.Kick or PunishmentAction.RemoveRoles && time != null)
if (punish is PunishmentAction.Softban or PunishmentAction.Kick or PunishmentAction.RemoveRoles && time is not null)
return false;
if (number <= 0 || (time != null && time.Time > TimeSpan.FromDays(49)))
if (number <= 0 || (time is not null && time.Time > TimeSpan.FromDays(49)))
return false;
using var uow = _db.GetDbContext();
@@ -336,7 +336,7 @@ WHERE GuildId={guildId}
var ps = uow.GuildConfigsForId(guildId, set => set.Include(x => x.WarnPunishments)).WarnPunishments;
var p = ps.FirstOrDefault(x => x.Count == number);
if (p != null)
if (p is not null)
{
uow.Remove(p);
uow.SaveChanges();

View File

@@ -137,7 +137,7 @@ public class VcRoleService : INService
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
if (toDelete != null) uow.Remove(toDelete);
if (toDelete is not null) uow.Remove(toDelete);
conf.VcRoleInfos.Add(new() { VoiceChannelId = vcId, RoleId = role.Id }); // add new one
uow.SaveChanges();
}
@@ -178,10 +178,10 @@ public class VcRoleService : INService
if (VcRoles.TryGetValue(guildId, out var guildVcRoles))
{
//remove old
if (oldVc != null && guildVcRoles.TryGetValue(oldVc.Id, out var role))
if (oldVc is not null && guildVcRoles.TryGetValue(oldVc.Id, out var role))
Assign(false, gusr, role);
//add new
if (newVc != null && guildVcRoles.TryGetValue(newVc.Id, out role)) Assign(true, gusr, role);
if (newVc is not null && guildVcRoles.TryGetValue(newVc.Id, out role)) Assign(true, gusr, role);
}
}
}