Reformatting code

This commit is contained in:
2023-11-21 22:04:38 +02:00
parent 79ecff971b
commit 944d59d9a3
37 changed files with 509 additions and 486 deletions

View File

@@ -5,12 +5,12 @@ using PluginManager.Others;
namespace DiscordBot.Bot.Actions; namespace DiscordBot.Bot.Actions;
public class Clear : ICommandAction public class Clear: ICommandAction
{ {
public string ActionName => "clear"; public string ActionName => "clear";
public string Description => "Clears the console"; public string Description => "Clears the console";
public string Usage => "clear"; public string Usage => "clear";
public InternalActionRunType RunType => InternalActionRunType.ON_CALL; public InternalActionRunType RunType => InternalActionRunType.ON_CALL;
public Task Execute(string[] args) public Task Execute(string[] args)
{ {

View File

@@ -6,12 +6,12 @@ using PluginManager.Others;
namespace DiscordBot.Bot.Actions; namespace DiscordBot.Bot.Actions;
public class Exit : ICommandAction public class Exit: ICommandAction
{ {
public string ActionName => "exit"; public string ActionName => "exit";
public string Description => "Exits the bot and saves the config. Use exit help for more info."; public string Description => "Exits the bot and saves the config. Use exit help for more info.";
public string Usage => "exit [help|force (-f)]"; public string Usage => "exit [help|force (-f)]";
public InternalActionRunType RunType => InternalActionRunType.ON_CALL; public InternalActionRunType RunType => InternalActionRunType.ON_CALL;
public async Task Execute(string[] args) public async Task Execute(string[] args)
{ {
@@ -23,7 +23,7 @@ public class Exit : ICommandAction
} }
else else
{ {
switch ( args[0] ) switch (args[0])
{ {
case "help": case "help":
Console.WriteLine("Usage : exit [help|force]"); Console.WriteLine("Usage : exit [help|force]");

View File

@@ -19,20 +19,20 @@ internal static class PluginMethods
internal static async Task List(PluginsManager manager) internal static async Task List(PluginsManager manager)
{ {
var data = await ConsoleUtilities.ExecuteWithProgressBar(manager.GetAvailablePlugins(), "Loading plugins..."); var data = await ConsoleUtilities.ExecuteWithProgressBar(manager.GetAvailablePlugins(), "Loading plugins...");
TableData tableData = new(new List<string> { "Name", "Description", "Type", "Version" }); TableData tableData = new(new List<string> { "Name", "Description", "Type", "Version" });
foreach (var plugin in data) tableData.AddRow(plugin); foreach (var plugin in data) tableData.AddRow(plugin);
tableData.HasRoundBorders = false; tableData.HasRoundBorders = false;
tableData.PrintAsTable(); tableData.PrintAsTable();
} }
internal static async Task RefreshPlugins(bool quiet) internal static async Task RefreshPlugins(bool quiet)
{ {
await Program.internalActionManager.Execute("plugin", "load", quiet ? "-q" : string.Empty); await Program.internalActionManager.Execute("plugin", "load", quiet ? "-q" : string.Empty);
await Program.internalActionManager.Refresh(); await Program.internalActionManager.Refresh();
} }
internal static async Task DownloadPlugin(PluginsManager manager, string pluginName) internal static async Task DownloadPlugin(PluginsManager manager, string pluginName)
{ {
var pluginData = await manager.GetPluginLinkByName(pluginName); var pluginData = await manager.GetPluginLinkByName(pluginName);
@@ -42,30 +42,32 @@ internal static class PluginMethods
return; return;
} }
var pluginType = pluginData[0]; var pluginType = pluginData[0];
var pluginLink = pluginData[1]; var pluginLink = pluginData[1];
var pluginRequirements = pluginData[2]; var pluginRequirements = pluginData[2];
await AnsiConsole.Progress() await AnsiConsole.Progress()
.Columns(new ProgressColumn[] .Columns(new ProgressColumn[]
{ {
new TaskDescriptionColumn(), new TaskDescriptionColumn(),
new ProgressBarColumn(), new ProgressBarColumn(),
new PercentageColumn() new PercentageColumn()
}) }
.StartAsync(async ctx => )
{ .StartAsync(async ctx =>
var downloadTask = ctx.AddTask("Downloading plugin..."); {
var downloadTask = ctx.AddTask("Downloading plugin...");
IProgress<float> progress = new Progress<float>(p => { downloadTask.Value = p; }); IProgress<float> progress = new Progress<float>(p => { downloadTask.Value = p; });
await ServerCom.DownloadFileAsync(pluginLink, $"./Data/{pluginType}s/{pluginName}.dll", progress); await ServerCom.DownloadFileAsync(pluginLink, $"./Data/{pluginType}s/{pluginName}.dll", progress);
downloadTask.Increment(100); downloadTask.Increment(100);
ctx.Refresh(); ctx.Refresh();
}); }
);
if (pluginRequirements == string.Empty) if (pluginRequirements == string.Empty)
{ {
@@ -75,150 +77,162 @@ internal static class PluginMethods
} }
List<string> requirementsUrLs = new(); List<string> requirementsUrLs = new();
await AnsiConsole.Progress() await AnsiConsole.Progress()
.Columns(new ProgressColumn[] .Columns(new ProgressColumn[]
{ {
new TaskDescriptionColumn(), new TaskDescriptionColumn(),
new ProgressBarColumn(), new ProgressBarColumn(),
new PercentageColumn() new PercentageColumn()
}) }
.StartAsync(async ctx => )
{ .StartAsync(async ctx =>
var gatherInformationTask = ctx.AddTask("Gathering info..."); {
gatherInformationTask.IsIndeterminate = true; var gatherInformationTask = ctx.AddTask("Gathering info...");
requirementsUrLs = await ServerCom.ReadTextFromURL(pluginRequirements); gatherInformationTask.IsIndeterminate = true;
requirementsUrLs = await ServerCom.ReadTextFromURL(pluginRequirements);
gatherInformationTask.Increment(100);
}); gatherInformationTask.Increment(100);
}
);
List<Tuple<ProgressTask, IProgress<float>, string, string>> downloadTasks = new(); List<Tuple<ProgressTask, IProgress<float>, string, string>> downloadTasks = new();
await AnsiConsole.Progress() await AnsiConsole.Progress()
.Columns(new ProgressColumn[] .Columns(new ProgressColumn[]
{ {
new TaskDescriptionColumn(), new TaskDescriptionColumn(),
new ProgressBarColumn(), new ProgressBarColumn(),
new PercentageColumn() new PercentageColumn()
}) }
.StartAsync(async ctx => )
{ .StartAsync(async ctx =>
{
foreach (var info in requirementsUrLs)
{
if (info.Length < 2) continue;
string[] data = info.Split(',');
string url = data[0];
string fileName = data[1];
var task = ctx.AddTask($"Downloading {fileName}: ");
IProgress<float> progress = new Progress<float>(p =>
{
task.Value = p;
});
task.IsIndeterminate = true; foreach (var info in requirementsUrLs)
downloadTasks.Add(new Tuple<ProgressTask, IProgress<float>, string, string>(task, progress, url, fileName)); {
} if (info.Length < 2) continue;
string[] data = info.Split(',');
string url = data[0];
string fileName = data[1];
if (!int.TryParse(Config.AppSettings["MaxParallelDownloads"], out int maxParallelDownloads)) var task = ctx.AddTask($"Downloading {fileName}: ");
{ IProgress<float> progress = new Progress<float>(p =>
maxParallelDownloads = 5; {
Config.AppSettings.Add("MaxParallelDownloads", "5"); task.Value = p;
await Config.AppSettings.SaveToFile(); }
} );
var options = new ParallelOptions()
{
MaxDegreeOfParallelism = maxParallelDownloads,
TaskScheduler = TaskScheduler.Default
};
await Parallel.ForEachAsync(downloadTasks, options, async (tuple, token) => task.IsIndeterminate = true;
{ downloadTasks.Add(new Tuple<ProgressTask, IProgress<float>, string, string>(task, progress, url, fileName));
tuple.Item1.IsIndeterminate = false; }
await ServerCom.DownloadFileAsync(tuple.Item3, $"./{tuple.Item4}", tuple.Item2);
}); if (!int.TryParse(Config.AppSettings["MaxParallelDownloads"], out int maxParallelDownloads))
{
maxParallelDownloads = 5;
Config.AppSettings.Add("MaxParallelDownloads", "5");
await Config.AppSettings.SaveToFile();
}
var options = new ParallelOptions()
{
MaxDegreeOfParallelism = maxParallelDownloads,
TaskScheduler = TaskScheduler.Default
};
await Parallel.ForEachAsync(downloadTasks, options, async (tuple, token) =>
{
tuple.Item1.IsIndeterminate = false;
await ServerCom.DownloadFileAsync(tuple.Item3, $"./{tuple.Item4}", tuple.Item2);
}
);
}
);
});
await RefreshPlugins(false); await RefreshPlugins(false);
} }
internal static async Task<bool> LoadPlugins(string[] args) internal static async Task<bool> LoadPlugins(string[] args)
{ {
var loader = new PluginLoader(Config.DiscordBot.client); var loader = new PluginLoader(Config.DiscordBot.client);
if (args.Length == 2 && args[1] == "-q") if (args.Length == 2 && args[1] == "-q")
{ {
loader.LoadPlugins(); loader.LoadPlugins();
return true; return true;
} }
var cc = Console.ForegroundColor; var cc = Console.ForegroundColor;
loader.onCMDLoad += (name, typeName, success, exception) => loader.onCMDLoad += (name, typeName, success, exception) =>
{ {
if (name == null || name.Length < 2) if (name == null || name.Length < 2)
name = typeName; name = typeName;
if (success) if (success)
{ {
Config.Logger.Log("Successfully loaded command : " + name, source: typeof(ICommandAction), Config.Logger.Log("Successfully loaded command : " + name, source: typeof(ICommandAction),
type: LogType.INFO); type: LogType.INFO
} );
}
else else
{ {
Config.Logger.Log("Failed to load command : " + name + " because " + exception?.Message, Config.Logger.Log("Failed to load command : " + name + " because " + exception?.Message,
source: typeof(ICommandAction), type: LogType.ERROR); source: typeof(ICommandAction), type: LogType.ERROR
} );
}
Console.ForegroundColor = cc; Console.ForegroundColor = cc;
}; };
loader.onEVELoad += (name, typeName, success, exception) => loader.onEVELoad += (name, typeName, success, exception) =>
{ {
if (name == null || name.Length < 2) if (name == null || name.Length < 2)
name = typeName; name = typeName;
if (success) if (success)
{ {
Config.Logger.Log("Successfully loaded event : " + name, source: typeof(ICommandAction), Config.Logger.Log("Successfully loaded event : " + name, source: typeof(ICommandAction),
type: LogType.INFO); type: LogType.INFO
} );
else }
{ else
Config.Logger.Log("Failed to load event : " + name + " because " + exception?.Message, {
source: typeof(ICommandAction), type: LogType.ERROR); Config.Logger.Log("Failed to load event : " + name + " because " + exception?.Message,
} source: typeof(ICommandAction), type: LogType.ERROR
);
}
Console.ForegroundColor = cc; Console.ForegroundColor = cc;
}; };
loader.onSLSHLoad += (name, typeName, success, exception) => loader.onSLSHLoad += (name, typeName, success, exception) =>
{ {
if (name == null || name.Length < 2) if (name == null || name.Length < 2)
name = typeName; name = typeName;
if (success) if (success)
{ {
Config.Logger.Log("Successfully loaded slash command : " + name, source: typeof(ICommandAction), Config.Logger.Log("Successfully loaded slash command : " + name, source: typeof(ICommandAction),
type: LogType.INFO); type: LogType.INFO
} );
else }
{ else
Config.Logger.Log("Failed to load slash command : " + name + " because " + exception?.Message, {
source: typeof(ICommandAction), type: LogType.ERROR); Config.Logger.Log("Failed to load slash command : " + name + " because " + exception?.Message,
} source: typeof(ICommandAction), type: LogType.ERROR
);
}
Console.ForegroundColor = cc; Console.ForegroundColor = cc;
}; };
loader.LoadPlugins(); loader.LoadPlugins();
Console.ForegroundColor = cc; Console.ForegroundColor = cc;
return true; return true;
} }
} }

View File

@@ -5,26 +5,26 @@ namespace DiscordBot.Bot.Actions.Extra;
internal static class SettingsConfigExtra internal static class SettingsConfigExtra
{ {
internal static void SetSettings(string key, params string[] value) internal static void SetSettings(string key, params string[] value)
{ {
if (key is null) return; if (key is null) return;
if (value is null) return; if (value is null) return;
if (!Config.AppSettings.ContainsKey(key)) if (!Config.AppSettings.ContainsKey(key))
return; return;
Config.AppSettings[key] = string.Join(' ', value); Config.AppSettings[key] = string.Join(' ', value);
// Config.AppSettings.SaveToFile().Wait(); // Config.AppSettings.SaveToFile().Wait();
} }
internal static void RemoveSettings(string key) internal static void RemoveSettings(string key)
{ {
if (key is null) return; if (key is null) return;
if(!Config.AppSettings.ContainsKey(key)) if (!Config.AppSettings.ContainsKey(key))
return; return;
Config.AppSettings.Remove(key); Config.AppSettings.Remove(key);
} }
@@ -33,11 +33,11 @@ internal static class SettingsConfigExtra
if (key is null) return; if (key is null) return;
if (value is null) return; if (value is null) return;
if (Config.AppSettings.ContainsKey(key)) if (Config.AppSettings.ContainsKey(key))
return; return;
Config.AppSettings.Add(key, string.Join(' ', value)); Config.AppSettings.Add(key, string.Join(' ', value));
// Config.AppSettings.SaveToFile().Wait(); // Config.AppSettings.SaveToFile().Wait();
} }
} }

View File

@@ -7,7 +7,7 @@ using PluginManager.Others;
namespace DiscordBot.Bot.Actions; namespace DiscordBot.Bot.Actions;
public class Help : ICommandAction public class Help: ICommandAction
{ {
public string ActionName => "help"; public string ActionName => "help";
@@ -34,8 +34,8 @@ public class Help : ICommandAction
items.Add(new[] { "-", "-", "-" }); items.Add(new[] { "-", "-", "-" });
ConsoleUtilities.FormatAndAlignTable(items, ConsoleUtilities.FormatAndAlignTable(items,
TableFormat.CENTER_EACH_COLUMN_BASED TableFormat.CENTER_EACH_COLUMN_BASED
); );
return; return;
} }
@@ -56,7 +56,7 @@ public class Help : ICommandAction
}; };
ConsoleUtilities.FormatAndAlignTable(actionData, ConsoleUtilities.FormatAndAlignTable(actionData,
TableFormat.CENTER_EACH_COLUMN_BASED TableFormat.CENTER_EACH_COLUMN_BASED
); );
} }
} }

View File

@@ -12,7 +12,7 @@ using Spectre.Console;
namespace DiscordBot.Bot.Actions; namespace DiscordBot.Bot.Actions;
public class Plugin : ICommandAction public class Plugin: ICommandAction
{ {
private bool pluginsLoaded; private bool pluginsLoaded;
public string ActionName => "plugin"; public string ActionName => "plugin";
@@ -46,7 +46,7 @@ public class Plugin : ICommandAction
case "refresh": case "refresh":
await PluginMethods.RefreshPlugins(true); await PluginMethods.RefreshPlugins(true);
break; break;
case "list": case "list":
await PluginMethods.List(manager); await PluginMethods.List(manager);
break; break;
@@ -56,7 +56,7 @@ public class Plugin : ICommandAction
Config.Logger.Log("Plugins already loaded", source: typeof(ICommandAction), type: LogType.WARNING); Config.Logger.Log("Plugins already loaded", source: typeof(ICommandAction), type: LogType.WARNING);
break; break;
} }
if (Config.DiscordBot is null) if (Config.DiscordBot is null)
{ {
Config.Logger.Log("DiscordBot is null", source: typeof(ICommandAction), type: LogType.WARNING); Config.Logger.Log("DiscordBot is null", source: typeof(ICommandAction), type: LogType.WARNING);
@@ -84,4 +84,4 @@ public class Plugin : ICommandAction
break; break;
} }
} }
} }

View File

@@ -7,7 +7,7 @@ using PluginManager.Others;
namespace DiscordBot.Bot.Actions; namespace DiscordBot.Bot.Actions;
public class SettingsConfig : ICommandAction public class SettingsConfig: ICommandAction
{ {
public string ActionName => "config"; public string ActionName => "config";
public string Description => "Change the settings of the bot"; public string Description => "Change the settings of the bot";
@@ -19,7 +19,7 @@ public class SettingsConfig : ICommandAction
{ {
foreach (var settings in Config.AppSettings) foreach (var settings in Config.AppSettings)
Console.WriteLine(settings.Key + ": " + settings.Value); Console.WriteLine(settings.Key + ": " + settings.Value);
return Task.CompletedTask; return Task.CompletedTask;
} }
@@ -27,25 +27,25 @@ public class SettingsConfig : ICommandAction
{ {
case "-s": case "-s":
case "set": case "set":
if(args.Length < 3) if (args.Length < 3)
return Task.CompletedTask; return Task.CompletedTask;
SettingsConfigExtra.SetSettings(args[1],args[2..]); SettingsConfigExtra.SetSettings(args[1], args[2..]);
break; break;
case "-r": case "-r":
case "remove": case "remove":
if(args.Length < 2) if (args.Length < 2)
return Task.CompletedTask; return Task.CompletedTask;
SettingsConfigExtra.RemoveSettings(args[1]); SettingsConfigExtra.RemoveSettings(args[1]);
break; break;
case "-a": case "-a":
case "add": case "add":
if(args.Length < 3) if (args.Length < 3)
return Task.CompletedTask; return Task.CompletedTask;
SettingsConfigExtra.AddSettings(args[1], args[2..]); SettingsConfigExtra.AddSettings(args[1], args[2..]);
break; break;
case "-h": case "-h":
case "-help": case "-help":
Console.WriteLine("Options:"); Console.WriteLine("Options:");
@@ -54,14 +54,14 @@ public class SettingsConfig : ICommandAction
Console.WriteLine("-a <settingName> <newValue>: Add a setting"); Console.WriteLine("-a <settingName> <newValue>: Add a setting");
Console.WriteLine("-h: Show this help message"); Console.WriteLine("-h: Show this help message");
break; break;
default: default:
Console.WriteLine("Invalid option"); Console.WriteLine("Invalid option");
return Task.CompletedTask; return Task.CompletedTask;
} }
return Task.CompletedTask; return Task.CompletedTask;
} }
} }

View File

@@ -10,7 +10,7 @@ namespace DiscordBot.Bot.Commands;
/// <summary> /// <summary>
/// The help command /// The help command
/// </summary> /// </summary>
internal class Help : DBCommand internal class Help: DBCommand
{ {
/// <summary> /// <summary>
/// Command name /// Command name
@@ -76,7 +76,7 @@ internal class Help : DBCommand
var embedBuilder = new EmbedBuilder(); var embedBuilder = new EmbedBuilder();
var cmd = PluginLoader.Commands.Find(p => p.Command == command || var cmd = PluginLoader.Commands.Find(p => p.Command == command ||
p.Aliases is not null && p.Aliases.Contains(command) p.Aliases is not null && p.Aliases.Contains(command)
); );
if (cmd == null) return null; if (cmd == null) return null;
embedBuilder.AddField("Usage", Config.AppSettings["prefix"] + cmd.Usage); embedBuilder.AddField("Usage", Config.AppSettings["prefix"] + cmd.Usage);

View File

@@ -8,11 +8,11 @@ using PluginManager.Others;
namespace DiscordBot.Bot.Commands.SlashCommands; namespace DiscordBot.Bot.Commands.SlashCommands;
public class Help : DBSlashCommand public class Help: DBSlashCommand
{ {
public string Name => "help"; public string Name => "help";
public string Description => "This command allows you to check all loaded commands"; public string Description => "This command allows you to check all loaded commands";
public bool canUseDM => true; public bool canUseDM => true;
public List<SlashCommandOptionBuilder> Options => public List<SlashCommandOptionBuilder> Options =>
new() new()

View File

@@ -29,13 +29,13 @@
<None Remove="Data\**"/> <None Remove="Data\**"/>
<None Remove="obj\**"/> <None Remove="obj\**"/>
<None Remove="Output\**"/> <None Remove="Output\**"/>
<None Remove="builder.bat" /> <None Remove="builder.bat"/>
<None Remove="builder.sh" /> <None Remove="builder.sh"/>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Discord.Net" Version="3.11.0"/> <PackageReference Include="Discord.Net" Version="3.11.0"/>
<PackageReference Include="pythonnet" Version="3.0.1" /> <PackageReference Include="pythonnet" Version="3.0.1"/>
<PackageReference Include="Spectre.Console" Version="0.47.0" /> <PackageReference Include="Spectre.Console" Version="0.47.0"/>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\PluginManager\PluginManager.csproj"/> <ProjectReference Include="..\PluginManager\PluginManager.csproj"/>

View File

@@ -16,16 +16,16 @@ public static class Entry
File.Delete(plugin); File.Delete(plugin);
} }
} }
#endif #endif
var currentDomain = AppDomain.CurrentDomain; var currentDomain = AppDomain.CurrentDomain;
currentDomain.AssemblyResolve += LoadFromSameFolder; currentDomain.AssemblyResolve += LoadFromSameFolder;
static Assembly LoadFromSameFolder(object sender, ResolveEventArgs args) static Assembly LoadFromSameFolder(object sender, ResolveEventArgs args)
{ {
var folderPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "./Libraries"); var folderPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "./Libraries");
var assemblyPath = Path.Combine(folderPath, new AssemblyName(args.Name).Name + ".dll"); var assemblyPath = Path.Combine(folderPath, new AssemblyName(args.Name).Name + ".dll");
if (!File.Exists(assemblyPath)) return null; if (!File.Exists(assemblyPath)) return null;
var assembly = Assembly.LoadFrom(assemblyPath); var assembly = Assembly.LoadFrom(assemblyPath);

View File

@@ -9,9 +9,9 @@ public static class Installer
{ {
AnsiConsole.MarkupLine("Welcome to the [bold]SethBot[/] installer !"); AnsiConsole.MarkupLine("Welcome to the [bold]SethBot[/] installer !");
AnsiConsole.MarkupLine("First, we need to configure the bot. Don't worry, it will be quick !"); AnsiConsole.MarkupLine("First, we need to configure the bot. Don't worry, it will be quick !");
var token = AnsiConsole.Ask<string>("Please enter the bot [yellow]token[/]:"); var token = AnsiConsole.Ask<string>("Please enter the bot [yellow]token[/]:");
var prefix = AnsiConsole.Ask<string>("Please enter the bot [yellow]prefix[/]:"); var prefix = AnsiConsole.Ask<string>("Please enter the bot [yellow]prefix[/]:");
var serverId = AnsiConsole.Ask<string>("Please enter the [yellow]Server ID[/]:"); var serverId = AnsiConsole.Ask<string>("Please enter the [yellow]Server ID[/]:");
if (string.IsNullOrWhiteSpace(serverId)) serverId = "NULL"; if (string.IsNullOrWhiteSpace(serverId)) serverId = "NULL";
@@ -20,9 +20,9 @@ public static class Installer
Config.AppSettings.Add("ServerID", serverId); Config.AppSettings.Add("ServerID", serverId);
Config.AppSettings.SaveToFile(); Config.AppSettings.SaveToFile();
AnsiConsole.MarkupLine("[bold]Config saved ![/]"); AnsiConsole.MarkupLine("[bold]Config saved ![/]");
Config.Logger.Log("Config Saved", source: typeof(Installer)); Config.Logger.Log("Config Saved", source: typeof(Installer));
} }
} }

View File

@@ -22,9 +22,9 @@ public class Program
public static void Startup(string[] args) public static void Startup(string[] args)
{ {
PreLoadComponents(args).Wait(); PreLoadComponents(args).Wait();
if (!AppSettings.ContainsKey("ServerID") || !AppSettings.ContainsKey("token") || !AppSettings.ContainsKey("prefix")) if (!AppSettings.ContainsKey("ServerID") || !AppSettings.ContainsKey("token") || !AppSettings.ContainsKey("prefix"))
Installer.GenerateStartupConfig(); Installer.GenerateStartupConfig();
HandleInput().Wait(); HandleInput().Wait();
} }
@@ -37,8 +37,8 @@ public class Program
internalActionManager.Initialize().Wait(); internalActionManager.Initialize().Wait();
internalActionManager.Execute("plugin", "load").Wait(); internalActionManager.Execute("plugin", "load").Wait();
internalActionManager.Refresh().Wait(); internalActionManager.Refresh().Wait();
while (true) while (true)
{ {
var cmd = Console.ReadLine(); var cmd = Console.ReadLine();
@@ -64,21 +64,21 @@ public class Program
Console.WriteLine($"Running on version: {Assembly.GetExecutingAssembly().GetName().Version}"); Console.WriteLine($"Running on version: {Assembly.GetExecutingAssembly().GetName().Version}");
Console.WriteLine("Git SethBot: https://github.com/andreitdr/SethDiscordBot"); Console.WriteLine("Git SethBot: https://github.com/andreitdr/SethDiscordBot");
Console.WriteLine("Git Plugins: https://github.com/andreitdr/SethPlugins"); Console.WriteLine("Git Plugins: https://github.com/andreitdr/SethPlugins");
ConsoleUtilities.WriteColorText("&rRemember to close the bot using the ShutDown command (&yexit&r) or some settings won't be saved"); ConsoleUtilities.WriteColorText("&rRemember to close the bot using the ShutDown command (&yexit&r) or some settings won't be saved");
ConsoleUtilities.WriteColorText($"Running on &m{Functions.GetOperatingSystem()}"); ConsoleUtilities.WriteColorText($"Running on &m{Functions.GetOperatingSystem()}");
Console.WriteLine("============================ LOG ============================"); Console.WriteLine("============================ LOG ============================");
Console.ForegroundColor = ConsoleColor.White; Console.ForegroundColor = ConsoleColor.White;
try try
{ {
var token = AppSettings["token"]; var token = AppSettings["token"];
var prefix = AppSettings["prefix"]; var prefix = AppSettings["prefix"];
var discordbooter = new Boot(token, prefix); var discordbooter = new Boot(token, prefix);
await discordbooter.Awake(); await discordbooter.Awake();
} }
catch ( Exception ex ) catch (Exception ex)
{ {
Logger.Log(ex.ToString(), source: typeof(Program), type: LogType.CRITICAL); Logger.Log(ex.ToString(), source: typeof(Program), type: LogType.CRITICAL);
} }
@@ -96,18 +96,20 @@ public class Program
internalActionManager = new InternalActionManager("./Data/Plugins", "*.dll"); internalActionManager = new InternalActionManager("./Data/Plugins", "*.dll");
NoGUI(); NoGUI();
} }
catch ( IOException ex ) catch (IOException ex)
{ {
if (ex.Message == "No process is on the other end of the pipe." || (uint)ex.HResult == 0x800700E9) if (ex.Message == "No process is on the other end of the pipe." || (uint)ex.HResult == 0x800700E9)
{ {
if (AppSettings.ContainsKey("LaunchMessage")) if (AppSettings.ContainsKey("LaunchMessage"))
AppSettings.Add("LaunchMessage", AppSettings.Add("LaunchMessage",
"An error occured while closing the bot last time. Please consider closing the bot using the &rexit&c method !\n" + "An error occured while closing the bot last time. Please consider closing the bot using the &rexit&c method !\n" +
"There is a risk of losing all data or corruption of the save file, which in some cases requires to reinstall the bot !"); "There is a risk of losing all data or corruption of the save file, which in some cases requires to reinstall the bot !"
);
Logger.Log("An error occured while closing the bot last time. Please consider closing the bot using the &rexit&c method !\n" + Logger.Log("An error occured while closing the bot last time. Please consider closing the bot using the &rexit&c method !\n" +
"There is a risk of losing all data or corruption of the save file, which in some cases requires to reinstall the bot !", "There is a risk of losing all data or corruption of the save file, which in some cases requires to reinstall the bot !",
source: typeof(Program), type: LogType.ERROR); source: typeof(Program), type: LogType.ERROR
);
} }
} }
} }
@@ -115,7 +117,7 @@ public class Program
private static async Task PreLoadComponents(string[] args) private static async Task PreLoadComponents(string[] args)
{ {
await Initialize(); await Initialize();
Logger.OnLog += (sender, logMessage) => Logger.OnLog += (sender, logMessage) =>
{ {
string messageColor = logMessage.Type switch string messageColor = logMessage.Type switch
@@ -133,10 +135,10 @@ public class Program
Console.WriteLine(logMessage.Message); Console.WriteLine(logMessage.Message);
return; return;
} }
AnsiConsole.MarkupLine($"{messageColor}{logMessage.ThrowTime} {logMessage.Message} [/]"); AnsiConsole.MarkupLine($"{messageColor}{logMessage.ThrowTime} {logMessage.Message} [/]");
}; };
AppSettings["Version"] = Assembly.GetExecutingAssembly().GetName().Version.ToString(); AppSettings["Version"] = Assembly.GetExecutingAssembly().GetName().Version.ToString();
} }
} }

View File

@@ -9,24 +9,24 @@ namespace DiscordBot.Utilities;
public class TableData public class TableData
{ {
public List<string> Columns; public List<string> Columns;
public List<string[]> Rows; public List<string[]> Rows;
public bool IsEmpty => Rows.Count == 0; public bool IsEmpty => Rows.Count == 0;
public bool HasRoundBorders { get; set; } = true; public bool HasRoundBorders { get; set; } = true;
public TableData(List<string> columns) public TableData(List<string> columns)
{ {
Columns = columns; Columns = columns;
Rows = new List<string[]>(); Rows = new List<string[]>();
} }
public TableData(string[] columns) public TableData(string[] columns)
{ {
Columns = columns.ToList(); Columns = columns.ToList();
Rows = new List<string[]>(); Rows = new List<string[]>();
} }
public void AddRow(string[] row) public void AddRow(string[] row)
{ {
Rows.Add(row); Rows.Add(row);
@@ -41,23 +41,23 @@ public static class ConsoleUtilities
T result = default; T result = default;
await AnsiConsole.Progress() await AnsiConsole.Progress()
.Columns( .Columns(
new ProgressColumn[] new ProgressColumn[]
{ {
new TaskDescriptionColumn(), new TaskDescriptionColumn(),
new ProgressBarColumn(), new ProgressBarColumn(),
new PercentageColumn(), new PercentageColumn(),
} }
) )
.StartAsync( .StartAsync(
async ctx => async ctx =>
{ {
var task = ctx.AddTask(message); var task = ctx.AddTask(message);
task.IsIndeterminate = true; task.IsIndeterminate = true;
result = await function; result = await function;
task.Increment(100); task.Increment(100);
} }
); );
return result; return result;
} }
@@ -66,21 +66,23 @@ public static class ConsoleUtilities
{ {
await AnsiConsole.Progress() await AnsiConsole.Progress()
.Columns(new ProgressColumn[] .Columns(new ProgressColumn[]
{ {
new TaskDescriptionColumn(), new TaskDescriptionColumn(),
new ProgressBarColumn(), new ProgressBarColumn(),
new PercentageColumn(), new PercentageColumn(),
}) }
)
.StartAsync(async ctx => .StartAsync(async ctx =>
{ {
var task = ctx.AddTask(message); var task = ctx.AddTask(message);
task.IsIndeterminate = true; task.IsIndeterminate = true;
await function; await function;
task.Increment(100); task.Increment(100);
}); }
);
} }
private static readonly Dictionary<char, ConsoleColor> Colors = new() private static readonly Dictionary<char, ConsoleColor> Colors = new()
{ {
{ 'g', ConsoleColor.Green }, { 'g', ConsoleColor.Green },
@@ -91,7 +93,7 @@ public static class ConsoleUtilities
}; };
private static readonly char ColorPrefix = '&'; private static readonly char ColorPrefix = '&';
private static bool CanAproximateTo(this float f, float y) private static bool CanAproximateTo(this float f, float y)
{ {
return MathF.Abs(f - y) < 0.000001; return MathF.Abs(f - y) < 0.000001;
@@ -104,7 +106,7 @@ public static class ConsoleUtilities
table.AddColumns(tableData.Columns.ToArray()); table.AddColumns(tableData.Columns.ToArray());
foreach (var row in tableData.Rows) foreach (var row in tableData.Rows)
table.AddRow(row); table.AddRow(row);
AnsiConsole.Write(table); AnsiConsole.Write(table);
} }
@@ -123,12 +125,12 @@ public static class ConsoleUtilities
data.RemoveAt(0); data.RemoveAt(0);
foreach (var row in data) foreach (var row in data)
table.AddRow(row); table.AddRow(row);
AnsiConsole.Write(table); AnsiConsole.Write(table);
return; return;
} }
if (format == TableFormat.CENTER_EACH_COLUMN_BASED) if (format == TableFormat.CENTER_EACH_COLUMN_BASED)
{ {
var tableLine = '-'; var tableLine = '-';
@@ -317,18 +319,18 @@ public static class ConsoleUtilities
Console.CursorVisible = false; Console.CursorVisible = false;
isRunning = true; isRunning = true;
thread = new Thread(() => thread = new Thread(() =>
{ {
while (isRunning) while (isRunning)
{ {
Console.SetCursorPosition(0, Console.CursorTop); Console.SetCursorPosition(0, Console.CursorTop);
Console.Write(" " + Sequence[position] + " " + Message + " "); Console.Write(" " + Sequence[position] + " " + Message + " ");
position++; position++;
if (position >= Sequence.Length) if (position >= Sequence.Length)
position = 0; position = 0;
Thread.Sleep(100); Thread.Sleep(100);
} }
} }
); );
thread.Start(); thread.Start();
} }

View File

@@ -78,7 +78,7 @@ public class Boot
CommonTasks(); CommonTasks();
await client.LoginAsync(TokenType.Bot, botToken); await client.LoginAsync(TokenType.Bot, botToken);
await client.StartAsync(); await client.StartAsync();
commandServiceHandler = new CommandHandler(client, service, botPrefix); commandServiceHandler = new CommandHandler(client, service, botPrefix);
@@ -105,7 +105,7 @@ public class Boot
if (arg.Message.Contains("401")) if (arg.Message.Contains("401"))
{ {
Config.AppSettings.Remove("token"); Config.AppSettings.Remove("token");
Config.Logger.Log("The token is invalid. Please restart the bot and enter a valid token.", source:typeof(Boot), type: LogType.CRITICAL); Config.Logger.Log("The token is invalid. Please restart the bot and enter a valid token.", source: typeof(Boot), type: LogType.CRITICAL);
await Config.AppSettings.SaveToFile(); await Config.AppSettings.SaveToFile();
await Task.Delay(4000); await Task.Delay(4000);
Environment.Exit(0); Environment.Exit(0);

View File

@@ -106,9 +106,11 @@ internal class CommandHandler
( (
plug.Aliases is not null && plug.Aliases is not null &&
plug.Aliases.Contains(message.CleanContent plug.Aliases.Contains(message.CleanContent
.Substring(mentionPrefix.Length + 1) .Substring(mentionPrefix.Length + 1)
.Split(' ')[0]) .Split(' ')[0]
)); )
)
);
cleanMessage = message.Content.Substring(mentionPrefix.Length + 1); cleanMessage = message.Content.Substring(mentionPrefix.Length + 1);
} }
@@ -120,11 +122,13 @@ internal class CommandHandler
message.Content.Split(' ')[0].Substring(botPrefix.Length) || message.Content.Split(' ')[0].Substring(botPrefix.Length) ||
(p.Aliases is not null && (p.Aliases is not null &&
p.Aliases.Contains( p.Aliases.Contains(
message.Content.Split(' ')[0] message.Content.Split(' ')[0]
.Substring(botPrefix.Length)))); .Substring(botPrefix.Length)
))
);
cleanMessage = message.Content.Substring(botPrefix.Length); cleanMessage = message.Content.Substring(botPrefix.Length);
} }
if (plugin is null) if (plugin is null)
return; return;
@@ -138,13 +142,13 @@ internal class CommandHandler
argsClean = string.Join(' ', split, 1, split.Length - 1).Split(' '); argsClean = string.Join(' ', split, 1, split.Length - 1).Split(' ');
DBCommandExecutingArguments cmd = new(context, cleanMessage, split[0], argsClean); DBCommandExecutingArguments cmd = new(context, cleanMessage, split[0], argsClean);
Config.Logger.Log( Config.Logger.Log(
message: $"User ({context.User.Username}) from Guild \"{context.Guild.Name}\" executed command \"{cmd.cleanContent}\"", message: $"User ({context.User.Username}) from Guild \"{context.Guild.Name}\" executed command \"{cmd.cleanContent}\"",
source: typeof(CommandHandler), source: typeof(CommandHandler),
type: LogType.INFO type: LogType.INFO
); );
if (context.Channel is SocketDMChannel) if (context.Channel is SocketDMChannel)
plugin.ExecuteDM(cmd); plugin.ExecuteDM(cmd);
else plugin.ExecuteServer(cmd); else plugin.ExecuteServer(cmd);

View File

@@ -20,18 +20,19 @@ public class Config
public static async Task Initialize() public static async Task Initialize()
{ {
if (_isLoaded) return; if (_isLoaded) return;
Directory.CreateDirectory("./Data/Resources"); Directory.CreateDirectory("./Data/Resources");
Directory.CreateDirectory("./Data/Plugins"); Directory.CreateDirectory("./Data/Plugins");
Directory.CreateDirectory("./Data/PAKS"); Directory.CreateDirectory("./Data/Archives");
Directory.CreateDirectory("./Data/Logs/Logs"); Directory.CreateDirectory("./Data/Logs");
Directory.CreateDirectory("./Data/Logs/Errors");
AppSettings = new SettingsDictionary<string, string>("./Data/Resources/config.json"); AppSettings = new SettingsDictionary<string, string>("./Data/Resources/config.json");
AppSettings["LogFolder"] = "./Data/Logs/Logs"; AppSettings["LogFolder"] = "./Data/Logs";
Logger = new Logger(false, true); Logger = new Logger(false, true,
AppSettings["LogFolder"] + $"/{DateTime.Today.ToShortDateString().Replace("/", "")}.log"
);
ArchiveManager.Initialize(); ArchiveManager.Initialize();
@@ -39,5 +40,5 @@ public class Config
Logger.Log(message: "Config initialized", source: typeof(Config)); Logger.Log(message: "Config initialized", source: typeof(Config));
} }
} }

View File

@@ -163,7 +163,8 @@ public class SqlDatabase
throw new Exception($"Table {tableName} does not exist"); throw new Exception($"Table {tableName} does not exist");
await ExecuteAsync( await ExecuteAsync(
$"UPDATE {tableName} SET {ResultColumnName}='{ResultColumnValue}' WHERE {keyName}='{KeyValue}'"); $"UPDATE {tableName} SET {ResultColumnName}='{ResultColumnValue}' WHERE {keyName}='{KeyValue}'"
);
} }
/// <summary> /// <summary>
@@ -238,7 +239,7 @@ public class SqlDatabase
{ {
var command = _connection.CreateCommand(); var command = _connection.CreateCommand();
command.CommandText = $"SELECT * FROM {tableName}"; command.CommandText = $"SELECT * FROM {tableName}";
var reader = await command.ExecuteReaderAsync(); var reader = await command.ExecuteReaderAsync();
var tableColumns = new List<string>(); var tableColumns = new List<string>();
for (var i = 0; i < reader.FieldCount; i++) for (var i = 0; i < reader.FieldCount; i++)
tableColumns.Add(reader.GetName(i)); tableColumns.Add(reader.GetName(i));
@@ -262,7 +263,7 @@ public class SqlDatabase
{ {
var command = _connection.CreateCommand(); var command = _connection.CreateCommand();
command.CommandText = $"SELECT * FROM {tableName}"; command.CommandText = $"SELECT * FROM {tableName}";
var reader = command.ExecuteReader(); var reader = command.ExecuteReader();
var tableColumns = new List<string>(); var tableColumns = new List<string>();
for (var i = 0; i < reader.FieldCount; i++) for (var i = 0; i < reader.FieldCount; i++)
tableColumns.Add(reader.GetName(i)); tableColumns.Add(reader.GetName(i));
@@ -343,7 +344,7 @@ public class SqlDatabase
if (!_connection.State.HasFlag(ConnectionState.Open)) if (!_connection.State.HasFlag(ConnectionState.Open))
await _connection.OpenAsync(); await _connection.OpenAsync();
var command = new SQLiteCommand(query, _connection); var command = new SQLiteCommand(query, _connection);
var answer = await command.ExecuteNonQueryAsync(); var answer = await command.ExecuteNonQueryAsync();
return answer; return answer;
} }
@@ -357,7 +358,7 @@ public class SqlDatabase
if (!_connection.State.HasFlag(ConnectionState.Open)) if (!_connection.State.HasFlag(ConnectionState.Open))
_connection.Open(); _connection.Open();
var command = new SQLiteCommand(query, _connection); var command = new SQLiteCommand(query, _connection);
var r = command.ExecuteNonQuery(); var r = command.ExecuteNonQuery();
return r; return r;
} }
@@ -372,7 +373,7 @@ public class SqlDatabase
if (!_connection.State.HasFlag(ConnectionState.Open)) if (!_connection.State.HasFlag(ConnectionState.Open))
await _connection.OpenAsync(); await _connection.OpenAsync();
var command = new SQLiteCommand(query, _connection); var command = new SQLiteCommand(query, _connection);
var reader = await command.ExecuteReaderAsync(); var reader = await command.ExecuteReaderAsync();
var values = new object[reader.FieldCount]; var values = new object[reader.FieldCount];
if (reader.Read()) if (reader.Read())
@@ -394,7 +395,7 @@ public class SqlDatabase
if (!_connection.State.HasFlag(ConnectionState.Open)) if (!_connection.State.HasFlag(ConnectionState.Open))
_connection.Open(); _connection.Open();
var command = new SQLiteCommand(query, _connection); var command = new SQLiteCommand(query, _connection);
var reader = command.ExecuteReader(); var reader = command.ExecuteReader();
var values = new object[reader.FieldCount]; var values = new object[reader.FieldCount];
if (reader.Read()) if (reader.Read())
@@ -416,7 +417,7 @@ public class SqlDatabase
if (!_connection.State.HasFlag(ConnectionState.Open)) if (!_connection.State.HasFlag(ConnectionState.Open))
await _connection.OpenAsync(); await _connection.OpenAsync();
var command = new SQLiteCommand(query, _connection); var command = new SQLiteCommand(query, _connection);
var reader = await command.ExecuteReaderAsync(); var reader = await command.ExecuteReaderAsync();
var values = new object[reader.FieldCount]; var values = new object[reader.FieldCount];
if (reader.Read()) if (reader.Read())
@@ -439,7 +440,7 @@ public class SqlDatabase
if (!_connection.State.HasFlag(ConnectionState.Open)) if (!_connection.State.HasFlag(ConnectionState.Open))
_connection.Open(); _connection.Open();
var command = new SQLiteCommand(query, _connection); var command = new SQLiteCommand(query, _connection);
var reader = command.ExecuteReader(); var reader = command.ExecuteReader();
var values = new object[reader.FieldCount]; var values = new object[reader.FieldCount];
if (reader.Read()) if (reader.Read())
@@ -462,7 +463,7 @@ public class SqlDatabase
if (!_connection.State.HasFlag(ConnectionState.Open)) if (!_connection.State.HasFlag(ConnectionState.Open))
await _connection.OpenAsync(); await _connection.OpenAsync();
var command = new SQLiteCommand(query, _connection); var command = new SQLiteCommand(query, _connection);
var reader = await command.ExecuteReaderAsync(); var reader = await command.ExecuteReaderAsync();
if (!reader.HasRows) if (!reader.HasRows)
return null; return null;
@@ -479,7 +480,7 @@ public class SqlDatabase
return rows; return rows;
} }
/// <summary> /// <summary>
/// Create a parameter for a query /// Create a parameter for a query
/// </summary> /// </summary>
@@ -490,7 +491,7 @@ public class SqlDatabase
{ {
var parameter = new SQLiteParameter(name); var parameter = new SQLiteParameter(name);
parameter.Value = value; parameter.Value = value;
if (value is string) if (value is string)
parameter.DbType = DbType.String; parameter.DbType = DbType.String;
else if (value is int) else if (value is int)
@@ -531,13 +532,13 @@ public class SqlDatabase
parameter.DbType = DbType.StringFixedLength; parameter.DbType = DbType.StringFixedLength;
else if (value is char[]) else if (value is char[])
parameter.DbType = DbType.StringFixedLength; parameter.DbType = DbType.StringFixedLength;
else else
return null; return null;
return parameter; return parameter;
} }
/// <summary> /// <summary>
/// Create a parameter for a query. The function automatically detects the type of the value. /// Create a parameter for a query. The function automatically detects the type of the value.
/// </summary> /// </summary>
@@ -545,7 +546,7 @@ public class SqlDatabase
/// <returns>The SQLiteParameter that has the name, value and DBType set according to your inputs</returns> /// <returns>The SQLiteParameter that has the name, value and DBType set according to your inputs</returns>
private SQLiteParameter? CreateParameter(KeyValuePair<string, object> parameterValues) => private SQLiteParameter? CreateParameter(KeyValuePair<string, object> parameterValues) =>
CreateParameter(parameterValues.Key, parameterValues.Value); CreateParameter(parameterValues.Key, parameterValues.Value);
/// <summary> /// <summary>
/// Execute a query with parameters /// Execute a query with parameters
/// </summary> /// </summary>
@@ -556,7 +557,7 @@ public class SqlDatabase
{ {
if (!_connection.State.HasFlag(ConnectionState.Open)) if (!_connection.State.HasFlag(ConnectionState.Open))
await _connection.OpenAsync(); await _connection.OpenAsync();
var command = new SQLiteCommand(query, _connection); var command = new SQLiteCommand(query, _connection);
foreach (var parameter in parameters) foreach (var parameter in parameters)
{ {
@@ -564,10 +565,10 @@ public class SqlDatabase
if (p is not null) if (p is not null)
command.Parameters.Add(p); command.Parameters.Add(p);
} }
return await command.ExecuteNonQueryAsync(); return await command.ExecuteNonQueryAsync();
} }
/// <summary> /// <summary>
/// Execute a query with parameters that returns a specific type of object. The function will return the first row of the result transformed into the specified type. /// Execute a query with parameters that returns a specific type of object. The function will return the first row of the result transformed into the specified type.
/// </summary> /// </summary>
@@ -576,11 +577,11 @@ public class SqlDatabase
/// <param name="parameters">The parameters of the query</param> /// <param name="parameters">The parameters of the query</param>
/// <typeparam name="T">The return object type</typeparam> /// <typeparam name="T">The return object type</typeparam>
/// <returns>An object of type T that represents the output of the convertor function based on the array of objects that the first row of the result has</returns> /// <returns>An object of type T that represents the output of the convertor function based on the array of objects that the first row of the result has</returns>
public async Task<T?> ReadObjectOfTypeAsync<T> (string query, Func<object[], T> convertor, params KeyValuePair<string, object>[] parameters) public async Task<T?> ReadObjectOfTypeAsync<T>(string query, Func<object[], T> convertor, params KeyValuePair<string, object>[] parameters)
{ {
if (!_connection.State.HasFlag(ConnectionState.Open)) if (!_connection.State.HasFlag(ConnectionState.Open))
await _connection.OpenAsync(); await _connection.OpenAsync();
var command = new SQLiteCommand(query, _connection); var command = new SQLiteCommand(query, _connection);
foreach (var parameter in parameters) foreach (var parameter in parameters)
{ {
@@ -588,7 +589,7 @@ public class SqlDatabase
if (p is not null) if (p is not null)
command.Parameters.Add(p); command.Parameters.Add(p);
} }
var reader = await command.ExecuteReaderAsync(); var reader = await command.ExecuteReaderAsync();
var values = new object[reader.FieldCount]; var values = new object[reader.FieldCount];
if (reader.Read()) if (reader.Read())
@@ -599,8 +600,8 @@ public class SqlDatabase
return default; return default;
} }
/// <summary> /// <summary>
/// Execute a query with parameters that returns a specific type of object. The function will return a list of objects of the specified type. /// Execute a query with parameters that returns a specific type of object. The function will return a list of objects of the specified type.
/// </summary> /// </summary>
@@ -614,7 +615,7 @@ public class SqlDatabase
{ {
if (!_connection.State.HasFlag(ConnectionState.Open)) if (!_connection.State.HasFlag(ConnectionState.Open))
await _connection.OpenAsync(); await _connection.OpenAsync();
var command = new SQLiteCommand(query, _connection); var command = new SQLiteCommand(query, _connection);
foreach (var parameter in parameters) foreach (var parameter in parameters)
{ {
@@ -622,12 +623,12 @@ public class SqlDatabase
if (p is not null) if (p is not null)
command.Parameters.Add(p); command.Parameters.Add(p);
} }
var reader = await command.ExecuteReaderAsync(); var reader = await command.ExecuteReaderAsync();
// //
if (!reader.HasRows) if (!reader.HasRows)
return null; return null;
List<T> rows = new(); List<T> rows = new();
while (await reader.ReadAsync()) while (await reader.ReadAsync())
{ {
@@ -638,4 +639,4 @@ public class SqlDatabase
return rows; return rows;
} }
} }

View File

@@ -6,7 +6,7 @@ namespace PluginManager.Interfaces;
public interface DBSlashCommand public interface DBSlashCommand
{ {
string Name { get; } string Name { get; }
string Description { get; } string Description { get; }
bool canUseDM { get; } bool canUseDM { get; }

View File

@@ -5,11 +5,10 @@ namespace PluginManager.Interfaces.Logger;
internal interface ILog internal interface ILog
{ {
string Message { get; set; } string Message { get; set; }
string OutputFile { get; set; }
Type? Source { get; set; } Type? Source { get; set; }
LogType Type { get; set; } LogType Type { get; set; }
DateTime ThrowTime { get; set; } DateTime ThrowTime { get; set; }
} }

View File

@@ -7,11 +7,13 @@ namespace PluginManager.Interfaces.Logger;
internal interface ILogger internal interface ILogger
{ {
bool IsEnabled { get; init; } bool IsEnabled { get; init; }
bool OutputToFile { get; init; } bool OutputToFile { get; init; }
string OutputFile { get; init; }
event EventHandler<Log> OnLog; event EventHandler<Log> OnLog;
void Log( void Log(
string message = "", string outputFile = "", Type? source = default, LogType type = LogType.INFO, string message = "", Type? source = default, LogType type = LogType.INFO,
DateTime throwTime = default); DateTime throwTime = default);
} }

View File

@@ -8,13 +8,13 @@ using PluginManager.Others;
namespace PluginManager.Loaders; namespace PluginManager.Loaders;
internal class LoaderArgs : EventArgs internal class LoaderArgs: EventArgs
{ {
internal string? PluginName { get; init; } internal string? PluginName { get; init; }
internal string? TypeName { get; init; } internal string? TypeName { get; init; }
internal bool IsLoaded { get; init; } internal bool IsLoaded { get; init; }
internal Exception? Exception { get; init; } internal Exception? Exception { get; init; }
internal object? Plugin { get; init; } internal object? Plugin { get; init; }
} }
internal class Loader internal class Loader
@@ -26,7 +26,7 @@ internal class Loader
} }
private string Path { get; } private string Path { get; }
private string Extension { get; } private string Extension { get; }
internal event FileLoadedEventHandler? FileLoaded; internal event FileLoadedEventHandler? FileLoaded;
@@ -101,28 +101,29 @@ internal class Loader
if (PluginLoaded != null) if (PluginLoaded != null)
PluginLoaded.Invoke(new LoaderArgs PluginLoaded.Invoke(new LoaderArgs
{ {
Exception = null, Exception = null,
IsLoaded = true, IsLoaded = true,
PluginName = type.FullName, PluginName = type.FullName,
TypeName = typeof(T) == typeof(DBCommand) ? "DBCommand" : TypeName = typeof(T) == typeof(DBCommand) ? "DBCommand" :
typeof(T) == typeof(DBEvent) ? "DBEvent" : typeof(T) == typeof(DBEvent) ? "DBEvent" :
typeof(T) == typeof(DBSlashCommand) ? "DBSlashCommand" : typeof(T) == typeof(DBSlashCommand) ? "DBSlashCommand" :
null, null,
Plugin = plugin Plugin = plugin
} }
); );
} }
catch (Exception ex) catch (Exception ex)
{ {
if (PluginLoaded != null) if (PluginLoaded != null)
PluginLoaded.Invoke(new LoaderArgs PluginLoaded.Invoke(new LoaderArgs
{ {
Exception = ex, Exception = ex,
IsLoaded = false, IsLoaded = false,
PluginName = type.FullName, PluginName = type.FullName,
TypeName = nameof(T) TypeName = nameof(T)
}); }
);
} }
return list; return list;

View File

@@ -131,7 +131,8 @@ public class PluginLoader
builder.Options = slash.Options; builder.Options = slash.Options;
onSLSHLoad?.Invoke(((DBSlashCommand)args.Plugin!).Name, args.TypeName, args.IsLoaded, onSLSHLoad?.Invoke(((DBSlashCommand)args.Plugin!).Name, args.TypeName, args.IsLoaded,
args.Exception); args.Exception
);
await _client.CreateGlobalApplicationCommandAsync(builder.Build()); await _client.CreateGlobalApplicationCommandAsync(builder.Build());
} }
@@ -161,7 +162,7 @@ public class PluginLoader
else if (type.IsClass && typeof(DBSlashCommand).IsAssignableFrom(type)) else if (type.IsClass && typeof(DBSlashCommand).IsAssignableFrom(type))
{ {
var instance = (DBSlashCommand)Activator.CreateInstance(type); var instance = (DBSlashCommand)Activator.CreateInstance(type);
var builder = new SlashCommandBuilder(); var builder = new SlashCommandBuilder();
builder.WithName(instance.Name); builder.WithName(instance.Name);
builder.WithDescription(instance.Description); builder.WithDescription(instance.Description);
builder.WithDMPermission(instance.canUseDM); builder.WithDMPermission(instance.canUseDM);
@@ -177,6 +178,6 @@ public class PluginLoader
//Console.WriteLine(ex.Message); //Console.WriteLine(ex.Message);
Config.Logger.Log(ex.Message, source: typeof(PluginLoader), type: LogType.ERROR); Config.Logger.Log(ex.Message, source: typeof(PluginLoader), type: LogType.ERROR);
} }
} }
} }

View File

@@ -19,10 +19,10 @@ internal static class OnlineFunctions
/// <param name="cancellation">The cancellation token</param> /// <param name="cancellation">The cancellation token</param>
/// <returns></returns> /// <returns></returns>
internal static async Task DownloadFileAsync( internal static async Task DownloadFileAsync(
this HttpClient client, string url, Stream destination, this HttpClient client, string url, Stream destination,
IProgress<float>? progress = null, IProgress<float>? progress = null,
IProgress<long>? downloadedBytes = null, int bufferSize = 81920, IProgress<long>? downloadedBytes = null, int bufferSize = 81920,
CancellationToken cancellation = default) CancellationToken cancellation = default)
{ {
using (var response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, cancellation)) using (var response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, cancellation))
{ {
@@ -35,7 +35,7 @@ internal static class OnlineFunctions
if (progress == null || !contentLength.HasValue) if (progress == null || !contentLength.HasValue)
{ {
await download.CopyToAsync(destination, cancellation); await download.CopyToAsync(destination, cancellation);
if(!contentLength.HasValue) if (!contentLength.HasValue)
progress?.Report(100f); progress?.Report(100f);
return; return;
} }

View File

@@ -10,7 +10,7 @@ namespace PluginManager.Online;
public class PluginsManager public class PluginsManager
{ {
#if DEBUG #if DEBUG
/// <summary> /// <summary>
/// The Plugin Manager constructor /// The Plugin Manager constructor
@@ -22,16 +22,16 @@ public class PluginsManager
PluginsLink = plink; PluginsLink = plink;
VersionsLink = vlink; VersionsLink = vlink;
} }
#endif #endif
/// <summary> /// <summary>
/// The Plugin Manager constructor. It uses the default links and the default branch. /// The Plugin Manager constructor. It uses the default links and the default branch.
/// </summary> /// </summary>
/// <param name="branch">The main branch from where the plugin manager gets its info</param> /// <param name="branch">The main branch from where the plugin manager gets its info</param>
public PluginsManager(string? branch = "releases") public PluginsManager(string? branch = "releases")
{ {
PluginsLink = $"https://raw.githubusercontent.com/andreitdr/SethPlugins/{branch}/PluginsList"; PluginsLink = $"https://raw.githubusercontent.com/andreitdr/SethPlugins/{branch}/PluginsList";
VersionsLink = $"https://raw.githubusercontent.com/andreitdr/SethPlugins/{branch}/Versions"; VersionsLink = $"https://raw.githubusercontent.com/andreitdr/SethPlugins/{branch}/Versions";
} }
@@ -95,7 +95,7 @@ public class PluginsManager
} }
catch (Exception exception) catch (Exception exception)
{ {
Config.Logger.Log(message: "Failed to execute command: listplugs\nReason: " + exception.Message, source: typeof(PluginsManager), type: LogType.ERROR ); Config.Logger.Log(message: "Failed to execute command: listplugs\nReason: " + exception.Message, source: typeof(PluginsManager), type: LogType.ERROR);
} }
return null; return null;
@@ -135,16 +135,18 @@ public class PluginsManager
for (var i = 0; i < len; i++) for (var i = 0; i < len; i++)
{ {
var contents = lines[i].Split(','); var contents = lines[i].Split(',');
if(Functions.GetOperatingSystem() == OperatingSystem.WINDOWS && contents[4].Contains("Windows")) if (Functions.GetOperatingSystem() == OperatingSystem.WINDOWS && contents[4].Contains("Windows"))
{if (contents[0].ToLowerInvariant() == name.ToLowerInvariant())
{ {
if (contents.Length == 6) if (contents[0].ToLowerInvariant() == name.ToLowerInvariant())
return new[] { contents[2], contents[3], contents[5] }; {
if (contents.Length == 5) if (contents.Length == 6)
return new[] { contents[2], contents[3], string.Empty }; return new[] { contents[2], contents[3], contents[5] };
throw new Exception("Failed to download plugin. Invalid Argument Length"); if (contents.Length == 5)
return new[] { contents[2], contents[3], string.Empty };
throw new Exception("Failed to download plugin. Invalid Argument Length");
}
} }
}else if (Functions.GetOperatingSystem() == OperatingSystem.LINUX && contents[4].Contains("Linux")) else if (Functions.GetOperatingSystem() == OperatingSystem.LINUX && contents[4].Contains("Linux"))
{ {
if (contents.Length == 6) if (contents.Length == 6)
return new[] { contents[2], contents[3], contents[5] }; return new[] { contents[2], contents[3], contents[5] };

View File

@@ -30,7 +30,7 @@ public static class ServerCom
/// <param name="progress">The <see cref="IProgress{T}" /> to track the download</param> /// <param name="progress">The <see cref="IProgress{T}" /> to track the download</param>
/// <returns></returns> /// <returns></returns>
public static async Task DownloadFileAsync( public static async Task DownloadFileAsync(
string URL, string location, IProgress<float> progress, string URL, string location, IProgress<float> progress,
IProgress<long>? downloadedBytes) IProgress<long>? downloadedBytes)
{ {
using (var client = new HttpClient()) using (var client = new HttpClient())
@@ -48,15 +48,15 @@ public static class ServerCom
{ {
await DownloadFileAsync(URl, location, progress, null); await DownloadFileAsync(URl, location, progress, null);
} }
public static Task CreateDownloadTask(string URl, string location) public static Task CreateDownloadTask(string URl, string location)
{ {
return DownloadFileAsync(URl, location, null, null); return DownloadFileAsync(URl, location, null, null);
} }
public static Task CreateDownloadTask(string URl, string location, IProgress<float> progress) public static Task CreateDownloadTask(string URl, string location, IProgress<float> progress)
{ {
return DownloadFileAsync(URl, location, progress, null); return DownloadFileAsync(URl, location, progress, null);
} }
} }

View File

@@ -26,7 +26,7 @@ public class InternalActionManager
Actions.TryAdd(action.ActionName, action); Actions.TryAdd(action.ActionName, action);
} }
} }
public async Task Refresh() public async Task Refresh()
{ {
Actions.Clear(); Actions.Clear();
@@ -59,7 +59,7 @@ public class InternalActionManager
} }
catch (Exception e) catch (Exception e)
{ {
Config.Logger.Log(e.Message , type: LogType.ERROR, source: typeof(InternalActionManager)); Config.Logger.Log(e.Message, type: LogType.ERROR, source: typeof(InternalActionManager));
return e.Message; return e.Message;
} }
} }

View File

@@ -37,24 +37,24 @@ public static class ArchiveManager
if (!File.Exists(archName)) if (!File.Exists(archName))
throw new Exception("Failed to load file !"); throw new Exception("Failed to load file !");
byte[]? data = null; byte[]? data = null;
using (var zip = ZipFile.OpenRead(archName)) using (var zip = ZipFile.OpenRead(archName))
{ {
var entry = zip.Entries.FirstOrDefault(entry => entry.FullName == fileName || entry.Name == fileName); var entry = zip.Entries.FirstOrDefault(entry => entry.FullName == fileName || entry.Name == fileName);
if (entry is null) throw new Exception("File not found in archive"); if (entry is null) throw new Exception("File not found in archive");
var MemoryStream = new MemoryStream(); var MemoryStream = new MemoryStream();
var stream = entry.Open(); var stream = entry.Open();
await stream.CopyToAsync(MemoryStream); await stream.CopyToAsync(MemoryStream);
data = MemoryStream.ToArray(); data = MemoryStream.ToArray();
stream.Close(); stream.Close();
MemoryStream.Close(); MemoryStream.Close();
} }
return data; return data;
} }
@@ -117,7 +117,7 @@ public static class ArchiveManager
{ {
if (type == UnzipProgressType.PERCENTAGE_FROM_NUMBER_OF_FILES) if (type == UnzipProgressType.PERCENTAGE_FROM_NUMBER_OF_FILES)
{ {
var totalZIPFiles = archive.Entries.Count(); var totalZIPFiles = archive.Entries.Count();
var currentZIPFile = 0; var currentZIPFile = 0;
foreach (var entry in archive.Entries) foreach (var entry in archive.Entries)
{ {
@@ -173,4 +173,4 @@ public static class ArchiveManager
} }
} }
} }
} }

View File

@@ -29,19 +29,19 @@ public class DBCommandExecutingArguments
{ {
this.cleanContent = message.Content.Substring(Config.DiscordBot.botPrefix.Length); this.cleanContent = message.Content.Substring(Config.DiscordBot.botPrefix.Length);
} }
var split = this.cleanContent.Split(' '); var split = this.cleanContent.Split(' ');
string[]? argsClean = null; string[]? argsClean = null;
if (split.Length > 1) if (split.Length > 1)
argsClean = string.Join(' ', split, 1, split.Length - 1).Split(' '); argsClean = string.Join(' ', split, 1, split.Length - 1).Split(' ');
this.commandUsed = split[0]; this.commandUsed = split[0];
this.arguments = argsClean; this.arguments = argsClean;
} }
public SocketCommandContext context { get; init; } public SocketCommandContext context { get; init; }
public string cleanContent { get; init; } public string cleanContent { get; init; }
public string commandUsed { get; init; } public string commandUsed { get; init; }
public string[]? arguments { get; init; } public string[]? arguments { get; init; }
} }

View File

@@ -40,8 +40,8 @@ public enum InternalActionRunType
ON_CALL ON_CALL
} }
internal enum ExceptionExitCode : int internal enum ExceptionExitCode: int
{ {
CONFIG_FAILED_TO_LOAD = 1, CONFIG_FAILED_TO_LOAD = 1,
CONFIG_KEY_NOT_FOUND = 2, CONFIG_KEY_NOT_FOUND = 2,
} }

View File

@@ -54,8 +54,8 @@ public static class Functions
/// <exception cref="InvalidOperationException">Triggered if <paramref name="stream" /> is not readable</exception> /// <exception cref="InvalidOperationException">Triggered if <paramref name="stream" /> is not readable</exception>
/// <exception cref="ArgumentException">Triggered in <paramref name="destination" /> is not writable</exception> /// <exception cref="ArgumentException">Triggered in <paramref name="destination" /> is not writable</exception>
public static async Task CopyToOtherStreamAsync( public static async Task CopyToOtherStreamAsync(
this Stream stream, Stream destination, int bufferSize, this Stream stream, Stream destination, int bufferSize,
IProgress<long>? progress = null, IProgress<long>? progress = null,
CancellationToken cancellationToken = default) CancellationToken cancellationToken = default)
{ {
if (stream == null) throw new ArgumentNullException(nameof(stream)); if (stream == null) throw new ArgumentNullException(nameof(stream));
@@ -76,7 +76,7 @@ public static class Functions
progress?.Report(totalBytesRead); progress?.Report(totalBytesRead);
} }
} }
public static T SelectRandomValueOf<T>() public static T SelectRandomValueOf<T>()
{ {

View File

@@ -38,10 +38,10 @@ public class JsonManager
else else
text = new MemoryStream(Encoding.ASCII.GetBytes(input)); text = new MemoryStream(Encoding.ASCII.GetBytes(input));
text.Position = 0; text.Position = 0;
var obj = await JsonSerializer.DeserializeAsync<T>(text); var obj = await JsonSerializer.DeserializeAsync<T>(text);
await text.FlushAsync(); await text.FlushAsync();
text.Close(); text.Close();
return (obj ?? default)!; return (obj ?? default)!;
} }
} }

View File

@@ -4,60 +4,46 @@ using PluginManager.Interfaces.Logger;
namespace PluginManager.Others.Logger; namespace PluginManager.Others.Logger;
public class Log : ILog public class Log: ILog
{ {
public string Message { get; set; } public string Message { get; set; }
public string OutputFile { get; set; } public Type? Source { get; set; }
public Type? Source { get; set; } public LogType Type { get; set; }
public LogType Type { get; set; } public DateTime ThrowTime { get; set; }
public DateTime ThrowTime { get; set; }
public Log(string message, Type? source, LogType type, DateTime throwTime)
public Log(string message, string outputFile, Type? source, LogType type, DateTime throwTime)
{ {
Message = message; Message = message;
OutputFile = outputFile; Source = source;
Source = source; Type = type;
Type = type; ThrowTime = throwTime;
ThrowTime = throwTime;
} }
public Log(string message, string outputFile, Type? source, LogType type) public Log(string message, Type? source, LogType type)
{ {
Message = message; Message = message;
OutputFile = outputFile; Source = source;
Source = source; Type = type;
Type = type; ThrowTime = DateTime.Now;
ThrowTime = DateTime.Now;
} }
public Log(string message, string outputFile, Type? source) public Log(string message, Type? source)
{ {
Message = message; Message = message;
OutputFile = outputFile; Source = source;
Source = source; Type = LogType.INFO;
Type = LogType.INFO; ThrowTime = DateTime.Now;
ThrowTime = DateTime.Now;
} }
public Log(string message, string outputFile)
{
Message = message;
OutputFile = outputFile;
Source = typeof(Log);
Type = LogType.INFO;
ThrowTime = DateTime.Now;
}
public Log(string message) public Log(string message)
{ {
Message = message; Message = message;
OutputFile = ""; Source = typeof(Log);
Source = typeof(Log); Type = LogType.INFO;
Type = LogType.INFO; ThrowTime = DateTime.Now;
ThrowTime = DateTime.Now;
} }
public static implicit operator Log(string message) => new (message); public static implicit operator Log(string message) => new(message);
public static implicit operator string(Log log) => $"[{log.ThrowTime}] {log.Message}"; public static implicit operator string(Log log) => $"[{log.ThrowTime}] {log.Message}";
@@ -65,7 +51,7 @@ public class Log : ILog
{ {
return $"[{ThrowTime}] [{Source}] [{Type}] {Message}"; return $"[{ThrowTime}] [{Source}] [{Type}] {Message}";
} }
public string AsShortString() public string AsShortString()
{ {
return this; return this;

View File

@@ -6,64 +6,72 @@ using PluginManager.Interfaces.Logger;
namespace PluginManager.Others.Logger; namespace PluginManager.Others.Logger;
public sealed class Logger : ILogger public sealed class Logger: ILogger
{ {
public bool IsEnabled { get; init; } public bool IsEnabled { get; init; }
public bool OutputToFile { get; init; } public bool OutputToFile { get; init; }
public string? OutputFile { get; init; }
private LogType LowestLogLevel { get; } private LogType LowestLogLevel { get; }
private bool UseShortVersion { get; } private bool UseShortVersion { get; }
public Logger(bool useShortVersion, bool outputToFile, LogType lowestLogLevel = LogType.INFO) public Logger(bool useShortVersion, bool outputToFile, string outputFile, LogType lowestLogLevel = LogType.INFO)
{ {
UseShortVersion = useShortVersion; UseShortVersion = useShortVersion;
OutputToFile = outputToFile; OutputToFile = outputToFile;
IsEnabled = true; IsEnabled = true;
LowestLogLevel = lowestLogLevel; LowestLogLevel = lowestLogLevel;
OutputFile = outputFile;
}
public Logger(bool useShortVersion, LogType lowestLogLevel = LogType.INFO)
{
UseShortVersion = useShortVersion;
OutputToFile = false;
IsEnabled = true;
LowestLogLevel = lowestLogLevel;
OutputFile = null;
} }
public event EventHandler<Log>? OnLog; public event EventHandler<Log>? OnLog;
private async Task Log(Log logMessage) private async Task Log(Log logMessage)
{ {
if (!IsEnabled) return; if (!IsEnabled) return;
OnLog?.Invoke(this, logMessage); OnLog?.Invoke(this, logMessage);
if (logMessage.Type < LowestLogLevel) return; if (logMessage.Type < LowestLogLevel) return;
if (OutputToFile) if (OutputToFile)
await File.AppendAllTextAsync( await File.AppendAllTextAsync(
logMessage.OutputFile, OutputFile!,
(UseShortVersion ? logMessage : logMessage.AsLongString()) + "\n"); (UseShortVersion ? logMessage : logMessage.AsLongString()) + "\n"
);
} }
public async void Log(string message = "", string outputFile = "", Type? source = default, LogType type = LogType.INFO, DateTime throwTime = default) public async void Log(string message = "", Type? source = default, LogType type = LogType.INFO, DateTime throwTime = default)
{ {
if (!IsEnabled) return; if (!IsEnabled) return;
if (type < LowestLogLevel) return; if (type < LowestLogLevel) return;
if (string.IsNullOrEmpty(message)) return; if (string.IsNullOrEmpty(message)) return;
if (string.IsNullOrEmpty(outputFile)) outputFile = Config.AppSettings["LogFolder"] + "/" + DateTime.Now.ToString("yyyy-MM-dd") + ".log"; if (throwTime == default) throwTime = DateTime.Now;
if(throwTime == default) throwTime = DateTime.Now;
if (source == default) source = typeof(Log); if (source == default) source = typeof(Log);
await Log(new Log(message, outputFile, source, type, throwTime)); await Log(new Log(message, source, type, throwTime));
} }
public async void Log(Exception exception, LogType logType = LogType.ERROR, Type? source = null) public async void Log(Exception exception, LogType logType = LogType.ERROR, Type? source = null)
{ {
if (!IsEnabled) return; if (!IsEnabled) return;
if (logType < LowestLogLevel) return; if (logType < LowestLogLevel) return;
await Log(new Log(exception.Message, await Log(new Log(exception.Message, source, logType, DateTime.Now));
Config.AppSettings["LogFolder"] + "/" + DateTime.Now.ToString("yyyy-MM-dd") + ".log",
source, logType, DateTime.Now));
} }
} }

View File

@@ -5,11 +5,11 @@ using System.Threading.Tasks;
namespace PluginManager.Others; namespace PluginManager.Others;
public class SettingsDictionary<TKey, TValue> : IDictionary<TKey, TValue> public class SettingsDictionary<TKey, TValue>: IDictionary<TKey, TValue>
{ {
public string? _file { get; } public string? _file { get; }
private IDictionary<TKey, TValue>? _dictionary; private IDictionary<TKey, TValue>? _dictionary;
public SettingsDictionary(string? file) public SettingsDictionary(string? file)
{ {
_file = file; _file = file;
@@ -19,7 +19,7 @@ public class SettingsDictionary<TKey, TValue> : IDictionary<TKey, TValue>
SaveToFile(); SaveToFile();
} }
} }
public async Task SaveToFile() public async Task SaveToFile()
{ {
if (!string.IsNullOrEmpty(_file)) if (!string.IsNullOrEmpty(_file))
@@ -36,8 +36,8 @@ public class SettingsDictionary<TKey, TValue> : IDictionary<TKey, TValue>
string FileContent = File.ReadAllText(_file); string FileContent = File.ReadAllText(_file);
if (string.IsNullOrEmpty(FileContent)) if (string.IsNullOrEmpty(FileContent))
File.WriteAllText(_file, "{}"); File.WriteAllText(_file, "{}");
if(!FileContent.Contains("{") || !FileContent.Contains("}")) if (!FileContent.Contains("{") || !FileContent.Contains("}"))
File.WriteAllText(_file, "{}"); File.WriteAllText(_file, "{}");
} }
else else
@@ -61,7 +61,7 @@ public class SettingsDictionary<TKey, TValue> : IDictionary<TKey, TValue>
IEnumerator IEnumerable.GetEnumerator() IEnumerator IEnumerable.GetEnumerator()
{ {
return ((IEnumerable) _dictionary!).GetEnumerator(); return ((IEnumerable)_dictionary!).GetEnumerator();
} }
public void Add(KeyValuePair<TKey, TValue> item) public void Add(KeyValuePair<TKey, TValue> item)
@@ -89,7 +89,7 @@ public class SettingsDictionary<TKey, TValue> : IDictionary<TKey, TValue>
return this._dictionary!.Remove(item); return this._dictionary!.Remove(item);
} }
public int Count => _dictionary!.Count; public int Count => _dictionary!.Count;
public bool IsReadOnly => _dictionary!.IsReadOnly; public bool IsReadOnly => _dictionary!.IsReadOnly;
public void Add(TKey key, TValue value) public void Add(TKey key, TValue value)
{ {
@@ -116,9 +116,9 @@ public class SettingsDictionary<TKey, TValue> : IDictionary<TKey, TValue>
get get
{ {
if (this._dictionary!.ContainsKey(key)) if (this._dictionary!.ContainsKey(key))
if(this._dictionary[key] is string s && !string.IsNullOrEmpty(s) && !string.IsNullOrWhiteSpace(s)) if (this._dictionary[key] is string s && !string.IsNullOrEmpty(s) && !string.IsNullOrWhiteSpace(s))
return this._dictionary[key]; return this._dictionary[key];
return default!; return default!;
} }
set => this._dictionary![key] = value; set => this._dictionary![key] = value;
@@ -126,4 +126,4 @@ public class SettingsDictionary<TKey, TValue> : IDictionary<TKey, TValue>
public ICollection<TKey> Keys => _dictionary!.Keys; public ICollection<TKey> Keys => _dictionary!.Keys;
public ICollection<TValue> Values => _dictionary!.Values; public ICollection<TValue> Values => _dictionary!.Values;
} }

View File

@@ -9,10 +9,10 @@
<DebugSymbols>false</DebugSymbols> <DebugSymbols>false</DebugSymbols>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<None Remove="BlankWindow1.xaml" /> <None Remove="BlankWindow1.xaml"/>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Discord.Net" Version="3.11.0" /> <PackageReference Include="Discord.Net" Version="3.11.0"/>
<PackageReference Include="System.Data.SQLite.Core" Version="1.0.118" /> <PackageReference Include="System.Data.SQLite.Core" Version="1.0.118"/>
</ItemGroup> </ItemGroup>
</Project> </Project>

View File

@@ -22,12 +22,12 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Folder Include="DiscordBot\" /> <Folder Include="DiscordBot\"/>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\DiscordBot\DiscordBot.csproj" /> <ProjectReference Include="..\DiscordBot\DiscordBot.csproj"/>
<ProjectReference Include="..\PluginManager\PluginManager.csproj" /> <ProjectReference Include="..\PluginManager\PluginManager.csproj"/>
</ItemGroup> </ItemGroup>
</Project> </Project>