More target-typed new and redundant paranthesis cleanup

This commit is contained in:
Kwoth
2021-12-20 00:33:11 +01:00
parent 345a9e9524
commit 1b2017024c
152 changed files with 573 additions and 580 deletions

View File

@@ -299,7 +299,7 @@ public partial class Administration : NadekoModule<AdministrationService>
[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,

View File

@@ -14,7 +14,7 @@ public sealed class UserSpamStats : IDisposable
public UserSpamStats(IUserMessage msg)
{
LastMessage = msg.Content.ToUpperInvariant();
timers = new ConcurrentQueue<Timer>();
timers = new();
ApplyNextMessage(msg);
}
@@ -31,7 +31,7 @@ public sealed class UserSpamStats : IDisposable
while (timers.TryDequeue(out var old))
old.Change(Timeout.Infinite, Timeout.Infinite);
}
var t = new Timer((_) => {
var t = new Timer(_ => {
if (timers.TryDequeue(out var old))
old.Change(Timeout.Infinite, Timeout.Infinite);
}, null, TimeSpan.FromMinutes(30), TimeSpan.FromMinutes(30));

View File

@@ -44,7 +44,7 @@ namespace NadekoBot.Modules.Administration
{
var result = _service.SelectSql(sql);
return ctx.SendPaginatedConfirmAsync(0, (cur) =>
return ctx.SendPaginatedConfirmAsync(0, cur =>
{
var items = result.Results.Skip(cur * 20).Take(20);

View File

@@ -69,7 +69,7 @@ public partial class Administration
}
else
{
ci = new CultureInfo(name);
ci = new(name);
Localization.SetGuildCulture(ctx.Guild, ci);
}
@@ -103,7 +103,7 @@ public partial class Administration
}
else
{
ci = new CultureInfo(name);
ci = new(name);
Localization.SetDefaultCulture(ci);
}

View File

@@ -23,9 +23,9 @@ public partial class Administration
var user = await ctx.Guild.GetCurrentUserAsync().ConfigureAwait(false);
if (parameter == "-s" || parameter == "--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).ConfigureAwait(false);
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).ConfigureAwait(false);
ctx.Message.DeleteAfter(3);
}
// prune x
@@ -43,7 +43,7 @@ public partial class Administration
count = 1000;
if (parameter == "-s" || parameter == "--safe")
await _service.PruneWhere((ITextChannel)ctx.Channel, count, (x) => !x.IsPinned).ConfigureAwait(false);
await _service.PruneWhere((ITextChannel)ctx.Channel, count, x => !x.IsPinned).ConfigureAwait(false);
else
await _service.PruneWhere((ITextChannel)ctx.Channel, count, x => true).ConfigureAwait(false);
}

View File

@@ -26,7 +26,7 @@ public partial class Administration
public async Task InternalReactionRoles(bool exclusive, ulong? messageId, params string[] input)
{
var target = messageId is ulong msgId
var target = messageId is { } msgId
? await ctx.Channel.GetMessageAsync(msgId).ConfigureAwait(false)
: (await ctx.Channel.GetMessagesAsync(2).FlattenAsync().ConfigureAwait(false))
.Skip(1)
@@ -66,7 +66,7 @@ public partial class Administration
{
try
{
await target.AddReactionAsync(x.emote, new RequestOptions()
await target.AddReactionAsync(x.emote, new()
{
RetryMode = RetryMode.Retry502 | RetryMode.RetryRatelimit
}).ConfigureAwait(false);
@@ -80,7 +80,7 @@ public partial class Administration
await Task.Delay(500).ConfigureAwait(false);
}
if (_service.Add(ctx.Guild.Id, new ReactionRoleMessage()
if (_service.Add(ctx.Guild.Id, new()
{
Exclusive = exclusive,
MessageId = target.Id,

View File

@@ -112,7 +112,7 @@ public partial class Administration
var (exclusive, roles, groups) = _service.GetRoles(ctx.Guild);
await ctx.SendPaginatedConfirmAsync(page, (cur) =>
await ctx.SendPaginatedConfirmAsync(page, cur =>
{
var rolesStr = new StringBuilder();
var roleGroups = roles

View File

@@ -264,7 +264,7 @@ public partial class Administration
$"| {st.GuildCount.ToString().PadBoth(maxGuildCountLength)} `";
})
.ToArray();
await ctx.SendPaginatedConfirmAsync(page, (curPage) =>
await ctx.SendPaginatedConfirmAsync(page, curPage =>
{
var str = string.Join("\n", allShardStrings.Skip(25 * curPage).Take(25));

View File

@@ -26,11 +26,11 @@ public class AdministrationService : INService
_db = db;
_logService = logService;
DeleteMessagesOnCommand = new ConcurrentHashSet<ulong>(bot.AllGuildConfigs
DeleteMessagesOnCommand = new(bot.AllGuildConfigs
.Where(g => g.DeleteMessageOnCommand)
.Select(g => g.GuildId));
DeleteMessagesOnCommandChannels = new ConcurrentDictionary<ulong, bool>(bot.AllGuildConfigs
DeleteMessagesOnCommandChannels = new(bot.AllGuildConfigs
.SelectMany(x => x.DelMsgOnCmdChannels)
.ToDictionary(x => x.ChannelId, x => x.State)
.ToConcurrent());
@@ -108,7 +108,7 @@ public class AdministrationService : INService
{
if (old is null)
{
old = new DelMsgOnCmdChannel { ChannelId = chId };
old = new() { ChannelId = chId };
conf.DelMsgOnCmdChannels.Add(old);
}

View File

@@ -128,7 +128,7 @@ public sealed class AutoAssignRoleService : INService
.GuildConfigs
.AsNoTracking()
.Where(x => x.GuildId == guildId)
.UpdateAsync(_ => new GuildConfig(){ AutoAssignRoleIds = null});
.UpdateAsync(_ => new(){ AutoAssignRoleIds = null});
_autoAssignableRoles.TryRemove(guildId, out _);
@@ -154,7 +154,7 @@ public static class GuildConfigExtensions
public static List<ulong> GetAutoAssignableRoles(this GuildConfig gc)
{
if (string.IsNullOrWhiteSpace(gc.AutoAssignRoleIds))
return new List<ulong>();
return new();
return gc.AutoAssignRoleIds.Split(',').Select(ulong.Parse).ToList();
}

View File

@@ -59,8 +59,8 @@ DELETE FROM Clubs;";
{
var result = new SelectResult()
{
ColumnNames = new List<string>(),
Results = new List<string[]>(),
ColumnNames = new(),
Results = new(),
};
using (var uow = _db.GetDbContext())
@@ -116,14 +116,14 @@ DELETE FROM Clubs;";
.Set<WaifuInfo>()
.AsQueryable()
.Where(x => x.Claimer.UserId == userId)
.UpdateAsync(x => new WaifuInfo() {ClaimerId = null});
.UpdateAsync(x => new() {ClaimerId = null});
// all affinities set to this waifu are reset
await uow
.Set<WaifuInfo>()
.AsQueryable()
.Where(x => x.Affinity.UserId == userId)
.UpdateAsync(x => new WaifuInfo() {AffinityId = null});
.UpdateAsync(x => new() {AffinityId = null});
}
// delete guild xp

View File

@@ -64,7 +64,7 @@ public class DiscordPermOverrideService : INService, ILateBlocker
if (over is null)
{
uow.Set<DiscordPermOverride>()
.Add(over = new DiscordPermOverride()
.Add(over = new()
{
Command = commandName,
Perm = perm,

View File

@@ -19,7 +19,7 @@ public class GameVoiceChannelService : INService
_db = db;
_client = client;
GameVoiceChannels = new ConcurrentHashSet<ulong>(
GameVoiceChannels = new(
bot.AllGuildConfigs.Where(gc => gc.GameVoiceChannel != null)
.Select(gc => gc.GameVoiceChannel.Value));
@@ -40,8 +40,7 @@ public class GameVoiceChannelService : INService
//if the activity has changed, and is a playing activity
if (before.Activity != after.Activity
&& after.Activity != null
&& after.Activity.Type == Discord.ActivityType.Playing)
&& after.Activity is { Type: Discord.ActivityType.Playing })
{
//trigger gvc
await TriggerGvc(after, after.Activity.Name);

View File

@@ -102,7 +102,7 @@ public sealed class LogCommandService : ILogCommandService
.ToConcurrent();
}
_timerReference = new Timer(async (state) =>
_timerReference = new(async state =>
{
var keys = PresenceUpdates.Keys.ToList();
@@ -143,7 +143,7 @@ public sealed class LogCommandService : ILogCommandService
_prot.OnAntiProtectionTriggered += TriggeredAntiProtection;
_clearTimer = new Timer(_ =>
_clearTimer = new(_ =>
{
_ignoreMessageIds.Clear();
}, null, TimeSpan.FromHours(1), TimeSpan.FromHours(1));
@@ -228,7 +228,7 @@ public sealed class LogCommandService : ILogCommandService
(value ? channelId : (ulong?) null);
;
await uow.SaveChangesAsync();
GuildLogSettings.AddOrUpdate(guildId, (id) => logSetting, (id, old) => logSetting);
GuildLogSettings.AddOrUpdate(guildId, id => logSetting, (id, old) => logSetting);
}
}
@@ -299,7 +299,7 @@ public sealed class LogCommandService : ILogCommandService
using (var uow = _db.GetDbContext())
{
var logSetting = uow.LogSettingsFor(gid);
GuildLogSettings.AddOrUpdate(gid, (id) => logSetting, (id, old) => logSetting);
GuildLogSettings.AddOrUpdate(gid, id => logSetting, (id, old) => logSetting);
switch (type)
{
case LogType.Other:

View File

@@ -60,7 +60,7 @@ public class MuteService : INService
.ToDictionary(c => c.GuildId, c => c.MuteRoleName)
.ToConcurrent();
MutedUsers = new ConcurrentDictionary<ulong, ConcurrentHashSet<ulong>>(configs
MutedUsers = new(configs
.ToDictionary(
k => k.GuildId,
v => new ConcurrentHashSet<ulong>(v.MutedUsers.Select(m => m.UserId))
@@ -194,7 +194,7 @@ public class MuteService : INService
var config = uow.GuildConfigsForId(usr.Guild.Id,
set => set.Include(gc => gc.MutedUsers)
.Include(gc => gc.UnmuteTimers));
config.MutedUsers.Add(new MutedUserId()
config.MutedUsers.Add(new()
{
UserId = usr.Id
});
@@ -327,7 +327,7 @@ public class MuteService : INService
using (var uow = _db.GetDbContext())
{
var config = uow.GuildConfigsForId(user.GuildId, set => set.Include(x => x.UnmuteTimers));
config.UnmuteTimers.Add(new UnmuteTimer()
config.UnmuteTimers.Add(new()
{
UserId = user.Id,
UnmuteAt = DateTime.UtcNow + after,
@@ -344,7 +344,7 @@ public class MuteService : INService
using (var uow = _db.GetDbContext())
{
var config = uow.GuildConfigsForId(guild.Id, set => set.Include(x => x.UnbanTimer));
config.UnbanTimer.Add(new UnbanTimer()
config.UnbanTimer.Add(new()
{
UserId = user.Id,
UnbanAt = DateTime.UtcNow + after,
@@ -361,7 +361,7 @@ public class MuteService : INService
using (var uow = _db.GetDbContext())
{
var config = uow.GuildConfigsForId(user.GuildId, set => set.Include(x => x.UnroleTimer));
config.UnroleTimer.Add(new UnroleTimer()
config.UnroleTimer.Add(new()
{
UserId = user.Id,
UnbanAt = DateTime.UtcNow + after,
@@ -433,7 +433,7 @@ public class MuteService : INService
}, null, after, Timeout.InfiniteTimeSpan);
//add it, or stop the old one and add this one
userUnTimers.AddOrUpdate((userId, type), (key) => toAdd, (key, old) =>
userUnTimers.AddOrUpdate((userId, type), key => toAdd, (key, old) =>
{
old.Change(Timeout.Infinite, Timeout.Infinite);
return toAdd;

View File

@@ -39,7 +39,7 @@ public sealed class PlayingRotateService : INService
.WithProviders(phProviders)
.Build();
_t = new Timer(RotatingStatuses, new TimerState(), TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(1));
_t = new(RotatingStatuses, new TimerState(), TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(1));
}
}

View File

@@ -32,7 +32,7 @@ public class ProtectionService : INService
private readonly UserPunishService _punishService;
private readonly Channel<PunishQueueItem> PunishUserQueue =
System.Threading.Channels.Channel.CreateUnbounded<PunishQueueItem>(new UnboundedChannelOptions()
System.Threading.Channels.Channel.CreateUnbounded<PunishQueueItem>(new()
{
SingleReader = true,
SingleWriter = false
@@ -134,11 +134,11 @@ public class ProtectionService : INService
}
if (spam != null)
_antiSpamGuilds[gc.GuildId] = new AntiSpamStats() { AntiSpamSettings = spam };
_antiSpamGuilds[gc.GuildId] = new() { AntiSpamSettings = spam };
var alt = gc.AntiAltSetting;
if (alt is not null)
_antiAltGuilds[gc.GuildId] = new AntiAltStats(alt);
_antiAltGuilds[gc.GuildId] = new(alt);
}
private Task HandleUserJoined(SocketGuildUser user)
@@ -154,7 +154,7 @@ public class ProtectionService : INService
_ = Task.Run(async () =>
{
if (maybeAlts is AntiAltStats alts)
if (maybeAlts is { } alts)
{
if (user.CreatedAt != default)
{
@@ -177,7 +177,7 @@ public class ProtectionService : INService
try
{
if (!(maybeStats is AntiRaidStats stats) || !stats.RaidUsers.Add(user))
if (!(maybeStats is { } stats) || !stats.RaidUsers.Add(user))
return;
++stats.UsersCount;
@@ -217,13 +217,13 @@ public class ProtectionService : INService
try
{
if (!_antiSpamGuilds.TryGetValue(channel.Guild.Id, out var spamSettings) ||
spamSettings.AntiSpamSettings.IgnoredChannels.Contains(new AntiSpamIgnore()
spamSettings.AntiSpamSettings.IgnoredChannels.Contains(new()
{
ChannelId = channel.Id
}))
return;
var stats = spamSettings.UserStats.AddOrUpdate(msg.Author.Id, (id) => new UserSpamStats(msg),
var stats = spamSettings.UserStats.AddOrUpdate(msg.Author.Id, id => new(msg),
(id, old) =>
{
old.ApplyNextMessage(msg); return old;
@@ -261,7 +261,7 @@ public class ProtectionService : INService
foreach (var gu in gus)
{
await PunishUserQueue.Writer.WriteAsync(new PunishQueueItem()
await PunishUserQueue.Writer.WriteAsync(new()
{
Action = action,
Type = pt,
@@ -288,7 +288,7 @@ public class ProtectionService : INService
var stats = new AntiRaidStats()
{
AntiRaidSettings = new AntiRaidSetting()
AntiRaidSettings = new()
{
Action = action,
Seconds = seconds,
@@ -355,7 +355,7 @@ public class ProtectionService : INService
var stats = new AntiSpamStats
{
AntiSpamSettings = new AntiSpamSetting()
AntiSpamSettings = new()
{
Action = action,
MessageThreshold = messageCount,
@@ -457,7 +457,7 @@ public class ProtectionService : INService
{
using var uow = _db.GetDbContext();
var gc = uow.GuildConfigsForId(guildId, set => set.Include(x => x.AntiAltSetting));
gc.AntiAltSetting = new AntiAltSetting()
gc.AntiAltSetting = new()
{
Action = action,
ActionDurationMinutes = actionDurationMinutes,
@@ -466,7 +466,7 @@ public class ProtectionService : INService
};
await uow.SaveChangesAsync();
_antiAltGuilds[guildId] = new AntiAltStats(gc.AntiAltSetting);
_antiAltGuilds[guildId] = new(gc.AntiAltSetting);
}
public async Task<bool> TryStopAntiAlt(ulong guildId)

View File

@@ -88,7 +88,7 @@ public class RoleCommandsService : INService
{
var dl = await msg.GetOrDownloadAsync().ConfigureAwait(false);
await dl.RemoveReactionAsync(reaction.Emote, dl.Author,
new RequestOptions()
new()
{
RetryMode = RetryMode.RetryRatelimit | RetryMode.Retry502
}).ConfigureAwait(false);

View File

@@ -44,7 +44,7 @@ public class SelfAssignedRolesService : INService
return false;
}
uow.SelfAssignableRoles.Add(new SelfAssignedRole
uow.SelfAssignableRoles.Add(new()
{
Group = group,
RoleId = role.Id,
@@ -73,7 +73,7 @@ public class SelfAssignedRolesService : INService
using (var uow = _db.GetDbContext())
{
var stats = uow.GetOrCreateUserXpStats(guildUser.Guild.Id, guildUser.Id);
userLevelData = new LevelStats(stats.Xp + stats.AwardedXp);
userLevelData = new(stats.Xp + stats.AwardedXp);
}
var (autoDelete, exclusive, roles) = GetAdAndRoles(guildUser.Guild.Id);
@@ -144,7 +144,7 @@ public class SelfAssignedRolesService : INService
}
else if (toUpdate is null)
{
gc.SelfAssignableRoleGroupNames.Add(new GroupName
gc.SelfAssignableRoleGroupNames.Add(new()
{
Name = name,
Number = group,

View File

@@ -134,7 +134,7 @@ public sealed class SelfService : ILateExecutor, IReadyExecutor, INService
private Timer TimerFromAutoCommand(AutoCommand x)
{
return new Timer(async (obj) => await ExecuteCommand((AutoCommand) obj).ConfigureAwait(false),
return new(async obj => await ExecuteCommand((AutoCommand) obj).ConfigureAwait(false),
x,
x.Interval * 1000,
x.Interval * 1000);

View File

@@ -30,7 +30,7 @@ public class UserPunishService : INService
_blacklistService = blacklistService;
_bcs = bcs;
_warnExpiryTimer = new Timer(async _ =>
_warnExpiryTimer = new(async _ =>
{
await CheckAllWarnExpiresAsync();
}, null, TimeSpan.FromSeconds(0), TimeSpan.FromHours(12));
@@ -330,7 +330,7 @@ WHERE GuildId={guildId}
uow.RemoveRange(toDelete);
ps.Add(new WarningPunishment()
ps.Add(new()
{
Count = number,
Punishment = punish,
@@ -437,7 +437,7 @@ WHERE GuildId={guildId}
}
else if (template is null)
{
uow.BanTemplates.Add(new BanTemplate()
uow.BanTemplates.Add(new()
{
GuildId = guildId,
Text = text,

View File

@@ -23,8 +23,8 @@ public class VcRoleService : INService
_client = client;
_client.UserVoiceStateUpdated += ClientOnUserVoiceStateUpdated;
VcRoles = new ConcurrentDictionary<ulong, ConcurrentDictionary<ulong, IRole>>();
ToAssign = new ConcurrentDictionary<ulong, ConcurrentQueue<(bool, IGuildUser, IRole)>>();
VcRoles = new();
ToAssign = new();
var missingRoles = new ConcurrentBag<VcRoleInfo>();
using (var uow = db.GetDbContext())
@@ -147,7 +147,7 @@ public class VcRoleService : INService
{
uow.Remove(toDelete);
}
conf.VcRoleInfos.Add(new VcRoleInfo()
conf.VcRoleInfos.Add(new()
{
VoiceChannelId = vcId,
RoleId = role.Id,

View File

@@ -49,7 +49,7 @@ public partial class Administration
await ctx.SendPaginatedConfirmAsync(page,
(curPage) => _eb.Create()
curPage => _eb.Create()
.WithOkColor()
.WithTitle(GetText(strs.timezones_available))
.WithDescription(string.Join("\n", timezoneStrings

View File

@@ -273,7 +273,7 @@ public partial class Administration
return;
var warnings = _service.WarnlogAll(ctx.Guild.Id);
await ctx.SendPaginatedConfirmAsync(page, (curPage) =>
await ctx.SendPaginatedConfirmAsync(page, curPage =>
{
var ws = warnings.Skip(curPage * 15)
.Take(15)
@@ -885,7 +885,7 @@ public partial class Administration
//do the banning
await Task.WhenAll(bans
.Where(x => x.Id.HasValue)
.Select(x => ctx.Guild.AddBanAsync(x.Id.Value, 7, x.Reason, new RequestOptions()
.Select(x => ctx.Guild.AddBanAsync(x.Id.Value, 7, x.Reason, new()
{
RetryMode = RetryMode.AlwaysRetry,
})))

View File

@@ -74,11 +74,11 @@ public static class CustomReactionExtensions
private static bool isValidWordDivider(this in ReadOnlySpan<char> str, int index)
{
var ch = str[index];
if (ch >= 'a' && ch <= 'z')
if (ch is >= 'a' and <= 'z')
return false;
if (ch >= 'A' && ch <= 'Z')
if (ch is >= 'A' and <= 'Z')
return false;
if (ch >= '1' && ch <= '9')
if (ch is >= '1' and <= '9')
return false;
return true;

View File

@@ -278,7 +278,7 @@ public sealed class CustomReactionsService : IEarlyBehavior, IReadyExecutor
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public CustomReaction[] GetCustomReactionsFor(ulong? maybeGuildId)
{
if (maybeGuildId is ulong guildId)
if (maybeGuildId is { } guildId)
{
return _newGuildReactions.TryGetValue(guildId, out var crs)
? crs
@@ -489,7 +489,7 @@ public sealed class CustomReactionsService : IEarlyBehavior, IReadyExecutor
private Task UpdateInternalAsync(ulong? maybeGuildId, CustomReaction cr)
{
if (maybeGuildId is ulong guildId)
if (maybeGuildId is { } guildId)
UpdateInternal(guildId, cr);
else
return _pubSub.Pub(_gcrEditedKey, cr);
@@ -499,7 +499,7 @@ public sealed class CustomReactionsService : IEarlyBehavior, IReadyExecutor
private void UpdateInternal(ulong? maybeGuildId, CustomReaction cr)
{
if (maybeGuildId is ulong guildId)
if (maybeGuildId is { } guildId)
{
_newGuildReactions.AddOrUpdate(guildId, new[] {cr},
(key, old) =>
@@ -532,7 +532,7 @@ public sealed class CustomReactionsService : IEarlyBehavior, IReadyExecutor
// only do this for perf purposes
cr.Trigger = cr.Trigger.Replace(MentionPh, _client.CurrentUser.Mention);
if (maybeGuildId is ulong guildId)
if (maybeGuildId is { } guildId)
{
_newGuildReactions.AddOrUpdate(guildId,
new[] {cr},
@@ -548,7 +548,7 @@ public sealed class CustomReactionsService : IEarlyBehavior, IReadyExecutor
private Task DeleteInternalAsync(ulong? maybeGuildId, int id)
{
if (maybeGuildId is ulong guildId)
if (maybeGuildId is { } guildId)
{
_newGuildReactions.AddOrUpdate(guildId,
Array.Empty<CustomReaction>(),

View File

@@ -38,7 +38,7 @@ public sealed class AnimalRace : IDisposable
{
this._currency = currency;
this._options = options;
this._animalsQueue = new Queue<RaceAnimal>(availableAnimals);
this._animalsQueue = new(availableAnimals);
this.MaxUsers = _animalsQueue.Count;
if (this._animalsQueue.Count == 0)

View File

@@ -16,7 +16,7 @@ public class Betroll
public Betroll(BetRollConfig settings)
{
_thresholdPairs = settings.Pairs.OrderByDescending(x => x.WhenAbove);
_rng = new Random();
_rng = new();
}
public Result Roll()
@@ -26,14 +26,14 @@ public class Betroll
var pair = _thresholdPairs.FirstOrDefault(x => x.WhenAbove < roll);
if (pair is null)
{
return new Result
return new()
{
Multiplier = 0,
Roll = roll,
};
}
return new Result
return new()
{
Multiplier = pair.MultiplyBy,
Roll = roll,

View File

@@ -35,7 +35,7 @@ public class Blackjack
{
_cs = cs;
_db = db;
Dealer = new Dealer();
Dealer = new();
}
public void Start()
@@ -105,7 +105,7 @@ public class Blackjack
{
var pause = Task.Delay(20000); //10 seconds to decide
CurrentUser = usr;
_currentUserMove = new TaskCompletionSource<bool>();
_currentUserMove = new();
await PrintState().ConfigureAwait(false);
// either wait for the user to make an action and
// if he doesn't - stand
@@ -134,7 +134,7 @@ public class Blackjack
return false;
}
Players.Add(new User(user, bet));
Players.Add(new(user, bet));
var _ = PrintState();
return true;
}

View File

@@ -45,7 +45,7 @@ public class CurrencyRaffleGame
_users.First().Amount != amount)
return false;
if (!_users.Add(new User
if (!_users.Add(new()
{
DiscordUser = usr,
Amount = amount,

View File

@@ -7,15 +7,15 @@ public class QuadDeck : Deck
{
protected override void RefillPool()
{
CardPool = new List<Card>(52 * 4);
CardPool = new(52 * 4);
for (var j = 1; j < 14; j++)
{
for (var i = 1; i < 5; i++)
{
CardPool.Add(new Card((CardSuit)i, j));
CardPool.Add(new Card((CardSuit)i, j));
CardPool.Add(new Card((CardSuit)i, j));
CardPool.Add(new Card((CardSuit)i, j));
CardPool.Add(new((CardSuit)i, j));
CardPool.Add(new((CardSuit)i, j));
CardPool.Add(new((CardSuit)i, j));
CardPool.Add(new((CardSuit)i, j));
}
}
}
@@ -60,7 +60,7 @@ public class Deck
{
var str = string.Empty;
if (Number <= 10 && Number > 1)
if (Number is <= 10 and > 1)
{
str += "_" + Number;
}
@@ -101,7 +101,7 @@ public class Deck
throw new ArgumentException("Invalid input", nameof(input));
}
return new Card(s, n);
return new(s, n);
}
public string GetEmojiString()
@@ -189,7 +189,7 @@ public class Deck
/// </summary>
protected virtual void RefillPool()
{
CardPool = new List<Card>(52);
CardPool = new(52);
//foreach suit
for (var j = 1; j < 14; j++)
{
@@ -199,7 +199,7 @@ public class Deck
//generate a card of that suit and number and add it to the pool
// the pool will go from ace of spades,hears,diamonds,clubs all the way to the king of spades. hearts, ...
CardPool.Add(new Card((CardSuit)i, j));
CardPool.Add(new((CardSuit)i, j));
}
}
}
@@ -256,7 +256,7 @@ public class Deck
- cards.Min(card => (int)card.Number) == 4);
if (toReturn || cards.All(c => c.Number != 1)) return toReturn;
var newCards = cards.Select(c => c.Number == 1 ? new Card(c.Suit, 14) : c);
var newCards = cards.Select(c => c.Number == 1 ? new(c.Suit, 14) : c);
return (newCards.Max(card => (int)card.Number)
- newCards.Min(card => (int)card.Number) == 4);
}
@@ -281,7 +281,7 @@ public class Deck
bool isStraightFlush(List<Card> cards) => hasStraightFlush(cards) && !isRoyalFlush(cards);
handValues = new Dictionary<string, Func<List<Card>, bool>>
handValues = new()
{
{ "Royal Flush", isRoyalFlush },
{ "Straight Flush", isStraightFlush },

View File

@@ -54,12 +54,12 @@ public class GameStatusEvent : ICurrencyEvent
_channel = ch;
_opts = opt;
// generate code
_code = new string(_sneakyGameStatusChars.Shuffle().Take(5).ToArray());
_code = new(_sneakyGameStatusChars.Shuffle().Take(5).ToArray());
_t = new Timer(OnTimerTick, null, Timeout.InfiniteTimeSpan, TimeSpan.FromSeconds(2));
_t = new(OnTimerTick, null, Timeout.InfiniteTimeSpan, TimeSpan.FromSeconds(2));
if (_opts.Hours > 0)
{
_timeout = new Timer(EventTimeout, null, TimeSpan.FromHours(_opts.Hours), Timeout.InfiniteTimeSpan);
_timeout = new(EventTimeout, null, TimeSpan.FromHours(_opts.Hours), Timeout.InfiniteTimeSpan);
}
}
@@ -92,7 +92,7 @@ public class GameStatusEvent : ICurrencyEvent
await _msg.ModifyAsync(m =>
{
m.Embed = GetEmbed(PotSize).Build();
}, new RequestOptions() { RetryMode = RetryMode.AlwaysRetry }).ConfigureAwait(false);
}, new() { RetryMode = RetryMode.AlwaysRetry }).ConfigureAwait(false);
}
Log.Information("Awarded {0} users {1} currency.{2}",
@@ -175,7 +175,7 @@ public class GameStatusEvent : ICurrencyEvent
try
{
await msg.DeleteAsync(new RequestOptions()
await msg.DeleteAsync(new()
{
RetryMode = RetryMode.AlwaysFail
});

View File

@@ -52,10 +52,10 @@ public class ReactionEvent : ICurrencyEvent
_opts = opt;
_config = config;
_t = new Timer(OnTimerTick, null, Timeout.InfiniteTimeSpan, TimeSpan.FromSeconds(2));
_t = new(OnTimerTick, null, Timeout.InfiniteTimeSpan, TimeSpan.FromSeconds(2));
if (_opts.Hours > 0)
{
_timeout = new Timer(EventTimeout, null, TimeSpan.FromHours(_opts.Hours), Timeout.InfiniteTimeSpan);
_timeout = new(EventTimeout, null, TimeSpan.FromHours(_opts.Hours), Timeout.InfiniteTimeSpan);
}
}
@@ -88,7 +88,7 @@ public class ReactionEvent : ICurrencyEvent
await _msg.ModifyAsync(m =>
{
m.Embed = GetEmbed(PotSize).Build();
}, new RequestOptions() { RetryMode = RetryMode.AlwaysRetry }).ConfigureAwait(false);
}, new() { RetryMode = RetryMode.AlwaysRetry }).ConfigureAwait(false);
}
Log.Information("Awarded {0} users {1} currency.{2}",

View File

@@ -11,15 +11,15 @@ public sealed partial class GamblingConfig : ICloneable<GamblingConfig>
{
public GamblingConfig()
{
BetRoll = new BetRollConfig();
WheelOfFortune = new WheelOfFortuneSettings();
Waifu = new WaifuConfig();
Currency = new CurrencyConfig();
BetFlip = new BetFlipConfig();
Generation = new GenerationConfig();
Timely = new TimelyConfig();
Decay = new DecayConfig();
Slots = new SlotsConfig();
BetRoll = new();
WheelOfFortune = new();
Waifu = new();
Currency = new();
BetFlip = new();
Generation = new();
Timely = new();
Decay = new();
Slots = new();
}
[Comment(@"DO NOT CHANGE")]

View File

@@ -13,7 +13,7 @@ public abstract class GamblingModule<TService> : NadekoModule<TService>
protected GamblingModule(GamblingConfigService gambService)
{
_lazyConfig = new Lazy<GamblingConfig>(() => gambService.Data);
_lazyConfig = new(() => gambService.Data);
}
private async Task<bool> InternalCheckBet(long amount)

View File

@@ -49,7 +49,7 @@ public class RollDuelGame
this.Amount = amount;
_cs = cs;
_timeoutTimer = new Timer(async delegate
_timeoutTimer = new(async delegate
{
await _locker.WaitAsync().ConfigureAwait(false);
try

View File

@@ -36,6 +36,6 @@ public class SlotGame
else if (rolls.Any(x => x == 5))
multi = 1;
return new Result(multi, rolls);
return new(multi, rolls);
}
}

View File

@@ -20,7 +20,7 @@ public class WheelOfFortuneGame
public WheelOfFortuneGame(ulong userId, long bet, GamblingConfig config, ICurrencyService cs)
{
_rng = new NadekoRandom();
_rng = new();
_cs = cs;
_bet = bet;
_config = config;
@@ -36,7 +36,7 @@ public class WheelOfFortuneGame
if (amount > 0)
await _cs.AddAsync(_userId, "Wheel Of Fortune - won", amount, gamble: true).ConfigureAwait(false);
return new Result
return new()
{
Index = result,
Amount = amount,

View File

@@ -78,7 +78,7 @@ public sealed class Connect4Game : IDisposable
_options = options;
_cs = cs;
_rng = new NadekoRandom();
_rng = new();
for (var i = 0; i < NumberOfColumns * NumberOfRows; i++)
{
_gameState[i] = Field.Empty;
@@ -133,7 +133,7 @@ public sealed class Connect4Game : IDisposable
_players[1] = (userId, userName);
CurrentPhase = Phase.P1Move; //start the game
_playerTimeoutTimer = new Timer(async state =>
_playerTimeoutTimer = new(async state =>
{
await _locker.WaitAsync().ConfigureAwait(false);
try

View File

@@ -137,7 +137,7 @@ public partial class Gambling
Match match;
if ((match = fudgeRegex.Match(arg)).Length != 0 &&
int.TryParse(match.Groups["n1"].ToString(), out var n1) &&
n1 > 0 && n1 < 500)
n1 is > 0 and < 500)
{
var rng = new NadekoRandom();

View File

@@ -31,7 +31,7 @@ public partial class Gambling
if (num < 1 || num > 10)
throw new ArgumentOutOfRangeException(nameof(num));
var cards = guildId is null ? new Deck() : _allDecks.GetOrAdd(ctx.Guild, (s) => new Deck());
var cards = guildId is null ? new() : _allDecks.GetOrAdd(ctx.Guild, s => new());
var images = new List<Image<Rgba32>>();
var cardObjects = new List<Deck.Card>();
for (var i = 0; i < num; i++)
@@ -108,7 +108,7 @@ public partial class Gambling
//var channel = (ITextChannel)ctx.Channel;
_allDecks.AddOrUpdate(ctx.Guild,
(g) => new Deck(),
g => new(),
(g, c) =>
{
c.Restart();

View File

@@ -105,7 +105,7 @@ public partial class Gambling
return Task.CompletedTask;
var enabledIn = _service.GetAllGeneratingChannels();
return ctx.SendPaginatedConfirmAsync(page, (cur) =>
return ctx.SendPaginatedConfirmAsync(page, cur =>
{
var items = enabledIn.Skip(page * 9).Take(9);

View File

@@ -34,7 +34,7 @@ public class CurrencyRaffleService : INService
if (!Games.TryGetValue(channelId, out var crg))
{
newGame = true;
crg = new CurrencyRaffleGame(mixed
crg = new(mixed
? CurrencyRaffleGame.Type.Mixed
: CurrencyRaffleGame.Type.Normal);
Games.Add(channelId, crg);

View File

@@ -24,7 +24,7 @@ public sealed class GamblingConfigService : ConfigServiceBase<GamblingConfig>
AddParsedProp("gen.min", gs => gs.Generation.MinAmount, int.TryParse, ConfigPrinters.ToString, val => val >= 1);
AddParsedProp("gen.max", gs => gs.Generation.MaxAmount, int.TryParse, ConfigPrinters.ToString, val => val >= 1);
AddParsedProp("gen.cd", gs => gs.Generation.GenCooldown, int.TryParse, ConfigPrinters.ToString, val => val > 0);
AddParsedProp("gen.chance", gs => gs.Generation.Chance, decimal.TryParse, ConfigPrinters.ToString, val => val >= 0 && val <= 1);
AddParsedProp("gen.chance", gs => gs.Generation.Chance, decimal.TryParse, ConfigPrinters.ToString, val => val is >= 0 and <= 1);
AddParsedProp("gen.has_pw", gs => gs.Generation.HasPassword, bool.TryParse, ConfigPrinters.ToString);
AddParsedProp("bf.multi", gs => gs.BetFlip.Multiplier, decimal.TryParse, ConfigPrinters.ToString, val => val >= 1);
AddParsedProp("waifu.min_price", gs => gs.Waifu.MinPrice, int.TryParse, ConfigPrinters.ToString, val => val >= 0);
@@ -35,7 +35,7 @@ public sealed class GamblingConfigService : ConfigServiceBase<GamblingConfig>
AddParsedProp("waifu.multi.all_gifts", gs => gs.Waifu.Multipliers.AllGiftPrices, decimal.TryParse, ConfigPrinters.ToString, val => val > 0);
AddParsedProp("waifu.multi.gift_effect", gs => gs.Waifu.Multipliers.GiftEffect, decimal.TryParse, ConfigPrinters.ToString, val => val >= 0);
AddParsedProp("waifu.multi.negative_gift_effect", gs => gs.Waifu.Multipliers.NegativeGiftEffect, decimal.TryParse, ConfigPrinters.ToString, val => val >= 0);
AddParsedProp("decay.percent", gs => gs.Decay.Percent, decimal.TryParse, ConfigPrinters.ToString, val => val >= 0 && val <= 1);
AddParsedProp("decay.percent", gs => gs.Decay.Percent, decimal.TryParse, ConfigPrinters.ToString, val => val is >= 0 and <= 1);
AddParsedProp("decay.maxdecay", gs => gs.Decay.MaxDecay, int.TryParse, ConfigPrinters.ToString, val => val >= 0);
AddParsedProp("decay.threshold", gs => gs.Decay.MinThreshold, int.TryParse, ConfigPrinters.ToString, val => val >= 0);

View File

@@ -39,7 +39,7 @@ public class GamblingService : INService
if (_bot.Client.ShardId == 0)
{
_decayTimer = new Timer(_ =>
_decayTimer = new(_ =>
{
var config = _gss.Data;
var maxDecay = config.Decay.MaxDecay;
@@ -85,7 +85,7 @@ WHERE CurrencyAmount > {config.Decay.MinThreshold} AND UserId!={_client.CurrentU
if (!takeRes)
{
return new SlotResponse
return new()
{
Error = GamblingError.NotEnough
};

View File

@@ -48,7 +48,7 @@ public class PlantPickService : INService
_fonts = fonts;
_cs = cs;
_cmdHandler = cmdHandler;
_rng = new NadekoRandom();
_rng = new();
_client = client;
_gss = gss;
@@ -62,7 +62,7 @@ public class PlantPickService : INService
.Where(x => guildIds.Contains(x.GuildId))
.ToList();
_generationChannels = new ConcurrentHashSet<ulong>(configs
_generationChannels = new(configs
.SelectMany(c => c.GenerateCurrencyChannelIds.Select(obj => obj.ChannelId)));
}
}
@@ -155,7 +155,7 @@ public class PlantPickService : INService
img.Mutate(x =>
{
// measure the size of the text to be drawing
var size = TextMeasurer.Measure(pass, new RendererOptions(font, new PointF(0, 0)));
var size = TextMeasurer.Measure(pass, new(font, new PointF(0, 0)));
// fill the background with black, add 5 pixels on each side to make it look better
x.FillPolygon(Color.ParseHex("00000080"),
@@ -168,7 +168,7 @@ public class PlantPickService : INService
x.DrawText(pass,
font,
SixLabors.ImageSharp.Color.White,
new PointF(0, 0));
new(0, 0));
});
// return image as a stream for easy sending
return (img.ToStream(format), format.FileExtensions.FirstOrDefault() ?? "png");
@@ -364,7 +364,7 @@ public class PlantPickService : INService
{
using (var uow = _db.GetDbContext())
{
uow.PlantedCurrency.Add(new PlantedCurrency
uow.PlantedCurrency.Add(new()
{
Amount = amount,
GuildId = gid,

View File

@@ -42,7 +42,7 @@ public class VoteRewardService : INService, IReadyExecutor
if (_client.ShardId != 0)
return;
_http = new HttpClient(new HttpClientHandler()
_http = new(new HttpClientHandler()
{
AllowAutoRedirect = false,
ServerCertificateCustomValidationCallback = delegate { return true; }

View File

@@ -175,14 +175,14 @@ public class WaifuService : INService
}
else
{
uow.WaifuInfo.Add(w = new WaifuInfo()
uow.WaifuInfo.Add(w = new()
{
Waifu = waifu,
Claimer = claimer,
Affinity = null,
Price = amount
});
uow.WaifuUpdates.Add(new WaifuUpdate()
uow.WaifuUpdates.Add(new()
{
User = waifu,
Old = null,
@@ -205,7 +205,7 @@ public class WaifuService : INService
w.Price = amount + (amount / 4);
result = WaifuClaimResult.Success;
uow.WaifuUpdates.Add(new WaifuUpdate()
uow.WaifuUpdates.Add(new()
{
User = w.Waifu,
Old = oldClaimer,
@@ -227,7 +227,7 @@ public class WaifuService : INService
w.Price = amount;
result = WaifuClaimResult.Success;
uow.WaifuUpdates.Add(new WaifuUpdate()
uow.WaifuUpdates.Add(new()
{
User = w.Waifu,
Old = oldClaimer,
@@ -264,7 +264,7 @@ public class WaifuService : INService
else if (w is null)
{
var thisUser = uow.GetOrCreateUser(user);
uow.WaifuInfo.Add(new WaifuInfo()
uow.WaifuInfo.Add(new()
{
Affinity = newAff,
Waifu = thisUser,
@@ -273,7 +273,7 @@ public class WaifuService : INService
});
success = true;
uow.WaifuUpdates.Add(new WaifuUpdate()
uow.WaifuUpdates.Add(new()
{
User = thisUser,
Old = null,
@@ -288,7 +288,7 @@ public class WaifuService : INService
w.Affinity = newAff;
success = true;
uow.WaifuUpdates.Add(new WaifuUpdate()
uow.WaifuUpdates.Add(new()
{
User = w.Waifu,
Old = oldAff,
@@ -353,7 +353,7 @@ public class WaifuService : INService
var oldClaimer = w.Claimer;
w.Claimer = null;
uow.WaifuUpdates.Add(new WaifuUpdate()
uow.WaifuUpdates.Add(new()
{
User = w.Waifu,
Old = oldClaimer,
@@ -382,7 +382,7 @@ public class WaifuService : INService
.Include(x => x.Claimer));
if (w is null)
{
uow.WaifuInfo.Add(w = new WaifuInfo()
uow.WaifuInfo.Add(w = new()
{
Affinity = null,
Claimer = null,
@@ -393,7 +393,7 @@ public class WaifuService : INService
if (!itemObj.Negative)
{
w.Items.Add(new WaifuItem()
w.Items.Add(new()
{
Name = itemObj.Name.ToLowerInvariant(),
ItemEmoji = itemObj.ItemEmoji,
@@ -428,17 +428,17 @@ public class WaifuService : INService
var wi = uow.GetWaifuInfo(targetId);
if (wi is null)
{
wi = new WaifuInfoStats
wi = new()
{
AffinityCount = 0,
AffinityName = null,
ClaimCount = 0,
ClaimerName = null,
Claims = new List<string>(),
Fans = new List<string>(),
Claims = new(),
Fans = new(),
DivorceCount = 0,
FullName = null,
Items = new List<WaifuItem>(),
Items = new(),
Price = 1
};
}

View File

@@ -49,7 +49,7 @@ public partial class Gambling
set => set.Include(x => x.ShopEntries)
.ThenInclude(x => x.Items)).ShopEntries
.ToIndexed();
return ctx.SendPaginatedConfirmAsync(page, (curPage) =>
return ctx.SendPaginatedConfirmAsync(page, curPage =>
{
var theseEntries = entries.Skip(curPage * 9).Take(9).ToArray();
@@ -261,7 +261,7 @@ public partial class Gambling
Price = price,
Type = ShopEntryType.List,
AuthorId = ctx.User.Id,
Items = new HashSet<ShopEntryItem>(),
Items = new(),
};
using (var uow = _db.GetDbContext())
{

View File

@@ -54,13 +54,13 @@ public partial class Gambling
static readonly List<Func<int[], int>> _winningCombos = new List<Func<int[], int>>()
{
//three flowers
(arr) => arr.All(a=>a==MaxValue) ? 30 : 0,
arr => arr.All(a=>a==MaxValue) ? 30 : 0,
//three of the same
(arr) => !arr.Any(a => a != arr[0]) ? 10 : 0,
arr => !arr.Any(a => a != arr[0]) ? 10 : 0,
//two flowers
(arr) => arr.Count(a => a == MaxValue) == 2 ? 4 : 0,
arr => arr.Count(a => a == MaxValue) == 2 ? 4 : 0,
//one flower
(arr) => arr.Any(a => a == MaxValue) ? 1 : 0,
arr => arr.Any(a => a == MaxValue) ? 1 : 0,
};
public static SlotResult Pull()
@@ -78,7 +78,7 @@ public partial class Gambling
break;
}
return new SlotResult(numbers, multi);
return new(numbers, multi);
}
public struct SlotResult
@@ -186,40 +186,40 @@ public partial class Gambling
Color fontColor = _config.Slots.CurrencyFontColor;
bgImage.Mutate(x => x.DrawText(new TextGraphicsOptions
bgImage.Mutate(x => x.DrawText(new()
{
TextOptions = new TextOptions()
TextOptions = new()
{
HorizontalAlignment = HorizontalAlignment.Center,
VerticalAlignment = VerticalAlignment.Center,
WrapTextWidth = 140,
}
}, result.Won.ToString(), _fonts.DottyFont.CreateFont(65), fontColor,
new PointF(227, 92)));
new(227, 92)));
var bottomFont = _fonts.DottyFont.CreateFont(50);
bgImage.Mutate(x => x.DrawText(new TextGraphicsOptions
bgImage.Mutate(x => x.DrawText(new()
{
TextOptions = new TextOptions()
TextOptions = new()
{
HorizontalAlignment = HorizontalAlignment.Center,
VerticalAlignment = VerticalAlignment.Center,
WrapTextWidth = 135,
}
}, amount.ToString(), bottomFont, fontColor,
new PointF(129, 472)));
new(129, 472)));
bgImage.Mutate(x => x.DrawText(new TextGraphicsOptions
bgImage.Mutate(x => x.DrawText(new()
{
TextOptions = new TextOptions()
TextOptions = new()
{
HorizontalAlignment = HorizontalAlignment.Center,
VerticalAlignment = VerticalAlignment.Center,
WrapTextWidth = 135,
}
}, ownedAmount.ToString(), bottomFont, fontColor,
new PointF(325, 472)));
new(325, 472)));
//sw.PrintLap("drew red text");
for (var i = 0; i < 3; i++)

View File

@@ -308,7 +308,7 @@ public partial class Gambling
return;
var waifuItems = _service.GetWaifuItems();
await ctx.SendPaginatedConfirmAsync(page, (cur) =>
await ctx.SendPaginatedConfirmAsync(page, cur =>
{
var embed = _eb.Create()
.WithTitle(GetText(strs.waifu_gift_shop))

View File

@@ -41,7 +41,7 @@ public partial class Games
return;
}
_service.ChatterBotGuilds.TryAdd(channel.Guild.Id, new Lazy<IChatterBotSession>(() => _service.CreateSession(), true));
_service.ChatterBotGuilds.TryAdd(channel.Guild.Id, new(() => _service.CreateSession(), true));
using (var uow = _db.GetDbContext())
{

View File

@@ -60,7 +60,7 @@ public sealed class AcrophobiaGame : IDisposable
public AcrophobiaGame(Options options)
{
Opts = options;
_rng = new NadekoRandom();
_rng = new();
InitializeStartingLetters();
}

View File

@@ -60,7 +60,7 @@ public class CleverbotIOSession : IChatterBotSession
this._user = user;
this._httpFactory = factory;
_nick = new AsyncLazy<string>((Func<Task<string>>)GetNick);
_nick = new((Func<Task<string>>)GetNick);
}
private async Task<string> GetNick()

View File

@@ -30,7 +30,7 @@ public class GirlRating
Advice = advice; // convenient to have it here, even though atm there are only few different ones.
_httpFactory = factory;
Stream = new AsyncLazy<Stream>(() =>
Stream = new(() =>
{
try
{
@@ -45,7 +45,7 @@ public class GirlRating
using (var pointImg = Image.Load(_images.RategirlDot))
{
img.Mutate(x => x.DrawImage(pointImg, new Point(pointx - 10, pointy - 10), new GraphicsOptions()));
img.Mutate(x => x.DrawImage(pointImg, new(pointx - 10, pointy - 10), new GraphicsOptions()));
}
var imgStream = new MemoryStream();

View File

@@ -67,7 +67,7 @@ public sealed class NunchiGame : IDisposable
return false;
}
_killTimer = new Timer(async state =>
_killTimer = new(async state =>
{
await _locker.WaitAsync().ConfigureAwait(false);
try

View File

@@ -43,7 +43,7 @@ public class PollRunner
if (usr is null)
return false;
voteObj = new PollVote()
voteObj = new()
{
UserId = msg.Author.Id,
VoteIndex = vote,

View File

@@ -68,7 +68,7 @@ public class TicTacToe
};
_phase = Phase.Starting;
_moveLock = new SemaphoreSlim(1, 1);
_moveLock = new(1, 1);
}
private string GetText(LocStr key)
@@ -149,7 +149,7 @@ public class TicTacToe
_phase = Phase.Started;
_timeoutTimer = new Timer(async (_) =>
_timeoutTimer = new(async _ =>
{
await _moveLock.WaitAsync().ConfigureAwait(false);
try

View File

@@ -43,7 +43,7 @@ public class TriviaGame
TriviaOptions options, string quitCommand, IEmbedBuilderService eb)
{
_cache = cache;
_questionPool = new TriviaQuestionPool(_cache);
_questionPool = new(_cache);
_strings = strings;
_client = client;
_config = config;
@@ -65,7 +65,7 @@ public class TriviaGame
while (!ShouldStopGame)
{
// reset the cancellation source
_triviaCancelSource = new CancellationTokenSource();
_triviaCancelSource = new();
showHowToQuit = !showHowToQuit;
// load question

View File

@@ -28,7 +28,7 @@ public class TriviaQuestionPool
if (isPokemon)
{
var num = _rng.Next(1, maxPokemonId + 1);
return new TriviaQuestion("Who's That Pokémon?",
return new("Who's That Pokémon?",
Map[num].ToTitleCase(),
"Pokemon",
$@"https://nadeko.bot/images/pokemon/shadows/{num}.png",

View File

@@ -47,8 +47,8 @@ public class TypingGame
this.Channel = channel;
IsActive = false;
sw = new Stopwatch();
finishedUserIds = new List<ulong>();
sw = new();
finishedUserIds = new();
}
public async Task<bool> Stop()
@@ -85,7 +85,7 @@ public class TypingGame
var time = _options.StartTime;
var msg = await Channel.SendMessageAsync($"Starting new typing contest in **{time}**...", options: new RequestOptions()
var msg = await Channel.SendMessageAsync($"Starting new typing contest in **{time}**...", options: new()
{
RetryMode = RetryMode.AlwaysRetry
}).ConfigureAwait(false);

View File

@@ -145,7 +145,7 @@ public partial class Games : NadekoModule<GamesService>
advice = ratings.Uni;
}
return new GirlRating(_images, _httpFactory, crazy, hot, roll, advice);
return new(_images, _httpFactory, crazy, hot, roll, advice);
}
[NadekoCommand, Aliases]

View File

@@ -38,7 +38,7 @@ public class ChatterBotService : IEarlyBehavior
_eb = eb;
_httpFactory = factory;
ChatterBotGuilds = new ConcurrentDictionary<ulong, Lazy<IChatterBotSession>>(
ChatterBotGuilds = new(
bot.AllGuildConfigs
.Where(gc => gc.CleverbotEnabled)
.ToDictionary(gc => gc.GuildId, gc => new Lazy<IChatterBotSession>(() => CreateSession(), true)));

View File

@@ -31,7 +31,7 @@ public sealed class GamesConfigService : ConfigServiceBase<GamesConfig>
ModifyConfig(c =>
{
c.Version = 1;
c.Hangman = new HangmanConfig()
c.Hangman = new()
{
CurrencyReward = 0
};

View File

@@ -62,11 +62,11 @@ public class GamesService : INService
SizeLimit = 500_000
});
Ratings = new AsyncLazy<RatingTexts>(GetRatingTexts);
Ratings = new(GetRatingTexts);
_rng = new NadekoRandom();
//girl ratings
_t = new Timer((_) =>
_t = new(_ =>
{
GirlRatings.Clear();
@@ -79,7 +79,7 @@ public class GamesService : INService
catch (Exception ex)
{
Log.Warning("Error while loading typing articles {0}", ex.ToString());
TypingArticles = new List<TypingArticle>();
TypingArticles = new();
}
}
@@ -94,7 +94,7 @@ public class GamesService : INService
public void AddTypingArticle(IUser user, string text)
{
TypingArticles.Add(new TypingArticle
TypingArticles.Add(new()
{
Source = user.ToString(),
Extra = $"Text added on {DateTime.UtcNow} by {user}.",

View File

@@ -51,13 +51,13 @@ public class PollService : IEarlyBehavior
var col = new IndexedCollection<PollAnswer>(data.Skip(1)
.Select(x => new PollAnswer() { Text = x }));
return new Poll()
return new()
{
Answers = col,
Question = data[0],
ChannelId = channelId,
GuildId = guildId,
Votes = new System.Collections.Generic.HashSet<PollVote>()
Votes = new()
};
}

View File

@@ -32,7 +32,7 @@ public partial class Games
var (options, _) = OptionsParser.ParseFrom(new TypingGame.Options(), args);
var channel = (ITextChannel)ctx.Channel;
var game = _service.RunningContests.GetOrAdd(ctx.Guild.Id, id => new TypingGame(_games, _client, channel, Prefix, options, _eb));
var game = _service.RunningContests.GetOrAdd(ctx.Guild.Id, id => new(_games, _client, channel, Prefix, options, _eb));
if (game.IsActive)
{

View File

@@ -42,11 +42,11 @@ public partial class Games
});
return;
}
game = new TicTacToe(base.Strings, this._client, channel, (IGuildUser)ctx.User, options, _eb);
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);
game.OnEnded += (g) =>
game.OnEnded += g =>
{
_service.TicTacToeGames.Remove(channel.Id);
_sem.Dispose();

View File

@@ -42,7 +42,7 @@ public class Help : NadekoModule<HelpService>
_client = client;
_strings = strings;
_lazyClientId = new AsyncLazy<ulong>(async () => (await _client.GetApplicationInfoAsync()).Id);
_lazyClientId = new(async () => (await _client.GetApplicationInfoAsync()).Id);
}
public async Task<SmartText> GetHelpString()
@@ -196,7 +196,7 @@ public class Help : NadekoModule<HelpService>
var succ = new HashSet<CommandInfo>();
if (opts.View != CommandsOptions.ViewType.All)
{
succ = new HashSet<CommandInfo>((await Task.WhenAll(cmds.Select(async x =>
succ = new((await Task.WhenAll(cmds.Select(async x =>
{
var pre = (await x.CheckPreconditionsAsync(Context, _services).ConfigureAwait(false));
return (Cmd: x, Succ: pre.IsSuccess);
@@ -360,7 +360,7 @@ public class Help : NadekoModule<HelpService>
var config = new AmazonS3Config {ServiceURL = serviceUrl};
using var dlClient = new AmazonS3Client(accessKey, secretAcccessKey, config);
var oldVersionObject = await dlClient.GetObjectAsync(new GetObjectRequest()
var oldVersionObject = await dlClient.GetObjectAsync(new()
{
BucketName = "nadeko-pictures",
Key = "cmds/versions.json",
@@ -368,7 +368,7 @@ public class Help : NadekoModule<HelpService>
using (var client = new AmazonS3Client(accessKey, secretAcccessKey, config))
{
await client.PutObjectAsync(new PutObjectRequest()
await client.PutObjectAsync(new()
{
BucketName = "nadeko-pictures",
ContentType = "application/json",
@@ -397,7 +397,7 @@ public class Help : NadekoModule<HelpService>
// upload the updated version list
using var client = new AmazonS3Client(accessKey, secretAcccessKey, config);
await client.PutObjectAsync(new PutObjectRequest()
await client.PutObjectAsync(new()
{
BucketName = "nadeko-pictures",
ContentType = "application/json",

View File

@@ -138,9 +138,9 @@ public class HelpService : ILateExecutor, INService
var userPermString = string.Empty;
if (userPerm is not null)
{
if (userPerm.UserPermissionAttribute.ChannelPermission is ChannelPermission cPerm)
if (userPerm.UserPermissionAttribute.ChannelPermission is { } cPerm)
userPermString = GetPreconditionString((ChannelPerm) cPerm);
if (userPerm.UserPermissionAttribute.GuildPermission is GuildPermission gPerm)
if (userPerm.UserPermissionAttribute.GuildPermission is { } gPerm)
userPermString = GetPreconditionString((GuildPerm) gPerm);
}

View File

@@ -57,7 +57,7 @@ public sealed class MusicPlayer : IMusicPlayer
_songBuffer = new PoopyBufferImmortalized(_vc.InputLength);
_thread = new Thread(async () =>
_thread = new(async () =>
{
await PlayLoop();
});
@@ -67,28 +67,28 @@ public sealed class MusicPlayer : IMusicPlayer
private static VoiceClient GetVoiceClient(QualityPreset qualityPreset)
=> qualityPreset switch
{
QualityPreset.Highest => new VoiceClient(
QualityPreset.Highest => new(
SampleRate._48k,
Bitrate._192k,
Channels.Two,
FrameDelay.Delay20,
BitDepthEnum.Float32
),
QualityPreset.High => new VoiceClient(
QualityPreset.High => new(
SampleRate._48k,
Bitrate._128k,
Channels.Two,
FrameDelay.Delay40,
BitDepthEnum.Float32
),
QualityPreset.Medium => new VoiceClient(
QualityPreset.Medium => new(
SampleRate._48k,
Bitrate._96k,
Channels.Two,
FrameDelay.Delay40,
BitDepthEnum.UInt16
),
QualityPreset.Low => new VoiceClient(
QualityPreset.Low => new(
SampleRate._48k,
Bitrate._64k,
Channels.Two,
@@ -315,7 +315,7 @@ public sealed class MusicPlayer : IMusicPlayer
private void HandleQueuePostTrack()
{
if (_forceIndex is int forceIndex)
if (_forceIndex is { } forceIndex)
{
_queue.SetIndex(forceIndex);
_forceIndex = null;

View File

@@ -62,7 +62,7 @@ public sealed partial class MusicQueue : IMusicQueue
public MusicQueue()
{
_index = 0;
_tracks = new LinkedList<QueuedTrackInfo>();
_tracks = new();
}
public IQueuedTrackInfo Enqueue(ITrackInfo trackInfo, string queuer, out int index)
@@ -283,7 +283,7 @@ public sealed partial class MusicQueue : IMusicQueue
_index = i;
}
_tracks = new LinkedList<QueuedTrackInfo>(list);
_tracks = new(list);
}
}

View File

@@ -81,7 +81,7 @@ public sealed class VoiceProxy : IVoiceProxy
await Task.Delay(DELAY_ON_ERROR_MILISECONDS);
Log.Debug(ex, "Error performing proxy gateway action");
}
} while (errorCount > 0 && errorCount <= MAX_ERROR_COUNT);
} while (errorCount is > 0 and <= MAX_ERROR_COUNT);
return State != VoiceProxyState.Stopped && errorCount <= MAX_ERROR_COUNT;
}
@@ -93,12 +93,12 @@ public sealed class VoiceProxy : IVoiceProxy
public Task StartSpeakingAsync()
{
return RunGatewayAction((gw) => gw.SendSpeakingAsync(VoiceSpeaking.State.Microphone));
return RunGatewayAction(gw => gw.SendSpeakingAsync(VoiceSpeaking.State.Microphone));
}
public Task StopSpeakingAsync()
{
return RunGatewayAction((gw) => gw.SendSpeakingAsync(VoiceSpeaking.State.None));
return RunGatewayAction(gw => gw.SendSpeakingAsync(VoiceSpeaking.State.None));
}
public async Task StartGateway()
@@ -108,7 +108,7 @@ public sealed class VoiceProxy : IVoiceProxy
public Task StopGateway()
{
if(_gateway is VoiceGateway gw)
if(_gateway is { } gw)
return gw.StopAsync();
return Task.CompletedTask;

View File

@@ -37,7 +37,7 @@ public sealed class LocalTrackResolver : ILocalTrackResolver
DirectoryInfo dir;
try
{
dir = new DirectoryInfo(dirPath);
dir = new(dirPath);
}
catch (Exception ex)
{

View File

@@ -32,46 +32,46 @@ public sealed class YtdlYoutubeResolver : IYoutubeResolver
_google = google;
_ytdlPlaylistOperation =
new YtdlOperation("-4 " +
"--geo-bypass " +
"--encoding UTF8 " +
"-f bestaudio " +
"-e " +
"--get-url " +
"--get-id " +
"--get-thumbnail " +
"--get-duration " +
"--no-check-certificate " +
"-i " +
"--yes-playlist " +
"-- \"{0}\"");
new("-4 " +
"--geo-bypass " +
"--encoding UTF8 " +
"-f bestaudio " +
"-e " +
"--get-url " +
"--get-id " +
"--get-thumbnail " +
"--get-duration " +
"--no-check-certificate " +
"-i " +
"--yes-playlist " +
"-- \"{0}\"");
_ytdlIdOperation =
new YtdlOperation("-4 " +
"--geo-bypass " +
"--encoding UTF8 " +
"-f bestaudio " +
"-e " +
"--get-url " +
"--get-id " +
"--get-thumbnail " +
"--get-duration " +
"--no-check-certificate " +
"-- \"{0}\"");
new("-4 " +
"--geo-bypass " +
"--encoding UTF8 " +
"-f bestaudio " +
"-e " +
"--get-url " +
"--get-id " +
"--get-thumbnail " +
"--get-duration " +
"--no-check-certificate " +
"-- \"{0}\"");
_ytdlSearchOperation =
new YtdlOperation("-4 " +
"--geo-bypass " +
"--encoding UTF8 " +
"-f bestaudio " +
"-e " +
"--get-url " +
"--get-id " +
"--get-thumbnail " +
"--get-duration " +
"--no-check-certificate " +
"--default-search " +
"\"ytsearch:\" -- \"{0}\"");
new("-4 " +
"--geo-bypass " +
"--encoding UTF8 " +
"-f bestaudio " +
"-e " +
"--get-url " +
"--get-id " +
"--get-thumbnail " +
"--get-duration " +
"--no-check-certificate " +
"--default-search " +
"\"ytsearch:\" -- \"{0}\"");
}
private readonly struct YtTrackData
@@ -114,7 +114,7 @@ public sealed class YtdlYoutubeResolver : IYoutubeResolver
? dataArray[3].Trim()
: string.Empty;
return new YtTrackData(
return new(
dataArray[0],
dataArray[1],
thumbnail,
@@ -190,7 +190,7 @@ public sealed class YtdlYoutubeResolver : IYoutubeResolver
return toReturn;
}
return DataToInfo(new YtTrackData(
return DataToInfo(new(
cachedData.Title,
cachedData.Id,
cachedData.Thumbnail,
@@ -337,7 +337,7 @@ public sealed class YtdlYoutubeResolver : IYoutubeResolver
return trackInfo;
}
return DataToInfo(new YtTrackData(
return DataToInfo(new(
cachedData.Title,
cachedData.Id,
cachedData.Thumbnail,

View File

@@ -110,7 +110,7 @@ public sealed partial class Music
mpl = uow.MusicPlaylists.GetWithSongs(id);
}
await ctx.SendPaginatedConfirmAsync(page, (cur) =>
await ctx.SendPaginatedConfirmAsync(page, cur =>
{
var i = 0;
var str = string.Join("\n", mpl.Songs
@@ -146,7 +146,7 @@ public sealed partial class Music
MusicPlaylist playlist;
using (var uow = _db.GetDbContext())
{
playlist = new MusicPlaylist
playlist = new()
{
Name = name,
Author = ctx.User.Username,

View File

@@ -180,7 +180,7 @@ public sealed class AyuVoiceStateService : INService
var current = _voiceProxies.AddOrUpdate(
guildId,
(gid) => new VoiceProxy(CreateVoiceGatewayLocal()),
gid => new VoiceProxy(CreateVoiceGatewayLocal()),
(gid, currentProxy) =>
{
_ = currentProxy.StopGateway();

View File

@@ -46,9 +46,9 @@ public sealed class MusicService : IMusicService
_ytLoader = ytLoader;
_eb = eb;
_players = new ConcurrentDictionary<ulong, IMusicPlayer>();
_players = new();
_outputChannels = new ConcurrentDictionary<ulong, (ITextChannel, ITextChannel?)>();
_settings = new ConcurrentDictionary<ulong, MusicPlayerSettings>();
_settings = new();
_client.LeftGuild += ClientOnLeftGuild;
}
@@ -149,7 +149,7 @@ public sealed class MusicService : IMusicService
var settings = await GetSettingsInternalAsync(guildId);
ITextChannel? overrideChannel = null;
if (settings.MusicChannelId is ulong channelId)
if (settings.MusicChannelId is { } channelId)
{
overrideChannel = _client.GetGuild(guildId)?.GetTextChannel(channelId);
@@ -170,7 +170,7 @@ public sealed class MusicService : IMusicService
mp.SetRepeat(settings.PlayerRepeat);
if (settings.Volume >= 0 && settings.Volume <= 100)
if (settings.Volume is >= 0 and <= 100)
{
mp.SetVolume(settings.Volume);
}
@@ -226,7 +226,7 @@ public sealed class MusicService : IMusicService
}
private Func<IMusicPlayer, Task> OnQueueStopped(ulong guildId)
=> (mp) =>
=> mp =>
{
if (_settings.TryGetValue(guildId, out var settings))
{

View File

@@ -9,7 +9,7 @@ public class Rule34Object : IImageData
public ImageData ToCachedImageData(Booru type)
{
return new ImageData(
return new(
$"https://img.rule34.xxx//images/{Directory}/{Image}",
Booru.Rule34,
Tags.Split(' '),

View File

@@ -22,7 +22,7 @@ public class NSFW : NadekoModule<ISearchImagesService>
public NSFW(IHttpClientFactory factory)
{
_httpFactory = factory;
_rng = new NadekoRandom();
_rng = new();
}
private async Task InternalBoobs()
@@ -85,7 +85,7 @@ public class NSFW : NadekoModule<ISearchImagesService>
if (interval < 20)
return;
t = new Timer(async (state) =>
t = new(async state =>
{
try
{
@@ -135,7 +135,7 @@ public class NSFW : NadekoModule<ISearchImagesService>
if (interval < 20)
return;
t = new Timer(async (state) =>
t = new(async state =>
{
try
{
@@ -175,7 +175,7 @@ public class NSFW : NadekoModule<ISearchImagesService>
if (interval < 20)
return;
t = new Timer(async (state) =>
t = new(async state =>
{
try
{

View File

@@ -12,7 +12,6 @@ namespace NadekoBot.Modules.Nsfw.Common;
public class SearchImageCacher : INService
{
private readonly IHttpClientFactory _httpFactory;
private readonly SemaphoreSlim _lock = new SemaphoreSlim(1, 1);
private readonly Random _rng;
private static readonly ISet<string> defaultTagBlacklist = new HashSet<string>()

View File

@@ -76,7 +76,7 @@ public class SearchImagesService : ISearchImagesService, INService
{
if (!tags.All(x => IsValidTag(x)))
{
return new UrlReply
return new()
{
Error = "One or more tags are invalid.",
Url = ""
@@ -106,7 +106,7 @@ public class SearchImagesService : ISearchImagesService, INService
if (result is null)
{
return new UrlReply
return new()
{
Error = "Image not found.",
Url = ""
@@ -129,7 +129,7 @@ public class SearchImagesService : ISearchImagesService, INService
catch (Exception ex)
{
Log.Error(ex, "Failed getting {Dapi} image: {Message}", dapi, ex.Message);
return new UrlReply
return new()
{
Error = ex.Message,
Url = ""
@@ -198,7 +198,7 @@ public class SearchImagesService : ISearchImagesService, INService
while (tasks.Count > 0); // keep looping as long as there is any task remaining to be attempted
// if we ran out of tasks, that means all tasks failed - return an error
return new UrlReply()
return new()
{
Error = "No hentai image found."
};
@@ -210,7 +210,7 @@ public class SearchImagesService : ISearchImagesService, INService
{
JToken obj;
obj = JArray.Parse(await _http.GetStringAsync($"http://api.oboobs.ru/boobs/{_rng.Next(0, 12000)}").ConfigureAwait(false))[0];
return new UrlReply
return new()
{
Error = "",
Url = $"http://media.oboobs.ru/{obj["preview"]}",
@@ -219,7 +219,7 @@ public class SearchImagesService : ISearchImagesService, INService
catch (Exception ex)
{
Log.Error(ex, "Error retreiving boob image: {Message}", ex.Message);
return new UrlReply
return new()
{
Error = ex.Message,
Url = "",
@@ -245,7 +245,7 @@ public class SearchImagesService : ISearchImagesService, INService
}
else
{
uow.NsfwBlacklistedTags.Add(new NsfwBlacklistedTag()
uow.NsfwBlacklistedTags.Add(new()
{
Tag = tag,
GuildId = guildId
@@ -278,7 +278,7 @@ public class SearchImagesService : ISearchImagesService, INService
{
JToken obj;
obj = JArray.Parse(await _http.GetStringAsync($"http://api.obutts.ru/butts/{_rng.Next(0, 6100)}"))[0];
return new UrlReply
return new()
{
Error = "",
Url = $"http://media.obutts.ru/{obj["preview"]}",
@@ -287,7 +287,7 @@ public class SearchImagesService : ISearchImagesService, INService
catch (Exception ex)
{
Log.Error(ex, "Error retreiving butt image: {Message}", ex.Message);
return new UrlReply
return new()
{
Error = ex.Message,
Url = "",
@@ -311,7 +311,7 @@ public class SearchImagesService : ISearchImagesService, INService
+ GetNhentaiExtensionInternal(model.Images.Thumbnail.T);
var url = $"https://nhentai.net/g/{model.Id}";
return new Gallery(
return new(
model.Id.ToString(),
url,
model.Title.English,

View File

@@ -247,7 +247,7 @@ public partial class Permissions
removed = config.FilteredWords.FirstOrDefault(fw => fw.Word.Trim().ToLowerInvariant() == word);
if (removed is null)
config.FilteredWords.Add(new FilteredWord() { Word = word });
config.FilteredWords.Add(new() { Word = word });
else
{
uow.Remove(removed);
@@ -285,7 +285,7 @@ public partial class Permissions
var fws = fwHash.ToArray();
await ctx.SendPaginatedConfirmAsync(page,
(curPage) => _eb.Create()
curPage => _eb.Create()
.WithTitle(GetText(strs.filter_word_list))
.WithDescription(string.Join("\n", fws.Skip(curPage * 10).Take(10)))
.WithOkColor()

View File

@@ -29,7 +29,7 @@ public partial class Permissions : NadekoModule<PermissionService>
using (var uow = _db.GetDbContext())
{
var config = uow.GcWithPermissionsv2For(ctx.Guild.Id);
if (action is null) action = new PermissionAction(!config.VerbosePermissions); // New behaviour, can toggle.
if (action is null) action = new(!config.VerbosePermissions); // New behaviour, can toggle.
config.VerbosePermissions = action.Value;
await uow.SaveChangesAsync();
_service.UpdateCache(config);

View File

@@ -18,7 +18,7 @@ public class CmdCdService : ILateBlocker, INService
public CmdCdService(Bot bot)
{
CommandCooldowns = new ConcurrentDictionary<ulong, ConcurrentHashSet<CommandCooldown>>(
CommandCooldowns = new(
bot.AllGuildConfigs.ToDictionary(k => k.GuildId,
v => new ConcurrentHashSet<CommandCooldown>(v.CommandCooldowns)));
}
@@ -38,7 +38,7 @@ public class CmdCdService : ILateBlocker, INService
return Task.FromResult(true);
}
activeCdsForGuild.Add(new ActiveCooldown()
activeCdsForGuild.Add(new()
{
UserId = user.Id,
Command = commandName,

View File

@@ -87,19 +87,19 @@ public sealed class FilterService : IEarlyBehavior
.Where(gc => ids.Contains(gc.GuildId))
.ToList();
InviteFilteringServers = new ConcurrentHashSet<ulong>(configs.Where(gc => gc.FilterInvites).Select(gc => gc.GuildId));
InviteFilteringChannels = new ConcurrentHashSet<ulong>(configs.SelectMany(gc => gc.FilterInvitesChannelIds.Select(fci => fci.ChannelId)));
InviteFilteringServers = new(configs.Where(gc => gc.FilterInvites).Select(gc => gc.GuildId));
InviteFilteringChannels = new(configs.SelectMany(gc => gc.FilterInvitesChannelIds.Select(fci => fci.ChannelId)));
LinkFilteringServers = new ConcurrentHashSet<ulong>(configs.Where(gc => gc.FilterLinks).Select(gc => gc.GuildId));
LinkFilteringChannels = new ConcurrentHashSet<ulong>(configs.SelectMany(gc => gc.FilterLinksChannelIds.Select(fci => fci.ChannelId)));
LinkFilteringServers = new(configs.Where(gc => gc.FilterLinks).Select(gc => gc.GuildId));
LinkFilteringChannels = new(configs.SelectMany(gc => gc.FilterLinksChannelIds.Select(fci => fci.ChannelId)));
var dict = configs.ToDictionary(gc => gc.GuildId, gc => new ConcurrentHashSet<string>(gc.FilteredWords.Select(fw => fw.Word)));
ServerFilteredWords = new ConcurrentDictionary<ulong, ConcurrentHashSet<string>>(dict);
ServerFilteredWords = new(dict);
var serverFiltering = configs.Where(gc => gc.FilterWords);
WordFilteringServers = new ConcurrentHashSet<ulong>(serverFiltering.Select(gc => gc.GuildId));
WordFilteringChannels = new ConcurrentHashSet<ulong>(configs.SelectMany(gc => gc.FilterWordsChannelIds.Select(fwci => fwci.ChannelId)));
WordFilteringServers = new(serverFiltering.Select(gc => gc.GuildId));
WordFilteringChannels = new(configs.SelectMany(gc => gc.FilterWordsChannelIds.Select(fwci => fwci.ChannelId)));
}
client.MessageUpdated += (oldData, newMsg, channel) =>

View File

@@ -42,11 +42,11 @@ public class PermissionService : ILateBlocker, INService
foreach (var x in uow.GuildConfigs.Permissionsv2ForAll(client.Guilds.ToArray().Select(x => x.Id)
.ToList()))
{
Cache.TryAdd(x.GuildId, new PermissionCache()
Cache.TryAdd(x.GuildId, new()
{
Verbose = x.VerbosePermissions,
PermRole = x.PermissionRole,
Permissions = new PermissionsCollection<Permissionv2>(x.Permissions)
Permissions = new(x.Permissions)
});
}
}
@@ -64,7 +64,7 @@ public class PermissionService : ILateBlocker, INService
}
Cache.TryGetValue(guildId, out pc);
if (pc is null)
throw new Exception("Cache is null.");
throw new("Cache is null.");
}
return pc;
}
@@ -90,12 +90,12 @@ public class PermissionService : ILateBlocker, INService
{
Cache.AddOrUpdate(config.GuildId, new PermissionCache()
{
Permissions = new PermissionsCollection<Permissionv2>(config.Permissions),
Permissions = new(config.Permissions),
PermRole = config.PermissionRole,
Verbose = config.VerbosePermissions
}, (id, old) =>
{
old.Permissions = new PermissionsCollection<Permissionv2>(config.Permissions);
old.Permissions = new(config.Permissions);
old.PermRole = config.PermissionRole;
old.Verbose = config.VerbosePermissions;
return old;

View File

@@ -21,14 +21,14 @@ public class ImageCacherObject : IComparable<ImageCacherObject>
}
this.SearchType = type;
this.Rating = obj.Rating;
this.Tags = new HashSet<string>((obj.Tags ?? obj.TagString).Split(' '));
this.Tags = new((obj.Tags ?? obj.TagString).Split(' '));
}
public ImageCacherObject(string url, Booru type, string tags, string rating)
{
this.SearchType = type;
this.FileUrl = url;
this.Tags = new HashSet<string>(tags.Split(' '));
this.Tags = new(tags.Split(' '));
this.Rating = rating;
}

View File

@@ -24,12 +24,12 @@ public class NotifChecker
{
_multi = multi;
_key = $"{uniqueCacheKey}_followed_streams_data";
_streamProviders = new Dictionary<FollowedStream.FType, Provider>()
_streamProviders = new()
{
{FollowedStream.FType.Twitch, new TwitchProvider(httpClientFactory)},
{FollowedStream.FType.Picarto, new PicartoProvider(httpClientFactory)}
};
_offlineBuffer = new HashSet<(FollowedStream.FType, string)>();
_offlineBuffer = new();
if (isMaster)
{
CacheClearAllData();
@@ -181,7 +181,7 @@ public class NotifChecker
var db = _multi.GetDatabase();
if (!db.KeyExists(_key))
{
return new Dictionary<StreamDataKey, StreamData?>();
return new();
}
return db.HashGetAll(_key)

View File

@@ -54,7 +54,7 @@ public class PicartoProvider : Provider
public async override Task<List<StreamData>> GetStreamDataAsync(List<string> logins)
{
if (logins.Count == 0)
return new List<StreamData>();
return new();
using (var http = _httpClientFactory.CreateClient())
{
@@ -63,7 +63,7 @@ public class PicartoProvider : Provider
{
try
{
http.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
http.DefaultRequestHeaders.Accept.Add(new("application/json"));
// get id based on the username
var res = await http.GetAsync($"https://api.picarto.tv/v1/channel/name/{login}");
@@ -88,7 +88,7 @@ public class PicartoProvider : Provider
private StreamData ToStreamData(PicartoChannelResponse stream)
{
return new StreamData()
return new()
{
StreamType = FollowedStream.FType.Picarto,
Name = stream.Name,

View File

@@ -53,7 +53,7 @@ public class TwitchProvider : Provider
public override async Task<List<StreamData>> GetStreamDataAsync(List<string> logins)
{
if (logins.Count == 0)
return new List<StreamData>();
return new();
using (var http = _httpClientFactory.CreateClient())
{
@@ -86,7 +86,7 @@ public class TwitchProvider : Provider
var chStr = await http.GetStringAsync($"https://api.twitch.tv/kraken/channels/{user.Id}");
var ch = JsonConvert.DeserializeObject<TwitchResponseV5.Channel>(chStr)!;
toReturn.Add(new StreamData
toReturn.Add(new()
{
StreamType = FollowedStream.FType.Twitch,
Name = ch.DisplayName,
@@ -116,7 +116,7 @@ public class TwitchProvider : Provider
private StreamData ToStreamData(TwitchResponseV5.Stream stream)
{
return new StreamData()
return new()
{
StreamType = FollowedStream.FType.Twitch,
Name = stream.Channel.DisplayName,

View File

@@ -95,7 +95,7 @@ public partial class Searches
return;
}
await ctx.SendPaginatedConfirmAsync(0, (cur) =>
await ctx.SendPaginatedConfirmAsync(0, cur =>
{
var embed = _eb.Create()
.WithOkColor();

View File

@@ -67,7 +67,7 @@ public partial class Searches
characters.RemoveAll(c => c.League != league);
}
await ctx.SendPaginatedConfirmAsync(page, (curPage) =>
await ctx.SendPaginatedConfirmAsync(page, curPage =>
{
var embed = _eb.Create()
.WithAuthor($"Characters on {usr}'s account",

View File

@@ -461,7 +461,7 @@ public partial class Searches : NadekoModule<SearchesService>
if (items.Any())
{
await ctx.SendPaginatedConfirmAsync(0, (p) =>
await ctx.SendPaginatedConfirmAsync(0, p =>
{
var item = items[p];
return _eb.Create().WithOkColor()

View File

@@ -45,7 +45,7 @@ public class SearchesService : INService
_cache = cache;
_fonts = fonts;
_creds = creds;
_rng = new NadekoRandom();
_rng = new();
//joke commands
if (File.Exists("data/wowjokes.json"))
@@ -70,7 +70,7 @@ public class SearchesService : INService
}
else
{
_yomamaJokes = new List<string>();
_yomamaJokes = new();
Log.Warning("data/yomama.txt is missing. .yomama command won't work");
}
}
@@ -86,7 +86,7 @@ public class SearchesService : INService
}
private void DrawAvatar(Image bg, Image avatarImage)
=> bg.Mutate(x => x.Grayscale().DrawImage(avatarImage, new Point(83, 139), new GraphicsOptions()));
=> bg.Mutate(x => x.Grayscale().DrawImage(avatarImage, new(83, 139), new GraphicsOptions()));
public async Task<byte[]> GetRipPictureFactory((string text, Uri avatarUrl) arg)
{
@@ -119,7 +119,7 @@ public class SearchesService : INService
}
bg.Mutate(x => x.DrawText(
new TextGraphicsOptions()
new()
{
TextOptions = new TextOptions
{
@@ -130,12 +130,12 @@ public class SearchesService : INService
text,
_fonts.RipFont,
SixLabors.ImageSharp.Color.Black,
new PointF(25, 225)));
new(25, 225)));
//flowa
using (var flowers = Image.Load(_imgs.RipOverlay.ToArray()))
{
bg.Mutate(x => x.DrawImage(flowers, new Point(0, 0), new GraphicsOptions()));
bg.Mutate(x => x.DrawImage(flowers, new(0, 0), new GraphicsOptions()));
}
return bg.ToStream().ToArray();
@@ -362,7 +362,7 @@ public class SearchesService : INService
}
catch { storeUrl = "<url can't be found>"; }
return new MtgData
return new()
{
Description = card.Text,
Name = card.Name,
@@ -573,7 +573,7 @@ public class SearchesService : INService
}
}
private static readonly HtmlParser _googleParser = new HtmlParser(new HtmlParserOptions()
private static readonly HtmlParser _googleParser = new HtmlParser(new()
{
IsScripting = false,
IsEmbedded = false,
@@ -630,7 +630,7 @@ public class SearchesService : INService
.Where(x => x != null)
.ToList();
return new GoogleSearchResultData(
return new(
results.AsReadOnly(),
fullQueryLink,
totalResults);
@@ -681,7 +681,7 @@ public class SearchesService : INService
.Where(x => x != null)
.ToList();
return new GoogleSearchResultData(
return new(
results.AsReadOnly(),
fullQueryLink,
"0");

View File

@@ -61,7 +61,7 @@ public sealed class StreamNotificationService : INService
_creds = creds;
_pubSub = pubSub;
_eb = eb;
_streamTracker = new NotifChecker(httpFactory, redis, creds.RedisKey(), client.ShardId == 0);
_streamTracker = new(httpFactory, redis, creds.RedisKey(), client.ShardId == 0);
_streamsOnlineKey = new("streams.online");
_streamsOfflineKey = new("streams.offline");
@@ -78,7 +78,7 @@ public sealed class StreamNotificationService : INService
.Where(x => ids.Contains(x.GuildId))
.ToList();
_offlineNotificationServers = new ConcurrentHashSet<ulong>(guildConfigs
_offlineNotificationServers = new(guildConfigs
.Where(gc => gc.NotifyStreamOffline)
.Select(x => x.GuildId)
.ToList());
@@ -125,7 +125,7 @@ public sealed class StreamNotificationService : INService
_streamTracker.OnStreamsOffline += OnStreamsOffline;
_streamTracker.OnStreamsOnline += OnStreamsOnline;
_ = _streamTracker.RunAsync();
_notifCleanupTimer = new Timer(_ =>
_notifCleanupTimer = new(_ =>
{
try
{
@@ -155,7 +155,7 @@ public sealed class StreamNotificationService : INService
uow.SaveChanges();
foreach(var loginToDelete in kvp.Value)
_streamTracker.UntrackStreamByKey(new StreamDataKey(kvp.Key, loginToDelete));
_streamTracker.UntrackStreamByKey(new(kvp.Key, loginToDelete));
}
}
}
@@ -191,7 +191,7 @@ public sealed class StreamNotificationService : INService
}
else
{
_trackCounter[key] = new HashSet<ulong>()
_trackCounter[key] = new()
{
info.GuildId
};
@@ -405,7 +405,7 @@ public sealed class StreamNotificationService : INService
var gc = uow.GuildConfigsForId(guildId, set => set.Include(x => x.FollowedStreams));
// add it to the database
fs = new FollowedStream()
fs = new()
{
Type = data.StreamType,
Username = data.UniqueName,
@@ -504,14 +504,14 @@ public sealed class StreamNotificationService : INService
}
else
{
return map[guildId] = new HashSet<FollowedStream>();
return map[guildId] = new();
}
}
else
{
_shardTrackedStreams[key] = new Dictionary<ulong, HashSet<FollowedStream>>()
_shardTrackedStreams[key] = new()
{
{guildId, new HashSet<FollowedStream>()}
{guildId, new()}
};
return _shardTrackedStreams[key][guildId];
}

View File

@@ -56,7 +56,7 @@ public sealed class TranslateService : ITranslateService, ILateExecutor, IReadyE
if (string.IsNullOrWhiteSpace(msg.Content))
return;
if (msg is IUserMessage { Channel: ITextChannel tch } um)
if (msg is { Channel: ITextChannel tch } um)
{
if (!_atcs.TryGetValue(tch.Id, out var autoDelete))
return;

View File

@@ -106,7 +106,7 @@ public partial class Searches
}
}
await ctx.SendPaginatedConfirmAsync(page, (cur) =>
await ctx.SendPaginatedConfirmAsync(page, cur =>
{
var elements = streams.Skip(cur * 12).Take(12)
.ToList();

View File

@@ -74,19 +74,19 @@ public partial class Utility
await ReplyConfirmLocalizedAsync(strs.alias_removed(Format.Code(trigger))).ConfigureAwait(false);
return;
}
_service.AliasMaps.AddOrUpdate(ctx.Guild.Id, (_) =>
_service.AliasMaps.AddOrUpdate(ctx.Guild.Id, _ =>
{
using (var uow = _db.GetDbContext())
{
var config = uow.GuildConfigsForId(ctx.Guild.Id, set => set.Include(x => x.CommandAliases));
config.CommandAliases.Add(new CommandAlias()
config.CommandAliases.Add(new()
{
Mapping = mapping,
Trigger = trigger
});
uow.SaveChanges();
}
return new ConcurrentDictionary<string, string>(new Dictionary<string, string>() {
return new(new Dictionary<string, string>() {
{trigger.Trim().ToLowerInvariant(), mapping.ToLowerInvariant() },
});
}, (_, map) =>
@@ -131,7 +131,7 @@ public partial class Utility
var arr = maps.ToArray();
await ctx.SendPaginatedConfirmAsync(page, (curPage) =>
await ctx.SendPaginatedConfirmAsync(page, curPage =>
{
return _eb.Create().WithOkColor()
.WithTitle(GetText(strs.alias_list))

View File

@@ -42,7 +42,7 @@ public partial class Utility
var invites = await channel.GetInvitesAsync().ConfigureAwait(false);
await ctx.SendPaginatedConfirmAsync(page, (cur) =>
await ctx.SendPaginatedConfirmAsync(page, cur =>
{
var i = 1;
var invs = invites

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