From e5f3aff39aed993cba60376c79ebff7448a42bd0 Mon Sep 17 00:00:00 2001 From: Wizzy69 Date: Wed, 2 Nov 2022 15:35:18 +0200 Subject: [PATCH] patch (database & slash commands) --- DiscordBot/App.config | 4 - DiscordBot/Discord/Core/Boot.cs | 9 +- DiscordBot/DiscordBot - Backup.csproj | 52 +++++++++ DiscordBot/Entry.cs | 29 +++++ DiscordBot/Program.cs | 54 ++++----- PluginManager/Items/ConsoleCommandsHandler.cs | 89 +++++++------- PluginManager/Loaders/PluginLoader.cs | 74 ++---------- PluginManager/Online/PluginsManager.cs | 6 +- PluginManager/Online/ServerCom.cs | 2 +- PluginManager/Online/Updates/PluginUpdater.cs | 2 +- PluginManager/Others/Console Utilities.cs | 109 ++++++++++-------- PluginManager/Others/Functions.cs | 4 +- PluginManager/PluginManager.csproj | 2 +- PluginManager/Variables.cs | 6 +- SethDiscordBot.sln | 2 +- 15 files changed, 240 insertions(+), 204 deletions(-) delete mode 100644 DiscordBot/App.config create mode 100644 DiscordBot/DiscordBot - Backup.csproj create mode 100644 DiscordBot/Entry.cs diff --git a/DiscordBot/App.config b/DiscordBot/App.config deleted file mode 100644 index d78bbbb..0000000 --- a/DiscordBot/App.config +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/DiscordBot/Discord/Core/Boot.cs b/DiscordBot/Discord/Core/Boot.cs index 460455e..aefffab 100644 --- a/DiscordBot/Discord/Core/Boot.cs +++ b/DiscordBot/Discord/Core/Boot.cs @@ -60,7 +60,14 @@ internal class Boot /// Task public async Task Awake() { - var config = new DiscordSocketConfig { AlwaysDownloadUsers = true }; + var config = new DiscordSocketConfig + { + + AlwaysDownloadUsers = true, + + //Disable system clock checkup (for responses at slash commands) + UseInteractionSnowflakeDate = false + }; client = new DiscordSocketClient(config); service = new CommandService(); diff --git a/DiscordBot/DiscordBot - Backup.csproj b/DiscordBot/DiscordBot - Backup.csproj new file mode 100644 index 0000000..5deed1f --- /dev/null +++ b/DiscordBot/DiscordBot - Backup.csproj @@ -0,0 +1,52 @@ + + + + Exe + net6.0 + disable + + + False + True + 1.0.1.0 + + + + none + + + + none + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/DiscordBot/Entry.cs b/DiscordBot/Entry.cs new file mode 100644 index 0000000..1a20f1c --- /dev/null +++ b/DiscordBot/Entry.cs @@ -0,0 +1,29 @@ +using System; +using System.IO; +using System.Reflection; + +namespace DiscordBot +{ + + public class Entry + { + [STAThread] + public static void Main(string[] args) + { + AppDomain currentDomain = AppDomain.CurrentDomain; + currentDomain.AssemblyResolve += new ResolveEventHandler(LoadFromSameFolder); + + static Assembly LoadFromSameFolder(object sender, ResolveEventArgs args) + { + string folderPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "./Libraries"); + string assemblyPath = Path.Combine(folderPath, new AssemblyName(args.Name).Name + ".dll"); + if (!File.Exists(assemblyPath)) return null; + Assembly assembly = Assembly.LoadFrom(assemblyPath); + return assembly; + } + + Program.Startup(args); + + } + } +} diff --git a/DiscordBot/Program.cs b/DiscordBot/Program.cs index f1ae28a..268e340 100644 --- a/DiscordBot/Program.cs +++ b/DiscordBot/Program.cs @@ -30,10 +30,9 @@ public class Program /// The main entry point for the application. /// [STAThread] - [Obsolete] - public static void Main(string[] args) + public static void Startup(string[] args) { - Console.WriteLine("Loading resources ..."); + PreLoadComponents().Wait(); if (!Config.Variables.Exists("ServerID") || !Config.Variables.Exists("token") || @@ -195,7 +194,7 @@ public class Program private static void NoGUI() { #if DEBUG - Console.WriteLine(); + Settings.Variables.outputStream.WriteLine(); ConsoleCommandsHandler.ExecuteCommad("lp").Wait(); #else if (loadPluginsOnStartup) consoleCommandsHandler.HandleCommand("lp"); @@ -211,7 +210,7 @@ public class Program #endif ) && cmd.Length > 0) - Console.WriteLine("Failed to run command " + cmd); + Settings.Variables.outputStream.WriteLine("Failed to run command " + cmd); } } @@ -229,36 +228,37 @@ public class Program "https://raw.githubusercontent.com/Wizzy69/installer/discord-bot-files/StartupMessage"); foreach (var message in startupMessageList) - Console.WriteLine(message); + Settings.Variables.outputStream.WriteLine(message); - Console.WriteLine( + Settings.Variables.outputStream.WriteLine( $"Running on version: {Assembly.GetExecutingAssembly().GetName().Version}"); - Console.WriteLine($"Git URL: {Settings.Variables.WebsiteURL}"); + Settings.Variables.outputStream.WriteLine($"Git URL: {Settings.Variables.WebsiteURL}"); - Console_Utilities.WriteColorText( + Utilities.WriteColorText( "&rRemember to close the bot using the ShutDown command (&ysd&r) or some settings won't be saved\n"); Console.ForegroundColor = ConsoleColor.White; if (Config.Variables.Exists("LaunchMessage")) - Console_Utilities.WriteColorText(Config.Variables.GetValue("LaunchMessage")); + Utilities.WriteColorText(Config.Variables.GetValue("LaunchMessage")); - Console_Utilities.WriteColorText( + Utilities.WriteColorText( "Please note that the bot saves a backup save file every time you are using the shudown command (&ysd&c)"); - Console.WriteLine("============================ LOG ============================"); + Settings.Variables.outputStream.WriteLine("============================ LOG ============================"); try { - var token = Config.Variables.GetValue("token"); + string token = ""; #if DEBUG - Console.WriteLine("Starting in DEBUG MODE"); - if (!Directory.Exists("./Data/BetaTest")) - Console.WriteLine("Failed to start in debug mode because the folder ./Data/BetaTest does not exist"); - else - token = File.ReadAllText("./Data/BetaTest/token.txt"); - //Debug mode code... -#endif + if (await Settings.sqlDatabase.TableExistsAsync("BetaTest")) + { + Settings.Variables.outputStream.WriteLine("Starting in DEBUG MODE"); + token = await Settings.sqlDatabase.GetValueAsync("BetaTest", "VariableName", "Token", "Value"); + } +#else + token = Config.Variables.GetValue("token"); +#endif var prefix = Config.Variables.GetValue("prefix"); var discordbooter = new Boot(token, prefix); await discordbooter.Awake(); @@ -266,7 +266,7 @@ public class Program } catch (Exception ex) { - Console.WriteLine(ex); + Settings.Variables.outputStream.WriteLine(ex); return null; } } @@ -285,7 +285,7 @@ public class Program if (len > 0 && args[0] == "/remplug") { var plugName = string.Join(' ', args, 1, args.Length - 1); - Console.WriteLine("Starting to remove " + plugName); + Settings.Variables.outputStream.WriteLine("Starting to remove " + plugName); await ConsoleCommandsHandler.ExecuteCommad("remplug " + plugName); loadPluginsOnStartup = true; } @@ -316,7 +316,9 @@ public class Program private static async Task PreLoadComponents() { - var main = new Console_Utilities.ProgressBar(ProgressBarType.NO_END); + Settings.Variables.outputStream = Console.Out; + Settings.Variables.outputStream.WriteLine("Loading resources ..."); + var main = new Utilities.ProgressBar(ProgressBarType.NO_END); main.Start(); Directory.CreateDirectory("./Data/Resources"); Directory.CreateDirectory("./Data/Plugins"); @@ -395,7 +397,7 @@ public class Program { var url = $"https://github.com/Wizzy69/SethDiscordBot/releases/download/v{newVersion}/net6.0_linux.zip"; - Console.WriteLine("Downloading update ..."); + Settings.Variables.outputStream.WriteLine("Downloading update ..."); await ServerCom.DownloadFileNoProgressAsync(url, "./update.zip"); await File.WriteAllTextAsync("Install.sh", "#!/bin/bash\nunzip -qq update.zip -d ./\nrm update.zip\nchmod +x SethDiscordBot\n./DiscordBot"); @@ -417,8 +419,8 @@ public class Program !File.Exists("./Updater/Updater.exe")) { Console.Clear(); - Console.WriteLine("Installing updater ...\nDo NOT close the bot during update !"); - var bar = new Console_Utilities.ProgressBar(ProgressBarType.NO_END); + Settings.Variables.outputStream.WriteLine("Installing updater ...\nDo NOT close the bot during update !"); + var bar = new Utilities.ProgressBar(ProgressBarType.NO_END); bar.Start(); await ServerCom.DownloadFileNoProgressAsync( "https://github.com/Wizzy69/installer/releases/download/release-1-discordbot/Updater.zip", diff --git a/PluginManager/Items/ConsoleCommandsHandler.cs b/PluginManager/Items/ConsoleCommandsHandler.cs index ad2d5b0..a99e935 100644 --- a/PluginManager/Items/ConsoleCommandsHandler.cs +++ b/PluginManager/Items/ConsoleCommandsHandler.cs @@ -34,7 +34,9 @@ public class ConsoleCommandsHandler { this.client = client; InitializeBasicCommands(); - //Console.WriteLine("Initialized console command handler !"); + + + //Settings.Variables.outputStream.WriteLine("Initialized console command handler !"); } private void InitializeBasicCommands() @@ -45,7 +47,7 @@ public class ConsoleCommandsHandler { if (args.Length <= 1) { - Console.WriteLine("Available commands:"); + Settings.Variables.outputStream.WriteLine("Available commands:"); var items = new List(); items.Add(new[] { "-", "-", "-" }); items.Add(new[] { "Command", "Description", "Usage" }); @@ -61,19 +63,19 @@ public class ConsoleCommandsHandler } items.Add(new[] { "-", "-", "-" }); - Console_Utilities.FormatAndAlignTable(items, TableFormat.DEFAULT); + Utilities.FormatAndAlignTable(items, TableFormat.DEFAULT); } else { foreach (var command in commandList) if (command.CommandName == args[1]) { - Console.WriteLine("Command description: " + command.Description); - Console.WriteLine("Command execution format:" + command.Usage); + Settings.Variables.outputStream.WriteLine("Command description: " + command.Description); + Settings.Variables.outputStream.WriteLine("Command execution format:" + command.Usage); return; } - Console.WriteLine("Command not found"); + Settings.Variables.outputStream.WriteLine("Command not found"); } } ); @@ -92,16 +94,16 @@ public class ConsoleCommandsHandler if (success) { Console.ForegroundColor = ConsoleColor.Green; - Console.WriteLine("[CMD] Successfully loaded command : " + name); + Settings.Variables.outputStream.WriteLine("[CMD] Successfully loaded command : " + name); } else { Console.ForegroundColor = ConsoleColor.Red; if (exception is null) - Console.WriteLine("An error occured while loading: " + name); + Settings.Variables.outputStream.WriteLine("An error occured while loading: " + name); else - Console.WriteLine("[CMD] Failed to load command : " + name + " because " + exception!.Message); + Settings.Variables.outputStream.WriteLine("[CMD] Failed to load command : " + name + " because " + exception!.Message); } Console.ForegroundColor = cc; @@ -114,12 +116,12 @@ public class ConsoleCommandsHandler if (success) { Console.ForegroundColor = ConsoleColor.Green; - Console.WriteLine("[EVENT] Successfully loaded event : " + name); + Settings.Variables.outputStream.WriteLine("[EVENT] Successfully loaded event : " + name); } else { Console.ForegroundColor = ConsoleColor.Red; - Console.WriteLine("[EVENT] Failed to load event : " + name + " because " + exception!.Message); + Settings.Variables.outputStream.WriteLine("[EVENT] Failed to load event : " + name + " because " + exception!.Message); } Console.ForegroundColor = cc; @@ -133,12 +135,12 @@ public class ConsoleCommandsHandler if (success) { Console.ForegroundColor = ConsoleColor.Green; - Console.WriteLine("[SLASH] Successfully loaded command : " + name); + Settings.Variables.outputStream.WriteLine("[SLASH] Successfully loaded command : " + name); } else { Console.ForegroundColor = ConsoleColor.Red; - Console.WriteLine("[SLASH] Failed to load command : " + name + " because " + exception!.Message); + Settings.Variables.outputStream.WriteLine("[SLASH] Failed to load command : " + name + " because " + exception!.Message); } Console.ForegroundColor = cc; @@ -158,7 +160,7 @@ public class ConsoleCommandsHandler if (args.Length == 1) { isDownloading = false; - Console.WriteLine("Please specify plugin name"); + Settings.Variables.outputStream.WriteLine("Please specify plugin name"); return; } @@ -172,12 +174,12 @@ public class ConsoleCommandsHandler if (name == "") { isDownloading = false; - Console_Utilities.WriteColorText("Name is invalid"); + Utilities.WriteColorText("Name is invalid"); return; } isDownloading = false; - Console_Utilities.WriteColorText($"Failed to find plugin &b{name} &c!" + + Utilities.WriteColorText($"Failed to find plugin &b{name} &c!" + " Use &glistplugs &ccommand to display all available plugins !"); return; } @@ -194,20 +196,20 @@ public class ConsoleCommandsHandler } else if (OperatingSystem.LINUX == Functions.GetOperatingSystem()) { - var bar = new Console_Utilities.ProgressBar(ProgressBarType.NO_END); + var bar = new Utilities.ProgressBar(ProgressBarType.NO_END); bar.Start(); await ServerCom.DownloadFileNoProgressAsync(info[1], path); bar.Stop("Plugin Downloaded !"); } - Console.WriteLine("\n"); + Settings.Variables.outputStream.WriteLine("\n"); // check requirements if any if (info.Length == 3 && info[2] != string.Empty && info[2] != null) { - Console.WriteLine($"Downloading requirements for plugin : {name}"); + Settings.Variables.outputStream.WriteLine($"Downloading requirements for plugin : {name}"); var lines = await ServerCom.ReadTextFromURL(info[2]); @@ -216,7 +218,7 @@ public class ConsoleCommandsHandler if (!(line.Length > 0 && line.Contains(","))) continue; var split = line.Split(','); - Console.WriteLine($"\nDownloading item: {split[1]}"); + Settings.Variables.outputStream.WriteLine($"\nDownloading item: {split[1]}"); if (File.Exists("./" + split[1])) File.Delete("./" + split[1]); if (OperatingSystem.WINDOWS == Functions.GetOperatingSystem()) { @@ -224,32 +226,32 @@ public class ConsoleCommandsHandler } else if (OperatingSystem.LINUX == Functions.GetOperatingSystem()) { - var bar = new Console_Utilities.ProgressBar(ProgressBarType.NO_END); + var bar = new Utilities.ProgressBar(ProgressBarType.NO_END); bar.Start(); await ServerCom.DownloadFileNoProgressAsync(split[0], "./" + split[1]); bar.Stop("Item downloaded !"); } - Console.WriteLine(); + Settings.Variables.outputStream.WriteLine(); if (split[0].EndsWith(".pak")) { File.Move("./" + split[1], "./Data/PAKS/" + split[1], true); } else if (split[0].EndsWith(".zip") || split[0].EndsWith(".pkg")) { - Console.WriteLine($"Extracting {split[1]} ..."); - var bar = new Console_Utilities.ProgressBar( + Settings.Variables.outputStream.WriteLine($"Extracting {split[1]} ..."); + var bar = new Utilities.ProgressBar( ProgressBarType.NO_END); bar.Start(); await Functions.ExtractArchive("./" + split[1], "./", null, UnzipProgressType.PercentageFromTotalSize); bar.Stop("Extracted"); - Console.WriteLine("\n"); + Settings.Variables.outputStream.WriteLine("\n"); File.Delete("./" + split[1]); } } - Console.WriteLine(); + Settings.Variables.outputStream.WriteLine(); } var ver = await ServerCom.GetVersionOfPackageFromWeb(name); @@ -269,7 +271,7 @@ public class ConsoleCommandsHandler return; var data = Config.Variables.GetValue(args[1]); - Console.WriteLine($"{args[1]} => {data}"); + Settings.Variables.outputStream.WriteLine($"{args[1]} => {data}"); } ); @@ -284,11 +286,11 @@ public class ConsoleCommandsHandler try { Config.Variables.Add(key, value, isReadOnly); - Console.WriteLine($"Updated config file with the following command: {args[1]} => {value}"); + Settings.Variables.outputStream.WriteLine($"Updated config file with the following command: {args[1]} => {value}"); } catch (Exception ex) { - Console.WriteLine(ex.ToString()); + Settings.Variables.outputStream.WriteLine(ex.ToString()); } } ); @@ -305,11 +307,11 @@ public class ConsoleCommandsHandler { if (client is null) return; - var bar = new Console_Utilities.ProgressBar(ProgressBarType.NO_END); + var bar = new Utilities.ProgressBar(ProgressBarType.NO_END); bar.Start(); bar.Stop("Saved config !"); - Console.WriteLine(); + Settings.Variables.outputStream.WriteLine(); Settings.sqlDatabase.Stop(); await client.StopAsync(); await client.DisposeAsync(); @@ -339,17 +341,17 @@ public class ConsoleCommandsHandler { var instance = (DBEvent)Activator.CreateInstance(type); instance.Start(this.client); - Console.WriteLine($"[EVENT] Loaded external {type.FullName}!"); + Settings.Variables.outputStream.WriteLine($"[EVENT] Loaded external {type.FullName}!"); } else if (type.IsClass && typeof(DBCommand).IsAssignableFrom(type)) { var instance = (DBCommand)Activator.CreateInstance(type); - Console.WriteLine($"[CMD] Instance: {type.FullName} loaded !"); + Settings.Variables.outputStream.WriteLine($"[CMD] Instance: {type.FullName} loaded !"); } } catch (Exception ex) { - Console.WriteLine(ex.Message); + Settings.Variables.outputStream.WriteLine(ex.Message); } }); @@ -383,13 +385,13 @@ public class ConsoleCommandsHandler if (!File.Exists(location)) { - Console.WriteLine("The plugin does not exist"); + Settings.Variables.outputStream.WriteLine("The plugin does not exist"); return; } File.Delete(location); - Console.WriteLine("Removed the plugin DLL. Checking for other files ..."); + Settings.Variables.outputStream.WriteLine("Removed the plugin DLL. Checking for other files ..."); var info = await manager.GetPluginLinkByName(plugName); if (info[2] != string.Empty) @@ -404,7 +406,7 @@ public class ConsoleCommandsHandler File.Delete("./" + split[1]); - Console.WriteLine("Removed: " + split[1]); + Settings.Variables.outputStream.WriteLine("Removed: " + split[1]); } if (Directory.Exists($"./Data/Plugins/{plugName}")) @@ -415,7 +417,7 @@ public class ConsoleCommandsHandler } isDownloading = false; - Console.WriteLine(plugName + " has been successfully deleted !"); + Settings.Variables.outputStream.WriteLine(plugName + " has been successfully deleted !"); }); AddCommand("reload", "Reload the bot with all plugins", () => @@ -443,7 +445,7 @@ public class ConsoleCommandsHandler commandList.Add(new ConsoleCommand { CommandName = command, Description = description, Action = action, Usage = usage }); Console.ForegroundColor = ConsoleColor.White; - Console_Utilities.WriteColorText($"Command &r{command} &cadded to the list of commands"); + Utilities.WriteColorText($"Command &r{command} &cadded to the list of commands"); } public static void AddCommand(string command, string description, Action action) @@ -469,13 +471,10 @@ public class ConsoleCommandsHandler public static async Task ExecuteCommad(string command) { var args = command.Split(' '); - // Console.WriteLine(command); foreach (var item in commandList.ToList()) if (item.CommandName == args[0]) { item.Action.Invoke(args); - Console.WriteLine(); - while (isDownloading) await Task.Delay(1000); } } @@ -491,17 +490,17 @@ public class ConsoleCommandsHandler { Console.SetCursorPosition(0, Console.CursorTop - 1); for (var i = 0; i < command.Length + 30; i++) - Console.Write(" "); + Settings.Variables.outputStream.Write(" "); Console.SetCursorPosition(0, Console.CursorTop); } - Console.WriteLine(); + Settings.Variables.outputStream.WriteLine(); item.Action(args); return true; } return false; - //Console.WriteLine($"Executing: {args[0]} with the following parameters: {args.MergeStrings(1)}"); + //Settings.Variables.outputStream.WriteLine($"Executing: {args[0]} with the following parameters: {args.MergeStrings(1)}"); } } \ No newline at end of file diff --git a/PluginManager/Loaders/PluginLoader.cs b/PluginManager/Loaders/PluginLoader.cs index 4d7defe..934788d 100644 --- a/PluginManager/Loaders/PluginLoader.cs +++ b/PluginManager/Loaders/PluginLoader.cs @@ -95,7 +95,7 @@ public class PluginLoader SlashCommands = new List(); Functions.WriteLogFile("Starting plugin loader ... Client: " + _client.CurrentUser.Username); - Console.WriteLine("Loading plugins"); + Settings.Variables.outputStream.WriteLine("Loading plugins"); var loader = new LoaderV2("./Data/Plugins", "dll"); loader.FileLoaded += (args) => Functions.WriteLogFile($"{args.PluginName} file Loaded"); @@ -108,7 +108,7 @@ public class PluginLoader private async void Loader_PluginLoaded(LoaderArgs args) { - // Console.WriteLine(args.TypeName); + // Settings.Variables.outputStream.WriteLine(args.TypeName); switch (args.TypeName) { case "DBCommand": @@ -124,10 +124,10 @@ public class PluginLoader } catch (Exception ex) { - Console.WriteLine(ex.ToString()); - Console.WriteLine("Plugin: " + args.PluginName); - Console.WriteLine("Type: " + args.TypeName); - Console.WriteLine("IsLoaded: " + args.IsLoaded); + Settings.Variables.outputStream.WriteLine(ex.ToString()); + Settings.Variables.outputStream.WriteLine("Plugin: " + args.PluginName); + Settings.Variables.outputStream.WriteLine("Type: " + args.TypeName); + Settings.Variables.outputStream.WriteLine("IsLoaded: " + args.IsLoaded); } break; case "DBSlashCommand": @@ -139,73 +139,13 @@ public class PluginLoader builder.WithDescription(slash.Description); builder.WithDMPermission(slash.canUseDM); builder.Options = slash.Options; - //Console.WriteLine("Loaded " + slash.Name); + //Settings.Variables.outputStream.WriteLine("Loaded " + slash.Name); onSLSHLoad?.Invoke(((DBSlashCommand)args.Plugin!).Name, args.TypeName, args.IsLoaded, args.Exception); await _client.CreateGlobalApplicationCommandAsync(builder.Build()); } - //else Console.WriteLine("Failed to load " + args.PluginName + "\nException: " + args.Exception.Message); break; } } - /* - private async void SlashLoader_PluginLoaded(LoaderArgs args) - { - if (args.IsLoaded) - { - var slash = (DBSlashCommand)args.Plugin; - SlashCommandBuilder builder = new SlashCommandBuilder(); - builder.WithName(slash.Name); - builder.WithDescription(slash.Description); - builder.WithDMPermission(slash.canUseDM); - builder.Options = slash.Options; - Console.WriteLine("Loaded " + slash.Name); - await _client.CreateGlobalApplicationCommandAsync(builder.Build()); - - - } - else Console.WriteLine("Failed to load " + args.PluginName + "\nException: " + args.Exception.Message); - } - - private void SlashLoader_FileLoaded(LoaderArgs args) - { - if (!args.IsLoaded) - Functions.WriteLogFile($"[SLASH] SlashCommand from file [{args.PluginName}] has been successfully created !"); - } - - private void EventFileLoaded(LoaderArgs e) - { - if (!e.IsLoaded) - Functions.WriteLogFile($"[EVENT] Event from file [{e.PluginName}] has been successfully created !"); - } - - private void OnCommandFileLoaded(LoaderArgs e) - { - if (!e.IsLoaded) - Functions.WriteLogFile($"[CMD] Command from file [{e.PluginName}] has been successfully loaded !"); - } - - private void OnEventLoaded(LoaderArgs e) - { - try - { - if (e.IsLoaded) - ((DBEvent)e.Plugin!).Start(_client); - - onEVELoad?.Invoke(((DBEvent)e.Plugin!).Name, e.TypeName!, e.IsLoaded, e.Exception); - } - catch (Exception ex) - { - Console.WriteLine(ex.ToString()); - Console.WriteLine("Plugin: " + e.PluginName); - Console.WriteLine("Type: " + e.TypeName); - Console.WriteLine("IsLoaded: " + e.IsLoaded); - } - } - - private void OnCommandLoaded(LoaderArgs e) - { - onCMDLoad?.Invoke(((DBCommand)e.Plugin!).Command, e.TypeName!, e.IsLoaded, e.Exception); - }*/ } \ No newline at end of file diff --git a/PluginManager/Online/PluginsManager.cs b/PluginManager/Online/PluginsManager.cs index 15f4c53..5e71644 100644 --- a/PluginManager/Online/PluginsManager.cs +++ b/PluginManager/Online/PluginsManager.cs @@ -80,11 +80,11 @@ public class PluginsManager data.Add(new[] { "-", "-", "-", "-" }); - Console_Utilities.FormatAndAlignTable(data, TableFormat.CENTER_EACH_COLUMN_BASED); + Utilities.FormatAndAlignTable(data, TableFormat.CENTER_EACH_COLUMN_BASED); } catch (Exception exception) { - Console.WriteLine("Failed to execute command: listplugs\nReason: " + exception.Message); + Settings.Variables.outputStream.WriteLine("Failed to execute command: listplugs\nReason: " + exception.Message); Functions.WriteErrFile(exception.ToString()); } } @@ -116,7 +116,7 @@ public class PluginsManager } catch (Exception exception) { - Console.WriteLine("Failed to execute command: listplugs\nReason: " + exception.Message); + Settings.Variables.outputStream.WriteLine("Failed to execute command: listplugs\nReason: " + exception.Message); Functions.WriteErrFile(exception.ToString()); } diff --git a/PluginManager/Online/ServerCom.cs b/PluginManager/Online/ServerCom.cs index adae25c..b6b0c59 100644 --- a/PluginManager/Online/ServerCom.cs +++ b/PluginManager/Online/ServerCom.cs @@ -57,7 +57,7 @@ public static class ServerCom var isDownloading = true; float c_progress = 0; - var pbar = new Console_Utilities.ProgressBar(ProgressBarType.NORMAL) { Max = 100f, NoColor = true }; + var pbar = new Utilities.ProgressBar(ProgressBarType.NORMAL) { Max = 100f, NoColor = true }; IProgress progress = new Progress(percent => { c_progress = percent; }); diff --git a/PluginManager/Online/Updates/PluginUpdater.cs b/PluginManager/Online/Updates/PluginUpdater.cs index c0d5afe..7f76cc6 100644 --- a/PluginManager/Online/Updates/PluginUpdater.cs +++ b/PluginManager/Online/Updates/PluginUpdater.cs @@ -42,7 +42,7 @@ public class PluginUpdater public static async Task Download(string pakName) { - Console_Utilities.WriteColorText("An update was found for &g" + pakName + "&c. Version: &r" + + Utilities.WriteColorText("An update was found for &g" + pakName + "&c. Version: &r" + (await ServerCom.GetVersionOfPackageFromWeb(pakName))?.ToShortString() + "&c. Current Version: &y" + ServerCom.GetVersionOfPackage(pakName)?.ToShortString()); diff --git a/PluginManager/Others/Console Utilities.cs b/PluginManager/Others/Console Utilities.cs index bc7bc36..e0149c0 100644 --- a/PluginManager/Others/Console Utilities.cs +++ b/PluginManager/Others/Console Utilities.cs @@ -4,7 +4,7 @@ using System.Threading.Tasks; namespace PluginManager.Others; -public static class Console_Utilities +public static class Utilities { private static Dictionary Colors = new() { @@ -46,38 +46,38 @@ public static class Console_Utilities foreach (var row in data) { if (row[0][0] == tableLine) - Console.Write(tableCross); + Settings.Variables.outputStream.Write(tableCross); else - Console.Write(tableWall); + Settings.Variables.outputStream.Write(tableWall); for (var l = 0; l < row.Length; l++) { if (row[l][0] == tableLine) { for (var i = 0; i < len[l] + 4; ++i) - Console.Write(tableLine); + Settings.Variables.outputStream.Write(tableLine); } else if (row[l].Length == len[l]) { - Console.Write(" "); - Console.Write(row[l]); - Console.Write(" "); + Settings.Variables.outputStream.Write(" "); + Settings.Variables.outputStream.Write(row[l]); + Settings.Variables.outputStream.Write(" "); } else { var lenHalf = row[l].Length / 2; for (var i = 0; i < (len[l] + 4) / 2 - lenHalf; ++i) - Console.Write(" "); - Console.Write(row[l]); + Settings.Variables.outputStream.Write(" "); + Settings.Variables.outputStream.Write(row[l]); for (var i = (len[l] + 4) / 2 + lenHalf + 1; i < len[l] + 4; ++i) - Console.Write(" "); + Settings.Variables.outputStream.Write(" "); if (row[l].Length % 2 == 0) - Console.Write(" "); + Settings.Variables.outputStream.Write(" "); } - Console.Write(row[l][0] == tableLine ? tableCross : tableWall); + Settings.Variables.outputStream.Write(row[l][0] == tableLine ? tableCross : tableWall); } - Console.WriteLine(); //end line + Settings.Variables.outputStream.WriteLine(); //end line } return; @@ -95,44 +95,44 @@ public static class Console_Utilities foreach (var row in data) { - Console.Write("\t"); + Settings.Variables.outputStream.Write("\t"); if (row[0] == "-") - Console.Write("+"); + Settings.Variables.outputStream.Write("+"); else - Console.Write("|"); + Settings.Variables.outputStream.Write("|"); foreach (var s in row) { if (s == "-") { for (var i = 0; i < maxLen + 4; ++i) - Console.Write("-"); + Settings.Variables.outputStream.Write("-"); } else if (s.Length == maxLen) { - Console.Write(" "); - Console.Write(s); - Console.Write(" "); + Settings.Variables.outputStream.Write(" "); + Settings.Variables.outputStream.Write(s); + Settings.Variables.outputStream.Write(" "); } else { var lenHalf = s.Length / 2; for (var i = 0; i < div - lenHalf; ++i) - Console.Write(" "); - Console.Write(s); + Settings.Variables.outputStream.Write(" "); + Settings.Variables.outputStream.Write(s); for (var i = div + lenHalf + 1; i < maxLen + 4; ++i) - Console.Write(" "); + Settings.Variables.outputStream.Write(" "); if (s.Length % 2 == 0) - Console.Write(" "); + Settings.Variables.outputStream.Write(" "); } if (s == "-") - Console.Write("+"); + Settings.Variables.outputStream.Write("+"); else - Console.Write("|"); + Settings.Variables.outputStream.Write("|"); } - Console.WriteLine(); //end line + Settings.Variables.outputStream.WriteLine(); //end line } return; @@ -153,12 +153,12 @@ public static class Console_Utilities { if (data[i][j] == "-") data[i][j] = " "; - Console.Write(data[i][j]); + Settings.Variables.outputStream.Write(data[i][j]); for (var k = 0; k < widths[j] - data[i][j].Length + 1 + space_between_columns; k++) - Console.Write(" "); + Settings.Variables.outputStream.Write(" "); } - Console.WriteLine(); + Settings.Variables.outputStream.WriteLine(); } return; @@ -169,6 +169,13 @@ public static class Console_Utilities public static void WriteColorText(string text, bool appendNewLineAtEnd = true) { + if (Console.Out != Settings.Variables.outputStream) + { + Settings.Variables.outputStream.Write(text); + if (appendNewLineAtEnd) + Settings.Variables.outputStream.WriteLine(); + return; + } var initialForeGround = Console.ForegroundColor; var input = text.ToCharArray(); for (var i = 0; i < input.Length; i++) @@ -190,12 +197,12 @@ public static class Console_Utilities } else { - Console.Write(input[i]); + Settings.Variables.outputStream.Write(input[i]); } Console.ForegroundColor = initialForeGround; if (appendNewLineAtEnd) - Console.WriteLine(); + Settings.Variables.outputStream.WriteLine(); } @@ -212,6 +219,8 @@ public static class Console_Utilities public ProgressBar(ProgressBarType type) { + if (Settings.Variables.outputStream != Console.Out) + throw new Exception("This class (or function) can be used with console only. For UI please use another approach."); this.type = type; } @@ -272,9 +281,9 @@ public static class Console_Utilities { Console.CursorLeft = 0; for (var i = 0; i < BarLength + message.Length + 1; i++) - Console.Write(" "); + Settings.Variables.outputStream.Write(" "); Console.CursorLeft = 0; - Console.WriteLine(message); + Settings.Variables.outputStream.WriteLine(message); } } @@ -289,14 +298,14 @@ public static class Console_Utilities private void UpdateNoEnd(string message) { Console.CursorLeft = 0; - Console.Write("["); + Settings.Variables.outputStream.Write("["); for (var i = 1; i <= position; i++) - Console.Write(" "); - Console.Write("<==()==>"); + Settings.Variables.outputStream.Write(" "); + Settings.Variables.outputStream.Write("<==()==>"); position += positive ? 1 : -1; for (var i = position; i <= BarLength - 1 - (positive ? 0 : 2); i++) - Console.Write(" "); - Console.Write("] " + message); + Settings.Variables.outputStream.Write(" "); + Settings.Variables.outputStream.Write("] " + message); if (position == BarLength - 1 || position == 1) @@ -306,14 +315,14 @@ public static class Console_Utilities private void UpdateNoEnd() { Console.CursorLeft = 0; - Console.Write("["); + Settings.Variables.outputStream.Write("["); for (var i = 1; i <= position; i++) - Console.Write(" "); - Console.Write("<==()==>"); + Settings.Variables.outputStream.Write(" "); + Settings.Variables.outputStream.Write("<==()==>"); position += positive ? 1 : -1; for (var i = position; i <= BarLength - 1 - (positive ? 0 : 2); i++) - Console.Write(" "); - Console.Write("]"); + Settings.Variables.outputStream.Write(" "); + Settings.Variables.outputStream.Write("]"); if (position == BarLength - 1 || position == 1) @@ -323,9 +332,9 @@ public static class Console_Utilities private void UpdateNormal(float progress) { Console.CursorLeft = 0; - Console.Write("["); + Settings.Variables.outputStream.Write("["); Console.CursorLeft = BarLength; - Console.Write("]"); + Settings.Variables.outputStream.Write("]"); Console.CursorLeft = 1; var onechunk = 30.0f / Max; @@ -335,22 +344,22 @@ public static class Console_Utilities { Console.BackgroundColor = NoColor ? ConsoleColor.Black : Color; Console.CursorLeft = position++; - Console.Write("#"); + Settings.Variables.outputStream.Write("#"); } for (var i = position; i < BarLength; i++) { Console.BackgroundColor = NoColor ? ConsoleColor.Black : ConsoleColor.DarkGray; Console.CursorLeft = position++; - Console.Write(" "); + Settings.Variables.outputStream.Write(" "); } Console.CursorLeft = BarLength + 4; Console.BackgroundColor = ConsoleColor.Black; if (progress.CanAproximateTo(Max)) - Console.Write(progress + " % ✓"); + Settings.Variables.outputStream.Write(progress + " % ✓"); else - Console.Write(MathF.Round(progress, 2) + " % "); + Settings.Variables.outputStream.Write(MathF.Round(progress, 2) + " % "); } } } \ No newline at end of file diff --git a/PluginManager/Others/Functions.cs b/PluginManager/Others/Functions.cs index 7be6825..4e2d89f 100644 --- a/PluginManager/Others/Functions.cs +++ b/PluginManager/Others/Functions.cs @@ -197,7 +197,7 @@ public static class Functions } catch (Exception ex) { - Console.WriteLine($"Failed to extract {entry.Name}. Exception: {ex.Message}"); + Settings.Variables.outputStream.WriteLine($"Failed to extract {entry.Name}. Exception: {ex.Message}"); } currentZIPFile++; @@ -229,7 +229,7 @@ public static class Functions } catch (Exception ex) { - Console.WriteLine($"Failed to extract {entry.Name}. Exception: {ex.Message}"); + Settings.Variables.outputStream.WriteLine($"Failed to extract {entry.Name}. Exception: {ex.Message}"); } await Task.Delay(10); diff --git a/PluginManager/PluginManager.csproj b/PluginManager/PluginManager.csproj index 24a6ac1..c0b07d0 100644 --- a/PluginManager/PluginManager.csproj +++ b/PluginManager/PluginManager.csproj @@ -1,4 +1,4 @@ - + net6.0 diff --git a/PluginManager/Variables.cs b/PluginManager/Variables.cs index b46e0cc..d830db0 100644 --- a/PluginManager/Variables.cs +++ b/PluginManager/Variables.cs @@ -1,5 +1,6 @@ -using PluginManager.Database; -using PluginManager.Others; +using System.IO; + +using PluginManager.Database; namespace PluginManager { @@ -11,6 +12,7 @@ namespace PluginManager public static string WebsiteURL = "https://wizzy69.github.io/SethDiscordBot"; public static string UpdaterURL = "https://github.com/Wizzy69/installer/releases/download/release-1-discordbot/Updater.zip"; + public static TextWriter outputStream; } public static SqlDatabase sqlDatabase; diff --git a/SethDiscordBot.sln b/SethDiscordBot.sln index ccf315f..bcf2c27 100644 --- a/SethDiscordBot.sln +++ b/SethDiscordBot.sln @@ -11,7 +11,7 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MusicLibrary", "..\DiscordB EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SlashCommands", "..\DiscordBotItems\Plugins\SlashCommands\SlashCommands.csproj", "{C2D73BE8-997B-4A4A-8EA5-989BE33EE1DD}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LevelingSystem", "..\DiscordBotItems\Plugins\LevelingSystem\LevelingSystem.csproj", "{0138F343-BBB9-4D5F-B499-D9C2978BE9AA}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "LevelingSystem", "..\DiscordBotItems\Plugins\LevelingSystem\LevelingSystem.csproj", "{0138F343-BBB9-4D5F-B499-D9C2978BE9AA}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution