Rework all usages of configuration

This commit is contained in:
Daniel_I_Am 2020-10-16 17:55:00 +02:00
parent 5019ea3d3e
commit afbb92b1e9
No known key found for this signature in database
GPG Key ID: 80C428FCC9743E84
12 changed files with 90 additions and 56 deletions

View File

@ -11,28 +11,32 @@ namespace ChaosBot
{ {
private readonly IConfiguration _appSettingsWrapper; private readonly IConfiguration _appSettingsWrapper;
private static readonly Dictionary<string, Type> ConfigurationFlags = new Dictionary<string, Type> private static readonly Dictionary<string, (Type type, object defaultValue)> ConfigurationFlags = new Dictionary<string, (Type type, object defaultValue)>
{ {
{"Bot:Name", typeof(string)}, {"Bot:Name", (typeof(string), "ChaosBot")},
{"Bot:Version", typeof(string)}, {"Bot:Version", (typeof(string), "1.0.0")},
{"WebServer:Port", typeof(int)}, {"WebServer:Port", (typeof(int), 8080)},
{"WebServer:Debug", typeof(bool)}, {"WebServer:Debug", (typeof(bool), false)},
{"Discord:Prefix", typeof(string)}, {"Discord:Prefix", (typeof(string), "!")},
{"Discord:Token", typeof(string)}, {"Discord:Token", (typeof(string), "SECRET_TOKEN")},
{"Discord:BaseUri", typeof(string)}, {"Discord:BaseUri", (typeof(string), "http://localhost:8080/")},
{"Discord:ClientId", typeof(string)}, {"Discord:ClientId", (typeof(string), "1234567890")},
{"Discord:ClientSecret", typeof(string)}, {"Discord:ClientSecret", (typeof(string), "1234567890_SECRET_TOKEN")},
{"Lodestone:ChaosBotApi:ApiToken", typeof(string)}, {"Lodestone:ChaosBotApi:ApiToken", (typeof(string), "SECRET_TOKEN")},
{"Lodestone:ChaosBotApi:Url", typeof(string)}, {"Lodestone:ChaosBotApi:Url", (typeof(string), "http://locahost:8000")},
{"Database:Host", typeof(string)}, {"Database:Host", (typeof(string), "localhost")},
{"Database:Port", typeof(int)}, {"Database:Port", (typeof(int), 3306)},
{"Database:User", typeof(string)}, {"Database:User", (typeof(string), "root")},
{"Database:Pass", typeof(string)}, {"Database:Pass", (typeof(string), "password")},
{"Database:Name", typeof(string)}, {"Database:Name", (typeof(string), "chaosbot")},
{"Module:Experience:Enabled", (typeof(bool), true)},
{"LevelUp:Channel", (typeof(string), null)},
{"LevelUp:MentionUser", (typeof(bool), true)},
}; };
public Configuration() public Configuration()
@ -56,7 +60,7 @@ namespace ChaosBot
if (!keyExists) if (!keyExists)
throw new ArgumentException($"Configuration does not contain key '{key}'"); throw new ArgumentException($"Configuration does not contain key '{key}'");
if (!(ConfigurationFlags[realKey] == typeof(T))) if (!(ConfigurationFlags[realKey].type == typeof(T)))
throw new ArgumentException($"Configuration flag '{realKey}<{ConfigurationFlags[realKey]}>' does not have type '{typeof(T)}'"); throw new ArgumentException($"Configuration flag '{realKey}<{ConfigurationFlags[realKey]}>' does not have type '{typeof(T)}'");
if (guildId.HasValue) if (guildId.HasValue)
@ -65,6 +69,18 @@ namespace ChaosBot
return _appSettingsWrapper.GetValue(realKey, defaultValue); return _appSettingsWrapper.GetValue(realKey, defaultValue);
} }
public T GetValueGlobalDefault<T>(string key, ulong? guildId = null)
{
bool keyExists = TryGetKeyFromRegexMatch(key, out string realKey);
object defaultObject = keyExists ? ConfigurationFlags[realKey].defaultValue : null;
T defaultValue = default;
if (defaultObject != null)
defaultValue = (T)Convert.ChangeType(defaultObject, typeof(T));
return GetValue(key, defaultValue);
}
public T GetValue<T>(string key) public T GetValue<T>(string key)
{ {
return GetValue<T>(key, default); return GetValue<T>(key, default);
@ -79,7 +95,7 @@ namespace ChaosBot
* Get the available configuration flags * Get the available configuration flags
* <returns>Immutable dictionary of config-key/type pairs</returns> * <returns>Immutable dictionary of config-key/type pairs</returns>
*/ */
public ImmutableDictionary<string, Type> GetConfigurationFlags() public ImmutableDictionary<string, (Type type, object defaultvalue)> GetConfigurationFlags()
{ {
return ConfigurationFlags.ToImmutableDictionary(); return ConfigurationFlags.ToImmutableDictionary();
} }

View File

@ -1,4 +1,5 @@
using System; using System;
using System.Collections.Immutable;
using Discord.Commands; using Discord.Commands;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Text; using System.Text;
@ -43,19 +44,20 @@ namespace ChaosBot.Discord.Modules.Admin
{ {
var sb = new StringBuilder(); var sb = new StringBuilder();
var embed = new EmbedBuilder(); var embed = new EmbedBuilder();
Configuration config = new Configuration();
embed.WithColor(new Color(255, 255, 0)); embed.WithColor(new Color(255, 255, 0));
embed.Title = $"Configuration Management Help"; embed.Title = $"Configuration Management Help";
sb.AppendLine(); sb.AppendLine();
sb.AppendLine("To set a configuration value:"); sb.AppendLine("To set a configuration value:");
sb.AppendLine($"{ConfigurationRepository.GetValue("Discord:Prefix", Context.Guild.Id, "!")}config set <configFlag> <value>"); sb.AppendLine($"{config.GetValueGlobalDefault<string>("Discord:Prefix", Context.Guild.Id)}config set <configFlag> <value>");
sb.AppendLine("To get a configuration value:"); sb.AppendLine("To get a configuration value:");
sb.AppendLine($"{ConfigurationRepository.GetValue("Discord:Prefix", Context.Guild.Id, "!")}config get <configFlag>"); sb.AppendLine($"{config.GetValueGlobalDefault<string>("Discord:Prefix", Context.Guild.Id)}config get <configFlag>");
sb.AppendLine("To reset a configuration value to default:"); sb.AppendLine("To reset a configuration value to default:");
sb.AppendLine($"{ConfigurationRepository.GetValue("Discord:Prefix", Context.Guild.Id, "!")}config reset <configFlag>"); sb.AppendLine($"{config.GetValueGlobalDefault<string>("Discord:Prefix", Context.Guild.Id)}config reset <configFlag>");
sb.AppendLine(); sb.AppendLine();
sb.AppendLine("To view this help:"); sb.AppendLine("To view this help:");
sb.AppendLine($"{ConfigurationRepository.GetValue("Discord:Prefix", Context.Guild.Id, "!")}config help"); sb.AppendLine($"{config.GetValueGlobalDefault<string>("Discord:Prefix", Context.Guild.Id)}config help");
/* /*
* Add the string to the Embed * Add the string to the Embed
@ -124,7 +126,18 @@ namespace ChaosBot.Discord.Modules.Admin
embed.Title = $"Configuration Retrieval"; embed.Title = $"Configuration Retrieval";
sb.AppendLine(); sb.AppendLine();
sb.AppendLine($" Flag: {key}"); sb.AppendLine($" Flag: {key}");
sb.AppendLine($"Value: {ConfigurationRepository.GetValue(key, Context.Guild.Id, "NotSet")}");
Configuration config = new Configuration();
ImmutableDictionary<string, (Type type, object defaultvalue)> configFlags =
config.GetConfigurationFlags();
dynamic configValue;
if (configFlags.TryGetValue(key, out (Type type, object defaultvalue) configFlagValue))
configValue = new Configuration().GetValue(key, configFlagValue.defaultvalue, Context.Guild.Id);
else
configValue = "Not a valid key";
sb.AppendLine($"Value: {configValue}");
/* /*
* Add the string to the Embed * Add the string to the Embed

View File

@ -23,19 +23,20 @@ namespace ChaosBot.Discord.Modules.Admin
{ {
var sb = new StringBuilder(); var sb = new StringBuilder();
var embed = new EmbedBuilder(); var embed = new EmbedBuilder();
Configuration config = new Configuration();
embed.WithColor(new Color(255, 255, 0)); embed.WithColor(new Color(255, 255, 0));
embed.Title = $"Role Management Help"; embed.Title = $"Role Management Help";
sb.AppendLine(); sb.AppendLine();
sb.AppendLine("To add a role-reaction to a message:"); sb.AppendLine("To add a role-reaction to a message:");
sb.AppendLine($"{ConfigurationRepository.GetValue("Discord:Prefix", Context.Guild.Id, "!")}role add <emote> <role>"); sb.AppendLine($"{config.GetValueGlobalDefault<string>("Discord:Prefix", Context.Guild.Id)}role add <emote> <role>");
sb.AppendLine("To add many role-reactions to a message add more sets of emote and role:"); sb.AppendLine("To add many role-reactions to a message add more sets of emote and role:");
sb.AppendLine($"{ConfigurationRepository.GetValue("Discord:Prefix", Context.Guild.Id, "!")}role add <emote> <role> <emote> <role> <emote> <role>"); sb.AppendLine($"{config.GetValueGlobalDefault<string>("Discord:Prefix", Context.Guild.Id)}role add <emote> <role> <emote> <role> <emote> <role>");
sb.AppendLine("To remove a role-reaction from a message:"); sb.AppendLine("To remove a role-reaction from a message:");
sb.AppendLine($"{ConfigurationRepository.GetValue("Discord:Prefix", Context.Guild.Id, "!")}role remove <emote>"); sb.AppendLine($"{config.GetValueGlobalDefault<string>("Discord:Prefix", Context.Guild.Id)}role remove <emote>");
sb.AppendLine(); sb.AppendLine();
sb.AppendLine("To view this help:"); sb.AppendLine("To view this help:");
sb.AppendLine($"{ConfigurationRepository.GetValue("Discord:Prefix", Context.Guild.Id, "!")}role help"); sb.AppendLine($"{config.GetValueGlobalDefault<string>("Discord:Prefix", Context.Guild.Id)}role help");
/* /*
* Add the string to the Embed * Add the string to the Embed

View File

@ -24,7 +24,7 @@ namespace ChaosBot.Discord.Modules.User
embed.WithColor(new Color(255, 255, 0)); embed.WithColor(new Color(255, 255, 0));
embed.Title = $"Information {config.GetValue<string>("Bot:Name")} v{config.GetValue<string>("Bot:Version")}"; embed.Title = $"Information {config.GetValue<string>("Bot:Name")} v{config.GetValue<string>("Bot:Version")}";
sb.AppendLine($"Prefix: {config.GetValue("Discord:Prefix", default(string), Context.Guild.Id)}"); sb.AppendLine($"Prefix: {config.GetValueGlobalDefault<string>("Discord:Prefix", Context.Guild.Id)}");
/* /*
* Add the string to the Embed * Add the string to the Embed

View File

@ -73,28 +73,29 @@ namespace ChaosBot.Discord.Modules.User
{ {
var sb = new StringBuilder(); var sb = new StringBuilder();
var embed = new EmbedBuilder(); var embed = new EmbedBuilder();
Configuration config = new Configuration();
embed.WithColor(new Color(255, 255, 0)); embed.WithColor(new Color(255, 255, 0));
embed.Title = "Lodestone API Help"; embed.Title = "Lodestone API Help";
sb.AppendLine(); sb.AppendLine();
sb.AppendLine(); sb.AppendLine();
sb.AppendLine("To get FreeCompany Info:"); sb.AppendLine("To get FreeCompany Info:");
sb.AppendLine($"By Id: {ConfigurationRepository.GetValue("Discord:Prefix", Context.Guild.Id, "!")}lodestone freecompany 9231394073691143535"); sb.AppendLine($"By Id: {config.GetValueGlobalDefault<string>("Discord:Prefix", Context.Guild.Id)}lodestone freecompany 9231394073691143535");
sb.AppendLine($"By Name: {ConfigurationRepository.GetValue("Discord:Prefix", Context.Guild.Id, "!")}lodestone freecompany Siren Helix"); sb.AppendLine($"By Name: {config.GetValueGlobalDefault<string>("Discord:Prefix", Context.Guild.Id)}lodestone freecompany Siren Helix");
sb.AppendLine(); sb.AppendLine();
sb.AppendLine("To get Character Info:"); sb.AppendLine("To get Character Info:");
sb.AppendLine($"By Id: {ConfigurationRepository.GetValue("Discord:Prefix", Context.Guild.Id, "!")}lodestone character 9231394073691143535"); sb.AppendLine($"By Id: {config.GetValueGlobalDefault<string>("Discord:Prefix", Context.Guild.Id)}lodestone character 9231394073691143535");
sb.AppendLine($"By Name: {ConfigurationRepository.GetValue("Discord:Prefix", Context.Guild.Id, "!")}lodestone character Siren Luna Kaisar"); sb.AppendLine($"By Name: {config.GetValueGlobalDefault<string>("Discord:Prefix", Context.Guild.Id)}lodestone character Siren Luna Kaisar");
if (CheckPermissions.CheckPerms(Context, "lodestone.link")) if (CheckPermissions.CheckPerms(Context, "lodestone.link"))
{ {
sb.AppendLine("To Link your Character:"); sb.AppendLine("To Link your Character:");
sb.AppendLine($"By Id: {ConfigurationRepository.GetValue("Discord:Prefix", Context.Guild.Id, "!")}lodestone link 9231394073691143535"); sb.AppendLine($"By Id: {config.GetValueGlobalDefault<string>("Discord:Prefix", Context.Guild.Id)}lodestone link 9231394073691143535");
sb.AppendLine($"By Name: {ConfigurationRepository.GetValue("Discord:Prefix", Context.Guild.Id, "!")}lodestone link Siren Luna Kaisar"); sb.AppendLine($"By Name: {config.GetValueGlobalDefault<string>("Discord:Prefix", Context.Guild.Id)}lodestone link Siren Luna Kaisar");
} }
sb.AppendLine(); sb.AppendLine();
sb.AppendLine(); sb.AppendLine();
sb.AppendLine("To view this help:"); sb.AppendLine("To view this help:");
sb.AppendLine($"{ConfigurationRepository.GetValue("Discord:Prefix", Context.Guild.Id, "!")}config help"); sb.AppendLine($"{config.GetValueGlobalDefault<string>("Discord:Prefix", Context.Guild.Id)}config help");
/* /*
* Add the string to the Embed * Add the string to the Embed

View File

@ -76,19 +76,20 @@ namespace ChaosBot.Discord.Modules.User
{ {
var sb = new StringBuilder(); var sb = new StringBuilder();
var embed = new EmbedBuilder(); var embed = new EmbedBuilder();
Configuration config = new Configuration();
embed.WithColor(new Color(255, 255, 0)); embed.WithColor(new Color(255, 255, 0));
embed.Title = "Points system"; embed.Title = "Points system";
sb.AppendLine($"{Context.User.Mention} has requested points information."); sb.AppendLine($"{Context.User.Mention} has requested points information.");
sb.AppendLine(); sb.AppendLine();
sb.AppendLine("Usage:"); sb.AppendLine("Usage:");
sb.AppendLine($"{ConfigurationRepository.GetValue("Discord:Prefix", Context.Guild.Id, "!")}points info"); sb.AppendLine($"{config.GetValueGlobalDefault<string>("Discord:Prefix", Context.Guild.Id)}points info");
sb.AppendLine($"{ConfigurationRepository.GetValue("Discord:Prefix", Context.Guild.Id, "!")}points help"); sb.AppendLine($"{config.GetValueGlobalDefault<string>("Discord:Prefix", Context.Guild.Id)}points help");
sb.AppendLine(); sb.AppendLine();
sb.AppendLine("Moderation commands:"); sb.AppendLine("Moderation commands:");
sb.AppendLine($"{ConfigurationRepository.GetValue("Discord:Prefix", Context.Guild.Id, "!")}points add <discord mention> <amount>"); sb.AppendLine($"{config.GetValueGlobalDefault<string>("Discord:Prefix", Context.Guild.Id)}points add <discord mention> <amount>");
sb.AppendLine($"{ConfigurationRepository.GetValue("Discord:Prefix", Context.Guild.Id, "!")}point remove <discord mention> <amount>"); sb.AppendLine($"{config.GetValueGlobalDefault<string>("Discord:Prefix", Context.Guild.Id)}point remove <discord mention> <amount>");
sb.AppendLine($"{ConfigurationRepository.GetValue("Discord:Prefix", Context.Guild.Id, "!")}point delete <discord mention>"); sb.AppendLine($"{config.GetValueGlobalDefault<string>("Discord:Prefix", Context.Guild.Id)}point delete <discord mention>");
/* /*
* Add the string to the Embed * Add the string to the Embed

View File

@ -85,23 +85,24 @@ namespace ChaosBot.Discord.Modules.User
{ {
var sb = new StringBuilder(); var sb = new StringBuilder();
var embed = new EmbedBuilder(); var embed = new EmbedBuilder();
Configuration config = new Configuration();
embed.WithColor(new Color(255, 255, 0)); embed.WithColor(new Color(255, 255, 0));
embed.Title = "Raffle system"; embed.Title = "Raffle system";
sb.AppendLine($"{Context.User.Mention} has requested Raffle information."); sb.AppendLine($"{Context.User.Mention} has requested Raffle information.");
sb.AppendLine(); sb.AppendLine();
sb.AppendLine("Usage:"); sb.AppendLine("Usage:");
sb.AppendLine($"{ConfigurationRepository.GetValue("Discord:Prefix", Context.Guild.Id, "!")}raffle info"); sb.AppendLine($"{config.GetValueGlobalDefault<string>("Discord:Prefix", Context.Guild.Id)}raffle info");
sb.AppendLine($"{ConfigurationRepository.GetValue("Discord:Prefix", Context.Guild.Id, "!")}raffle help"); sb.AppendLine($"{config.GetValueGlobalDefault<string>("Discord:Prefix", Context.Guild.Id)}raffle help");
sb.AppendLine($"{ConfigurationRepository.GetValue("Discord:Prefix", Context.Guild.Id, "!")}raffle buy <amount>"); sb.AppendLine($"{config.GetValueGlobalDefault<string>("Discord:Prefix", Context.Guild.Id)}raffle buy <amount>");
sb.AppendLine(); sb.AppendLine();
sb.AppendLine("Moderation commands:"); sb.AppendLine("Moderation commands:");
if(CheckPermissions.CheckPerms(Context, "raffle.add", "Admin")) if(CheckPermissions.CheckPerms(Context, "raffle.add", "Admin"))
sb.AppendLine($"{ConfigurationRepository.GetValue("Discord:Prefix", Context.Guild.Id, "!")}raffle add <discord mention> <amount>"); sb.AppendLine($"{config.GetValueGlobalDefault<string>("Discord:Prefix", Context.Guild.Id)}raffle add <discord mention> <amount>");
if(CheckPermissions.CheckPerms(Context, "raffle.remove", "Admin")) if(CheckPermissions.CheckPerms(Context, "raffle.remove", "Admin"))
{ {
sb.AppendLine($"{ConfigurationRepository.GetValue("Discord:Prefix", Context.Guild.Id, "!")}raffle remove <discord mention> <amount>"); sb.AppendLine($"{config.GetValueGlobalDefault<string>("Discord:Prefix", Context.Guild.Id)}raffle remove <discord mention> <amount>");
sb.AppendLine($"{ConfigurationRepository.GetValue("Discord:Prefix", Context.Guild.Id, "!")}raffle delete <discord mention>"); sb.AppendLine($"{config.GetValueGlobalDefault<string>("Discord:Prefix", Context.Guild.Id)}raffle delete <discord mention>");
} }
/* /*
* Add the string to the Embed * Add the string to the Embed
@ -279,7 +280,7 @@ namespace ChaosBot.Discord.Modules.User
else else
{ {
await ReplyAsync( await ReplyAsync(
$"{Context.User.Mention}, if you wish to clear ALL tickets, please send the below command.```{ConfigurationRepository.GetValue("Discord:Prefix", Context.Guild.Id, "!")}raffle clear confirm```"); $"{Context.User.Mention}, if you wish to clear ALL tickets, please send the below command.```{new Configuration().GetValueGlobalDefault<string>("Discord:Prefix", Context.Guild.Id)}raffle clear confirm```");
} }
} }
catch (Exception ex) catch (Exception ex)

View File

@ -32,8 +32,7 @@ namespace ChaosBot.Discord.PreConditions
if (context.Guild == null) throw new Exception("This must be run in a guild"); if (context.Guild == null) throw new Exception("This must be run in a guild");
// Check if module enabled in database // Check if module enabled in database
return Convert.ToBoolean(ConfigurationRepository.GetValue<string>($"Module:{moduleName}:Enabled", return new Configuration().GetValue<bool>($"Module:{moduleName}:Enabled", true, context.Guild.Id);
context.Guild.Id, "true"));
} }
} }
} }

View File

@ -66,13 +66,14 @@ namespace ChaosBot.Discord.Services
SocketCommandContext context = new SocketCommandContext(_client, message); SocketCommandContext context = new SocketCommandContext(_client, message);
Configuration config = new Configuration();
int argPos = 0; int argPos = 0;
string prefix = ConfigurationRepository.GetValue("Discord:Prefix", context.Guild.Id, "!"); string prefix = config.GetValueGlobalDefault<string>("Discord:Prefix", context.Guild.Id);
if (!(message.HasMentionPrefix(_client.CurrentUser, ref argPos) || if (!(message.HasMentionPrefix(_client.CurrentUser, ref argPos) ||
message.HasStringPrefix(prefix, ref argPos))) message.HasStringPrefix(prefix, ref argPos)))
{ {
if(Convert.ToBoolean(ConfigurationRepository.GetValue("Experience:Commands", context.Guild.Id, "false"))) if(config.GetValue("Module:Experience:Enabled", false, context.Guild.Id))
ExperienceHandler.AddXp(context); ExperienceHandler.AddXp(context);
return; return;
} }

View File

@ -66,12 +66,13 @@ namespace ChaosBot.Discord.Services
{ {
// The user has leveled up, we can send a message // The user has leveled up, we can send a message
LoggingFacade.Info($"User leveled up [{context.User.Username}#{context.User.Discriminator} -> Level {newLevel}]"); LoggingFacade.Info($"User leveled up [{context.User.Username}#{context.User.Discriminator} -> Level {newLevel}]");
Configuration config = new Configuration();
string channelToSendIn = string channelToSendIn =
ConfigurationRepository.GetValue("LevelUp:Channel", context.Guild.Id, "false"); config.GetValue<string>("LevelUp:Channel", null, context.Guild.Id);
string mentionString = $"<@{context.User.Id}>"; string mentionString = $"<@{context.User.Id}>";
if (!Convert.ToBoolean(ConfigurationRepository.GetValue("LevelUp:MentionUser", context.Guild.Id, "true"))) if (!config.GetValueGlobalDefault<bool>("LevelUp:MentionUser", context.Guild.Id))
{ {
mentionString = context.User.Username; mentionString = context.User.Username;
if (context.User is IGuildUser guildUser) if (context.User is IGuildUser guildUser)

View File

@ -42,7 +42,7 @@ namespace ChaosBot.WebServer
{ {
LoggingFacade.Info("Initializing Kestrel Startup and Configuration"); LoggingFacade.Info("Initializing Kestrel Startup and Configuration");
if (new Configuration().GetValue("WebServer:Debug", false)) if (new Configuration().GetValueGlobalDefault<bool>("WebServer:Debug"))
app.UseDeveloperExceptionPage(); app.UseDeveloperExceptionPage();
app.UseForwardedHeaders(); app.UseForwardedHeaders();

View File

@ -28,7 +28,7 @@ namespace ChaosBot.WebServer
webBuilder.UseWebRoot(webRoot); webBuilder.UseWebRoot(webRoot);
webBuilder.ConfigureKestrel(serverOptions => webBuilder.ConfigureKestrel(serverOptions =>
{ {
serverOptions.Listen(IPAddress.Any, config.GetValue("WebServer:Port", 80), serverOptions.Listen(IPAddress.Any, config.GetValueGlobalDefault<int>("WebServer:Port"),
listenOptions => listenOptions =>
{ {
listenOptions.UseConnectionLogging(); listenOptions.UseConnectionLogging();