Removed plugins from the project and reworked the Plugin Manager

This commit is contained in:
Wizzy69
2023-04-29 19:35:19 +03:00
parent 0dc8cdbce5
commit bcef58a46b
17 changed files with 83 additions and 861 deletions

49
.vscode/launch.json vendored
View File

@@ -1,48 +1,6 @@
{ {
"version": "0.2.0", "version": "0.2.0",
"configurations": [ "configurations": [
{
"name": ".NET Core Watch (web)",
"type": "coreclr",
"request": "launch",
"preLaunchTask": "watch",
"program": "${workspaceFolder}/DiscordBotPlugins/DiscordBotUI/bin/Debug/net6.0/DiscordBotUI.dll",
"args": [],
"cwd": "${workspaceFolder}/DiscordBotPlugins/DiscordBotUI/bin/Debug/net6.0",
"stopAtEntry": false,
"console": "externalTerminal",
"serverReadyAction": {
"action": "openExternally",
"pattern": "\\bNow listening on:\\s+(https?://\\S+)"
},
"env": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"sourceFileMap": {
"/Views": "${workspaceFolder}/Views"
}
},
{
"name": ".NET Core Launch (web)",
"type": "coreclr",
"request": "launch",
"preLaunchTask": "buildUI",
"program": "${workspaceFolder}/DiscordBotPlugins/DiscordBotUI/bin/Debug/net6.0/DiscordBotUI.dll",
"args": [],
"cwd": "${workspaceFolder}/DiscordBotPlugins/DiscordBotUI/bin/Debug/net6.0",
"stopAtEntry": false,
"console": "externalTerminal",
"serverReadyAction": {
"action": "openExternally",
"pattern": "\\bNow listening on:\\s+(https?://\\S+)"
},
"env": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"sourceFileMap": {
"/Views": "${workspaceFolder}/Views"
}
},
{ {
// Use IntelliSense to find out which attributes exist for C# debugging // Use IntelliSense to find out which attributes exist for C# debugging
// Use hover for the description of the existing attributes // Use hover for the description of the existing attributes
@@ -54,10 +12,15 @@
// If you have changed target frameworks, make sure to update the program path. // If you have changed target frameworks, make sure to update the program path.
"program": "${workspaceFolder}/DiscordBot/bin/Debug/net6.0/DiscordBot.dll", "program": "${workspaceFolder}/DiscordBot/bin/Debug/net6.0/DiscordBot.dll",
"args": [], "args": [],
"cwd": "${workspaceFolder}/DiscordBot/bin/Debug/net6.0", "cwd": "${workspaceFolder}/DiscordBot/bin/Debug/net6.0/",
// For more information about the 'console' field, see https://aka.ms/VSCode-CS-LaunchJson-Console // For more information about the 'console' field, see https://aka.ms/VSCode-CS-LaunchJson-Console
"console": "externalTerminal", "console": "externalTerminal",
"stopAtEntry": false "stopAtEntry": false
},
{
"name": ".NET Core Attach",
"type": "coreclr",
"request": "attach"
} }
] ]
} }

52
.vscode/tasks.json vendored
View File

@@ -1,34 +1,6 @@
{ {
"version": "2.0.0", "version": "2.0.0",
"tasks": [ "tasks": [
{
"label": "watch",
"command": "dotnet",
"type": "process",
"args": [
"watch",
"run",
"--project",
"${workspaceFolder}/DiscordBotPlugins/DiscordBotUI/DiscordBotUI.csproj",
"/property:GenerateFullPaths=true",
"/consoleloggerparameters:NoSummary"
],
"problemMatcher": "$msCompile",
"options": {
"cwd": "${workspaceFolder}/DiscordBotPlugins/DiscordBotUI/bin/Debug/net6.0",
"env": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"sourceFileMap": {
"/Views": "${workspaceFolder}/Views"
},
"serverReadyAction": {
"action": "openExternally",
"pattern": "\\bNow listening on:\\s+(https?://\\S+)"
},
"console": "externalTerminal"
}
},
{ {
"label": "build", "label": "build",
"command": "dotnet", "command": "dotnet",
@@ -41,18 +13,6 @@
], ],
"problemMatcher": "$msCompile" "problemMatcher": "$msCompile"
}, },
{
"label": "buildUI",
"command": "dotnet",
"type": "process",
"args": [
"build",
"${workspaceFolder}/DiscordBotPlugins/DiscordBotUI/DiscordBotUI.csproj",
"/property:GenerateFullPaths=true",
"/consoleloggerparameters:NoSummary"
],
"problemMatcher": "$msCompile"
},
{ {
"label": "publish", "label": "publish",
"command": "dotnet", "command": "dotnet",
@@ -64,6 +24,18 @@
"/consoleloggerparameters:NoSummary" "/consoleloggerparameters:NoSummary"
], ],
"problemMatcher": "$msCompile" "problemMatcher": "$msCompile"
},
{
"label": "watch",
"command": "dotnet",
"type": "process",
"args": [
"watch",
"run",
"--project",
"${workspaceFolder}/DiscordBot/DiscordBot.csproj"
],
"problemMatcher": "$msCompile"
} }
] ]
} }

View File

@@ -11,7 +11,6 @@ using PluginManager.Bot;
using PluginManager.Online; using PluginManager.Online;
using PluginManager.Online.Helpers; using PluginManager.Online.Helpers;
using PluginManager.Others; using PluginManager.Others;
using PluginManager.WindowManagement;
using DiscordBot.Utilities; using DiscordBot.Utilities;
@@ -39,7 +38,7 @@ public class Program
Config.Data["prefix"]?.Length != 1 || Config.Data["prefix"]?.Length != 1 ||
(args.Length == 1 && args[0] == "/reset")) (args.Length == 1 && args[0] == "/reset"))
{ {
GenerateStartUI(); GenerateStartupConfig();
} }
HandleInput(args).Wait(); HandleInput(args).Wait();
@@ -84,11 +83,11 @@ public class Program
"https://raw.githubusercontent.com/Wizzy69/installer/discord-bot-files/StartupMessage"); "https://raw.githubusercontent.com/Wizzy69/installer/discord-bot-files/StartupMessage");
foreach (var message in startupMessageList) foreach (var message in startupMessageList)
Config.Logger.Log(message); Console.WriteLine(message);
Logger.WriteLine( Console.WriteLine(
$"Running on version: {Assembly.GetExecutingAssembly().GetName().Version}"); $"Running on version: {Assembly.GetExecutingAssembly().GetName().Version}");
Logger.WriteLine($"Git URL: {Config.Data["GitURL"]}"); Console.WriteLine($"Git URL: {Config.Data["GitURL"]}");
Utilities.Utilities.WriteColorText( Utilities.Utilities.WriteColorText(
"&rRemember to close the bot using the ShutDown command (&ysd&r) or some settings won't be saved\n"); "&rRemember to close the bot using the ShutDown command (&ysd&r) or some settings won't be saved\n");
@@ -101,9 +100,8 @@ public class Program
Utilities.Utilities.WriteColorText( Utilities.Utilities.WriteColorText(
"Please note that the bot saves a backup save file every time you are using the shudown command (&ysd&c)"); "Please note that the bot saves a backup save file every time you are using the shudown command (&ysd&c)");
Logger.WriteLine(); Console.WriteLine("Running on " + Functions.GetOperatingSystem().ToString());
Logger.WriteLine("Running on " + Functions.GetOperatingSystem().ToString()); Console.WriteLine("============================ LOG ============================");
Logger.WriteLine("============================ LOG ============================");
try try
{ {
@@ -121,7 +119,7 @@ public class Program
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.LogError(ex); Config.Logger.Log(ex.ToString(),"Bot",TextType.ERROR);
return null; return null;
} }
} }
@@ -137,16 +135,6 @@ public class Program
var b = await StartNoGui(); var b = await StartNoGui();
consoleCommandsHandler = new ConsoleCommandsHandler(b.client); consoleCommandsHandler = new ConsoleCommandsHandler(b.client);
if (len > 0 && args[0] == "/remplug")
{
var plugName = string.Join(' ', args, 1, args.Length - 1);
Logger.WriteLine("Starting to remove " + plugName);
await ConsoleCommandsHandler.ExecuteCommad("remplug " + plugName);
loadPluginsOnStartup = true;
}
var mainThread = new Thread(() => var mainThread = new Thread(() =>
{ {
try try
@@ -160,7 +148,7 @@ public class Program
if (Config.Data.ContainsKey("LaunchMessage")) if (Config.Data.ContainsKey("LaunchMessage"))
Config.Data.Add("LaunchMessage", Config.Data.Add("LaunchMessage",
"An error occured while closing the bot last time. Please consider closing the bot using the &rsd&c method !\nThere is a risk of losing all data or corruption of the save file, which in some cases requires to reinstall the bot !"); "An error occured while closing the bot last time. Please consider closing the bot using the &rsd&c method !\nThere is a risk of losing all data or corruption of the save file, which in some cases requires to reinstall the bot !");
Logger.WriteErrFile(ex.ToString()); Config.Logger.Log("An error occured while closing the bot last time. Please consider closing the bot using the &rsd&c method !\nThere is a risk of losing all data or corruption of the save file, which in some cases requires to reinstall the bot !","Bot",TextType.ERROR);
} }
} }
}); });
@@ -169,10 +157,12 @@ public class Program
private static async Task PreLoadComponents(string[] args) private static async Task PreLoadComponents(string[] args)
{ {
await Config.Initialize(true); await Config.Initialize();
Config.Logger.LogEvent += (message, type) => { Console.WriteLine(message); };
Logger.WriteLine("Loading resources ..."); Console.WriteLine("Loading resources ...");
var main = new Utilities.Utilities.ProgressBar(ProgressBarType.NO_END); var main = new Utilities.Utilities.ProgressBar(ProgressBarType.NO_END);
main.Start(); main.Start();
@@ -197,7 +187,7 @@ public class Program
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.WriteErrFile(ex.Message); Config.Logger.Log(ex.ToString(),"Bot",TextType.ERROR);
} }
} }
@@ -225,14 +215,14 @@ public class Program
Config.Data["Version"] = "1." + cVer.ToShortString() + " (Beta)"; Config.Data["Version"] = "1." + cVer.ToShortString() + " (Beta)";
break; break;
} }
if (OperatingSystem.WINDOWS == Functions.GetOperatingSystem()) if (OperatingSystem.WINDOWS == Functions.GetOperatingSystem())
{ {
Console.Clear(); Console.Clear();
Logger.WriteLine("A new update was found !"); Console.WriteLine("A new update was found !");
Logger.WriteLine("Run the launcher to update"); Console.WriteLine("Run the launcher to update");
Logger.WriteLine("Current version: " + currentVersion); Console.WriteLine("Current version: " + currentVersion);
Logger.WriteLine("Latest version: " + s[1]); Console.WriteLine("Latest version: " + s[1]);
File.WriteAllText("version.txt", currentVersion); File.WriteAllText("version.txt", currentVersion);
@@ -243,54 +233,51 @@ public class Program
Console.Clear(); Console.Clear();
Console.ForegroundColor = ConsoleColor.Red; Console.ForegroundColor = ConsoleColor.Red;
Logger.WriteLine("A new version of the bot is available !"); Console.WriteLine("A new version of the bot is available !");
Console.ForegroundColor = ConsoleColor.Yellow; Console.ForegroundColor = ConsoleColor.Yellow;
Logger.WriteLine("Current version : " + Console.WriteLine("Current version : " +
Assembly.GetExecutingAssembly().GetName().Version.ToString()); Assembly.GetExecutingAssembly().GetName().Version.ToString());
Console.ForegroundColor = ConsoleColor.Green; Console.ForegroundColor = ConsoleColor.Green;
Logger.WriteLine("New version : " + newVersion); Console.WriteLine("New version : " + newVersion);
Console.ForegroundColor = ConsoleColor.White; Console.ForegroundColor = ConsoleColor.White;
File.WriteAllText("version.txt", newVersion); File.WriteAllText("version.txt", newVersion);
Logger.WriteLine("Changelog :"); Console.WriteLine("Changelog :");
List<string> changeLog = await ServerCom.ReadTextFromURL( List<string> changeLog = await ServerCom.ReadTextFromURL(
"https://raw.githubusercontent.com/Wizzy69/installer/discord-bot-files/VersionData/DiscordBot"); "https://raw.githubusercontent.com/Wizzy69/installer/discord-bot-files/VersionData/DiscordBot");
foreach (var item in changeLog) foreach (var item in changeLog)
Utilities.Utilities.WriteColorText(item); Utilities.Utilities.WriteColorText(item);
Logger.WriteLine("Do you want to update the bot ? (y/n)"); Console.WriteLine("Do you want to update the bot ? (y/n)");
if (Console.ReadKey().Key == ConsoleKey.Y) if (Console.ReadKey().Key == ConsoleKey.Y)
{ {
var url = var url =
$"https://github.com/Wizzy69/SethDiscordBot/releases/download/v{newVersion}/net6.0_linux.zip"; $"https://github.com/Wizzy69/SethDiscordBot/releases/download/v{newVersion}/net6.0_linux.zip";
if (Logger.isConsole) Config.Logger.Log($"executing: download_file {url}");
Console.SetCursorPosition(0, Console.CursorTop);
Logger.WriteLine($"executing: download_file {url}");
await ServerCom.DownloadFileAsync(url, "./update.zip", new Progress<float>(percent => { Logger.Write($"\rProgress: {percent}% "); })); await ServerCom.DownloadFileAsync(url, "./update.zip", new Progress<float>(percent => { Console.WriteLine($"\rProgress: {percent}% "); }));
await File.WriteAllTextAsync("Install.sh", await File.WriteAllTextAsync("Install.sh",
"#!/bin/bash\nunzip -qq -o update.zip \nrm update.zip\nchmod a+x DiscordBot"); "#!/bin/bash\nunzip -qq -o update.zip \nrm update.zip\nchmod a+x DiscordBot");
Logger.WriteLine();
try try
{ {
Logger.WriteLine("executing: chmod a+x Install.sh"); Console.WriteLine("executing: chmod a+x Install.sh");
Process.Start("chmod", "a+x Install.sh").WaitForExit(); Process.Start("chmod", "a+x Install.sh").WaitForExit();
Process.Start("Install.sh").WaitForExit(); Process.Start("Install.sh").WaitForExit();
Logger.WriteLine("executing: rm Install.sh"); Console.WriteLine("executing: rm Install.sh");
Process.Start("rm", "Install.sh").WaitForExit(); Process.Start("rm", "Install.sh").WaitForExit();
Logger.WriteLine("The new version of the bot has been installed."); Config.Logger.Log("The new version of the bot has been installed.");
Logger.WriteLine("Please restart the bot."); Console.WriteLine("Please restart the bot.");
Environment.Exit(0); Environment.Exit(0);
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.WriteErrFile(ex.Message); Config.Logger.Log(ex.Message,"Updater", TextType.ERROR);
if (ex.Message.Contains("Access de")) if (ex.Message.Contains("Access de"))
Logger.WriteLine("Please run the bot as root."); Config.Logger.Log("Please run the bot as root.");
} }
@@ -311,7 +298,7 @@ public class Program
!File.Exists("./Launcher.exe")) !File.Exists("./Launcher.exe"))
{ {
Console.Clear(); Console.Clear();
Logger.WriteLine("Installing a new Launcher ...\nDo NOT close the bot during update !"); Console.WriteLine("Installing a new Launcher ...\nDo NOT close the bot during update !");
var bar = new Utilities.Utilities.ProgressBar(ProgressBarType.NO_END); var bar = new Utilities.Utilities.ProgressBar(ProgressBarType.NO_END);
bar.Start(); bar.Start();
await ServerCom.DownloadFileAsync( await ServerCom.DownloadFileAsync(
@@ -332,56 +319,27 @@ public class Program
Console.Clear(); Console.Clear();
} }
public static void GenerateStartUI() public static void GenerateStartupConfig()
{ {
InputBox box = new InputBox(); Console.WriteLine("Welcome to the SethBot installer !");
box.Title = "Discord Bot Config - " + Assembly.GetExecutingAssembly().GetName().Version; Console.WriteLine("First, we need to configure the bot. Don't worry, it will be quick !");
box.Message = "Let's setup the bot. Please go through this setup so that you can run the bot.\n\n"; Console.WriteLine("The following information will be stored in the config.json file in the ./Data/Resources folder. You can change it later from there.");
box.AddLabel("Note:All the information collected here will only be stored locally (on your machine) at the following path: ", TextType.WARNING); Console.WriteLine("The bot tokn is required to run the bot. You can get it from the Discord Developer Portal. (https://discord.com/developers/applications)");
box.AddLabel("<executable path>/Data/Resources/Config.json", TextType.SUCCESS); Console.WriteLine("Please enter the bot token :");
var token = Console.ReadLine();
box.AddOption("Bot Token", (token) => { Console.WriteLine("Please enter the bot prefix :");
if (token.Length != 70 && token.Length != 59) var prefix = Console.ReadLine();
{
Console.WriteLine("The token is invalid !");
return false;
}
return true; Console.WriteLine("Please enter the Server ID :");
}); var serverId = Console.ReadLine();
box.AddOption("Bot prefix (should be one character long)", (prefix) => { Config.Data.Add("token", token);
if (int.TryParse(prefix, out int value)) Config.Data.Add("prefix", prefix);
{ Config.Data.Add("ServerID", serverId);
Console.WriteLine("The prefix can not be a number");
return false;
}
if (prefix.Length != 1) Config.Logger.Log("Config Saved", "Installer", TextType.NORMAL);
{
Console.WriteLine("The bot does not support longer prefixes");
return false;
}
return true; Config.Data.Save();
});
box.AddOption("Server ID (Optional => Press ENTER to leave empty)\nIf you let the Server ID field option empty, some plugins may not work", (servId) => {
if (servId.Length != 18 && servId.Length > 0)
{
Console.WriteLine("The Server ID is invalid");
return false;
}
return true;
});
List<string> result = box.Show();
Config.Data.Add("ServerID", result[2]);
Config.Data.Add("token", result[0]);
Config.Data.Add("prefix", result[1]);
} }
} }

View File

@@ -34,9 +34,6 @@ public class ConsoleCommandsHandler
{ {
this.client = client; this.client = client;
InitializeBasicCommands(); InitializeBasicCommands();
//Console.WriteLine("Initialized console command handler !");
} }
private void InitializeBasicCommands() private void InitializeBasicCommands()
@@ -209,6 +206,7 @@ public class ConsoleCommandsHandler
if (OperatingSystem.WINDOWS == Functions.GetOperatingSystem()) if (OperatingSystem.WINDOWS == Functions.GetOperatingSystem())
{ {
await ServerCom.DownloadFileAsync(info[1], path, null); await ServerCom.DownloadFileAsync(info[1], path, null);
Console.WriteLine("Plugin Downloaded !", this, TextType.SUCCESS);
} }
else if (OperatingSystem.LINUX == Functions.GetOperatingSystem()) else if (OperatingSystem.LINUX == Functions.GetOperatingSystem())
{ {
@@ -218,6 +216,8 @@ public class ConsoleCommandsHandler
bar.Stop("Plugin Downloaded !"); bar.Stop("Plugin Downloaded !");
} }
Console.WriteLine("\n"); Console.WriteLine("\n");
@@ -239,6 +239,7 @@ public class ConsoleCommandsHandler
if (OperatingSystem.WINDOWS == Functions.GetOperatingSystem()) if (OperatingSystem.WINDOWS == Functions.GetOperatingSystem())
{ {
await ServerCom.DownloadFileAsync(split[0], "./" + split[1], null); await ServerCom.DownloadFileAsync(split[0], "./" + split[1], null);
Console.WriteLine("Item "+split[1]+" downloaded !", this, TextType.SUCCESS);
} }
else if (OperatingSystem.LINUX == Functions.GetOperatingSystem()) else if (OperatingSystem.LINUX == Functions.GetOperatingSystem())
{ {
@@ -276,6 +277,8 @@ public class ConsoleCommandsHandler
isDownloading = false; isDownloading = false;
Config.Logger.Log("Plugin installed !", this, TextType.SUCCESS);
//await ExecuteCommad("localload " + name); //await ExecuteCommad("localload " + name);
} }
); );
@@ -330,6 +333,8 @@ public class ConsoleCommandsHandler
await Functions.SaveToJsonFile(Functions.dataFolder + "Plugins.json", Config.Plugins); await Functions.SaveToJsonFile(Functions.dataFolder + "Plugins.json", Config.Plugins);
await client.StopAsync(); await client.StopAsync();
await client.DisposeAsync(); await client.DisposeAsync();
Config.Logger.SaveToFile();
await Task.Delay(1000); await Task.Delay(1000);
Environment.Exit(0); Environment.Exit(0);
} }
@@ -378,89 +383,7 @@ public class ConsoleCommandsHandler
} }
}); });
AddCommand("remplug", "Remove a plugin", "remplug [plugName]", async args =>
{
if (args.Length <= 1) return;
isDownloading = true;
var plugName = string.Join(' ', args, 1, args.Length - 1);
if (pluginsLoaded)
{
if (Functions.GetOperatingSystem() == OperatingSystem.WINDOWS)
{
Process.Start("DiscordBot.exe", $"/remplug {plugName}");
await Task.Delay(100);
Environment.Exit(0);
}
else
{
Process.Start("./DiscordBot", $"/remplug {plugName}");
await Task.Delay(100);
Environment.Exit(0);
}
isDownloading = false;
return;
}
var location = $"./Data/Plugins/{plugName}.dll";
if (!File.Exists(location))
{
Console.WriteLine("The plugin does not exist");
return;
}
File.Delete(location);
Console.WriteLine("Removed the plugin DLL. Checking for other files ...");
var info = await manager.GetPluginLinkByName(plugName);
if (info[2] != string.Empty)
{
var lines = await ServerCom.ReadTextFromURL(info[2]);
foreach (var line in lines)
{
if (!(line.Length > 0 && line.Contains(",")))
continue;
var split = line.Split(',');
if (File.Exists("./" + split[1]))
File.Delete("./" + split[1]);
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);
}
isDownloading = false;
Console.WriteLine(plugName + " has been successfully deleted !");
});
AddCommand("reload", "Reload the bot with all plugins", () =>
{
if (Functions.GetOperatingSystem() == OperatingSystem.WINDOWS)
{
Process.Start("DiscordBot.exe", "lp");
HandleCommand("sd");
}
else
{
//HandleCommand("sd");
Console.WriteLine("This command can not be used outside of Windows yet. Please restart the bot using the manual way");
}
});
//AddCommand("");
//Sort the commands by name
commandList.Sort((x, y) => x.CommandName.CompareTo(y.CommandName)); commandList.Sort((x, y) => x.CommandName.CompareTo(y.CommandName));
} }
@@ -492,20 +415,6 @@ public class ConsoleCommandsHandler
return commandList.FirstOrDefault(t => t.CommandName == command); return commandList.FirstOrDefault(t => t.CommandName == command);
} }
/* public static async Task ExecuteSpecialCommand(string command)
{
if (!command.StartsWith("_")) return;
string[] args = command.Split(' ');
foreach (var item in commandList)
if (item.CommandName == args[0])
{
Console.WriteLine();
item.Action(args);
}
}*/
public static async Task ExecuteCommad(string command) public static async Task ExecuteCommad(string command)
{ {
var args = command.Split(' '); var args = command.Split(' ');

View File

@@ -1,72 +0,0 @@
using Discord;
using PluginManager.Interfaces;
using Discord.WebSocket;
namespace Economy.Commands;
public class Balance : DBSlashCommand
{
public string Name => "balance";
public string Description => "Change or view info about your balance";
public bool canUseDM => false; // server only
public List<SlashCommandOptionBuilder> Options => new List<SlashCommandOptionBuilder>()
{
new SlashCommandOptionBuilder(){Name="send", Description="Send money to another user", Type=ApplicationCommandOptionType.SubCommand, Options=new List<SlashCommandOptionBuilder>()
{
new SlashCommandOptionBuilder(){Name="user", Description="The user to send money to", Type=ApplicationCommandOptionType.User, IsRequired=true},
new SlashCommandOptionBuilder(){Name="amount", Description="The amount of money to send", Type=ApplicationCommandOptionType.Number, IsRequired=true}
}},
new SlashCommandOptionBuilder(){Name="info", Description="View info about your balance", Type=ApplicationCommandOptionType.SubCommand}
};
public async void ExecuteServer(SocketSlashCommand context)
{
var option = context.Data.Options.FirstOrDefault();
var guild = context.User.MutualGuilds.FirstOrDefault(g => g.Id == context.GuildId);
if (option.Name == "send")
{
var options = option.Options.ToArray();
Console.WriteLine(options.Length);
var user = options[0].Value as IUser;
var amount = options[1].Value as float?;
if (amount == null)
{
await context.RespondAsync("The amount is invalid");
return;
}
if (user == null)
{
await context.RespondAsync("The user is invalid");
return;
}
if (user.Id == context.User.Id)
{
await context.RespondAsync("You can't send money to yourself");
return;
}
var balance = await Engine.GetBalance(context.User.Id);
if (balance < amount)
{
await context.RespondAsync("You don't have enough money to send");
return;
}
await Engine.RemoveMoney(context.User.Id, amount.Value);
await Engine.AddMoney(user.Id, amount.Value);
await context.RespondAsync($"You sent {amount} to {guild.GetUser(user.Id).Mention}");
}
else if (option.Name == "info")
{
var balance = await Engine.GetBalance(context.User.Id);
await context.RespondAsync($"Your balance is {balance}");
}
}
}

View File

@@ -1,10 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<ItemGroup>
<ProjectReference Include="..\..\PluginManager\PluginManager.csproj" />
</ItemGroup>
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>

View File

@@ -1,62 +0,0 @@
using System;
using System.Collections.Generic;
using PluginManager.Database;
namespace Economy;
public static class Engine
{
public static SqlDatabase Database { get; set; }
public static async void AddUser(ulong userID)
{
await Database.InsertAsync("UserBank", userID.ToString(), "0");
}
public static async void RemoveUser(ulong userID)
{
await Database.RemoveKeyAsync("UserBank", "UserID", userID.ToString());
}
public static async Task AddMoney(ulong userID, float amount)
{
var balance = await Database.GetValueAsync("UserBank", "UserID", userID.ToString(), "Balance");
if (balance == null)
{
AddUser(userID);
balance = "0";
}
var float_balance = float.Parse(balance);
float_balance += amount;
await Database.SetValueAsync("UserBank", "UserID", userID.ToString(), "Balance", float_balance.ToString());
}
public static async Task RemoveMoney(ulong userID, float amount)
{
var balance = await Database.GetValueAsync("UserBank", "UserID", userID.ToString(), "Balance");
if (balance == null)
{
AddUser(userID);
balance = "0";
}
var float_balance = float.Parse(balance);
float_balance -= amount;
await Database.SetValueAsync("UserBank", "UserID", userID.ToString(), "Balance", float_balance.ToString());
}
public static async Task<float> GetBalance(ulong userID)
{
var balance = await Database.GetValueAsync("UserBank", "UserID", userID.ToString(), "Balance");
if (balance == null)
{
AddUser(userID);
balance = "0";
}
return float.Parse(balance);
}
}

View File

@@ -1,31 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using PluginManager.Interfaces;
using PluginManager.Database;
namespace Economy
{
public class EntryEvent : DBEvent
{
public string Name => "Economy Plugin Engine";
public string Description => "The economy plugin main engine";
public async void Start(global::Discord.WebSocket.DiscordSocketClient client)
{
Console.WriteLine("Economy Plugin Engine Started");
Directory.CreateDirectory(PluginManager.Others.Functions.dataFolder + "/Economy");
Engine.Database = new SqlDatabase(PluginManager.Others.Functions.dataFolder + "/Economy/Economy.db");
await Engine.Database.Open();
await Engine.Database.CreateTableAsync("UserBank", "UserID INT", "Balance FLOAT");
client.Disconnected += (e) =>
{
Engine.Database.Stop();
return Task.CompletedTask;
};
}
}
}

View File

@@ -61,9 +61,7 @@ internal class CommandHandler
} }
catch (Exception ex) catch (Exception ex)
{ {
Config.Logger.Log(ex.Message, "CommandHandler", TextType.ERROR);
Console.WriteLine(ex.ToString());
ex.WriteErrFile();
} }
return Task.CompletedTask; return Task.CompletedTask;

View File

@@ -18,7 +18,7 @@ public static class Config
public static Json<string, string> Data; public static Json<string, string> Data;
public static Json<string, string> Plugins; public static Json<string, string> Plugins;
public static async Task Initialize(bool isConsole) public static async Task Initialize()
{ {
if (IsLoaded) if (IsLoaded)
return; return;
@@ -26,21 +26,21 @@ public static class Config
Directory.CreateDirectory("./Data/Resources"); Directory.CreateDirectory("./Data/Resources");
Directory.CreateDirectory("./Data/Plugins"); Directory.CreateDirectory("./Data/Plugins");
Directory.CreateDirectory("./Data/PAKS"); Directory.CreateDirectory("./Data/PAKS");
Directory.CreateDirectory("./Data/Logs/Logs");
Directory.CreateDirectory("./Data/Logs/Errors");
Data = new Json<string, string>("./Data/Resources/config.json"); Data = new Json<string, string>("./Data/Resources/config.json");
Plugins = new Json<string, string>("./Data/Resources/Plugins.json"); Plugins = new Json<string, string>("./Data/Resources/Plugins.json");
Logger = new DBLogger(); Config.Data["LogFolder"] = "./Data/Logs/Logs";
Config.Data["ErrorFolder"] = "./Data/Logs/Errors";
PluginManager.Logger.Initialize(isConsole); Logger = new DBLogger();
ArchiveManager.Initialize(); ArchiveManager.Initialize();
IsLoaded = true; IsLoaded = true;
if (isConsole)
PluginManager.Logger.LogEvent += (message) => { Console.Write(message); };
Logger.Log("Config initialized", TextType.NORMAL); Logger.Log("Config initialized", TextType.NORMAL);
} }

View File

@@ -60,9 +60,7 @@ namespace PluginManager.Loaders
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.WriteLine(ex.Message); Config.Logger.Log("PluginName: " + new FileInfo(file).Name.Split('.')[0] + " not loaded", this, Others.TextType.ERROR);
Logger.WriteLine("PluginName: " + new FileInfo(file).Name.Split('.')[0] + " not loaded");
continue; continue;
} }
if (FileLoaded != null) if (FileLoaded != null)
@@ -133,7 +131,7 @@ namespace PluginManager.Loaders
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.WriteErrFile(ex.ToString()); Config.Logger.Log(ex.Message, this, Others.TextType.ERROR);
return null; return null;
} }

View File

@@ -1,182 +0,0 @@
using System;
using System.IO;
using System.Numerics;
using PluginManager.Others;
using Discord;
namespace PluginManager
{
[Obsolete("Use Logger from PluginManager.Others.Logger namespace instead\nThis class will be removed soon")]
public static class Logger
{
public static bool isConsole { get; private set; }
private static bool isInitialized;
private static string? logFolder;
private static string? errFolder;
public static void Initialize(bool console)
{
if (isInitialized)
throw new Exception("Logger is already initialized");
if (!Config.Data.ContainsKey("LogFolder"))
Config.Data.Add("LogFolder", "./Data/Output/Logs/");
if (!Config.Data.ContainsKey("ErrorFolder"))
Config.Data.Add("ErrorFolder", "./Data/Output/Errors/");
isInitialized = true;
logFolder = Config.Data["LogFolder"];
errFolder = Config.Data["ErrorFolder"];
isConsole = console;
}
public delegate void LogEventHandler(string Message);
public static event LogEventHandler LogEvent;
public static void Log(string Message)
{
if (!isInitialized) throw new Exception("Logger is not initialized");
LogEvent?.Invoke(Message);
}
public static void Log(string Message, params object[] Args)
{
if (!isInitialized) throw new Exception("Logger is not initialized");
LogEvent?.Invoke(string.Format(Message, Args));
}
public static void Log(IMessage message, bool newLine)
{
if (!isInitialized) throw new Exception("Logger is not initialized");
LogEvent?.Invoke(message.Content);
if (newLine)
LogEvent?.Invoke("\n");
}
public static void WriteLine(string? message)
{
if (!isInitialized) throw new Exception("Logger is not initialized");
if (message is not null)
LogEvent?.Invoke(message + '\n');
}
public static void LogError(System.Exception ex)
{
if (!isInitialized) throw new Exception("Logger is not initialized");
string message = "[ERROR]" + ex.Message;
LogEvent?.Invoke(message + '\n');
}
public static void LogError(string? message)
{
if (!isInitialized) throw new Exception("Logger is not initialized");
if (message is not null)
LogEvent?.Invoke("[ERROR]" + message + '\n');
}
public static void WriteLine()
{
if (!isInitialized) throw new Exception("Logger is not initialized");
LogEvent?.Invoke("\n");
}
public static void Write(string message)
{
if (!isInitialized) throw new Exception("Logger is not initialized");
LogEvent?.Invoke(message);
}
public static void Write<T>(T c)
{
if (!isInitialized) throw new Exception("Logger is not initialized");
LogEvent?.Invoke($"{c}");
}
public static void Write<T>(T c, params object[] Args)
{
if (!isInitialized) throw new Exception("Logger is not initialized");
LogEvent?.Invoke(string.Format($"{c}", Args));
}
public static void WriteColored(string message, ConsoleColor color)
{
if (!isInitialized) throw new Exception("Logger is not initialized");
if (!isConsole)
{
LogEvent?.Invoke(message);
return;
}
var oldColor = Console.ForegroundColor;
Console.ForegroundColor = color;
LogEvent?.Invoke(message);
Console.ForegroundColor = oldColor;
}
public static void SetConsoleColor(TextType type)
{
if(!isConsole) return;
switch (type)
{
case TextType.NORMAL:
Console.ForegroundColor = ConsoleColor.White;
break;
case TextType.ERROR:
Console.ForegroundColor = ConsoleColor.Red;
break;
case TextType.WARNING:
Console.ForegroundColor = ConsoleColor.Yellow;
break;
case TextType.SUCCESS:
Console.ForegroundColor = ConsoleColor.Green;
break;
default:
Console.ForegroundColor = ConsoleColor.White;
break;
}
}
public static void ResetConsoleColor()
{
if (!isConsole) return;
Console.ForegroundColor = ConsoleColor.White;
}
/// <summary>
/// Write logs to file
/// </summary>
/// <param name="LogMessage">The message to be wrote</param>
public static void WriteLogFile(string LogMessage)
{
if (!isInitialized) throw new Exception("Logger is not initialized");
var logsPath = logFolder + $"{DateTime.Today.ToShortDateString().Replace("/", "-").Replace("\\", "-")} Log.txt";
Directory.CreateDirectory(logFolder);
File.AppendAllText(logsPath, $"[{DateTime.Today.ToShortTimeString()}] {LogMessage} \n");
}
/// <summary>
/// Write error to file
/// </summary>
/// <param name="ErrMessage">The message to be wrote</param>
public static void WriteErrFile(string ErrMessage)
{
if (!isInitialized) throw new Exception("Logger is not initialized");
var errPath = errFolder +
$"{DateTime.Today.ToShortDateString().Replace("/", "-").Replace("\\", "-")} Error.txt";
Directory.CreateDirectory(errFolder);
File.AppendAllText(errPath, $"[{DateTime.Today.ToShortTimeString()}] {ErrMessage} \n");
}
public static void WriteErrFile(this Exception ex)
{
if (!isInitialized) throw new Exception("Logger is not initialized");
WriteErrFile(ex.ToString());
}
}
}

View File

@@ -1,15 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace PluginManager.WindowManagement.Controls
{
public class ConsoleOption
{
public string Text { get; set; }
public byte Index { get; set; }
public Action Action { get; set; }
}
}

View File

@@ -1,47 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using PluginManager.Others;
namespace PluginManager.WindowManagement.Controls
{
public class Label
{
public string Text { get; set; }
public TextType Type { get; set; } = TextType.NORMAL;
public void Show()
{
Logger.SetConsoleColor(Type);
Console.WriteLine(Text);
Logger.ResetConsoleColor();
}
public void Show(int x, int y)
{
Logger.SetConsoleColor(Type);
Console.SetCursorPosition(x, y);
Console.WriteLine(Text);
Logger.ResetConsoleColor();
}
public void Show(int x, int y, ConsoleColor color)
{
Console.SetCursorPosition(x, y);
Console.ForegroundColor = color;
Console.WriteLine(Text);
Console.ResetColor();
}
public void Show(int x, int y, ConsoleColor color, ConsoleColor background)
{
Console.SetCursorPosition(x, y);
Console.ForegroundColor = color;
Console.BackgroundColor = background;
Console.WriteLine(Text);
Console.ResetColor();
}
}
}

View File

@@ -1,26 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace PluginManager.WindowManagement.Controls
{
public class TextBox
{
public Label Label { get; set; }
public string Text { get; private set; }
public Func<string, bool> IsValid { get; set; }
public bool SetText(string text)
{
if(IsValid(text))
{
Text = text;
return true;
}
return false;
}
}
}

View File

@@ -1,61 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using PluginManager.WindowManagement.Controls;
using PluginManager.Others;
namespace PluginManager.WindowManagement
{
public class InputBox
{
public string Title { get; set; }
public string Message { get; set; }
private List<TextBox> options = new List<TextBox>();
private List<Label> labels = new List<Label>();
private string InputStr = "=> ";
public List<string> Show()
{
List<string> result = new List<string>();
Console.Clear();
Console.WriteLine(Title);
Console.WriteLine(Message);
foreach (var label in labels)
label.Show();
foreach (var option in options)
{
option.Label.Show();
while (true)
{
Console.Write(InputStr);
if(option.SetText(Console.ReadLine()))
{
result.Add(option.Text);
break;
}
}
}
return result;
}
public void AddOption(string text, Func<string, bool> isValid)
{
options.Add(new TextBox() { Label = new Label() {Text = text}, IsValid = isValid });
}
public void AddLabel(string text, TextType type)
{
labels.Add(new Label() {Text = text, Type = type});
}
}
}

View File

@@ -1,70 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using PluginManager.WindowManagement.Controls;
namespace PluginManager.WindowManagement
{
public class MessageBox
{
public string Title { get; set; }
public string Message { get; set; }
private List<ConsoleOption> options = new List<ConsoleOption>();
public int OptionsCount {get => options.Count;}
public MessageBox(string title, string message)
{
Title = title;
Message = message;
}
public void AddOption(string text, Action action)
{
options.Add(new ConsoleOption() { Text = text, Index = (byte)(options.Count+1), Action = action});
}
public void AddRangeOptions(List<string> texts, List<Action> actions)
{
for (int i = 0; i < texts.Count; i++)
{
options.Add(new ConsoleOption() { Text = texts[i], Index = (byte)(options.Count + 1), Action = actions[i] });
}
}
public int Show()
{
Console.Clear();
Console.WriteLine(Title);
Console.WriteLine(Message);
foreach (var option in options)
{
Console.WriteLine($"{option.Index}. {option.Text}");
}
if(options.Count == 0)
{
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
return 0;
}
if(int.TryParse(Console.ReadLine(), out int result))
{
if(result > 0 && result <= options.Count)
{
if(options[result - 1].Action != null)
options[result - 1].Action();
return result;
}
}
return -1;
}
}
}