diff --git a/BrackeysBot/BrackeysBotApp.cs b/BrackeysBot/BrackeysBotApp.cs index 93c4f7b..ce51c5e 100644 --- a/BrackeysBot/BrackeysBotApp.cs +++ b/BrackeysBot/BrackeysBotApp.cs @@ -1,4 +1,7 @@ -using System.Reflection; +using System; +using System.Collections.Generic; +using System.IO; +using System.Reflection; using System.Threading; using System.Threading.Tasks; using BrackeysBot.API; @@ -14,6 +17,8 @@ namespace BrackeysBot; /// internal sealed class BrackeysBotApp : BackgroundService, IBot { + private readonly List _libraries = new(); + /// /// Initializes a new instance of the class. /// @@ -23,6 +28,12 @@ public BrackeysBotApp() Version = assembly.GetName().Version!.ToString(3); } + /// + /// Gets the libraries directory for this bot. + /// + /// The libraries directory. + public DirectoryInfo LibrariesDirectory { get; } = new("libraries"); + /// public ILogger Logger { get; } = LogManager.GetLogger("BrackeysBot"); @@ -50,17 +61,52 @@ public void EnablePlugins() PluginManager.EnablePlugin(plugin); } + /// + /// Loads third party dependencies as found . + /// + public void LoadLibraries() + { + foreach (FileInfo file in LibrariesDirectory.EnumerateFiles("*.dll")) + { + try + { + Assembly assembly = Assembly.LoadFrom(file.FullName); + if (!_libraries.Contains(assembly)) + _libraries.Add(assembly); + Logger.Debug($"Loaded {assembly.GetName()}"); + } + catch (Exception exception) + { + Logger.Warn(exception, $"Could not load library '{file.Name}' - SOME PLUGINS MAY NOT WORK"); + } + } + } + /// protected override Task ExecuteAsync(CancellationToken stoppingToken) { Logger.Info($"Starting Brackeys Bot version {Version}"); + LoadLibraries(); + int libraryCount = _libraries.Count; + Logger.Info($"Loaded {libraryCount} {(libraryCount == 1 ? "library" : "libraries")}"); + PluginManager.LoadPlugins(); - Logger.Info($"Loaded {PluginManager.LoadedPlugins.Count} plugins"); + int loadedPluginCount = PluginManager.LoadedPlugins.Count; + Logger.Info($"Loaded {loadedPluginCount} {(loadedPluginCount == 1 ? "plugin" : "plugins")}"); EnablePlugins(); - Logger.Info($"Enabled {PluginManager.EnabledPlugins.Count} plugins"); + int enabledPluginCount = PluginManager.EnabledPlugins.Count; + Logger.Info($"Enabled {enabledPluginCount} {(enabledPluginCount == 1 ? "plugin" : "plugins")}"); return Task.CompletedTask; } + + public override Task StopAsync(CancellationToken cancellationToken) + { + DisablePlugins(); + foreach (Plugin plugin in PluginManager.LoadedPlugins) PluginManager.UnloadPlugin(plugin); + + return base.StopAsync(cancellationToken); + } }