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>
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);
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.
/// </summary>
[STAThread]
[Obsolete]
public static void Main(string[] args)
public static void Startup(string[] args)
{
Console.WriteLine("Loading resources ...");
PreLoadComponents().Wait();
if (!Config.Variables.Exists("ServerID") || !Config.Variables.Exists("token") ||
@@ -195,7 +194,7 @@ public class Program
private static void NoGUI()
{
#if DEBUG
Console.WriteLine();
Settings.Variables.outputStream.WriteLine();
ConsoleCommandsHandler.ExecuteCommad("lp").Wait();
#else
if (loadPluginsOnStartup) consoleCommandsHandler.HandleCommand("lp");
@@ -211,7 +210,7 @@ public class Program
#endif
) && 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");
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}");
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");
Console.ForegroundColor = ConsoleColor.White;
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)");
Console.WriteLine("============================ LOG ============================");
Settings.Variables.outputStream.WriteLine("============================ LOG ============================");
try
{
var token = Config.Variables.GetValue("token");
string token = "";
#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 discordbooter = new Boot(token, prefix);
await discordbooter.Awake();
@@ -266,7 +266,7 @@ public class Program
}
catch (Exception ex)
{
Console.WriteLine(ex);
Settings.Variables.outputStream.WriteLine(ex);
return null;
}
}
@@ -285,7 +285,7 @@ public class Program
if (len > 0 && args[0] == "/remplug")
{
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);
loadPluginsOnStartup = true;
}
@@ -316,7 +316,9 @@ public class Program
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();
Directory.CreateDirectory("./Data/Resources");
Directory.CreateDirectory("./Data/Plugins");
@@ -395,7 +397,7 @@ public class Program
{
var url =
$"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 File.WriteAllTextAsync("Install.sh",
"#!/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"))
{
Console.Clear();
Console.WriteLine("Installing updater ...\nDo NOT close the bot during update !");
var bar = new Console_Utilities.ProgressBar(ProgressBarType.NO_END);
Settings.Variables.outputStream.WriteLine("Installing updater ...\nDo NOT close the bot during update !");
var bar = new Utilities.ProgressBar(ProgressBarType.NO_END);
bar.Start();
await ServerCom.DownloadFileNoProgressAsync(
"https://github.com/Wizzy69/installer/releases/download/release-1-discordbot/Updater.zip",

View File

@@ -34,7 +34,9 @@ public class ConsoleCommandsHandler
{
this.client = client;
InitializeBasicCommands();
//Console.WriteLine("Initialized console command handler !");
//Settings.Variables.outputStream.WriteLine("Initialized console command handler !");
}
private void InitializeBasicCommands()
@@ -45,7 +47,7 @@ public class ConsoleCommandsHandler
{
if (args.Length <= 1)
{
Console.WriteLine("Available commands:");
Settings.Variables.outputStream.WriteLine("Available commands:");
var items = new List<string[]>();
items.Add(new[] { "-", "-", "-" });
items.Add(new[] { "Command", "Description", "Usage" });
@@ -61,19 +63,19 @@ public class ConsoleCommandsHandler
}
items.Add(new[] { "-", "-", "-" });
Console_Utilities.FormatAndAlignTable(items, TableFormat.DEFAULT);
Utilities.FormatAndAlignTable(items, TableFormat.DEFAULT);
}
else
{
foreach (var command in commandList)
if (command.CommandName == args[1])
{
Console.WriteLine("Command description: " + command.Description);
Console.WriteLine("Command execution format:" + command.Usage);
Settings.Variables.outputStream.WriteLine("Command description: " + command.Description);
Settings.Variables.outputStream.WriteLine("Command execution format:" + command.Usage);
return;
}
Console.WriteLine("Command not found");
Settings.Variables.outputStream.WriteLine("Command not found");
}
}
);
@@ -92,16 +94,16 @@ public class ConsoleCommandsHandler
if (success)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("[CMD] Successfully loaded command : " + name);
Settings.Variables.outputStream.WriteLine("[CMD] Successfully loaded command : " + name);
}
else
{
Console.ForegroundColor = ConsoleColor.Red;
if (exception is null)
Console.WriteLine("An error occured while loading: " + name);
Settings.Variables.outputStream.WriteLine("An error occured while loading: " + name);
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;
@@ -114,12 +116,12 @@ public class ConsoleCommandsHandler
if (success)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("[EVENT] Successfully loaded event : " + name);
Settings.Variables.outputStream.WriteLine("[EVENT] Successfully loaded event : " + name);
}
else
{
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;
@@ -133,12 +135,12 @@ public class ConsoleCommandsHandler
if (success)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("[SLASH] Successfully loaded command : " + name);
Settings.Variables.outputStream.WriteLine("[SLASH] Successfully loaded command : " + name);
}
else
{
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;
@@ -158,7 +160,7 @@ public class ConsoleCommandsHandler
if (args.Length == 1)
{
isDownloading = false;
Console.WriteLine("Please specify plugin name");
Settings.Variables.outputStream.WriteLine("Please specify plugin name");
return;
}
@@ -172,12 +174,12 @@ public class ConsoleCommandsHandler
if (name == "")
{
isDownloading = false;
Console_Utilities.WriteColorText("Name is invalid");
Utilities.WriteColorText("Name is invalid");
return;
}
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 !");
return;
}
@@ -194,20 +196,20 @@ public class ConsoleCommandsHandler
}
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();
await ServerCom.DownloadFileNoProgressAsync(info[1], path);
bar.Stop("Plugin Downloaded !");
}
Console.WriteLine("\n");
Settings.Variables.outputStream.WriteLine("\n");
// check requirements if any
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]);
@@ -216,7 +218,7 @@ public class ConsoleCommandsHandler
if (!(line.Length > 0 && line.Contains(",")))
continue;
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 (OperatingSystem.WINDOWS == Functions.GetOperatingSystem())
{
@@ -224,32 +226,32 @@ public class ConsoleCommandsHandler
}
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();
await ServerCom.DownloadFileNoProgressAsync(split[0], "./" + split[1]);
bar.Stop("Item downloaded !");
}
Console.WriteLine();
Settings.Variables.outputStream.WriteLine();
if (split[0].EndsWith(".pak"))
{
File.Move("./" + split[1], "./Data/PAKS/" + split[1], true);
}
else if (split[0].EndsWith(".zip") || split[0].EndsWith(".pkg"))
{
Console.WriteLine($"Extracting {split[1]} ...");
var bar = new Console_Utilities.ProgressBar(
Settings.Variables.outputStream.WriteLine($"Extracting {split[1]} ...");
var bar = new Utilities.ProgressBar(
ProgressBarType.NO_END);
bar.Start();
await Functions.ExtractArchive("./" + split[1], "./", null,
UnzipProgressType.PercentageFromTotalSize);
bar.Stop("Extracted");
Console.WriteLine("\n");
Settings.Variables.outputStream.WriteLine("\n");
File.Delete("./" + split[1]);
}
}
Console.WriteLine();
Settings.Variables.outputStream.WriteLine();
}
var ver = await ServerCom.GetVersionOfPackageFromWeb(name);
@@ -269,7 +271,7 @@ public class ConsoleCommandsHandler
return;
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
{
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)
{
Console.WriteLine(ex.ToString());
Settings.Variables.outputStream.WriteLine(ex.ToString());
}
}
);
@@ -305,11 +307,11 @@ public class ConsoleCommandsHandler
{
if (client is null)
return;
var bar = new Console_Utilities.ProgressBar(ProgressBarType.NO_END);
var bar = new Utilities.ProgressBar(ProgressBarType.NO_END);
bar.Start();
bar.Stop("Saved config !");
Console.WriteLine();
Settings.Variables.outputStream.WriteLine();
Settings.sqlDatabase.Stop();
await client.StopAsync();
await client.DisposeAsync();
@@ -339,17 +341,17 @@ public class ConsoleCommandsHandler
{
var instance = (DBEvent)Activator.CreateInstance(type);
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))
{
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)
{
Console.WriteLine(ex.Message);
Settings.Variables.outputStream.WriteLine(ex.Message);
}
});
@@ -383,13 +385,13 @@ public class ConsoleCommandsHandler
if (!File.Exists(location))
{
Console.WriteLine("The plugin does not exist");
Settings.Variables.outputStream.WriteLine("The plugin does not exist");
return;
}
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);
if (info[2] != string.Empty)
@@ -404,7 +406,7 @@ public class ConsoleCommandsHandler
File.Delete("./" + split[1]);
Console.WriteLine("Removed: " + split[1]);
Settings.Variables.outputStream.WriteLine("Removed: " + split[1]);
}
if (Directory.Exists($"./Data/Plugins/{plugName}"))
@@ -415,7 +417,7 @@ public class ConsoleCommandsHandler
}
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", () =>
@@ -443,7 +445,7 @@ public class ConsoleCommandsHandler
commandList.Add(new ConsoleCommand
{ CommandName = command, Description = description, Action = action, Usage = usage });
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)
@@ -469,13 +471,10 @@ public class ConsoleCommandsHandler
public static async Task ExecuteCommad(string command)
{
var args = command.Split(' ');
// Console.WriteLine(command);
foreach (var item in commandList.ToList())
if (item.CommandName == args[0])
{
item.Action.Invoke(args);
Console.WriteLine();
while (isDownloading) await Task.Delay(1000);
}
}
@@ -491,17 +490,17 @@ public class ConsoleCommandsHandler
{
Console.SetCursorPosition(0, Console.CursorTop - 1);
for (var i = 0; i < command.Length + 30; i++)
Console.Write(" ");
Settings.Variables.outputStream.Write(" ");
Console.SetCursorPosition(0, Console.CursorTop);
}
Console.WriteLine();
Settings.Variables.outputStream.WriteLine();
item.Action(args);
return true;
}
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>();
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");
loader.FileLoaded += (args) => Functions.WriteLogFile($"{args.PluginName} file Loaded");
@@ -108,7 +108,7 @@ public class PluginLoader
private async void Loader_PluginLoaded(LoaderArgs args)
{
// Console.WriteLine(args.TypeName);
// Settings.Variables.outputStream.WriteLine(args.TypeName);
switch (args.TypeName)
{
case "DBCommand":
@@ -124,10 +124,10 @@ public class PluginLoader
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
Console.WriteLine("Plugin: " + args.PluginName);
Console.WriteLine("Type: " + args.TypeName);
Console.WriteLine("IsLoaded: " + args.IsLoaded);
Settings.Variables.outputStream.WriteLine(ex.ToString());
Settings.Variables.outputStream.WriteLine("Plugin: " + args.PluginName);
Settings.Variables.outputStream.WriteLine("Type: " + args.TypeName);
Settings.Variables.outputStream.WriteLine("IsLoaded: " + args.IsLoaded);
}
break;
case "DBSlashCommand":
@@ -139,73 +139,13 @@ public class PluginLoader
builder.WithDescription(slash.Description);
builder.WithDMPermission(slash.canUseDM);
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);
await _client.CreateGlobalApplicationCommandAsync(builder.Build());
}
//else Console.WriteLine("Failed to load " + args.PluginName + "\nException: " + args.Exception.Message);
break;
}
}
/*
private async void SlashLoader_PluginLoaded(LoaderArgs args)
{
if (args.IsLoaded)
{
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[] { "-", "-", "-", "-" });
Console_Utilities.FormatAndAlignTable(data, TableFormat.CENTER_EACH_COLUMN_BASED);
Utilities.FormatAndAlignTable(data, TableFormat.CENTER_EACH_COLUMN_BASED);
}
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());
}
}
@@ -116,7 +116,7 @@ public class PluginsManager
}
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());
}

View File

@@ -57,7 +57,7 @@ public static class ServerCom
var isDownloading = true;
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; });

View File

@@ -42,7 +42,7 @@ public class PluginUpdater
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() +
"&c. Current Version: &y" +
ServerCom.GetVersionOfPackage(pakName)?.ToShortString());

View File

@@ -4,7 +4,7 @@ using System.Threading.Tasks;
namespace PluginManager.Others;
public static class Console_Utilities
public static class Utilities
{
private static Dictionary<char, ConsoleColor> Colors = new()
{
@@ -46,38 +46,38 @@ public static class Console_Utilities
foreach (var row in data)
{
if (row[0][0] == tableLine)
Console.Write(tableCross);
Settings.Variables.outputStream.Write(tableCross);
else
Console.Write(tableWall);
Settings.Variables.outputStream.Write(tableWall);
for (var l = 0; l < row.Length; l++)
{
if (row[l][0] == tableLine)
{
for (var i = 0; i < len[l] + 4; ++i)
Console.Write(tableLine);
Settings.Variables.outputStream.Write(tableLine);
}
else if (row[l].Length == len[l])
{
Console.Write(" ");
Console.Write(row[l]);
Console.Write(" ");
Settings.Variables.outputStream.Write(" ");
Settings.Variables.outputStream.Write(row[l]);
Settings.Variables.outputStream.Write(" ");
}
else
{
var lenHalf = row[l].Length / 2;
for (var i = 0; i < (len[l] + 4) / 2 - lenHalf; ++i)
Console.Write(" ");
Console.Write(row[l]);
Settings.Variables.outputStream.Write(" ");
Settings.Variables.outputStream.Write(row[l]);
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)
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;
@@ -95,44 +95,44 @@ public static class Console_Utilities
foreach (var row in data)
{
Console.Write("\t");
Settings.Variables.outputStream.Write("\t");
if (row[0] == "-")
Console.Write("+");
Settings.Variables.outputStream.Write("+");
else
Console.Write("|");
Settings.Variables.outputStream.Write("|");
foreach (var s in row)
{
if (s == "-")
{
for (var i = 0; i < maxLen + 4; ++i)
Console.Write("-");
Settings.Variables.outputStream.Write("-");
}
else if (s.Length == maxLen)
{
Console.Write(" ");
Console.Write(s);
Console.Write(" ");
Settings.Variables.outputStream.Write(" ");
Settings.Variables.outputStream.Write(s);
Settings.Variables.outputStream.Write(" ");
}
else
{
var lenHalf = s.Length / 2;
for (var i = 0; i < div - lenHalf; ++i)
Console.Write(" ");
Console.Write(s);
Settings.Variables.outputStream.Write(" ");
Settings.Variables.outputStream.Write(s);
for (var i = div + lenHalf + 1; i < maxLen + 4; ++i)
Console.Write(" ");
Settings.Variables.outputStream.Write(" ");
if (s.Length % 2 == 0)
Console.Write(" ");
Settings.Variables.outputStream.Write(" ");
}
if (s == "-")
Console.Write("+");
Settings.Variables.outputStream.Write("+");
else
Console.Write("|");
Settings.Variables.outputStream.Write("|");
}
Console.WriteLine(); //end line
Settings.Variables.outputStream.WriteLine(); //end line
}
return;
@@ -153,12 +153,12 @@ public static class Console_Utilities
{
if (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++)
Console.Write(" ");
Settings.Variables.outputStream.Write(" ");
}
Console.WriteLine();
Settings.Variables.outputStream.WriteLine();
}
return;
@@ -169,6 +169,13 @@ public static class Console_Utilities
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 input = text.ToCharArray();
for (var i = 0; i < input.Length; i++)
@@ -190,12 +197,12 @@ public static class Console_Utilities
}
else
{
Console.Write(input[i]);
Settings.Variables.outputStream.Write(input[i]);
}
Console.ForegroundColor = initialForeGround;
if (appendNewLineAtEnd)
Console.WriteLine();
Settings.Variables.outputStream.WriteLine();
}
@@ -212,6 +219,8 @@ public static class Console_Utilities
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;
}
@@ -272,9 +281,9 @@ public static class Console_Utilities
{
Console.CursorLeft = 0;
for (var i = 0; i < BarLength + message.Length + 1; i++)
Console.Write(" ");
Settings.Variables.outputStream.Write(" ");
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)
{
Console.CursorLeft = 0;
Console.Write("[");
Settings.Variables.outputStream.Write("[");
for (var i = 1; i <= position; i++)
Console.Write(" ");
Console.Write("<==()==>");
Settings.Variables.outputStream.Write(" ");
Settings.Variables.outputStream.Write("<==()==>");
position += positive ? 1 : -1;
for (var i = position; i <= BarLength - 1 - (positive ? 0 : 2); i++)
Console.Write(" ");
Console.Write("] " + message);
Settings.Variables.outputStream.Write(" ");
Settings.Variables.outputStream.Write("] " + message);
if (position == BarLength - 1 || position == 1)
@@ -306,14 +315,14 @@ public static class Console_Utilities
private void UpdateNoEnd()
{
Console.CursorLeft = 0;
Console.Write("[");
Settings.Variables.outputStream.Write("[");
for (var i = 1; i <= position; i++)
Console.Write(" ");
Console.Write("<==()==>");
Settings.Variables.outputStream.Write(" ");
Settings.Variables.outputStream.Write("<==()==>");
position += positive ? 1 : -1;
for (var i = position; i <= BarLength - 1 - (positive ? 0 : 2); i++)
Console.Write(" ");
Console.Write("]");
Settings.Variables.outputStream.Write(" ");
Settings.Variables.outputStream.Write("]");
if (position == BarLength - 1 || position == 1)
@@ -323,9 +332,9 @@ public static class Console_Utilities
private void UpdateNormal(float progress)
{
Console.CursorLeft = 0;
Console.Write("[");
Settings.Variables.outputStream.Write("[");
Console.CursorLeft = BarLength;
Console.Write("]");
Settings.Variables.outputStream.Write("]");
Console.CursorLeft = 1;
var onechunk = 30.0f / Max;
@@ -335,22 +344,22 @@ public static class Console_Utilities
{
Console.BackgroundColor = NoColor ? ConsoleColor.Black : Color;
Console.CursorLeft = position++;
Console.Write("#");
Settings.Variables.outputStream.Write("#");
}
for (var i = position; i < BarLength; i++)
{
Console.BackgroundColor = NoColor ? ConsoleColor.Black : ConsoleColor.DarkGray;
Console.CursorLeft = position++;
Console.Write(" ");
Settings.Variables.outputStream.Write(" ");
}
Console.CursorLeft = BarLength + 4;
Console.BackgroundColor = ConsoleColor.Black;
if (progress.CanAproximateTo(Max))
Console.Write(progress + " % ✓");
Settings.Variables.outputStream.Write(progress + " % ✓");
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)
{
Console.WriteLine($"Failed to extract {entry.Name}. Exception: {ex.Message}");
Settings.Variables.outputStream.WriteLine($"Failed to extract {entry.Name}. Exception: {ex.Message}");
}
currentZIPFile++;
@@ -229,7 +229,7 @@ public static class Functions
}
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);

View File

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

View File

@@ -1,5 +1,6 @@
using PluginManager.Database;
using PluginManager.Others;
using System.IO;
using PluginManager.Database;
namespace PluginManager
{
@@ -11,6 +12,7 @@ namespace PluginManager
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 TextWriter outputStream;
}
public static SqlDatabase sqlDatabase;

View File

@@ -11,7 +11,7 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MusicLibrary", "..\DiscordB
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SlashCommands", "..\DiscordBotItems\Plugins\SlashCommands\SlashCommands.csproj", "{C2D73BE8-997B-4A4A-8EA5-989BE33EE1DD}"
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
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution