Moved Console activity on another thread

This commit is contained in:
2022-07-17 18:53:56 +03:00
parent c415fa1c0c
commit 17f68a8e5e
10 changed files with 73 additions and 73 deletions

Binary file not shown.

View File

@@ -2,6 +2,7 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using DiscordBot.Discord.Core; using DiscordBot.Discord.Core;
using PluginManager; using PluginManager;
@@ -66,7 +67,7 @@ public class Program
/// The main loop for the discord bot /// The main loop for the discord bot
/// </summary> /// </summary>
/// <param name="discordbooter">The discord booter used to start the application</param> /// <param name="discordbooter">The discord booter used to start the application</param>
private static Task NoGUI(Boot discordbooter) private static void NoGUI(Boot discordbooter)
{ {
var consoleCommandsHandler = new ConsoleCommandsHandler(discordbooter.client); var consoleCommandsHandler = new ConsoleCommandsHandler(discordbooter.client);
if (loadPluginsOnStartup) consoleCommandsHandler.HandleCommand("lp"); if (loadPluginsOnStartup) consoleCommandsHandler.HandleCommand("lp");
@@ -77,9 +78,18 @@ public class Program
while (true) while (true)
{ {
Console.ForegroundColor = ConsoleColor.White; Console.ForegroundColor = ConsoleColor.White;
#if DEBUG
Console_Utilities.WriteColorText("&rSethBot (&yDEBUG&r) &c> ", false);
var cmd = Console.ReadLine(); var cmd = Console.ReadLine();
if (!consoleCommandsHandler.HandleCommand(cmd)) if (!consoleCommandsHandler.HandleCommand(cmd!, false) && cmd.Length > 0)
Console.WriteLine("Failed to run command " + cmd); Console.WriteLine("Failed to run command " + cmd);
#else
Console_Utilities.WriteColorText("&rSethBot &c> ", false);
var cmd = Console.ReadLine();
if (!consoleCommandsHandler.HandleCommand(cmd!) && cmd.Length > 0)
Console.WriteLine("Failed to run command " + cmd);
#endif
} }
} }
@@ -178,7 +188,8 @@ public class Program
if (len == 0 || (args[0] != "--exec" && args[0] != "--execute")) if (len == 0 || (args[0] != "--exec" && args[0] != "--execute"))
{ {
var b = await StartNoGUI(); var b = await StartNoGUI();
await NoGUI(b); Thread mainThread = new Thread(() => NoGUI(b));
mainThread.Start();
return; return;
} }
@@ -204,15 +215,7 @@ public class Program
case "--help": case "--help":
case "-help": case "-help":
Console.ForegroundColor = ConsoleColor.DarkYellow; Console.ForegroundColor = ConsoleColor.DarkYellow;
Console.WriteLine( Console.WriteLine("\tCommand name\t\t\t\tDescription\n" + "-- help | -help\t\t ------ \tDisplay the help message\n" + "--reset-full\t\t ------ \tReset all files (clear files)\n" + "--reset-settings\t ------ \tReset only bot settings\n" + "--reset-logs\t\t ------ \tClear up the output folder\n" + "--start\t\t ------ \tStart the bot\n" + "exit\t\t\t ------ \tClose the application");
"\tCommand name\t\t\t\tDescription\n" +
"-- help | -help\t\t ------ \tDisplay the help message\n" +
"--reset-full\t\t ------ \tReset all files (clear files)\n" +
"--reset-settings\t ------ \tReset only bot settings\n" +
"--reset-logs\t\t ------ \tClear up the output folder\n" +
"--start\t\t ------ \tStart the bot\n" +
"exit\t\t\t ------ \tClose the application"
);
break; break;
case "--reset-full": case "--reset-full":
await ClearFolder("./Data/Resources/"); await ClearFolder("./Data/Resources/");
@@ -232,10 +235,6 @@ public class Program
case "exit": case "exit":
Environment.Exit(0); Environment.Exit(0);
break; break;
case "--start":
var booter = await StartNoGUI();
await NoGUI(booter);
return;
default: default:
Console.WriteLine("Failed to execute command " + message[0]); Console.WriteLine("Failed to execute command " + message[0]);
@@ -321,6 +320,7 @@ public class Program
} }
} }
Console_Utilities.Initialize();
Config.SaveConfig(); Config.SaveConfig();
} }

View File

@@ -11,15 +11,18 @@ namespace EVE_LevelingSystem
{ {
public string name => "Leveling System Event Handler"; public string name => "Leveling System Event Handler";
public string description => "The Leveling System Event Handler"; public string description => "The Leveling System Event Handler";
internal static Settings globalSettings = new(); internal static Settings globalSettings = new();
public async void Start(DiscordSocketClient client) public async void Start(DiscordSocketClient client)
{ {
Directory.CreateDirectory("./Data/Resources/LevelingSystem"); Directory.CreateDirectory("./Data/Resources/LevelingSystem");
if (!Config.ContainsKey("LevelingSystemPath"))
Config.AddValueToVariables("LevelingSystemPath", "./Data/Resources/LevelingSystem", true); Config.AddValueToVariables("LevelingSystemPath", "./Data/Resources/LevelingSystem", true);
if (!Config.ContainsKey("LevelingSystemSettingsFile"))
Config.AddValueToVariables("LevelingSystemSettingsFile", "./Data/Resources/LevelingSystemSettings.txt", true); Config.AddValueToVariables("LevelingSystemSettingsFile", "./Data/Resources/LevelingSystemSettings.txt", true);
//PluginManager.Config.AddValueToVariables
if (!File.Exists(Config.GetValue<string>("LevelingSystemSettingsFile"))) if (!File.Exists(Config.GetValue<string>("LevelingSystemSettingsFile")))
{ {
globalSettings = new Settings { TimeToWaitBetweenMessages = 5 }; globalSettings = new Settings { TimeToWaitBetweenMessages = 5 };

View File

@@ -1,5 +1,6 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Threading.Tasks;
using Discord.WebSocket; using Discord.WebSocket;
using PluginManager.Others; using PluginManager.Others;

View File

@@ -97,7 +97,7 @@ public class ConsoleCommandsHandler
} }
); );
AddCommand("listplugs", "list available plugins", async () => { await manager.ListAvailablePlugins(); }); AddCommand("listplugs", "list available plugins", () => { manager.ListAvailablePlugins().Wait(); });
AddCommand("dwplug", "download plugin", "dwplug [name]", async args => AddCommand("dwplug", "download plugin", "dwplug [name]", async args =>
{ {
@@ -233,20 +233,6 @@ public class ConsoleCommandsHandler
} }
); );
AddCommand("vars", "Display all variables", () =>
{
var d = Config.GetAllVariables();
var data = new List<string[]>();
data.Add(new[] { "-", "-" });
data.Add(new[] { "Key", "Value" });
data.Add(new[] { "-", "-" });
foreach (var kvp in d)
data.Add(new[] { kvp.Key, kvp.Value.ToString()! });
data.Add(new[] { "-", "-" });
Console_Utilities.FormatAndAlignTable(data);
}
);
AddCommand("sd", "Shuts down the discord bot", async () => AddCommand("sd", "Shuts down the discord bot", async () =>
{ {
if (client is null) if (client is null)
@@ -299,7 +285,7 @@ public class ConsoleCommandsHandler
if (removeCommandExecution) if (removeCommandExecution)
{ {
Console.SetCursorPosition(0, Console.CursorTop - 1); Console.SetCursorPosition(0, Console.CursorTop - 1);
for (int i = 0; i < command.Length; i++) for (int i = 0; i < command.Length + 30; i++)
Console.Write(" "); Console.Write(" ");
Console.SetCursorPosition(0, Console.CursorTop); Console.SetCursorPosition(0, Console.CursorTop);
} }

View File

@@ -85,10 +85,21 @@ public class PluginLoader
private void OnEventLoaded(LoaderArgs e) private void OnEventLoaded(LoaderArgs e)
{ {
if (e.IsLoaded) ((DBEvent)e.Plugin!).Start(_client); try
{
if (e.IsLoaded)
((DBEvent)e.Plugin!).Start(_client);
onEVELoad?.Invoke(((DBEvent)e.Plugin!).name, e.TypeName!, e.IsLoaded, e.Exception); 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) private void OnCommandLoaded(LoaderArgs e)
{ {

View File

@@ -7,6 +7,26 @@ namespace PluginManager.Others
{ {
public static class Console_Utilities public static class Console_Utilities
{ {
public static void Initialize()
{
if (!Config.ContainsKey("TableVariables"))
Config.AddValueToVariables("TableVariables", new Dictionary<string, string> { { "DefaultSpace", "3" } }, false);
if (!Config.ContainsKey("ColorDataBase"))
Config.AddValueToVariables("ColorDataBase", new Dictionary<char, ConsoleColor>()
{
{ 'g', ConsoleColor.Green },
{ 'b', ConsoleColor.Blue },
{ 'r', ConsoleColor.Red },
{ 'm', ConsoleColor.Magenta },
{ 'y', ConsoleColor.Yellow },
}, false
);
if (!Config.ContainsKey("ColorPrefix"))
Config.AddValueToVariables("ColorPrefix", '&', false);
}
/// <summary> /// <summary>
/// Progress bar object /// Progress bar object
/// </summary> /// </summary>
@@ -177,7 +197,7 @@ namespace PluginManager.Others
if (format == TableFormat.DEFAULT) if (format == TableFormat.DEFAULT)
{ {
int[] widths = new int[data[0].Length]; int[] widths = new int[data[0].Length];
int space_between_columns = 5; int space_between_columns = int.Parse(Config.GetValue<Dictionary<string, string>>("TableVariables")?["DefaultSpace"]!);
for (int i = 0; i < data.Count; i++) for (int i = 0; i < data.Count; i++)
{ {
for (int j = 0; j < data[i].Length; j++) for (int j = 0; j < data[i].Length; j++)
@@ -210,26 +230,21 @@ namespace PluginManager.Others
public static void WriteColorText(string text, bool appendNewLineAtEnd = true) public static void WriteColorText(string text, bool appendNewLineAtEnd = true)
{ {
ConsoleColor initialForeGround = Console.ForegroundColor; ConsoleColor initialForeGround = Console.ForegroundColor;
Dictionary<char, ConsoleColor> colors = new()
{
{ 'g', ConsoleColor.Green },
{ 'b', ConsoleColor.Blue },
{ 'r', ConsoleColor.Red },
{ 'm', ConsoleColor.Magenta },
{ 'y', ConsoleColor.Yellow },
{ 'c', initialForeGround }
};
char[] input = text.ToCharArray(); char[] input = text.ToCharArray();
for (int i = 0; i < input.Length; i++) for (int i = 0; i < input.Length; i++)
{ {
if (input[i] == '&') if (input[i] == Config.GetValue<char>("ColorPrefix"))
{ {
if (i + 1 < input.Length) if (i + 1 < input.Length)
{ {
if (colors.ContainsKey(input[i + 1])) if (Config.GetValue<Dictionary<char, ConsoleColor>>("ColorDataBase")!.ContainsKey(input[i + 1]))
{ {
Console.ForegroundColor = colors[input[i + 1]]; Console.ForegroundColor = Config.GetValue<Dictionary<char, ConsoleColor>>("ColorDataBase")![input[i + 1]];
i++;
}
else if (input[i + 1] == 'c')
{
Console.ForegroundColor = initialForeGround;
i++; i++;
} }
} }

View File

@@ -50,31 +50,15 @@ namespace PluginManager.Others
/// <param name="FileName">The file name that is inside the archive or its full path</param> /// <param name="FileName">The file name that is inside the archive or its full path</param>
/// <param name="archFile">The archive location from the PAKs folder</param> /// <param name="archFile">The archive location from the PAKs folder</param>
/// <returns>A string that represents the content of the file or null if the file does not exists or it has no content</returns> /// <returns>A string that represents the content of the file or null if the file does not exists or it has no content</returns>
public static async Task<Stream?> ReadFromPakAsync(string FileName, string archFile) public static Stream? ReadFromPakAsync(string FileName, string archFile)
{ {
archFile = pakFolder + archFile; archFile = pakFolder + archFile;
Directory.CreateDirectory(pakFolder); Directory.CreateDirectory(pakFolder);
if (!File.Exists(archFile)) throw new FileNotFoundException("Failed to load file !"); if (!File.Exists(archFile)) throw new FileNotFoundException("Failed to load file !");
Stream? textValue = null; using ZipArchive archive = ZipFile.OpenRead(archFile);
var fs = new FileStream(archFile, FileMode.Open); ZipArchiveEntry? entry = archive.GetEntry(FileName);
var zip = new ZipArchive(fs, ZipArchiveMode.Read); return entry?.Open();
foreach (var entry in zip.Entries)
{
if (entry.Name == FileName || entry.FullName == FileName)
{
Stream s = entry.Open();
StreamReader reader = new StreamReader(s);
textValue = reader.BaseStream;
textValue.Position = 0;
reader.Close();
s.Close();
fs.Close();
break;
}
}
return textValue;
} }
/// <summary> /// <summary>