Kotz's editorconfig styles slightly modified. Target typed new usage. Brackets in expressions used for clarity.

This commit is contained in:
Kwoth
2021-12-26 02:52:09 +01:00
parent 68741ec484
commit d18f9429c6
172 changed files with 921 additions and 494 deletions

View File

@@ -14,14 +14,13 @@ public class AntiRaidStats
{
public AntiRaidSetting AntiRaidSettings { get; set; }
public int UsersCount { get; set; }
public ConcurrentHashSet<IGuildUser> RaidUsers { get; set; } = new ConcurrentHashSet<IGuildUser>();
public ConcurrentHashSet<IGuildUser> RaidUsers { get; set; } = new();
}
public class AntiSpamStats
{
public AntiSpamSetting AntiSpamSettings { get; set; }
public ConcurrentDictionary<ulong, UserSpamStats> UserStats { get; set; }
= new ConcurrentDictionary<ulong, UserSpamStats>();
public ConcurrentDictionary<ulong, UserSpamStats> UserStats { get; set; } = new();
}
public class AntiAltStats

View File

@@ -15,13 +15,13 @@ public sealed class UserSpamStats : IDisposable
ApplyNextMessage(msg);
}
private readonly object applyLock = new object();
private readonly object applyLock = new();
public void ApplyNextMessage(IUserMessage message)
{
lock (applyLock)
{
var upperMsg = message.Content.ToUpperInvariant();
if (upperMsg != LastMessage || string.IsNullOrWhiteSpace(upperMsg) && message.Attachments.Any())
if (upperMsg != LastMessage || (string.IsNullOrWhiteSpace(upperMsg) && message.Attachments.Any()))
{
LastMessage = upperMsg;
while (timers.TryDequeue(out var old))

View File

@@ -263,7 +263,7 @@ public partial class Administration
.Where(x => !x.IsManaged && x != x.Guild.EveryoneRole)
.ToList();
if (user.Id == ctx.Guild.OwnerId || ctx.User.Id != ctx.Guild.OwnerId && guser.GetRoles().Max(x => x.Position) <= userRoles.Max(x => x.Position))
if (user.Id == ctx.Guild.OwnerId || (ctx.User.Id != ctx.Guild.OwnerId && guser.GetRoles().Max(x => x.Position) <= userRoles.Max(x => x.Position)))
return;
try
{

View File

@@ -101,7 +101,7 @@ public partial class Administration
await SendConfirmAsync(
text: string.Join("\n", scmds
.Select(x => $@"```css
#{++i + page * 5}
#{++i + (page * 5)}
[{GetText(strs.server)}]: {(x.GuildId.HasValue ? $"{x.GuildName} #{x.GuildId}" : "-")}
[{GetText(strs.channel)}]: {x.ChannelName} #{x.ChannelId}
[{GetText(strs.command_text)}]: {x.CommandText}```")),
@@ -133,7 +133,7 @@ public partial class Administration
await SendConfirmAsync(
text: string.Join("\n", scmds
.Select(x => $@"```css
#{++i + page * 5}
#{++i + (page * 5)}
[{GetText(strs.server)}]: {(x.GuildId.HasValue ? $"{x.GuildName} #{x.GuildId}" : "-")}
[{GetText(strs.channel)}]: {x.ChannelName} #{x.ChannelId}
{GetIntervalText(x.Interval)}

View File

@@ -45,7 +45,7 @@ public class AdministrationService : INService
{
var _ = Task.Run(async () =>
{
if (!(msg.Channel is SocketTextChannel channel))
if (msg.Channel is not SocketTextChannel channel)
return;
//wat ?!
@@ -145,7 +145,7 @@ public class AdministrationService : INService
{
var msg = await chanl.GetMessageAsync(messageId);
if (!(msg is IUserMessage umsg) || msg.Author.Id != context.Client.CurrentUser.Id)
if (msg is not IUserMessage umsg || msg.Author.Id != context.Client.CurrentUser.Id)
return;
var rep = new ReplacementBuilder()

View File

@@ -14,7 +14,7 @@ public sealed class AutoAssignRoleService : INService
//guildid/roleid
private readonly ConcurrentDictionary<ulong, IReadOnlyList<ulong>> _autoAssignableRoles;
private Channel<SocketGuildUser> _assignQueue = Channel.CreateBounded<SocketGuildUser>(
private readonly Channel<SocketGuildUser> _assignQueue = Channel.CreateBounded<SocketGuildUser>(
new BoundedChannelOptions(100)
{
FullMode = BoundedChannelFullMode.DropOldest,

View File

@@ -41,7 +41,7 @@ public class DiscordPermOverrideService : INService, ILateBlocker
public Task<PreconditionResult> ExecuteOverrides(ICommandContext ctx, CommandInfo command,
GuildPerm perms, IServiceProvider services)
{
var rupa = new RequireUserPermissionAttribute((GuildPermission) perms);
var rupa = new RequireUserPermissionAttribute(perms);
return rupa.CheckPermissionsAsync(ctx, command, services);
}

View File

@@ -6,7 +6,7 @@ namespace NadekoBot.Modules.Administration.Services;
// todo if any activity...
public class GameVoiceChannelService : INService
{
public ConcurrentHashSet<ulong> GameVoiceChannels { get; } = new ConcurrentHashSet<ulong>();
public ConcurrentHashSet<ulong> GameVoiceChannels { get; } = new();
private readonly DbService _db;
private readonly DiscordSocketClient _client;
@@ -84,7 +84,7 @@ public class GameVoiceChannelService : INService
{
try
{
if (!(usr is SocketGuildUser gUser))
if (usr is not SocketGuildUser gUser)
return;
var game = gUser.Activities.FirstOrDefault()?.Name;

View File

@@ -5,7 +5,7 @@ namespace NadekoBot.Modules.Administration.Services;
public class GuildTimezoneService : INService
{
public static ConcurrentDictionary<ulong, GuildTimezoneService> AllServices { get; } = new ConcurrentDictionary<ulong, GuildTimezoneService>();
public static ConcurrentDictionary<ulong, GuildTimezoneService> AllServices { get; } = new();
private readonly ConcurrentDictionary<ulong, TimeZoneInfo> _timezones;
private readonly DbService _db;

View File

@@ -14,7 +14,7 @@ public sealed class ImageOnlyChannelService : IEarlyBehavior
private readonly DbService _db;
private readonly ConcurrentDictionary<ulong, ConcurrentHashSet<ulong>> _enabledOn;
private Channel<IUserMessage> _deleteQueue = Channel.CreateBounded<IUserMessage>(new BoundedChannelOptions(100)
private readonly Channel<IUserMessage> _deleteQueue = Channel.CreateBounded<IUserMessage>(new BoundedChannelOptions(100)
{
FullMode = BoundedChannelFullMode.DropOldest,
SingleReader = true,
@@ -74,8 +74,8 @@ public sealed class ImageOnlyChannelService : IEarlyBehavior
var newState = false;
using var uow = _db.GetDbContext();
if (forceDisable
|| _enabledOn.TryGetValue(guildId, out var channels)
&& channels.TryRemove(channelId))
|| (_enabledOn.TryGetValue(guildId, out var channels)
&& channels.TryRemove(channelId)))
{
uow.ImageOnlyChannels.Delete(x => x.ChannelId == channelId);
}

View File

@@ -49,8 +49,7 @@ public sealed class LogCommandService : ILogCommandService
public ConcurrentDictionary<ulong, LogSetting> GuildLogSettings { get; }
private ConcurrentDictionary<ITextChannel, List<string>> PresenceUpdates { get; } =
new ConcurrentDictionary<ITextChannel, List<string>>();
private ConcurrentDictionary<ITextChannel, List<string>> PresenceUpdates { get; } = new();
private readonly Timer _timerReference;
private readonly IBotStrings _strings;
@@ -62,7 +61,7 @@ public sealed class LogCommandService : ILogCommandService
private readonly IMemoryCache _memoryCache;
private readonly Timer _clearTimer;
private readonly ConcurrentHashSet<ulong> _ignoreMessageIds = new ConcurrentHashSet<ulong>();
private readonly ConcurrentHashSet<ulong> _ignoreMessageIds = new();
public LogCommandService(DiscordSocketClient client, IBotStrings strings,
DbService db, MuteService mute, ProtectionService prot, GuildTimezoneService tz,
@@ -218,7 +217,7 @@ public sealed class LogCommandService : ILogCommandService
logSetting.LogVoicePresenceId =
logSetting.UserMutedId =
logSetting.LogVoicePresenceTTSId =
value ? channelId : (ulong?) null;
value ? channelId : null;
;
await uow.SaveChangesAsync();
GuildLogSettings.AddOrUpdate(guildId, id => logSetting, (id, old) => logSetting);
@@ -231,7 +230,7 @@ public sealed class LogCommandService : ILogCommandService
{
try
{
if (!(uAfter is SocketGuildUser after))
if (uAfter is not SocketGuildUser after)
return;
var g = after.Guild;
@@ -359,7 +358,7 @@ public sealed class LogCommandService : ILogCommandService
{
try
{
if (!(iusr is IGuildUser usr))
if (iusr is not IGuildUser usr)
return;
var beforeVch = before.VoiceChannel;
@@ -673,7 +672,7 @@ public sealed class LogCommandService : ILogCommandService
{
try
{
if (!(cbefore is IGuildChannel before))
if (cbefore is not IGuildChannel before)
return;
var after = (IGuildChannel) cafter;
@@ -726,7 +725,7 @@ public sealed class LogCommandService : ILogCommandService
{
try
{
if (!(ich is IGuildChannel ch))
if (ich is not IGuildChannel ch)
return;
if (!GuildLogSettings.TryGetValue(ch.Guild.Id, out var logSetting)
@@ -766,7 +765,7 @@ public sealed class LogCommandService : ILogCommandService
{
try
{
if (!(ich is IGuildChannel ch))
if (ich is not IGuildChannel ch)
return;
if (!GuildLogSettings.TryGetValue(ch.Guild.Id, out var logSetting)
@@ -805,7 +804,7 @@ public sealed class LogCommandService : ILogCommandService
{
try
{
if (!(iusr is IGuildUser usr) || usr.IsBot)
if (iusr is not IGuildUser usr || usr.IsBot)
return;
var beforeVch = before.VoiceChannel;
@@ -1024,7 +1023,7 @@ public sealed class LogCommandService : ILogCommandService
return;
var ch = optCh.Value;
if (!(ch is ITextChannel channel))
if (ch is not ITextChannel channel)
return;
if (!GuildLogSettings.TryGetValue(channel.Guild.Id, out var logSetting)
@@ -1069,14 +1068,14 @@ public sealed class LogCommandService : ILogCommandService
{
try
{
if (!(imsg2 is IUserMessage after) || after.IsAuthor(_client))
if (imsg2 is not IUserMessage after || after.IsAuthor(_client))
return;
var before = (optmsg.HasValue ? optmsg.Value : null) as IUserMessage;
if (before is null)
return;
if (!(ch is ITextChannel channel))
if (ch is not ITextChannel channel)
return;
if (before.Content == after.Content)

View File

@@ -17,14 +17,13 @@ public class MuteService : INService
public ConcurrentDictionary<ulong, string> GuildMuteRoles { get; }
public ConcurrentDictionary<ulong, ConcurrentHashSet<ulong>> MutedUsers { get; }
public ConcurrentDictionary<ulong, ConcurrentDictionary<(ulong, TimerType), Timer>> Un_Timers { get; }
= new ConcurrentDictionary<ulong, ConcurrentDictionary<(ulong, TimerType), Timer>>();
public ConcurrentDictionary<ulong, ConcurrentDictionary<(ulong, TimerType), Timer>> Un_Timers { get; } = new();
public event Action<IGuildUser, IUser, MuteType, string> UserMuted = delegate { };
public event Action<IGuildUser, IUser, MuteType, string> UserUnmuted = delegate { };
private static readonly OverwritePermissions denyOverwrite =
new OverwritePermissions(addReactions: PermValue.Deny, sendMessages: PermValue.Deny,
new(addReactions: PermValue.Deny, sendMessages: PermValue.Deny,
attachFiles: PermValue.Deny);
private readonly DiscordSocketClient _client;

View File

@@ -8,14 +8,11 @@ namespace NadekoBot.Modules.Administration.Services;
public class ProtectionService : INService
{
private readonly ConcurrentDictionary<ulong, AntiRaidStats> _antiRaidGuilds
= new ConcurrentDictionary<ulong, AntiRaidStats>();
private readonly ConcurrentDictionary<ulong, AntiRaidStats> _antiRaidGuilds = new();
private readonly ConcurrentDictionary<ulong, AntiSpamStats> _antiSpamGuilds
= new ConcurrentDictionary<ulong, AntiSpamStats>();
private readonly ConcurrentDictionary<ulong, AntiSpamStats> _antiSpamGuilds = new();
private readonly ConcurrentDictionary<ulong, AntiAltStats> _antiAltGuilds
= new ConcurrentDictionary<ulong, AntiAltStats>();
private readonly ConcurrentDictionary<ulong, AntiAltStats> _antiAltGuilds = new();
public event Func<PunishmentAction, ProtectionType, IGuildUser[], Task> OnAntiProtectionTriggered
= delegate { return Task.CompletedTask; };
@@ -171,7 +168,7 @@ public class ProtectionService : INService
try
{
if (!(maybeStats is { } stats) || !stats.RaidUsers.Add(user))
if (maybeStats is not { } stats || !stats.RaidUsers.Add(user))
return;
++stats.UsersCount;
@@ -201,10 +198,10 @@ public class ProtectionService : INService
private Task HandleAntiSpam(SocketMessage arg)
{
if (!(arg is SocketUserMessage msg) || msg.Author.IsBot)
if (arg is not SocketUserMessage msg || msg.Author.IsBot)
return Task.CompletedTask;
if (!(msg.Channel is ITextChannel channel))
if (msg.Channel is not ITextChannel channel)
return Task.CompletedTask;
var _ = Task.Run(async () =>
{

View File

@@ -5,7 +5,7 @@ namespace NadekoBot.Modules.Administration.Services;
public class PruneService : INService
{
//channelids where prunes are currently occuring
private ConcurrentHashSet<ulong> _pruningGuilds = new ConcurrentHashSet<ulong>();
private readonly ConcurrentHashSet<ulong> _pruningGuilds = new();
private readonly TimeSpan twoWeeks = TimeSpan.FromDays(14);
private readonly ILogCommandService _logService;

View File

@@ -17,8 +17,7 @@ public sealed class SelfService : ILateExecutor, IReadyExecutor, INService
private ImmutableDictionary<ulong, IDMChannel> ownerChannels =
new Dictionary<ulong, IDMChannel>().ToImmutableDictionary();
private ConcurrentDictionary<ulong?, ConcurrentDictionary<int, Timer>> _autoCommands =
new ConcurrentDictionary<ulong?, ConcurrentDictionary<int, Timer>>();
private ConcurrentDictionary<ulong?, ConcurrentDictionary<int, Timer>> _autoCommands = new();
private readonly IImageCache _imgs;
private readonly IHttpClientFactory _httpFactory;

View File

@@ -312,7 +312,7 @@ WHERE GuildId={guildId}
// these 3 don't make sense with time
if ((punish == PunishmentAction.Softban || punish == PunishmentAction.Kick || punish == PunishmentAction.RemoveRoles) && time != null)
return false;
if (number <= 0 || time != null && time.Time > TimeSpan.FromDays(49))
if (number <= 0 || (time != null && time.Time > TimeSpan.FromDays(49)))
return false;
using (var uow = _db.GetDbContext())

View File

@@ -31,7 +31,7 @@ public partial class Administration
// bot can't punish a user who is higher in the hierarchy. Discord will return 403
// moderator can be owner, in which case role hierarchy doesn't matter
// otherwise, moderator has to have a higher role
if (botMaxRole <= targetMaxRole || ctx.User.Id != ownerId && targetMaxRole >= modMaxRole || target.Id == ownerId)
if (botMaxRole <= targetMaxRole || (ctx.User.Id != ownerId && targetMaxRole >= modMaxRole) || target.Id == ownerId)
{
await ReplyErrorLocalizedAsync(strs.hierarchy);
return false;

View File

@@ -13,7 +13,7 @@ public class ExportedExpr
public string[] React;
public static ExportedExpr FromModel(CustomReaction cr)
=> new ExportedExpr()
=> new()
{
Res = cr.Response,
Id = ((kwum)cr.Id).ToString(),

View File

@@ -13,8 +13,8 @@ public class CustomReactions : NadekoModule<CustomReactionsService>
_clientFactory = clientFactory;
}
private bool AdminInGuildOrOwnerInDm() => ctx.Guild is null && _creds.IsOwner(ctx.User)
|| ctx.Guild != null && ((IGuildUser)ctx.User).GuildPermissions.Administrator;
private bool AdminInGuildOrOwnerInDm() => (ctx.Guild is null && _creds.IsOwner(ctx.User))
|| (ctx.Guild != null && ((IGuildUser)ctx.User).GuildPermissions.Administrator);
[NadekoCommand, Aliases]
public async Task AddCustReact(string key, [Leftover] string message)
@@ -33,7 +33,7 @@ public class CustomReactions : NadekoModule<CustomReactionsService>
await ctx.Channel.EmbedAsync(_eb.Create().WithOkColor()
.WithTitle(GetText(strs.new_cust_react))
.WithDescription($"#{(kwum)cr.Id}")
.WithDescription($"#{cr.Id}")
.AddField(GetText(strs.trigger), key)
.AddField(GetText(strs.response), message.Length > 1024 ? GetText(strs.redacted_too_long) : message)
).ConfigureAwait(false);
@@ -46,13 +46,13 @@ public class CustomReactions : NadekoModule<CustomReactionsService>
if (string.IsNullOrWhiteSpace(message) || id < 0)
return;
if (channel is null && !_creds.IsOwner(ctx.User) || channel != null && !((IGuildUser)ctx.User).GuildPermissions.Administrator)
if ((channel is null && !_creds.IsOwner(ctx.User)) || (channel != null && !((IGuildUser)ctx.User).GuildPermissions.Administrator))
{
await ReplyErrorLocalizedAsync(strs.insuff_perms).ConfigureAwait(false);
return;
}
var cr = await _service.EditAsync(ctx.Guild?.Id, (int)id, message).ConfigureAwait(false);
var cr = await _service.EditAsync(ctx.Guild?.Id, id, message).ConfigureAwait(false);
if (cr != null)
{
await ctx.Channel.EmbedAsync(_eb.Create().WithOkColor()
@@ -112,7 +112,7 @@ public class CustomReactions : NadekoModule<CustomReactionsService>
[NadekoCommand, Aliases]
public async Task ShowCustReact(kwum id)
{
var found = _service.GetCustomReaction(ctx.Guild?.Id, (int)id);
var found = _service.GetCustomReaction(ctx.Guild?.Id, id);
if (found is null)
{
@@ -138,7 +138,7 @@ public class CustomReactions : NadekoModule<CustomReactionsService>
return;
}
var cr = await _service.DeleteAsync(ctx.Guild?.Id, (int)id);
var cr = await _service.DeleteAsync(ctx.Guild?.Id, id);
if (cr != null)
{

View File

@@ -22,12 +22,12 @@ public sealed class CustomReactionsService : IEarlyBehavior, IReadyExecutor
Message,
}
private readonly object _gcrWriteLock = new object();
private readonly object _gcrWriteLock = new();
private readonly TypedKey<CustomReaction> _gcrAddedKey = new TypedKey<CustomReaction>("gcr.added");
private readonly TypedKey<int> _gcrDeletedkey = new TypedKey<int>("gcr.deleted");
private readonly TypedKey<CustomReaction> _gcrEditedKey = new TypedKey<CustomReaction>("gcr.edited");
private readonly TypedKey<bool> _crsReloadedKey = new TypedKey<bool>("crs.reloaded");
private readonly TypedKey<CustomReaction> _gcrAddedKey = new("gcr.added");
private readonly TypedKey<int> _gcrDeletedkey = new("gcr.deleted");
private readonly TypedKey<CustomReaction> _gcrEditedKey = new("gcr.edited");
private readonly TypedKey<bool> _crsReloadedKey = new("crs.reloaded");
private const string MentionPh = "%bot.mention%";
// it is perfectly fine to have global customreactions as an array
@@ -119,8 +119,7 @@ public sealed class CustomReactionsService : IEarlyBehavior, IReadyExecutor
public Task OnReadyAsync()
=> ReloadInternal(_bot.GetCurrentGuildIds());
private ValueTask OnCrsShouldReload(bool _)
=> new ValueTask(ReloadInternal(_bot.GetCurrentGuildIds()));
private ValueTask OnCrsShouldReload(bool _) => new(ReloadInternal(_bot.GetCurrentGuildIds()));
private ValueTask OnGcrAdded(CustomReaction c)
{
@@ -257,7 +256,7 @@ public sealed class CustomReactionsService : IEarlyBehavior, IReadyExecutor
if (toDelete is null)
return null;
if (toDelete.IsGlobal() && guildId is null || guildId == toDelete.GuildId)
if ((toDelete.IsGlobal() && guildId is null) || guildId == toDelete.GuildId)
{
uow.CustomReactions.Remove(toDelete);
await uow.SaveChangesAsync();
@@ -290,7 +289,7 @@ public sealed class CustomReactionsService : IEarlyBehavior, IReadyExecutor
if (!ready)
return null;
if (!(umsg.Channel is SocketTextChannel channel))
if (umsg.Channel is not SocketTextChannel channel)
return null;
var content = umsg.Content.Trim().ToLowerInvariant();

View File

@@ -70,7 +70,7 @@ public partial class Gambling
GetText(strs.animal_race_won_money(
Format.Bold(winner.Username),
winner.Animal.Icon,
race.FinishedUsers[0].Bet * (race.Users.Count - 1) + CurrencySign)));
(race.FinishedUsers[0].Bet * (race.Users.Count - 1)) + CurrencySign)));
}
else
{

View File

@@ -20,10 +20,10 @@ public sealed class AnimalRace : IDisposable
public event Func<AnimalRace, Task> OnEnded = delegate { return Task.CompletedTask; };
public IReadOnlyCollection<AnimalRacingUser> Users => _users.ToList();
public List<AnimalRacingUser> FinishedUsers { get; } = new List<AnimalRacingUser>();
public List<AnimalRacingUser> FinishedUsers { get; } = new();
private readonly SemaphoreSlim _locker = new SemaphoreSlim(1, 1);
private readonly HashSet<AnimalRacingUser> _users = new HashSet<AnimalRacingUser>();
private readonly SemaphoreSlim _locker = new(1, 1);
private readonly HashSet<AnimalRacingUser> _users = new();
private readonly ICurrencyService _currency;
private readonly RaceOptions _options;
private readonly Queue<RaceAnimal> _animalsQueue;

View File

@@ -13,7 +13,7 @@ public class Blackjack
public Dealer Dealer { get; set; }
public List<User> Players { get; set; } = new List<User>();
public List<User> Players { get; set; } = new();
public GameState State { get; set; } = GameState.Starting;
public User CurrentUser { get; private set; }
@@ -24,7 +24,7 @@ public class Blackjack
public event Func<Blackjack, Task> StateUpdated;
public event Func<Blackjack, Task> GameEnded;
private readonly SemaphoreSlim locker = new SemaphoreSlim(1, 1);
private readonly SemaphoreSlim locker = new(1, 1);
public Blackjack(ICurrencyService cs, DbService db)
{
@@ -174,7 +174,7 @@ public class Blackjack
{
var hw = Dealer.GetHandValue();
while (hw < 17
|| hw == 17 && Dealer.Cards.Count(x => x.Number == 1) > (Dealer.GetRawHandValue() - 17) / 10)// hit on soft 17
|| (hw == 17 && Dealer.Cards.Count(x => x.Number == 1) > (Dealer.GetRawHandValue() - 17) / 10))// hit on soft 17
{
/* Dealer has
A 6

View File

@@ -2,7 +2,7 @@
public abstract class Player
{
public List<Deck.Card> Cards { get; } = new List<Deck.Card>();
public List<Deck.Card> Cards { get; } = new();
public int GetHandValue()
{

View File

@@ -25,7 +25,7 @@ public class CurrencyRaffleGame
}
}
private readonly HashSet<User> _users = new HashSet<User>();
private readonly HashSet<User> _users = new();
public IEnumerable<User> Users => _users;
public Type GameType { get; }

View File

@@ -20,7 +20,7 @@ public class QuadDeck : Deck
public class Deck
{
private static readonly Dictionary<int, string> cardNames = new Dictionary<int, string>() {
private static readonly Dictionary<int, string> _cardNames = new() {
{ 1, "Ace" },
{ 2, "Two" },
{ 3, "Three" },
@@ -35,7 +35,7 @@ public class Deck
{ 12, "Queen" },
{ 13, "King" }
};
private static Dictionary<string, Func<List<Card>, bool>> handValues;
private static Dictionary<string, Func<List<Card>, bool>> _handValues;
public enum CardSuit
@@ -75,15 +75,14 @@ public class Deck
this.Number = cardNum;
}
public string GetValueText() => cardNames[Number];
public string GetValueText() => _cardNames[Number];
public override string ToString() => cardNames[Number] + " Of " + Suit;
public override string ToString() => _cardNames[Number] + " Of " + Suit;
public int CompareTo(object obj)
{
if (!(obj is Card)) return 0;
var c = (Card)obj;
return this.Number - c.Number;
if (obj is not Card card) return 0;
return this.Number - card.Number;
}
public static Card Parse(string input)
@@ -133,7 +132,7 @@ public class Deck
{CardSuit.Spades, "♠"},
{CardSuit.Hearts, "♥"},
};
private static IReadOnlyDictionary<string, CardSuit> _suitCharToSuit = new Dictionary<string, CardSuit>
private static readonly IReadOnlyDictionary<string, CardSuit> _suitCharToSuit = new Dictionary<string, CardSuit>
{
{"♦", CardSuit.Diamonds },
{"d", CardSuit.Diamonds },
@@ -144,7 +143,7 @@ public class Deck
{"♥", CardSuit.Hearts },
{"h", CardSuit.Hearts },
};
private static IReadOnlyDictionary<char, int> _numberCharToNumber = new Dictionary<char, int>()
private static readonly IReadOnlyDictionary<char, int> _numberCharToNumber = new Dictionary<char, int>()
{
{'a', 1 },
{'2', 2 },
@@ -200,7 +199,7 @@ public class Deck
}
}
}
private Random r = new NadekoRandom();
private readonly Random _r = new NadekoRandom();
/// <summary>
/// Take a card from the pool, you either take it from the top if the deck is shuffled, or from a random place if the deck is in the default order.
/// </summary>
@@ -211,7 +210,7 @@ public class Deck
Restart();
//you can either do this if your deck is not shuffled
var num = r.Next(0, CardPool.Count);
var num = _r.Next(0, CardPool.Count);
var c = CardPool[num];
CardPool.RemoveAt(num);
return c;
@@ -230,73 +229,73 @@ public class Deck
{
if (CardPool.Count <= 1) return;
var orderedPool = CardPool.Shuffle();
CardPool = CardPool as List<Card> ?? orderedPool.ToList();
CardPool ??= orderedPool.ToList();
}
public override string ToString() => string.Concat(CardPool.Select(c => c.ToString())) + Environment.NewLine;
private static void InitHandValues()
{
bool hasPair(List<Card> cards) => cards.GroupBy(card => card.Number)
bool HasPair(List<Card> cards) => cards.GroupBy(card => card.Number)
.Count(group => group.Count() == 2) == 1;
bool isPair(List<Card> cards) => cards.GroupBy(card => card.Number)
bool IsPair(List<Card> cards) => cards.GroupBy(card => card.Number)
.Count(group => group.Count() == 3) == 0
&& hasPair(cards);
&& HasPair(cards);
bool isTwoPair(List<Card> cards) => cards.GroupBy(card => card.Number)
bool IsTwoPair(List<Card> cards) => cards.GroupBy(card => card.Number)
.Count(group => group.Count() == 2) == 2;
bool isStraight(List<Card> cards)
bool IsStraight(List<Card> cards)
{
if (cards.GroupBy(card => card.Number).Count() != cards.Count())
return false;
var toReturn = cards.Max(card => (int)card.Number)
- cards.Min(card => (int)card.Number) == 4;
var toReturn = cards.Max(card => card.Number)
- cards.Min(card => card.Number) == 4;
if (toReturn || cards.All(c => c.Number != 1)) return toReturn;
var newCards = cards.Select(c => c.Number == 1 ? new(c.Suit, 14) : c);
return newCards.Max(card => (int)card.Number)
- newCards.Min(card => (int)card.Number) == 4;
return newCards.Max(card => card.Number)
- newCards.Min(card => card.Number) == 4;
}
bool hasThreeOfKind(List<Card> cards) => cards.GroupBy(card => card.Number)
bool HasThreeOfKind(List<Card> cards) => cards.GroupBy(card => card.Number)
.Any(group => group.Count() == 3);
bool isThreeOfKind(List<Card> cards) => hasThreeOfKind(cards) && !hasPair(cards);
bool IsThreeOfKind(List<Card> cards) => HasThreeOfKind(cards) && !HasPair(cards);
bool isFlush(List<Card> cards) => cards.GroupBy(card => card.Suit).Count() == 1;
bool IsFlush(List<Card> cards) => cards.GroupBy(card => card.Suit).Count() == 1;
bool isFourOfKind(List<Card> cards) => cards.GroupBy(card => card.Number)
bool IsFourOfKind(List<Card> cards) => cards.GroupBy(card => card.Number)
.Any(group => group.Count() == 4);
bool isFullHouse(List<Card> cards) => hasPair(cards) && hasThreeOfKind(cards);
bool IsFullHouse(List<Card> cards) => HasPair(cards) && HasThreeOfKind(cards);
bool hasStraightFlush(List<Card> cards) => isFlush(cards) && isStraight(cards);
bool HasStraightFlush(List<Card> cards) => IsFlush(cards) && IsStraight(cards);
bool isRoyalFlush(List<Card> cards) => cards.Min(card => card.Number) == 1 &&
bool IsRoyalFlush(List<Card> cards) => cards.Min(card => card.Number) == 1 &&
cards.Max(card => card.Number) == 13
&& hasStraightFlush(cards);
&& HasStraightFlush(cards);
bool isStraightFlush(List<Card> cards) => hasStraightFlush(cards) && !isRoyalFlush(cards);
bool IsStraightFlush(List<Card> cards) => HasStraightFlush(cards) && !IsRoyalFlush(cards);
handValues = new()
_handValues = new()
{
{ "Royal Flush", isRoyalFlush },
{ "Straight Flush", isStraightFlush },
{ "Four Of A Kind", isFourOfKind },
{ "Full House", isFullHouse },
{ "Flush", isFlush },
{ "Straight", isStraight },
{ "Three Of A Kind", isThreeOfKind },
{ "Two Pairs", isTwoPair },
{ "A Pair", isPair }
{ "Royal Flush", IsRoyalFlush },
{ "Straight Flush", IsStraightFlush },
{ "Four Of A Kind", IsFourOfKind },
{ "Full House", IsFullHouse },
{ "Flush", IsFlush },
{ "Straight", IsStraight },
{ "Three Of A Kind", IsThreeOfKind },
{ "Two Pairs", IsTwoPair },
{ "A Pair", IsPair }
};
}
public static string GetHandValue(List<Card> cards)
{
if (handValues is null)
if (_handValues is null)
InitHandValues();
foreach (var kvp in handValues.Where(x => x.Value(cards)))
foreach (var kvp in _handValues.Where(x => x.Value(cards)))
{
return kvp.Key;
}

View File

@@ -18,8 +18,8 @@ public class GameStatusEvent : ICurrencyEvent
private readonly Func<CurrencyEvent.Type, EventOptions, long, IEmbedBuilder> _embedFunc;
private readonly bool _isPotLimited;
private readonly ITextChannel _channel;
private readonly ConcurrentHashSet<ulong> _awardedUsers = new ConcurrentHashSet<ulong>();
private readonly ConcurrentQueue<ulong> _toAward = new ConcurrentQueue<ulong>();
private readonly ConcurrentHashSet<ulong> _awardedUsers = new();
private readonly ConcurrentQueue<ulong> _toAward = new();
private readonly Timer _t;
private readonly Timer _timeout = null;
private readonly EventOptions _opts;
@@ -127,7 +127,7 @@ public class GameStatusEvent : ICurrencyEvent
}
}
private readonly object stopLock = new object();
private readonly object stopLock = new();
public async Task StopEvent()
{
await Task.Yield();
@@ -150,7 +150,7 @@ public class GameStatusEvent : ICurrencyEvent
{
var _ = Task.Run(async () =>
{
if (!(msg.Author is IGuildUser gu) // no unknown users, as they could be bots, or alts
if (msg.Author is not IGuildUser gu // no unknown users, as they could be bots, or alts
|| gu.IsBot // no bots
|| msg.Content != _code // code has to be the same
|| (DateTime.UtcNow - gu.CreatedAt).TotalDays <= 5) // no recently created accounts
@@ -178,7 +178,7 @@ public class GameStatusEvent : ICurrencyEvent
return Task.CompletedTask;
}
private readonly object potLock = new object();
private readonly object potLock = new();
private bool TryTakeFromPot()
{
if (_isPotLimited)

View File

@@ -19,8 +19,8 @@ public class ReactionEvent : ICurrencyEvent
private readonly Func<CurrencyEvent.Type, EventOptions, long, IEmbedBuilder> _embedFunc;
private readonly bool _isPotLimited;
private readonly ITextChannel _channel;
private readonly ConcurrentHashSet<ulong> _awardedUsers = new ConcurrentHashSet<ulong>();
private readonly ConcurrentQueue<ulong> _toAward = new ConcurrentQueue<ulong>();
private readonly ConcurrentHashSet<ulong> _awardedUsers = new();
private readonly ConcurrentQueue<ulong> _toAward = new();
private readonly Timer _t;
private readonly Timer _timeout = null;
private readonly bool _noRecentlyJoinedServer;
@@ -130,7 +130,7 @@ public class ReactionEvent : ICurrencyEvent
}
}
private readonly object stopLock = new object();
private readonly object stopLock = new();
public async Task StopEvent()
{
await Task.Yield();
@@ -160,8 +160,8 @@ public class ReactionEvent : ICurrencyEvent
|| msg.Id != _msg.Id // same message
|| gu.IsBot // no bots
|| (DateTime.UtcNow - gu.CreatedAt).TotalDays <= 5 // no recently created accounts
|| _noRecentlyJoinedServer && // if specified, no users who joined the server in the last 24h
(gu.JoinedAt is null || (DateTime.UtcNow - gu.JoinedAt.Value).TotalDays < 1)) // and no users for who we don't know when they joined
|| (_noRecentlyJoinedServer && // if specified, no users who joined the server in the last 24h
(gu.JoinedAt is null || (DateTime.UtcNow - gu.JoinedAt.Value).TotalDays < 1))) // and no users for who we don't know when they joined
{
return;
}
@@ -177,7 +177,7 @@ public class ReactionEvent : ICurrencyEvent
return Task.CompletedTask;
}
private readonly object potLock = new object();
private readonly object potLock = new();
private bool TryTakeFromPot()
{
if (_isPotLimited)

View File

@@ -108,9 +108,9 @@ Doesn't have to be ordered.")]
{
Pairs = new BetRollPair[]
{
new BetRollPair { WhenAbove = 99, MultiplyBy = 10 },
new BetRollPair { WhenAbove = 90, MultiplyBy = 4 },
new BetRollPair { WhenAbove = 66, MultiplyBy = 2 }
new() { WhenAbove = 99, MultiplyBy = 10 },
new() { WhenAbove = 90, MultiplyBy = 4 },
new() { WhenAbove = 66, MultiplyBy = 2 }
};
}
}
@@ -184,11 +184,11 @@ public sealed partial class WaifuConfig
[Comment(@"Minimum price a waifu can have")]
public int MinPrice { get; set; } = 50;
public MultipliersData Multipliers { get; set; } = new MultipliersData();
public MultipliersData Multipliers { get; set; } = new();
[Comment(@"List of items available for gifting.
If negative is true, gift will instead reduce waifu value.")]
public List<WaifuItemModel> Items { get; set; } = new List<WaifuItemModel>();
public List<WaifuItemModel> Items { get; set; } = new();
public WaifuConfig()
{

View File

@@ -26,13 +26,13 @@ public class RollDuelGame
}
private readonly Timer _timeoutTimer;
private readonly NadekoRandom _rng = new NadekoRandom();
private readonly SemaphoreSlim _locker = new SemaphoreSlim(1, 1);
private readonly NadekoRandom _rng = new();
private readonly SemaphoreSlim _locker = new(1, 1);
public event Func<RollDuelGame, Task> OnGameTick;
public event Func<RollDuelGame, Reason, Task> OnEnded;
public List<(int, int)> Rolls { get; } = new List<(int, int)>();
public List<(int, int)> Rolls { get; } = new();
public State CurrentState { get; private set; }
public ulong Winner { get; private set; }
@@ -111,7 +111,7 @@ public class RollDuelGame
await _cs.AddAsync(Winner, "Roll Duel win", won)
.ConfigureAwait(false);
await _cs.AddAsync(_botId, "Roll Duel fee", Amount * 2 - won)
await _cs.AddAsync(_botId, "Roll Duel fee", (Amount * 2) - won)
.ConfigureAwait(false);
}
try { await (OnGameTick?.Invoke(this)).ConfigureAwait(false); } catch { }

View File

@@ -4,6 +4,6 @@ public class SlotResponse
{
public float Multiplier { get; set; }
public long Won { get; set; }
public List<int> Rolls { get; set; } = new List<int>();
public List<int> Rolls { get; set; } = new();
public GamblingError Error { get; set; }
}

View File

@@ -52,7 +52,7 @@ public sealed class Connect4Game : IDisposable
public event Func<Connect4Game, Task> OnGameFailedToStart;
public event Func<Connect4Game, Result, Task> OnGameEnded;
private readonly SemaphoreSlim _locker = new SemaphoreSlim(1, 1);
private readonly SemaphoreSlim _locker = new(1, 1);
private readonly Options _options;
private readonly ICurrencyService _cs;
private readonly NadekoRandom _rng;
@@ -154,8 +154,8 @@ public sealed class Connect4Game : IDisposable
if (CurrentPhase == Phase.Ended || CurrentPhase == Phase.Joining)
return false;
if (!(_players[0].Value.UserId == userId && CurrentPhase == Phase.P1Move
|| _players[1].Value.UserId == userId && CurrentPhase == Phase.P2Move))
if (!((_players[0].Value.UserId == userId && CurrentPhase == Phase.P1Move)
|| (_players[1].Value.UserId == userId && CurrentPhase == Phase.P2Move)))
return false;
if (inputCol < 0 || inputCol > NumberOfColumns) //invalid input
@@ -187,12 +187,12 @@ public sealed class Connect4Game : IDisposable
if (CurrentPhase == Phase.Ended)
break;
var first = _gameState[i + j * NumberOfRows];
var first = _gameState[i + (j * NumberOfRows)];
if (first != Field.Empty)
{
for (var k = 1; k < 4; k++)
{
var next = _gameState[i + k + j * NumberOfRows];
var next = _gameState[i + k + (j * NumberOfRows)];
if (next == first)
{
if (k == 3)
@@ -217,12 +217,12 @@ public sealed class Connect4Game : IDisposable
if (CurrentPhase == Phase.Ended)
break;
var first = _gameState[j + i * NumberOfRows];
var first = _gameState[j + (i * NumberOfRows)];
if (first != Field.Empty)
{
for (var k = 1; k < 4; k++)
{
var next = _gameState[j + (i + k) * NumberOfRows];
var next = _gameState[j + ((i + k) * NumberOfRows)];
if (next == first)
if (k == 3)
EndGame(Result.CurrentPlayerWon, CurrentPlayer.UserId);
@@ -245,7 +245,7 @@ public sealed class Connect4Game : IDisposable
if (CurrentPhase == Phase.Ended)
break;
var first = _gameState[row + col * NumberOfRows];
var first = _gameState[row + (col * NumberOfRows)];
if (first != Field.Empty)
{
@@ -264,7 +264,7 @@ public sealed class Connect4Game : IDisposable
if (curCol < 0 || curCol >= NumberOfColumns)
break;
var cur = _gameState[curRow + curCol * NumberOfRows];
var cur = _gameState[curRow + (curCol * NumberOfRows)];
if (cur == first)
same++;
else break;
@@ -291,7 +291,7 @@ public sealed class Connect4Game : IDisposable
if (curCol < 0 || curCol >= NumberOfColumns)
break;
var cur = _gameState[curRow + curCol * NumberOfRows];
var cur = _gameState[curRow + (curCol * NumberOfRows)];
if (cur == first)
same++;
else break;

View File

@@ -177,7 +177,7 @@ public partial class Gambling
{
for (var j = 0; j < Connect4Game.NumberOfColumns; j++)
{
var cur = game.GameState[i + j * Connect4Game.NumberOfRows - 1];
var cur = game.GameState[i + (j * Connect4Game.NumberOfRows) - 1];
if (cur == Connect4Game.Field.Empty)
sb.Append("⚫"); //black circle

View File

@@ -10,8 +10,8 @@ public partial class Gambling
[Group]
public class DiceRollCommands : NadekoSubmodule
{
private static readonly Regex dndRegex = new Regex(@"^(?<n1>\d+)d(?<n2>\d+)(?:\+(?<add>\d+))?(?:\-(?<sub>\d+))?$", RegexOptions.Compiled);
private static readonly Regex fudgeRegex = new Regex(@"^(?<n1>\d+)d(?:F|f)$", RegexOptions.Compiled);
private static readonly Regex dndRegex = new(@"^(?<n1>\d+)d(?<n2>\d+)(?:\+(?<add>\d+))?(?:\-(?<sub>\d+))?$", RegexOptions.Compiled);
private static readonly Regex fudgeRegex = new(@"^(?<n1>\d+)d(?:F|f)$", RegexOptions.Compiled);
private static readonly char[] _fateRolls = { '-', ' ', '+' };
private readonly IImageCache _images;

View File

@@ -10,7 +10,7 @@ public partial class Gambling
[Group]
public class DrawCommands : NadekoSubmodule
{
private static readonly ConcurrentDictionary<IGuild, Deck> _allDecks = new ConcurrentDictionary<IGuild, Deck>();
private static readonly ConcurrentDictionary<IGuild, Deck> _allDecks = new();
private readonly IImageCache _images;
public DrawCommands(IDataCache data)

View File

@@ -13,7 +13,7 @@ public partial class Gambling
{
private readonly IImageCache _images;
private readonly ICurrencyService _cs;
private static readonly NadekoRandom rng = new NadekoRandom();
private static readonly NadekoRandom rng = new();
public FlipCoinCommands(IDataCache data, ICurrencyService cs, GamblingConfigService gss) : base(gss)
{

View File

@@ -574,7 +574,7 @@ public partial class Gambling : GamblingModule<GamblingService>
var usrStr = x.ToString().TrimTo(20, true);
var j = i;
embed.AddField("#" + (9 * curPage + j + 1) + " " + usrStr, n(x.CurrencyAmount), true);
embed.AddField("#" + ((9 * curPage) + j + 1) + " " + usrStr, n(x.CurrencyAmount), true);
}
return embed;
@@ -642,9 +642,9 @@ public partial class Gambling : GamblingModule<GamblingService>
embed.WithOkColor();
msg = GetText(strs.rps_draw(getRpsPick(pick)));
}
else if (pick == RpsPick.Paper && nadekoPick == RpsPick.Rock ||
pick == RpsPick.Rock && nadekoPick == RpsPick.Scissors ||
pick == RpsPick.Scissors && nadekoPick == RpsPick.Paper)
else if ((pick == RpsPick.Paper && nadekoPick == RpsPick.Rock) ||
(pick == RpsPick.Rock && nadekoPick == RpsPick.Scissors) ||
(pick == RpsPick.Scissors && nadekoPick == RpsPick.Paper))
{
amount = (long)(amount * base._config.BetFlip.Multiplier);
await _cs.AddAsync(ctx.User.Id,

View File

@@ -4,5 +4,5 @@ namespace NadekoBot.Modules.Gambling.Services;
public class AnimalRaceService : INService
{
public ConcurrentDictionary<ulong, AnimalRace> AnimalRaces { get; } = new ConcurrentDictionary<ulong, AnimalRace>();
public ConcurrentDictionary<ulong, AnimalRace> AnimalRaces { get; } = new();
}

View File

@@ -4,5 +4,5 @@ namespace NadekoBot.Modules.Gambling.Services;
public class BlackJackService : INService
{
public ConcurrentDictionary<ulong, Blackjack> Games { get; } = new ConcurrentDictionary<ulong, Blackjack>();
public ConcurrentDictionary<ulong, Blackjack> Games { get; } = new();
}

View File

@@ -10,8 +10,7 @@ public class CurrencyEventsService : INService
private readonly ICurrencyService _cs;
private readonly GamblingConfigService _configService;
private readonly ConcurrentDictionary<ulong, ICurrencyEvent> _events =
new ConcurrentDictionary<ulong, ICurrencyEvent>();
private readonly ConcurrentDictionary<ulong, ICurrencyEvent> _events = new();
public CurrencyEventsService(

View File

@@ -9,11 +9,11 @@ public class CurrencyRaffleService : INService
NotEnoughCurrency,
AlreadyJoinedOrInvalidAmount
}
private readonly SemaphoreSlim _locker = new SemaphoreSlim(1, 1);
private readonly SemaphoreSlim _locker = new(1, 1);
private readonly DbService _db;
private readonly ICurrencyService _cs;
public Dictionary<ulong, CurrencyRaffleGame> Games { get; } = new Dictionary<ulong, CurrencyRaffleGame>();
public Dictionary<ulong, CurrencyRaffleGame> Games { get; } = new();
public CurrencyRaffleService(DbService db, ICurrencyService cs)
{

View File

@@ -7,7 +7,7 @@ public sealed class GamblingConfigService : ConfigServiceBase<GamblingConfig>
{
public override string Name { get; } = "gambling";
private const string FilePath = "data/gambling.yml";
private static TypedKey<GamblingConfig> changeKey = new TypedKey<GamblingConfig>("config.gambling.updated");
private static readonly TypedKey<GamblingConfig> changeKey = new("config.gambling.updated");
public GamblingConfigService(IConfigSeria serializer, IPubSub pubSub)

View File

@@ -17,8 +17,8 @@ public class GamblingService : INService
private readonly IDataCache _cache;
private readonly GamblingConfigService _gss;
public ConcurrentDictionary<(ulong, ulong), RollDuelGame> Duels { get; } = new ConcurrentDictionary<(ulong, ulong), RollDuelGame>();
public ConcurrentDictionary<ulong, Connect4Game> Connect4Games { get; } = new ConcurrentDictionary<ulong, Connect4Game>();
public ConcurrentDictionary<(ulong, ulong), RollDuelGame> Duels { get; } = new();
public ConcurrentDictionary<ulong, Connect4Game> Connect4Games { get; } = new();
private readonly Timer _decayTimer;

View File

@@ -24,10 +24,10 @@ public class PlantPickService : INService
private readonly DiscordSocketClient _client;
private readonly GamblingConfigService _gss;
public readonly ConcurrentHashSet<ulong> _generationChannels = new ConcurrentHashSet<ulong>();
public readonly ConcurrentHashSet<ulong> _generationChannels = new();
//channelId/last generation
public ConcurrentDictionary<ulong, DateTime> LastGenerations { get; } = new ConcurrentDictionary<ulong, DateTime>();
private readonly SemaphoreSlim pickLock = new SemaphoreSlim(1, 1);
public ConcurrentDictionary<ulong, DateTime> LastGenerations { get; } = new();
private readonly SemaphoreSlim pickLock = new(1, 1);
public PlantPickService(DbService db, CommandHandler cmd, IBotStrings strings,
IDataCache cache, FontProvider fonts, ICurrencyService cs,
@@ -172,7 +172,7 @@ public class PlantPickService : INService
if (msg is null || msg.Author.IsBot)
return Task.CompletedTask;
if (!(imsg.Channel is ITextChannel channel))
if (imsg.Channel is not ITextChannel channel)
return Task.CompletedTask;
if (!_generationChannels.Contains(channel.Id))
@@ -189,7 +189,7 @@ public class PlantPickService : INService
if (DateTime.UtcNow - TimeSpan.FromSeconds(config.Generation.GenCooldown) < lastGeneration) //recently generated in this channel, don't generate again
return;
var num = rng.Next(1, 101) + config.Generation.Chance * 100;
var num = rng.Next(1, 101) + (config.Generation.Chance * 100);
if (num > 100 && LastGenerations.TryUpdate(channel.Id, DateTime.UtcNow, lastGeneration))
{
var dropAmount = config.Generation.MinAmount;

View File

@@ -107,7 +107,7 @@ public class WaifuService : INService
.Count();
return (int) Math.Ceiling(waifu.Price * 1.25f) +
(divorces + affs + 2) * settings.Waifu.Multipliers.WaifuReset;
((divorces + affs + 2) * settings.Waifu.Multipliers.WaifuReset);
}
}
@@ -199,7 +199,7 @@ public class WaifuService : INService
{
var oldClaimer = w.Claimer;
w.Claimer = uow.GetOrCreateUser(user);
w.Price = amount + amount / 4;
w.Price = amount + (amount / 4);
result = WaifuClaimResult.Success;
uow.WaifuUpdates.Add(new()

View File

@@ -56,7 +56,7 @@ public partial class Gambling
{
var entry = theseEntries[i];
embed.AddField(
$"#{curPage * 9 + i + 1} - {entry.Price}{CurrencySign}",
$"#{(curPage * 9) + i + 1} - {entry.Price}{CurrencySign}",
EntryToString(entry),
true);
}

View File

@@ -20,7 +20,7 @@ public partial class Gambling
private static long _totalBet;
private static long _totalPaidOut;
private static readonly HashSet<ulong> _runningUsers = new HashSet<ulong>();
private static readonly HashSet<ulong> _runningUsers = new();
//here is a payout chart
//https://lh6.googleusercontent.com/-i1hjAJy_kN4/UswKxmhrbPI/AAAAAAAAB1U/82wq_4ZZc-Y/DE6B0895-6FC1-48BE-AC4F-14D1B91AB75B.jpg
@@ -43,7 +43,7 @@ public partial class Gambling
{
public const int MaxValue = 5;
static readonly List<Func<int[], int>> _winningCombos = new List<Func<int[], int>>()
static readonly List<Func<int[], int>> _winningCombos = new()
{
//three flowers
arr => arr.All(a=>a==MaxValue) ? 30 : 0,
@@ -218,7 +218,7 @@ public partial class Gambling
{
using (var img = Image.Load(_images.SlotEmojis[numbers[i]]))
{
bgImage.Mutate(x => x.DrawImage(img, new Point(148 + 105 * i, 217), 1f));
bgImage.Mutate(x => x.DrawImage(img, new Point(148 + (105 * i), 217), 1f));
}
}

View File

@@ -222,7 +222,7 @@ public partial class Gambling
foreach (var w in waifus)
{
var j = i++;
embed.AddField("#" + (page * 9 + j + 1) + " - " + w.Price + CurrencySign, w.ToString(), false);
embed.AddField("#" + ((page * 9) + j + 1) + " - " + w.Price + CurrencySign, w.ToString(), false);
}
await ctx.Channel.EmbedAsync(embed);

View File

@@ -41,8 +41,8 @@ public sealed class AcrophobiaGame : IDisposable
public Phase CurrentPhase { get; private set; } = Phase.Submission;
public ImmutableArray<char> StartingLetters { get; private set; }
private readonly Dictionary<AcrophobiaUser, int> submissions = new Dictionary<AcrophobiaUser, int>();
private readonly SemaphoreSlim locker = new SemaphoreSlim(1, 1);
private readonly Dictionary<AcrophobiaUser, int> submissions = new();
private readonly SemaphoreSlim locker = new(1, 1);
public Options Opts { get; }
private readonly NadekoRandom _rng;
@@ -51,7 +51,7 @@ public sealed class AcrophobiaGame : IDisposable
public event Func<string, Task> OnUserVoted = delegate { return Task.CompletedTask; };
public event Func<AcrophobiaGame, ImmutableArray<KeyValuePair<AcrophobiaUser, int>>, Task> OnEnded = delegate { return Task.CompletedTask; };
private readonly HashSet<ulong> _usersWhoVoted = new HashSet<ulong>();
private readonly HashSet<ulong> _usersWhoVoted = new();
public AcrophobiaGame(Options options)
{

View File

@@ -4,7 +4,7 @@ namespace NadekoBot.Modules.Games.Common.ChatterBot;
public class ChatterBotSession : IChatterBotSession
{
private static NadekoRandom Rng { get; } = new NadekoRandom();
private static NadekoRandom Rng { get; } = new();
private readonly string _chatterBotId;
private readonly IHttpClientFactory _httpFactory;

View File

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

View File

@@ -10,20 +10,20 @@ public sealed partial class GamesConfig : ICloneable<GamesConfig>
public int Version { get; set; }
[Comment("Hangman related settings (.hangman command)")]
public HangmanConfig Hangman { get; set; } = new HangmanConfig()
public HangmanConfig Hangman { get; set; } = new()
{
CurrencyReward = 0
};
[Comment("Trivia related settings (.t command)")]
public TriviaConfig Trivia { get; set; } = new TriviaConfig()
public TriviaConfig Trivia { get; set; } = new()
{
CurrencyReward = 0,
MinimumWinReq = 1,
};
[Comment("List of responses for the .8ball command. A random one will be selected every time")]
public List<string> EightBallResponses { get; set; } = new List<string>()
public List<string> EightBallResponses { get; set; } = new()
{
"Most definitely yes.",
"For sure.",
@@ -51,16 +51,16 @@ public sealed partial class GamesConfig : ICloneable<GamesConfig>
};
[Comment("List of animals which will be used for the animal race game (.race)")]
public List<RaceAnimal> RaceAnimals { get; set; } = new List<RaceAnimal>()
public List<RaceAnimal> RaceAnimals { get; set; } = new()
{
new RaceAnimal { Icon = "🐼", Name = "Panda" },
new RaceAnimal { Icon = "🐻", Name = "Bear" },
new RaceAnimal { Icon = "🐧", Name = "Pengu" },
new RaceAnimal { Icon = "🐨", Name = "Koala" },
new RaceAnimal { Icon = "🐬", Name = "Dolphin" },
new RaceAnimal { Icon = "🐞", Name = "Ladybird" },
new RaceAnimal { Icon = "🦀", Name = "Crab" },
new RaceAnimal { Icon = "🦄", Name = "Unicorn" }
new() { Icon = "🐼", Name = "Panda" },
new() { Icon = "🐻", Name = "Bear" },
new() { Icon = "🐧", Name = "Pengu" },
new() { Icon = "🐨", Name = "Koala" },
new() { Icon = "🐬", Name = "Dolphin" },
new() { Icon = "🐞", Name = "Ladybird" },
new() { Icon = "🦀", Name = "Crab" },
new() { Icon = "🦄", Name = "Unicorn" }
};
}

View File

@@ -36,8 +36,8 @@ public class GirlRating
const int miny = 385;
const int length = 345;
var pointx = (int)(minx + length * (Hot / 10));
var pointy = (int)(miny - length * ((Crazy - 4) / 6));
var pointx = (int)(minx + (length * (Hot / 10)));
var pointy = (int)(miny - (length * ((Crazy - 4) / 6)));
using (var pointImg = Image.Load(_images.RategirlDot))
{

View File

@@ -40,7 +40,7 @@ public sealed class HangmanGame
}
public State GetState(GuessResult guessResult = GuessResult.NoAction)
=> new State(_incorrect.Count,
=> new(_incorrect.Count,
CurrentPhase,
CurrentPhase == Phase.Ended
? _word
@@ -64,7 +64,7 @@ public sealed class HangmanGame
else
output[i*2] = '_';
output[i * 2 + 1] = ' ';
output[(i * 2) + 1] = ' ';
}
return new(output);

View File

@@ -21,10 +21,10 @@ public sealed class NunchiGame : IDisposable
public event Func<NunchiGame, (ulong Id, string Name)?, Task> OnRoundEnded; // tuple of the user who failed
public event Func<NunchiGame, string, Task> OnGameEnded; // name of the user who won
private readonly SemaphoreSlim _locker = new SemaphoreSlim(1, 1);
private readonly SemaphoreSlim _locker = new(1, 1);
private HashSet<(ulong Id, string Name)> _participants = new HashSet<(ulong Id, string Name)>();
private HashSet<(ulong Id, string Name)> _passed = new HashSet<(ulong Id, string Name)>();
private HashSet<(ulong Id, string Name)> _participants = new();
private readonly HashSet<(ulong Id, string Name)> _passed = new();
public ImmutableArray<(ulong Id, string Name)> Participants => _participants.ToImmutableArray();
public int ParticipantCount => _participants.Count;

View File

@@ -9,7 +9,7 @@ public class PollRunner
public event Func<IUserMessage, IGuildUser, Task> OnVoted;
private readonly SemaphoreSlim _locker = new SemaphoreSlim(1, 1);
private readonly SemaphoreSlim _locker = new(1, 1);
public PollRunner(DbService db, Poll poll)
{

View File

@@ -74,7 +74,7 @@ public class TicTacToe
{
for (var j = 0; j < _state.GetLength(1); j++)
{
sb.Append(_state[i, j] is null ? _numbers[i * 3 + j] : GetIcon(_state[i, j]));
sb.Append(_state[i, j] is null ? _numbers[(i * 3) + j] : GetIcon(_state[i, j]));
if (j < _state.GetLength(1) - 1)
sb.Append("┃");
}

View File

@@ -4,7 +4,7 @@ namespace NadekoBot.Modules.Games.Common.Trivia;
public class TriviaGame
{
private readonly SemaphoreSlim _guessLock = new SemaphoreSlim(1, 1);
private readonly SemaphoreSlim _guessLock = new(1, 1);
private readonly IDataCache _cache;
private readonly IBotStrings _strings;
private readonly DiscordSocketClient _client;
@@ -18,9 +18,9 @@ public class TriviaGame
private CancellationTokenSource _triviaCancelSource;
public TriviaQuestion CurrentQuestion { get; private set; }
public HashSet<TriviaQuestion> OldQuestions { get; } = new HashSet<TriviaQuestion>();
public HashSet<TriviaQuestion> OldQuestions { get; } = new();
public ConcurrentDictionary<IGuildUser, int> Users { get; } = new ConcurrentDictionary<IGuildUser, int>();
public ConcurrentDictionary<IGuildUser, int> Users { get; } = new();
public bool GameActive { get; private set; }
public bool ShouldStopGame { get; private set; }

View File

@@ -6,11 +6,12 @@ namespace NadekoBot.Modules.Games.Common.Trivia;
public class TriviaQuestion
{
//represents the min size to judge levDistance with
private static readonly HashSet<Tuple<int, int>> strictness = new HashSet<Tuple<int, int>> {
new Tuple<int, int>(9, 0),
new Tuple<int, int>(14, 1),
new Tuple<int, int>(19, 2),
new Tuple<int, int>(22, 3),
private static readonly HashSet<Tuple<int, int>> strictness = new()
{
new(9, 0),
new(14, 1),
new(19, 2),
new(22, 3),
};
public const int maxStringLength = 22;

View File

@@ -5,7 +5,7 @@ public class TriviaQuestionPool
private readonly IDataCache _cache;
private readonly int maxPokemonId;
private readonly NadekoRandom _rng = new NadekoRandom();
private readonly NadekoRandom _rng = new();
private TriviaQuestion[] Pool => _cache.LocalData.TriviaQuestions;
private IReadOnlyDictionary<int, string> Map => _cache.LocalData.PokemonMap;

View File

@@ -11,7 +11,7 @@ public partial class Games : NadekoModule<GamesService>
{
private readonly IImageCache _images;
private readonly IHttpClientFactory _httpFactory;
private readonly Random _rng = new Random();
private readonly Random _rng = new();
public Games(IDataCache data, IHttpClientFactory factory)
{
@@ -79,7 +79,7 @@ public partial class Games : NadekoModule<GamesService>
private double NextDouble(double x, double y)
{
return _rng.NextDouble() * (y - x) + x;
return (_rng.NextDouble() * (y - x)) + x;
}
private GirlRating GetGirl(ulong uid)
@@ -102,19 +102,19 @@ public partial class Games : NadekoModule<GamesService>
else if (roll < 750)
{
hot = NextDouble(5, 8);
crazy = NextDouble(4, .6 * hot + 4);
crazy = NextDouble(4, (.6 * hot) + 4);
advice = ratings.Fun;
}
else if (roll < 900)
{
hot = NextDouble(5, 10);
crazy = NextDouble(.61 * hot + 4, 10);
crazy = NextDouble((.61 * hot) + 4, 10);
advice = ratings.Dan;
}
else if (roll < 951)
{
hot = NextDouble(8, 10);
crazy = NextDouble(7, .6 * hot + 4);
crazy = NextDouble(7, (.6 * hot) + 4);
advice = ratings.Dat;
}
else if (roll < 990)

View File

@@ -96,7 +96,7 @@ public class ChatterBotService : IEarlyBehavior
public async Task<bool> RunBehavior(IGuild guild, IUserMessage usrMsg)
{
if (!(guild is SocketGuild sg))
if (guild is not SocketGuild sg)
return false;
try
{
@@ -113,7 +113,7 @@ public class ChatterBotService : IEarlyBehavior
if (pc.Verbose)
{
var returnMsg = _strings.GetText(strs.perm_prevent(index + 1,
Format.Bold(pc.Permissions[index].GetCommand(_cmd.GetPrefix(guild), (SocketGuild)guild))));
Format.Bold(pc.Permissions[index].GetCommand(_cmd.GetPrefix(sg), sg))));
try { await usrMsg.Channel.SendErrorAsync(_eb, returnMsg).ConfigureAwait(false); } catch { }
Log.Information(returnMsg);

View File

@@ -7,7 +7,7 @@ public sealed class GamesConfigService : ConfigServiceBase<GamesConfig>
{
public override string Name { get; } = "games";
private const string FilePath = "data/games.yml";
private static TypedKey<GamesConfig> changeKey = new TypedKey<GamesConfig>("config.games.updated");
private static readonly TypedKey<GamesConfig> changeKey = new("config.games.updated");
public GamesConfigService(IConfigSeria serializer, IPubSub pubSub)
: base(FilePath, serializer, pubSub, changeKey)

View File

@@ -11,7 +11,7 @@ public class GamesService : INService
{
private readonly GamesConfigService _gamesConfig;
public ConcurrentDictionary<ulong, GirlRating> GirlRatings { get; } = new ConcurrentDictionary<ulong, GirlRating>();
public ConcurrentDictionary<ulong, GirlRating> GirlRatings { get; } = new();
public IReadOnlyList<string> EightBallResponses => _gamesConfig.Data.EightBallResponses;
@@ -22,14 +22,14 @@ public class GamesService : INService
private const string TypingArticlesPath = "data/typing_articles3.json";
public List<TypingArticle> TypingArticles { get; } = new List<TypingArticle>();
public List<TypingArticle> TypingArticles { get; } = new();
//channelId, game
public ConcurrentDictionary<ulong, AcrophobiaGame> AcrophobiaGames { get; } = new ConcurrentDictionary<ulong, AcrophobiaGame>();
public ConcurrentDictionary<ulong, TriviaGame> RunningTrivias { get; } = new ConcurrentDictionary<ulong, TriviaGame>();
public Dictionary<ulong, TicTacToe> TicTacToeGames { get; } = new Dictionary<ulong, TicTacToe>();
public ConcurrentDictionary<ulong, TypingGame> RunningContests { get; } = new ConcurrentDictionary<ulong, TypingGame>();
public ConcurrentDictionary<ulong, NunchiGame> NunchiGames { get; } = new ConcurrentDictionary<ulong, NunchiGame>();
public ConcurrentDictionary<ulong, AcrophobiaGame> AcrophobiaGames { get; } = new();
public ConcurrentDictionary<ulong, TriviaGame> RunningTrivias { get; } = new();
public Dictionary<ulong, TicTacToe> TicTacToeGames { get; } = new();
public ConcurrentDictionary<ulong, TypingGame> RunningContests { get; } = new();
public ConcurrentDictionary<ulong, NunchiGame> NunchiGames { get; } = new();
public AsyncLazy<RatingTexts> Ratings { get; }

View File

@@ -8,7 +8,7 @@ namespace NadekoBot.Modules.Games.Services;
public class PollService : IEarlyBehavior
{
public ConcurrentDictionary<ulong, PollRunner> ActivePolls { get; } = new ConcurrentDictionary<ulong, PollRunner>();
public ConcurrentDictionary<ulong, PollRunner> ActivePolls { get; } = new();
public int Priority => 5;

View File

@@ -8,7 +8,7 @@ public partial class Games
[Group]
public class TicTacToeCommands : NadekoSubmodule<GamesService>
{
private readonly SemaphoreSlim _sem = new SemaphoreSlim(1, 1);
private readonly SemaphoreSlim _sem = new(1, 1);
private readonly DiscordSocketClient _client;
public TicTacToeCommands(DiscordSocketClient client)

View File

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

View File

@@ -12,7 +12,7 @@ public sealed class MusicPlayer : IMusicPlayer
{
private delegate void AdjustVolumeDelegate(Span<byte> data, float volume);
private AdjustVolumeDelegate AdjustVolume;
private readonly AdjustVolumeDelegate AdjustVolume;
private readonly VoiceClient _vc;
public bool IsKilled { get; private set; }
@@ -369,7 +369,7 @@ public sealed class MusicPlayer : IMusicPlayer
for (var i = 0; i < samples.Length; i++)
{
ref var sample = ref samples[i];
sample = (float) (sample * volume);
sample = sample * volume;
}
}

View File

@@ -55,7 +55,7 @@ public sealed partial class MusicQueue : IMusicQueue
}
}
private readonly object locker = new object();
private readonly object locker = new();
public MusicQueue()
{

View File

@@ -9,7 +9,7 @@ public sealed class SimpleTrackInfo : ITrackInfo
public TimeSpan Duration { get; }
public MusicPlatform Platform { get; }
public string? StreamUrl { get; }
public ValueTask<string?> GetStreamUrl() => new ValueTask<string?>(StreamUrl);
public ValueTask<string?> GetStreamUrl() => new(StreamUrl);
public SimpleTrackInfo(string title, string url, string thumbnail, TimeSpan duration,
MusicPlatform platform, string streamUrl)

View File

@@ -4,10 +4,10 @@ namespace NadekoBot.Modules.Music.Resolvers;
public class RadioResolver : IRadioResolver
{
private readonly Regex plsRegex = new Regex("File1=(?<url>.*?)\\n", RegexOptions.Compiled);
private readonly Regex m3uRegex = new Regex("(?<url>^[^#].*)", RegexOptions.Compiled | RegexOptions.Multiline);
private readonly Regex asxRegex = new Regex("<ref href=\"(?<url>.*?)\"", RegexOptions.Compiled);
private readonly Regex xspfRegex = new Regex("<location>(?<url>.*?)</location>", RegexOptions.Compiled);
private readonly Regex plsRegex = new("File1=(?<url>.*?)\\n", RegexOptions.Compiled);
private readonly Regex m3uRegex = new("(?<url>^[^#].*)", RegexOptions.Compiled | RegexOptions.Multiline);
private readonly Regex asxRegex = new("<ref href=\"(?<url>.*?)\"", RegexOptions.Compiled);
private readonly Regex xspfRegex = new("<location>(?<url>.*?)</location>", RegexOptions.Compiled);
public RadioResolver()
{

View File

@@ -10,7 +10,7 @@ public sealed class YtdlYoutubeResolver : IYoutubeResolver
{"ss", "m\\:ss", "mm\\:ss", "h\\:mm\\:ss", "hh\\:mm\\:ss", "hhh\\:mm\\:ss"};
public Regex YtVideoIdRegex { get; }
= new Regex(
= new(
@"(?:youtube\.com\/\S*(?:(?:\/e(?:mbed))?\/|watch\?(?:\S*?&?v\=))|youtu\.be\/)(?<id>[a-zA-Z0-9_-]{6,11})",
RegexOptions.Compiled
);
@@ -21,7 +21,7 @@ public sealed class YtdlYoutubeResolver : IYoutubeResolver
private readonly YtdlOperation _ytdlIdOperation;
private readonly YtdlOperation _ytdlSearchOperation;
private IGoogleApiService _google;
private readonly IGoogleApiService _google;
public YtdlYoutubeResolver(ITrackCacher trackCacher, IGoogleApiService google)
{
@@ -136,7 +136,7 @@ public sealed class YtdlYoutubeResolver : IYoutubeResolver
async () => await ExtractNewStreamUrlAsync(id)
);
private static readonly Regex expiryRegex = new Regex(@"(?:[\?\&]expire\=(?<timestamp>\d+))");
private static readonly Regex expiryRegex = new(@"(?:[\?\&]expire\=(?<timestamp>\d+))");
private static TimeSpan GetExpiry(string streamUrl)
{
var match = expiryRegex.Match(streamUrl);
@@ -205,8 +205,7 @@ public sealed class YtdlYoutubeResolver : IYoutubeResolver
);
private static readonly Regex _simplePlaylistRegex
= new Regex(@"&list=(?<id>[\w\-]{12,})", RegexOptions.Compiled);
private static readonly Regex _simplePlaylistRegex = new(@"&list=(?<id>[\w\-]{12,})", RegexOptions.Compiled);
public async IAsyncEnumerable<ITrackInfo> ResolveTracksByPlaylistIdAsync(string playlistId)
{

View File

@@ -36,7 +36,7 @@ public sealed partial class Music : NadekoModule<IMusicService>
return true;
}
private static readonly SemaphoreSlim voiceChannelLock = new SemaphoreSlim(1, 1);
private static readonly SemaphoreSlim voiceChannelLock = new(1, 1);
private async Task EnsureBotInVoiceChannelAsync(ulong voiceChannelId, IGuildUser botUser = null)
{
botUser ??= await ctx.Guild.GetCurrentUserAsync();
@@ -253,7 +253,7 @@ public sealed partial class Music : NadekoModule<IMusicService>
return;
}
await ListQueue(mp.CurrentIndex / LQ_ITEMS_PER_PAGE + 1);
await ListQueue((mp.CurrentIndex / LQ_ITEMS_PER_PAGE) + 1);
}
// list queue, specify page
@@ -319,7 +319,7 @@ public sealed partial class Music : NadekoModule<IMusicService>
desc = add + "\n" + desc;
var embed = _eb.Create()
.WithAuthor(GetText(strs.player_queue(curPage + 1, tracks.Count / LQ_ITEMS_PER_PAGE + 1)),
.WithAuthor(GetText(strs.player_queue(curPage + 1, (tracks.Count / LQ_ITEMS_PER_PAGE) + 1)),
MusicIconUrl)
.WithDescription(desc)
.WithFooter($" {mp.PrettyVolume()} | 🎶 {tracks.Count} | ⌛ {mp.PrettyTotalTime()} ")

View File

@@ -158,7 +158,7 @@ public sealed partial class Music
}
private static readonly SemaphoreSlim _playlistLock = new SemaphoreSlim(1, 1);
private static readonly SemaphoreSlim _playlistLock = new(1, 1);
[NadekoCommand, Aliases]
[RequireContext(ContextType.Guild)]

View File

@@ -8,8 +8,8 @@ public sealed class AyuVoiceStateService : INService
// public delegate Task VoiceProxyUpdatedDelegate(ulong guildId, IVoiceProxy proxy);
// public event VoiceProxyUpdatedDelegate OnVoiceProxyUpdate = delegate { return Task.CompletedTask; };
private readonly ConcurrentDictionary<ulong, IVoiceProxy> _voiceProxies = new ConcurrentDictionary<ulong, IVoiceProxy>();
private readonly ConcurrentDictionary<ulong, SemaphoreSlim> _voiceGatewayLocks = new ConcurrentDictionary<ulong, SemaphoreSlim>();
private readonly ConcurrentDictionary<ulong, IVoiceProxy> _voiceProxies = new();
private readonly ConcurrentDictionary<ulong, SemaphoreSlim> _voiceGatewayLocks = new();
private readonly DiscordSocketClient _client;
private readonly MethodInfo _sendVoiceStateUpdateMethodInfo;
@@ -167,7 +167,7 @@ public sealed class AyuVoiceStateService : INService
var voiceServerData = await voiceServerUpdatedSource.Task;
VoiceGateway CreateVoiceGatewayLocal() =>
new VoiceGateway(
new(
guildId,
_currentUserId,
session,

View File

@@ -13,5 +13,5 @@ public class DapiImageObject : IImageData
public string Rating { get; set; }
public ImageData ToCachedImageData(Booru type)
=> new ImageData(this.FileUrl, type, this.Tags?.Split(' ') ?? this.TagString?.Split(' '), Score.ToString() ?? Rating);
=> new(this.FileUrl, type, this.Tags?.Split(' ') ?? this.TagString?.Split(' '), Score.ToString() ?? Rating);
}

View File

@@ -8,7 +8,7 @@ public abstract class ImageDownloader<T> : IImageDownloader
{
protected readonly HttpClient _http;
protected JsonSerializerOptions _serializerOptions = new JsonSerializerOptions()
protected JsonSerializerOptions _serializerOptions = new()
{
PropertyNameCaseInsensitive = true,
NumberHandling = JsonNumberHandling.WriteAsString | JsonNumberHandling.AllowReadingFromString,

View File

@@ -9,6 +9,5 @@ public class SafebooruElement : IImageData
public string FileUrl => $"https://safebooru.org/images/{Directory}/{Image}";
public string Rating { get; set; }
public string Tags { get; set; }
public ImageData ToCachedImageData(Booru type)
=> new ImageData(FileUrl, Booru.Safebooru, this.Tags.Split(' '), Rating);
public ImageData ToCachedImageData(Booru type) => new(FileUrl, Booru.Safebooru, this.Tags.Split(' '), Rating);
}

View File

@@ -7,7 +7,7 @@ namespace NadekoBot.Modules.Nsfw;
[NoPublicBot]
public class NSFW : NadekoModule<ISearchImagesService>
{
private static readonly ConcurrentHashSet<ulong> _hentaiBombBlacklist = new ConcurrentHashSet<ulong>();
private static readonly ConcurrentHashSet<ulong> _hentaiBombBlacklist = new();
private readonly IHttpClientFactory _httpFactory;
private readonly NadekoRandom _rng;

View File

@@ -14,7 +14,7 @@ public record UrlReply
public string Url { get; init; }
public string Rating { get; init; }
public string Provider { get; init; }
public List<string> Tags { get; } = new List<string>();
public List<string> Tags { get; } = new();
}
public class SearchImagesService : ISearchImagesService, INService
@@ -26,9 +26,9 @@ public class SearchImagesService : ISearchImagesService, INService
private readonly DbService _db;
private ConcurrentDictionary<ulong, HashSet<string>> BlacklistedTags { get; }
public ConcurrentDictionary<ulong, Timer> AutoHentaiTimers { get; } = new ConcurrentDictionary<ulong, Timer>();
public ConcurrentDictionary<ulong, Timer> AutoBoobTimers { get; } = new ConcurrentDictionary<ulong, Timer>();
public ConcurrentDictionary<ulong, Timer> AutoButtTimers { get; } = new ConcurrentDictionary<ulong, Timer>();
public ConcurrentDictionary<ulong, Timer> AutoHentaiTimers { get; } = new();
public ConcurrentDictionary<ulong, Timer> AutoBoobTimers { get; } = new();
public ConcurrentDictionary<ulong, Timer> AutoButtTimers { get; } = new();
public SearchImagesService(DbService db,
IHttpClientFactory http,
@@ -219,7 +219,7 @@ public class SearchImagesService : ISearchImagesService, INService
}
}
private readonly object taglock = new object();
private readonly object taglock = new();
public ValueTask<bool> ToggleBlacklistTag(ulong guildId, string tag)
{
lock (taglock)

View File

@@ -31,10 +31,10 @@ public static class PermissionExtensions
//false = applicable, not allowed
public static bool? CheckPermission(this Permissionv2 perm, IUserMessage message, string commandName, string moduleName)
{
if (!(perm.SecondaryTarget == SecondaryPermissionType.Command &&
perm.SecondaryTargetName.ToLowerInvariant() == commandName.ToLowerInvariant() ||
perm.SecondaryTarget == SecondaryPermissionType.Module &&
perm.SecondaryTargetName.ToLowerInvariant() == moduleName.ToLowerInvariant() ||
if (!((perm.SecondaryTarget == SecondaryPermissionType.Command &&
perm.SecondaryTargetName.ToLowerInvariant() == commandName.ToLowerInvariant()) ||
(perm.SecondaryTarget == SecondaryPermissionType.Module &&
perm.SecondaryTargetName.ToLowerInvariant() == moduleName.ToLowerInvariant()) ||
perm.SecondaryTarget == SecondaryPermissionType.AllModules))
return null;

View File

@@ -5,7 +5,7 @@ namespace NadekoBot.Modules.Permissions.Common;
public class PermissionsCollection<T> : IndexedCollection<T> where T : class, IIndexed
{
private readonly object _localLocker = new object();
private readonly object _localLocker = new();
public PermissionsCollection(IEnumerable<T> source) : base(source)
{
}

View File

@@ -13,7 +13,7 @@ public sealed class BlacklistService : IEarlyBehavior
private IReadOnlyList<BlacklistEntry> _blacklist;
public int Priority => int.MaxValue;
private readonly TypedKey<BlacklistEntry[]> blPubKey = new TypedKey<BlacklistEntry[]>("blacklist.reload");
private readonly TypedKey<BlacklistEntry[]> blPubKey = new("blacklist.reload");
public BlacklistService(DbService db, IPubSub pubSub, IBotCredentials creds)
{
_db = db;

View File

@@ -7,7 +7,7 @@ namespace NadekoBot.Modules.Permissions.Services;
public class CmdCdService : ILateBlocker, INService
{
public ConcurrentDictionary<ulong, ConcurrentHashSet<CommandCooldown>> CommandCooldowns { get; }
public ConcurrentDictionary<ulong, ConcurrentHashSet<ActiveCooldown>> ActiveCooldowns { get; } = new ConcurrentDictionary<ulong, ConcurrentHashSet<ActiveCooldown>>();
public ConcurrentDictionary<ulong, ConcurrentHashSet<ActiveCooldown>> ActiveCooldowns { get; } = new();
public int Priority { get; } = 0;

View File

@@ -113,7 +113,7 @@ public sealed class FilterService : IEarlyBehavior
public async Task<bool> RunBehavior(IGuild guild, IUserMessage msg)
{
if (!(msg.Author is IGuildUser gu) || gu.GuildPermissions.Administrator)
if (msg.Author is not IGuildUser gu || gu.GuildPermissions.Administrator)
return false;
var results = await Task.WhenAll(

View File

@@ -16,8 +16,7 @@ public class PermissionService : ILateBlocker, INService
private readonly IEmbedBuilderService _eb;
//guildid, root permission
public ConcurrentDictionary<ulong, PermissionCache> Cache { get; } =
new ConcurrentDictionary<ulong, PermissionCache>();
public ConcurrentDictionary<ulong, PermissionCache> Cache { get; } = new();
public PermissionService(DiscordSocketClient client,
DbService db,
@@ -135,7 +134,7 @@ public class PermissionService : ILateBlocker, INService
if (moduleName == nameof(Permissions))
{
if (!(user is IGuildUser guildUser))
if (user is not IGuildUser guildUser)
return true;
if (guildUser.GuildPermissions.Administrator)

View File

@@ -4,7 +4,7 @@ namespace SystemTextJsonSamples;
public class LowerCaseNamingPolicy : JsonNamingPolicy
{
public static LowerCaseNamingPolicy Default = new LowerCaseNamingPolicy();
public static LowerCaseNamingPolicy Default = new();
public override string ConvertName(string name) =>
name.ToLower();

View File

@@ -15,5 +15,5 @@ public class StreamData
public string StreamUrl { get; set; }
public string AvatarUrl { get; set; }
public StreamDataKey CreateKey() => new StreamDataKey(StreamType, UniqueName.ToLower());
public StreamDataKey CreateKey() => new(StreamType, UniqueName.ToLower());
}

View File

@@ -9,7 +9,7 @@ public class PicartoProvider : Provider
{
private readonly IHttpClientFactory _httpClientFactory;
private static Regex Regex { get; } = new Regex(@"picarto.tv/(?<name>.+[^/])/?",
private static Regex Regex { get; } = new(@"picarto.tv/(?<name>.+[^/])/?",
RegexOptions.Compiled | RegexOptions.IgnoreCase);
public override FollowedStream.FType Platform => FollowedStream.FType.Picarto;

View File

@@ -51,8 +51,7 @@ public abstract class Provider
/// <summary>
/// When was the first time the stream continually had errors while being retrieved
/// </summary>
protected readonly ConcurrentDictionary<string, DateTime> _failingStreams =
new ConcurrentDictionary<string, DateTime>();
protected readonly ConcurrentDictionary<string, DateTime> _failingStreams = new();
public void ClearErrorsFor(string login)
=> _failingStreams.TryRemove(login, out _);

View File

@@ -9,7 +9,7 @@ public class TwitchProvider : Provider
{
private readonly IHttpClientFactory _httpClientFactory;
private static Regex Regex { get; } = new Regex(@"twitch.tv/(?<name>.+[^/])/?",
private static Regex Regex { get; } = new(@"twitch.tv/(?<name>.+[^/])/?",
RegexOptions.Compiled | RegexOptions.IgnoreCase);
public override FollowedStream.FType Platform => FollowedStream.FType.Twitch;

View File

@@ -9,7 +9,7 @@ public partial class Searches
public class FeedCommands : NadekoSubmodule<FeedsService>
{
private static readonly Regex YtChannelRegex =
new Regex(@"youtube\.com\/(?:c\/|channel\/|user\/)?(?<channelid>[a-zA-Z0-9\-]{1,})");
new(@"youtube\.com\/(?:c\/|channel\/|user\/)?(?<channelid>[a-zA-Z0-9\-]{1,})");
[NadekoCommand, Aliases]
[RequireContext(ContextType.Guild)]
@@ -97,7 +97,7 @@ public partial class Searches
var i = 0;
var fs = string.Join("\n", feeds.Skip(cur * 10)
.Take(10)
.Select(x => $"`{cur * 10 + ++i}.` <#{x.ChannelId}> {x.Url}"));
.Select(x => $"`{(cur * 10) + ++i}.` <#{x.ChannelId}> {x.Url}"));
return embed.WithDescription(fs);

View File

@@ -200,16 +200,16 @@ public partial class Searches
double totalHits;
if (mode == 0)
{
hitPoints = play.Count50 * 50 +
play.Count100 * 100 +
play.Count300 * 300;
hitPoints = (play.Count50 * 50) +
(play.Count100 * 100) +
(play.Count300 * 300);
totalHits = play.Count50 + play.Count100 +
play.Count300 + play.Countmiss;
totalHits *= 300;
}
else if (mode == 1)
{
hitPoints = play.Countmiss * 0 + play.Count100 * 0.5 + play.Count300;
hitPoints = (play.Countmiss * 0) + (play.Count100 * 0.5) + play.Count300;
totalHits = (play.Countmiss + play.Count100 + play.Count300) * 300;
hitPoints *= 300;
}
@@ -221,10 +221,10 @@ public partial class Searches
}
else
{
hitPoints = play.Count50 * 50 +
play.Count100 * 100 +
play.Countkatu * 200 +
(play.Count300 + play.Countgeki) * 300;
hitPoints = (play.Count50 * 50) +
(play.Count100 * 100) +
(play.Countkatu * 200) +
((play.Count300 + play.Countgeki) * 300);
totalHits = (play.Countmiss + play.Count50 + play.Count100 +
play.Countkatu + play.Count300 + play.Countgeki) * 300;

View File

@@ -84,7 +84,7 @@ public partial class Searches
{
var character = tempList[i];
sb.AppendLine($"#{i + 1 + curPage * 9,-4}{character.Name,-23}{ShortLeagueName(character.League),-10}{character.Class,-13}{character.Level,-3}");
sb.AppendLine($"#{i + 1 + (curPage * 9),-4}{character.Name,-23}{ShortLeagueName(character.League),-10}{character.Class,-13}{character.Level,-3}");
}
sb.AppendLine("```");
@@ -212,7 +212,7 @@ public partial class Searches
}
}
private Dictionary<string, string> currencyDictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
private Dictionary<string, string> currencyDictionary = new(StringComparer.OrdinalIgnoreCase)
{
{"Chaos Orb", "Chaos Orb" },
{"Orb of Alchemy", "Orb of Alchemy" },

View File

@@ -267,7 +267,7 @@ public partial class Searches : NadekoModule<SearchesService>
public string ResultUrl { get; set; }
}
private static readonly ConcurrentDictionary<string, string> cachedShortenedLinks = new ConcurrentDictionary<string, string>();
private static readonly ConcurrentDictionary<string, string> cachedShortenedLinks = new();
[NadekoCommand, Aliases]
public async Task Shorten([Leftover] string query)
@@ -491,7 +491,7 @@ public partial class Searches : NadekoModule<SearchesService>
var data = JsonConvert.DeserializeObject<DefineModel>(res);
var datas = data.Results
.Where(x => !(x.Senses is null) && x.Senses.Count > 0 && !(x.Senses[0].Definition is null))
.Where(x => x.Senses is not null && x.Senses.Count > 0 && x.Senses[0].Definition is not null)
.Select(x => (Sense: x.Senses[0], x.PartOfSpeech));
if (!datas.Any())
@@ -611,10 +611,10 @@ public partial class Searches : NadekoModule<SearchesService>
{
var x = i * 50;
img.Mutate(m => m.FillPolygon(colorObjects[i], new PointF[] {
new PointF(x, 0),
new PointF(x + 50, 0),
new PointF(x + 50, 50),
new PointF(x, 50)
new(x, 0),
new(x + 50, 0),
new(x + 50, 50),
new(x, 50)
}));
}

View File

@@ -53,7 +53,7 @@ public class CryptoService : INService
return (crypto, null);
}
private readonly SemaphoreSlim getCryptoLock = new SemaphoreSlim(1, 1);
private readonly SemaphoreSlim getCryptoLock = new(1, 1);
public async Task<List<CryptoResponseData>> CryptoData()
{
await getCryptoLock.WaitAsync();

View File

@@ -12,8 +12,7 @@ public class FeedsService : INService
private readonly DiscordSocketClient _client;
private readonly IEmbedBuilderService _eb;
private readonly ConcurrentDictionary<string, DateTime> _lastPosts =
new ConcurrentDictionary<string, DateTime>();
private readonly ConcurrentDictionary<string, DateTime> _lastPosts = new();
public FeedsService(Bot bot, DbService db, DiscordSocketClient client, IEmbedBuilderService eb)
{
@@ -59,7 +58,7 @@ public class FeedsService : INService
.Select(item => (Item: item, LastUpdate: item.PublishingDate?.ToUniversalTime()
?? (item.SpecificItem as AtomFeedItem)?.UpdatedDate
?.ToUniversalTime()))
.Where(data => !(data.LastUpdate is null))
.Where(data => data.LastUpdate is not null)
.Select(data => (data.Item, LastUpdate: (DateTime) data.LastUpdate))
.OrderByDescending(data => data.LastUpdate)
.Reverse() // start from the oldest

View File

@@ -23,8 +23,8 @@ public class SearchesService : INService
private readonly IBotCredentials _creds;
private readonly NadekoRandom _rng;
public List<WoWJoke> WowJokes { get; } = new List<WoWJoke>();
public List<MagicItem> MagicItems { get; } = new List<MagicItem>();
public List<WoWJoke> WowJokes { get; } = new();
public List<MagicItem> MagicItems { get; } = new();
private readonly List<string> _yomamaJokes;
public SearchesService(IGoogleApiService google,
@@ -282,7 +282,7 @@ public class SearchesService : INService
_rng.Next(1, max).ToString("000") + ".png";
}
private readonly object yomamaLock = new object();
private readonly object yomamaLock = new();
private int yomamaJokeIndex = 0;
public Task<string> GetYomamaJoke()
{
@@ -567,7 +567,7 @@ public class SearchesService : INService
}
}
private static readonly HtmlParser _googleParser = new HtmlParser(new()
private static readonly HtmlParser _googleParser = new(new()
{
IsScripting = false,
IsEmbedded = false,

View File

@@ -17,10 +17,9 @@ public sealed class StreamNotificationService : INService
private readonly DiscordSocketClient _client;
private readonly NotifChecker _streamTracker;
private readonly object _shardLock = new object();
private readonly object _shardLock = new();
private readonly Dictionary<StreamDataKey, HashSet<ulong>> _trackCounter =
new Dictionary<StreamDataKey, HashSet<ulong>>();
private readonly Dictionary<StreamDataKey, HashSet<ulong>> _trackCounter = new();
private readonly Dictionary<StreamDataKey, Dictionary<ulong, HashSet<FollowedStream>>> _shardTrackedStreams;
private readonly ConcurrentHashSet<ulong> _offlineNotificationServers;

View File

@@ -118,7 +118,7 @@ public partial class Searches
{
var elem = elements[index];
eb.AddField(
$"**#{index + 1 + 12 * cur}** {elem.Username.ToLower()}",
$"**#{index + 1 + (12 * cur)}** {elem.Username.ToLower()}",
$"【{elem.Type}】\n<#{elem.ChannelId}>\n{elem.Message?.TrimTo(50)}",
true);
}

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