patch for UI

This commit is contained in:
2022-06-02 13:48:56 +03:00
parent ab6f14e74c
commit 0d524cdf65
21 changed files with 265 additions and 359 deletions

13
.idea/.idea.DiscordBotWithAPI/.idea/.gitignore generated vendored Normal file
View File

@@ -0,0 +1,13 @@
# 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

@@ -0,0 +1,13 @@
<?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

@@ -0,0 +1,4 @@
<?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

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

View File

@@ -0,0 +1,6 @@
<?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

@@ -1,4 +1,7 @@
<dependentAssembly> <dependentAssembly>
<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,12 +75,11 @@ namespace DiscordBot.Discord.Commands
string normalCommands = ""; string normalCommands = "";
string DMCommands = ""; string DMCommands = "";
foreach (var cmd in PluginLoader.Plugins!) foreach (var cmd in PluginLoader.Commands!)
{ {
if (cmd.canUseDM) if (cmd.canUseDM) DMCommands += cmd.Command + " ";
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 + " ";
} }
@@ -94,7 +93,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.Plugins.Find(p => p.Command == command); DBCommand cmd = PluginLoader.Commands.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.Plugins!.Where(p => p.Command == (message.Content.Split(' ')[0]).Substring(botPrefix.Length)).FirstOrDefault(); DBCommand plugin = PluginLoader.Commands!.Where(p => p.Command == (message.Content.Split(' ')[0]).Substring(botPrefix.Length)).FirstOrDefault();
if (plugin != null) if (plugin != null)

View File

@@ -1,16 +1,14 @@
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
@@ -20,21 +18,23 @@ 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");
@@ -45,13 +45,13 @@ namespace DiscordBot
string botToken = Console.ReadLine(); string botToken = Console.ReadLine();
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) if (prefix == string.Empty || prefix == null) prefix = "!";
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 Console.WriteLine("Invalid Token !"); else
Console.WriteLine("Invalid Token !");
} }
} }
@@ -72,17 +72,14 @@ 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 async Task NoGUI(Boot discordbooter) private static Task NoGUI(Boot discordbooter)
{ {
Language.LoadLanguage(); Language.LoadLanguage();
ConsoleCommandsHandler consoleCommandsHandler = new ConsoleCommandsHandler(discordbooter.client); ConsoleCommandsHandler consoleCommandsHandler = new ConsoleCommandsHandler(discordbooter.client);
if (loadPluginsOnStartup) if (loadPluginsOnStartup) consoleCommandsHandler.HandleCommand("lp");
consoleCommandsHandler.HandleCommand("lp"); if (listPluginsAtStartup) consoleCommandsHandler.HandleCommand("listplugs");
if (listPluginsAtStartup) if (listLanguagAtStartup) consoleCommandsHandler.HandleCommand("listlang");
consoleCommandsHandler.HandleCommand("listplugs");
if (listLanguagAtStartup)
consoleCommandsHandler.HandleCommand("listlang");
while (true) while (true)
{ {
@@ -98,23 +95,14 @@ 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", '=');
string prefix = Functions.readCodeFromFile(Functions.dataFolder + "DiscordBotCore.data", "BOT_PREFIX", '='); string prefix = Functions.readCodeFromFile(Functions.dataFolder + "DiscordBotCore.data", "BOT_PREFIX", '=');
var discordbooter = new Boot(token, prefix); var discordbooter = new Boot(token, prefix);
@@ -128,8 +116,8 @@ namespace DiscordBot
/// <param name="d">Directory path</param> /// <param name="d">Directory path</param>
private static Task ClearFolder(string d) private static Task ClearFolder(string d)
{ {
string[] files = Directory.GetFiles(d); string[] files = Directory.GetFiles(d);
int fileNumb = files.Length; int fileNumb = files.Length;
for (var i = 0; i < fileNumb; i++) for (var i = 0; i < fileNumb; i++)
{ {
File.Delete(files[i]); File.Delete(files[i]);
@@ -145,7 +133,6 @@ 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"))
@@ -164,8 +151,12 @@ namespace DiscordBot
if (len == 1 && args[0] == "--logout") if (len == 1 && args[0] == "--logout")
{ {
File.Delete(Functions.dataFolder + "Login.dat"); File.Delete(Functions.dataFolder + "DiscordBotCore.dat");
Console.WriteLine("Logged out. Please restart the application !"); await Task.Run(async () =>
{
await Task.Delay(1000);
Environment.Exit(0x08);
});
return; return;
} }
@@ -179,20 +170,14 @@ 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")) if (args.Contains("lp") || args.Contains("loadplugins")) loadPluginsOnStartup = true;
loadPluginsOnStartup = true; if (args.Contains("listplugs")) listPluginsAtStartup = true;
if (args.Contains("listplugs")) if (args.Contains("listlang")) listLanguagAtStartup = true;
listPluginsAtStartup = true; //if (args.Contains("--nomessage")) ShowStartupMessage = false;
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,6 +1,8 @@
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
{ {
@@ -13,13 +15,7 @@ namespace DiscordBotGUI
public override void OnFrameworkInitializationCompleted() public override void OnFrameworkInitializationCompleted()
{ {
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop) if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop) { desktop.MainWindow = new AppUpdater() { Width = 300, Height = 50, WindowStartupLocation = Avalonia.Controls.WindowStartupLocation.CenterScreen }; }
{
desktop.MainWindow = new AppUpdater() { Width = 300, Height = 50, WindowStartupLocation = Avalonia.Controls.WindowStartupLocation.CenterScreen };
}
base.OnFrameworkInitializationCompleted(); base.OnFrameworkInitializationCompleted();
} }

View File

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

View File

@@ -23,8 +23,6 @@ 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
@@ -61,10 +59,6 @@ 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
@@ -81,7 +75,6 @@ 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

@@ -1,99 +0,0 @@
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

@@ -1,100 +0,0 @@
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

@@ -0,0 +1,94 @@
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,35 +1,32 @@
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 DiscordSocketClient client; private readonly 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) public PluginLoader(DiscordSocketClient discordSocketClient) { this._client = 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>? Plugins { get; set; } public static List<DBCommand>? Commands { get; set; }
/// <summary> /// <summary>
/// A list of <see cref="DBEvent"/> commands /// A list of <see cref="DBEvent"/> commands
@@ -38,6 +35,7 @@ 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>
@@ -55,11 +53,10 @@ namespace PluginManager.Loaders
/// </summary> /// </summary>
public void LoadPlugins() public void LoadPlugins()
{ {
Commands = new List<DBCommand>();
Events = new List<DBEvent>();
Plugins = new List<DBCommand>(); Functions.WriteLogFile("Starting plugin loader ... Client: " + _client.CurrentUser.Username);
Events = new List<DBEvent>();
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(
@@ -67,45 +64,40 @@ 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);
//Load Events commandsLoader.FileLoaded += OnCommandFileLoaded;
EventsLoader EVLoader = new EventsLoader(pluginEVEFolder, pluginEVEExtension); commandsLoader.PluginLoaded += OnCommandLoaded;
EVLoader.EventLoad += OnEventLoaded!;
EVLoader.EventFileLoaded += EventFileLoaded;
Events = EVLoader.LoadEvents();
eventsLoader.FileLoaded += EventFileLoaded;
eventsLoader.PluginLoaded += OnEventLoaded;
Commands = commandsLoader.Load();
Events = eventsLoader.Load();
} }
private void EventFileLoaded(string path) private void EventFileLoaded(LoaderArgs e)
{ {
if (path != null) if (e.IsLoaded) Functions.WriteLogFile($"[EVENT] Event from file [{e.PluginName}] has been successfully created !");
Functions.WriteLogFile($"[EVENT] Event from file [{path}] has been successfully created !");
} }
private void OnCommandFileLoaded(string path) private void OnCommandFileLoaded(LoaderArgs e)
{ {
if (path != null) if (e.IsLoaded) Functions.WriteLogFile($"[CMD] Command from file [{e.PluginName}] has been successfully loaded !");
Functions.WriteLogFile($"[CMD] Command from file [{path}] has been successfully loaded !");
} }
private void OnEventLoaded(string typename, bool success, DBEvent eve, Exception exception) private void OnEventLoaded(LoaderArgs e)
{ {
if (eve != null && success) if (e.IsLoaded) { ((DBEvent)e.Plugin!).Start(_client); }
eve.Start(client);
if (onEVELoad != null) if (onEVELoad != null) onEVELoad.Invoke(((DBEvent)e.Plugin!).name, e.TypeName!, e.IsLoaded, e.Exception);
onEVELoad.Invoke(eve!.name, typename, success, exception);
} }
private void OnCommandLoaded(string name, bool success, DBCommand command, Exception exception) private void OnCommandLoaded(LoaderArgs e)
{ {
if (onCMDLoad != null) if (onCMDLoad != null) onCMDLoad.Invoke(((DBCommand)e.Plugin!).Command, e.TypeName!, e.IsLoaded, e.Exception);
onCMDLoad.Invoke(command.Command, name, success, exception);
} }
} }
} }

View File

@@ -1,9 +1,5 @@
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
{ {
@@ -14,17 +10,20 @@ 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 async void Update(int progress, double speed = -1, string? unit = null) public void Update(int progress, double speed = -1, string? unit = null)
{ {
//progress bar //progress bar
@@ -39,8 +38,8 @@ namespace PluginManager.Others
for (int i = 0; i < onechunk * progress; i++) for (int i = 0; i < onechunk * progress; i++)
{ {
Console.BackgroundColor = ConsoleColor.Green; Console.BackgroundColor = this.Color;
Console.CursorLeft = position++; Console.CursorLeft = position++;
Console.Write(" "); Console.Write(" ");
} }
@@ -130,11 +129,12 @@ namespace PluginManager.Others
ConsoleColor fg = Console.ForegroundColor; ConsoleColor fg = Console.ForegroundColor;
Dictionary<string, ConsoleColor> colors = new Dictionary<string, ConsoleColor>() Dictionary<string, ConsoleColor> colors = new Dictionary<string, ConsoleColor>()
{ {
{"&g", ConsoleColor.Green }, { "&g", ConsoleColor.Green },
{"&b", ConsoleColor.Blue }, { "&b", ConsoleColor.Blue },
{"&r", ConsoleColor.Red }, { "&r", ConsoleColor.Red },
{"&m", ConsoleColor.Magenta }, { "&m", ConsoleColor.Magenta },
{"&c", fg } { "&y", ConsoleColor.Yellow },
{ "&c", fg }
}; };
foreach (string word in words) foreach (string word in words)
{ {
@@ -145,7 +145,9 @@ namespace PluginManager.Others
Console.ForegroundColor = colors[prefix]; Console.ForegroundColor = colors[prefix];
} }
string m = word.Replace("&g", "").Replace("&b", "").Replace("&r", "").Replace("&c", "").Replace("&m", ""); string m = word;
foreach (var key in colors.Keys) { m = m.Replace(key, ""); }
Console.Write(m + " "); Console.Write(m + " ");
} }
if (appendNewLine) if (appendNewLine)

View File

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

View File

@@ -19,10 +19,4 @@
<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>