Implement style suggestions

This commit is contained in:
Noi 2024-06-08 21:07:35 -07:00
parent 7668c82cf9
commit cc148d5257
18 changed files with 54 additions and 61 deletions

View file

@ -1,11 +1,12 @@
using System.Collections; using System.Collections;
using System.Collections.ObjectModel;
namespace RegexBot.Common; namespace RegexBot.Common;
/// <summary> /// <summary>
/// Represents a commonly-used configuration structure: an array of strings consisting of <see cref="EntityName"/> values. /// Represents a commonly-used configuration structure: an array of strings consisting of <see cref="EntityName"/> values.
/// </summary> /// </summary>
public class EntityList : IEnumerable<EntityName> { public class EntityList : IEnumerable<EntityName> {
private readonly IReadOnlyCollection<EntityName> _innerList; private readonly ReadOnlyCollection<EntityName> _innerList;
/// <summary>Gets an enumerable collection of all role names defined in this list.</summary> /// <summary>Gets an enumerable collection of all role names defined in this list.</summary>
public IEnumerable<EntityName> Roles public IEnumerable<EntityName> Roles

View file

@ -11,7 +11,7 @@ public class RateLimit<T> where T : notnull {
/// Time until an entry within this instance expires, in seconds. /// Time until an entry within this instance expires, in seconds.
/// </summary> /// </summary>
public int Timeout { get; } public int Timeout { get; }
private Dictionary<T, DateTime> Entries { get; } = new Dictionary<T, DateTime>(); private Dictionary<T, DateTime> Entries { get; } = [];
/// <summary> /// <summary>
/// Creates a new <see cref="RateLimit&lt;T&gt;"/> instance with the default timeout value. /// Creates a new <see cref="RateLimit&lt;T&gt;"/> instance with the default timeout value.

View file

@ -1,7 +1,6 @@
using Discord; using Discord;
using RegexBot.Data; using RegexBot.Data;
using System.Diagnostics.CodeAnalysis; using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Text; using System.Text;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
@ -9,26 +8,30 @@ namespace RegexBot.Common;
/// <summary> /// <summary>
/// Miscellaneous utility methods useful for the bot and modules. /// Miscellaneous utility methods useful for the bot and modules.
/// </summary> /// </summary>
public static class Utilities { public static partial class Utilities {
/// <summary> /// <summary>
/// Gets a compiled regex that matches a channel tag and pulls its snowflake value. /// Gets a precompiled regex that matches a channel tag and pulls its snowflake value.
/// </summary> /// </summary>
public static Regex ChannelMention { get; } = new(@"<#(?<snowflake>\d+)>", RegexOptions.Compiled); [GeneratedRegex(@"<#(?<snowflake>\d+)>")]
public static partial Regex ChannelMentionRegex();
/// <summary> /// <summary>
/// Gets a compiled regex that matches a custom emoji and pulls its name and ID. /// Gets a precompiled regex that matches a custom emoji and pulls its name and ID.
/// </summary> /// </summary>
public static Regex CustomEmoji { get; } = new(@"<:(?<name>[A-Za-z0-9_]{2,}):(?<ID>\d+)>", RegexOptions.Compiled); [GeneratedRegex(@"<:(?<name>[A-Za-z0-9_]{2,}):(?<ID>\d+)>")]
public static partial Regex CustomEmojiRegex();
/// <summary> /// <summary>
/// Gets a compiled regex that matches a fully formed Discord handle, extracting the name and discriminator. /// Gets a precompiled regex that matches a fully formed Discord handle, extracting the name and discriminator.
/// </summary> /// </summary>
public static Regex DiscriminatorSearch { get; } = new(@"(.+)#(\d{4}(?!\d))", RegexOptions.Compiled); [GeneratedRegex(@"(.+)#(\d{4}(?!\d))")]
public static partial Regex DiscriminatorSearchRegex();
/// <summary> /// <summary>
/// Gets a compiled regex that matches a user tag and pulls its snowflake value. /// Gets a precompiled regex that matches a user tag and pulls its snowflake value.
/// </summary> /// </summary>
public static Regex UserMention { get; } = new(@"<@!?(?<snowflake>\d+)>", RegexOptions.Compiled); [GeneratedRegex(@"<@!?(?<snowflake>\d+)>")]
public static partial Regex UserMentionRegex();
/// <summary> /// <summary>
/// Performs common checks on the specified message to see if it fits all the criteria of a /// Performs common checks on the specified message to see if it fits all the criteria of a
@ -77,7 +80,7 @@ public static class Utilities {
/// If given string is in an EntityName format, returns a displayable representation of it based on /// If given string is in an EntityName format, returns a displayable representation of it based on
/// a cache query. Otherwise, returns the input string as-is. /// a cache query. Otherwise, returns the input string as-is.
/// </summary> /// </summary>
[return: NotNullIfNotNull("input")] [return: NotNullIfNotNull(nameof(input))]
public static string? TryFromEntityNameString(string? input, RegexbotClient bot) { public static string? TryFromEntityNameString(string? input, RegexbotClient bot) {
string? result = null; string? result = null;
try { try {

View file

@ -51,9 +51,8 @@ class Configuration {
throw new Exception($"'{nameof(Assemblies)}' is not properly specified in configuration."); throw new Exception($"'{nameof(Assemblies)}' is not properly specified in configuration.");
} }
var dbconf = conf["DatabaseOptions"]?.Value<JObject>(); var dbconf = (conf["DatabaseOptions"]?.Value<JObject>())
if (dbconf == null) throw new Exception("Database settings were not specified in configuration."); ?? throw new Exception("Database settings were not specified in configuration.");
// TODO more detailed database configuration? password file, other advanced authentication settings... look into this.
Host = ReadConfKey<string>(dbconf, nameof(Host), false); Host = ReadConfKey<string>(dbconf, nameof(Host), false);
Database = ReadConfKey<string?>(dbconf, nameof(Database), false); Database = ReadConfKey<string?>(dbconf, nameof(Database), false);
Username = ReadConfKey<string>(dbconf, nameof(Username), true); Username = ReadConfKey<string>(dbconf, nameof(Username), true);

View file

@ -4,9 +4,4 @@
/// Represents an error occurring when a module attempts to create a new guild state object /// Represents an error occurring when a module attempts to create a new guild state object
/// (that is, read or refresh its configuration). /// (that is, read or refresh its configuration).
/// </summary> /// </summary>
public class ModuleLoadException : Exception { public class ModuleLoadException(string message) : Exception(message) { }
/// <summary>
/// Initializes this exception class with the specified error message.
/// </summary>
public ModuleLoadException(string message) : base(message) { }
}

View file

@ -38,7 +38,7 @@ static class ModuleLoader {
return modules.AsReadOnly(); return modules.AsReadOnly();
} }
static IEnumerable<RegexbotModule> LoadModulesFromAssembly(Assembly asm, RegexbotClient rb) { static List<RegexbotModule> LoadModulesFromAssembly(Assembly asm, RegexbotClient rb) {
var eligibleTypes = from type in asm.GetTypes() var eligibleTypes = from type in asm.GetTypes()
where !type.IsAssignableFrom(typeof(RegexbotModule)) where !type.IsAssignableFrom(typeof(RegexbotModule))
where type.GetCustomAttribute<RegexbotModuleAttribute>() != null where type.GetCustomAttribute<RegexbotModuleAttribute>() != null

View file

@ -45,7 +45,7 @@ internal class AutoResponder : RegexbotModule {
if (def.Command == null) { if (def.Command == null) {
await msg.Channel.SendMessageAsync(def.GetResponse()); await msg.Channel.SendMessageAsync(def.GetResponse());
} else { } else {
var cmdline = def.Command.Split(new char[] { ' ' }, 2); var cmdline = def.Command.Split([' '], 2);
var ps = new ProcessStartInfo() { var ps = new ProcessStartInfo() {
FileName = cmdline[0], FileName = cmdline[0],

View file

@ -83,7 +83,7 @@ internal sealed class EntryRole : RegexbotModule, IDisposable {
foreach (var g in DiscordClient.Guilds) { foreach (var g in DiscordClient.Guilds) {
subworkers.Add(RoleApplyGuildSubWorker(g)); subworkers.Add(RoleApplyGuildSubWorker(g));
} }
Task.WaitAll(subworkers.ToArray()); Task.WaitAll([.. subworkers]);
} }
} }

View file

@ -21,7 +21,7 @@ class GuildData {
const int WaitTimeMax = 600; // 10 minutes const int WaitTimeMax = 600; // 10 minutes
public GuildData(JObject conf) : this(conf, new Dictionary<ulong, DateTimeOffset>()) { } public GuildData(JObject conf) : this(conf, []) { }
public GuildData(JObject conf, Dictionary<ulong, DateTimeOffset> _waitingList) { public GuildData(JObject conf, Dictionary<ulong, DateTimeOffset> _waitingList) {
WaitingList = _waitingList; WaitingList = _waitingList;

View file

@ -17,9 +17,9 @@ class ModuleConfig {
Label = def[nameof(Label)]?.Value<string>() Label = def[nameof(Label)]?.Value<string>()
?? throw new ModuleLoadException($"'{nameof(Label)}' was not defined in a command definition."); ?? throw new ModuleLoadException($"'{nameof(Label)}' was not defined in a command definition.");
var cmd = CreateCommandInstance(instance, def); var cmd = CreateCommandInstance(instance, def);
if (commands.ContainsKey(cmd.Command)) { if (commands.TryGetValue(cmd.Command, out CommandConfig? existing)) {
throw new ModuleLoadException( throw new ModuleLoadException(
$"{Label}: The command name '{cmd.Command}' is already in use by '{commands[cmd.Command].Label}'."); $"{Label}: The command name '{cmd.Command}' is already in use by '{existing.Label}'.");
} }
commands.Add(cmd.Command, cmd); commands.Add(cmd.Command, cmd);
} }

View file

@ -33,7 +33,7 @@ class ResponseExecutor {
_user = (SocketGuildUser)msg.Author; _user = (SocketGuildUser)msg.Author;
_guild = _user.Guild; _guild = _user.Guild;
_reports = new(); _reports = [];
Log = logger; Log = logger;
} }

View file

@ -23,9 +23,7 @@ class ModuleConfig {
} catch (FormatException) { } catch (FormatException) {
throw new ModuleLoadException($"'{item.Name}' is not specified as a role."); throw new ModuleLoadException($"'{item.Name}' is not specified as a role.");
} }
var role = name.FindRoleIn(g); var role = name.FindRoleIn(g) ?? throw new ModuleLoadException($"Unable to find role '{name}'.");
if (role == null) throw new ModuleLoadException($"Unable to find role '{name}'.");
var channels = Utilities.LoadStringOrStringArray(item.Value); var channels = Utilities.LoadStringOrStringArray(item.Value);
if (channels.Count == 0) throw new ModuleLoadException($"One or more channels must be defined under '{name}'."); if (channels.Count == 0) throw new ModuleLoadException($"One or more channels must be defined under '{name}'.");
foreach (var id in channels) { foreach (var id in channels) {

View file

@ -10,24 +10,20 @@ namespace RegexBot;
/// <remarks> /// <remarks>
/// Implementing classes should not rely on local variables to store runtime or state data for guilds. /// Implementing classes should not rely on local variables to store runtime or state data for guilds.
/// Instead, use <see cref="CreateGuildStateAsync"/> and <see cref="GetGuildState"/>. /// Instead, use <see cref="CreateGuildStateAsync"/> and <see cref="GetGuildState"/>.
/// <br/><br/>
/// Additionally, do not assume that <see cref="DiscordClient"/> is available during the constructor.
/// </remarks> /// </remarks>
public abstract class RegexbotModule { public abstract class RegexbotModule(RegexbotClient bot) {
/// <summary> /// <summary>
/// Retrieves the bot instance. /// Retrieves the bot instance.
/// </summary> /// </summary>
public RegexbotClient Bot { get; } public RegexbotClient Bot { get; } = bot;
/// <summary> /// <summary>
/// Retrieves the Discord client instance. /// Retrieves the Discord client instance.
/// </summary> /// </summary>
public DiscordSocketClient DiscordClient { get => Bot.DiscordClient; } public DiscordSocketClient DiscordClient { get => Bot.DiscordClient; }
/// <summary>
/// Called when a module is being loaded.
/// At this point, all bot services are available, but Discord is not. Do not use <see cref="DiscordClient"/>.
/// </summary>
public RegexbotModule(RegexbotClient bot) => Bot = bot;
/// <summary> /// <summary>
/// Gets the name of this module. /// Gets the name of this module.
/// </summary> /// </summary>

View file

@ -6,10 +6,9 @@ namespace RegexBot.Services.CommonFunctions {
/// functions may help enforce a sense of consistency across modules when performing common actions, and may /// functions may help enforce a sense of consistency across modules when performing common actions, and may
/// inform services which provide any additional features the ability to respond to those actions ahead of time. /// inform services which provide any additional features the ability to respond to those actions ahead of time.
/// </summary> /// </summary>
internal partial class CommonFunctionsService : Service { internal partial class CommonFunctionsService(RegexbotClient bot) : Service(bot) {
// Note: Several classes within this service created by its hooks are meant to be sent to modules, // Note: Several classes within this service created by its hooks are meant to be sent to modules,
// therefore those public classes are placed into the root RegexBot namespace for the developer's convenience. // therefore those public classes are placed into the root RegexBot namespace for the developer's convenience.
public CommonFunctionsService(RegexbotClient bot) : base(bot) { }
} }
} }

View file

@ -86,7 +86,7 @@ class UserCachingSubservice {
if (sID.HasValue) if (sID.HasValue)
query = query.Where(c => c.UserId == (long)sID.Value); query = query.Where(c => c.UserId == (long)sID.Value);
if (nameSearch != null) { if (nameSearch != null) {
query = query.Where(c => c.Username.ToLower() == nameSearch.Value.name.ToLower()); query = query.Where(c => c.Username.Equals(nameSearch.Value.name, StringComparison.OrdinalIgnoreCase));
if (nameSearch.Value.disc != null) query = query.Where(c => c.Discriminator == nameSearch.Value.disc); if (nameSearch.Value.disc != null) query = query.Where(c => c.Discriminator == nameSearch.Value.disc);
} }
query = query.OrderByDescending(e => e.ULastUpdateTime); query = query.OrderByDescending(e => e.ULastUpdateTime);
@ -95,7 +95,7 @@ class UserCachingSubservice {
} }
// Is search actually a ping? Extract ID. // Is search actually a ping? Extract ID.
var m = Utilities.UserMention.Match(search); var m = Utilities.UserMentionRegex().Match(search);
if (m.Success) search = m.Groups["snowflake"].Value; if (m.Success) search = m.Groups["snowflake"].Value;
// Is search a number? Assume ID, proceed to query. // Is search a number? Assume ID, proceed to query.
@ -117,8 +117,9 @@ class UserCachingSubservice {
if (sID.HasValue) if (sID.HasValue)
query = query.Where(c => c.UserId == (long)sID.Value); query = query.Where(c => c.UserId == (long)sID.Value);
if (nameSearch != null) { if (nameSearch != null) {
query = query.Where(c => (c.Nickname != null && c.Nickname.ToLower() == nameSearch.Value.name.ToLower()) || query = query.Where(c => (c.Nickname != null
c.User.Username.ToLower() == nameSearch.Value.name.ToLower()); && c.Nickname.Equals(nameSearch.Value.name, StringComparison.OrdinalIgnoreCase))
|| c.User.Username.Equals(nameSearch.Value.name, StringComparison.OrdinalIgnoreCase));
if (nameSearch.Value.disc != null) query = query.Where(c => c.User.Discriminator == nameSearch.Value.disc); if (nameSearch.Value.disc != null) query = query.Where(c => c.User.Discriminator == nameSearch.Value.disc);
} }
query = query.OrderByDescending(e => e.GULastUpdateTime); query = query.OrderByDescending(e => e.GULastUpdateTime);
@ -127,7 +128,7 @@ class UserCachingSubservice {
} }
// Is search actually a ping? Extract ID. // Is search actually a ping? Extract ID.
var m = Utilities.UserMention.Match(search); var m = Utilities.UserMentionRegex().Match(search);
if (m.Success) search = m.Groups["snowflake"].Value; if (m.Success) search = m.Groups["snowflake"].Value;
// Is search a number? Assume ID, proceed to query. // Is search a number? Assume ID, proceed to query.
@ -144,7 +145,7 @@ class UserCachingSubservice {
private static (string, string?) SplitNameAndDiscriminator(string input) { private static (string, string?) SplitNameAndDiscriminator(string input) {
string name; string name;
string? disc = null; string? disc = null;
var split = Utilities.DiscriminatorSearch.Match(input); var split = Utilities.DiscriminatorSearchRegex().Match(input);
if (split.Success) { if (split.Success) {
name = split.Groups[1].Value; name = split.Groups[1].Value;
disc = split.Groups[2].Value; disc = split.Groups[2].Value;

View file

@ -52,7 +52,7 @@ class LoggingService : Service {
var now = DateTimeOffset.Now; var now = DateTimeOffset.Now;
var output = new StringBuilder(); var output = new StringBuilder();
var prefix = $"[{now:s}] [{source}] "; var prefix = $"[{now:s}] [{source}] ";
foreach (var line in message.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None)) { foreach (var line in message.Split(["\r\n", "\n"], StringSplitOptions.None)) {
output.Append(prefix).AppendLine(line); output.Append(prefix).AppendLine(line);
} }
var outstr = output.ToString(); var outstr = output.ToString();

View file

@ -6,12 +6,12 @@ namespace RegexBot.Services.ModuleState;
/// </summary> /// </summary>
class ModuleStateService : Service { class ModuleStateService : Service {
private readonly Dictionary<ulong, EntityList> _moderators; private readonly Dictionary<ulong, EntityList> _moderators;
private readonly Dictionary<ulong, Dictionary<Type, object?>> _stateData; private readonly Dictionary<ulong, Dictionary<Type, object?>> _guildStates;
private readonly JObject _serverConfs; private readonly JObject _serverConfs;
public ModuleStateService(RegexbotClient bot, JObject servers) : base(bot) { public ModuleStateService(RegexbotClient bot, JObject servers) : base(bot) {
_moderators = new(); _moderators = [];
_stateData = new(); _guildStates = [];
_serverConfs = servers; _serverConfs = servers;
bot.DiscordClient.GuildAvailable += RefreshGuildState; bot.DiscordClient.GuildAvailable += RefreshGuildState;
@ -25,17 +25,20 @@ class ModuleStateService : Service {
} }
private Task RemoveGuildData(SocketGuild arg) { private Task RemoveGuildData(SocketGuild arg) {
_stateData.Remove(arg.Id); _guildStates.Remove(arg.Id);
_moderators.Remove(arg.Id); _moderators.Remove(arg.Id);
return Task.CompletedTask; return Task.CompletedTask;
} }
// Hooked // Hooked
public T? DoGetStateObj<T>(ulong guildId, Type t) { public T? DoGetStateObj<T>(ulong guildId, Type t) {
if (_stateData.ContainsKey(guildId) && _stateData[guildId].ContainsKey(t)) { if (_guildStates.TryGetValue(guildId, out var guildConfs)) {
// Leave handling of potential InvalidCastException to caller. if (guildConfs.TryGetValue(t, out var moduleConf)) {
return (T?)_stateData[guildId][t]; // Leave handling of potential InvalidCastException to caller.
return (T?)moduleConf;
}
} }
return default; return default;
} }
@ -71,7 +74,7 @@ class ModuleStateService : Service {
} }
} }
_moderators[guild.Id] = mods; _moderators[guild.Id] = mods;
_stateData[guild.Id] = newStates; _guildStates[guild.Id] = newStates;
return true; return true;
} }
} }

View file

@ -6,13 +6,11 @@
/// Services provide core and shared functionality for this program. Modules are expected to call into services /// Services provide core and shared functionality for this program. Modules are expected to call into services
/// directly or indirectly in order to access bot features. /// directly or indirectly in order to access bot features.
/// </remarks> /// </remarks>
internal abstract class Service { internal abstract class Service(RegexbotClient bot) {
public RegexbotClient BotClient { get; } public RegexbotClient BotClient { get; } = bot;
public string Name => GetType().Name; public string Name => GetType().Name;
public Service(RegexbotClient bot) => BotClient = bot;
/// <summary> /// <summary>
/// Emits a log message. /// Emits a log message.
/// </summary> /// </summary>