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

@@ -8,7 +8,7 @@ namespace NadekoBot.Services;
public class CommandHandler : INService
{
public const int GlobalCommandsCooldown = 750;
private const int GlobalCommandsCooldown = 750;
private readonly DiscordSocketClient _client;
private readonly CommandService _commandService;
@@ -24,9 +24,9 @@ public class CommandHandler : INService
public event Func<IUserMessage, Task> OnMessageNoTrigger = delegate { return Task.CompletedTask; };
//userid/msg count
public ConcurrentDictionary<ulong, uint> UserMessagesSent { get; } = new ConcurrentDictionary<ulong, uint>();
public ConcurrentDictionary<ulong, uint> UserMessagesSent { get; } = new();
public ConcurrentHashSet<ulong> UsersOnShortCooldown { get; } = new ConcurrentHashSet<ulong>();
public ConcurrentHashSet<ulong> UsersOnShortCooldown { get; } = new();
private readonly Timer _clearUsersOnShortCooldown;
public CommandHandler(
@@ -105,9 +105,9 @@ public class CommandHandler : INService
if (guildId != null)
{
var guild = _client.GetGuild(guildId.Value);
if (!(guild?.GetChannel(channelId) is SocketTextChannel channel))
if (guild?.GetChannel(channelId) is not SocketTextChannel channel)
{
Log.Warning("Channel for external execution not found.");
Log.Warning("Channel for external execution not found");
return;
}
@@ -143,15 +143,16 @@ public class CommandHandler : INService
{
if (_bss.Data.ConsoleOutputType == ConsoleOutputType.Normal)
{
Log.Information($"Command Executed after " + string.Join("/", execPoints.Select(x => (x * _oneThousandth).ToString("F3"))) + "s\n\t" +
"User: {0}\n\t" +
"Server: {1}\n\t" +
"Channel: {2}\n\t" +
"Message: {3}",
usrMsg.Author + " [" + usrMsg.Author.Id + "]", // {0}
channel is null ? "PRIVATE" : channel.Guild.Name + " [" + channel.Guild.Id + "]", // {1}
channel is null ? "PRIVATE" : channel.Name + " [" + channel.Id + "]", // {2}
usrMsg.Content // {3}
Log.Information(@"Command Executed after {ExecTime}s
User: {User}
Server: {Server}
Channel: {Channel}
Message: {MessageContent}",
string.Join("/", execPoints.Select(x => (x * _oneThousandth).ToString("F3"))),
usrMsg.Author + " [" + usrMsg.Author.Id + "]",
channel is null ? "PRIVATE" : channel.Guild.Name + " [" + channel.Guild.Id + "]",
channel is null ? "PRIVATE" : channel.Name + " [" + channel.Id + "]",
usrMsg.Content
);
}
else
@@ -169,18 +170,18 @@ public class CommandHandler : INService
{
if (_bss.Data.ConsoleOutputType == ConsoleOutputType.Normal)
{
Log.Warning($"Command Errored after " + string.Join("/", execPoints.Select(x => (x * _oneThousandth).ToString("F3"))) + "s\n\t" +
"User: {0}\n\t" +
"Server: {1}\n\t" +
"Channel: {2}\n\t" +
"Message: {3}\n\t" +
"Error: {4}",
usrMsg.Author + " [" + usrMsg.Author.Id + "]", // {0}
channel is null ? "PRIVATE" : channel.Guild.Name + " [" + channel.Guild.Id + "]", // {1}
channel is null ? "PRIVATE" : channel.Name + " [" + channel.Id + "]", // {2}
usrMsg.Content,// {3}
Log.Warning(@"Command Errored after {ExecTime}s
User: {User}
Server: {Server}
Channel: {Channel}
Message: {MessageContent}
Error: {ErrorMessage}",
string.Join("/", execPoints.Select(x => (x * _oneThousandth).ToString("F3"))),
usrMsg.Author + " [" + usrMsg.Author.Id + "]",
channel is null ? "PRIVATE" : channel.Guild.Name + " [" + channel.Guild.Id + "]",
channel is null ? "PRIVATE" : channel.Name + " [" + channel.Id + "]",
usrMsg.Content,
errorMessage
//exec.Result.ErrorReason // {4}
);
}
else
@@ -196,19 +197,20 @@ public class CommandHandler : INService
private async Task MessageReceivedHandler(SocketMessage msg)
{
try
{
if (msg.Author.IsBot || !_bot.IsReady) //no bots, wait until bot connected and initialized
return;
if (!(msg is SocketUserMessage usrMsg))
if (msg is not SocketUserMessage usrMsg)
return;
#if !GLOBAL_NADEKO
// track how many messagges each user is sending
UserMessagesSent.AddOrUpdate(usrMsg.Author.Id, 1, (key, old) => ++old);
#endif
var channel = msg.Channel as ISocketMessageChannel;
var channel = msg.Channel;
var guild = (msg.Channel as SocketTextChannel)?.Guild;
await TryRunCommand(guild, channel, usrMsg).ConfigureAwait(false);
@@ -240,20 +242,20 @@ public class CommandHandler : INService
// execute the command and measure the time it took
if (messageContent.StartsWith(prefix, StringComparison.InvariantCulture) || isPrefixCommand)
{
var (Success, Error, Info) = await ExecuteCommandAsync(new(_client, usrMsg), messageContent, isPrefixCommand ? 1 : prefix.Length, _services, MultiMatchHandling.Best).ConfigureAwait(false);
var (success, error, info) = await ExecuteCommandAsync(new(_client, usrMsg), messageContent, isPrefixCommand ? 1 : prefix.Length, _services, MultiMatchHandling.Best).ConfigureAwait(false);
startTime = Environment.TickCount - startTime;
if (Success)
if (success)
{
await LogSuccessfulExecution(usrMsg, channel as ITextChannel, blockTime, startTime).ConfigureAwait(false);
await CommandExecuted(usrMsg, Info).ConfigureAwait(false);
await CommandExecuted(usrMsg, info).ConfigureAwait(false);
return;
}
else if (Error != null)
else if (error != null)
{
LogErroredExecution(Error, usrMsg, channel as ITextChannel, blockTime, startTime);
LogErroredExecution(error, usrMsg, channel as ITextChannel, blockTime, startTime);
if (guild != null)
await CommandErrored(Info, channel as ITextChannel, Error).ConfigureAwait(false);
await CommandErrored(info, channel as ITextChannel, error).ConfigureAwait(false);
}
}
else
@@ -330,12 +332,13 @@ public class CommandHandler : INService
}
var totalArgsScore = (argValuesScore + paramValuesScore) / 2;
return match.Command.Priority + totalArgsScore * 0.99f;
return match.Command.Priority + (totalArgsScore * 0.99f);
}
//Order the parse results by their score so that we choose the most likely result to execute
var parseResults = parseResultsDict
.OrderByDescending(x => CalculateScore(x.Key, x.Value));
.OrderByDescending(x => CalculateScore(x.Key, x.Value))
.ToList();
var successfulParses = parseResults
.Where(x => x.Value.IsSuccess)
@@ -365,7 +368,7 @@ public class CommandHandler : INService
var chosenOverload = successfulParses[0];
var execResult = (Discord.Commands.ExecuteResult)await chosenOverload.Key.ExecuteAsync(context, chosenOverload.Value, services).ConfigureAwait(false);
if (execResult.Exception != null && (!(execResult.Exception is HttpException he) || he.DiscordCode != DiscordErrorCode.InsufficientPermissions))
if (execResult.Exception != null && (execResult.Exception is not HttpException he || he.DiscordCode != DiscordErrorCode.InsufficientPermissions))
{
Log.Warning(execResult.Exception, "Command Error");
}

View File

@@ -3,7 +3,7 @@
public class GreetGrouper<T>
{
private readonly Dictionary<ulong, HashSet<T>> group;
private readonly object locker = new object();
private readonly object locker = new();
public GreetGrouper()
{

View File

@@ -10,8 +10,8 @@ public class GreetSettingsService : INService
public ConcurrentDictionary<ulong, GreetSettings> GuildConfigsCache { get; }
private readonly DiscordSocketClient _client;
private GreetGrouper<IGuildUser> greets = new GreetGrouper<IGuildUser>();
private GreetGrouper<IUser> byes = new GreetGrouper<IUser>();
private readonly GreetGrouper<IGuildUser> greets = new();
private readonly GreetGrouper<IUser> byes = new();
private readonly BotConfigService _bss;
private readonly IEmbedBuilderService _eb;
public bool GroupGreets => _bss.Data.GroupGreets;
@@ -634,7 +634,7 @@ public class GreetSettings
public int BoostMessageDeleteAfter { get; set; }
public ulong BoostMessageChannelId { get; set; }
public static GreetSettings Create(GuildConfig g) => new GreetSettings()
public static GreetSettings Create(GuildConfig g) => new()
{
AutoDeleteByeMessagesTimer = g.AutoDeleteByeMessagesTimer,
AutoDeleteGreetMessagesTimer = g.AutoDeleteGreetMessagesTimer,

View File

@@ -24,11 +24,11 @@ public sealed class BotCredsProvider : IBotCredsProvider
private string OldCredsJsonBackupPath => Path.Combine(Directory.GetCurrentDirectory(), "credentials.json.bak");
private Creds _creds = new Creds();
private IConfigurationRoot _config;
private readonly Creds _creds = new();
private readonly IConfigurationRoot _config;
private readonly object reloadLock = new object();
private readonly object reloadLock = new();
public void Reload()
{
lock (reloadLock)

View File

@@ -21,7 +21,7 @@ public class CurrencyService : ICurrencyService, INService
}
private CurrencyTransaction GetCurrencyTransaction(ulong userId, string reason, long amount) =>
new CurrencyTransaction
new()
{
Amount = amount,
UserId = userId,

View File

@@ -13,9 +13,9 @@ public class GoogleApiService : IGoogleApiService, INService
{
private const string SearchEngineId = "018084019232060951019:hs5piey28-e";
private YouTubeService yt;
private UrlshortenerService sh;
private CustomsearchService cs;
private readonly YouTubeService yt;
private readonly UrlshortenerService sh;
private readonly CustomsearchService cs;
public GoogleApiService(IBotCredentials creds, IHttpClientFactory factory)
{
@@ -32,7 +32,7 @@ public class GoogleApiService : IGoogleApiService, INService
sh = new(bcs);
cs = new(bcs);
}
private static readonly Regex plRegex = new Regex("(?:youtu\\.be\\/|list=)(?<id>[\\da-zA-Z\\-_]*)", RegexOptions.Compiled);
private static readonly Regex plRegex = new("(?:youtu\\.be\\/|list=)(?<id>[\\da-zA-Z\\-_]*)", RegexOptions.Compiled);
public async Task<IEnumerable<string>> GetPlaylistIdsByKeywordsAsync(string keywords, int count = 1)
{
await Task.Yield();

View File

@@ -67,7 +67,7 @@ public class RedisCache : IDataCache
return _db.StringSetAsync("novel_" + key, data, expiry: TimeSpan.FromHours(3));
}
private readonly object timelyLock = new object();
private readonly object timelyLock = new();
public TimeSpan? AddTimelyClaim(ulong id, int period)
{
if (period == 0)

View File

@@ -55,7 +55,7 @@ public class SoundCloudVideo
{
public string Kind { get; set; } = string.Empty;
public long Id { get; set; } = 0;
public SoundCloudUser User { get; set; } = new SoundCloudUser();
public SoundCloudUser User { get; set; } = new();
public string Title { get; set; } = string.Empty;
public string FullName => User.Name + " - " + Title;
public bool? Streamable { get; set; } = false;

View File

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

View File

@@ -41,5 +41,5 @@ public static class ConfigPrinters
=> culture.Name;
public static string Color(Rgba32 color)
=> ((uint) (color.B << 0 | color.G << 8 | color.R << 16)).ToString("X6");
=> ((uint) ((color.B << 0) | (color.G << 8) | (color.R << 16))).ToString("X6");
}

View File

@@ -95,10 +95,10 @@ public abstract class ConfigServiceBase<TSettings> : IConfigService
File.WriteAllText(_filePath, strData);
}
private readonly Dictionary<string, Func<TSettings, string, bool>> _propSetters = new Dictionary<string, Func<TSettings, string, bool>>();
private readonly Dictionary<string, Func<object>> _propSelectors = new Dictionary<string, Func<object>>();
private readonly Dictionary<string, Func<object, string>> _propPrinters = new Dictionary<string, Func<object, string>>();
private readonly Dictionary<string, string> _propComments = new Dictionary<string, string>();
private readonly Dictionary<string, Func<TSettings, string, bool>> _propSetters = new();
private readonly Dictionary<string, Func<object>> _propSelectors = new();
private readonly Dictionary<string, Func<object, string>> _propPrinters = new();
private readonly Dictionary<string, string> _propComments = new();
protected void AddParsedProp<TProp>(
string key,

View File

@@ -4,6 +4,6 @@ public static class StandardConversions
{
public static double CelsiusToFahrenheit(double cel)
{
return cel * 1.8f + 32;
return (cel * 1.8f) + 32;
}
}

View File

@@ -8,7 +8,7 @@ public class BotStrings : IBotStrings
/// <summary>
/// Used as failsafe in case response key doesn't exist in the selected or default language.
/// </summary>
private readonly CultureInfo _usCultureInfo = new CultureInfo("en-US");
private readonly CultureInfo _usCultureInfo = new("en-US");
private readonly ILocalization _localization;
private readonly IBotStringsProvider _stringsProvider;