This commit is contained in:
2022-06-03 22:28:22 +03:00
parent 3e01e75de3
commit ab6f14e74c
21 changed files with 358 additions and 264 deletions

View File

@@ -1,13 +0,0 @@
# Default ignored files
/shelf/
/workspace.xml
# Rider ignored files
/modules.xml
/contentModel.xml
/.idea.DiscordBotWithAPI.iml
/projectSettingsUpdater.xml
# Editor-based HTTP Client requests
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml

View File

@@ -1,13 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="AvaloniaProject">
<option name="projectPerEditor">
<map>
<entry key="DiscordBotGUI/App.axaml" value="DiscordBotGUI/DiscordBotGUI.csproj" />
<entry key="DiscordBotGUI/AppUpdater.axaml" value="DiscordBotGUI/DiscordBotGUI.csproj" />
<entry key="DiscordBotGUI/Settings/Commands.axaml" value="DiscordBotGUI/DiscordBotGUI.csproj" />
<entry key="DiscordBotGUI/Settings/Events.axaml" value="DiscordBotGUI/DiscordBotGUI.csproj" />
</map>
</option>
</component>
</project>

View File

@@ -1,4 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Encoding" addBOMForNewFiles="with BOM under Windows, with no BOM otherwise" />
</project>

View File

@@ -1,8 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="UserContentModel">
<attachedFolders />
<explicitIncludes />
<explicitExcludes />
</component>
</project>

View File

@@ -1,6 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>

Binary file not shown.

Binary file not shown.

View File

@@ -2,6 +2,3 @@
<assemblyIdentity name="System.Runtime" publicKeyToken="b03f5f7f11d50a3a" culture="neutral"/> <assemblyIdentity name="System.Runtime" publicKeyToken="b03f5f7f11d50a3a" culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="4.0.0.0"/> <bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="4.0.0.0"/>
</dependentAssembly> </dependentAssembly>

View File

@@ -75,9 +75,10 @@ namespace DiscordBot.Discord.Commands
string normalCommands = ""; string normalCommands = "";
string DMCommands = ""; string DMCommands = "";
foreach (var cmd in PluginLoader.Commands!) foreach (var cmd in PluginLoader.Plugins!)
{ {
if (cmd.canUseDM) DMCommands += cmd.Command + " "; if (cmd.canUseDM)
DMCommands += cmd.Command + " ";
if (cmd.requireAdmin) if (cmd.requireAdmin)
adminCommands += cmd.Command + " "; adminCommands += cmd.Command + " ";
else if (cmd.canUseServer) normalCommands += cmd.Command + " "; else if (cmd.canUseServer) normalCommands += cmd.Command + " ";
@@ -93,7 +94,7 @@ namespace DiscordBot.Discord.Commands
private EmbedBuilder GenerateHelpCommand(string command) private EmbedBuilder GenerateHelpCommand(string command)
{ {
EmbedBuilder embedBuilder = new EmbedBuilder(); EmbedBuilder embedBuilder = new EmbedBuilder();
DBCommand cmd = PluginLoader.Commands.Find(p => p.Command == command); DBCommand cmd = PluginLoader.Plugins.Find(p => p.Command == command);
if (cmd == null) if (cmd == null)
return null; return null;

View File

@@ -80,7 +80,7 @@ namespace PluginManager.Core
services: null services: null
); );
DBCommand plugin = PluginLoader.Commands!.Where(p => p.Command == (message.Content.Split(' ')[0]).Substring(botPrefix.Length)).FirstOrDefault(); DBCommand plugin = PluginLoader.Plugins!.Where(p => p.Command == (message.Content.Split(' ')[0]).Substring(botPrefix.Length)).FirstOrDefault();
if (plugin != null) if (plugin != null)

View File

@@ -1,14 +1,16 @@
using Discord; using Discord;
using System; using System;
using System.IO; using System.IO;
using System.Threading.Tasks; using System.Threading.Tasks;
using PluginManager.Core; using PluginManager.Core;
using PluginManager.Others; using PluginManager.Others;
using PluginManager.LanguageSystem; using PluginManager.LanguageSystem;
using PluginManager.Online; using PluginManager.Online;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading;
using PluginManager.Items; using PluginManager.Items;
namespace DiscordBot namespace DiscordBot
@@ -18,23 +20,21 @@ namespace DiscordBot
private static bool loadPluginsOnStartup = false; private static bool loadPluginsOnStartup = false;
private static bool listPluginsAtStartup = false; private static bool listPluginsAtStartup = false;
private static bool listLanguagAtStartup = false; private static bool listLanguagAtStartup = false;
//private static bool ShowStartupMessage = true;
private static bool ShowStartupMessage = true;
/// <summary> /// <summary>
/// The main entry point for the application. /// The main entry point for the application.
/// </summary> /// </summary>
[STAThread] [STAThread]
[Obsolete] [Obsolete]
public static void Main(string[] args) public static void Main(string[] args)
{ {
Directory.CreateDirectory("./Data/Resources"); Directory.CreateDirectory("./Data/Resources");
Directory.CreateDirectory("./Data/Languages"); Directory.CreateDirectory("./Data/Languages");
Directory.CreateDirectory("./Data/Plugins/Commands"); Directory.CreateDirectory("./Data/Plugins/Commands");
Directory.CreateDirectory("./Data/Plugins/Events"); Directory.CreateDirectory("./Data/Plugins/Events");
Directory.CreateDirectory("./Data/runtime");
AppDomain.CurrentDomain.AppendPrivatePath("./Data/runtime");
if (!File.Exists("./Data/Resources/DiscordBotCore.data") || (Functions.readCodeFromFile("./Data/Resources/DiscordBotCore.data", "BOT_TOKEN", '=').Length != 59 && Functions.readCodeFromFile("./Data/Resources/DiscordBotCore.data", "BOT_TOKEN", '=').Length != 70)) if (!File.Exists("./Data/Resources/DiscordBotCore.data") || (Functions.readCodeFromFile("./Data/Resources/DiscordBotCore.data", "BOT_TOKEN", '=').Length != 59 && Functions.readCodeFromFile("./Data/Resources/DiscordBotCore.data", "BOT_TOKEN", '=').Length != 70))
{ {
File.WriteAllText("./Data/Resources/DiscordBotCore.data", "BOT_TOKEN=token\nBOT_PREFIX=!\n"); File.WriteAllText("./Data/Resources/DiscordBotCore.data", "BOT_TOKEN=token\nBOT_PREFIX=!\n");
@@ -46,12 +46,12 @@ namespace DiscordBot
if (botToken.Length == 59 || botToken.Length == 70) if (botToken.Length == 59 || botToken.Length == 70)
{ {
string prefix = Functions.readCodeFromFile("./Data/Resources/DiscordBotCore.data", "BOT_PREFIX", '='); string prefix = Functions.readCodeFromFile("./Data/Resources/DiscordBotCore.data", "BOT_PREFIX", '=');
if (prefix == string.Empty || prefix == null) prefix = "!"; if (prefix == string.Empty || prefix == null)
prefix = "!";
File.WriteAllText("./Data/Resources/DiscordBotCore.data", $"BOT_TOKEN={botToken}\nBOT_PREFIX={prefix}\n"); File.WriteAllText("./Data/Resources/DiscordBotCore.data", $"BOT_TOKEN={botToken}\nBOT_PREFIX={prefix}\n");
break; break;
} }
else else Console.WriteLine("Invalid Token !");
Console.WriteLine("Invalid Token !");
} }
} }
@@ -72,14 +72,17 @@ namespace DiscordBot
/// 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 async Task NoGUI(Boot discordbooter)
{ {
Language.LoadLanguage(); Language.LoadLanguage();
ConsoleCommandsHandler consoleCommandsHandler = new ConsoleCommandsHandler(discordbooter.client); ConsoleCommandsHandler consoleCommandsHandler = new ConsoleCommandsHandler(discordbooter.client);
if (loadPluginsOnStartup) consoleCommandsHandler.HandleCommand("lp"); if (loadPluginsOnStartup)
if (listPluginsAtStartup) consoleCommandsHandler.HandleCommand("listplugs"); consoleCommandsHandler.HandleCommand("lp");
if (listLanguagAtStartup) consoleCommandsHandler.HandleCommand("listlang"); if (listPluginsAtStartup)
consoleCommandsHandler.HandleCommand("listplugs");
if (listLanguagAtStartup)
consoleCommandsHandler.HandleCommand("listlang");
while (true) while (true)
{ {
@@ -95,11 +98,20 @@ namespace DiscordBot
/// <returns>Returns the boot loader for the Discord Bot</returns> /// <returns>Returns the boot loader for the Discord Bot</returns>
private static async Task<Boot> StartNoGUI() private static async Task<Boot> StartNoGUI()
{ {
Console.Clear(); Console.Clear();
Console.ForegroundColor = ConsoleColor.DarkYellow; Console.ForegroundColor = ConsoleColor.DarkYellow;
Console.WriteLine("Discord BOT for Cross Platform"); Console.WriteLine("Discord BOT for Cross Platform");
Console.WriteLine("Created by: Wizzy\nDiscord: Wizzy#9181"); Console.WriteLine("Created by: Wizzy\nDiscord: Wizzy#9181");
if (ShowStartupMessage)
try
{
Console.WriteLine("Connecting to server ...");
List<string> text = await ServerCom.ReadTextFromFile("https://sethdiscordbot.000webhostapp.com/Storage/Discord%20Bot/StartupMessage");
foreach (var t in text) Console_Utilities.WriteColorText(t);
}
catch { Console.WriteLine("Failed to connect to server."); }
Console.ForegroundColor = ConsoleColor.White; Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine("============================ Discord BOT - Cross Platform ============================"); Console.WriteLine("============================ Discord BOT - Cross Platform ============================");
string token = Functions.readCodeFromFile(Functions.dataFolder + "DiscordBotCore.data", "BOT_TOKEN", '='); string token = Functions.readCodeFromFile(Functions.dataFolder + "DiscordBotCore.data", "BOT_TOKEN", '=');
@@ -133,6 +145,7 @@ namespace DiscordBot
/// <param name="args">The arguments</param> /// <param name="args">The arguments</param>
private static async Task HandleInput(string[] args) private static async Task HandleInput(string[] args)
{ {
if (args.Length == 0) if (args.Length == 0)
{ {
if (File.Exists("./ref/startupArguments.txt")) if (File.Exists("./ref/startupArguments.txt"))
@@ -151,12 +164,8 @@ namespace DiscordBot
if (len == 1 && args[0] == "--logout") if (len == 1 && args[0] == "--logout")
{ {
File.Delete(Functions.dataFolder + "DiscordBotCore.dat"); File.Delete(Functions.dataFolder + "Login.dat");
await Task.Run(async () => Console.WriteLine("Logged out. Please restart the application !");
{
await Task.Delay(1000);
Environment.Exit(0x08);
});
return; return;
} }
@@ -170,14 +179,20 @@ namespace DiscordBot
if (len > 0 && (args.Contains("--cmd") || args.Contains("--args") || args.Contains("--nomessage"))) if (len > 0 && (args.Contains("--cmd") || args.Contains("--args") || args.Contains("--nomessage")))
{ {
if (args.Contains("lp") || args.Contains("loadplugins")) loadPluginsOnStartup = true; if (args.Contains("lp") || args.Contains("loadplugins"))
if (args.Contains("listplugs")) listPluginsAtStartup = true; loadPluginsOnStartup = true;
if (args.Contains("listlang")) listLanguagAtStartup = true; if (args.Contains("listplugs"))
//if (args.Contains("--nomessage")) ShowStartupMessage = false; listPluginsAtStartup = true;
if (args.Contains("listlang"))
listLanguagAtStartup = true;
if (args.Contains("--nomessage"))
ShowStartupMessage = false;
len = 0; len = 0;
} }
if (len == 0 || args[0] != "--exec" && args[0] != "--execute") if (len == 0 || args[0] != "--exec" && args[0] != "--execute")
{ {
Boot b = await StartNoGUI(); Boot b = await StartNoGUI();

View File

@@ -1,8 +1,6 @@
using System.IO;
using Avalonia; using Avalonia;
using Avalonia.Controls.ApplicationLifetimes; using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Markup.Xaml; using Avalonia.Markup.Xaml;
using PluginManager.Others;
namespace DiscordBotGUI namespace DiscordBotGUI
{ {
@@ -15,7 +13,13 @@ namespace DiscordBotGUI
public override void OnFrameworkInitializationCompleted() public override void OnFrameworkInitializationCompleted()
{ {
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop) { desktop.MainWindow = new AppUpdater() { Width = 300, Height = 50, WindowStartupLocation = Avalonia.Controls.WindowStartupLocation.CenterScreen }; } if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
{
desktop.MainWindow = new AppUpdater() { Width = 300, Height = 50, WindowStartupLocation = Avalonia.Controls.WindowStartupLocation.CenterScreen };
}
base.OnFrameworkInitializationCompleted(); base.OnFrameworkInitializationCompleted();
} }

View File

@@ -21,48 +21,42 @@ namespace DiscordBotGUI
InitializeComponent(); InitializeComponent();
if (!File.Exists("./Version.txt")) if (!File.Exists("./Version.txt"))
{ {
textBox1.Text = "Checking ...";
File.WriteAllText("./Version.txt", "DiscordBotVersion=0"); File.WriteAllText("./Version.txt", "DiscordBotVersion=0");
DownloadDiscordBotClientNoGUIAsDLL(); //DownloadDiscordBotClientNoGUIAsDLL();
} }
if (!File.Exists("./DiscordBot.exe")) DownloadDiscordBotClientNoGUIAsDLL();
Updates(); Updates();
} }
private async void DownloadDiscordBotClientNoGUIAsDLL() /* private async void DownloadDiscordBotClientNoGUIAsDLL()
{ {
//await Task.Delay(5000); //await Task.Delay(5000);
string url_bot_dll = "https://sethdiscordbot.000webhostapp.com/Storage/Discord%20Bot/Updates/DiscordBot.zip"; string url_bot_dll = "https://sethdiscordbot.000webhostapp.com/Storage/Discord%20Bot/Updates/DiscordBot.dll";
int actiontype = 0; //0 - downolad, 1- extract
IProgress<float> progress = new Progress<float>((percent) => IProgress<float> progress = new Progress<float>((percent) =>
{ {
if (actiontype == 0) textBox1.Text = "Downloading DiscordBot.dll ... " + (percent * 100).ToString() + "%";
textBox1.Text = "Downloading DiscordBot ... " + MathF.Round(percent, 2) + "%"; this.progressBar1.Value = percent * 100;
else
textBox1.Text = "Extracting package ..." + MathF.Round(percent, 2) + "%";
this.progressBar1.Value = percent;
}); });
this.progressBar1.IsIndeterminate = false; this.progressBar1.IsIndeterminate = false;
try try
{ {
await ServerCom.DownloadFileAsync(url_bot_dll, "./DiscordBot.zip", progress); await ServerCom.DownloadFileAsync(url_bot_dll, "./DiscordBot.dll", progress);
actiontype++;
await Functions.ExtractArchive("./DiscordBot.zip", "./", progress);
} }
catch catch
{ {
textBox1.Text = "Error downloading DiscordBot.dll. Server is not responding."; textBox1.Text = "Error downloading DiscordBot.dll. Server is not responding.";
await Task.Delay(1000); await Task.Delay(1000);
return;
}
new MainWindow() { Height = 425, Width = 500 }.Show(); //new MainWindow() { Height = 425, Width = 500 }.Show();
Close(); //Close();
} }*/
}
private async void Updates() private async void Updates()
{ {

View File

@@ -23,6 +23,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CMD_Utils", "CMD_Utils\CMD_
EndProject EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MusicCommands", "MusicCommands\MusicCommands.csproj", "{B1B4976E-5112-4217-B57B-3A03C5207B6E}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MusicCommands", "MusicCommands\MusicCommands.csproj", "{B1B4976E-5112-4217-B57B-3A03C5207B6E}"
EndProject EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Games", "FreeGames\Games.csproj", "{7CC0819E-2BC0-44F0-8D92-EC442F36E1BB}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DiscordBotGUI", "DiscordBotGUI\DiscordBotGUI.csproj", "{7B5899F0-0218-4537-8C74-6210ED2D3690}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DiscordBotGUI", "DiscordBotGUI\DiscordBotGUI.csproj", "{7B5899F0-0218-4537-8C74-6210ED2D3690}"
EndProject EndProject
Global Global
@@ -59,6 +61,10 @@ Global
{B1B4976E-5112-4217-B57B-3A03C5207B6E}.Debug|Any CPU.Build.0 = Debug|Any CPU {B1B4976E-5112-4217-B57B-3A03C5207B6E}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B1B4976E-5112-4217-B57B-3A03C5207B6E}.Release|Any CPU.ActiveCfg = Release|Any CPU {B1B4976E-5112-4217-B57B-3A03C5207B6E}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B1B4976E-5112-4217-B57B-3A03C5207B6E}.Release|Any CPU.Build.0 = Release|Any CPU {B1B4976E-5112-4217-B57B-3A03C5207B6E}.Release|Any CPU.Build.0 = Release|Any CPU
{7CC0819E-2BC0-44F0-8D92-EC442F36E1BB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{7CC0819E-2BC0-44F0-8D92-EC442F36E1BB}.Debug|Any CPU.Build.0 = Debug|Any CPU
{7CC0819E-2BC0-44F0-8D92-EC442F36E1BB}.Release|Any CPU.ActiveCfg = Release|Any CPU
{7CC0819E-2BC0-44F0-8D92-EC442F36E1BB}.Release|Any CPU.Build.0 = Release|Any CPU
{7B5899F0-0218-4537-8C74-6210ED2D3690}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {7B5899F0-0218-4537-8C74-6210ED2D3690}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{7B5899F0-0218-4537-8C74-6210ED2D3690}.Debug|Any CPU.Build.0 = Debug|Any CPU {7B5899F0-0218-4537-8C74-6210ED2D3690}.Debug|Any CPU.Build.0 = Debug|Any CPU
{7B5899F0-0218-4537-8C74-6210ED2D3690}.Release|Any CPU.ActiveCfg = Release|Any CPU {7B5899F0-0218-4537-8C74-6210ED2D3690}.Release|Any CPU.ActiveCfg = Release|Any CPU
@@ -75,6 +81,7 @@ Global
{CE9DBF06-38A0-4192-8B3E-4009210D040D} = {A290C028-77C4-4D1D-AB43-DDFE6ABD9012} {CE9DBF06-38A0-4192-8B3E-4009210D040D} = {A290C028-77C4-4D1D-AB43-DDFE6ABD9012}
{E26C87A4-3DD6-4B58-B14B-C8E086B852F9} = {449FA364-0B72-43FF-B3A3-806E2916200E} {E26C87A4-3DD6-4B58-B14B-C8E086B852F9} = {449FA364-0B72-43FF-B3A3-806E2916200E}
{B1B4976E-5112-4217-B57B-3A03C5207B6E} = {449FA364-0B72-43FF-B3A3-806E2916200E} {B1B4976E-5112-4217-B57B-3A03C5207B6E} = {449FA364-0B72-43FF-B3A3-806E2916200E}
{7CC0819E-2BC0-44F0-8D92-EC442F36E1BB} = {449FA364-0B72-43FF-B3A3-806E2916200E}
EndGlobalSection EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {3FB3C5DE-ED21-4D2E-ABDD-3A00EE4A2FFF} SolutionGuid = {3FB3C5DE-ED21-4D2E-ABDD-3A00EE4A2FFF}

View File

@@ -0,0 +1,99 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using PluginManager.Interfaces;
namespace PluginManager.Loaders
{
internal class CommandsLoader
{
private readonly string CMDPath;
private readonly string CMDExtension;
internal delegate void onCommandLoaded(string name, bool success, DBCommand? command = null, Exception? exception = null);
internal delegate void onCommandFileLoaded(string path);
/// <summary>
/// Event fired when a command is loaded
/// </summary>
internal onCommandLoaded? OnCommandLoaded;
/// <summary>
/// Event fired when the file is loaded
/// </summary>
internal onCommandFileLoaded? OnCommandFileLoaded;
/// <summary>
/// Command Loader contructor
/// </summary>
/// <param name="CommandPath">The path to the commands</param>
/// <param name="CommandExtension">The extension to search for in the <paramref name="CommandPath"/></param>
internal CommandsLoader(string CommandPath, string CommandExtension)
{
CMDPath = CommandPath;
CMDExtension = CommandExtension;
}
/// <summary>
/// The method that loads all commands
/// </summary>
/// <returns></returns>
internal List<DBCommand>? LoadCommands()
{
if (!Directory.Exists(CMDPath))
{
Directory.CreateDirectory(CMDPath);
return null;
}
string[] files = Directory.GetFiles(CMDPath, $"*{CMDExtension}", SearchOption.AllDirectories);
foreach (var file in files)
{
Assembly.LoadFile(Path.GetFullPath(file));
if (OnCommandFileLoaded != null)
OnCommandFileLoaded.Invoke(file);
}
List<DBCommand> plugins = new List<DBCommand>();
try
{
Type interfaceType = typeof(DBCommand);
Type[] types = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(a => a.GetTypes())
.Where(p => interfaceType.IsAssignableFrom(p) && p.IsClass)
.ToArray();
foreach (Type type in types)
{
try
{
DBCommand plugin = (DBCommand)Activator.CreateInstance(type)!;
plugins.Add(plugin);
if (OnCommandLoaded != null)
OnCommandLoaded.Invoke(type.FullName!, true, plugin);
}
catch (Exception e)
{
if (OnCommandLoaded != null)
OnCommandLoaded.Invoke(type.FullName!, false, null, e);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return null;
}
return plugins;
}
}
}

View File

@@ -0,0 +1,100 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using PluginManager.Interfaces;
namespace PluginManager.Loaders
{
internal class EventsLoader
{
private readonly string EVPath;
private readonly string EVExtension;
internal delegate void onEventLoad(string name, bool success, DBEvent? ev = null, Exception? e = null);
internal delegate void onEventFileLoaded(string path);
/// <summary>
/// An event that is fired whenever a <see cref="DBEvent"/> event is loaded in memory
/// </summary>
internal onEventLoad? EventLoad;
/// <summary>
/// An event that is fired whenever a <see cref="DBEvent"/> event file is loaded
/// </summary>
internal onEventFileLoaded? EventFileLoaded;
/// <summary>
/// The Event Loader constructor
/// </summary>
/// <param name="path">The path to all events</param>
/// <param name="ext">The extension for events</param>
internal EventsLoader(string path, string ext)
{
EVPath = path;
EVExtension = ext;
}
/// <summary>
/// The method that loads all events
/// </summary>
/// <returns></returns>
internal List<DBEvent>? LoadEvents()
{
if (!Directory.Exists(EVPath))
{
Directory.CreateDirectory(EVPath);
return null;
}
string[] files = Directory.GetFiles(EVPath, $"*{EVExtension}", SearchOption.AllDirectories);
foreach (var file in files)
{
Assembly.LoadFile(Path.GetFullPath(file));
if (EventFileLoaded != null)
EventFileLoaded.Invoke(file);
}
List<DBEvent> events = new List<DBEvent>();
try
{
Type interfaceType = typeof(DBEvent);
Type[] types = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(a => a.GetTypes())
.Where(p => interfaceType.IsAssignableFrom(p) && p.IsClass)
.ToArray();
foreach (Type type in types)
{
try
{
DBEvent ev = (DBEvent)Activator.CreateInstance(type)!;
events.Add(ev);
if (EventLoad != null)
EventLoad.Invoke(type.FullName!, true, ev, null);
}
catch (Exception e)
{
if (EventLoad != null)
EventLoad.Invoke(type.FullName!, false, null, e);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return null;
}
return events;
}
}
}

View File

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

View File

@@ -1,32 +1,35 @@
using Discord.WebSocket; using Discord.WebSocket;
using PluginManager.Interfaces; using PluginManager.Interfaces;
using PluginManager.Others; using PluginManager.Others;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
namespace PluginManager.Loaders namespace PluginManager.Loaders
{ {
public class PluginLoader public class PluginLoader
{ {
private readonly DiscordSocketClient _client; private DiscordSocketClient client;
/// <summary> /// <summary>
/// The Plugin Loader constructor /// The Plugin Loader constructor
/// </summary> /// </summary>
/// <param name="discordSocketClient">The discord bot client where the plugins will pe attached to</param> /// <param name="discordSocketClient">The discord bot client where the plugins will pe attached to</param>
public PluginLoader(DiscordSocketClient discordSocketClient) { this._client = discordSocketClient; } public PluginLoader(DiscordSocketClient discordSocketClient)
{
this.client = discordSocketClient;
}
private const string pluginCMDFolder = @"./Data/Plugins/Commands/"; private const string pluginCMDFolder = @"./Data/Plugins/Commands/";
private const string pluginEVEFolder = @"./Data/Plugins/Events/"; private const string pluginEVEFolder = @"./Data/Plugins/Events/";
private const string pluginCMDExtension = "dll"; private const string pluginCMDExtension = ".dll";
private const string pluginEVEExtension = "dll"; private const string pluginEVEExtension = ".dll";
/// <summary> /// <summary>
/// A list of <see cref="DBCommand"/> commands /// A list of <see cref="DBCommand"/> commands
/// </summary> /// </summary>
public static List<DBCommand>? Commands { get; set; } public static List<DBCommand>? Plugins { get; set; }
/// <summary> /// <summary>
/// A list of <see cref="DBEvent"/> commands /// A list of <see cref="DBEvent"/> commands
@@ -35,7 +38,6 @@ namespace PluginManager.Loaders
public delegate void CMDLoaded(string name, string typeName, bool success, Exception? e = null); public delegate void CMDLoaded(string name, string typeName, bool success, Exception? e = null);
public delegate void EVELoaded(string name, string typeName, bool success, Exception? e = null); public delegate void EVELoaded(string name, string typeName, bool success, Exception? e = null);
/// <summary> /// <summary>
@@ -53,10 +55,11 @@ namespace PluginManager.Loaders
/// </summary> /// </summary>
public void LoadPlugins() public void LoadPlugins()
{ {
Commands = new List<DBCommand>();
Plugins = new List<DBCommand>();
Events = new List<DBEvent>(); Events = new List<DBEvent>();
Functions.WriteLogFile("Starting plugin loader ... Client: " + _client.CurrentUser.Username); Functions.WriteLogFile("Starting plugin loader ... Client: " + client.CurrentUser.Username);
if (LanguageSystem.Language.ActiveLanguage != null) if (LanguageSystem.Language.ActiveLanguage != null)
Console_Utilities.WriteColorText( Console_Utilities.WriteColorText(
LanguageSystem.Language.ActiveLanguage.FormatText( LanguageSystem.Language.ActiveLanguage.FormatText(
@@ -64,40 +67,45 @@ namespace PluginManager.Loaders
) )
); );
//Load commands
CommandsLoader CMDLoader = new CommandsLoader(pluginCMDFolder, pluginCMDExtension);
CMDLoader.OnCommandLoaded += OnCommandLoaded!;
CMDLoader.OnCommandFileLoaded += OnCommandFileLoaded;
Plugins = CMDLoader.LoadCommands();
Loader<DBCommand> commandsLoader = new Loader<DBCommand>(pluginCMDFolder, pluginCMDExtension);
Loader<DBEvent> eventsLoader = new Loader<DBEvent>(pluginEVEFolder, pluginEVEExtension);
commandsLoader.FileLoaded += OnCommandFileLoaded; //Load Events
commandsLoader.PluginLoaded += OnCommandLoaded; EventsLoader EVLoader = new EventsLoader(pluginEVEFolder, pluginEVEExtension);
EVLoader.EventLoad += OnEventLoaded!;
EVLoader.EventFileLoaded += EventFileLoaded;
Events = EVLoader.LoadEvents();
eventsLoader.FileLoaded += EventFileLoaded;
eventsLoader.PluginLoaded += OnEventLoaded;
Commands = commandsLoader.Load();
Events = eventsLoader.Load();
} }
private void EventFileLoaded(LoaderArgs e) private void EventFileLoaded(string path)
{ {
if (e.IsLoaded) Functions.WriteLogFile($"[EVENT] Event from file [{e.PluginName}] has been successfully created !"); if (path != null)
Functions.WriteLogFile($"[EVENT] Event from file [{path}] has been successfully created !");
} }
private void OnCommandFileLoaded(LoaderArgs e) private void OnCommandFileLoaded(string path)
{ {
if (e.IsLoaded) Functions.WriteLogFile($"[CMD] Command from file [{e.PluginName}] has been successfully loaded !"); if (path != null)
Functions.WriteLogFile($"[CMD] Command from file [{path}] has been successfully loaded !");
} }
private void OnEventLoaded(LoaderArgs e) private void OnEventLoaded(string typename, bool success, DBEvent eve, Exception exception)
{ {
if (e.IsLoaded) { ((DBEvent)e.Plugin!).Start(_client); } if (eve != null && success)
eve.Start(client);
if (onEVELoad != null) onEVELoad.Invoke(((DBEvent)e.Plugin!).name, e.TypeName!, e.IsLoaded, e.Exception); if (onEVELoad != null)
onEVELoad.Invoke(eve!.name, typename, success, exception);
} }
private void OnCommandLoaded(LoaderArgs e) private void OnCommandLoaded(string name, bool success, DBCommand command, Exception exception)
{ {
if (onCMDLoad != null) onCMDLoad.Invoke(((DBCommand)e.Plugin!).Command, e.TypeName!, e.IsLoaded, e.Exception); if (onCMDLoad != null)
onCMDLoad.Invoke(command.Command, name, success, exception);
} }
} }
} }

View File

@@ -1,5 +1,9 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace PluginManager.Others namespace PluginManager.Others
{ {
@@ -10,20 +14,17 @@ namespace PluginManager.Others
/// </summary> /// </summary>
public class ProgressBar public class ProgressBar
{ {
public int Progress { get; set; }
public int Max { get; set; } public int Max { get; set; }
public string Message { get; set; } public string Message { get; set; }
public ConsoleColor Color { get; init; }
public ProgressBar(int max, string message) public ProgressBar(int max, string message)
{ {
Max = max; Max = max;
Message = message; Message = message;
var consoleColors = Enum.GetValues(typeof(ConsoleColor));
while ((Color = (ConsoleColor)consoleColors.GetValue(new Random().Next(consoleColors.Length))!) == ConsoleColor.White && Color != ConsoleColor.Black) ;
} }
public void Update(int progress, double speed = -1, string? unit = null) public async void Update(int progress, double speed = -1, string? unit = null)
{ {
//progress bar //progress bar
@@ -38,7 +39,7 @@ namespace PluginManager.Others
for (int i = 0; i < onechunk * progress; i++) for (int i = 0; i < onechunk * progress; i++)
{ {
Console.BackgroundColor = this.Color; Console.BackgroundColor = ConsoleColor.Green;
Console.CursorLeft = position++; Console.CursorLeft = position++;
Console.Write(" "); Console.Write(" ");
} }
@@ -133,7 +134,6 @@ namespace PluginManager.Others
{"&b", ConsoleColor.Blue }, {"&b", ConsoleColor.Blue },
{"&r", ConsoleColor.Red }, {"&r", ConsoleColor.Red },
{"&m", ConsoleColor.Magenta }, {"&m", ConsoleColor.Magenta },
{ "&y", ConsoleColor.Yellow },
{"&c", fg } {"&c", fg }
}; };
foreach (string word in words) foreach (string word in words)
@@ -145,9 +145,7 @@ namespace PluginManager.Others
Console.ForegroundColor = colors[prefix]; Console.ForegroundColor = colors[prefix];
} }
string m = word; string m = word.Replace("&g", "").Replace("&b", "").Replace("&r", "").Replace("&c", "").Replace("&m", "");
foreach (var key in colors.Keys) { m = m.Replace(key, ""); }
Console.Write(m + " "); Console.Write(m + " ");
} }
if (appendNewLine) if (appendNewLine)

View File

@@ -259,13 +259,16 @@ namespace PluginManager.Others
foreach (ZipArchiveEntry entry in archive.Entries) foreach (ZipArchiveEntry entry in archive.Entries)
{ {
if (entry.FullName.EndsWith("/")) if (entry.FullName.EndsWith("/"))
Directory.CreateDirectory(Path.Combine(folder, entry.FullName)); {
else
try { entry.ExtractToFile(Path.Combine(folder, entry.FullName), true); }
catch { }
currentZIPFile++; currentZIPFile++;
Directory.CreateDirectory(Path.Combine(folder, entry.FullName));
}
else
{
entry.ExtractToFile(Path.Combine(folder, entry.FullName), true);
currentZIPFile++;
}
await Task.Delay(10); await Task.Delay(10);
progress.Report((float)currentZIPFile / totalZIPFiles * 100); progress.Report((float)currentZIPFile / totalZIPFiles * 100);
} }

View File

@@ -19,4 +19,10 @@
<PackageReference Include="Discord.Net" Version="3.6.1" /> <PackageReference Include="Discord.Net" Version="3.6.1" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<Page Include="BlankWindow1.xaml">
<Generator>MSBuild:Compile</Generator>
</Page>
</ItemGroup>
</Project> </Project>