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

@@ -44,14 +44,14 @@ public sealed class Bot
_credsProvider = new BotCredsProvider(totalShards); _credsProvider = new BotCredsProvider(totalShards);
_creds = _credsProvider.GetCreds(); _creds = _credsProvider.GetCreds();
_db = new DbService(_creds); _db = new(_creds);
if (shardId == 0) if (shardId == 0)
{ {
_db.Setup(); _db.Setup();
} }
Client = new DiscordSocketClient(new DiscordSocketConfig Client = new(new()
{ {
MessageCacheSize = 50, MessageCacheSize = 50,
LogLevel = LogSeverity.Warning, LogLevel = LogSeverity.Warning,
@@ -62,7 +62,7 @@ public sealed class Bot
ExclusiveBulkDelete = true, ExclusiveBulkDelete = true,
}); });
_commandService = new CommandService(new CommandServiceConfig() _commandService = new(new()
{ {
CaseSensitiveCommands = false, CaseSensitiveCommands = false,
DefaultRunMode = RunMode.Sync, DefaultRunMode = RunMode.Sync,

View File

@@ -12,12 +12,12 @@ public class UserPermAttribute : PreconditionAttribute
public UserPermAttribute(GuildPerm permission) public UserPermAttribute(GuildPerm permission)
{ {
UserPermissionAttribute = new RequireUserPermissionAttribute((GuildPermission)permission); UserPermissionAttribute = new((GuildPermission)permission);
} }
public UserPermAttribute(ChannelPerm permission) public UserPermAttribute(ChannelPerm permission)
{ {
UserPermissionAttribute = new RequireUserPermissionAttribute((ChannelPermission)permission); UserPermissionAttribute = new((ChannelPermission)permission);
} }
public override Task<PreconditionResult> CheckPermissionsAsync(ICommandContext context, CommandInfo command, IServiceProvider services) public override Task<PreconditionResult> CheckPermissionsAsync(ICommandContext context, CommandInfo command, IServiceProvider services)

View File

@@ -245,12 +245,12 @@ public sealed class ConcurrentHashSet<T> : IReadOnlyCollection<T>, ICollection<T
var locks = new object[concurrencyLevel]; var locks = new object[concurrencyLevel];
for (var i = 0; i < locks.Length; i++) for (var i = 0; i < locks.Length; i++)
{ {
locks[i] = new object(); locks[i] = new();
} }
var countPerLock = new int[locks.Length]; var countPerLock = new int[locks.Length];
var buckets = new Node[capacity]; var buckets = new Node[capacity];
_tables = new Tables(buckets, locks, countPerLock); _tables = new(buckets, locks, countPerLock);
_growLockArray = growLockArray; _growLockArray = growLockArray;
_budget = buckets.Length / locks.Length; _budget = buckets.Length / locks.Length;
@@ -480,7 +480,7 @@ public sealed class ConcurrentHashSet<T> : IReadOnlyCollection<T>, ICollection<T
} }
// The item was not found in the bucket. Insert the new item. // The item was not found in the bucket. Insert the new item.
Volatile.Write(ref tables.Buckets[bucketNo], new Node(item, hashcode, tables.Buckets[bucketNo])); Volatile.Write(ref tables.Buckets[bucketNo], new(item, hashcode, tables.Buckets[bucketNo]));
checked checked
{ {
tables.CountPerLock[lockNo]++; tables.CountPerLock[lockNo]++;
@@ -628,7 +628,7 @@ public sealed class ConcurrentHashSet<T> : IReadOnlyCollection<T>, ICollection<T
Array.Copy(tables.Locks, 0, newLocks, 0, tables.Locks.Length); Array.Copy(tables.Locks, 0, newLocks, 0, tables.Locks.Length);
for (var i = tables.Locks.Length; i < newLocks.Length; i++) for (var i = tables.Locks.Length; i < newLocks.Length; i++)
{ {
newLocks[i] = new object(); newLocks[i] = new();
} }
} }
@@ -644,7 +644,7 @@ public sealed class ConcurrentHashSet<T> : IReadOnlyCollection<T>, ICollection<T
var next = current.Next; var next = current.Next;
GetBucketAndLockNo(current.Hashcode, out var newBucketNo, out var newLockNo, newBuckets.Length, newLocks.Length); GetBucketAndLockNo(current.Hashcode, out var newBucketNo, out var newLockNo, newBuckets.Length, newLocks.Length);
newBuckets[newBucketNo] = new Node(current.Item, current.Hashcode, newBuckets[newBucketNo]); newBuckets[newBucketNo] = new(current.Item, current.Hashcode, newBuckets[newBucketNo]);
checked checked
{ {
@@ -659,7 +659,7 @@ public sealed class ConcurrentHashSet<T> : IReadOnlyCollection<T>, ICollection<T
_budget = Math.Max(1, newBuckets.Length / newLocks.Length); _budget = Math.Max(1, newBuckets.Length / newLocks.Length);
// Replace tables with the new versions // Replace tables with the new versions
_tables = new Tables(newBuckets, newLocks, newCountPerLock); _tables = new(newBuckets, newLocks, newCountPerLock);
} }
finally finally
{ {

View File

@@ -14,7 +14,7 @@ public class IndexedCollection<T> : IList<T> where T : class, IIndexed
public IndexedCollection() public IndexedCollection()
{ {
Source = new List<T>(); Source = new();
} }
public IndexedCollection(IEnumerable<T> source) public IndexedCollection(IEnumerable<T> source)

View File

@@ -95,7 +95,7 @@ See RotatingStatuses submodule in Administration.")]
{ {
var color = new ColorConfig(); var color = new ColorConfig();
Color = color; Color = color;
DefaultLocale = new CultureInfo("en-US"); DefaultLocale = new("en-US");
ConsoleOutputType = ConsoleOutputType.Normal; ConsoleOutputType = ConsoleOutputType.Normal;
ForwardMessages = false; ForwardMessages = false;
ForwardToAllOwners = false; ForwardToAllOwners = false;
@@ -130,7 +130,7 @@ See RotatingStatuses submodule in Administration.")]
Prefix = "."; Prefix = ".";
RotateStatuses = false; RotateStatuses = false;
GroupGreets = false; GroupGreets = false;
DmHelpTextKeywords = new List<string>() DmHelpTextKeywords = new()
{ {
"help", "help",
"commands", "commands",
@@ -149,8 +149,8 @@ public sealed partial class BlockedConfig
public BlockedConfig() public BlockedConfig()
{ {
Modules = new HashSet<string>(); Modules = new();
Commands = new HashSet<string>(); Commands = new();
} }
} }

View File

@@ -22,7 +22,7 @@ public class CultureInfoConverter : JsonConverter<CultureInfo>
{ {
public override CultureInfo Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) public override CultureInfo Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{ {
return new CultureInfo(reader.GetString()); return new(reader.GetString());
} }
public override void Write(Utf8JsonWriter writer, CultureInfo value, JsonSerializerOptions options) public override void Write(Utf8JsonWriter writer, CultureInfo value, JsonSerializerOptions options)

View File

@@ -44,7 +44,7 @@ public readonly struct kwum : IEquatable<kwum>
if (!IsValidChar(c)) if (!IsValidChar(c))
return false; return false;
value = new kwum(input); value = new(input);
return true; return true;
} }
@@ -80,7 +80,7 @@ public readonly struct kwum : IEquatable<kwum>
chars[--arrSize] = ValidCharacters[(int)rem]; chars[--arrSize] = ValidCharacters[(int)rem];
} }
return new string(chars); return new(chars);
} }
public override bool Equals(object obj) public override bool Equals(object obj)

View File

@@ -16,14 +16,14 @@ public class EventPubSub : IPubSub
Dictionary<Delegate, List<Func<object, ValueTask>>> keyActions; Dictionary<Delegate, List<Func<object, ValueTask>>> keyActions;
if (!_actions.TryGetValue(key.Key, out keyActions)) if (!_actions.TryGetValue(key.Key, out keyActions))
{ {
keyActions = new Dictionary<Delegate, List<Func<object, ValueTask>>>(); keyActions = new();
_actions[key.Key] = keyActions; _actions[key.Key] = keyActions;
} }
List<Func<object, ValueTask>> sameActions; List<Func<object, ValueTask>> sameActions;
if (!keyActions.TryGetValue(action, out sameActions)) if (!keyActions.TryGetValue(action, out sameActions))
{ {
sameActions = new List<Func<object, ValueTask>>(); sameActions = new();
keyActions[action] = sameActions; keyActions[action] = sameActions;
} }

View File

@@ -66,7 +66,7 @@ public class ReplacementBuilder
/*OBSOLETE*/ /*OBSOLETE*/
_reps.TryAdd("%sid%", () => g is null ? "DM" : g.Id.ToString()); _reps.TryAdd("%sid%", () => g is null ? "DM" : g.Id.ToString());
_reps.TryAdd("%server%", () => g is null ? "DM" : g.Name); _reps.TryAdd("%server%", () => g is null ? "DM" : g.Name);
_reps.TryAdd("%members%", () => g != null && g is SocketGuild sg ? sg.MemberCount.ToString() : "?"); _reps.TryAdd("%members%", () => g is { } sg ? sg.MemberCount.ToString() : "?");
_reps.TryAdd("%server_time%", () => _reps.TryAdd("%server_time%", () =>
{ {
var to = TimeZoneInfo.Local; var to = TimeZoneInfo.Local;
@@ -83,7 +83,7 @@ public class ReplacementBuilder
/*NEW*/ /*NEW*/
_reps.TryAdd("%server.id%", () => g is null ? "DM" : g.Id.ToString()); _reps.TryAdd("%server.id%", () => g is null ? "DM" : g.Id.ToString());
_reps.TryAdd("%server.name%", () => g is null ? "DM" : g.Name); _reps.TryAdd("%server.name%", () => g is null ? "DM" : g.Name);
_reps.TryAdd("%server.members%", () => g != null && g is SocketGuild sg ? sg.MemberCount.ToString() : "?"); _reps.TryAdd("%server.members%", () => g is { } sg ? sg.MemberCount.ToString() : "?");
_reps.TryAdd("%server.boosters%", () => g.PremiumSubscriptionCount.ToString()); _reps.TryAdd("%server.boosters%", () => g.PremiumSubscriptionCount.ToString());
_reps.TryAdd("%server.boost_level%", () => ((int)g.PremiumTier).ToString()); _reps.TryAdd("%server.boost_level%", () => ((int)g.PremiumTier).ToString());
_reps.TryAdd("%server.time%", () => _reps.TryAdd("%server.time%", () =>
@@ -120,25 +120,6 @@ public class ReplacementBuilder
public ReplacementBuilder WithUser(IUser user) public ReplacementBuilder WithUser(IUser user)
{ {
// /*OBSOLETE*/
// _reps.TryAdd("%user%", () => user.Mention);
// _reps.TryAdd("%userfull%", () => user.ToString());
// _reps.TryAdd("%username%", () => user.Username);
// _reps.TryAdd("%userdiscrim%", () => user.Discriminator);
// _reps.TryAdd("%useravatar%", () => user.RealAvatarUrl()?.ToString());
// _reps.TryAdd("%id%", () => user.Id.ToString());
// _reps.TryAdd("%uid%", () => user.Id.ToString());
// /*NEW*/
// _reps.TryAdd("%user.mention%", () => user.Mention);
// _reps.TryAdd("%user.fullname%", () => user.ToString());
// _reps.TryAdd("%user.name%", () => user.Username);
// _reps.TryAdd("%user.discrim%", () => user.Discriminator);
// _reps.TryAdd("%user.avatar%", () => user.RealAvatarUrl()?.ToString());
// _reps.TryAdd("%user.id%", () => user.Id.ToString());
// _reps.TryAdd("%user.created_time%", () => user.CreatedAt.ToString("HH:mm"));
// _reps.TryAdd("%user.created_date%", () => user.CreatedAt.ToString("dd.MM.yyyy"));
// _reps.TryAdd("%user.joined_time%", () => (user as IGuildUser)?.JoinedAt?.ToString("HH:mm") ?? "-");
// _reps.TryAdd("%user.joined_date%", () => (user as IGuildUser)?.JoinedAt?.ToString("dd.MM.yyyy") ?? "-");
WithManyUsers(new[] {user}); WithManyUsers(new[] {user});
return this; return this;
} }
@@ -171,15 +152,11 @@ public class ReplacementBuilder
{ {
/*OBSOLETE*/ /*OBSOLETE*/
_reps.TryAdd("%servers%", () => c.Guilds.Count.ToString()); _reps.TryAdd("%servers%", () => c.Guilds.Count.ToString());
#if !GLOBAL_NADEKO
_reps.TryAdd("%users%", () => c.Guilds.Sum(g => g.MemberCount).ToString()); _reps.TryAdd("%users%", () => c.Guilds.Sum(g => g.MemberCount).ToString());
#endif
/*NEW*/ /*NEW*/
_reps.TryAdd("%shard.servercount%", () => c.Guilds.Count.ToString()); _reps.TryAdd("%shard.servercount%", () => c.Guilds.Count.ToString());S
#if !GLOBAL_NADEKO
_reps.TryAdd("%shard.usercount%", () => c.Guilds.Sum(g => g.MemberCount).ToString()); _reps.TryAdd("%shard.usercount%", () => c.Guilds.Sum(g => g.MemberCount).ToString());
#endif
_reps.TryAdd("%shard.id%", () => c.ShardId.ToString()); _reps.TryAdd("%shard.id%", () => c.ShardId.ToString());
return this; return this;
} }
@@ -187,7 +164,7 @@ public class ReplacementBuilder
public ReplacementBuilder WithRngRegex() public ReplacementBuilder WithRngRegex()
{ {
var rng = new NadekoRandom(); var rng = new NadekoRandom();
_regex.TryAdd(rngRegex, (match) => _regex.TryAdd(rngRegex, match =>
{ {
if (!int.TryParse(match.Groups["from"].ToString(), out var from)) if (!int.TryParse(match.Groups["from"].ToString(), out var from))
from = 0; from = 0;
@@ -213,7 +190,7 @@ public class ReplacementBuilder
public Replacer Build() public Replacer Build()
{ {
return new Replacer(_reps.Select(x => (x.Key, x.Value)).ToArray(), _regex.Select(x => (x.Key, x.Value)).ToArray()); return new(_reps.Select(x => (x.Key, x.Value)).ToArray(), _regex.Select(x => (x.Key, x.Value)).ToArray());
} }
public ReplacementBuilder WithProviders(IEnumerable<IPlaceholderProvider> phProviders) public ReplacementBuilder WithProviders(IEnumerable<IPlaceholderProvider> phProviders)

View File

@@ -26,7 +26,7 @@ public class Replacer
foreach (var item in _regex) foreach (var item in _regex)
{ {
input = item.Regex.Replace(input, (m) => item.Replacement(m)); input = item.Regex.Replace(input, m => item.Replacement(m));
} }
return input; return input;
@@ -45,18 +45,22 @@ public class Replacer
public SmartEmbedText Replace(SmartEmbedText embedData) public SmartEmbedText Replace(SmartEmbedText embedData)
{ {
var newEmbedData = new SmartEmbedText(); var newEmbedData = new SmartEmbedText
newEmbedData.PlainText = Replace(embedData.PlainText); {
newEmbedData.Description = Replace(embedData.Description); PlainText = Replace(embedData.PlainText),
newEmbedData.Title = Replace(embedData.Title); Description = Replace(embedData.Description),
newEmbedData.Thumbnail = Replace(embedData.Thumbnail); Title = Replace(embedData.Title),
newEmbedData.Image = Replace(embedData.Image); Thumbnail = Replace(embedData.Thumbnail),
newEmbedData.Url = Replace(embedData.Url); Image = Replace(embedData.Image),
Url = Replace(embedData.Url)
};
if (embedData.Author != null) if (embedData.Author != null)
{ {
newEmbedData.Author = new SmartTextEmbedAuthor(); newEmbedData.Author = new()
newEmbedData.Author.Name = Replace(embedData.Author.Name); {
newEmbedData.Author.IconUrl = Replace(embedData.Author.IconUrl); Name = Replace(embedData.Author.Name),
IconUrl = Replace(embedData.Author.IconUrl)
};
} }
if (embedData.Fields != null) if (embedData.Fields != null)
@@ -64,10 +68,12 @@ public class Replacer
var fields = new List<SmartTextEmbedField>(); var fields = new List<SmartTextEmbedField>();
foreach (var f in embedData.Fields) foreach (var f in embedData.Fields)
{ {
var newF = new SmartTextEmbedField(); var newF = new SmartTextEmbedField
newF.Name = Replace(f.Name); {
newF.Value = Replace(f.Value); Name = Replace(f.Name),
newF.Inline = f.Inline; Value = Replace(f.Value),
Inline = f.Inline
};
fields.Add(newF); fields.Add(newF);
} }
@@ -76,9 +82,11 @@ public class Replacer
if (embedData.Footer != null) if (embedData.Footer != null)
{ {
newEmbedData.Footer = new SmartTextEmbedFooter(); newEmbedData.Footer = new()
newEmbedData.Footer.Text = Replace(embedData.Footer.Text); {
newEmbedData.Footer.IconUrl = Replace(embedData.Footer.IconUrl); Text = Replace(embedData.Footer.Text),
IconUrl = Replace(embedData.Footer.IconUrl)
};
} }
newEmbedData.Color = embedData.Color; newEmbedData.Color = embedData.Color;

View File

@@ -13,7 +13,7 @@ public struct ShmartNumber : IEquatable<ShmartNumber>
public static implicit operator ShmartNumber(long num) public static implicit operator ShmartNumber(long num)
{ {
return new ShmartNumber(num); return new(num);
} }
public static implicit operator long(ShmartNumber num) public static implicit operator long(ShmartNumber num)
@@ -23,7 +23,7 @@ public struct ShmartNumber : IEquatable<ShmartNumber>
public static implicit operator ShmartNumber(int num) public static implicit operator ShmartNumber(int num)
{ {
return new ShmartNumber(num); return new(num);
} }
public override string ToString() public override string ToString()

View File

@@ -25,33 +25,34 @@ public sealed record SmartEmbedText : SmartText
!string.IsNullOrWhiteSpace(Thumbnail) || !string.IsNullOrWhiteSpace(Thumbnail) ||
!string.IsNullOrWhiteSpace(Image) || !string.IsNullOrWhiteSpace(Image) ||
(Footer != null && (!string.IsNullOrWhiteSpace(Footer.Text) || !string.IsNullOrWhiteSpace(Footer.IconUrl))) || (Footer != null && (!string.IsNullOrWhiteSpace(Footer.Text) || !string.IsNullOrWhiteSpace(Footer.IconUrl))) ||
(Fields != null && Fields.Length > 0); Fields is { Length: > 0 };
public static SmartEmbedText FromEmbed(IEmbed eb, string plainText = null) public static SmartEmbedText FromEmbed(IEmbed eb, string plainText = null)
{ {
var set = new SmartEmbedText(); var set = new SmartEmbedText
{
set.PlainText = plainText; PlainText = plainText,
set.Title = eb.Title; Title = eb.Title,
set.Description = eb.Description; Description = eb.Description,
set.Url = eb.Url; Url = eb.Url,
set.Thumbnail = eb.Thumbnail?.Url; Thumbnail = eb.Thumbnail?.Url,
set.Image = eb.Image?.Url; Image = eb.Image?.Url,
set.Author = eb.Author is EmbedAuthor ea Author = eb.Author is { } ea
? new() ? new()
{ {
Name = ea.Name, Name = ea.Name,
Url = ea.Url, Url = ea.Url,
IconUrl = ea.IconUrl IconUrl = ea.IconUrl
} }
: null; : null,
set.Footer = eb.Footer is EmbedFooter ef Footer = eb.Footer is { } ef
? new() ? new()
{ {
Text = ef.Text, Text = ef.Text,
IconUrl = ef.IconUrl IconUrl = ef.IconUrl
} }
: null; : null
};
if (eb.Fields.Length > 0) if (eb.Fields.Length > 0)
set.Fields = eb set.Fields = eb
@@ -122,7 +123,7 @@ public sealed record SmartEmbedText : SmartText
public void NormalizeFields() public void NormalizeFields()
{ {
if (Fields != null && Fields.Length > 0) if (Fields is { Length: > 0 })
{ {
foreach (var f in Fields) foreach (var f in Fields)
{ {

View File

@@ -53,7 +53,7 @@ public class StoopidTime
throw new ArgumentException("Time is too long."); throw new ArgumentException("Time is too long.");
} }
return new StoopidTime() return new()
{ {
Input = input, Input = input,
Time = ts, Time = ts,

View File

@@ -19,7 +19,7 @@ public class MultilineScalarFlowStyleEmitter : ChainedEventEmitter
{ {
var isMultiLine = value.IndexOfAny(new char[] { '\r', '\n', '\x85', '\x2028', '\x2029' }) >= 0; var isMultiLine = value.IndexOfAny(new char[] { '\r', '\n', '\x85', '\x2028', '\x2029' }) >= 0;
if (isMultiLine) if (isMultiLine)
eventInfo = new ScalarEventInfo(eventInfo.Source) eventInfo = new(eventInfo.Source)
{ {
Style = ScalarStyle.Literal, Style = ScalarStyle.Literal,
}; };

View File

@@ -26,7 +26,7 @@ public class YamlHelper
// Check the value and write the character. // Check the value and write the character.
if (character >= 0xD800 && character <= 0xDFFF || character > 0x10FFFF) if (character is >= 0xD800 and <= 0xDFFF || character > 0x10FFFF)
{ {
return point; return point;
} }
@@ -37,9 +37,9 @@ public class YamlHelper
public static bool IsHex(char c) public static bool IsHex(char c)
{ {
return return
(c >= '0' && c <= '9') || c is >= '0' and <= '9' ||
(c >= 'A' && c <= 'F') || c is >= 'A' and <= 'F' ||
(c >= 'a' && c <= 'f'); c is >= 'a' and <= 'f';
} }
public static int AsHex(char c) public static int AsHex(char c)

View File

@@ -26,7 +26,7 @@ public static class GuildConfigExtensions
.Include(y => y.StreamRole.Blacklist)); .Include(y => y.StreamRole.Blacklist));
if (conf.StreamRole is null) if (conf.StreamRole is null)
conf.StreamRole = new StreamRoleSettings(); conf.StreamRole = new();
return conf.StreamRole; return conf.StreamRole;
} }
@@ -91,7 +91,7 @@ public static class GuildConfigExtensions
if (config is null) if (config is null)
{ {
ctx.GuildConfigs.Add((config = new GuildConfig ctx.GuildConfigs.Add((config = new()
{ {
GuildId = guildId, GuildId = guildId,
Permissions = Permissionv2.GetDefaultPermlist, Permissions = Permissionv2.GetDefaultPermlist,
@@ -150,7 +150,7 @@ public static class GuildConfigExtensions
if (config is null) // if there is no guildconfig, create new one if (config is null) // if there is no guildconfig, create new one
{ {
ctx.GuildConfigs.Add((config = new GuildConfig ctx.GuildConfigs.Add((config = new()
{ {
GuildId = guildId, GuildId = guildId,
Permissions = Permissionv2.GetDefaultPermlist Permissions = Permissionv2.GetDefaultPermlist

View File

@@ -13,7 +13,7 @@ public static class UserXpExtensions
if (usr is null) if (usr is null)
{ {
ctx.Add(usr = new UserXpStats() ctx.Add(usr = new()
{ {
Xp = 0, Xp = 0,
UserId = userId, UserId = userId,

View File

@@ -299,7 +299,7 @@ public partial class Administration : NadekoModule<AdministrationService>
[RequireContext(ContextType.Guild)] [RequireContext(ContextType.Guild)]
public async Task Delete(ITextChannel channel, ulong messageId, StoopidTime time = null) 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, 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) public UserSpamStats(IUserMessage msg)
{ {
LastMessage = msg.Content.ToUpperInvariant(); LastMessage = msg.Content.ToUpperInvariant();
timers = new ConcurrentQueue<Timer>(); timers = new();
ApplyNextMessage(msg); ApplyNextMessage(msg);
} }
@@ -31,7 +31,7 @@ public sealed class UserSpamStats : IDisposable
while (timers.TryDequeue(out var old)) while (timers.TryDequeue(out var old))
old.Change(Timeout.Infinite, Timeout.Infinite); old.Change(Timeout.Infinite, Timeout.Infinite);
} }
var t = new Timer((_) => { var t = new Timer(_ => {
if (timers.TryDequeue(out var old)) if (timers.TryDequeue(out var old))
old.Change(Timeout.Infinite, Timeout.Infinite); old.Change(Timeout.Infinite, Timeout.Infinite);
}, null, TimeSpan.FromMinutes(30), TimeSpan.FromMinutes(30)); }, null, TimeSpan.FromMinutes(30), TimeSpan.FromMinutes(30));

View File

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

View File

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

View File

@@ -23,9 +23,9 @@ public partial class Administration
var user = await ctx.Guild.GetCurrentUserAsync().ConfigureAwait(false); var user = await ctx.Guild.GetCurrentUserAsync().ConfigureAwait(false);
if (parameter == "-s" || parameter == "--safe") 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 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); ctx.Message.DeleteAfter(3);
} }
// prune x // prune x
@@ -43,7 +43,7 @@ public partial class Administration
count = 1000; count = 1000;
if (parameter == "-s" || parameter == "--safe") 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 else
await _service.PruneWhere((ITextChannel)ctx.Channel, count, x => true).ConfigureAwait(false); 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) 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.GetMessageAsync(msgId).ConfigureAwait(false)
: (await ctx.Channel.GetMessagesAsync(2).FlattenAsync().ConfigureAwait(false)) : (await ctx.Channel.GetMessagesAsync(2).FlattenAsync().ConfigureAwait(false))
.Skip(1) .Skip(1)
@@ -66,7 +66,7 @@ public partial class Administration
{ {
try try
{ {
await target.AddReactionAsync(x.emote, new RequestOptions() await target.AddReactionAsync(x.emote, new()
{ {
RetryMode = RetryMode.Retry502 | RetryMode.RetryRatelimit RetryMode = RetryMode.Retry502 | RetryMode.RetryRatelimit
}).ConfigureAwait(false); }).ConfigureAwait(false);
@@ -80,7 +80,7 @@ public partial class Administration
await Task.Delay(500).ConfigureAwait(false); await Task.Delay(500).ConfigureAwait(false);
} }
if (_service.Add(ctx.Guild.Id, new ReactionRoleMessage() if (_service.Add(ctx.Guild.Id, new()
{ {
Exclusive = exclusive, Exclusive = exclusive,
MessageId = target.Id, MessageId = target.Id,

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -134,7 +134,7 @@ public sealed class SelfService : ILateExecutor, IReadyExecutor, INService
private Timer TimerFromAutoCommand(AutoCommand x) 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,
x.Interval * 1000, x.Interval * 1000,
x.Interval * 1000); x.Interval * 1000);

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -7,15 +7,15 @@ public class QuadDeck : Deck
{ {
protected override void RefillPool() protected override void RefillPool()
{ {
CardPool = new List<Card>(52 * 4); CardPool = new(52 * 4);
for (var j = 1; j < 14; j++) for (var j = 1; j < 14; j++)
{ {
for (var i = 1; i < 5; i++) for (var i = 1; i < 5; i++)
{ {
CardPool.Add(new Card((CardSuit)i, j)); CardPool.Add(new((CardSuit)i, j));
CardPool.Add(new Card((CardSuit)i, j)); CardPool.Add(new((CardSuit)i, j));
CardPool.Add(new Card((CardSuit)i, j)); CardPool.Add(new((CardSuit)i, j));
CardPool.Add(new Card((CardSuit)i, j)); CardPool.Add(new((CardSuit)i, j));
} }
} }
} }
@@ -60,7 +60,7 @@ public class Deck
{ {
var str = string.Empty; var str = string.Empty;
if (Number <= 10 && Number > 1) if (Number is <= 10 and > 1)
{ {
str += "_" + Number; str += "_" + Number;
} }
@@ -101,7 +101,7 @@ public class Deck
throw new ArgumentException("Invalid input", nameof(input)); throw new ArgumentException("Invalid input", nameof(input));
} }
return new Card(s, n); return new(s, n);
} }
public string GetEmojiString() public string GetEmojiString()
@@ -189,7 +189,7 @@ public class Deck
/// </summary> /// </summary>
protected virtual void RefillPool() protected virtual void RefillPool()
{ {
CardPool = new List<Card>(52); CardPool = new(52);
//foreach suit //foreach suit
for (var j = 1; j < 14; j++) 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 //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, ... // 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); - cards.Min(card => (int)card.Number) == 4);
if (toReturn || cards.All(c => c.Number != 1)) return toReturn; 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) return (newCards.Max(card => (int)card.Number)
- newCards.Min(card => (int)card.Number) == 4); - newCards.Min(card => (int)card.Number) == 4);
} }
@@ -281,7 +281,7 @@ public class Deck
bool isStraightFlush(List<Card> cards) => hasStraightFlush(cards) && !isRoyalFlush(cards); bool isStraightFlush(List<Card> cards) => hasStraightFlush(cards) && !isRoyalFlush(cards);
handValues = new Dictionary<string, Func<List<Card>, bool>> handValues = new()
{ {
{ "Royal Flush", isRoyalFlush }, { "Royal Flush", isRoyalFlush },
{ "Straight Flush", isStraightFlush }, { "Straight Flush", isStraightFlush },

View File

@@ -54,12 +54,12 @@ public class GameStatusEvent : ICurrencyEvent
_channel = ch; _channel = ch;
_opts = opt; _opts = opt;
// generate code // 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) 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 => await _msg.ModifyAsync(m =>
{ {
m.Embed = GetEmbed(PotSize).Build(); 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}", Log.Information("Awarded {0} users {1} currency.{2}",
@@ -175,7 +175,7 @@ public class GameStatusEvent : ICurrencyEvent
try try
{ {
await msg.DeleteAsync(new RequestOptions() await msg.DeleteAsync(new()
{ {
RetryMode = RetryMode.AlwaysFail RetryMode = RetryMode.AlwaysFail
}); });

View File

@@ -52,10 +52,10 @@ public class ReactionEvent : ICurrencyEvent
_opts = opt; _opts = opt;
_config = config; _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) 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 => await _msg.ModifyAsync(m =>
{ {
m.Embed = GetEmbed(PotSize).Build(); 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}", Log.Information("Awarded {0} users {1} currency.{2}",

View File

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

View File

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

View File

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

View File

@@ -36,6 +36,6 @@ public class SlotGame
else if (rolls.Any(x => x == 5)) else if (rolls.Any(x => x == 5))
multi = 1; 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) public WheelOfFortuneGame(ulong userId, long bet, GamblingConfig config, ICurrencyService cs)
{ {
_rng = new NadekoRandom(); _rng = new();
_cs = cs; _cs = cs;
_bet = bet; _bet = bet;
_config = config; _config = config;
@@ -36,7 +36,7 @@ public class WheelOfFortuneGame
if (amount > 0) if (amount > 0)
await _cs.AddAsync(_userId, "Wheel Of Fortune - won", amount, gamble: true).ConfigureAwait(false); await _cs.AddAsync(_userId, "Wheel Of Fortune - won", amount, gamble: true).ConfigureAwait(false);
return new Result return new()
{ {
Index = result, Index = result,
Amount = amount, Amount = amount,

View File

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

View File

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

View File

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

View File

@@ -105,7 +105,7 @@ public partial class Gambling
return Task.CompletedTask; return Task.CompletedTask;
var enabledIn = _service.GetAllGeneratingChannels(); var enabledIn = _service.GetAllGeneratingChannels();
return ctx.SendPaginatedConfirmAsync(page, (cur) => return ctx.SendPaginatedConfirmAsync(page, cur =>
{ {
var items = enabledIn.Skip(page * 9).Take(9); 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)) if (!Games.TryGetValue(channelId, out var crg))
{ {
newGame = true; newGame = true;
crg = new CurrencyRaffleGame(mixed crg = new(mixed
? CurrencyRaffleGame.Type.Mixed ? CurrencyRaffleGame.Type.Mixed
: CurrencyRaffleGame.Type.Normal); : CurrencyRaffleGame.Type.Normal);
Games.Add(channelId, crg); 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.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.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.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("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("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); 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.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.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("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.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); 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) if (_bot.Client.ShardId == 0)
{ {
_decayTimer = new Timer(_ => _decayTimer = new(_ =>
{ {
var config = _gss.Data; var config = _gss.Data;
var maxDecay = config.Decay.MaxDecay; var maxDecay = config.Decay.MaxDecay;
@@ -85,7 +85,7 @@ WHERE CurrencyAmount > {config.Decay.MinThreshold} AND UserId!={_client.CurrentU
if (!takeRes) if (!takeRes)
{ {
return new SlotResponse return new()
{ {
Error = GamblingError.NotEnough Error = GamblingError.NotEnough
}; };

View File

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

View File

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

View File

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

View File

@@ -49,7 +49,7 @@ public partial class Gambling
set => set.Include(x => x.ShopEntries) set => set.Include(x => x.ShopEntries)
.ThenInclude(x => x.Items)).ShopEntries .ThenInclude(x => x.Items)).ShopEntries
.ToIndexed(); .ToIndexed();
return ctx.SendPaginatedConfirmAsync(page, (curPage) => return ctx.SendPaginatedConfirmAsync(page, curPage =>
{ {
var theseEntries = entries.Skip(curPage * 9).Take(9).ToArray(); var theseEntries = entries.Skip(curPage * 9).Take(9).ToArray();
@@ -261,7 +261,7 @@ public partial class Gambling
Price = price, Price = price,
Type = ShopEntryType.List, Type = ShopEntryType.List,
AuthorId = ctx.User.Id, AuthorId = ctx.User.Id,
Items = new HashSet<ShopEntryItem>(), Items = new(),
}; };
using (var uow = _db.GetDbContext()) 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>>() static readonly List<Func<int[], int>> _winningCombos = new List<Func<int[], int>>()
{ {
//three flowers //three flowers
(arr) => arr.All(a=>a==MaxValue) ? 30 : 0, arr => arr.All(a=>a==MaxValue) ? 30 : 0,
//three of the same //three of the same
(arr) => !arr.Any(a => a != arr[0]) ? 10 : 0, arr => !arr.Any(a => a != arr[0]) ? 10 : 0,
//two flowers //two flowers
(arr) => arr.Count(a => a == MaxValue) == 2 ? 4 : 0, arr => arr.Count(a => a == MaxValue) == 2 ? 4 : 0,
//one flower //one flower
(arr) => arr.Any(a => a == MaxValue) ? 1 : 0, arr => arr.Any(a => a == MaxValue) ? 1 : 0,
}; };
public static SlotResult Pull() public static SlotResult Pull()
@@ -78,7 +78,7 @@ public partial class Gambling
break; break;
} }
return new SlotResult(numbers, multi); return new(numbers, multi);
} }
public struct SlotResult public struct SlotResult
@@ -186,40 +186,40 @@ public partial class Gambling
Color fontColor = _config.Slots.CurrencyFontColor; 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, HorizontalAlignment = HorizontalAlignment.Center,
VerticalAlignment = VerticalAlignment.Center, VerticalAlignment = VerticalAlignment.Center,
WrapTextWidth = 140, WrapTextWidth = 140,
} }
}, result.Won.ToString(), _fonts.DottyFont.CreateFont(65), fontColor, }, result.Won.ToString(), _fonts.DottyFont.CreateFont(65), fontColor,
new PointF(227, 92))); new(227, 92)));
var bottomFont = _fonts.DottyFont.CreateFont(50); 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, HorizontalAlignment = HorizontalAlignment.Center,
VerticalAlignment = VerticalAlignment.Center, VerticalAlignment = VerticalAlignment.Center,
WrapTextWidth = 135, WrapTextWidth = 135,
} }
}, amount.ToString(), bottomFont, fontColor, }, 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, HorizontalAlignment = HorizontalAlignment.Center,
VerticalAlignment = VerticalAlignment.Center, VerticalAlignment = VerticalAlignment.Center,
WrapTextWidth = 135, WrapTextWidth = 135,
} }
}, ownedAmount.ToString(), bottomFont, fontColor, }, ownedAmount.ToString(), bottomFont, fontColor,
new PointF(325, 472))); new(325, 472)));
//sw.PrintLap("drew red text"); //sw.PrintLap("drew red text");
for (var i = 0; i < 3; i++) for (var i = 0; i < 3; i++)

View File

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

View File

@@ -41,7 +41,7 @@ public partial class Games
return; 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()) using (var uow = _db.GetDbContext())
{ {

View File

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

View File

@@ -60,7 +60,7 @@ public class CleverbotIOSession : IChatterBotSession
this._user = user; this._user = user;
this._httpFactory = factory; this._httpFactory = factory;
_nick = new AsyncLazy<string>((Func<Task<string>>)GetNick); _nick = new((Func<Task<string>>)GetNick);
} }
private async 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. Advice = advice; // convenient to have it here, even though atm there are only few different ones.
_httpFactory = factory; _httpFactory = factory;
Stream = new AsyncLazy<Stream>(() => Stream = new(() =>
{ {
try try
{ {
@@ -45,7 +45,7 @@ public class GirlRating
using (var pointImg = Image.Load(_images.RategirlDot)) 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(); var imgStream = new MemoryStream();

View File

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

View File

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

View File

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

View File

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

View File

@@ -28,7 +28,7 @@ public class TriviaQuestionPool
if (isPokemon) if (isPokemon)
{ {
var num = _rng.Next(1, maxPokemonId + 1); 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(), Map[num].ToTitleCase(),
"Pokemon", "Pokemon",
$@"https://nadeko.bot/images/pokemon/shadows/{num}.png", $@"https://nadeko.bot/images/pokemon/shadows/{num}.png",

View File

@@ -47,8 +47,8 @@ public class TypingGame
this.Channel = channel; this.Channel = channel;
IsActive = false; IsActive = false;
sw = new Stopwatch(); sw = new();
finishedUserIds = new List<ulong>(); finishedUserIds = new();
} }
public async Task<bool> Stop() public async Task<bool> Stop()
@@ -85,7 +85,7 @@ public class TypingGame
var time = _options.StartTime; 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 RetryMode = RetryMode.AlwaysRetry
}).ConfigureAwait(false); }).ConfigureAwait(false);

View File

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

View File

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

View File

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

View File

@@ -62,11 +62,11 @@ public class GamesService : INService
SizeLimit = 500_000 SizeLimit = 500_000
}); });
Ratings = new AsyncLazy<RatingTexts>(GetRatingTexts); Ratings = new(GetRatingTexts);
_rng = new NadekoRandom(); _rng = new NadekoRandom();
//girl ratings //girl ratings
_t = new Timer((_) => _t = new(_ =>
{ {
GirlRatings.Clear(); GirlRatings.Clear();
@@ -79,7 +79,7 @@ public class GamesService : INService
catch (Exception ex) catch (Exception ex)
{ {
Log.Warning("Error while loading typing articles {0}", ex.ToString()); 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) public void AddTypingArticle(IUser user, string text)
{ {
TypingArticles.Add(new TypingArticle TypingArticles.Add(new()
{ {
Source = user.ToString(), Source = user.ToString(),
Extra = $"Text added on {DateTime.UtcNow} by {user}.", 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) var col = new IndexedCollection<PollAnswer>(data.Skip(1)
.Select(x => new PollAnswer() { Text = x })); .Select(x => new PollAnswer() { Text = x }));
return new Poll() return new()
{ {
Answers = col, Answers = col,
Question = data[0], Question = data[0],
ChannelId = channelId, ChannelId = channelId,
GuildId = guildId, 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 (options, _) = OptionsParser.ParseFrom(new TypingGame.Options(), args);
var channel = (ITextChannel)ctx.Channel; 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) if (game.IsActive)
{ {

View File

@@ -42,11 +42,11 @@ public partial class Games
}); });
return; 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); _service.TicTacToeGames.Add(channel.Id, game);
await ReplyConfirmLocalizedAsync(strs.ttt_created).ConfigureAwait(false); await ReplyConfirmLocalizedAsync(strs.ttt_created).ConfigureAwait(false);
game.OnEnded += (g) => game.OnEnded += g =>
{ {
_service.TicTacToeGames.Remove(channel.Id); _service.TicTacToeGames.Remove(channel.Id);
_sem.Dispose(); _sem.Dispose();

View File

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

View File

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

View File

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

View File

@@ -62,7 +62,7 @@ public sealed partial class MusicQueue : IMusicQueue
public MusicQueue() public MusicQueue()
{ {
_index = 0; _index = 0;
_tracks = new LinkedList<QueuedTrackInfo>(); _tracks = new();
} }
public IQueuedTrackInfo Enqueue(ITrackInfo trackInfo, string queuer, out int index) public IQueuedTrackInfo Enqueue(ITrackInfo trackInfo, string queuer, out int index)
@@ -283,7 +283,7 @@ public sealed partial class MusicQueue : IMusicQueue
_index = i; _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); await Task.Delay(DELAY_ON_ERROR_MILISECONDS);
Log.Debug(ex, "Error performing proxy gateway action"); 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; return State != VoiceProxyState.Stopped && errorCount <= MAX_ERROR_COUNT;
} }
@@ -93,12 +93,12 @@ public sealed class VoiceProxy : IVoiceProxy
public Task StartSpeakingAsync() public Task StartSpeakingAsync()
{ {
return RunGatewayAction((gw) => gw.SendSpeakingAsync(VoiceSpeaking.State.Microphone)); return RunGatewayAction(gw => gw.SendSpeakingAsync(VoiceSpeaking.State.Microphone));
} }
public Task StopSpeakingAsync() public Task StopSpeakingAsync()
{ {
return RunGatewayAction((gw) => gw.SendSpeakingAsync(VoiceSpeaking.State.None)); return RunGatewayAction(gw => gw.SendSpeakingAsync(VoiceSpeaking.State.None));
} }
public async Task StartGateway() public async Task StartGateway()
@@ -108,7 +108,7 @@ public sealed class VoiceProxy : IVoiceProxy
public Task StopGateway() public Task StopGateway()
{ {
if(_gateway is VoiceGateway gw) if(_gateway is { } gw)
return gw.StopAsync(); return gw.StopAsync();
return Task.CompletedTask; return Task.CompletedTask;

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -12,7 +12,6 @@ namespace NadekoBot.Modules.Nsfw.Common;
public class SearchImageCacher : INService public class SearchImageCacher : INService
{ {
private readonly IHttpClientFactory _httpFactory; private readonly IHttpClientFactory _httpFactory;
private readonly SemaphoreSlim _lock = new SemaphoreSlim(1, 1);
private readonly Random _rng; private readonly Random _rng;
private static readonly ISet<string> defaultTagBlacklist = new HashSet<string>() 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))) if (!tags.All(x => IsValidTag(x)))
{ {
return new UrlReply return new()
{ {
Error = "One or more tags are invalid.", Error = "One or more tags are invalid.",
Url = "" Url = ""
@@ -106,7 +106,7 @@ public class SearchImagesService : ISearchImagesService, INService
if (result is null) if (result is null)
{ {
return new UrlReply return new()
{ {
Error = "Image not found.", Error = "Image not found.",
Url = "" Url = ""
@@ -129,7 +129,7 @@ public class SearchImagesService : ISearchImagesService, INService
catch (Exception ex) catch (Exception ex)
{ {
Log.Error(ex, "Failed getting {Dapi} image: {Message}", dapi, ex.Message); Log.Error(ex, "Failed getting {Dapi} image: {Message}", dapi, ex.Message);
return new UrlReply return new()
{ {
Error = ex.Message, Error = ex.Message,
Url = "" 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 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 // if we ran out of tasks, that means all tasks failed - return an error
return new UrlReply() return new()
{ {
Error = "No hentai image found." Error = "No hentai image found."
}; };
@@ -210,7 +210,7 @@ public class SearchImagesService : ISearchImagesService, INService
{ {
JToken obj; JToken obj;
obj = JArray.Parse(await _http.GetStringAsync($"http://api.oboobs.ru/boobs/{_rng.Next(0, 12000)}").ConfigureAwait(false))[0]; obj = JArray.Parse(await _http.GetStringAsync($"http://api.oboobs.ru/boobs/{_rng.Next(0, 12000)}").ConfigureAwait(false))[0];
return new UrlReply return new()
{ {
Error = "", Error = "",
Url = $"http://media.oboobs.ru/{obj["preview"]}", Url = $"http://media.oboobs.ru/{obj["preview"]}",
@@ -219,7 +219,7 @@ public class SearchImagesService : ISearchImagesService, INService
catch (Exception ex) catch (Exception ex)
{ {
Log.Error(ex, "Error retreiving boob image: {Message}", ex.Message); Log.Error(ex, "Error retreiving boob image: {Message}", ex.Message);
return new UrlReply return new()
{ {
Error = ex.Message, Error = ex.Message,
Url = "", Url = "",
@@ -245,7 +245,7 @@ public class SearchImagesService : ISearchImagesService, INService
} }
else else
{ {
uow.NsfwBlacklistedTags.Add(new NsfwBlacklistedTag() uow.NsfwBlacklistedTags.Add(new()
{ {
Tag = tag, Tag = tag,
GuildId = guildId GuildId = guildId
@@ -278,7 +278,7 @@ public class SearchImagesService : ISearchImagesService, INService
{ {
JToken obj; JToken obj;
obj = JArray.Parse(await _http.GetStringAsync($"http://api.obutts.ru/butts/{_rng.Next(0, 6100)}"))[0]; obj = JArray.Parse(await _http.GetStringAsync($"http://api.obutts.ru/butts/{_rng.Next(0, 6100)}"))[0];
return new UrlReply return new()
{ {
Error = "", Error = "",
Url = $"http://media.obutts.ru/{obj["preview"]}", Url = $"http://media.obutts.ru/{obj["preview"]}",
@@ -287,7 +287,7 @@ public class SearchImagesService : ISearchImagesService, INService
catch (Exception ex) catch (Exception ex)
{ {
Log.Error(ex, "Error retreiving butt image: {Message}", ex.Message); Log.Error(ex, "Error retreiving butt image: {Message}", ex.Message);
return new UrlReply return new()
{ {
Error = ex.Message, Error = ex.Message,
Url = "", Url = "",
@@ -311,7 +311,7 @@ public class SearchImagesService : ISearchImagesService, INService
+ GetNhentaiExtensionInternal(model.Images.Thumbnail.T); + GetNhentaiExtensionInternal(model.Images.Thumbnail.T);
var url = $"https://nhentai.net/g/{model.Id}"; var url = $"https://nhentai.net/g/{model.Id}";
return new Gallery( return new(
model.Id.ToString(), model.Id.ToString(),
url, url,
model.Title.English, model.Title.English,

View File

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

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