From bcef58a46bd569cc430a9205e69fdca792b9744a Mon Sep 17 00:00:00 2001 From: Wizzy69 Date: Sat, 29 Apr 2023 19:35:19 +0300 Subject: [PATCH] Removed plugins from the project and reworked the Plugin Manager --- .vscode/launch.json | 49 +---- .vscode/tasks.json | 52 ++--- DiscordBot/Program.cs | 138 +++++-------- .../Utilities/ConsoleCommandsHandler.cs | 107 +--------- DiscordBotPlugins/Economy/Commands/Balance.cs | 72 ------- DiscordBotPlugins/Economy/Economy.csproj | 10 - DiscordBotPlugins/Economy/Engine.cs | 62 ------ DiscordBotPlugins/Economy/Entry.cs | 31 --- PluginManager/Bot/CommandHandler.cs | 4 +- PluginManager/Config.cs | 12 +- PluginManager/Loaders/Loader.cs | 6 +- PluginManager/Logger.cs | 182 ------------------ .../Controls/ConsoleOption.cs | 15 -- .../WindowManagement/Controls/Label.cs | 47 ----- .../WindowManagement/Controls/TextBox.cs | 26 --- PluginManager/WindowManagement/InputBox.cs | 61 ------ PluginManager/WindowManagement/MessageBox.cs | 70 ------- 17 files changed, 83 insertions(+), 861 deletions(-) delete mode 100644 DiscordBotPlugins/Economy/Commands/Balance.cs delete mode 100644 DiscordBotPlugins/Economy/Economy.csproj delete mode 100644 DiscordBotPlugins/Economy/Engine.cs delete mode 100644 DiscordBotPlugins/Economy/Entry.cs delete mode 100644 PluginManager/Logger.cs delete mode 100644 PluginManager/WindowManagement/Controls/ConsoleOption.cs delete mode 100644 PluginManager/WindowManagement/Controls/Label.cs delete mode 100644 PluginManager/WindowManagement/Controls/TextBox.cs delete mode 100644 PluginManager/WindowManagement/InputBox.cs delete mode 100644 PluginManager/WindowManagement/MessageBox.cs diff --git a/.vscode/launch.json b/.vscode/launch.json index 303eba1..e141305 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -1,48 +1,6 @@ { "version": "0.2.0", "configurations": [ - { - "name": ".NET Core Watch (web)", - "type": "coreclr", - "request": "launch", - "preLaunchTask": "watch", - "program": "${workspaceFolder}/DiscordBotPlugins/DiscordBotUI/bin/Debug/net6.0/DiscordBotUI.dll", - "args": [], - "cwd": "${workspaceFolder}/DiscordBotPlugins/DiscordBotUI/bin/Debug/net6.0", - "stopAtEntry": false, - "console": "externalTerminal", - "serverReadyAction": { - "action": "openExternally", - "pattern": "\\bNow listening on:\\s+(https?://\\S+)" - }, - "env": { - "ASPNETCORE_ENVIRONMENT": "Development" - }, - "sourceFileMap": { - "/Views": "${workspaceFolder}/Views" - } - }, - { - "name": ".NET Core Launch (web)", - "type": "coreclr", - "request": "launch", - "preLaunchTask": "buildUI", - "program": "${workspaceFolder}/DiscordBotPlugins/DiscordBotUI/bin/Debug/net6.0/DiscordBotUI.dll", - "args": [], - "cwd": "${workspaceFolder}/DiscordBotPlugins/DiscordBotUI/bin/Debug/net6.0", - "stopAtEntry": false, - "console": "externalTerminal", - "serverReadyAction": { - "action": "openExternally", - "pattern": "\\bNow listening on:\\s+(https?://\\S+)" - }, - "env": { - "ASPNETCORE_ENVIRONMENT": "Development" - }, - "sourceFileMap": { - "/Views": "${workspaceFolder}/Views" - } - }, { // Use IntelliSense to find out which attributes exist for C# debugging // Use hover for the description of the existing attributes @@ -54,10 +12,15 @@ // If you have changed target frameworks, make sure to update the program path. "program": "${workspaceFolder}/DiscordBot/bin/Debug/net6.0/DiscordBot.dll", "args": [], - "cwd": "${workspaceFolder}/DiscordBot/bin/Debug/net6.0", + "cwd": "${workspaceFolder}/DiscordBot/bin/Debug/net6.0/", // For more information about the 'console' field, see https://aka.ms/VSCode-CS-LaunchJson-Console "console": "externalTerminal", "stopAtEntry": false + }, + { + "name": ".NET Core Attach", + "type": "coreclr", + "request": "attach" } ] } \ No newline at end of file diff --git a/.vscode/tasks.json b/.vscode/tasks.json index f72e550..08f8fa7 100644 --- a/.vscode/tasks.json +++ b/.vscode/tasks.json @@ -1,34 +1,6 @@ { "version": "2.0.0", "tasks": [ - { - "label": "watch", - "command": "dotnet", - "type": "process", - "args": [ - "watch", - "run", - "--project", - "${workspaceFolder}/DiscordBotPlugins/DiscordBotUI/DiscordBotUI.csproj", - "/property:GenerateFullPaths=true", - "/consoleloggerparameters:NoSummary" - ], - "problemMatcher": "$msCompile", - "options": { - "cwd": "${workspaceFolder}/DiscordBotPlugins/DiscordBotUI/bin/Debug/net6.0", - "env": { - "ASPNETCORE_ENVIRONMENT": "Development" - }, - "sourceFileMap": { - "/Views": "${workspaceFolder}/Views" - }, - "serverReadyAction": { - "action": "openExternally", - "pattern": "\\bNow listening on:\\s+(https?://\\S+)" - }, - "console": "externalTerminal" - } - }, { "label": "build", "command": "dotnet", @@ -41,18 +13,6 @@ ], "problemMatcher": "$msCompile" }, - { - "label": "buildUI", - "command": "dotnet", - "type": "process", - "args": [ - "build", - "${workspaceFolder}/DiscordBotPlugins/DiscordBotUI/DiscordBotUI.csproj", - "/property:GenerateFullPaths=true", - "/consoleloggerparameters:NoSummary" - ], - "problemMatcher": "$msCompile" - }, { "label": "publish", "command": "dotnet", @@ -64,6 +24,18 @@ "/consoleloggerparameters:NoSummary" ], "problemMatcher": "$msCompile" + }, + { + "label": "watch", + "command": "dotnet", + "type": "process", + "args": [ + "watch", + "run", + "--project", + "${workspaceFolder}/DiscordBot/DiscordBot.csproj" + ], + "problemMatcher": "$msCompile" } ] } \ No newline at end of file diff --git a/DiscordBot/Program.cs b/DiscordBot/Program.cs index f7ef03a..1394dfd 100644 --- a/DiscordBot/Program.cs +++ b/DiscordBot/Program.cs @@ -11,7 +11,6 @@ using PluginManager.Bot; using PluginManager.Online; using PluginManager.Online.Helpers; using PluginManager.Others; -using PluginManager.WindowManagement; using DiscordBot.Utilities; @@ -39,7 +38,7 @@ public class Program Config.Data["prefix"]?.Length != 1 || (args.Length == 1 && args[0] == "/reset")) { - GenerateStartUI(); + GenerateStartupConfig(); } HandleInput(args).Wait(); @@ -84,11 +83,11 @@ public class Program "https://raw.githubusercontent.com/Wizzy69/installer/discord-bot-files/StartupMessage"); foreach (var message in startupMessageList) - Config.Logger.Log(message); + Console.WriteLine(message); - Logger.WriteLine( + Console.WriteLine( $"Running on version: {Assembly.GetExecutingAssembly().GetName().Version}"); - Logger.WriteLine($"Git URL: {Config.Data["GitURL"]}"); + Console.WriteLine($"Git URL: {Config.Data["GitURL"]}"); Utilities.Utilities.WriteColorText( "&rRemember to close the bot using the ShutDown command (&ysd&r) or some settings won't be saved\n"); @@ -101,9 +100,8 @@ public class Program Utilities.Utilities.WriteColorText( "Please note that the bot saves a backup save file every time you are using the shudown command (&ysd&c)"); - Logger.WriteLine(); - Logger.WriteLine("Running on " + Functions.GetOperatingSystem().ToString()); - Logger.WriteLine("============================ LOG ============================"); + Console.WriteLine("Running on " + Functions.GetOperatingSystem().ToString()); + Console.WriteLine("============================ LOG ============================"); try { @@ -121,7 +119,7 @@ public class Program } catch (Exception ex) { - Logger.LogError(ex); + Config.Logger.Log(ex.ToString(),"Bot",TextType.ERROR); return null; } } @@ -137,16 +135,6 @@ public class Program var b = await StartNoGui(); consoleCommandsHandler = new ConsoleCommandsHandler(b.client); - if (len > 0 && args[0] == "/remplug") - { - var plugName = string.Join(' ', args, 1, args.Length - 1); - Logger.WriteLine("Starting to remove " + plugName); - await ConsoleCommandsHandler.ExecuteCommad("remplug " + plugName); - loadPluginsOnStartup = true; - } - - - var mainThread = new Thread(() => { try @@ -160,7 +148,7 @@ public class Program if (Config.Data.ContainsKey("LaunchMessage")) Config.Data.Add("LaunchMessage", "An error occured while closing the bot last time. Please consider closing the bot using the &rsd&c method !\nThere is a risk of losing all data or corruption of the save file, which in some cases requires to reinstall the bot !"); - Logger.WriteErrFile(ex.ToString()); + Config.Logger.Log("An error occured while closing the bot last time. Please consider closing the bot using the &rsd&c method !\nThere is a risk of losing all data or corruption of the save file, which in some cases requires to reinstall the bot !","Bot",TextType.ERROR); } } }); @@ -169,10 +157,12 @@ public class Program private static async Task PreLoadComponents(string[] args) { - await Config.Initialize(true); + await Config.Initialize(); + + Config.Logger.LogEvent += (message, type) => { Console.WriteLine(message); }; - Logger.WriteLine("Loading resources ..."); + Console.WriteLine("Loading resources ..."); var main = new Utilities.Utilities.ProgressBar(ProgressBarType.NO_END); main.Start(); @@ -197,7 +187,7 @@ public class Program } catch (Exception ex) { - Logger.WriteErrFile(ex.Message); + Config.Logger.Log(ex.ToString(),"Bot",TextType.ERROR); } } @@ -225,14 +215,14 @@ public class Program Config.Data["Version"] = "1." + cVer.ToShortString() + " (Beta)"; break; } - + if (OperatingSystem.WINDOWS == Functions.GetOperatingSystem()) { Console.Clear(); - Logger.WriteLine("A new update was found !"); - Logger.WriteLine("Run the launcher to update"); - Logger.WriteLine("Current version: " + currentVersion); - Logger.WriteLine("Latest version: " + s[1]); + Console.WriteLine("A new update was found !"); + Console.WriteLine("Run the launcher to update"); + Console.WriteLine("Current version: " + currentVersion); + Console.WriteLine("Latest version: " + s[1]); File.WriteAllText("version.txt", currentVersion); @@ -243,54 +233,51 @@ public class Program Console.Clear(); Console.ForegroundColor = ConsoleColor.Red; - Logger.WriteLine("A new version of the bot is available !"); + Console.WriteLine("A new version of the bot is available !"); Console.ForegroundColor = ConsoleColor.Yellow; - Logger.WriteLine("Current version : " + + Console.WriteLine("Current version : " + Assembly.GetExecutingAssembly().GetName().Version.ToString()); Console.ForegroundColor = ConsoleColor.Green; - Logger.WriteLine("New version : " + newVersion); + Console.WriteLine("New version : " + newVersion); Console.ForegroundColor = ConsoleColor.White; File.WriteAllText("version.txt", newVersion); - Logger.WriteLine("Changelog :"); + Console.WriteLine("Changelog :"); List changeLog = await ServerCom.ReadTextFromURL( "https://raw.githubusercontent.com/Wizzy69/installer/discord-bot-files/VersionData/DiscordBot"); foreach (var item in changeLog) Utilities.Utilities.WriteColorText(item); - Logger.WriteLine("Do you want to update the bot ? (y/n)"); + Console.WriteLine("Do you want to update the bot ? (y/n)"); if (Console.ReadKey().Key == ConsoleKey.Y) { var url = $"https://github.com/Wizzy69/SethDiscordBot/releases/download/v{newVersion}/net6.0_linux.zip"; - if (Logger.isConsole) - Console.SetCursorPosition(0, Console.CursorTop); - Logger.WriteLine($"executing: download_file {url}"); + Config.Logger.Log($"executing: download_file {url}"); - await ServerCom.DownloadFileAsync(url, "./update.zip", new Progress(percent => { Logger.Write($"\rProgress: {percent}% "); })); + await ServerCom.DownloadFileAsync(url, "./update.zip", new Progress(percent => { Console.WriteLine($"\rProgress: {percent}% "); })); await File.WriteAllTextAsync("Install.sh", "#!/bin/bash\nunzip -qq -o update.zip \nrm update.zip\nchmod a+x DiscordBot"); - Logger.WriteLine(); try { - Logger.WriteLine("executing: chmod a+x Install.sh"); + Console.WriteLine("executing: chmod a+x Install.sh"); Process.Start("chmod", "a+x Install.sh").WaitForExit(); Process.Start("Install.sh").WaitForExit(); - Logger.WriteLine("executing: rm Install.sh"); + Console.WriteLine("executing: rm Install.sh"); Process.Start("rm", "Install.sh").WaitForExit(); - Logger.WriteLine("The new version of the bot has been installed."); - Logger.WriteLine("Please restart the bot."); + Config.Logger.Log("The new version of the bot has been installed."); + Console.WriteLine("Please restart the bot."); Environment.Exit(0); } catch (Exception ex) { - Logger.WriteErrFile(ex.Message); + Config.Logger.Log(ex.Message,"Updater", TextType.ERROR); if (ex.Message.Contains("Access de")) - Logger.WriteLine("Please run the bot as root."); + Config.Logger.Log("Please run the bot as root."); } @@ -311,7 +298,7 @@ public class Program !File.Exists("./Launcher.exe")) { Console.Clear(); - Logger.WriteLine("Installing a new Launcher ...\nDo NOT close the bot during update !"); + Console.WriteLine("Installing a new Launcher ...\nDo NOT close the bot during update !"); var bar = new Utilities.Utilities.ProgressBar(ProgressBarType.NO_END); bar.Start(); await ServerCom.DownloadFileAsync( @@ -332,56 +319,27 @@ public class Program Console.Clear(); } - public static void GenerateStartUI() + public static void GenerateStartupConfig() { - InputBox box = new InputBox(); - box.Title = "Discord Bot Config - " + Assembly.GetExecutingAssembly().GetName().Version; - box.Message = "Let's setup the bot. Please go through this setup so that you can run the bot.\n\n"; - box.AddLabel("Note:All the information collected here will only be stored locally (on your machine) at the following path: ", TextType.WARNING); - box.AddLabel("/Data/Resources/Config.json", TextType.SUCCESS); + Console.WriteLine("Welcome to the SethBot installer !"); + Console.WriteLine("First, we need to configure the bot. Don't worry, it will be quick !"); + Console.WriteLine("The following information will be stored in the config.json file in the ./Data/Resources folder. You can change it later from there."); + Console.WriteLine("The bot tokn is required to run the bot. You can get it from the Discord Developer Portal. (https://discord.com/developers/applications)"); + Console.WriteLine("Please enter the bot token :"); + var token = Console.ReadLine(); - box.AddOption("Bot Token", (token) => { - if (token.Length != 70 && token.Length != 59) - { - Console.WriteLine("The token is invalid !"); - return false; - } + Console.WriteLine("Please enter the bot prefix :"); + var prefix = Console.ReadLine(); - return true; - }); + Console.WriteLine("Please enter the Server ID :"); + var serverId = Console.ReadLine(); - box.AddOption("Bot prefix (should be one character long)", (prefix) => { - if (int.TryParse(prefix, out int value)) - { - Console.WriteLine("The prefix can not be a number"); - return false; - } + Config.Data.Add("token", token); + Config.Data.Add("prefix", prefix); + Config.Data.Add("ServerID", serverId); - if (prefix.Length != 1) - { - Console.WriteLine("The bot does not support longer prefixes"); - return false; - } + Config.Logger.Log("Config Saved", "Installer", TextType.NORMAL); - return true; - - }); - - - box.AddOption("Server ID (Optional => Press ENTER to leave empty)\nIf you let the Server ID field option empty, some plugins may not work", (servId) => { - if (servId.Length != 18 && servId.Length > 0) - { - Console.WriteLine("The Server ID is invalid"); - return false; - } - - return true; - }); - - List result = box.Show(); - - Config.Data.Add("ServerID", result[2]); - Config.Data.Add("token", result[0]); - Config.Data.Add("prefix", result[1]); + Config.Data.Save(); } } \ No newline at end of file diff --git a/DiscordBot/Utilities/ConsoleCommandsHandler.cs b/DiscordBot/Utilities/ConsoleCommandsHandler.cs index f2d50b8..4cc0fdc 100644 --- a/DiscordBot/Utilities/ConsoleCommandsHandler.cs +++ b/DiscordBot/Utilities/ConsoleCommandsHandler.cs @@ -34,9 +34,6 @@ public class ConsoleCommandsHandler { this.client = client; InitializeBasicCommands(); - - - //Console.WriteLine("Initialized console command handler !"); } private void InitializeBasicCommands() @@ -209,6 +206,7 @@ public class ConsoleCommandsHandler if (OperatingSystem.WINDOWS == Functions.GetOperatingSystem()) { await ServerCom.DownloadFileAsync(info[1], path, null); + Console.WriteLine("Plugin Downloaded !", this, TextType.SUCCESS); } else if (OperatingSystem.LINUX == Functions.GetOperatingSystem()) { @@ -218,6 +216,8 @@ public class ConsoleCommandsHandler bar.Stop("Plugin Downloaded !"); } + + Console.WriteLine("\n"); @@ -239,6 +239,7 @@ public class ConsoleCommandsHandler if (OperatingSystem.WINDOWS == Functions.GetOperatingSystem()) { await ServerCom.DownloadFileAsync(split[0], "./" + split[1], null); + Console.WriteLine("Item "+split[1]+" downloaded !", this, TextType.SUCCESS); } else if (OperatingSystem.LINUX == Functions.GetOperatingSystem()) { @@ -276,6 +277,8 @@ public class ConsoleCommandsHandler isDownloading = false; + Config.Logger.Log("Plugin installed !", this, TextType.SUCCESS); + //await ExecuteCommad("localload " + name); } ); @@ -330,6 +333,8 @@ public class ConsoleCommandsHandler await Functions.SaveToJsonFile(Functions.dataFolder + "Plugins.json", Config.Plugins); await client.StopAsync(); await client.DisposeAsync(); + + Config.Logger.SaveToFile(); await Task.Delay(1000); Environment.Exit(0); } @@ -378,89 +383,7 @@ public class ConsoleCommandsHandler } }); - AddCommand("remplug", "Remove a plugin", "remplug [plugName]", async args => - { - if (args.Length <= 1) return; - isDownloading = true; - var plugName = string.Join(' ', args, 1, args.Length - 1); - if (pluginsLoaded) - { - if (Functions.GetOperatingSystem() == OperatingSystem.WINDOWS) - { - Process.Start("DiscordBot.exe", $"/remplug {plugName}"); - await Task.Delay(100); - Environment.Exit(0); - } - else - { - Process.Start("./DiscordBot", $"/remplug {plugName}"); - await Task.Delay(100); - Environment.Exit(0); - } - - isDownloading = false; - return; - } - - - var location = $"./Data/Plugins/{plugName}.dll"; - - if (!File.Exists(location)) - { - Console.WriteLine("The plugin does not exist"); - return; - } - - File.Delete(location); - - Console.WriteLine("Removed the plugin DLL. Checking for other files ..."); - - var info = await manager.GetPluginLinkByName(plugName); - if (info[2] != string.Empty) - { - var lines = await ServerCom.ReadTextFromURL(info[2]); - foreach (var line in lines) - { - if (!(line.Length > 0 && line.Contains(","))) - continue; - var split = line.Split(','); - if (File.Exists("./" + split[1])) - File.Delete("./" + split[1]); - - - Console.WriteLine("Removed: " + split[1]); - } - - if (Directory.Exists($"./Data/Plugins/{plugName}")) - Directory.Delete($"./Data/Plugins/{plugName}", true); - - if (Directory.Exists(plugName)) - Directory.Delete(plugName, true); - } - - isDownloading = false; - Console.WriteLine(plugName + " has been successfully deleted !"); - }); - - AddCommand("reload", "Reload the bot with all plugins", () => - { - - if (Functions.GetOperatingSystem() == OperatingSystem.WINDOWS) - { - Process.Start("DiscordBot.exe", "lp"); - HandleCommand("sd"); - } - else - { - //HandleCommand("sd"); - Console.WriteLine("This command can not be used outside of Windows yet. Please restart the bot using the manual way"); - } - }); - - //AddCommand(""); - - //Sort the commands by name commandList.Sort((x, y) => x.CommandName.CompareTo(y.CommandName)); } @@ -492,20 +415,6 @@ public class ConsoleCommandsHandler return commandList.FirstOrDefault(t => t.CommandName == command); } - /* public static async Task ExecuteSpecialCommand(string command) - { - if (!command.StartsWith("_")) return; - - string[] args = command.Split(' '); - foreach (var item in commandList) - if (item.CommandName == args[0]) - { - Console.WriteLine(); - item.Action(args); - } - - }*/ - public static async Task ExecuteCommad(string command) { var args = command.Split(' '); diff --git a/DiscordBotPlugins/Economy/Commands/Balance.cs b/DiscordBotPlugins/Economy/Commands/Balance.cs deleted file mode 100644 index 7653790..0000000 --- a/DiscordBotPlugins/Economy/Commands/Balance.cs +++ /dev/null @@ -1,72 +0,0 @@ -using Discord; -using PluginManager.Interfaces; -using Discord.WebSocket; -namespace Economy.Commands; - -public class Balance : DBSlashCommand -{ - public string Name => "balance"; - - public string Description => "Change or view info about your balance"; - - public bool canUseDM => false; // server only - - public List Options => new List() - { - new SlashCommandOptionBuilder(){Name="send", Description="Send money to another user", Type=ApplicationCommandOptionType.SubCommand, Options=new List() - { - new SlashCommandOptionBuilder(){Name="user", Description="The user to send money to", Type=ApplicationCommandOptionType.User, IsRequired=true}, - new SlashCommandOptionBuilder(){Name="amount", Description="The amount of money to send", Type=ApplicationCommandOptionType.Number, IsRequired=true} - }}, - - new SlashCommandOptionBuilder(){Name="info", Description="View info about your balance", Type=ApplicationCommandOptionType.SubCommand} - }; - - public async void ExecuteServer(SocketSlashCommand context) - { - var option = context.Data.Options.FirstOrDefault(); - var guild = context.User.MutualGuilds.FirstOrDefault(g => g.Id == context.GuildId); - if (option.Name == "send") - { - var options = option.Options.ToArray(); - Console.WriteLine(options.Length); - var user = options[0].Value as IUser; - var amount = options[1].Value as float?; - - if (amount == null) - { - await context.RespondAsync("The amount is invalid"); - return; - } - - if (user == null) - { - await context.RespondAsync("The user is invalid"); - return; - } - - if (user.Id == context.User.Id) - { - await context.RespondAsync("You can't send money to yourself"); - return; - } - - var balance = await Engine.GetBalance(context.User.Id); - if (balance < amount) - { - await context.RespondAsync("You don't have enough money to send"); - return; - } - - await Engine.RemoveMoney(context.User.Id, amount.Value); - await Engine.AddMoney(user.Id, amount.Value); - - await context.RespondAsync($"You sent {amount} to {guild.GetUser(user.Id).Mention}"); - } - else if (option.Name == "info") - { - var balance = await Engine.GetBalance(context.User.Id); - await context.RespondAsync($"Your balance is {balance}"); - } - } -} diff --git a/DiscordBotPlugins/Economy/Economy.csproj b/DiscordBotPlugins/Economy/Economy.csproj deleted file mode 100644 index 3c7c46a..0000000 --- a/DiscordBotPlugins/Economy/Economy.csproj +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - net6.0 - enable - enable - - \ No newline at end of file diff --git a/DiscordBotPlugins/Economy/Engine.cs b/DiscordBotPlugins/Economy/Engine.cs deleted file mode 100644 index f22b778..0000000 --- a/DiscordBotPlugins/Economy/Engine.cs +++ /dev/null @@ -1,62 +0,0 @@ -using System; -using System.Collections.Generic; - -using PluginManager.Database; - -namespace Economy; -public static class Engine -{ - public static SqlDatabase Database { get; set; } - - public static async void AddUser(ulong userID) - { - await Database.InsertAsync("UserBank", userID.ToString(), "0"); - } - - public static async void RemoveUser(ulong userID) - { - await Database.RemoveKeyAsync("UserBank", "UserID", userID.ToString()); - } - - public static async Task AddMoney(ulong userID, float amount) - { - var balance = await Database.GetValueAsync("UserBank", "UserID", userID.ToString(), "Balance"); - if (balance == null) - { - AddUser(userID); - balance = "0"; - } - - var float_balance = float.Parse(balance); - float_balance += amount; - await Database.SetValueAsync("UserBank", "UserID", userID.ToString(), "Balance", float_balance.ToString()); - } - - public static async Task RemoveMoney(ulong userID, float amount) - { - var balance = await Database.GetValueAsync("UserBank", "UserID", userID.ToString(), "Balance"); - if (balance == null) - { - AddUser(userID); - balance = "0"; - } - - var float_balance = float.Parse(balance); - float_balance -= amount; - await Database.SetValueAsync("UserBank", "UserID", userID.ToString(), "Balance", float_balance.ToString()); - } - - public static async Task GetBalance(ulong userID) - { - var balance = await Database.GetValueAsync("UserBank", "UserID", userID.ToString(), "Balance"); - if (balance == null) - { - AddUser(userID); - balance = "0"; - } - - return float.Parse(balance); - } - - -} diff --git a/DiscordBotPlugins/Economy/Entry.cs b/DiscordBotPlugins/Economy/Entry.cs deleted file mode 100644 index 882c5c7..0000000 --- a/DiscordBotPlugins/Economy/Entry.cs +++ /dev/null @@ -1,31 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using PluginManager.Interfaces; -using PluginManager.Database; - -namespace Economy -{ - public class EntryEvent : DBEvent - { - public string Name => "Economy Plugin Engine"; - - public string Description => "The economy plugin main engine"; - - public async void Start(global::Discord.WebSocket.DiscordSocketClient client) - { - Console.WriteLine("Economy Plugin Engine Started"); - Directory.CreateDirectory(PluginManager.Others.Functions.dataFolder + "/Economy"); - Engine.Database = new SqlDatabase(PluginManager.Others.Functions.dataFolder + "/Economy/Economy.db"); - await Engine.Database.Open(); - await Engine.Database.CreateTableAsync("UserBank", "UserID INT", "Balance FLOAT"); - - client.Disconnected += (e) => - { - Engine.Database.Stop(); - return Task.CompletedTask; - }; - } - } -} \ No newline at end of file diff --git a/PluginManager/Bot/CommandHandler.cs b/PluginManager/Bot/CommandHandler.cs index 4c9d2ca..9493000 100644 --- a/PluginManager/Bot/CommandHandler.cs +++ b/PluginManager/Bot/CommandHandler.cs @@ -61,9 +61,7 @@ internal class CommandHandler } catch (Exception ex) { - - Console.WriteLine(ex.ToString()); - ex.WriteErrFile(); + Config.Logger.Log(ex.Message, "CommandHandler", TextType.ERROR); } return Task.CompletedTask; diff --git a/PluginManager/Config.cs b/PluginManager/Config.cs index 49b3069..e4ca614 100644 --- a/PluginManager/Config.cs +++ b/PluginManager/Config.cs @@ -18,7 +18,7 @@ public static class Config public static Json Data; public static Json Plugins; - public static async Task Initialize(bool isConsole) + public static async Task Initialize() { if (IsLoaded) return; @@ -26,21 +26,21 @@ public static class Config Directory.CreateDirectory("./Data/Resources"); Directory.CreateDirectory("./Data/Plugins"); Directory.CreateDirectory("./Data/PAKS"); + Directory.CreateDirectory("./Data/Logs/Logs"); + Directory.CreateDirectory("./Data/Logs/Errors"); Data = new Json("./Data/Resources/config.json"); Plugins = new Json("./Data/Resources/Plugins.json"); - Logger = new DBLogger(); + Config.Data["LogFolder"] = "./Data/Logs/Logs"; + Config.Data["ErrorFolder"] = "./Data/Logs/Errors"; - PluginManager.Logger.Initialize(isConsole); + Logger = new DBLogger(); ArchiveManager.Initialize(); IsLoaded = true; - if (isConsole) - PluginManager.Logger.LogEvent += (message) => { Console.Write(message); }; - Logger.Log("Config initialized", TextType.NORMAL); } diff --git a/PluginManager/Loaders/Loader.cs b/PluginManager/Loaders/Loader.cs index a688a92..c1f971e 100644 --- a/PluginManager/Loaders/Loader.cs +++ b/PluginManager/Loaders/Loader.cs @@ -60,9 +60,7 @@ namespace PluginManager.Loaders } catch (Exception ex) { - Logger.WriteLine(ex.Message); - Logger.WriteLine("PluginName: " + new FileInfo(file).Name.Split('.')[0] + " not loaded"); - + Config.Logger.Log("PluginName: " + new FileInfo(file).Name.Split('.')[0] + " not loaded", this, Others.TextType.ERROR); continue; } if (FileLoaded != null) @@ -133,7 +131,7 @@ namespace PluginManager.Loaders } catch (Exception ex) { - Logger.WriteErrFile(ex.ToString()); + Config.Logger.Log(ex.Message, this, Others.TextType.ERROR); return null; } diff --git a/PluginManager/Logger.cs b/PluginManager/Logger.cs deleted file mode 100644 index 3ee5d7e..0000000 --- a/PluginManager/Logger.cs +++ /dev/null @@ -1,182 +0,0 @@ -using System; -using System.IO; -using System.Numerics; -using PluginManager.Others; - -using Discord; - -namespace PluginManager -{ - [Obsolete("Use Logger from PluginManager.Others.Logger namespace instead\nThis class will be removed soon")] - public static class Logger - { - public static bool isConsole { get; private set; } - private static bool isInitialized; - - private static string? logFolder; - private static string? errFolder; - - public static void Initialize(bool console) - { - if (isInitialized) - throw new Exception("Logger is already initialized"); - - if (!Config.Data.ContainsKey("LogFolder")) - Config.Data.Add("LogFolder", "./Data/Output/Logs/"); - - if (!Config.Data.ContainsKey("ErrorFolder")) - Config.Data.Add("ErrorFolder", "./Data/Output/Errors/"); - - isInitialized = true; - - logFolder = Config.Data["LogFolder"]; - errFolder = Config.Data["ErrorFolder"]; - isConsole = console; - } - - - public delegate void LogEventHandler(string Message); - public static event LogEventHandler LogEvent; - - public static void Log(string Message) - { - if (!isInitialized) throw new Exception("Logger is not initialized"); - LogEvent?.Invoke(Message); - } - - public static void Log(string Message, params object[] Args) - { - if (!isInitialized) throw new Exception("Logger is not initialized"); - LogEvent?.Invoke(string.Format(Message, Args)); - } - - public static void Log(IMessage message, bool newLine) - { - if (!isInitialized) throw new Exception("Logger is not initialized"); - LogEvent?.Invoke(message.Content); - if (newLine) - LogEvent?.Invoke("\n"); - } - - public static void WriteLine(string? message) - { - if (!isInitialized) throw new Exception("Logger is not initialized"); - if (message is not null) - LogEvent?.Invoke(message + '\n'); - } - - public static void LogError(System.Exception ex) - { - if (!isInitialized) throw new Exception("Logger is not initialized"); - string message = "[ERROR]" + ex.Message; - LogEvent?.Invoke(message + '\n'); - } - - public static void LogError(string? message) - { - if (!isInitialized) throw new Exception("Logger is not initialized"); - if (message is not null) - LogEvent?.Invoke("[ERROR]" + message + '\n'); - } - - - public static void WriteLine() - { - if (!isInitialized) throw new Exception("Logger is not initialized"); - LogEvent?.Invoke("\n"); - } - - public static void Write(string message) - { - if (!isInitialized) throw new Exception("Logger is not initialized"); - LogEvent?.Invoke(message); - } - - - public static void Write(T c) - { - if (!isInitialized) throw new Exception("Logger is not initialized"); - LogEvent?.Invoke($"{c}"); - } - - public static void Write(T c, params object[] Args) - { - if (!isInitialized) throw new Exception("Logger is not initialized"); - LogEvent?.Invoke(string.Format($"{c}", Args)); - } - - public static void WriteColored(string message, ConsoleColor color) - { - if (!isInitialized) throw new Exception("Logger is not initialized"); - if (!isConsole) - { - LogEvent?.Invoke(message); - return; - } - var oldColor = Console.ForegroundColor; - Console.ForegroundColor = color; - LogEvent?.Invoke(message); - Console.ForegroundColor = oldColor; - } - public static void SetConsoleColor(TextType type) - { - if(!isConsole) return; - switch (type) - { - case TextType.NORMAL: - Console.ForegroundColor = ConsoleColor.White; - break; - case TextType.ERROR: - Console.ForegroundColor = ConsoleColor.Red; - break; - case TextType.WARNING: - Console.ForegroundColor = ConsoleColor.Yellow; - break; - case TextType.SUCCESS: - Console.ForegroundColor = ConsoleColor.Green; - break; - default: - Console.ForegroundColor = ConsoleColor.White; - break; - } - } - - public static void ResetConsoleColor() - { - if (!isConsole) return; - Console.ForegroundColor = ConsoleColor.White; - } - - /// - /// Write logs to file - /// - /// The message to be wrote - public static void WriteLogFile(string LogMessage) - { - if (!isInitialized) throw new Exception("Logger is not initialized"); - var logsPath = logFolder + $"{DateTime.Today.ToShortDateString().Replace("/", "-").Replace("\\", "-")} Log.txt"; - Directory.CreateDirectory(logFolder); - File.AppendAllText(logsPath, $"[{DateTime.Today.ToShortTimeString()}] {LogMessage} \n"); - } - - /// - /// Write error to file - /// - /// The message to be wrote - public static void WriteErrFile(string ErrMessage) - { - if (!isInitialized) throw new Exception("Logger is not initialized"); - var errPath = errFolder + - $"{DateTime.Today.ToShortDateString().Replace("/", "-").Replace("\\", "-")} Error.txt"; - Directory.CreateDirectory(errFolder); - File.AppendAllText(errPath, $"[{DateTime.Today.ToShortTimeString()}] {ErrMessage} \n"); - } - - public static void WriteErrFile(this Exception ex) - { - if (!isInitialized) throw new Exception("Logger is not initialized"); - WriteErrFile(ex.ToString()); - } - - } -} diff --git a/PluginManager/WindowManagement/Controls/ConsoleOption.cs b/PluginManager/WindowManagement/Controls/ConsoleOption.cs deleted file mode 100644 index 7a212f2..0000000 --- a/PluginManager/WindowManagement/Controls/ConsoleOption.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; - -namespace PluginManager.WindowManagement.Controls -{ - public class ConsoleOption - { - public string Text { get; set; } - public byte Index { get; set; } - - public Action Action { get; set; } - } -} \ No newline at end of file diff --git a/PluginManager/WindowManagement/Controls/Label.cs b/PluginManager/WindowManagement/Controls/Label.cs deleted file mode 100644 index e7d41ce..0000000 --- a/PluginManager/WindowManagement/Controls/Label.cs +++ /dev/null @@ -1,47 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using PluginManager.Others; - -namespace PluginManager.WindowManagement.Controls -{ - public class Label - { - public string Text { get; set; } - public TextType Type { get; set; } = TextType.NORMAL; - - public void Show() - { - Logger.SetConsoleColor(Type); - Console.WriteLine(Text); - Logger.ResetConsoleColor(); - } - - public void Show(int x, int y) - { - Logger.SetConsoleColor(Type); - Console.SetCursorPosition(x, y); - Console.WriteLine(Text); - - Logger.ResetConsoleColor(); - } - - public void Show(int x, int y, ConsoleColor color) - { - Console.SetCursorPosition(x, y); - Console.ForegroundColor = color; - Console.WriteLine(Text); - Console.ResetColor(); - } - - public void Show(int x, int y, ConsoleColor color, ConsoleColor background) - { - Console.SetCursorPosition(x, y); - Console.ForegroundColor = color; - Console.BackgroundColor = background; - Console.WriteLine(Text); - Console.ResetColor(); - } - } -} \ No newline at end of file diff --git a/PluginManager/WindowManagement/Controls/TextBox.cs b/PluginManager/WindowManagement/Controls/TextBox.cs deleted file mode 100644 index 2a58b6c..0000000 --- a/PluginManager/WindowManagement/Controls/TextBox.cs +++ /dev/null @@ -1,26 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; - -namespace PluginManager.WindowManagement.Controls -{ - public class TextBox - { - public Label Label { get; set; } - public string Text { get; private set; } - public Func IsValid { get; set; } - - public bool SetText(string text) - { - if(IsValid(text)) - { - Text = text; - return true; - } - - return false; - - } - } -} \ No newline at end of file diff --git a/PluginManager/WindowManagement/InputBox.cs b/PluginManager/WindowManagement/InputBox.cs deleted file mode 100644 index 34ee93d..0000000 --- a/PluginManager/WindowManagement/InputBox.cs +++ /dev/null @@ -1,61 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using PluginManager.WindowManagement.Controls; -using PluginManager.Others; - -namespace PluginManager.WindowManagement -{ - public class InputBox - { - public string Title { get; set; } - public string Message { get; set; } - - private List options = new List(); - private List