Formatted code and rebuilt PluginLoader

This commit is contained in:
2024-02-27 11:07:27 +02:00
parent 14f280baef
commit ef7a2c0896
40 changed files with 525 additions and 524 deletions

View File

@@ -17,7 +17,7 @@ public class Exit: ICommandAction
{
if (args is null || args.Length == 0)
{
Config.Logger.Log("Exiting...", source: typeof(ICommandAction), type: LogType.WARNING);
Config.Logger.Log("Exiting...", typeof(ICommandAction), LogType.WARNING);
await Config.AppSettings.SaveToFile();
Environment.Exit(0);
}
@@ -33,7 +33,7 @@ public class Exit: ICommandAction
case "-f":
case "force":
Config.Logger.Log("Exiting (FORCE)...", source: typeof(ICommandAction), type: LogType.WARNING);
Config.Logger.Log("Exiting (FORCE)...", typeof(ICommandAction), LogType.WARNING);
Environment.Exit(0);
break;

View File

@@ -21,7 +21,14 @@ internal static class PluginMethods
{
var data = await ConsoleUtilities.ExecuteWithProgressBar(manager.GetPluginsList(), "Loading plugins...");
TableData tableData = new(new List<string> { "Name", "Description", "Version", "Has Dependencies" });
TableData tableData = new(new List<string>
{
"Name",
"Description",
"Version",
"Has Dependencies"
}
);
foreach (var plugin in data) tableData.AddRow([plugin.Name, plugin.Description, plugin.Version.ToString(), plugin.HasDependencies ? "Yes" : "No"]);
tableData.HasRoundBorders = false;
@@ -42,16 +49,14 @@ internal static class PluginMethods
Console.WriteLine($"Plugin {pluginName} not found. Please check the spelling and try again.");
return;
}
var pluginLink = pluginData.DownLoadLink;
await AnsiConsole.Progress()
.Columns(new ProgressColumn[]
{
new TaskDescriptionColumn(),
new ProgressBarColumn(),
new PercentageColumn()
new TaskDescriptionColumn(), new ProgressBarColumn(), new PercentageColumn()
}
)
.StartAsync(async ctx =>
@@ -74,21 +79,19 @@ internal static class PluginMethods
await RefreshPlugins(false);
return;
}
List<Tuple<ProgressTask, IProgress<float>, string, string>> downloadTasks = new();
await AnsiConsole.Progress()
.Columns(new ProgressColumn[]
{
new TaskDescriptionColumn(),
new ProgressBarColumn(),
new PercentageColumn()
new TaskDescriptionColumn(), new ProgressBarColumn(), new PercentageColumn()
}
)
.StartAsync(async ctx =>
{
foreach (OnlineDependencyInfo dependency in pluginData.Dependencies)
foreach (var dependency in pluginData.Dependencies)
{
var task = ctx.AddTask($"Downloading {dependency.DownloadLocation}: ");
IProgress<float> progress = new Progress<float>(p =>
@@ -101,7 +104,7 @@ internal static class PluginMethods
downloadTasks.Add(new Tuple<ProgressTask, IProgress<float>, string, string>(task, progress, dependency.DownloadLink, dependency.DownloadLocation));
}
if (!int.TryParse(Config.AppSettings["MaxParallelDownloads"], out int maxParallelDownloads))
if (!int.TryParse(Config.AppSettings["MaxParallelDownloads"], out var maxParallelDownloads))
{
maxParallelDownloads = 5;
Config.AppSettings.Add("MaxParallelDownloads", "5");
@@ -126,7 +129,7 @@ internal static class PluginMethods
}
);
await RefreshPlugins(false);
}
@@ -135,74 +138,66 @@ internal static class PluginMethods
var loader = new PluginLoader(Config.DiscordBot.client);
if (args.Length == 2 && args[1] == "-q")
{
loader.LoadPlugins();
await loader.LoadPlugins();
return true;
}
var cc = Console.ForegroundColor;
loader.onCMDLoad += (name, typeName, success, exception) =>
loader.OnCommandLoaded += (data) =>
{
if (name == null || name.Length < 2)
name = typeName;
if (success)
if (data.IsSuccess)
{
Config.Logger.Log("Successfully loaded command : " + name, source: typeof(ICommandAction),
type: LogType.INFO
Config.Logger.Log("Successfully loaded command : " + data.PluginName, typeof(ICommandAction),
LogType.INFO
);
}
else
{
Config.Logger.Log("Failed to load command : " + name + " because " + exception?.Message,
source: typeof(ICommandAction), type: LogType.ERROR
Config.Logger.Log("Failed to load command : " + data.PluginName + " because " + data.ErrorMessage,
typeof(ICommandAction), LogType.ERROR
);
}
Console.ForegroundColor = cc;
};
loader.onEVELoad += (name, typeName, success, exception) =>
loader.OnEventLoaded += (data) =>
{
if (name == null || name.Length < 2)
name = typeName;
if (success)
if (data.IsSuccess)
{
Config.Logger.Log("Successfully loaded event : " + name, source: typeof(ICommandAction),
type: LogType.INFO
Config.Logger.Log("Successfully loaded event : " + data.PluginName, typeof(ICommandAction),
LogType.INFO
);
}
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 : " + data.PluginName + " because " + data.ErrorMessage,
typeof(ICommandAction), LogType.ERROR
);
}
Console.ForegroundColor = cc;
};
loader.onSLSHLoad += (name, typeName, success, exception) =>
loader.OnSlashCommandLoaded += (data) =>
{
if (name == null || name.Length < 2)
name = typeName;
if (success)
if (data.IsSuccess)
{
Config.Logger.Log("Successfully loaded slash command : " + name, source: typeof(ICommandAction),
type: LogType.INFO
Config.Logger.Log("Successfully loaded slash command : " + data.PluginName, typeof(ICommandAction),
LogType.INFO
);
}
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 : " + data.PluginName + " because " + data.ErrorMessage,
typeof(ICommandAction), LogType.ERROR
);
}
Console.ForegroundColor = cc;
};
loader.LoadPlugins();
await loader.LoadPlugins();
Console.ForegroundColor = cc;
return true;
}

View File

@@ -23,15 +23,32 @@ public class Help: ICommandAction
{
var items = new List<string[]>
{
new[] { "-", "-", "-" },
new[] { "Command", "Usage", "Description" },
new[] { "-", "-", "-" }
new[]
{
"-", "-", "-"
},
new[]
{
"Command", "Usage", "Description"
},
new[]
{
"-", "-", "-"
}
};
foreach (var a in Program.internalActionManager.Actions)
items.Add(new[] { a.Key, a.Value.Usage, a.Value.Description });
items.Add(new[]
{
a.Key, a.Value.Usage, a.Value.Description
}
);
items.Add(new[] { "-", "-", "-" });
items.Add(new[]
{
"-", "-", "-"
}
);
ConsoleUtilities.FormatAndAlignTable(items,
TableFormat.CENTER_EACH_COLUMN_BASED
@@ -48,11 +65,26 @@ public class Help: ICommandAction
var action = Program.internalActionManager.Actions[args[0]];
var actionData = new List<string[]>
{
new[] { "-", "-", "-" },
new[] { "Command", "Usage", "Description" },
new[] { "-", "-", "-" },
new[] { action.ActionName, action.Usage, action.Description },
new[] { "-", "-", "-" }
new[]
{
"-", "-", "-"
},
new[]
{
"Command", "Usage", "Description"
},
new[]
{
"-", "-", "-"
},
new[]
{
action.ActionName, action.Usage, action.Description
},
new[]
{
"-", "-", "-"
}
};
ConsoleUtilities.FormatAndAlignTable(actionData,

View File

@@ -34,7 +34,7 @@ public class Plugin: ICommandAction
return;
}
PluginsManager manager =
var manager =
#if !DEBUG
new PluginsManager("releases");
#else
@@ -54,13 +54,13 @@ public class Plugin: ICommandAction
case "load":
if (pluginsLoaded)
{
Config.Logger.Log("Plugins already loaded", source: typeof(ICommandAction), type: LogType.WARNING);
Config.Logger.Log("Plugins already loaded", typeof(ICommandAction), LogType.WARNING);
break;
}
if (Config.DiscordBot is null)
{
Config.Logger.Log("DiscordBot is null", source: typeof(ICommandAction), type: LogType.WARNING);
Config.Logger.Log("DiscordBot is null", typeof(ICommandAction), LogType.WARNING);
break;
}

View File

@@ -40,15 +40,15 @@ public class Help: DBSlashCommand
if (options.Count > 0)
{
var commandName = options.First().Name;
var slashCommand = slashCommands.FirstOrDefault(x => x.Name == commandName);
var commandName = options.First().Value;
var slashCommand = slashCommands.FirstOrDefault(x => x.Name.TrimEnd() == commandName.ToString());
if (slashCommand is null)
{
await context.RespondAsync("Unknown Command " + commandName);
return;
}
embedBuilder.AddField(slashCommand.Name, slashCommand.canUseDM)
embedBuilder.AddField("DM Usable:", slashCommand.canUseDM, true)
.WithDescription(slashCommand.Description);
}

View File

@@ -1,7 +1,6 @@
using System;
using PluginManager;
using Spectre.Console;
using System.Threading.Tasks;
namespace DiscordBot;
@@ -10,10 +9,10 @@ public static class Installer
{
public static async Task GenerateStartupConfig()
{
string token = await PluginManager.UX.UxHandler.ShowInputBox("SethBot", "Please enter the bot token:");
string botPrefix = await PluginManager.UX.UxHandler.ShowInputBox("SethBot", "Please enter the bot prefix:");
string serverId = await PluginManager.UX.UxHandler.ShowInputBox("SethBot", "Please enter the Server ID:");
var token = await PluginManager.UX.UxHandler.ShowInputBox("SethBot", "Please enter the bot token:");
var botPrefix = await PluginManager.UX.UxHandler.ShowInputBox("SethBot", "Please enter the bot prefix:");
var serverId = await PluginManager.UX.UxHandler.ShowInputBox("SethBot", "Please enter the Server ID:");
if (string.IsNullOrWhiteSpace(serverId)) serverId = "NULL";
if (string.IsNullOrWhiteSpace(token) || string.IsNullOrWhiteSpace(botPrefix))
@@ -21,13 +20,13 @@ public static class Installer
await PluginManager.UX.UxHandler.ShowMessageBox("SethBot", "Invalid token or prefix !", PluginManager.UX.MessageBoxType.Error);
Environment.Exit(-20);
}
Config.AppSettings.Add("token", token);
Config.AppSettings.Add("prefix", botPrefix);
Config.AppSettings.Add("ServerID", serverId);
await Config.AppSettings.SaveToFile();
Config.Logger.Log("Config Saved", source: typeof(Installer));
Config.Logger.Log("Config Saved", typeof(Installer));
}
}

View File

@@ -69,7 +69,7 @@ public class Program
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{(System.OperatingSystem.IsWindows() ? "Windows" : "Linux")}");
ConsoleUtilities.WriteColorText($"Running on &m{(OperatingSystem.IsWindows() ? "Windows" : "Linux")}");
Console.WriteLine("============================ LOG ============================");
Console.ForegroundColor = ConsoleColor.White;
@@ -82,7 +82,7 @@ public class Program
}
catch (Exception ex)
{
Logger.Log(ex.ToString(), source: typeof(Program), type: LogType.CRITICAL);
Logger.Log(ex.ToString(), typeof(Program), LogType.CRITICAL);
}
}
@@ -102,12 +102,13 @@ public class Program
if (ex.Message == "No process is on the other end of the pipe." || (uint)ex.HResult == 0x800700E9)
{
UxHandler.ShowMessageBox("SethBot", "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 !", MessageBoxType.Error).Wait();
"There is a risk of losing all data or corruption of the save file, which in some cases requires to reinstall the bot !", MessageBoxType.Error
).Wait();
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 !",
source: typeof(Program), type: LogType.ERROR
typeof(Program), LogType.ERROR
);
}
}
@@ -119,7 +120,7 @@ public class Program
Logger.OnLog += (sender, logMessage) =>
{
string messageColor = logMessage.Type switch
var messageColor = logMessage.Type switch
{
LogType.INFO => "[green]",
LogType.WARNING => "[yellow]",

View File

@@ -43,9 +43,7 @@ public static class ConsoleUtilities
.Columns(
new ProgressColumn[]
{
new TaskDescriptionColumn(),
new ProgressBarColumn(),
new PercentageColumn(),
new TaskDescriptionColumn(), new ProgressBarColumn(), new PercentageColumn()
}
)
.StartAsync(
@@ -67,9 +65,7 @@ public static class ConsoleUtilities
await AnsiConsole.Progress()
.Columns(new ProgressColumn[]
{
new TaskDescriptionColumn(),
new ProgressBarColumn(),
new PercentageColumn(),
new TaskDescriptionColumn(), new ProgressBarColumn(), new PercentageColumn()
}
)
.StartAsync(async ctx =>
@@ -85,11 +81,21 @@ public static class ConsoleUtilities
private static readonly Dictionary<char, ConsoleColor> Colors = new()
{
{ 'g', ConsoleColor.Green },
{ 'b', ConsoleColor.Blue },
{ 'r', ConsoleColor.Red },
{ 'm', ConsoleColor.Magenta },
{ 'y', ConsoleColor.Yellow }
{
'g', ConsoleColor.Green
},
{
'b', ConsoleColor.Blue
},
{
'r', ConsoleColor.Red
},
{
'm', ConsoleColor.Magenta
},
{
'y', ConsoleColor.Yellow
}
};
private static readonly char ColorPrefix = '&';
@@ -310,7 +316,10 @@ public static class ConsoleUtilities
public Spinner()
{
Sequence = new[] { "|", "/", "-", "\\" };
Sequence = new[]
{
"|", "/", "-", "\\"
};
position = 0;
}