This commit is contained in:
2022-10-23 20:11:27 +03:00
parent cbaf552e7a
commit 47f88f167f
10 changed files with 337 additions and 241 deletions

View File

@@ -1,8 +1,10 @@
using System;
using System.Threading.Tasks;
using Discord;
using Discord.Commands;
using Discord.WebSocket;
using static PluginManager.Others.Functions;
namespace DiscordBot.Discord.Core;
@@ -66,11 +68,14 @@ internal class Boot
CommonTasks();
await client.LoginAsync(TokenType.Bot, botToken);
await client.StartAsync();
commandServiceHandler = new CommandHandler(client, service, botPrefix);
await commandServiceHandler.InstallCommandsAsync();
await Task.Delay(2000);
while (!isReady) ;
}
@@ -84,19 +89,22 @@ internal class Boot
client.Ready += Ready;
}
private Task Client_LoggedOut()
private async Task Client_LoggedOut()
{
WriteLogFile("Successfully Logged Out");
Log(new LogMessage(LogSeverity.Info, "Boot", "Successfully logged out from discord !"));
return Task.CompletedTask;
await Log(new LogMessage(LogSeverity.Info, "Boot", "Successfully logged out from discord !"));
/* var cmds = await client.GetGlobalApplicationCommandsAsync();
foreach (var cmd in cmds)
await cmd.DeleteAsync();*/
}
private Task Ready()
private async Task Ready()
{
Console.Title = "ONLINE";
isReady = true;
return Task.CompletedTask;
isReady = true;
}
private Task LoggedIn()

View File

@@ -306,8 +306,7 @@ public class Program
var main = new Console_Utilities.ProgressBar(ProgressBarType.NO_END);
main.Start();
Directory.CreateDirectory("./Data/Resources");
Directory.CreateDirectory("./Data/Plugins/Commands");
Directory.CreateDirectory("./Data/Plugins/Events");
Directory.CreateDirectory("./Data/Plugins");
Directory.CreateDirectory("./Data/PAKS");
await Config.LoadConfig();
if (Config.ContainsKey("DeleteLogsAtStartup"))
@@ -318,8 +317,6 @@ public class Program
await ServerCom.ReadTextFromURL(
"https://raw.githubusercontent.com/Wizzy69/installer/discord-bot-files/SetupKeys");
Config.PluginConfig.Load();
if (!Config.ContainsKey("Version"))
Config.AddValueToVariables("Version", Assembly.GetExecutingAssembly().GetName().Version.ToString(), false);
else

View File

@@ -2,10 +2,8 @@
using System.Collections.Generic;
using System.IO;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using PluginManager.Loaders;
using PluginManager.Others;
namespace PluginManager;
@@ -246,64 +244,4 @@ public static class Config
{
return appConfig?.ApplicationVariables;
}
public static class PluginConfig
{
public static readonly List<Tuple<string, PluginType>> InstalledPlugins = new();
public static void Load()
{
new Thread(LoadCommands).Start();
new Thread(LoadEvents).Start();
}
private static void LoadCommands()
{
var cmd_path = "./Data/Plugins/Commands/";
var files = Directory.GetFiles(cmd_path, $"*.{PluginLoader.pluginCMDExtension}",
SearchOption.AllDirectories);
foreach (var file in files)
if (!file.Contains("PluginManager", StringComparison.InvariantCultureIgnoreCase))
{
var PluginName = new FileInfo(file).Name;
var name = PluginName.Substring(0, PluginName.Length - 1 - PluginLoader.pluginCMDExtension.Length);
InstalledPlugins.Add(new Tuple<string, PluginType>(name, PluginType.Command));
}
}
private static void LoadEvents()
{
var eve_path = "./Data/Plugins/Events/";
var files = Directory.GetFiles(eve_path, $"*.{PluginLoader.pluginEVEExtension}",
SearchOption.AllDirectories);
foreach (var file in files)
if (!file.Contains("PluginManager", StringComparison.InvariantCultureIgnoreCase))
if (!file.Contains("PluginManager", StringComparison.InvariantCultureIgnoreCase))
{
var PluginName = new FileInfo(file).Name;
var name = PluginName.Substring(
0, PluginName.Length - 1 - PluginLoader.pluginEVEExtension.Length);
InstalledPlugins.Add(new Tuple<string, PluginType>(name, PluginType.Event));
}
}
public static bool Contains(string pluginName)
{
foreach (var tuple in InstalledPlugins)
if (tuple.Item1 == pluginName)
return true;
return false;
}
public static PluginType GetPluginType(string pluginName)
{
foreach (var tuple in InstalledPlugins)
if (tuple.Item1 == pluginName)
return tuple.Item2;
return PluginType.Unknown;
}
}
}

View File

@@ -125,6 +125,25 @@ public class ConsoleCommandsHandler
Console.ForegroundColor = cc;
};
loader.onSLSHLoad += (name, typeName, success, exception) =>
{
if (name == null || name.Length < 2)
name = typeName;
if (success)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("[SLASH] Successfully loaded command : " + name);
}
else
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("[SLASH] Failed to load command : " + name + " because " + exception!.Message);
}
Console.ForegroundColor = cc;
};
loader.LoadPlugins();
Console.ForegroundColor = cc;
pluginsLoaded = true;
@@ -164,12 +183,11 @@ public class ConsoleCommandsHandler
}
string path;
if (info[0] == "Command" || info[0] == "Event")
path = "./Data/Plugins/" + info[0] + "s/" + name + "." + (info[0] == "Command"
? PluginLoader.pluginCMDExtension
: PluginLoader.pluginEVEExtension);
if (info[0] == "Plugin")
path = "./Data/Plugins/" + name + ".dll";
else
path = $"./{info[1].Split('/')[info[1].Split('/').Length - 1]}";
if (OperatingSystem.WINDOWS == Functions.GetOperatingSystem())
{
await ServerCom.DownloadFileAsync(info[1], path);
@@ -182,11 +200,6 @@ public class ConsoleCommandsHandler
bar.Stop("Plugin Downloaded !");
}
if (info[0] == "Event")
Config.PluginConfig.InstalledPlugins.Add(new Tuple<string, PluginType>(name, PluginType.Event));
else if (info[0] == "Command")
Config.PluginConfig.InstalledPlugins.Add(new Tuple<string, PluginType>(name, PluginType.Command));
Console.WriteLine("\n");
@@ -226,7 +239,7 @@ public class ConsoleCommandsHandler
{
Console.WriteLine($"Extracting {split[1]} ...");
var bar = new Console_Utilities.ProgressBar(
ProgressBarType.NO_END); // { Max = 100f, Color = ConsoleColor.Green };
ProgressBarType.NO_END);
bar.Start();
await Functions.ExtractArchive("./" + split[1], "./", null,
UnzipProgressType.PercentageFromTotalSize);
@@ -368,16 +381,7 @@ public class ConsoleCommandsHandler
}
var location = "./Data/Plugins/";
location = Config.PluginConfig.GetPluginType(plugName) switch
{
PluginType.Command => location + "Commands/" + plugName + "." +
PluginLoader.pluginCMDExtension,
PluginType.Event => location + "Events/" + plugName + "." + PluginLoader.pluginEVEExtension,
PluginType.Unknown => "./",
_ => throw new NotImplementedException("Plugin type incorrect")
};
var location = $"./Data/Plugins/{plugName}.dll";
if (!File.Exists(location))
{
@@ -386,14 +390,6 @@ public class ConsoleCommandsHandler
}
File.Delete(location);
if (Config.PluginConfig.Contains(plugName))
{
var tuple = Config.PluginConfig.InstalledPlugins.Where(t => t.Item1 == plugName).FirstOrDefault();
Console.WriteLine("Found: " + tuple);
Config.PluginConfig.InstalledPlugins.Remove(tuple);
Config.RemovePluginVersion(plugName);
await Config.SaveConfig(SaveType.NORMAL);
}
Console.WriteLine("Removed the plugin DLL. Checking for other files ...");
@@ -413,6 +409,8 @@ public class ConsoleCommandsHandler
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);

View File

@@ -3,6 +3,7 @@ using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using PluginManager.Others;
namespace PluginManager.Loaders;
@@ -92,7 +93,10 @@ internal class Loader<T>
if (PluginLoaded != null)
PluginLoaded.Invoke(new LoaderArgs
{
Exception = ex, IsLoaded = false, PluginName = type.FullName, TypeName = nameof(T)
Exception = ex,
IsLoaded = false,
PluginName = type.FullName,
TypeName = nameof(T)
});
}
}

View File

@@ -0,0 +1,127 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using PluginManager.Interfaces;
using PluginManager.Others;
namespace PluginManager.Loaders
{
internal class LoaderV2
{
internal LoaderV2(string path, string extension)
{
this.path = path;
this.extension = extension;
}
private string path { get; }
private string extension { get; }
internal event FileLoadedEventHandler? FileLoaded;
internal event PluginLoadedEventHandler? PluginLoaded;
internal delegate void FileLoadedEventHandler(LoaderArgs args);
internal delegate void PluginLoadedEventHandler(LoaderArgs args);
internal (List<DBEvent>?, List<DBCommand>?, List<DBSlashCommand>?) Load()
{
List<DBEvent> events = new();
List<DBSlashCommand> slashCommands = new();
List<DBCommand> commands = new();
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
return (null, null, null);
}
var files = Directory.GetFiles(path, $"*.{extension}", SearchOption.AllDirectories);
foreach (var file in files)
{
Assembly.LoadFrom(file);
if (FileLoaded != null)
{
var args = new LoaderArgs
{
Exception = null,
TypeName = null,
IsLoaded = false,
PluginName = new FileInfo(file).Name.Split('.')[0],
Plugin = null
};
FileLoaded.Invoke(args);
}
}
return (LoadItems<DBEvent>(), LoadItems<DBCommand>(), LoadItems<DBSlashCommand>());
}
internal List<T> LoadItems<T>()
{
List<T> list = new();
try
{
var interfaceType = typeof(T);
var types = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(a => a.GetTypes())
.Where(p => interfaceType.IsAssignableFrom(p) && p.IsClass)
.ToArray();
list.Clear();
foreach (var type in types)
try
{
var plugin = (T)Activator.CreateInstance(type)!;
list.Add(plugin);
if (PluginLoaded != null)
PluginLoaded.Invoke(new LoaderArgs
{
Exception = null,
IsLoaded = true,
PluginName = type.FullName,
TypeName = typeof(T) == typeof(DBCommand) ? "DBCommand" : typeof(T) == typeof(DBEvent) ? "DBEvent" : "DBSlashCommand",
Plugin = plugin
}
);
}
catch (Exception ex)
{
if (PluginLoaded != null)
PluginLoaded.Invoke(new LoaderArgs
{
Exception = ex,
IsLoaded = false,
PluginName = type.FullName,
TypeName = nameof(T)
});
}
return list;
}
catch (Exception ex)
{
Functions.WriteErrFile(ex.ToString());
return null;
}
return null;
}
}
}

View File

@@ -19,11 +19,11 @@ public class PluginLoader
public delegate void EVELoaded(string name, string typeName, bool success, Exception? e = null);
private const string pluginCMDFolder = @"./Data/Plugins/Commands/";
private const string pluginEVEFolder = @"./Data/Plugins/Events/";
public delegate void SLSHLoaded(string name, string tyypename, bool success, Exception? e = null);
internal const string pluginCMDExtension = "dll";
internal const string pluginEVEExtension = "dll";
private const string pluginFolder = @"./Data/Plugins/";
internal const string pluginExtension = "dll";
private readonly DiscordSocketClient _client;
/// <summary>
@@ -36,6 +36,11 @@ public class PluginLoader
/// </summary>
public EVELoaded? onEVELoad;
/// <summary>
/// Event that is fired when a <see cref="DBEvent" /> is successfully loaded into events list
/// </summary>
public SLSHLoaded? onSLSHLoad;
/// <summary>
/// The Plugin Loader constructor
/// </summary>
@@ -67,7 +72,7 @@ public class PluginLoader
public async void LoadPlugins()
{
//Check for updates in commands
foreach (var file in Directory.GetFiles("./Data/Plugins/Commands", $"*.{pluginCMDExtension}",
foreach (var file in Directory.GetFiles("./Data/Plugins/", $"*.{pluginExtension}",
SearchOption.AllDirectories))
await Task.Run(async () =>
{
@@ -83,22 +88,6 @@ public class PluginLoader
await PluginUpdater.Download(name);
});
//Check for updates in events
foreach (var file in Directory.GetFiles("./Data/Plugins/Events", $"*.{pluginEVEExtension}",
SearchOption.AllDirectories))
await Task.Run(async () =>
{
var name = new FileInfo(file).Name.Split('.')[0];
var version = await ServerCom.GetVersionOfPackageFromWeb(name);
if (version is null)
return;
if (!Config.PluginVersionsContainsKey(name))
Config.SetPluginVersion(
name, (version.PackageVersionID + ".0.0"));
if (await PluginUpdater.CheckForUpdates(name))
await PluginUpdater.Download(name);
});
//Save the new config file (after the updates)
@@ -114,7 +103,7 @@ public class PluginLoader
Functions.WriteLogFile("Starting plugin loader ... Client: " + _client.CurrentUser.Username);
Console.WriteLine("Loading plugins");
var commandsLoader = new Loader<DBCommand>(pluginCMDFolder, pluginCMDExtension);
/* var commandsLoader = new Loader<DBCommand>(pluginCMDFolder, pluginCMDExtension);
var eventsLoader = new Loader<DBEvent>(pluginEVEFolder, pluginEVEExtension);
var slashLoader = new Loader<DBSlashCommand>("./Data/Plugins/SlashCommands/", "dll");
@@ -129,10 +118,61 @@ public class PluginLoader
Commands = commandsLoader.Load();
Events = eventsLoader.Load();
SlashCommands = slashLoader.Load();
SlashCommands = slashLoader.Load();*/
var loader = new LoaderV2("./Data/Plugins", "dll");
loader.FileLoaded += (args) => Functions.WriteLogFile($"{args.PluginName} file Loaded");
loader.PluginLoaded += Loader_PluginLoaded;
var res = loader.Load();
Events = res.Item1;
Commands = res.Item2;
SlashCommands = res.Item3;
}
private async void Loader_PluginLoaded(LoaderArgs args)
{
// Console.WriteLine(args.TypeName);
switch (args.TypeName)
{
case "DBCommand":
onCMDLoad?.Invoke(((DBCommand)args.Plugin!).Command, args.TypeName!, args.IsLoaded, args.Exception);
break;
case "DBEvent":
try
{
if (args.IsLoaded)
((DBEvent)args.Plugin!).Start(_client);
onEVELoad?.Invoke(((DBEvent)args.Plugin!).Name, args.TypeName!, args.IsLoaded, args.Exception);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
Console.WriteLine("Plugin: " + args.PluginName);
Console.WriteLine("Type: " + args.TypeName);
Console.WriteLine("IsLoaded: " + args.IsLoaded);
}
break;
case "DBSlashCommand":
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);
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)
@@ -154,7 +194,7 @@ public class PluginLoader
private void SlashLoader_FileLoaded(LoaderArgs args)
{
if (!args.IsLoaded)
Functions.WriteLogFile($"[SLASH] Event from file [{args.PluginName}] has been successfully created !");
Functions.WriteLogFile($"[SLASH] SlashCommand from file [{args.PluginName}] has been successfully created !");
}
private void EventFileLoaded(LoaderArgs e)
@@ -190,5 +230,5 @@ public class PluginLoader
private void OnCommandLoaded(LoaderArgs e)
{
onCMDLoad?.Invoke(((DBCommand)e.Plugin!).Command, e.TypeName!, e.IsLoaded, e.Exception);
}
}*/
}

View File

@@ -1,8 +1,10 @@
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using PluginManager.Online.Helpers;
using PluginManager.Others;
using OperatingSystem = PluginManager.Others.OperatingSystem;
namespace PluginManager.Online;
@@ -38,10 +40,10 @@ public class PluginsManager
var op = Functions.GetOperatingSystem();
var len = lines.Length;
string[] titles = { "Name", "Description", "Type", "Version", "Installed" };
data.Add(new[] { "-", "-", "-", "-", "-" });
string[] titles = { "Name", "Description", "Type", "Version" };
data.Add(new[] { "-", "-", "-", "-" });
data.Add(titles);
data.Add(new[] { "-", "-", "-", "-", "-" });
data.Add(new[] { "-", "-", "-", "-" });
for (var i = 0; i < len; i++)
{
if (lines[i].Length <= 2)
@@ -58,10 +60,6 @@ public class PluginsManager
display[3] =
(await ServerCom.GetVersionOfPackageFromWeb(content[0]) ?? new VersionString("0.0.0"))
.ToShortString();
if (Config.PluginConfig.Contains(content[0]) || Config.PluginConfig.Contains(content[0]))
display[4] = "✓";
else
display[4] = "X";
data.Add(display);
}
}
@@ -75,16 +73,12 @@ public class PluginsManager
display[3] =
(await ServerCom.GetVersionOfPackageFromWeb(content[0]) ?? new VersionString("0.0.0"))
.ToShortString();
if (Config.PluginConfig.Contains(content[0]) || Config.PluginConfig.Contains(content[0]))
display[4] = "✓";
else
display[4] = "X";
data.Add(display);
}
}
}
data.Add(new[] { "-", "-", "-", "-", "-" });
data.Add(new[] { "-", "-", "-", "-" });
Console_Utilities.FormatAndAlignTable(data, TableFormat.CENTER_EACH_COLUMN_BASED);
}

View File

@@ -36,16 +36,6 @@ public enum OutputLogLevel
CRITICAL
}
/// <summary>
/// Plugin Type
/// </summary>
public enum PluginType
{
Command,
Event,
Unknown
}
public enum UnzipProgressType
{
PercentageFromNumberOfFiles,

View File

@@ -9,9 +9,9 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "PluginManager", "PluginMana
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MusicLibrary", "..\DiscordBotItems\Plugins\MusicLibrary\MusicLibrary.csproj", "{878DFE01-4596-4EBC-9651-0679598CE794}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MusicLibraryEvent", "..\DiscordBotItems\Plugins\MusicLibraryEvent\MusicLibraryEvent.csproj", "{3EE0C8B4-5625-48A8-8246-5AD54A38A9B1}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SlashCommands", "..\DiscordBotItems\Plugins\SlashCommands\SlashCommands.csproj", "{C2D73BE8-997B-4A4A-8EA5-989BE33EE1DD}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SlashCommands", "..\DiscordBotItems\Plugins\SlashCommands\SlashCommands.csproj", "{C2D73BE8-997B-4A4A-8EA5-989BE33EE1DD}"
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LevelingSystem", "..\DiscordBotItems\Plugins\LevelingSystem\LevelingSystem.csproj", "{0138F343-BBB9-4D5F-B499-D9C2978BE9AA}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
@@ -31,14 +31,14 @@ Global
{878DFE01-4596-4EBC-9651-0679598CE794}.Debug|Any CPU.Build.0 = Debug|Any CPU
{878DFE01-4596-4EBC-9651-0679598CE794}.Release|Any CPU.ActiveCfg = Release|Any CPU
{878DFE01-4596-4EBC-9651-0679598CE794}.Release|Any CPU.Build.0 = Release|Any CPU
{3EE0C8B4-5625-48A8-8246-5AD54A38A9B1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{3EE0C8B4-5625-48A8-8246-5AD54A38A9B1}.Debug|Any CPU.Build.0 = Debug|Any CPU
{3EE0C8B4-5625-48A8-8246-5AD54A38A9B1}.Release|Any CPU.ActiveCfg = Release|Any CPU
{3EE0C8B4-5625-48A8-8246-5AD54A38A9B1}.Release|Any CPU.Build.0 = Release|Any CPU
{C2D73BE8-997B-4A4A-8EA5-989BE33EE1DD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C2D73BE8-997B-4A4A-8EA5-989BE33EE1DD}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C2D73BE8-997B-4A4A-8EA5-989BE33EE1DD}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C2D73BE8-997B-4A4A-8EA5-989BE33EE1DD}.Release|Any CPU.Build.0 = Release|Any CPU
{0138F343-BBB9-4D5F-B499-D9C2978BE9AA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{0138F343-BBB9-4D5F-B499-D9C2978BE9AA}.Debug|Any CPU.Build.0 = Debug|Any CPU
{0138F343-BBB9-4D5F-B499-D9C2978BE9AA}.Release|Any CPU.ActiveCfg = Release|Any CPU
{0138F343-BBB9-4D5F-B499-D9C2978BE9AA}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE