patch (database & slash commands)

This commit is contained in:
2022-11-02 15:35:18 +02:00
parent 11ec02ef68
commit e5f3aff39a
15 changed files with 240 additions and 204 deletions

View File

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

View File

@@ -60,7 +60,14 @@ internal class Boot
/// <returns>Task</returns> /// <returns>Task</returns>
public async Task Awake() public async Task Awake()
{ {
var config = new DiscordSocketConfig { AlwaysDownloadUsers = true }; var config = new DiscordSocketConfig
{
AlwaysDownloadUsers = true,
//Disable system clock checkup (for responses at slash commands)
UseInteractionSnowflakeDate = false
};
client = new DiscordSocketClient(config); client = new DiscordSocketClient(config);
service = new CommandService(); service = new CommandService();

View File

@@ -0,0 +1,52 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<Nullable>disable</Nullable>
<ApplicationIcon />
<StartupObject />
<SignAssembly>False</SignAssembly>
<IsPublishable>True</IsPublishable>
<AssemblyVersion>1.0.1.0</AssemblyVersion>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<DebugType>none</DebugType>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
<DebugType>none</DebugType>
</PropertyGroup>
<ItemGroup>
<Compile Remove="Data\**" />
<Compile Remove="obj\**" />
<Compile Remove="Output\**" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Remove="Data\**" />
<EmbeddedResource Remove="obj\**" />
<EmbeddedResource Remove="Output\**" />
</ItemGroup>
<ItemGroup>
<None Remove="Data\**" />
<None Remove="obj\**" />
<None Remove="Output\**" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Discord.Net" Version="3.7.2" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\PluginManager\PluginManager.csproj" />
</ItemGroup>
<Target Name="PostBuild" AfterTargets="PostBuildEvent">
<Exec Command="xcopy /B /Y &quot;$(TargetDir)*.dll&quot; &quot;$(TargetDir)Libraries&quot;" />
</Target>
</Project>

29
DiscordBot/Entry.cs Normal file
View File

@@ -0,0 +1,29 @@
using System;
using System.IO;
using System.Reflection;
namespace DiscordBot
{
public class Entry
{
[STAThread]
public static void Main(string[] args)
{
AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.AssemblyResolve += new ResolveEventHandler(LoadFromSameFolder);
static Assembly LoadFromSameFolder(object sender, ResolveEventArgs args)
{
string folderPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "./Libraries");
string assemblyPath = Path.Combine(folderPath, new AssemblyName(args.Name).Name + ".dll");
if (!File.Exists(assemblyPath)) return null;
Assembly assembly = Assembly.LoadFrom(assemblyPath);
return assembly;
}
Program.Startup(args);
}
}
}

View File

@@ -30,10 +30,9 @@ public class Program
/// The main entry point for the application. /// The main entry point for the application.
/// </summary> /// </summary>
[STAThread] [STAThread]
[Obsolete] public static void Startup(string[] args)
public static void Main(string[] args)
{ {
Console.WriteLine("Loading resources ...");
PreLoadComponents().Wait(); PreLoadComponents().Wait();
if (!Config.Variables.Exists("ServerID") || !Config.Variables.Exists("token") || if (!Config.Variables.Exists("ServerID") || !Config.Variables.Exists("token") ||
@@ -195,7 +194,7 @@ public class Program
private static void NoGUI() private static void NoGUI()
{ {
#if DEBUG #if DEBUG
Console.WriteLine(); Settings.Variables.outputStream.WriteLine();
ConsoleCommandsHandler.ExecuteCommad("lp").Wait(); ConsoleCommandsHandler.ExecuteCommad("lp").Wait();
#else #else
if (loadPluginsOnStartup) consoleCommandsHandler.HandleCommand("lp"); if (loadPluginsOnStartup) consoleCommandsHandler.HandleCommand("lp");
@@ -211,7 +210,7 @@ public class Program
#endif #endif
) && cmd.Length > 0) ) && cmd.Length > 0)
Console.WriteLine("Failed to run command " + cmd); Settings.Variables.outputStream.WriteLine("Failed to run command " + cmd);
} }
} }
@@ -229,36 +228,37 @@ 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)
Console.WriteLine(message); Settings.Variables.outputStream.WriteLine(message);
Console.WriteLine( Settings.Variables.outputStream.WriteLine(
$"Running on version: {Assembly.GetExecutingAssembly().GetName().Version}"); $"Running on version: {Assembly.GetExecutingAssembly().GetName().Version}");
Console.WriteLine($"Git URL: {Settings.Variables.WebsiteURL}"); Settings.Variables.outputStream.WriteLine($"Git URL: {Settings.Variables.WebsiteURL}");
Console_Utilities.WriteColorText( 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");
Console.ForegroundColor = ConsoleColor.White; Console.ForegroundColor = ConsoleColor.White;
if (Config.Variables.Exists("LaunchMessage")) if (Config.Variables.Exists("LaunchMessage"))
Console_Utilities.WriteColorText(Config.Variables.GetValue("LaunchMessage")); Utilities.WriteColorText(Config.Variables.GetValue("LaunchMessage"));
Console_Utilities.WriteColorText( 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)");
Console.WriteLine("============================ LOG ============================"); Settings.Variables.outputStream.WriteLine("============================ LOG ============================");
try try
{ {
var token = Config.Variables.GetValue("token"); string token = "";
#if DEBUG #if DEBUG
Console.WriteLine("Starting in DEBUG MODE");
if (!Directory.Exists("./Data/BetaTest"))
Console.WriteLine("Failed to start in debug mode because the folder ./Data/BetaTest does not exist");
else
token = File.ReadAllText("./Data/BetaTest/token.txt");
//Debug mode code...
#endif
if (await Settings.sqlDatabase.TableExistsAsync("BetaTest"))
{
Settings.Variables.outputStream.WriteLine("Starting in DEBUG MODE");
token = await Settings.sqlDatabase.GetValueAsync("BetaTest", "VariableName", "Token", "Value");
}
#else
token = Config.Variables.GetValue("token");
#endif
var prefix = Config.Variables.GetValue("prefix"); var prefix = Config.Variables.GetValue("prefix");
var discordbooter = new Boot(token, prefix); var discordbooter = new Boot(token, prefix);
await discordbooter.Awake(); await discordbooter.Awake();
@@ -266,7 +266,7 @@ public class Program
} }
catch (Exception ex) catch (Exception ex)
{ {
Console.WriteLine(ex); Settings.Variables.outputStream.WriteLine(ex);
return null; return null;
} }
} }
@@ -285,7 +285,7 @@ public class Program
if (len > 0 && args[0] == "/remplug") if (len > 0 && args[0] == "/remplug")
{ {
var plugName = string.Join(' ', args, 1, args.Length - 1); var plugName = string.Join(' ', args, 1, args.Length - 1);
Console.WriteLine("Starting to remove " + plugName); Settings.Variables.outputStream.WriteLine("Starting to remove " + plugName);
await ConsoleCommandsHandler.ExecuteCommad("remplug " + plugName); await ConsoleCommandsHandler.ExecuteCommad("remplug " + plugName);
loadPluginsOnStartup = true; loadPluginsOnStartup = true;
} }
@@ -316,7 +316,9 @@ public class Program
private static async Task PreLoadComponents() private static async Task PreLoadComponents()
{ {
var main = new Console_Utilities.ProgressBar(ProgressBarType.NO_END); Settings.Variables.outputStream = Console.Out;
Settings.Variables.outputStream.WriteLine("Loading resources ...");
var main = new Utilities.ProgressBar(ProgressBarType.NO_END);
main.Start(); main.Start();
Directory.CreateDirectory("./Data/Resources"); Directory.CreateDirectory("./Data/Resources");
Directory.CreateDirectory("./Data/Plugins"); Directory.CreateDirectory("./Data/Plugins");
@@ -395,7 +397,7 @@ public class Program
{ {
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";
Console.WriteLine("Downloading update ..."); Settings.Variables.outputStream.WriteLine("Downloading update ...");
await ServerCom.DownloadFileNoProgressAsync(url, "./update.zip"); await ServerCom.DownloadFileNoProgressAsync(url, "./update.zip");
await File.WriteAllTextAsync("Install.sh", await File.WriteAllTextAsync("Install.sh",
"#!/bin/bash\nunzip -qq update.zip -d ./\nrm update.zip\nchmod +x SethDiscordBot\n./DiscordBot"); "#!/bin/bash\nunzip -qq update.zip -d ./\nrm update.zip\nchmod +x SethDiscordBot\n./DiscordBot");
@@ -417,8 +419,8 @@ public class Program
!File.Exists("./Updater/Updater.exe")) !File.Exists("./Updater/Updater.exe"))
{ {
Console.Clear(); Console.Clear();
Console.WriteLine("Installing updater ...\nDo NOT close the bot during update !"); Settings.Variables.outputStream.WriteLine("Installing updater ...\nDo NOT close the bot during update !");
var bar = new Console_Utilities.ProgressBar(ProgressBarType.NO_END); var bar = new Utilities.ProgressBar(ProgressBarType.NO_END);
bar.Start(); bar.Start();
await ServerCom.DownloadFileNoProgressAsync( await ServerCom.DownloadFileNoProgressAsync(
"https://github.com/Wizzy69/installer/releases/download/release-1-discordbot/Updater.zip", "https://github.com/Wizzy69/installer/releases/download/release-1-discordbot/Updater.zip",

View File

@@ -34,7 +34,9 @@ public class ConsoleCommandsHandler
{ {
this.client = client; this.client = client;
InitializeBasicCommands(); InitializeBasicCommands();
//Console.WriteLine("Initialized console command handler !");
//Settings.Variables.outputStream.WriteLine("Initialized console command handler !");
} }
private void InitializeBasicCommands() private void InitializeBasicCommands()
@@ -45,7 +47,7 @@ public class ConsoleCommandsHandler
{ {
if (args.Length <= 1) if (args.Length <= 1)
{ {
Console.WriteLine("Available commands:"); Settings.Variables.outputStream.WriteLine("Available commands:");
var items = new List<string[]>(); var items = new List<string[]>();
items.Add(new[] { "-", "-", "-" }); items.Add(new[] { "-", "-", "-" });
items.Add(new[] { "Command", "Description", "Usage" }); items.Add(new[] { "Command", "Description", "Usage" });
@@ -61,19 +63,19 @@ public class ConsoleCommandsHandler
} }
items.Add(new[] { "-", "-", "-" }); items.Add(new[] { "-", "-", "-" });
Console_Utilities.FormatAndAlignTable(items, TableFormat.DEFAULT); Utilities.FormatAndAlignTable(items, TableFormat.DEFAULT);
} }
else else
{ {
foreach (var command in commandList) foreach (var command in commandList)
if (command.CommandName == args[1]) if (command.CommandName == args[1])
{ {
Console.WriteLine("Command description: " + command.Description); Settings.Variables.outputStream.WriteLine("Command description: " + command.Description);
Console.WriteLine("Command execution format:" + command.Usage); Settings.Variables.outputStream.WriteLine("Command execution format:" + command.Usage);
return; return;
} }
Console.WriteLine("Command not found"); Settings.Variables.outputStream.WriteLine("Command not found");
} }
} }
); );
@@ -92,16 +94,16 @@ public class ConsoleCommandsHandler
if (success) if (success)
{ {
Console.ForegroundColor = ConsoleColor.Green; Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("[CMD] Successfully loaded command : " + name); Settings.Variables.outputStream.WriteLine("[CMD] Successfully loaded command : " + name);
} }
else else
{ {
Console.ForegroundColor = ConsoleColor.Red; Console.ForegroundColor = ConsoleColor.Red;
if (exception is null) if (exception is null)
Console.WriteLine("An error occured while loading: " + name); Settings.Variables.outputStream.WriteLine("An error occured while loading: " + name);
else else
Console.WriteLine("[CMD] Failed to load command : " + name + " because " + exception!.Message); Settings.Variables.outputStream.WriteLine("[CMD] Failed to load command : " + name + " because " + exception!.Message);
} }
Console.ForegroundColor = cc; Console.ForegroundColor = cc;
@@ -114,12 +116,12 @@ public class ConsoleCommandsHandler
if (success) if (success)
{ {
Console.ForegroundColor = ConsoleColor.Green; Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("[EVENT] Successfully loaded event : " + name); Settings.Variables.outputStream.WriteLine("[EVENT] Successfully loaded event : " + name);
} }
else else
{ {
Console.ForegroundColor = ConsoleColor.Red; Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("[EVENT] Failed to load event : " + name + " because " + exception!.Message); Settings.Variables.outputStream.WriteLine("[EVENT] Failed to load event : " + name + " because " + exception!.Message);
} }
Console.ForegroundColor = cc; Console.ForegroundColor = cc;
@@ -133,12 +135,12 @@ public class ConsoleCommandsHandler
if (success) if (success)
{ {
Console.ForegroundColor = ConsoleColor.Green; Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("[SLASH] Successfully loaded command : " + name); Settings.Variables.outputStream.WriteLine("[SLASH] Successfully loaded command : " + name);
} }
else else
{ {
Console.ForegroundColor = ConsoleColor.Red; Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("[SLASH] Failed to load command : " + name + " because " + exception!.Message); Settings.Variables.outputStream.WriteLine("[SLASH] Failed to load command : " + name + " because " + exception!.Message);
} }
Console.ForegroundColor = cc; Console.ForegroundColor = cc;
@@ -158,7 +160,7 @@ public class ConsoleCommandsHandler
if (args.Length == 1) if (args.Length == 1)
{ {
isDownloading = false; isDownloading = false;
Console.WriteLine("Please specify plugin name"); Settings.Variables.outputStream.WriteLine("Please specify plugin name");
return; return;
} }
@@ -172,12 +174,12 @@ public class ConsoleCommandsHandler
if (name == "") if (name == "")
{ {
isDownloading = false; isDownloading = false;
Console_Utilities.WriteColorText("Name is invalid"); Utilities.WriteColorText("Name is invalid");
return; return;
} }
isDownloading = false; isDownloading = false;
Console_Utilities.WriteColorText($"Failed to find plugin &b{name} &c!" + Utilities.WriteColorText($"Failed to find plugin &b{name} &c!" +
" Use &glistplugs &ccommand to display all available plugins !"); " Use &glistplugs &ccommand to display all available plugins !");
return; return;
} }
@@ -194,20 +196,20 @@ public class ConsoleCommandsHandler
} }
else if (OperatingSystem.LINUX == Functions.GetOperatingSystem()) else if (OperatingSystem.LINUX == Functions.GetOperatingSystem())
{ {
var bar = new Console_Utilities.ProgressBar(ProgressBarType.NO_END); var bar = new Utilities.ProgressBar(ProgressBarType.NO_END);
bar.Start(); bar.Start();
await ServerCom.DownloadFileNoProgressAsync(info[1], path); await ServerCom.DownloadFileNoProgressAsync(info[1], path);
bar.Stop("Plugin Downloaded !"); bar.Stop("Plugin Downloaded !");
} }
Console.WriteLine("\n"); Settings.Variables.outputStream.WriteLine("\n");
// check requirements if any // check requirements if any
if (info.Length == 3 && info[2] != string.Empty && info[2] != null) if (info.Length == 3 && info[2] != string.Empty && info[2] != null)
{ {
Console.WriteLine($"Downloading requirements for plugin : {name}"); Settings.Variables.outputStream.WriteLine($"Downloading requirements for plugin : {name}");
var lines = await ServerCom.ReadTextFromURL(info[2]); var lines = await ServerCom.ReadTextFromURL(info[2]);
@@ -216,7 +218,7 @@ public class ConsoleCommandsHandler
if (!(line.Length > 0 && line.Contains(","))) if (!(line.Length > 0 && line.Contains(",")))
continue; continue;
var split = line.Split(','); var split = line.Split(',');
Console.WriteLine($"\nDownloading item: {split[1]}"); Settings.Variables.outputStream.WriteLine($"\nDownloading item: {split[1]}");
if (File.Exists("./" + split[1])) File.Delete("./" + split[1]); if (File.Exists("./" + split[1])) File.Delete("./" + split[1]);
if (OperatingSystem.WINDOWS == Functions.GetOperatingSystem()) if (OperatingSystem.WINDOWS == Functions.GetOperatingSystem())
{ {
@@ -224,32 +226,32 @@ public class ConsoleCommandsHandler
} }
else if (OperatingSystem.LINUX == Functions.GetOperatingSystem()) else if (OperatingSystem.LINUX == Functions.GetOperatingSystem())
{ {
var bar = new Console_Utilities.ProgressBar(ProgressBarType.NO_END); var bar = new Utilities.ProgressBar(ProgressBarType.NO_END);
bar.Start(); bar.Start();
await ServerCom.DownloadFileNoProgressAsync(split[0], "./" + split[1]); await ServerCom.DownloadFileNoProgressAsync(split[0], "./" + split[1]);
bar.Stop("Item downloaded !"); bar.Stop("Item downloaded !");
} }
Console.WriteLine(); Settings.Variables.outputStream.WriteLine();
if (split[0].EndsWith(".pak")) if (split[0].EndsWith(".pak"))
{ {
File.Move("./" + split[1], "./Data/PAKS/" + split[1], true); File.Move("./" + split[1], "./Data/PAKS/" + split[1], true);
} }
else if (split[0].EndsWith(".zip") || split[0].EndsWith(".pkg")) else if (split[0].EndsWith(".zip") || split[0].EndsWith(".pkg"))
{ {
Console.WriteLine($"Extracting {split[1]} ..."); Settings.Variables.outputStream.WriteLine($"Extracting {split[1]} ...");
var bar = new Console_Utilities.ProgressBar( var bar = new Utilities.ProgressBar(
ProgressBarType.NO_END); ProgressBarType.NO_END);
bar.Start(); bar.Start();
await Functions.ExtractArchive("./" + split[1], "./", null, await Functions.ExtractArchive("./" + split[1], "./", null,
UnzipProgressType.PercentageFromTotalSize); UnzipProgressType.PercentageFromTotalSize);
bar.Stop("Extracted"); bar.Stop("Extracted");
Console.WriteLine("\n"); Settings.Variables.outputStream.WriteLine("\n");
File.Delete("./" + split[1]); File.Delete("./" + split[1]);
} }
} }
Console.WriteLine(); Settings.Variables.outputStream.WriteLine();
} }
var ver = await ServerCom.GetVersionOfPackageFromWeb(name); var ver = await ServerCom.GetVersionOfPackageFromWeb(name);
@@ -269,7 +271,7 @@ public class ConsoleCommandsHandler
return; return;
var data = Config.Variables.GetValue(args[1]); var data = Config.Variables.GetValue(args[1]);
Console.WriteLine($"{args[1]} => {data}"); Settings.Variables.outputStream.WriteLine($"{args[1]} => {data}");
} }
); );
@@ -284,11 +286,11 @@ public class ConsoleCommandsHandler
try try
{ {
Config.Variables.Add(key, value, isReadOnly); Config.Variables.Add(key, value, isReadOnly);
Console.WriteLine($"Updated config file with the following command: {args[1]} => {value}"); Settings.Variables.outputStream.WriteLine($"Updated config file with the following command: {args[1]} => {value}");
} }
catch (Exception ex) catch (Exception ex)
{ {
Console.WriteLine(ex.ToString()); Settings.Variables.outputStream.WriteLine(ex.ToString());
} }
} }
); );
@@ -305,11 +307,11 @@ public class ConsoleCommandsHandler
{ {
if (client is null) if (client is null)
return; return;
var bar = new Console_Utilities.ProgressBar(ProgressBarType.NO_END); var bar = new Utilities.ProgressBar(ProgressBarType.NO_END);
bar.Start(); bar.Start();
bar.Stop("Saved config !"); bar.Stop("Saved config !");
Console.WriteLine(); Settings.Variables.outputStream.WriteLine();
Settings.sqlDatabase.Stop(); Settings.sqlDatabase.Stop();
await client.StopAsync(); await client.StopAsync();
await client.DisposeAsync(); await client.DisposeAsync();
@@ -339,17 +341,17 @@ public class ConsoleCommandsHandler
{ {
var instance = (DBEvent)Activator.CreateInstance(type); var instance = (DBEvent)Activator.CreateInstance(type);
instance.Start(this.client); instance.Start(this.client);
Console.WriteLine($"[EVENT] Loaded external {type.FullName}!"); Settings.Variables.outputStream.WriteLine($"[EVENT] Loaded external {type.FullName}!");
} }
else if (type.IsClass && typeof(DBCommand).IsAssignableFrom(type)) else if (type.IsClass && typeof(DBCommand).IsAssignableFrom(type))
{ {
var instance = (DBCommand)Activator.CreateInstance(type); var instance = (DBCommand)Activator.CreateInstance(type);
Console.WriteLine($"[CMD] Instance: {type.FullName} loaded !"); Settings.Variables.outputStream.WriteLine($"[CMD] Instance: {type.FullName} loaded !");
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
Console.WriteLine(ex.Message); Settings.Variables.outputStream.WriteLine(ex.Message);
} }
}); });
@@ -383,13 +385,13 @@ public class ConsoleCommandsHandler
if (!File.Exists(location)) if (!File.Exists(location))
{ {
Console.WriteLine("The plugin does not exist"); Settings.Variables.outputStream.WriteLine("The plugin does not exist");
return; return;
} }
File.Delete(location); File.Delete(location);
Console.WriteLine("Removed the plugin DLL. Checking for other files ..."); Settings.Variables.outputStream.WriteLine("Removed the plugin DLL. Checking for other files ...");
var info = await manager.GetPluginLinkByName(plugName); var info = await manager.GetPluginLinkByName(plugName);
if (info[2] != string.Empty) if (info[2] != string.Empty)
@@ -404,7 +406,7 @@ public class ConsoleCommandsHandler
File.Delete("./" + split[1]); File.Delete("./" + split[1]);
Console.WriteLine("Removed: " + split[1]); Settings.Variables.outputStream.WriteLine("Removed: " + split[1]);
} }
if (Directory.Exists($"./Data/Plugins/{plugName}")) if (Directory.Exists($"./Data/Plugins/{plugName}"))
@@ -415,7 +417,7 @@ public class ConsoleCommandsHandler
} }
isDownloading = false; isDownloading = false;
Console.WriteLine(plugName + " has been successfully deleted !"); Settings.Variables.outputStream.WriteLine(plugName + " has been successfully deleted !");
}); });
AddCommand("reload", "Reload the bot with all plugins", () => AddCommand("reload", "Reload the bot with all plugins", () =>
@@ -443,7 +445,7 @@ public class ConsoleCommandsHandler
commandList.Add(new ConsoleCommand commandList.Add(new ConsoleCommand
{ CommandName = command, Description = description, Action = action, Usage = usage }); { CommandName = command, Description = description, Action = action, Usage = usage });
Console.ForegroundColor = ConsoleColor.White; Console.ForegroundColor = ConsoleColor.White;
Console_Utilities.WriteColorText($"Command &r{command} &cadded to the list of commands"); Utilities.WriteColorText($"Command &r{command} &cadded to the list of commands");
} }
public static void AddCommand(string command, string description, Action action) public static void AddCommand(string command, string description, Action action)
@@ -469,13 +471,10 @@ public class ConsoleCommandsHandler
public static async Task ExecuteCommad(string command) public static async Task ExecuteCommad(string command)
{ {
var args = command.Split(' '); var args = command.Split(' ');
// Console.WriteLine(command);
foreach (var item in commandList.ToList()) foreach (var item in commandList.ToList())
if (item.CommandName == args[0]) if (item.CommandName == args[0])
{ {
item.Action.Invoke(args); item.Action.Invoke(args);
Console.WriteLine();
while (isDownloading) await Task.Delay(1000); while (isDownloading) await Task.Delay(1000);
} }
} }
@@ -491,17 +490,17 @@ public class ConsoleCommandsHandler
{ {
Console.SetCursorPosition(0, Console.CursorTop - 1); Console.SetCursorPosition(0, Console.CursorTop - 1);
for (var i = 0; i < command.Length + 30; i++) for (var i = 0; i < command.Length + 30; i++)
Console.Write(" "); Settings.Variables.outputStream.Write(" ");
Console.SetCursorPosition(0, Console.CursorTop); Console.SetCursorPosition(0, Console.CursorTop);
} }
Console.WriteLine(); Settings.Variables.outputStream.WriteLine();
item.Action(args); item.Action(args);
return true; return true;
} }
return false; return false;
//Console.WriteLine($"Executing: {args[0]} with the following parameters: {args.MergeStrings(1)}"); //Settings.Variables.outputStream.WriteLine($"Executing: {args[0]} with the following parameters: {args.MergeStrings(1)}");
} }
} }

View File

@@ -95,7 +95,7 @@ public class PluginLoader
SlashCommands = new List<DBSlashCommand>(); SlashCommands = new List<DBSlashCommand>();
Functions.WriteLogFile("Starting plugin loader ... Client: " + _client.CurrentUser.Username); Functions.WriteLogFile("Starting plugin loader ... Client: " + _client.CurrentUser.Username);
Console.WriteLine("Loading plugins"); Settings.Variables.outputStream.WriteLine("Loading plugins");
var loader = new LoaderV2("./Data/Plugins", "dll"); var loader = new LoaderV2("./Data/Plugins", "dll");
loader.FileLoaded += (args) => Functions.WriteLogFile($"{args.PluginName} file Loaded"); loader.FileLoaded += (args) => Functions.WriteLogFile($"{args.PluginName} file Loaded");
@@ -108,7 +108,7 @@ public class PluginLoader
private async void Loader_PluginLoaded(LoaderArgs args) private async void Loader_PluginLoaded(LoaderArgs args)
{ {
// Console.WriteLine(args.TypeName); // Settings.Variables.outputStream.WriteLine(args.TypeName);
switch (args.TypeName) switch (args.TypeName)
{ {
case "DBCommand": case "DBCommand":
@@ -124,10 +124,10 @@ public class PluginLoader
} }
catch (Exception ex) catch (Exception ex)
{ {
Console.WriteLine(ex.ToString()); Settings.Variables.outputStream.WriteLine(ex.ToString());
Console.WriteLine("Plugin: " + args.PluginName); Settings.Variables.outputStream.WriteLine("Plugin: " + args.PluginName);
Console.WriteLine("Type: " + args.TypeName); Settings.Variables.outputStream.WriteLine("Type: " + args.TypeName);
Console.WriteLine("IsLoaded: " + args.IsLoaded); Settings.Variables.outputStream.WriteLine("IsLoaded: " + args.IsLoaded);
} }
break; break;
case "DBSlashCommand": case "DBSlashCommand":
@@ -139,73 +139,13 @@ public class PluginLoader
builder.WithDescription(slash.Description); builder.WithDescription(slash.Description);
builder.WithDMPermission(slash.canUseDM); builder.WithDMPermission(slash.canUseDM);
builder.Options = slash.Options; builder.Options = slash.Options;
//Console.WriteLine("Loaded " + slash.Name); //Settings.Variables.outputStream.WriteLine("Loaded " + slash.Name);
onSLSHLoad?.Invoke(((DBSlashCommand)args.Plugin!).Name, args.TypeName, args.IsLoaded, args.Exception); onSLSHLoad?.Invoke(((DBSlashCommand)args.Plugin!).Name, args.TypeName, args.IsLoaded, args.Exception);
await _client.CreateGlobalApplicationCommandAsync(builder.Build()); await _client.CreateGlobalApplicationCommandAsync(builder.Build());
} }
//else Console.WriteLine("Failed to load " + args.PluginName + "\nException: " + args.Exception.Message);
break; break;
} }
} }
/*
private async void SlashLoader_PluginLoaded(LoaderArgs args)
{
if (args.IsLoaded)
{
var slash = (DBSlashCommand)args.Plugin;
SlashCommandBuilder builder = new SlashCommandBuilder();
builder.WithName(slash.Name);
builder.WithDescription(slash.Description);
builder.WithDMPermission(slash.canUseDM);
builder.Options = slash.Options;
Console.WriteLine("Loaded " + slash.Name);
await _client.CreateGlobalApplicationCommandAsync(builder.Build());
}
else Console.WriteLine("Failed to load " + args.PluginName + "\nException: " + args.Exception.Message);
}
private void SlashLoader_FileLoaded(LoaderArgs args)
{
if (!args.IsLoaded)
Functions.WriteLogFile($"[SLASH] SlashCommand from file [{args.PluginName}] has been successfully created !");
}
private void EventFileLoaded(LoaderArgs e)
{
if (!e.IsLoaded)
Functions.WriteLogFile($"[EVENT] Event from file [{e.PluginName}] has been successfully created !");
}
private void OnCommandFileLoaded(LoaderArgs e)
{
if (!e.IsLoaded)
Functions.WriteLogFile($"[CMD] Command from file [{e.PluginName}] has been successfully loaded !");
}
private void OnEventLoaded(LoaderArgs e)
{
try
{
if (e.IsLoaded)
((DBEvent)e.Plugin!).Start(_client);
onEVELoad?.Invoke(((DBEvent)e.Plugin!).Name, e.TypeName!, e.IsLoaded, e.Exception);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
Console.WriteLine("Plugin: " + e.PluginName);
Console.WriteLine("Type: " + e.TypeName);
Console.WriteLine("IsLoaded: " + e.IsLoaded);
}
}
private void OnCommandLoaded(LoaderArgs e)
{
onCMDLoad?.Invoke(((DBCommand)e.Plugin!).Command, e.TypeName!, e.IsLoaded, e.Exception);
}*/
} }

View File

@@ -80,11 +80,11 @@ public class PluginsManager
data.Add(new[] { "-", "-", "-", "-" }); data.Add(new[] { "-", "-", "-", "-" });
Console_Utilities.FormatAndAlignTable(data, TableFormat.CENTER_EACH_COLUMN_BASED); Utilities.FormatAndAlignTable(data, TableFormat.CENTER_EACH_COLUMN_BASED);
} }
catch (Exception exception) catch (Exception exception)
{ {
Console.WriteLine("Failed to execute command: listplugs\nReason: " + exception.Message); Settings.Variables.outputStream.WriteLine("Failed to execute command: listplugs\nReason: " + exception.Message);
Functions.WriteErrFile(exception.ToString()); Functions.WriteErrFile(exception.ToString());
} }
} }
@@ -116,7 +116,7 @@ public class PluginsManager
} }
catch (Exception exception) catch (Exception exception)
{ {
Console.WriteLine("Failed to execute command: listplugs\nReason: " + exception.Message); Settings.Variables.outputStream.WriteLine("Failed to execute command: listplugs\nReason: " + exception.Message);
Functions.WriteErrFile(exception.ToString()); Functions.WriteErrFile(exception.ToString());
} }

View File

@@ -57,7 +57,7 @@ public static class ServerCom
var isDownloading = true; var isDownloading = true;
float c_progress = 0; float c_progress = 0;
var pbar = new Console_Utilities.ProgressBar(ProgressBarType.NORMAL) { Max = 100f, NoColor = true }; var pbar = new Utilities.ProgressBar(ProgressBarType.NORMAL) { Max = 100f, NoColor = true };
IProgress<float> progress = new Progress<float>(percent => { c_progress = percent; }); IProgress<float> progress = new Progress<float>(percent => { c_progress = percent; });

View File

@@ -42,7 +42,7 @@ public class PluginUpdater
public static async Task Download(string pakName) public static async Task Download(string pakName)
{ {
Console_Utilities.WriteColorText("An update was found for &g" + pakName + "&c. Version: &r" + Utilities.WriteColorText("An update was found for &g" + pakName + "&c. Version: &r" +
(await ServerCom.GetVersionOfPackageFromWeb(pakName))?.ToShortString() + (await ServerCom.GetVersionOfPackageFromWeb(pakName))?.ToShortString() +
"&c. Current Version: &y" + "&c. Current Version: &y" +
ServerCom.GetVersionOfPackage(pakName)?.ToShortString()); ServerCom.GetVersionOfPackage(pakName)?.ToShortString());

View File

@@ -4,7 +4,7 @@ using System.Threading.Tasks;
namespace PluginManager.Others; namespace PluginManager.Others;
public static class Console_Utilities public static class Utilities
{ {
private static Dictionary<char, ConsoleColor> Colors = new() private static Dictionary<char, ConsoleColor> Colors = new()
{ {
@@ -46,38 +46,38 @@ public static class Console_Utilities
foreach (var row in data) foreach (var row in data)
{ {
if (row[0][0] == tableLine) if (row[0][0] == tableLine)
Console.Write(tableCross); Settings.Variables.outputStream.Write(tableCross);
else else
Console.Write(tableWall); Settings.Variables.outputStream.Write(tableWall);
for (var l = 0; l < row.Length; l++) for (var l = 0; l < row.Length; l++)
{ {
if (row[l][0] == tableLine) if (row[l][0] == tableLine)
{ {
for (var i = 0; i < len[l] + 4; ++i) for (var i = 0; i < len[l] + 4; ++i)
Console.Write(tableLine); Settings.Variables.outputStream.Write(tableLine);
} }
else if (row[l].Length == len[l]) else if (row[l].Length == len[l])
{ {
Console.Write(" "); Settings.Variables.outputStream.Write(" ");
Console.Write(row[l]); Settings.Variables.outputStream.Write(row[l]);
Console.Write(" "); Settings.Variables.outputStream.Write(" ");
} }
else else
{ {
var lenHalf = row[l].Length / 2; var lenHalf = row[l].Length / 2;
for (var i = 0; i < (len[l] + 4) / 2 - lenHalf; ++i) for (var i = 0; i < (len[l] + 4) / 2 - lenHalf; ++i)
Console.Write(" "); Settings.Variables.outputStream.Write(" ");
Console.Write(row[l]); Settings.Variables.outputStream.Write(row[l]);
for (var i = (len[l] + 4) / 2 + lenHalf + 1; i < len[l] + 4; ++i) for (var i = (len[l] + 4) / 2 + lenHalf + 1; i < len[l] + 4; ++i)
Console.Write(" "); Settings.Variables.outputStream.Write(" ");
if (row[l].Length % 2 == 0) if (row[l].Length % 2 == 0)
Console.Write(" "); Settings.Variables.outputStream.Write(" ");
} }
Console.Write(row[l][0] == tableLine ? tableCross : tableWall); Settings.Variables.outputStream.Write(row[l][0] == tableLine ? tableCross : tableWall);
} }
Console.WriteLine(); //end line Settings.Variables.outputStream.WriteLine(); //end line
} }
return; return;
@@ -95,44 +95,44 @@ public static class Console_Utilities
foreach (var row in data) foreach (var row in data)
{ {
Console.Write("\t"); Settings.Variables.outputStream.Write("\t");
if (row[0] == "-") if (row[0] == "-")
Console.Write("+"); Settings.Variables.outputStream.Write("+");
else else
Console.Write("|"); Settings.Variables.outputStream.Write("|");
foreach (var s in row) foreach (var s in row)
{ {
if (s == "-") if (s == "-")
{ {
for (var i = 0; i < maxLen + 4; ++i) for (var i = 0; i < maxLen + 4; ++i)
Console.Write("-"); Settings.Variables.outputStream.Write("-");
} }
else if (s.Length == maxLen) else if (s.Length == maxLen)
{ {
Console.Write(" "); Settings.Variables.outputStream.Write(" ");
Console.Write(s); Settings.Variables.outputStream.Write(s);
Console.Write(" "); Settings.Variables.outputStream.Write(" ");
} }
else else
{ {
var lenHalf = s.Length / 2; var lenHalf = s.Length / 2;
for (var i = 0; i < div - lenHalf; ++i) for (var i = 0; i < div - lenHalf; ++i)
Console.Write(" "); Settings.Variables.outputStream.Write(" ");
Console.Write(s); Settings.Variables.outputStream.Write(s);
for (var i = div + lenHalf + 1; i < maxLen + 4; ++i) for (var i = div + lenHalf + 1; i < maxLen + 4; ++i)
Console.Write(" "); Settings.Variables.outputStream.Write(" ");
if (s.Length % 2 == 0) if (s.Length % 2 == 0)
Console.Write(" "); Settings.Variables.outputStream.Write(" ");
} }
if (s == "-") if (s == "-")
Console.Write("+"); Settings.Variables.outputStream.Write("+");
else else
Console.Write("|"); Settings.Variables.outputStream.Write("|");
} }
Console.WriteLine(); //end line Settings.Variables.outputStream.WriteLine(); //end line
} }
return; return;
@@ -153,12 +153,12 @@ public static class Console_Utilities
{ {
if (data[i][j] == "-") if (data[i][j] == "-")
data[i][j] = " "; data[i][j] = " ";
Console.Write(data[i][j]); Settings.Variables.outputStream.Write(data[i][j]);
for (var k = 0; k < widths[j] - data[i][j].Length + 1 + space_between_columns; k++) for (var k = 0; k < widths[j] - data[i][j].Length + 1 + space_between_columns; k++)
Console.Write(" "); Settings.Variables.outputStream.Write(" ");
} }
Console.WriteLine(); Settings.Variables.outputStream.WriteLine();
} }
return; return;
@@ -169,6 +169,13 @@ public static class Console_Utilities
public static void WriteColorText(string text, bool appendNewLineAtEnd = true) public static void WriteColorText(string text, bool appendNewLineAtEnd = true)
{ {
if (Console.Out != Settings.Variables.outputStream)
{
Settings.Variables.outputStream.Write(text);
if (appendNewLineAtEnd)
Settings.Variables.outputStream.WriteLine();
return;
}
var initialForeGround = Console.ForegroundColor; var initialForeGround = Console.ForegroundColor;
var input = text.ToCharArray(); var input = text.ToCharArray();
for (var i = 0; i < input.Length; i++) for (var i = 0; i < input.Length; i++)
@@ -190,12 +197,12 @@ public static class Console_Utilities
} }
else else
{ {
Console.Write(input[i]); Settings.Variables.outputStream.Write(input[i]);
} }
Console.ForegroundColor = initialForeGround; Console.ForegroundColor = initialForeGround;
if (appendNewLineAtEnd) if (appendNewLineAtEnd)
Console.WriteLine(); Settings.Variables.outputStream.WriteLine();
} }
@@ -212,6 +219,8 @@ public static class Console_Utilities
public ProgressBar(ProgressBarType type) public ProgressBar(ProgressBarType type)
{ {
if (Settings.Variables.outputStream != Console.Out)
throw new Exception("This class (or function) can be used with console only. For UI please use another approach.");
this.type = type; this.type = type;
} }
@@ -272,9 +281,9 @@ public static class Console_Utilities
{ {
Console.CursorLeft = 0; Console.CursorLeft = 0;
for (var i = 0; i < BarLength + message.Length + 1; i++) for (var i = 0; i < BarLength + message.Length + 1; i++)
Console.Write(" "); Settings.Variables.outputStream.Write(" ");
Console.CursorLeft = 0; Console.CursorLeft = 0;
Console.WriteLine(message); Settings.Variables.outputStream.WriteLine(message);
} }
} }
@@ -289,14 +298,14 @@ public static class Console_Utilities
private void UpdateNoEnd(string message) private void UpdateNoEnd(string message)
{ {
Console.CursorLeft = 0; Console.CursorLeft = 0;
Console.Write("["); Settings.Variables.outputStream.Write("[");
for (var i = 1; i <= position; i++) for (var i = 1; i <= position; i++)
Console.Write(" "); Settings.Variables.outputStream.Write(" ");
Console.Write("<==()==>"); Settings.Variables.outputStream.Write("<==()==>");
position += positive ? 1 : -1; position += positive ? 1 : -1;
for (var i = position; i <= BarLength - 1 - (positive ? 0 : 2); i++) for (var i = position; i <= BarLength - 1 - (positive ? 0 : 2); i++)
Console.Write(" "); Settings.Variables.outputStream.Write(" ");
Console.Write("] " + message); Settings.Variables.outputStream.Write("] " + message);
if (position == BarLength - 1 || position == 1) if (position == BarLength - 1 || position == 1)
@@ -306,14 +315,14 @@ public static class Console_Utilities
private void UpdateNoEnd() private void UpdateNoEnd()
{ {
Console.CursorLeft = 0; Console.CursorLeft = 0;
Console.Write("["); Settings.Variables.outputStream.Write("[");
for (var i = 1; i <= position; i++) for (var i = 1; i <= position; i++)
Console.Write(" "); Settings.Variables.outputStream.Write(" ");
Console.Write("<==()==>"); Settings.Variables.outputStream.Write("<==()==>");
position += positive ? 1 : -1; position += positive ? 1 : -1;
for (var i = position; i <= BarLength - 1 - (positive ? 0 : 2); i++) for (var i = position; i <= BarLength - 1 - (positive ? 0 : 2); i++)
Console.Write(" "); Settings.Variables.outputStream.Write(" ");
Console.Write("]"); Settings.Variables.outputStream.Write("]");
if (position == BarLength - 1 || position == 1) if (position == BarLength - 1 || position == 1)
@@ -323,9 +332,9 @@ public static class Console_Utilities
private void UpdateNormal(float progress) private void UpdateNormal(float progress)
{ {
Console.CursorLeft = 0; Console.CursorLeft = 0;
Console.Write("["); Settings.Variables.outputStream.Write("[");
Console.CursorLeft = BarLength; Console.CursorLeft = BarLength;
Console.Write("]"); Settings.Variables.outputStream.Write("]");
Console.CursorLeft = 1; Console.CursorLeft = 1;
var onechunk = 30.0f / Max; var onechunk = 30.0f / Max;
@@ -335,22 +344,22 @@ public static class Console_Utilities
{ {
Console.BackgroundColor = NoColor ? ConsoleColor.Black : Color; Console.BackgroundColor = NoColor ? ConsoleColor.Black : Color;
Console.CursorLeft = position++; Console.CursorLeft = position++;
Console.Write("#"); Settings.Variables.outputStream.Write("#");
} }
for (var i = position; i < BarLength; i++) for (var i = position; i < BarLength; i++)
{ {
Console.BackgroundColor = NoColor ? ConsoleColor.Black : ConsoleColor.DarkGray; Console.BackgroundColor = NoColor ? ConsoleColor.Black : ConsoleColor.DarkGray;
Console.CursorLeft = position++; Console.CursorLeft = position++;
Console.Write(" "); Settings.Variables.outputStream.Write(" ");
} }
Console.CursorLeft = BarLength + 4; Console.CursorLeft = BarLength + 4;
Console.BackgroundColor = ConsoleColor.Black; Console.BackgroundColor = ConsoleColor.Black;
if (progress.CanAproximateTo(Max)) if (progress.CanAproximateTo(Max))
Console.Write(progress + " % ✓"); Settings.Variables.outputStream.Write(progress + " % ✓");
else else
Console.Write(MathF.Round(progress, 2) + " % "); Settings.Variables.outputStream.Write(MathF.Round(progress, 2) + " % ");
} }
} }
} }

View File

@@ -197,7 +197,7 @@ public static class Functions
} }
catch (Exception ex) catch (Exception ex)
{ {
Console.WriteLine($"Failed to extract {entry.Name}. Exception: {ex.Message}"); Settings.Variables.outputStream.WriteLine($"Failed to extract {entry.Name}. Exception: {ex.Message}");
} }
currentZIPFile++; currentZIPFile++;
@@ -229,7 +229,7 @@ public static class Functions
} }
catch (Exception ex) catch (Exception ex)
{ {
Console.WriteLine($"Failed to extract {entry.Name}. Exception: {ex.Message}"); Settings.Variables.outputStream.WriteLine($"Failed to extract {entry.Name}. Exception: {ex.Message}");
} }
await Task.Delay(10); await Task.Delay(10);

View File

@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <PropertyGroup>
<TargetFramework>net6.0</TargetFramework> <TargetFramework>net6.0</TargetFramework>

View File

@@ -1,5 +1,6 @@
using PluginManager.Database; using System.IO;
using PluginManager.Others;
using PluginManager.Database;
namespace PluginManager namespace PluginManager
{ {
@@ -11,6 +12,7 @@ namespace PluginManager
public static string WebsiteURL = "https://wizzy69.github.io/SethDiscordBot"; public static string WebsiteURL = "https://wizzy69.github.io/SethDiscordBot";
public static string UpdaterURL = "https://github.com/Wizzy69/installer/releases/download/release-1-discordbot/Updater.zip"; public static string UpdaterURL = "https://github.com/Wizzy69/installer/releases/download/release-1-discordbot/Updater.zip";
public static TextWriter outputStream;
} }
public static SqlDatabase sqlDatabase; public static SqlDatabase sqlDatabase;

View File

@@ -11,7 +11,7 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MusicLibrary", "..\DiscordB
EndProject EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SlashCommands", "..\DiscordBotItems\Plugins\SlashCommands\SlashCommands.csproj", "{C2D73BE8-997B-4A4A-8EA5-989BE33EE1DD}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SlashCommands", "..\DiscordBotItems\Plugins\SlashCommands\SlashCommands.csproj", "{C2D73BE8-997B-4A4A-8EA5-989BE33EE1DD}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LevelingSystem", "..\DiscordBotItems\Plugins\LevelingSystem\LevelingSystem.csproj", "{0138F343-BBB9-4D5F-B499-D9C2978BE9AA}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "LevelingSystem", "..\DiscordBotItems\Plugins\LevelingSystem\LevelingSystem.csproj", "{0138F343-BBB9-4D5F-B499-D9C2978BE9AA}"
EndProject EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution