80 Commits

Author SHA1 Message Date
f3c3c7939c Fixed some outputs in plugin manager 2023-08-06 17:37:02 +03:00
361ed37362 Reimplemented error handling for SettingsFile 2023-08-06 17:14:57 +03:00
ed3128b940 Created a batch file to build on windows 2023-08-06 14:25:18 +03:00
6bbd68a135 Fixed release Config not found bug 2023-08-05 21:54:05 +03:00
06d322b5b3 Removed temp file creation 2023-08-05 21:53:08 +03:00
5497ee9119 - 2023-08-05 21:33:16 +03:00
0aa78e3560 Changed README.md 2023-08-05 21:32:49 +03:00
41ad37b3bb Fixed a bug when loading empty json file 2023-08-05 21:25:47 +03:00
0104d09509 Delete .github/workflows directory 2023-08-01 21:33:45 +03:00
b4f5e40f12 Moved items and reimplemented SettingsDictionary.cs 2023-08-01 21:28:44 +03:00
7107b17f19 Update README.md 2023-07-31 22:15:24 +03:00
42e1fd917e Removed some logs from console about json files that are opened 2023-07-31 22:10:26 +03:00
9e6fcdbe6f removed submodules 2023-07-31 21:47:43 +03:00
a24d8aa222 Removed dependencies 2023-07-31 21:11:17 +03:00
0e5c9ff14b Fixed help message on /help command 2023-07-31 20:55:38 +03:00
f8977d8840 Update submodules 2023-07-30 23:09:34 +03:00
bb9768f3a1 patch 2023-07-30 22:30:53 +03:00
b3d6930142 Updated functions in Discord Bot 2023-07-30 22:26:43 +03:00
5254be44be Added plugins folder to solution 2023-07-30 18:36:41 +03:00
207e0d6abd Added plugins submodule 2023-07-30 18:32:47 +03:00
968d23380f message 2023-07-30 18:31:06 +03:00
fff9e2e897 - 2023-07-30 18:27:05 +03:00
3e4e777d8d updated project file 2023-07-30 18:22:20 +03:00
7f906d400f - 2023-07-20 20:38:52 +03:00
c1161a3bca Bot no longer exits when a plugin fails to load 2023-07-20 11:32:15 +03:00
ac512e3a27 Updated display when installing a new plugin 2023-07-16 00:18:27 +03:00
730b628fe3 New method in archive manager and shortcut on exit command 2023-07-15 23:23:06 +03:00
701edc5c6a Update README.md 2023-07-10 21:29:36 +03:00
e7688762b8 Moved to API v11 due to the discriminator removal from discord 2023-07-05 21:01:51 +03:00
a7a71bf49a The logger now supports colors 2023-07-05 19:30:38 +03:00
ac7212ca00 Merge remote-tracking branch 'origin/preview' into preview 2023-07-03 14:40:08 +03:00
298e557260 Fixed some text and added some missing texts to commands. Added new command to clear screen and formated code. 2023-07-03 14:39:50 +03:00
7ba791f906 Create dotnet.yml 2023-07-01 17:37:59 +03:00
4a6a12baae Moved to API v3.10.0 2023-06-26 14:55:54 +03:00
f1dda5da3c Added new functions into Functions.cs and added help command for slash Commands. 2023-06-26 14:51:15 +03:00
3ab96e2d0d Fixed some warnings 2023-06-25 21:35:53 +03:00
970c519a32 Fixed loading plugins at startup 2023-06-15 22:12:15 +03:00
188920ec7f Cleaned up after removal of old commands 2023-06-15 21:59:48 +03:00
dcfc4ea32f Removed ConsoleCommandsHandler_OLD.cs 2023-06-15 21:57:22 +03:00
a8c02176d3 Fixed bug in PluginManager at getting info about plugin & new console commands 2023-06-15 21:55:42 +03:00
1665d47a25 Fixed a bug with invalid token bot startup 2023-06-15 14:46:28 +03:00
0b2f1e6ab6 Reimplemented Command Actions. 2023-06-07 20:36:11 +03:00
bcd9245502 update to display the changelogs for application when an update was found 2023-05-28 19:17:06 +03:00
59da9b295b 2023-05-28 19:14:39 +03:00
99d7d5e7e7 self update removed 2023-05-28 19:08:23 +03:00
e4c60f1606 builder added 2023-05-28 17:54:14 +03:00
77f1bef862 Changed from TextType to LogLevel 2023-05-28 17:37:19 +03:00
f16c139362 The bot is running on the main Thread now 2023-05-28 17:18:55 +03:00
c94cdca6eb New plugin downloader based on threads 2023-05-27 16:28:01 +03:00
dcdf80112d Merge branch 'preview' of https://github.com/Wizzy69/SethDiscordBot into preview 2023-05-23 17:00:14 +03:00
eb836c5b74 2023-05-23 17:00:10 +03:00
de680c6771 removed the economy plugin from the sln 2023-05-21 10:28:08 +03:00
Wizzy69
bcef58a46b Removed plugins from the project and reworked the Plugin Manager 2023-04-29 19:35:19 +03:00
Wizzy69
0dc8cdbce5 2023-04-29 18:57:33 +03:00
Wizzy69
dbdbaa9802 2023-04-29 18:57:26 +03:00
Tudor Andrei
5edcf93371 cleaning up PluginManager (phase 1) 2023-04-25 14:27:55 +03:00
Andrei Tudor
b0be76c62b Created new logger 2023-04-20 19:52:55 +03:00
75a77389a8 2023-04-13 19:58:16 +03:00
0bbced3d58 patch 2023-04-09 20:47:21 +03:00
244209093e patch on discord bot UI 2023-04-08 15:54:39 +03:00
54a68d635d 2023-04-08 13:48:53 +03:00
d7a5cb5a64 updated .vscode 2023-04-08 13:45:41 +03:00
6124f89cb0 updated to start the webpage at startup 2023-04-08 13:33:16 +03:00
810a527cc1 Discord Bot web UI first preview 2023-04-08 13:18:25 +03:00
0a2dff0c6d 2023-04-07 10:02:40 +03:00
382c376c03 2023-04-07 10:01:10 +03:00
84b7d663bc fixed README 2023-04-07 09:59:41 +03:00
623232b67e added documentation to the sql database class 2023-04-07 09:42:36 +03:00
d5df6cfb9d update 2023-04-05 20:10:43 +03:00
10b9548c29 Delete test directory 2023-04-01 16:16:02 +03:00
fa1a136ef1 2023-04-01 16:15:49 +03:00
d20cb62139 Updated initial setup 2023-04-01 16:14:04 +03:00
f2418d0395 fixed start error when no config file exists or is null 2023-03-25 11:51:48 +02:00
460a85944a changed to .json file instead of database for settings 2023-03-24 21:52:03 +02:00
7e2fa02d07 2023-03-11 00:07:11 +02:00
873855937f 2023-02-24 16:46:59 +02:00
1cdd2644df 2023-02-24 11:37:21 +02:00
532540b74f 2023-02-24 11:36:43 +02:00
9ba4ca43e2 Update 2023-02-24 11:12:23 +02:00
8bcaf3f254 2023-02-14 11:33:03 +02:00
57 changed files with 2789 additions and 2831 deletions

5
.gitignore vendored
View File

@@ -370,4 +370,7 @@ FodyWeavers.xsd
/Plugins/ /Plugins/
/DiscordBot.rar /DiscordBot.rar
/DiscordBot/Data/ /DiscordBot/Data/
/DiscordBot/Updater/ /DiscordBot/Updater/
.idea/
DiscordBot/Launcher.exe
DiscordBotUI/*

26
.vscode/launch.json vendored Normal file
View File

@@ -0,0 +1,26 @@
{
"version": "0.2.0",
"configurations": [
{
// Use IntelliSense to find out which attributes exist for C# debugging
// Use hover for the description of the existing attributes
// For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md
"name": ".NET Core Launch (console)",
"type": "coreclr",
"request": "launch",
"preLaunchTask": "build",
// If you have changed target frameworks, make sure to update the program path.
"program": "${workspaceFolder}/DiscordBot/bin/Debug/net6.0/DiscordBot.dll",
"args": [],
"cwd": "${workspaceFolder}/DiscordBot/bin/Debug/net6.0/",
// For more information about the 'console' field, see https://aka.ms/VSCode-CS-LaunchJson-Console
"console": "externalTerminal",
"stopAtEntry": false
},
{
"name": ".NET Core Attach",
"type": "coreclr",
"request": "attach"
}
]
}

41
.vscode/tasks.json vendored Normal file
View File

@@ -0,0 +1,41 @@
{
"version": "2.0.0",
"tasks": [
{
"label": "build",
"command": "dotnet",
"type": "process",
"args": [
"build",
"${workspaceFolder}/DiscordBot/DiscordBot.csproj",
"/property:GenerateFullPaths=true",
"/consoleloggerparameters:NoSummary"
],
"problemMatcher": "$msCompile"
},
{
"label": "publish",
"command": "dotnet",
"type": "process",
"args": [
"publish",
"${workspaceFolder}/DiscordBot/DiscordBot.csproj",
"/property:GenerateFullPaths=true",
"/consoleloggerparameters:NoSummary"
],
"problemMatcher": "$msCompile"
},
{
"label": "watch",
"command": "dotnet",
"type": "process",
"args": [
"watch",
"run",
"--project",
"${workspaceFolder}/DiscordBot/DiscordBot.csproj"
],
"problemMatcher": "$msCompile"
}
]
}

View File

@@ -0,0 +1,24 @@
using System;
using System.Threading.Tasks;
using PluginManager;
using PluginManager.Interfaces;
using PluginManager.Others;
namespace DiscordBot.Bot.Actions;
public class Clear : ICommandAction
{
public string ActionName => "clear";
public string Description => "Clears the console";
public string Usage => "clear";
public InternalActionRunType RunType => InternalActionRunType.ON_CALL;
public Task Execute(string[] args)
{
Console.Clear();
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("===== Seth Discord Bot =====");
Console.ResetColor();
return Task.CompletedTask;
}
}

View File

@@ -0,0 +1,47 @@
using System;
using System.Threading.Tasks;
using PluginManager;
using PluginManager.Interfaces;
using PluginManager.Others;
namespace DiscordBot.Bot.Actions;
public class Exit : ICommandAction
{
public string ActionName => "exit";
public string Description => "Exits the bot and saves the config. Use exit help for more info.";
public string Usage => "exit [help|force (-f)]";
public InternalActionRunType RunType => InternalActionRunType.ON_CALL;
public async Task Execute(string[] args)
{
if (args is null || args.Length == 0)
{
Config.Logger.Log("Exiting...", "Exit", isInternal: false);
await Config.AppSettings.SaveToFile();
await Config.Logger.SaveToFile();
Environment.Exit(0);
}
else
{
switch ( args[0] )
{
case "help":
Console.WriteLine("Usage : exit [help|force]");
Console.WriteLine("help : Displays this message");
Console.WriteLine("force | -f : Exits the bot without saving the config");
break;
case "-f":
case "force":
Config.Logger.Log("Exiting (FORCE)...", "Exit", LogLevel.WARNING, false);
Environment.Exit(0);
break;
default:
Console.WriteLine("Invalid argument !");
break;
}
}
}
}

View File

@@ -0,0 +1,62 @@
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using DiscordBot.Utilities;
using PluginManager.Interfaces;
using PluginManager.Others;
namespace DiscordBot.Bot.Actions;
public class Help : ICommandAction
{
public string ActionName => "help";
public string Description => "Shows the list of commands and their usage";
public string Usage => "help [command]";
public InternalActionRunType RunType => InternalActionRunType.ON_CALL;
public async Task Execute(string[] args)
{
if (args == null || args.Length == 0)
{
var items = new List<string[]>
{
new[] { "-", "-", "-" },
new[] { "Command", "Usage", "Description" },
new[] { "-", "-", "-" }
};
foreach (var a in Program.internalActionManager.Actions)
items.Add(new[] { a.Key, a.Value.Usage, a.Value.Description });
items.Add(new[] { "-", "-", "-" });
Utilities.Utilities.FormatAndAlignTable(items,
TableFormat.CENTER_EACH_COLUMN_BASED
);
return;
}
if (!Program.internalActionManager.Actions.ContainsKey(args[0]))
{
Console.WriteLine("Command not found");
return;
}
var action = Program.internalActionManager.Actions[args[0]];
var actionData = new List<string[]>
{
new[] { "-", "-", "-" },
new[] { "Command", "Usage", "Description" },
new[] { "-", "-", "-" },
new[] { action.ActionName, action.Usage, action.Description },
new[] { "-", "-", "-" }
};
Utilities.Utilities.FormatAndAlignTable(actionData,
TableFormat.CENTER_EACH_COLUMN_BASED
);
}
}

View File

@@ -0,0 +1,197 @@
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using DiscordBot.Utilities;
using PluginManager;
using PluginManager.Interfaces;
using PluginManager.Loaders;
using PluginManager.Online;
using PluginManager.Others;
namespace DiscordBot.Bot.Actions;
public class Plugin : ICommandAction
{
private bool pluginsLoaded;
public string ActionName => "plugin";
public string Description => "Manages plugins. Use plugin help for more info.";
public string Usage => "plugin [help|list|load|install]";
public InternalActionRunType RunType => InternalActionRunType.ON_CALL;
public async Task Execute(string[] args)
{
if (args is null || args.Length == 0 || args[0] == "help")
{
Console.WriteLine("Usage : plugin [help|list|load|install]");
Console.WriteLine("help : Displays this message");
Console.WriteLine("list : Lists all plugins");
Console.WriteLine("load : Loads all plugins");
Console.WriteLine("install : Installs a plugin");
return;
}
switch ( args[0] )
{
case "list":
var manager =
new PluginsManager(Program.URLs["PluginList"], Program.URLs["PluginVersions"]);
var data = await manager.GetAvailablePlugins();
var items = new List<string[]>
{
new[] { "-", "-", "-", "-" },
new[] { "Name", "Description", "Type", "Version" },
new[] { "-", "-", "-", "-" }
};
foreach (var plugin in data) items.Add(new[] { plugin[0], plugin[1], plugin[2], plugin[3] });
items.Add(new[] { "-", "-", "-", "-" });
Utilities.Utilities.FormatAndAlignTable(items, TableFormat.DEFAULT);
break;
case "load":
if (pluginsLoaded)
break;
var loader = new PluginLoader(Config.DiscordBot.client);
var cc = Console.ForegroundColor;
loader.onCMDLoad += (name, typeName, success, exception) =>
{
if (name == null || name.Length < 2)
name = typeName;
if (success)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("[CMD] Successfully loaded command : " + name);
}
else
{
Console.ForegroundColor = ConsoleColor.Red;
if (exception is null)
Console.WriteLine("An error occured while loading: " + name);
else
Console.WriteLine("[CMD] Failed to load command : " + name + " because " +
exception!.Message
);
}
Console.ForegroundColor = cc;
};
loader.onEVELoad += (name, typeName, success, exception) =>
{
if (name == null || name.Length < 2)
name = typeName;
if (success)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("[EVENT] Successfully loaded event : " + name);
}
else
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("[EVENT] Failed to load event : " + name + " because " + exception!.Message);
}
Console.ForegroundColor = cc;
};
loader.onSLSHLoad += (name, typeName, success, exception) =>
{
if (name == null || name.Length < 2)
name = typeName;
if (success)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("[SLASH] Successfully loaded command : " + name);
}
else
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("[SLASH] Failed to load command : " + name + " because " +
exception!.Message
);
}
Console.ForegroundColor = cc;
};
loader.LoadPlugins();
Console.ForegroundColor = cc;
pluginsLoaded = true;
break;
case "install":
var pluginName = string.Join(' ', args, 1, args.Length - 1);
if (string.IsNullOrEmpty(pluginName) || pluginName.Length < 2)
{
Console.WriteLine("Please specify a plugin name");
Console.Write("Plugin name : ");
pluginName = Console.ReadLine();
if (string.IsNullOrEmpty(pluginName) || pluginName.Length < 2)
{
Console.WriteLine("Invalid plugin name");
break;
}
}
var pluginManager =
new PluginsManager(Program.URLs["PluginList"], Program.URLs["PluginVersions"]);
var pluginData = await pluginManager.GetPluginLinkByName(pluginName);
if (pluginData == null || pluginData.Length == 0)
{
Console.WriteLine($"Plugin {pluginName} not found. Please check the spelling and try again.");
break;
}
var pluginType = pluginData[0];
var pluginLink = pluginData[1];
var pluginRequirements = pluginData[2];
Console.WriteLine("Downloading plugin...");
//download plugin progress bar for linux and windows terminals
var spinner = new Utilities.Utilities.Spinner();
spinner.Start();
IProgress<float> progress = new Progress<float>(p => { spinner.Message = $"Downloading {pluginName}... {Math.Round(p, 2)}% "; });
await ServerCom.DownloadFileAsync(pluginLink, $"./Data/{pluginType}s/{pluginName}.dll", progress);
spinner.Stop();
Console.WriteLine();
if (pluginRequirements == string.Empty)
{
Console.WriteLine("Plugin installed successfully");
break;
}
Console.WriteLine("Downloading plugin requirements...");
var requirementsURLs = await ServerCom.ReadTextFromURL(pluginRequirements);
foreach (var requirement in requirementsURLs)
{
if (requirement.Length < 2)
continue;
var reqdata = requirement.Split(',');
var url = reqdata[0];
var filename = reqdata[1];
Console.WriteLine($"Downloading {filename}... ");
spinner.Start();
await ServerCom.DownloadFileAsync(url, $"./{filename}.dll", null);
spinner.Stop();
await Task.Delay(1000);
Console.WriteLine("Downloaded " + filename + " successfully");
}
Console.WriteLine("Finished installing " + pluginName + " successfully");
break;
}
}
}

View File

@@ -1,14 +1,11 @@
using System; using System.Collections.Generic;
using System.Collections.Generic;
using Discord; using Discord;
using Discord.Commands;
using PluginManager; using PluginManager;
using PluginManager.Interfaces; using PluginManager.Interfaces;
using PluginManager.Loaders; using PluginManager.Loaders;
using PluginManager.Others; using PluginManager.Others;
namespace DiscordBot.Discord.Commands; namespace DiscordBot.Bot.Commands;
/// <summary> /// <summary>
/// The help command /// The help command
@@ -41,7 +38,7 @@ internal class Help : DBCommand
/// The main body of the command /// The main body of the command
/// </summary> /// </summary>
/// <param name="context">The command context</param> /// <param name="context">The command context</param>
public void ExecuteServer(CmdArgs args) public void ExecuteServer(DBCommandExecutingArguments args)
{ {
if (args.arguments is not null) if (args.arguments is not null)
{ {
@@ -50,26 +47,26 @@ internal class Help : DBCommand
args.context.Channel.SendMessageAsync("Unknown Command " + args.arguments[0]); args.context.Channel.SendMessageAsync("Unknown Command " + args.arguments[0]);
else else
args.context.Channel.SendMessageAsync(embed: e.Build()); args.context.Channel.SendMessageAsync(embed: e.Build());
return; return;
} }
var embedBuilder = new EmbedBuilder(); var embedBuilder = new EmbedBuilder();
var adminCommands = ""; var adminCommands = "";
var normalCommands = ""; var normalCommands = "";
foreach (var cmd in PluginLoader.Commands!) foreach (var cmd in PluginLoader.Commands)
if (cmd.requireAdmin) if (cmd.requireAdmin)
adminCommands += cmd.Command + " "; adminCommands += cmd.Command + " ";
else else
normalCommands += cmd.Command + " "; normalCommands += cmd.Command + " ";
if(adminCommands.Length > 0) if (adminCommands.Length > 0)
embedBuilder.AddField("Admin Commands", adminCommands); embedBuilder.AddField("Admin Commands", adminCommands);
if(normalCommands.Length > 0) if (normalCommands.Length > 0)
embedBuilder.AddField("Normal Commands", normalCommands); embedBuilder.AddField("Normal Commands", normalCommands);
args.context.Channel.SendMessageAsync(embed: embedBuilder.Build()); args.context.Channel.SendMessageAsync(embed: embedBuilder.Build());
} }
@@ -77,11 +74,12 @@ internal class Help : DBCommand
private EmbedBuilder GenerateHelpCommand(string command) private EmbedBuilder GenerateHelpCommand(string command)
{ {
var embedBuilder = new EmbedBuilder(); var embedBuilder = new EmbedBuilder();
var cmd = PluginLoader.Commands!.Find(p => p.Command == command || var cmd = PluginLoader.Commands.Find(p => p.Command == command ||
(p.Aliases is not null && p.Aliases.Contains(command))); p.Aliases is not null && p.Aliases.Contains(command)
);
if (cmd == null) return null; if (cmd == null) return null;
embedBuilder.AddField("Usage", Config.Variables.GetValue("prefix") + cmd.Usage); embedBuilder.AddField("Usage", Config.AppSettings["prefix"] + cmd.Usage);
embedBuilder.AddField("Description", cmd.Description); embedBuilder.AddField("Description", cmd.Description);
if (cmd.Aliases is null) if (cmd.Aliases is null)
return embedBuilder; return embedBuilder;
@@ -89,4 +87,4 @@ internal class Help : DBCommand
return embedBuilder; return embedBuilder;
} }
} }

View File

@@ -0,0 +1,57 @@
using System.Collections.Generic;
using System.Linq;
using Discord;
using Discord.WebSocket;
using PluginManager.Interfaces;
using PluginManager.Loaders;
using PluginManager.Others;
namespace DiscordBot.Bot.Commands.SlashCommands;
public class Help : DBSlashCommand
{
public string Name => "help";
public string Description => "This command allows you to check all loaded commands";
public bool canUseDM => true;
public List<SlashCommandOptionBuilder> Options =>
new()
{
new SlashCommandOptionBuilder()
.WithName("command")
.WithDescription("The command you want to get help for")
.WithRequired(false)
.WithType(ApplicationCommandOptionType.String)
};
public async void ExecuteServer(SocketSlashCommand context)
{
EmbedBuilder embedBuilder = new();
embedBuilder.WithTitle("Help Command");
embedBuilder.WithColor(Functions.RandomColor);
var slashCommands = PluginLoader.SlashCommands;
var options = context.Data.Options;
//Console.WriteLine("Options: " + options.Count);
if (options is null || options.Count == 0)
foreach (var slashCommand in slashCommands)
embedBuilder.AddField(slashCommand.Name, slashCommand.Description);
if (options.Count > 0)
{
var commandName = options.First().Name;
var slashCommand = slashCommands.FirstOrDefault(x => x.Name == commandName);
if (slashCommand is null)
{
await context.RespondAsync("Unknown Command " + commandName);
return;
}
embedBuilder.AddField(slashCommand.Name, slashCommand.canUseDM)
.WithDescription(slashCommand.Description);
}
await context.RespondAsync(embed: embedBuilder.Build());
}
}

View File

@@ -1,48 +1,42 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<PropertyGroup> <OutputType>Exe</OutputType>
<OutputType>Exe</OutputType> <TargetFramework>net6.0</TargetFramework>
<TargetFramework>net6.0</TargetFramework> <Nullable>disable</Nullable>
<Nullable>disable</Nullable> <ApplicationIcon/>
<ApplicationIcon /> <StartupObject/>
<StartupObject /> <SignAssembly>False</SignAssembly>
<SignAssembly>False</SignAssembly> <IsPublishable>True</IsPublishable>
<IsPublishable>True</IsPublishable> <AssemblyVersion>1.0.2.2</AssemblyVersion>
<AssemblyVersion>1.0.1.2</AssemblyVersion> </PropertyGroup>
</PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<DebugType>none</DebugType>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'"> </PropertyGroup>
<DebugType>none</DebugType> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
</PropertyGroup> <DebugType>none</DebugType>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'"> <ItemGroup>
<DebugType>none</DebugType> <Compile Remove="Data\**"/>
</PropertyGroup> <Compile Remove="obj\**"/>
<Compile Remove="Output\**"/>
<ItemGroup> </ItemGroup>
<Compile Remove="Data\**" /> <ItemGroup>
<Compile Remove="obj\**" /> <EmbeddedResource Remove="Data\**"/>
<Compile Remove="Output\**" /> <EmbeddedResource Remove="obj\**"/>
</ItemGroup> <EmbeddedResource Remove="Output\**"/>
</ItemGroup>
<ItemGroup> <ItemGroup>
<EmbeddedResource Remove="Data\**" /> <None Remove="Data\**"/>
<EmbeddedResource Remove="obj\**" /> <None Remove="obj\**"/>
<EmbeddedResource Remove="Output\**" /> <None Remove="Output\**"/>
</ItemGroup> <None Remove="builder.bat" />
<None Remove="builder.sh" />
<ItemGroup> </ItemGroup>
<None Remove="Data\**" /> <ItemGroup>
<None Remove="obj\**" /> <PackageReference Include="Discord.Net" Version="3.11.0"/>
<None Remove="Output\**" /> <PackageReference Include="Sodium.Core" Version="1.3.3"/>
</ItemGroup> </ItemGroup>
<ItemGroup>
<ItemGroup> <ProjectReference Include="..\PluginManager\PluginManager.csproj"/>
<PackageReference Include="Discord.Net" Version="3.9.0" /> </ItemGroup>
</ItemGroup> </Project>
<ItemGroup>
<ProjectReference Include="..\PluginManager\PluginManager.csproj" />
</ItemGroup>
</Project>

View File

@@ -1,32 +1,28 @@
using PluginManager.Others; using System;
using System;
using System.IO; using System.IO;
using System.Linq;
using System.Reflection; using System.Reflection;
using System.Threading.Tasks;
namespace DiscordBot namespace DiscordBot;
public class Entry
{ {
public static void Main(string[] args)
public class Entry
{ {
internal static StartupArguments startupArguments; var currentDomain = AppDomain.CurrentDomain;
public static void Main(string[] args) currentDomain.AssemblyResolve += LoadFromSameFolder;
static Assembly LoadFromSameFolder(object sender, ResolveEventArgs args)
{ {
AppDomain currentDomain = AppDomain.CurrentDomain; var folderPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
currentDomain.AssemblyResolve += new ResolveEventHandler(LoadFromSameFolder); "./Libraries"
);
static Assembly LoadFromSameFolder(object sender, ResolveEventArgs args) var assemblyPath = Path.Combine(folderPath, new AssemblyName(args.Name).Name + ".dll");
{ if (!File.Exists(assemblyPath)) return null;
string folderPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "./Libraries"); var assembly = Assembly.LoadFrom(assemblyPath);
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);
return assembly;
} }
Program.Startup(args);
} }
} }

64
DiscordBot/Installer.cs Normal file
View File

@@ -0,0 +1,64 @@
using System;
using System.IO;
using System.Threading.Tasks;
using PluginManager;
using PluginManager.Online;
namespace DiscordBot;
public static class Installer
{
public static void GenerateStartupConfig()
{
Console.WriteLine("Welcome to the SethBot installer !");
Console.WriteLine("First, we need to configure the bot. Don't worry, it will be quick !");
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.");
Console.WriteLine("The bot token is required to run the bot. You can get it from the Discord Developer Portal. (https://discord.com/developers/applications)");
if (!Config.AppSettings.ContainsKey("token"))
{
Console.WriteLine("Please enter the bot token :");
var token = Console.ReadLine();
Config.AppSettings.Add("token", token);
}
if (!Config.AppSettings.ContainsKey("prefix"))
{
Console.WriteLine("Please enter the bot prefix :");
var prefix = Console.ReadLine();
Config.AppSettings.Add("prefix", prefix);
}
if (!Config.AppSettings.ContainsKey("ServerID"))
{
Console.WriteLine("Please enter the Server ID :");
var serverId = Console.ReadLine();
Config.AppSettings.Add("ServerID", serverId);
}
Config.Logger.Log("Config Saved", "Installer", isInternal: true);
Config.AppSettings.SaveToFile();
Console.WriteLine("Config saved !");
}
public static async Task SetupPluginDatabase()
{
Console.WriteLine("The plugin database is required to run the bot but there is nothing configured yet.");
Console.WriteLine("Downloading the default database...");
await DownloadPluginDatabase();
}
private static async Task DownloadPluginDatabase(
string url = "https://raw.githubusercontent.com/andreitdr/SethDiscordBot/gh-pages/defaultURLs.json")
{
var path = "./Data/Resources/URLs.json";
Directory.CreateDirectory("./Data/Resources");
var spinner = new Utilities.Utilities.Spinner();
spinner.Start();
await ServerCom.DownloadFileAsync(url, path, null);
spinner.Stop();
}
}

View File

@@ -1,31 +1,22 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics;
using System.IO; using System.IO;
using System.Linq;
using System.Reflection; using System.Reflection;
using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using PluginManager.Bot;
using DiscordBot.Discord.Core;
using PluginManager;
using PluginManager.Database;
using PluginManager.Items;
using PluginManager.Online; using PluginManager.Online;
using PluginManager.Online.Helpers; using PluginManager.Online.Helpers;
using PluginManager.Others; using PluginManager.Others;
using PluginManager.Others.Actions;
using Terminal.Gui; using static PluginManager.Config;
using OperatingSystem = PluginManager.Others.OperatingSystem;
namespace DiscordBot; namespace DiscordBot;
public class Program public class Program
{ {
private static bool loadPluginsOnStartup; public static SettingsDictionary<string, string> URLs;
private static ConsoleCommandsHandler consoleCommandsHandler; public static InternalActionManager internalActionManager;
//private static bool isUI_ON;
/// <summary> /// <summary>
/// The main entry point for the application. /// The main entry point for the application.
@@ -35,17 +26,15 @@ public class Program
{ {
PreLoadComponents(args).Wait(); PreLoadComponents(args).Wait();
if (!Config.Variables.Exists("ServerID") || !Config.Variables.Exists("token") || if (!AppSettings.ContainsKey("ServerID") || !AppSettings.ContainsKey("token") ||
Config.Variables.GetValue("token") == null || AppSettings["token"] == null ||
(Config.Variables.GetValue("token")?.Length != 70 && Config.Variables.GetValue("token")?.Length != 59) || AppSettings["token"]?.Length != 70 && AppSettings["token"]?.Length != 59 ||
!Config.Variables.Exists("prefix") || Config.Variables.GetValue("prefix") == null || !AppSettings.ContainsKey("prefix") || AppSettings["prefix"] == null ||
Config.Variables.GetValue("prefix")?.Length != 1 || AppSettings["prefix"]?.Length != 1 ||
(args.Length == 1 && args[0] == "/reset")) args.Length == 1 && args[0] == "/reset")
{ Installer.GenerateStartupConfig();
GenerateStartUI("First time setup. Please fill the following with your discord bot data.\nThis are saved ONLY on YOUR computer.");
}
HandleInput(args).Wait(); HandleInput(args.ToList()).Wait();
} }
/// <summary> /// <summary>
@@ -54,24 +43,20 @@ public class Program
private static void NoGUI() private static void NoGUI()
{ {
#if DEBUG #if DEBUG
Logger.WriteLine(); Console.WriteLine("Debug mode enabled");
Logger.WriteLine("Debug mode enabled"); internalActionManager.Execute("plugin", "load").Wait(); // Load plugins at startup
Logger.WriteLine();
#endif #endif
if (loadPluginsOnStartup)
consoleCommandsHandler.HandleCommand("lp");
while (true) while (true)
{ {
var cmd = Console.ReadLine(); var cmd = Console.ReadLine();
if (!consoleCommandsHandler.HandleCommand(cmd! var args = cmd.Split(' ');
#if DEBUG var command = args[0];
, false args = args.Skip(1).ToArray();
#endif if (args.Length == 0)
args = null;
) && cmd.Length > 0) internalActionManager.Execute(command, args).Wait(); // Execute the command
Logger.WriteLine("Failed to run command " + cmd);
} }
} }
@@ -85,45 +70,49 @@ public class Program
Console.ForegroundColor = ConsoleColor.DarkYellow; Console.ForegroundColor = ConsoleColor.DarkYellow;
var startupMessageList = var startupMessageList =
await ServerCom.ReadTextFromURL( await ServerCom.ReadTextFromURL(URLs["StartupMessage"]);
"https://raw.githubusercontent.com/Wizzy69/installer/discord-bot-files/StartupMessage");
foreach (var message in startupMessageList) foreach (var message in startupMessageList)
Logger.WriteLine(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: {Settings.Variables.WebsiteURL}"); );
Console.WriteLine($"Git URL: {AppSettings["GitURL"]}");
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"
);
Console.ForegroundColor = ConsoleColor.White; Console.ForegroundColor = ConsoleColor.White;
if (Config.Variables.Exists("LaunchMessage")) if (AppSettings.ContainsKey("LaunchMessage"))
Utilities.WriteColorText(Config.Variables.GetValue("LaunchMessage")); Utilities.Utilities.WriteColorText(AppSettings["LaunchMessage"]);
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("============================ LOG ============================"); );
Console.WriteLine("Running on " + Functions.GetOperatingSystem());
Console.WriteLine("============================ LOG ============================");
try try
{ {
string token = ""; var token = "";
#if DEBUG #if DEBUG
if (File.Exists("./Data/Resources/token.txt")) token = File.ReadAllText("./Data/Resources/token.txt"); if (File.Exists("./Data/Resources/token.txt")) token = File.ReadAllText("./Data/Resources/token.txt");
else token = Config.Variables.GetValue("token"); else token = AppSettings["token"];
#else #else
token = Config.Variables.GetValue("token"); token = AppSettings["token"];
#endif #endif
var prefix = Config.Variables.GetValue("prefix"); var prefix = AppSettings["prefix"];
var discordbooter = new Boot(token, prefix); var discordbooter = new Boot(token, prefix);
await discordbooter.Awake(); await discordbooter.Awake();
return discordbooter; return discordbooter;
} }
catch (Exception ex) catch ( Exception ex )
{ {
Logger.LogError(ex); Logger.Log(ex.ToString(), "Bot", LogLevel.ERROR);
return null; return null;
} }
} }
@@ -132,91 +121,82 @@ public class Program
/// Handle user input arguments from the startup of the application /// Handle user input arguments from the startup of the application
/// </summary> /// </summary>
/// <param name="args">The arguments</param> /// <param name="args">The arguments</param>
private static async Task HandleInput(string[] args) private static async Task HandleInput(List<string> args)
{ {
var len = args.Length; Console.WriteLine("Loading Core ...");
var b = await StartNoGui(); //Handle arguments here:
consoleCommandsHandler = new ConsoleCommandsHandler(b.client);
if (Entry.startupArguments.loadPluginsAtStartup) { loadPluginsOnStartup = true; } if (args.Contains("--gui"))
if (len > 0 && args[0] == "/remplug")
{ {
var plugName = string.Join(' ', args, 1, args.Length - 1); // GUI not implemented yet
Logger.WriteLine("Starting to remove " + plugName); Console.WriteLine("GUI not implemented yet");
await ConsoleCommandsHandler.ExecuteCommad("remplug " + plugName); return;
loadPluginsOnStartup = true;
} }
// Starting bot after all arguments are handled
var mainThread = new Thread(() => var b = await StartNoGui();
try
{ {
try internalActionManager = new InternalActionManager("./Data/Actions", "*.dll");
await internalActionManager.Initialize();
NoGUI();
}
catch ( IOException ex )
{
if (ex.Message == "No process is on the other end of the pipe." || (uint)ex.HResult == 0x800700E9)
{ {
NoGUI(); if (AppSettings.ContainsKey("LaunchMessage"))
AppSettings.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 !"
);
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", LogLevel.ERROR
);
} }
catch (IOException ex) }
{
if (ex.Message == "No process is on the other end of the pipe." || (uint)ex.HResult == 0x800700E9)
{
if (Config.Variables.Exists("LaunchMessage"))
Config.Variables.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 !",
false);
Logger.WriteErrFile(ex.ToString());
}
}
});
mainThread.Start();
} }
private static async Task PreLoadComponents(string[] args) private static async Task PreLoadComponents(string[] args)
{ {
Directory.CreateDirectory("./Data/Resources"); await Initialize();
Directory.CreateDirectory("./Data/Plugins");
Directory.CreateDirectory("./Data/PAKS");
if (!File.Exists(Functions.dataFolder + "loader.json"))
{
Entry.startupArguments = new StartupArguments();
await Functions.SaveToJsonFile(Functions.dataFolder + "loader.json", Entry.startupArguments);
}
else
Entry.startupArguments = await Functions.ConvertFromJson<StartupArguments>(Functions.dataFolder + "loader.json");
Logger.LogEvent += (message, type, isInternal) =>
{
if (type == LogLevel.INFO)
Console.ForegroundColor = ConsoleColor.Green;
else if (type == LogLevel.WARNING)
Console.ForegroundColor = ConsoleColor.DarkYellow;
else if (type == LogLevel.ERROR)
Console.ForegroundColor = ConsoleColor.Red;
else if (type == LogLevel.CRITICAL)
Console.ForegroundColor = ConsoleColor.DarkRed;
Settings.sqlDatabase = new SqlDatabase("SetDB.dat"); Console.WriteLine($"[{type.ToString()}] {message}");
Console.ResetColor();
};
await Settings.sqlDatabase.Open(); if (!Directory.Exists("./Data/Resources") || !File.Exists("./Data/Resources/URLs.json"))
await Config.Initialize(); await Installer.SetupPluginDatabase();
Logger.Initialize(true);
ArchiveManager.Initialize();
Logger.LogEvent += (message) => { Console.Write(message); }; URLs = new SettingsDictionary<string, string>("./Data/Resources/URLs.json");
Logger.WriteLine("Loading resources ...");
var main = new Utilities.ProgressBar(ProgressBarType.NO_END);
main.Start();
if (await Config.Variables.ExistsAsync("DeleteLogsAtStartup")) Console.WriteLine("Loading resources ...");
if (await Config.Variables.GetValueAsync("DeleteLogsAtStartup") == "true")
if (AppSettings.ContainsKey("DeleteLogsAtStartup"))
if (AppSettings["DeleteLogsAtStartup"] == "true")
foreach (var file in Directory.GetFiles("./Output/Logs/")) foreach (var file in Directory.GetFiles("./Output/Logs/"))
File.Delete(file); File.Delete(file);
var OnlineDefaultKeys =
await ServerCom.ReadTextFromURL( var OnlineDefaultKeys = await ServerCom.ReadTextFromURL(URLs["SetupKeys"]);
"https://raw.githubusercontent.com/Wizzy69/installer/discord-bot-files/SetupKeys");
if (!await Config.Variables.ExistsAsync("Version")) AppSettings["Version"] = Assembly.GetExecutingAssembly().GetName().Version.ToString();
await Config.Variables.AddAsync("Version", Assembly.GetExecutingAssembly().GetName().Version.ToString(),
false);
else
await Config.Variables.SetValueAsync(
"Version", Assembly.GetExecutingAssembly().GetName().Version.ToString());
foreach (var key in OnlineDefaultKeys) foreach (var key in OnlineDefaultKeys)
{ {
@@ -224,129 +204,38 @@ public class Program
var s = key.Split(' '); var s = key.Split(' ');
try try
{ {
if (await Config.Variables.ExistsAsync(s[0])) await Config.Variables.SetValueAsync(s[0], s[1]); AppSettings[s[0]] = s[1];
else
await Config.Variables.AddAsync(s[0], s[1], s[2].ToLower() == "true");
} }
catch (Exception ex) catch ( Exception ex )
{ {
Logger.WriteErrFile(ex.Message); Logger.Log(ex.ToString(), "Bot", LogLevel.ERROR);
} }
} }
var onlineSettingsList = await ServerCom.ReadTextFromURL(URLs["Versions"]);
var onlineSettingsList =
await ServerCom.ReadTextFromURL(
"https://raw.githubusercontent.com/Wizzy69/installer/discord-bot-files/OnlineData");
main.Stop("Loaded online settings. Loading updates ...");
foreach (var key in onlineSettingsList) foreach (var key in onlineSettingsList)
{ {
if (key.Length <= 3 || !key.Contains(' ')) continue; if (key.Length <= 3 || !key.Contains(' ')) continue;
var s = key.Split(' '); var s = key.Split(' ');
switch (s[0]) switch ( s[0] )
{ {
case "CurrentVersion": case "CurrentVersion":
var newVersion = s[1]; var currentVersion = AppSettings["Version"];
if (!newVersion.Equals(await Config.Variables.GetValueAsync("Version"))) var newVersion = s[1];
if (new VersionString(newVersion) != new VersionString(newVersion))
{ {
var nVer = new VersionString(newVersion.Substring(2)); Console.WriteLine("A new updated was found. Check the changelog for more information.");
var cVer = new VersionString((await Config.Variables.GetValueAsync("Version")).Substring(2)); var changeLog = await ServerCom.ReadTextFromURL(URLs["Changelog"]);
if (cVer > nVer)
{
await Config.Variables.SetValueAsync("Version", "1." + cVer.ToShortString() + " (Beta)");
break;
}
Console.Clear();
Console.ForegroundColor = ConsoleColor.Red;
Logger.WriteLine("A new version of the bot is available !");
Console.ForegroundColor = ConsoleColor.Yellow;
Logger.WriteLine("Current version : " +
Assembly.GetExecutingAssembly().GetName().Version.ToString());
Console.ForegroundColor = ConsoleColor.Green;
Logger.WriteLine("New version : " + newVersion);
Console.ForegroundColor = ConsoleColor.White;
Logger.WriteLine("Changelog :");
List<string> changeLog = await ServerCom.ReadTextFromURL(
"https://raw.githubusercontent.com/Wizzy69/installer/discord-bot-files/VersionData/DiscordBot");
foreach (var item in changeLog) foreach (var item in changeLog)
Utilities.WriteColorText(item); Utilities.Utilities.WriteColorText(item);
Logger.WriteLine("Do you want to update the bot ? (y/n)"); Console.WriteLine("Current version: " + currentVersion);
if (Console.ReadKey().Key == ConsoleKey.Y) Console.WriteLine("Latest version: " + newVersion);
{
if (Functions.GetOperatingSystem() == OperatingSystem.WINDOWS)
{
var url =
$"https://github.com/Wizzy69/SethDiscordBot/releases/download/v{newVersion}/net6.0.zip";
Process.Start($"{Functions.dataFolder}Applications/Updater.exe",
$"{newVersion} {url} {Process.GetCurrentProcess().ProcessName}");
}
else
{
var url =
$"https://github.com/Wizzy69/SethDiscordBot/releases/download/v{newVersion}/net6.0_linux.zip";
if (Logger.isConsole)
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}% "); })); Console.WriteLine("Download from here: https://github.com/andreitdr/SethDiscordBot/releases");
await File.WriteAllTextAsync("Install.sh",
"#!/bin/bash\nunzip -qq -o update.zip \nrm update.zip\nchmod a+x DiscordBot");
Logger.WriteLine();
try Console.WriteLine("Press any key to continue ...");
{ Console.ReadKey();
Logger.WriteLine("executing: chmod a+x Install.sh");
Process.Start("chmod", "a+x Install.sh").WaitForExit();
Process.Start("Install.sh").WaitForExit();
Logger.WriteLine("executing: rm Install.sh");
Process.Start("rm", "Install.sh").WaitForExit();
Logger.WriteLine("The new version of the bot has been installed.");
Logger.WriteLine("Please restart the bot.");
Environment.Exit(0);
}
catch (Exception ex)
{
Logger.WriteErrFile(ex.Message);
if (ex.Message.Contains("Access de"))
Logger.WriteLine("Please run the bot as root.");
}
//Process.Start(Functions.dataFolder + "Applications/Updater", $"{url}");
}
}
}
break;
case "UpdaterVersion":
var updaternewversion = s[1];
if (Functions.GetOperatingSystem() == OperatingSystem.LINUX)
break;
if (!await Config.Variables.ExistsAsync("UpdaterVersion"))
await Config.Variables.AddAsync("UpdaterVersion", "0.0.0.0", false);
if (await Config.Variables.GetValueAsync("UpdaterVersion") != updaternewversion ||
!File.Exists(Functions.dataFolder+"Applications/Updater.exe"))
{
Console.Clear();
Logger.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.exe",
$"{Functions.dataFolder}Applications/Updater.exe");
//await ArchiveManager.ExtractArchive("./Updater.zip", "./", null,
// UnzipProgressType.PercentageFromTotalSize);
await Config.Variables.SetValueAsync("UpdaterVersion", updaternewversion);
// File.Delete("Updater.zip");
bar.Stop("Updater has been updated !");
Console.Clear();
} }
break; break;
@@ -355,146 +244,4 @@ public class Program
Console.Clear(); Console.Clear();
} }
}
public static void GenerateStartUI(string titleMessage)
{
Application.Init();
var top = Application.Top;
var win = new Window("Discord Bot Config - " + Assembly.GetExecutingAssembly().GetName().Version)
{
X = 0,
Y = 1,
Width = Dim.Fill(),
Height = Dim.Fill()
};
top.Add(win);
var labelInfo = new Label(titleMessage)
{
X = Pos.Center(),
Y = 2
};
var labelToken = new Label("Please insert your token here: ")
{
X = 5,
Y = 5
};
var textFiledToken = new TextField(Config.Variables.GetValue("token") ?? "")
{
X = Pos.Left(labelToken) + labelToken.Text.Length + 2,
Y = labelToken.Y,
Width = 70
};
var labelPrefix = new Label("Please insert your prefix here: ")
{
X = 5,
Y = 8
};
var textFiledPrefix = new TextField(Config.Variables.GetValue("prefix") ?? "")
{
X = Pos.Left(labelPrefix) + labelPrefix.Text.Length + 2,
Y = labelPrefix.Y,
Width = 1
};
var labelServerid = new Label("Please insert your server id here (optional): ")
{
X = 5,
Y = 11
};
var textFiledServerID = new TextField(Config.Variables.GetValue("ServerID") ?? "")
{
X = Pos.Left(labelServerid) + labelServerid.Text.Length + 2,
Y = labelServerid.Y,
Width = 18
};
var button = new Button("Submit")
{
X = Pos.Center() - 10,
Y = 16
};
var button2 = new Button("License")
{
X = Pos.Center() + 10,
Y = 16
};
var button3 = new Button("ⓘ")
{
X = Pos.Left(textFiledServerID) + 20,
Y = textFiledServerID.Y
};
Console.CancelKeyPress += (sender, e) => { top.Running = false; };
button.Clicked += () =>
{
var passMessage = "";
if (textFiledToken.Text.Length != 70 && textFiledToken.Text.Length != 59)
passMessage += "Invalid token, ";
if (textFiledPrefix.Text.ContainsAny("0123456789/\\ ") || textFiledPrefix.Text.Length != 1)
passMessage += "Invalid prefix, ";
if (textFiledServerID.Text.Length != 18 && textFiledServerID.Text.Length > 0)
passMessage += "Invalid serverID";
if (passMessage != "")
{
MessageBox.ErrorQuery("Discord Bot Settings",
"Failed to pass check. Invalid information given:\n" + passMessage, "Retry");
return;
}
Config.Variables.Add("ServerID", (string)textFiledServerID.Text, true);
Config.Variables.Add("token", (string)textFiledToken.Text, true);
Config.Variables.Add("prefix", (string)textFiledPrefix.Text, true);
MessageBox.Query("Discord Bot Settings", "Successfully saved config !\nJust start the bot :D",
"Start :D");
top.Running = false;
};
button2.Clicked += async () =>
{
var license =
await ServerCom.ReadTextFromURL(
"https://raw.githubusercontent.com/Wizzy69/installer/discord-bot-files/LICENSE.txt");
var ProductLicense =
"Seth Discord Bot\n\nDeveloped by Wizzy#9181\nThis application can be used and modified by anyone. Plugin development for this application is also free and supported";
var r = MessageBox.Query("Discord Bot Settings", ProductLicense, "Close", "Read about libraries used");
if (r == 1)
{
var i = 0;
while (i < license.Count)
{
var print_message = license[i++] + "\n";
for (; i < license.Count && !license[i].StartsWith("-----------"); i++)
print_message += license[i] + "\n";
if (print_message.Contains("https://"))
print_message += "\n\nCTRL + Click on a link to open it";
if (MessageBox.Query("Licenses", print_message, "Next", "Quit") == 1) break;
}
}
};
button3.Clicked += () =>
{
MessageBox.Query("Discord Bot Settings",
"Server ID can be found in Server settings => Widget => Server ID",
"Close");
};
win.Add(labelInfo, labelPrefix, labelServerid, labelToken);
win.Add(textFiledToken, textFiledPrefix, textFiledServerID, button3);
win.Add(button, button2);
Application.Run();
Application.Shutdown();
}
}

View File

@@ -1,14 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DiscordBot
{
internal class StartupArguments
{
public string runArgs { get; } = "";
public bool loadPluginsAtStartup { get; } = true;
}
}

View File

@@ -0,0 +1,243 @@
using System;
using System.Collections.Generic;
using System.Threading;
namespace DiscordBot.Utilities;
public static class Utilities
{
private static readonly Dictionary<char, ConsoleColor> Colors = new()
{
{ 'g', ConsoleColor.Green },
{ 'b', ConsoleColor.Blue },
{ 'r', ConsoleColor.Red },
{ 'm', ConsoleColor.Magenta },
{ 'y', ConsoleColor.Yellow }
};
private static readonly char ColorPrefix = '&';
private static bool CanAproximateTo(this float f, float y)
{
return MathF.Abs(f - y) < 0.000001;
}
/// <summary>
/// A way to create a table based on input data
/// </summary>
/// <param name="data">The List of arrays of strings that represent the rows.</param>
public static void FormatAndAlignTable(List<string[]> data, TableFormat format)
{
if (format == TableFormat.CENTER_EACH_COLUMN_BASED)
{
var tableLine = '-';
var tableCross = '+';
var tableWall = '|';
var len = new int[data[0].Length];
foreach (var line in data)
for (var i = 0; i < line.Length; i++)
if (line[i].Length > len[i])
len[i] = line[i].Length;
foreach (var row in data)
{
if (row[0][0] == tableLine)
Console.Write(tableCross);
else
Console.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);
}
else if (row[l].Length == len[l])
{
Console.Write(" ");
Console.Write(row[l]);
Console.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]);
for (var i = (len[l] + 4) / 2 + lenHalf + 1; i < len[l] + 4; ++i)
Console.Write(" ");
if (row[l].Length % 2 == 0)
Console.Write(" ");
}
Console.Write(row[l][0] == tableLine ? tableCross : tableWall);
}
Console.WriteLine(); //end line
}
return;
}
if (format == TableFormat.CENTER_OVERALL_LENGTH)
{
var maxLen = 0;
foreach (var row in data)
foreach (var s in row)
if (s.Length > maxLen)
maxLen = s.Length;
var div = (maxLen + 4) / 2;
foreach (var row in data)
{
Console.Write("\t");
if (row[0] == "-")
Console.Write("+");
else
Console.Write("|");
foreach (var s in row)
{
if (s == "-")
{
for (var i = 0; i < maxLen + 4; ++i)
Console.Write("-");
}
else if (s.Length == maxLen)
{
Console.Write(" ");
Console.Write(s);
Console.Write(" ");
}
else
{
var lenHalf = s.Length / 2;
for (var i = 0; i < div - lenHalf; ++i)
Console.Write(" ");
Console.Write(s);
for (var i = div + lenHalf + 1; i < maxLen + 4; ++i)
Console.Write(" ");
if (s.Length % 2 == 0)
Console.Write(" ");
}
if (s == "-")
Console.Write("+");
else
Console.Write("|");
}
Console.WriteLine(); //end line
}
return;
}
if (format == TableFormat.DEFAULT)
{
var widths = new int[data[0].Length];
var space_between_columns = 3;
for (var i = 0; i < data.Count; i++)
for (var j = 0; j < data[i].Length; j++)
if (data[i][j].Length > widths[j])
widths[j] = data[i][j].Length;
for (var i = 0; i < data.Count; i++)
{
for (var j = 0; j < data[i].Length; j++)
{
if (data[i][j] == "-")
data[i][j] = " ";
Console.Write(data[i][j]);
for (var k = 0; k < widths[j] - data[i][j].Length + 1 + space_between_columns; k++)
Console.Write(" ");
}
Console.WriteLine();
}
return;
}
throw new Exception("Unknown type of table");
}
public static void WriteColorText(string text, bool appendNewLineAtEnd = true)
{
var initialForeGround = Console.ForegroundColor;
var input = text.ToCharArray();
for (var i = 0; i < input.Length; i++)
if (input[i] == ColorPrefix)
{
if (i + 1 < input.Length)
{
if (Colors.ContainsKey(input[i + 1]))
{
Console.ForegroundColor = Colors[input[i + 1]];
i++;
}
else if (input[i + 1] == 'c')
{
Console.ForegroundColor = initialForeGround;
i++;
}
}
}
else
{
Console.Write(input[i]);
}
Console.ForegroundColor = initialForeGround;
if (appendNewLineAtEnd)
Console.WriteLine();
}
public class Spinner
{
private readonly string[] Sequence;
private bool isRunning;
public string Message;
private int position;
private Thread thread;
public Spinner()
{
Sequence = new[] { "|", "/", "-", "\\" };
position = 0;
}
public void Start()
{
Console.CursorVisible = false;
isRunning = true;
thread = new Thread(() =>
{
while (isRunning)
{
Console.SetCursorPosition(0, Console.CursorTop);
Console.Write(" " + Sequence[position] + " " + Message + " ");
position++;
if (position >= Sequence.Length)
position = 0;
Thread.Sleep(100);
}
}
);
thread.Start();
}
public void Stop()
{
isRunning = false;
Console.CursorVisible = true;
}
}
}

View File

@@ -0,0 +1,8 @@
namespace DiscordBot.Utilities;
public enum TableFormat
{
CENTER_EACH_COLUMN_BASED,
CENTER_OVERALL_LENGTH,
DEFAULT
}

35
DiscordBot/builder.bat Normal file
View File

@@ -0,0 +1,35 @@
@echo off
echo "Building..."
echo "Building linux-x64 not self-contained"
dotnet publish -r linux-x64 -p:PublishSingleFile=false --self-contained true -c Release -o ../publish/linux-x64
echo "Building win-x64 not self-contained"
dotnet publish -r win-x64 -p:PublishSingleFile=false --self-contained true -c Release -o ../publish/win-x64
echo "Building osx-x64 not self-contained"
dotnet publish -r osx-x64 -p:PublishSingleFile=false --self-contained true -c Release -o ../publish/osx-x64
echo "Building linux-x64 self-contained"
dotnet publish -r linux-x64 -p:PublishSingleFile=true --self-contained true -c Release -o ../publish/linux-x64-selfcontained
echo "Building win-x64 self-contained"
dotnet publish -r win-x64 -p:PublishSingleFile=true --self-contained true -c Release -o ../publish/win-x64-selfcontained
echo "Building osx-x64 self-contained"
dotnet publish -r osx-x64 -p:PublishSingleFile=true --self-contained true -c Release -o ../publish/osx-x64-selfcontained
echo "Zipping..."
mkdir ../publish/zip
zip -r ../publish/zip/linux-x64.zip ../publish/linux-x64
zip -r ../publish/zip/win-x64.zip ../publish/win-x64
zip -r ../publish/zip/osx-x64.zip ../publish/osx-x64
zip -r ../publish/zip/linux-x64-selfcontained.zip ../publish/linux-x64-selfcontained
zip -r ../publish/zip/win-x64-selfcontained.zip ../publish/win-x64-selfcontained
zip -r ../publish/zip/osx-x64-selfcontained.zip ../publish/osx-x64-selfcontained
echo "Done!"

36
DiscordBot/builder.sh Normal file
View File

@@ -0,0 +1,36 @@
# All files in this directory will be copied to the root of the container
echo "Building..."
echo "Building linux-x64 not self-contained"
dotnet publish -r linux-x64 -p:PublishSingleFile=false --self-contained true -c Release -o ./publish/linux-x64
echo "Building win-x64 not self-contained"
dotnet publish -r win-x64 -p:PublishSingleFile=false --self-contained true -c Release -o ./publish/win-x64
echo "Building osx-x64 not self-contained"
dotnet publish -r osx-x64 -p:PublishSingleFile=false --self-contained true -c Release -o ./publish/osx-x64
#One file per platform
echo "Building linux-x64 self-contained"
dotnet publish -r linux-x64 -p:PublishSingleFile=true --self-contained true -c Release -o ./publish/linux-x64-selfcontained
echo "Building win-x64 self-contained"
dotnet publish -r win-x64 -p:PublishSingleFile=true --self-contained true -c Release -o ./publish/win-x64-selfcontained
echo "Building osx-x64 self-contained"
dotnet publish -r osx-x64 -p:PublishSingleFile=true --self-contained true -c Release -o ./publish/osx-x64-selfcontained
echo "Zipping..."
mkdir ./publish/zip
zip -r ./publish/zip/linux-x64.zip ./publish/linux-x64
zip -r ./publish/zip/win-x64.zip ./publish/win-x64
zip -r ./publish/zip/osx-x64.zip ./publish/osx-x64
zip -r ./publish/zip/linux-x64-selfcontained.zip ./publish/linux-x64-selfcontained
zip -r ./publish/zip/win-x64-selfcontained.zip ./publish/win-x64-selfcontained
zip -r ./publish/zip/osx-x64-selfcontained.zip ./publish/osx-x64-selfcontained
echo "Done!"

View File

@@ -1,15 +1,13 @@
using System; using System;
using System.Threading.Tasks; using System.Threading.Tasks;
using Discord; using Discord;
using Discord.Commands; using Discord.Commands;
using Discord.WebSocket; using Discord.WebSocket;
using PluginManager.Others;
using PluginManager; namespace PluginManager.Bot;
namespace DiscordBot.Discord.Core; public class Boot
internal class Boot
{ {
/// <summary> /// <summary>
/// The bot prefix /// The bot prefix
@@ -44,34 +42,37 @@ internal class Boot
public Boot(string botToken, string botPrefix) public Boot(string botToken, string botPrefix)
{ {
this.botPrefix = botPrefix; this.botPrefix = botPrefix;
this.botToken = botToken; this.botToken = botToken;
} }
/// <summary> /// <summary>
/// Checks if the bot is ready /// Checks if the bot is ready
/// </summary> /// </summary>
/// <value> true if the bot is ready, othwerwise false </value> /// <value> true if the bot is ready, otherwise false </value>
public bool isReady { get; private set; } public bool isReady { get; private set; }
/// <summary> /// <summary>
/// The start method for the bot. This method is used to load the bot /// The start method for the bot. This method is used to load the bot
/// </summary> /// </summary>
/// <param name="config">
/// The discord socket config. If null then the default one will be applied (AlwaysDownloadUsers=true,
/// UseInteractionSnowflakeDate=false, GatewayIntents=GatewayIntents.All)
/// </param>
/// <returns>Task</returns> /// <returns>Task</returns>
public async Task Awake() public async Task Awake(DiscordSocketConfig? config = null)
{ {
var config = new DiscordSocketConfig if (config is null)
{ config = new DiscordSocketConfig
{
AlwaysDownloadUsers = true,
AlwaysDownloadUsers = true, //Disable system clock checkup (for responses at slash commands)
UseInteractionSnowflakeDate = false,
GatewayIntents = GatewayIntents.All
};
//Disable system clock checkup (for responses at slash commands) client = new DiscordSocketClient(config);
UseInteractionSnowflakeDate = false,
GatewayIntents = GatewayIntents.All
};
client = new DiscordSocketClient(config);
service = new CommandService(); service = new CommandService();
CommonTasks(); CommonTasks();
@@ -85,52 +86,51 @@ internal class Boot
await commandServiceHandler.InstallCommandsAsync(); await commandServiceHandler.InstallCommandsAsync();
await Task.Delay(2000); await Task.Delay(2000);
Config._DiscordBotClient = this;
while (!isReady) ; while (!isReady) ;
} }
private void CommonTasks() private void CommonTasks()
{ {
if (client == null) return; if (client == null) return;
client.LoggedOut += Client_LoggedOut; client.LoggedOut += Client_LoggedOut;
client.Log += Log; client.Log += Log;
client.LoggedIn += LoggedIn; client.LoggedIn += LoggedIn;
client.Ready += Ready; client.Ready += Ready;
client.Disconnected += Client_Disconnected; client.Disconnected += Client_Disconnected;
} }
private Task Client_Disconnected(Exception arg) private async Task Client_Disconnected(Exception arg)
{ {
if (arg.Message.Contains("401")) if (arg.Message.Contains("401"))
{ {
Config.Variables.RemoveKey("token"); Config.AppSettings.Remove("token");
Program.GenerateStartUI("The token is invalid"); Config.Logger.Log("The token is invalid. Please restart the bot and enter a valid token.", this,
LogLevel.ERROR);
await Config.AppSettings.SaveToFile();
await Task.Delay(4000);
Environment.Exit(0);
} }
Logger.WriteErrFile(arg);
return Task.CompletedTask;
} }
private async Task Client_LoggedOut() private async Task Client_LoggedOut()
{ {
Logger.WriteLine("Successfully Logged Out"); Config.Logger.Log("Successfully Logged Out", this);
await Log(new LogMessage(LogSeverity.Info, "Boot", "Successfully logged out from discord !")); await Log(new LogMessage(LogSeverity.Info, "Boot", "Successfully logged out from discord !"));
} }
private Task Ready() private Task Ready()
{ {
Console.Title = "ONLINE";
isReady = true; isReady = true;
return Task.CompletedTask; return Task.CompletedTask;
} }
private Task LoggedIn() private Task LoggedIn()
{ {
Console.Title = "CONNECTED"; Config.Logger.Log("Successfully Logged In", this);
Logger.WriteLine("The bot has been logged in at " + DateTime.Now.ToShortDateString() + " (" +
DateTime.Now.ToShortTimeString() + ")"
);
return Task.CompletedTask; return Task.CompletedTask;
} }
@@ -140,21 +140,13 @@ internal class Boot
{ {
case LogSeverity.Error: case LogSeverity.Error:
case LogSeverity.Critical: case LogSeverity.Critical:
Logger.WriteErrFile(message.Message); Config.Logger.Log(message.Message, this, LogLevel.ERROR);
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("[ERROR] " + message.Message);
Console.ForegroundColor = ConsoleColor.White;
break; break;
case LogSeverity.Info: case LogSeverity.Info:
case LogSeverity.Debug: case LogSeverity.Debug:
Logger.WriteLogFile(message.Message); Config.Logger.Log(message.Message, this);
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine("[INFO] " + message.Message);
Console.ForegroundColor = ConsoleColor.White;
break; break;
@@ -162,4 +154,4 @@ internal class Boot
return Task.CompletedTask; return Task.CompletedTask;
} }
} }

View File

@@ -1,8 +1,7 @@
using System; using System;
using System.Linq; using System.Linq;
using System.Reflection; using System.Reflection;
using System.Threading.Tasks; using System.Threading.Tasks;
using Discord.Commands; using Discord.Commands;
using Discord.WebSocket; using Discord.WebSocket;
using PluginManager.Interfaces; using PluginManager.Interfaces;
@@ -10,15 +9,13 @@ using PluginManager.Loaders;
using PluginManager.Others; using PluginManager.Others;
using PluginManager.Others.Permissions; using PluginManager.Others.Permissions;
using static PluginManager.Logger; namespace PluginManager.Bot;
namespace DiscordBot.Discord.Core;
internal class CommandHandler internal class CommandHandler
{ {
private readonly string botPrefix; private readonly string botPrefix;
private readonly DiscordSocketClient client; private readonly DiscordSocketClient client;
private readonly CommandService commandService; private readonly CommandService commandService;
/// <summary> /// <summary>
/// Command handler constructor /// Command handler constructor
@@ -28,10 +25,9 @@ internal class CommandHandler
/// <param name="botPrefix">The prefix to watch for</param> /// <param name="botPrefix">The prefix to watch for</param>
public CommandHandler(DiscordSocketClient client, CommandService commandService, string botPrefix) public CommandHandler(DiscordSocketClient client, CommandService commandService, string botPrefix)
{ {
this.client = client; this.client = client;
this.commandService = commandService; this.commandService = commandService;
this.botPrefix = botPrefix; this.botPrefix = botPrefix;
} }
/// <summary> /// <summary>
@@ -40,7 +36,7 @@ internal class CommandHandler
/// <returns></returns> /// <returns></returns>
public async Task InstallCommandsAsync() public async Task InstallCommandsAsync()
{ {
client.MessageReceived += MessageHandler; client.MessageReceived += MessageHandler;
client.SlashCommandExecuted += Client_SlashCommandExecuted; client.SlashCommandExecuted += Client_SlashCommandExecuted;
await commandService.AddModulesAsync(Assembly.GetEntryAssembly(), null); await commandService.AddModulesAsync(Assembly.GetEntryAssembly(), null);
} }
@@ -49,9 +45,7 @@ internal class CommandHandler
{ {
try try
{ {
var plugin = PluginLoader.SlashCommands! var plugin = PluginLoader.SlashCommands!.FirstOrDefault(p => p.Name == arg.Data.Name);
.Where(p => p.Name == arg.Data.Name)
.FirstOrDefault();
if (plugin is null) if (plugin is null)
throw new Exception("Failed to run command. !"); throw new Exception("Failed to run command. !");
@@ -63,13 +57,10 @@ internal class CommandHandler
} }
catch (Exception ex) catch (Exception ex)
{ {
Config.Logger.Log(ex.Message, "CommandHandler", LogLevel.ERROR);
Console.WriteLine(ex.ToString());
ex.WriteErrFile();
} }
return Task.CompletedTask; return Task.CompletedTask;
} }
/// <summary> /// <summary>
@@ -79,10 +70,9 @@ internal class CommandHandler
/// <returns></returns> /// <returns></returns>
private async Task MessageHandler(SocketMessage Message) private async Task MessageHandler(SocketMessage Message)
{ {
try try
{ {
if (Message.Author.IsBot) if (Message.Author.IsBot)
return; return;
if (Message as SocketUserMessage == null) if (Message as SocketUserMessage == null)
@@ -102,23 +92,23 @@ internal class CommandHandler
await commandService.ExecuteAsync(context, argPos, null); await commandService.ExecuteAsync(context, argPos, null);
DBCommand plugin; DBCommand? plugin;
string cleanMessage = ""; var cleanMessage = "";
if (message.HasMentionPrefix(client.CurrentUser, ref argPos)) if (message.HasMentionPrefix(client.CurrentUser, ref argPos))
{ {
string mentionPrefix = "<@" + client.CurrentUser.Id + ">"; var mentionPrefix = "<@" + client.CurrentUser.Id + ">";
plugin = PluginLoader.Commands! plugin = PluginLoader.Commands!
.Where .FirstOrDefault(plug => plug.Command ==
( message.Content.Substring(mentionPrefix.Length + 1)
plug => plug.Command == message.Content.Substring(mentionPrefix.Length+1).Split(' ')[0] || .Split(' ')[0] ||
( (
plug.Aliases is not null && plug.Aliases is not null &&
plug.Aliases.Contains(message.CleanContent.Substring(mentionPrefix.Length+1).Split(' ')[0]) plug.Aliases.Contains(message.CleanContent
) .Substring(mentionPrefix.Length + 1)
) .Split(' ')[0])
.FirstOrDefault(); ));
cleanMessage = message.Content.Substring(mentionPrefix.Length + 1); cleanMessage = message.Content.Substring(mentionPrefix.Length + 1);
} }
@@ -126,32 +116,29 @@ internal class CommandHandler
else else
{ {
plugin = PluginLoader.Commands! plugin = PluginLoader.Commands!
.Where( .FirstOrDefault(p => p.Command ==
p => p.Command == message.Content.Split(' ')[0].Substring(botPrefix.Length) || message.Content.Split(' ')[0].Substring(botPrefix.Length) ||
(p.Aliases is not null && (p.Aliases is not null &&
p.Aliases.Contains( p.Aliases.Contains(
message.Content.Split(' ')[0].Substring(botPrefix.Length)))) message.Content.Split(' ')[0]
.FirstOrDefault(); .Substring(botPrefix.Length))));
cleanMessage = message.Content.Substring(botPrefix.Length); cleanMessage = message.Content.Substring(botPrefix.Length);
} }
if (plugin is null)
throw new Exception($"Failed to run command ! " + message.CleanContent); if (plugin is null)
throw new Exception("Failed to run command ! " + message.CleanContent + " (user: " +
context.Message.Author.Username + " - " + context.Message.Author.Id + ")");
if (plugin.requireAdmin && !context.Message.Author.isAdmin()) if (plugin.requireAdmin && !context.Message.Author.isAdmin())
return; return;
string[] split = cleanMessage.Split(' '); var split = cleanMessage.Split(' ');
string[] argsClean = null; string[]? argsClean = null;
if(split.Length > 1) if (split.Length > 1)
argsClean = string.Join(' ', split, 1, split.Length-1).Split(' '); argsClean = string.Join(' ', split, 1, split.Length - 1).Split(' ');
CmdArgs cmd = new() { DBCommandExecutingArguments cmd = new(context, cleanMessage, split[0], argsClean);
context = context,
cleanContent = cleanMessage,
commandUsed = split[0],
arguments = argsClean
};
if (context.Channel is SocketDMChannel) if (context.Channel is SocketDMChannel)
plugin.ExecuteDM(cmd); plugin.ExecuteDM(cmd);
@@ -159,9 +146,7 @@ internal class CommandHandler
} }
catch (Exception ex) catch (Exception ex)
{ {
ex.WriteErrFile(); Config.Logger.Log(ex.Message, this, LogLevel.ERROR);
Console.WriteLine(ex.ToString());
} }
} }
} }

View File

@@ -1,202 +1,44 @@
using System; using System;
using System.IO;
using System.Threading.Tasks; using System.Threading.Tasks;
using PluginManager.Bot;
using PluginManager.Online.Helpers; using PluginManager.Others;
using PluginManager.Others.Logger;
namespace PluginManager; namespace PluginManager;
public static class Config public class Config
{ {
private static bool IsLoaded = false; private static bool IsLoaded;
public static DBLogger Logger;
public static SettingsDictionary<string, string>? AppSettings;
internal static Boot? _DiscordBotClient;
public static Boot? DiscordBot => _DiscordBotClient;
public static async Task Initialize() public static async Task Initialize()
{ {
if (IsLoaded) if (IsLoaded) return;
return;
if (!await Settings.sqlDatabase.TableExistsAsync("Plugins")) Directory.CreateDirectory("./Data/Resources");
await Settings.sqlDatabase.CreateTableAsync("Plugins", "PluginName", "Version"); Directory.CreateDirectory("./Data/Plugins");
if (!await Settings.sqlDatabase.TableExistsAsync("Variables")) Directory.CreateDirectory("./Data/PAKS");
await Settings.sqlDatabase.CreateTableAsync("Variables", "VarName", "Value", "ReadOnly"); Directory.CreateDirectory("./Data/Logs/Logs");
Directory.CreateDirectory("./Data/Logs/Errors");
AppSettings = new SettingsDictionary<string, string>("./Data/Resources/config.json");
AppSettings["LogFolder"] = "./Data/Logs/Logs";
AppSettings["ErrorFolder"] = "./Data/Logs/Errors";
Logger = new DBLogger();
ArchiveManager.Initialize();
IsLoaded = true; IsLoaded = true;
Logger.Log("Config initialized", LogLevel.INFO);
} }
public static class Variables }
{
public static async Task<string> GetValueAsync(string VarName)
{
if (!IsLoaded)
throw new Exception("Config is not loaded");
return await Settings.sqlDatabase.GetValueAsync("Variables", "VarName", VarName, "Value");
}
public static string GetValue(string VarName)
{
if (!IsLoaded)
throw new Exception("Config is not loaded");
return Settings.sqlDatabase.GetValue("Variables", "VarName", VarName, "Value");
}
public static async Task SetValueAsync(string VarName, string Value)
{
if (!IsLoaded)
throw new Exception("Config is not loaded");
if (await IsReadOnlyAsync(VarName))
throw new Exception($"Variable ({VarName}) is read only and can not be changed to {Value}");
await Settings.sqlDatabase.SetValueAsync("Variables", "VarName", VarName, "Value", Value);
}
public static void SetValue(string VarName, string Value)
{
if (!IsLoaded)
throw new Exception("Config is not loaded");
if (IsReadOnly(VarName))
throw new Exception($"Variable ({VarName}) is read only and can not be changed to {Value}");
Settings.sqlDatabase.SetValue("Variables", "VarName", VarName, "Value", Value);
}
public static async Task<bool> IsReadOnlyAsync(string VarName)
{
if (!IsLoaded)
throw new Exception("Config is not loaded");
return (await Settings.sqlDatabase.GetValueAsync("Variables", "VarName", VarName, "ReadOnly")).Equals("true", StringComparison.CurrentCultureIgnoreCase);
}
public static bool IsReadOnly(string VarName)
{
if (!IsLoaded)
throw new Exception("Config is not loaded");
return (Settings.sqlDatabase.GetValue("Variables", "VarName", VarName, "ReadOnly")).Equals("true", StringComparison.CurrentCultureIgnoreCase);
}
public static async Task SetReadOnlyAsync(string VarName, bool ReadOnly)
{
if (!IsLoaded)
throw new Exception("Config is not loaded");
await Settings.sqlDatabase.SetValueAsync("Variables", "VarName", VarName, "ReadOnly", ReadOnly ? "true" : "false");
}
public static void SetReadOnly(string VarName, bool ReadOnly)
{
if (!IsLoaded)
throw new Exception("Config is not loaded");
Settings.sqlDatabase.SetValue("Variables", "VarName", VarName, "ReadOnly", ReadOnly ? "true" : "false");
}
public static async Task<bool> ExistsAsync(string VarName)
{
if (!IsLoaded)
throw new Exception("Config is not loaded");
return await Settings.sqlDatabase.KeyExistsAsync("Variables", "VarName", VarName);
}
public static bool Exists(string VarName)
{
if (!IsLoaded)
throw new Exception("Config is not loaded");
return Settings.sqlDatabase.KeyExists("Variables", "VarName", VarName);
}
public static async Task AddAsync(string VarName, string Value, bool ReadOnly = false)
{
if (!IsLoaded)
throw new Exception("Config is not loaded");
if (await ExistsAsync(VarName))
{
await SetValueAsync(VarName, Value);
await SetReadOnlyAsync(VarName, ReadOnly);
return;
}
await Settings.sqlDatabase.InsertAsync("Variables", VarName, Value, ReadOnly ? "true" : "false");
}
public static void Add(string VarName, string Value, bool ReadOnly = false)
{
if (!IsLoaded)
throw new Exception("Config is not loaded");
if (Exists(VarName))
{
if (GetValue(VarName) == Value)
return;
SetValue(VarName, Value);
SetReadOnly(VarName, ReadOnly);
return;
}
Settings.sqlDatabase.Insert("Variables", VarName, Value, ReadOnly ? "true" : "false");
}
public static async Task RemoveKeyAsync(string VarName)
{
if (!IsLoaded)
throw new Exception("Config is not loaded");
await Settings.sqlDatabase.RemoveKeyAsync("Variables", "VarName", VarName);
}
public static void RemoveKey(string VarName)
{
if (!IsLoaded)
throw new Exception("Config is not loaded");
Settings.sqlDatabase.RemoveKey("Variables", "VarName", VarName);
}
}
public static class Plugins
{
public static async Task<string> GetVersionAsync(string pluginName)
{
if (!IsLoaded)
throw new Exception("Config is not loaded yet");
string result = await Settings.sqlDatabase.GetValueAsync("Plugins", "PluginName", pluginName, "Version");
if (result is null)
return "0.0.0";
return result;
}
public static string GetVersion(string pluginName)
{
if (!IsLoaded)
throw new Exception("Config is not loaded yet");
string result = Settings.sqlDatabase.GetValue("Plugins", "PluginName", pluginName, "Version");
if (result is null)
return "0.0.0";
return result;
}
public static async Task SetVersionAsync(string pluginName, VersionString version)
{
if (!IsLoaded)
throw new Exception("Config is not loaded yet");
if (!await Settings.sqlDatabase.KeyExistsAsync("Plugins", "PluginName", pluginName))
{
await Settings.sqlDatabase.InsertAsync("Plugins", pluginName, version.ToShortString());
return;
}
await Settings.sqlDatabase.SetValueAsync("Plugins", "PluginName", pluginName, "Version", version.ToShortString());
}
public static void SetVersion(string pluginName, VersionString version)
{
if (!IsLoaded)
throw new Exception("Config is not loaded yet");
if (!Settings.sqlDatabase.KeyExists("Plugins", "PluginName", pluginName))
{
Settings.sqlDatabase.Insert("Plugins", pluginName, version.ToShortString());
return;
}
Settings.sqlDatabase.SetValue("Plugins", "PluginName", pluginName, "Version", version.ToShortString());
}
}
}

View File

@@ -1,327 +1,482 @@
using System.Collections.Generic; using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SQLite; using System.Data.SQLite;
using System.IO; using System.IO;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace PluginManager.Database namespace PluginManager.Database;
public class SqlDatabase
{ {
public class SqlDatabase private readonly SQLiteConnection Connection;
/// <summary>
/// Initialize a SQL connection by specifing its private path
/// </summary>
/// <param name="fileName">The path to the database (it is starting from ./Data/Resources/)</param>
public SqlDatabase(string fileName)
{ {
private string ConnectionString; if (!fileName.StartsWith("./Data/Resources/"))
private SQLiteConnection Connection; fileName = Path.Combine("./Data/Resources", fileName);
if (!File.Exists(fileName))
public SqlDatabase(string fileName) SQLiteConnection.CreateFile(fileName);
{ var connectionString = $"URI=file:{fileName}";
if (!fileName.StartsWith("./Data/Resources/")) Connection = new SQLiteConnection(connectionString);
fileName = Path.Combine("./Data/Resources", fileName);
if (!File.Exists(fileName))
SQLiteConnection.CreateFile(fileName);
ConnectionString = $"URI=file:{fileName}";
Connection = new SQLiteConnection(ConnectionString);
}
public async Task Open()
{
await Connection.OpenAsync();
//Console.WriteLine("Opened database successfully");
}
public async Task InsertAsync(string tableName, params string[] values)
{
string query = $"INSERT INTO {tableName} VALUES (";
for (int i = 0; i < values.Length; i++)
{
query += $"'{values[i]}'";
if (i != values.Length - 1)
query += ", ";
}
query += ")";
SQLiteCommand command = new SQLiteCommand(query, Connection);
await command.ExecuteNonQueryAsync();
}
public void Insert(string tableName, params string[] values)
{
string query = $"INSERT INTO {tableName} VALUES (";
for (int i = 0; i < values.Length; i++)
{
query += $"'{values[i]}'";
if (i != values.Length - 1)
query += ", ";
}
query += ")";
SQLiteCommand command = new SQLiteCommand(query, Connection);
command.ExecuteNonQuery();
}
public async Task RemoveKeyAsync(string tableName, string KeyName, string KeyValue)
{
string query = $"DELETE FROM {tableName} WHERE {KeyName} = '{KeyValue}'";
SQLiteCommand command = new SQLiteCommand(query, Connection);
await command.ExecuteNonQueryAsync();
}
public void RemoveKey(string tableName, string KeyName, string KeyValue)
{
string query = $"DELETE FROM {tableName} WHERE {KeyName} = '{KeyValue}'";
SQLiteCommand command = new SQLiteCommand(query, Connection);
command.ExecuteNonQuery();
}
public async Task<bool> KeyExistsAsync(string tableName, string keyName, string KeyValue)
{
string query = $"SELECT * FROM {tableName} where {keyName} = '{KeyValue}'";
if (await ReadDataAsync(query) is not null)
return true;
return false;
}
public bool KeyExists(string tableName, string keyName, string KeyValue)
{
string query = $"SELECT * FROM {tableName} where {keyName} = '{KeyValue}'";
if (ReadData(query) is not null)
return true;
return false;
}
public async Task SetValueAsync(string tableName, string keyName, string KeyValue, string ResultColumnName,
string ResultColumnValue)
{
if (!await TableExistsAsync(tableName))
throw new System.Exception($"Table {tableName} does not exist");
await ExecuteAsync(
$"UPDATE {tableName} SET {ResultColumnName}='{ResultColumnValue}' WHERE {keyName}='{KeyValue}'");
}
public void SetValue(string tableName, string keyName, string KeyValue, string ResultColumnName,
string ResultColumnValue)
{
if (!TableExists(tableName))
throw new System.Exception($"Table {tableName} does not exist");
Execute($"UPDATE {tableName} SET {ResultColumnName}='{ResultColumnValue}' WHERE {keyName}='{KeyValue}'");
}
public async Task<string?> GetValueAsync(string tableName, string keyName, string KeyValue,
string ResultColumnName)
{
if (!await TableExistsAsync(tableName))
throw new System.Exception($"Table {tableName} does not exist");
return await ReadDataAsync($"SELECT {ResultColumnName} FROM {tableName} WHERE {keyName}='{KeyValue}'");
}
public string? GetValue(string tableName, string keyName, string KeyValue, string ResultColumnName)
{
if (!TableExists(tableName))
throw new System.Exception($"Table {tableName} does not exist");
return ReadData($"SELECT {ResultColumnName} FROM {tableName} WHERE {keyName}='{KeyValue}'");
}
public async void Stop()
{
await Connection.CloseAsync();
}
public async Task AddColumnsToTableAsync(string tableName, string[] columns)
{
var command = Connection.CreateCommand();
command.CommandText = $"SELECT * FROM {tableName}";
var reader = await command.ExecuteReaderAsync();
var tableColumns = new List<string>();
for (int i = 0; i < reader.FieldCount; i++)
tableColumns.Add(reader.GetName(i));
foreach (var column in columns)
{
if (!tableColumns.Contains(column))
{
command.CommandText = $"ALTER TABLE {tableName} ADD COLUMN {column} TEXT";
await command.ExecuteNonQueryAsync();
}
}
}
public void AddColumnsToTable(string tableName, string[] columns)
{
var command = Connection.CreateCommand();
command.CommandText = $"SELECT * FROM {tableName}";
var reader = command.ExecuteReader();
var tableColumns = new List<string>();
for (int i = 0; i < reader.FieldCount; i++)
tableColumns.Add(reader.GetName(i));
foreach (var column in columns)
{
if (!tableColumns.Contains(column))
{
command.CommandText = $"ALTER TABLE {tableName} ADD COLUMN {column} TEXT";
command.ExecuteNonQuery();
}
}
}
public async Task<bool> TableExistsAsync(string tableName)
{
var cmd = Connection.CreateCommand();
cmd.CommandText = $"SELECT name FROM sqlite_master WHERE type='table' AND name='{tableName}'";
var result = await cmd.ExecuteScalarAsync();
if (result == null)
return false;
return true;
}
public bool TableExists(string tableName)
{
var cmd = Connection.CreateCommand();
cmd.CommandText = $"SELECT name FROM sqlite_master WHERE type='table' AND name='{tableName}'";
var result = cmd.ExecuteScalar();
if (result == null)
return false;
return true;
}
public async Task CreateTableAsync(string tableName, params string[] columns)
{
var cmd = Connection.CreateCommand();
cmd.CommandText = $"CREATE TABLE IF NOT EXISTS {tableName} ({string.Join(", ", columns)})";
await cmd.ExecuteNonQueryAsync();
}
public void CreateTable(string tableName, params string[] columns)
{
var cmd = Connection.CreateCommand();
cmd.CommandText = $"CREATE TABLE IF NOT EXISTS {tableName} ({string.Join(", ", columns)})";
cmd.ExecuteNonQuery();
}
public async Task<int> ExecuteAsync(string query)
{
if (!Connection.State.HasFlag(System.Data.ConnectionState.Open))
await Connection.OpenAsync();
var command = new SQLiteCommand(query, Connection);
int answer = await command.ExecuteNonQueryAsync();
return answer;
}
public int Execute(string query)
{
if (!Connection.State.HasFlag(System.Data.ConnectionState.Open))
Connection.Open();
var command = new SQLiteCommand(query, Connection);
int r = command.ExecuteNonQuery();
return r;
}
public async Task<string?> ReadDataAsync(string query)
{
if (!Connection.State.HasFlag(System.Data.ConnectionState.Open))
await Connection.OpenAsync();
var command = new SQLiteCommand(query, Connection);
var reader = await command.ExecuteReaderAsync();
object[] values = new object[reader.FieldCount];
if (reader.Read())
{
reader.GetValues(values);
return string.Join<object>(" ", values);
}
return null;
}
public string? ReadData(string query)
{
if (!Connection.State.HasFlag(System.Data.ConnectionState.Open))
Connection.Open();
var command = new SQLiteCommand(query, Connection);
var reader = command.ExecuteReader();
object[] values = new object[reader.FieldCount];
if (reader.Read())
{
reader.GetValues(values);
return string.Join<object>(" ", values);
}
return null;
}
public async Task<object[]?> ReadDataArrayAsync(string query)
{
if (!Connection.State.HasFlag(System.Data.ConnectionState.Open))
await Connection.OpenAsync();
var command = new SQLiteCommand(query, Connection);
var reader = await command.ExecuteReaderAsync();
object[] values = new object[reader.FieldCount];
if (reader.Read())
{
reader.GetValues(values);
return values;
}
return null;
}
public async Task<List<string[]>?> ReadAllRowsAsync(string query)
{
if (!Connection.State.HasFlag(System.Data.ConnectionState.Open))
await Connection.OpenAsync();
var command = new SQLiteCommand(query, Connection);
var reader = await command.ExecuteReaderAsync();
if (!reader.HasRows)
return null;
List<string[]> rows = new();
while (await reader.ReadAsync())
{
string[] values = new string[reader.FieldCount];
reader.GetValues(values);
rows.Add(values);
}
if (rows.Count == 0) return null;
return rows;
}
public object[]? ReadDataArray(string query)
{
if (!Connection.State.HasFlag(System.Data.ConnectionState.Open))
Connection.Open();
var command = new SQLiteCommand(query, Connection);
var reader = command.ExecuteReader();
object[] values = new object[reader.FieldCount];
if (reader.Read())
{
reader.GetValues(values);
return values;
}
return null;
}
} }
}
/// <summary>
/// Open the SQL Connection. To close use the Stop() method
/// </summary>
/// <returns></returns>
public async Task Open()
{
await Connection.OpenAsync();
}
/// <summary>
/// <para>
/// Insert into a specified table some values
/// </para>
/// </summary>
/// <param name="tableName">The table name</param>
/// <param name="values">The values to be inserted (in the correct order and number)</param>
/// <returns></returns>
public async Task InsertAsync(string tableName, params string[] values)
{
var query = $"INSERT INTO {tableName} VALUES (";
for (var i = 0; i < values.Length; i++)
{
query += $"'{values[i]}'";
if (i != values.Length - 1)
query += ", ";
}
query += ")";
var command = new SQLiteCommand(query, Connection);
await command.ExecuteNonQueryAsync();
}
/// <summary>
/// <para>
/// Insert into a specified table some values
/// </para>
/// </summary>
/// <param name="tableName">The table name</param>
/// <param name="values">The values to be inserted (in the correct order and number)</param>
/// <returns></returns>
public void Insert(string tableName, params string[] values)
{
var query = $"INSERT INTO {tableName} VALUES (";
for (var i = 0; i < values.Length; i++)
{
query += $"'{values[i]}'";
if (i != values.Length - 1)
query += ", ";
}
query += ")";
var command = new SQLiteCommand(query, Connection);
command.ExecuteNonQuery();
}
/// <summary>
/// Remove every row in a table that has a certain propery
/// </summary>
/// <param name="tableName">The table name</param>
/// <param name="KeyName">The column name that the search is made by</param>
/// <param name="KeyValue">The value that is searched in the specified column</param>
/// <returns></returns>
public async Task RemoveKeyAsync(string tableName, string KeyName, string KeyValue)
{
var query = $"DELETE FROM {tableName} WHERE {KeyName} = '{KeyValue}'";
var command = new SQLiteCommand(query, Connection);
await command.ExecuteNonQueryAsync();
}
/// <summary>
/// Remove every row in a table that has a certain propery
/// </summary>
/// <param name="tableName">The table name</param>
/// <param name="KeyName">The column name that the search is made by</param>
/// <param name="KeyValue">The value that is searched in the specified column</param>
/// <returns></returns>
public void RemoveKey(string tableName, string KeyName, string KeyValue)
{
var query = $"DELETE FROM {tableName} WHERE {KeyName} = '{KeyValue}'";
var command = new SQLiteCommand(query, Connection);
command.ExecuteNonQuery();
}
/// <summary>
/// Check if the key exists in the table
/// </summary>
/// <param name="tableName">The table name</param>
/// <param name="keyName">The column that the search is made by</param>
/// <param name="KeyValue">The value that is searched in the specified column</param>
/// <returns></returns>
public async Task<bool> KeyExistsAsync(string tableName, string keyName, string KeyValue)
{
var query = $"SELECT * FROM {tableName} where {keyName} = '{KeyValue}'";
if (await ReadDataAsync(query) is not null)
return true;
return false;
}
/// <summary>
/// Check if the key exists in the table
/// </summary>
/// <param name="tableName">The table name</param>
/// <param name="keyName">The column that the search is made by</param>
/// <param name="KeyValue">The value that is searched in the specified column</param>
/// <returns></returns>
public bool KeyExists(string tableName, string keyName, string KeyValue)
{
var query = $"SELECT * FROM {tableName} where {keyName} = '{KeyValue}'";
if (ReadData(query) is not null)
return true;
return false;
}
/// <summary>
/// Set value of a column in a table
/// </summary>
/// <param name="tableName">The table name</param>
/// <param name="keyName">The column that the search is made by</param>
/// <param name="KeyValue">The value that is searched in the column specified</param>
/// <param name="ResultColumnName">The column that has to be modified</param>
/// <param name="ResultColumnValue">The new value that will replace the old value from the column specified</param>
public async Task SetValueAsync(
string tableName, string keyName, string KeyValue, string ResultColumnName,
string ResultColumnValue)
{
if (!await TableExistsAsync(tableName))
throw new Exception($"Table {tableName} does not exist");
await ExecuteAsync(
$"UPDATE {tableName} SET {ResultColumnName}='{ResultColumnValue}' WHERE {keyName}='{KeyValue}'");
}
/// <summary>
/// Set value of a column in a table
/// </summary>
/// <param name="tableName">The table name</param>
/// <param name="keyName">The column that the search is made by</param>
/// <param name="KeyValue">The value that is searched in the column specified</param>
/// <param name="ResultColumnName">The column that has to be modified</param>
/// <param name="ResultColumnValue">The new value that will replace the old value from the column specified</param>
public void SetValue(
string tableName, string keyName, string KeyValue, string ResultColumnName,
string ResultColumnValue)
{
if (!TableExists(tableName))
throw new Exception($"Table {tableName} does not exist");
Execute($"UPDATE {tableName} SET {ResultColumnName}='{ResultColumnValue}' WHERE {keyName}='{KeyValue}'");
}
/// <summary>
/// Get value from a column in a table
/// </summary>
/// <param name="tableName">The table name</param>
/// <param name="keyName">The column that the search is made by</param>
/// <param name="KeyValue">The value that is searched in the specified column</param>
/// <param name="ResultColumnName">The column that has the result</param>
/// <returns>A string that has the requested value (can be null if nothing found)</returns>
public async Task<string?> GetValueAsync(
string tableName, string keyName, string KeyValue,
string ResultColumnName)
{
if (!await TableExistsAsync(tableName))
throw new Exception($"Table {tableName} does not exist");
return await ReadDataAsync($"SELECT {ResultColumnName} FROM {tableName} WHERE {keyName}='{KeyValue}'");
}
/// <summary>
/// Get value from a column in a table
/// </summary>
/// <param name="tableName">The table name</param>
/// <param name="keyName">The column that the search is made by</param>
/// <param name="KeyValue">The value that is searched in the specified column</param>
/// <param name="ResultColumnName">The column that has the result</param>
/// <returns>A string that has the requested value (can be null if nothing found)</returns>
public string? GetValue(string tableName, string keyName, string KeyValue, string ResultColumnName)
{
if (!TableExists(tableName))
throw new Exception($"Table {tableName} does not exist");
return ReadData($"SELECT {ResultColumnName} FROM {tableName} WHERE {keyName}='{KeyValue}'");
}
/// <summary>
/// Stop the connection to the SQL Database
/// </summary>
/// <returns></returns>
public async void Stop()
{
await Connection.CloseAsync();
}
/// <summary>
/// Change the structure of a table by adding new columns
/// </summary>
/// <param name="tableName">The table name</param>
/// <param name="columns">The columns to be added</param>
/// <param name="TYPE">The type of the columns (TEXT, INTEGER, FLOAT, etc)</param>
/// <returns></returns>
public async Task AddColumnsToTableAsync(string tableName, string[] columns, string TYPE = "TEXT")
{
var command = Connection.CreateCommand();
command.CommandText = $"SELECT * FROM {tableName}";
var reader = await command.ExecuteReaderAsync();
var tableColumns = new List<string>();
for (var i = 0; i < reader.FieldCount; i++)
tableColumns.Add(reader.GetName(i));
foreach (var column in columns)
if (!tableColumns.Contains(column))
{
command.CommandText = $"ALTER TABLE {tableName} ADD COLUMN {column} {TYPE}";
await command.ExecuteNonQueryAsync();
}
}
/// <summary>
/// Change the structure of a table by adding new columns
/// </summary>
/// <param name="tableName">The table name</param>
/// <param name="columns">The columns to be added</param>
/// <param name="TYPE">The type of the columns (TEXT, INTEGER, FLOAT, etc)</param>
/// <returns></returns>
public void AddColumnsToTable(string tableName, string[] columns, string TYPE = "TEXT")
{
var command = Connection.CreateCommand();
command.CommandText = $"SELECT * FROM {tableName}";
var reader = command.ExecuteReader();
var tableColumns = new List<string>();
for (var i = 0; i < reader.FieldCount; i++)
tableColumns.Add(reader.GetName(i));
foreach (var column in columns)
if (!tableColumns.Contains(column))
{
command.CommandText = $"ALTER TABLE {tableName} ADD COLUMN {column} {TYPE}";
command.ExecuteNonQuery();
}
}
/// <summary>
/// Check if a table exists
/// </summary>
/// <param name="tableName">The table name</param>
/// <returns>True if the table exists, false if not</returns>
public async Task<bool> TableExistsAsync(string tableName)
{
var cmd = Connection.CreateCommand();
cmd.CommandText = $"SELECT name FROM sqlite_master WHERE type='table' AND name='{tableName}'";
var result = await cmd.ExecuteScalarAsync();
if (result == null)
return false;
return true;
}
/// <summary>
/// Check if a table exists
/// </summary>
/// <param name="tableName">The table name</param>
/// <returns>True if the table exists, false if not</returns>
public bool TableExists(string tableName)
{
var cmd = Connection.CreateCommand();
cmd.CommandText = $"SELECT name FROM sqlite_master WHERE type='table' AND name='{tableName}'";
var result = cmd.ExecuteScalar();
if (result == null)
return false;
return true;
}
/// <summary>
/// Create a table
/// </summary>
/// <param name="tableName">The table name</param>
/// <param name="columns">The columns of the table</param>
/// <returns></returns>
public async Task CreateTableAsync(string tableName, params string[] columns)
{
var cmd = Connection.CreateCommand();
cmd.CommandText = $"CREATE TABLE IF NOT EXISTS {tableName} ({string.Join(", ", columns)})";
await cmd.ExecuteNonQueryAsync();
}
/// <summary>
/// Create a table
/// </summary>
/// <param name="tableName">The table name</param>
/// <param name="columns">The columns of the table</param>
/// <returns></returns>
public void CreateTable(string tableName, params string[] columns)
{
var cmd = Connection.CreateCommand();
cmd.CommandText = $"CREATE TABLE IF NOT EXISTS {tableName} ({string.Join(", ", columns)})";
cmd.ExecuteNonQuery();
}
/// <summary>
/// Execute a custom query
/// </summary>
/// <param name="query">The query</param>
/// <returns>The number of rows that the query modified</returns>
public async Task<int> ExecuteAsync(string query)
{
if (!Connection.State.HasFlag(ConnectionState.Open))
await Connection.OpenAsync();
var command = new SQLiteCommand(query, Connection);
var answer = await command.ExecuteNonQueryAsync();
return answer;
}
/// <summary>
/// Execute a custom query
/// </summary>
/// <param name="query">The query</param>
/// <returns>The number of rows that the query modified</returns>
public int Execute(string query)
{
if (!Connection.State.HasFlag(ConnectionState.Open))
Connection.Open();
var command = new SQLiteCommand(query, Connection);
var r = command.ExecuteNonQuery();
return r;
}
/// <summary>
/// Read data from the result table and return the first row
/// </summary>
/// <param name="query">The query</param>
/// <returns>The result is a string that has all values separated by space character</returns>
public async Task<string?> ReadDataAsync(string query)
{
if (!Connection.State.HasFlag(ConnectionState.Open))
await Connection.OpenAsync();
var command = new SQLiteCommand(query, Connection);
var reader = await command.ExecuteReaderAsync();
var values = new object[reader.FieldCount];
if (reader.Read())
{
reader.GetValues(values);
return string.Join<object>(" ", values);
}
return null;
}
/// <summary>
/// Read data from the result table and return the first row
/// </summary>
/// <param name="query">The query</param>
/// <returns>The result is a string that has all values separated by space character</returns>
public string? ReadData(string query)
{
if (!Connection.State.HasFlag(ConnectionState.Open))
Connection.Open();
var command = new SQLiteCommand(query, Connection);
var reader = command.ExecuteReader();
var values = new object[reader.FieldCount];
if (reader.Read())
{
reader.GetValues(values);
return string.Join<object>(" ", values);
}
return null;
}
/// <summary>
/// Read data from the result table and return the first row
/// </summary>
/// <param name="query">The query</param>
/// <returns>The first row as separated items</returns>
public async Task<object[]?> ReadDataArrayAsync(string query)
{
if (!Connection.State.HasFlag(ConnectionState.Open))
await Connection.OpenAsync();
var command = new SQLiteCommand(query, Connection);
var reader = await command.ExecuteReaderAsync();
var values = new object[reader.FieldCount];
if (reader.Read())
{
reader.GetValues(values);
return values;
}
return null;
}
/// <summary>
/// Read data from the result table and return the first row
/// </summary>
/// <param name="query">The query</param>
/// <returns>The first row as separated items</returns>
public object[]? ReadDataArray(string query)
{
if (!Connection.State.HasFlag(ConnectionState.Open))
Connection.Open();
var command = new SQLiteCommand(query, Connection);
var reader = command.ExecuteReader();
var values = new object[reader.FieldCount];
if (reader.Read())
{
reader.GetValues(values);
return values;
}
return null;
}
/// <summary>
/// Read all rows from the result table and return them as a list of string arrays. The string arrays contain the
/// values of each row
/// </summary>
/// <param name="query">The query</param>
/// <returns>A list of string arrays representing the values that the query returns</returns>
public async Task<List<string[]>?> ReadAllRowsAsync(string query)
{
if (!Connection.State.HasFlag(ConnectionState.Open))
await Connection.OpenAsync();
var command = new SQLiteCommand(query, Connection);
var reader = await command.ExecuteReaderAsync();
if (!reader.HasRows)
return null;
List<string[]> rows = new();
while (await reader.ReadAsync())
{
var values = new string[reader.FieldCount];
reader.GetValues(values);
rows.Add(values);
}
if (rows.Count == 0) return null;
return rows;
}
}

View File

@@ -1,6 +1,4 @@
using System.Collections.Generic; using System.Collections.Generic;
using Discord.Commands;
using PluginManager.Others; using PluginManager.Others;
namespace PluginManager.Interfaces; namespace PluginManager.Interfaces;
@@ -37,16 +35,16 @@ public interface DBCommand
/// <summary> /// <summary>
/// The main body of the command. This is what is executed when user calls the command in Server /// The main body of the command. This is what is executed when user calls the command in Server
/// </summary> /// </summary>
/// <param name="context">The disocrd Context</param> /// <param name="args">The disocrd Context</param>
void ExecuteServer(CmdArgs args) void ExecuteServer(DBCommandExecutingArguments args)
{ {
} }
/// <summary> /// <summary>
/// The main body of the command. This is what is executed when user calls the command in DM /// The main body of the command. This is what is executed when user calls the command in DM
/// </summary> /// </summary>
/// <param name="context">The disocrd Context</param> /// <param name="args">The disocrd Context</param>
void ExecuteDM(CmdArgs args) void ExecuteDM(DBCommandExecutingArguments args)
{ {
} }
} }

View File

@@ -19,4 +19,4 @@ public interface DBEvent
/// </summary> /// </summary>
/// <param name="client">The discord bot client</param> /// <param name="client">The discord bot client</param>
void Start(DiscordSocketClient client); void Start(DiscordSocketClient client);
} }

View File

@@ -1,25 +1,21 @@
using System.Collections.Generic; using System.Collections.Generic;
using Discord; using Discord;
using Discord.WebSocket; using Discord.WebSocket;
namespace PluginManager.Interfaces namespace PluginManager.Interfaces;
public interface DBSlashCommand
{ {
public interface DBSlashCommand string Name { get; }
string Description { get; }
bool canUseDM { get; }
List<SlashCommandOptionBuilder> Options { get; }
void ExecuteServer(SocketSlashCommand context)
{ {
string Name { get; }
string Description { get; }
bool canUseDM { get; }
List<SlashCommandOptionBuilder> Options { get; }
void ExecuteServer(SocketSlashCommand context)
{
}
void ExecuteDM(SocketSlashCommand context) { }
} }
void ExecuteDM(SocketSlashCommand context) { }
} }

View File

@@ -0,0 +1,17 @@
using System.Collections.Generic;
namespace PluginManager.Interfaces.Exceptions;
public interface IException
{
public List<string> Messages { get; set; }
public bool isFatal { get; }
public string GenerateFullMessage();
public void HandleException();
public IException AppendError(string message);
public IException AppendError(List<string> messages);
public IException IsFatal(bool isFatal = true);
}

View File

@@ -0,0 +1,17 @@
using System.Threading.Tasks;
using PluginManager.Others;
namespace PluginManager.Interfaces;
public interface ICommandAction
{
public string ActionName { get; }
public string? Description { get; }
public string? Usage { get; }
public InternalActionRunType RunType { get; }
public Task Execute(string[]? args);
}

View File

@@ -1,14 +0,0 @@
using System;
using System.Collections.Generic;
using Discord.Commands;
using Discord.WebSocket;
namespace PluginManager.Items;
public class ConsoleCommand
{
public string? CommandName { get; init; }
public string? Description { get; init; }
public string? Usage { get; init; }
public Action<string[]>? Action { get; init; }
}

View File

@@ -1,533 +0,0 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Reflection;
using System.Threading.Tasks;
using Discord.WebSocket;
using PluginManager.Loaders;
using PluginManager.Online;
using PluginManager.Others;
using OperatingSystem = PluginManager.Others.OperatingSystem;
namespace PluginManager.Items;
public class ConsoleCommandsHandler
{
private static readonly PluginsManager manager =
new("https://raw.githubusercontent.com/Wizzy69/installer/discord-bot-files/Plugins.txt");
private static readonly List<ConsoleCommand> commandList = new();
private static bool isDownloading;
private static bool pluginsLoaded;
private readonly DiscordSocketClient? client;
public ConsoleCommandsHandler(DiscordSocketClient client)
{
if (!Logger.isConsole) throw new Exception("Can not use ConsoleCommandsHandler for Non console apps");
this.client = client;
InitializeBasicCommands();
//Logger.WriteLine("Initialized console command handler !");
}
private void InitializeBasicCommands()
{
commandList.Clear();
AddCommand("help", "Show help", "help <command>", args =>
{
if (args.Length <= 1)
{
Logger.WriteLine("Available commands:");
var items = new List<string[]>();
items.Add(new[] { "-", "-", "-" });
items.Add(new[] { "Command", "Description", "Usage" });
items.Add(new[] { " ", " ", "Argument type: <optional> [required]" });
items.Add(new[] { "-", "-", "-" });
foreach (var command in commandList)
{
if (!command.CommandName.StartsWith("_"))
items.Add(new[] { command.CommandName, command.Description, command.Usage });
}
items.Add(new[] { "-", "-", "-" });
Utilities.FormatAndAlignTable(items, TableFormat.DEFAULT);
}
else
{
foreach (var command in commandList)
if (command.CommandName == args[1])
{
Logger.WriteLine("Command description: " + command.Description);
Logger.WriteLine("Command execution format:" + command.Usage);
return;
}
Logger.WriteLine("Command not found");
}
}
);
AddCommand("lp", "Load plugins", () =>
{
if (pluginsLoaded)
return;
var loader = new PluginLoader(client!);
var cc = Console.ForegroundColor;
loader.onCMDLoad += (name, typeName, success, exception) =>
{
if (name == null || name.Length < 2)
name = typeName;
if (success)
{
Console.ForegroundColor = ConsoleColor.Green;
Logger.WriteLine("[CMD] Successfully loaded command : " + name);
}
else
{
Console.ForegroundColor = ConsoleColor.Red;
if (exception is null)
Logger.WriteLine("An error occured while loading: " + name);
else
Logger.WriteLine("[CMD] Failed to load command : " + name + " because " + exception!.Message);
}
Console.ForegroundColor = cc;
};
loader.onEVELoad += (name, typeName, success, exception) =>
{
if (name == null || name.Length < 2)
name = typeName;
if (success)
{
Console.ForegroundColor = ConsoleColor.Green;
Logger.WriteLine("[EVENT] Successfully loaded event : " + name);
}
else
{
Console.ForegroundColor = ConsoleColor.Red;
Logger.WriteLine("[EVENT] Failed to load event : " + name + " because " + exception!.Message);
}
Console.ForegroundColor = cc;
};
loader.onSLSHLoad += (name, typeName, success, exception) =>
{
if (name == null || name.Length < 2)
name = typeName;
if (success)
{
Console.ForegroundColor = ConsoleColor.Green;
Logger.WriteLine("[SLASH] Successfully loaded command : " + name);
}
else
{
Console.ForegroundColor = ConsoleColor.Red;
Logger.WriteLine("[SLASH] Failed to load command : " + name + " because " + exception!.Message);
}
Console.ForegroundColor = cc;
};
loader.LoadPlugins();
Console.ForegroundColor = cc;
pluginsLoaded = true;
}
);
AddCommand("listplugs", "list available plugins", () => { manager.ListAvailablePlugins().Wait(); });
AddCommand("dwplug", "download plugin", "dwplug [name]", async args =>
{
isDownloading = true;
if (args.Length == 1)
{
isDownloading = false;
Logger.WriteLine("Please specify plugin name");
return;
}
var name = string.Join(' ', args, 1, args.Length - 1);
// info[0] = plugin type
// info[1] = plugin link
// info[2] = if others are required, or string.Empty if none
var info = await manager.GetPluginLinkByName(name);
if (info[1] == null) // link is null
{
if (name == "")
{
isDownloading = false;
Utilities.WriteColorText("Name is invalid");
return;
}
isDownloading = false;
Utilities.WriteColorText($"Failed to find plugin &b{name} &c!" +
" Use &glistplugs &ccommand to display all available plugins !");
return;
}
string path;
if (info[0] == "Plugin")
path = "./Data/Plugins/" + name + ".dll";
else
path = $"./{info[1].Split('/')[info[1].Split('/').Length - 1]}";
if (OperatingSystem.WINDOWS == Functions.GetOperatingSystem())
{
await ServerCom.DownloadFileAsync(info[1], path);
}
else if (OperatingSystem.LINUX == Functions.GetOperatingSystem())
{
var bar = new Utilities.ProgressBar(ProgressBarType.NO_END);
bar.Start();
await ServerCom.DownloadFileNoProgressAsync(info[1], path);
bar.Stop("Plugin Downloaded !");
}
Logger.WriteLine("\n");
// check requirements if any
if (info.Length == 3 && info[2] != string.Empty && info[2] != null)
{
Logger.WriteLine($"Downloading requirements for plugin : {name}");
var lines = await ServerCom.ReadTextFromURL(info[2]);
foreach (var line in lines)
{
if (!(line.Length > 0 && line.Contains(",")))
continue;
var split = line.Split(',');
Logger.WriteLine($"\nDownloading item: {split[1]}");
if (File.Exists("./" + split[1])) File.Delete("./" + split[1]);
if (OperatingSystem.WINDOWS == Functions.GetOperatingSystem())
{
await ServerCom.DownloadFileAsync(split[0], "./" + split[1]);
}
else if (OperatingSystem.LINUX == Functions.GetOperatingSystem())
{
var bar = new Utilities.ProgressBar(ProgressBarType.NO_END);
bar.Start();
await ServerCom.DownloadFileNoProgressAsync(split[0], "./" + split[1]);
bar.Stop("Item downloaded !");
}
Logger.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"))
{
Logger.WriteLine($"Extracting {split[1]} ...");
var bar = new Utilities.ProgressBar(
ProgressBarType.NO_END);
bar.Start();
await ArchiveManager.ExtractArchive("./" + split[1], "./", null,
UnzipProgressType.PercentageFromTotalSize);
bar.Stop("Extracted");
Logger.WriteLine("\n");
File.Delete("./" + split[1]);
}
}
Logger.WriteLine();
}
var ver = await ServerCom.GetVersionOfPackageFromWeb(name);
if (ver is null) throw new Exception("Incorrect version");
await Config.Plugins.SetVersionAsync(name, ver);
isDownloading = false;
await ExecuteCommad("localload " + name);
}
);
AddCommand("value", "read value from VariableStack", "value [key]", args =>
{
if (args.Length != 2)
return;
if (!Config.Variables.Exists(args[1]))
return;
var data = Config.Variables.GetValue(args[1]);
Logger.WriteLine($"{args[1]} => {data}");
}
);
AddCommand("add", "add variable to the system variables", "add [key] [value] [isReadOnly=true/false]", args =>
{
if (args.Length < 4)
return;
var key = args[1];
var value = args[2];
var isReadOnly = args[3].Equals("true", StringComparison.CurrentCultureIgnoreCase);
try
{
Config.Variables.Add(key, value, isReadOnly);
Logger.WriteLine($"Updated config file with the following command: {args[1]} => {value}");
}
catch (Exception ex)
{
Logger.WriteLine(ex.ToString());
}
}
);
AddCommand("remv", "remove variable from system variables", "remv [key]", args =>
{
if (args.Length < 2)
return;
Config.Variables.RemoveKey(args[1]);
}
);
AddCommand("sd", "Shuts down the discord bot", async () =>
{
if (client is null)
return;
Settings.sqlDatabase.Stop();
await client.StopAsync();
await client.DisposeAsync();
await Task.Delay(1000);
Environment.Exit(0);
}
);
AddCommand("import", "Load an external command", "import [pluginName]", async args =>
{
if (args.Length <= 1) return;
try
{
var pName = string.Join(' ', args, 1, args.Length - 1);
using (var client = new HttpClient())
{
var url = (await manager.GetPluginLinkByName(pName))[1];
if (url is null) throw new Exception($"Invalid plugin name {pName}.");
var s = await client.GetStreamAsync(url);
var str = new MemoryStream();
await s.CopyToAsync(str);
var asmb = Assembly.Load(str.ToArray());
await PluginLoader.LoadPluginFromAssembly(asmb, this.client);
}
}
catch (Exception ex)
{
Logger.WriteLine(ex.Message);
}
});
AddCommand("localload", "Load a local command", "local [pluginName]", async args =>
{
if (args.Length <= 1) return;
try
{
var pName = string.Join(' ', args, 1, args.Length - 1);
var asmb = Assembly.LoadFile(Path.GetFullPath("./Data/Plugins/" + pName + ".dll"));
await PluginLoader.LoadPluginFromAssembly(asmb, this.client);
}
catch (Exception ex)
{
Logger.WriteLine(ex.Message);
Logger.WriteErrFile(ex);
}
});
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))
{
Logger.WriteLine("The plugin does not exist");
return;
}
File.Delete(location);
Logger.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]);
Logger.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;
Logger.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));
}
public static void AddCommand(string command, string description, string usage, Action<string[]> action)
{
commandList.Add(new ConsoleCommand
{ CommandName = command, Description = description, Action = action, Usage = usage });
Console.ForegroundColor = ConsoleColor.White;
Utilities.WriteColorText($"Command &r{command} &cadded to the list of commands");
}
public static void AddCommand(string command, string description, Action action)
{
AddCommand(command, description, command, args => action());
}
public static void RemoveCommand(string command)
{
commandList.RemoveAll(x => x.CommandName == command);
}
public static bool CommandExists(string command)
{
return GetCommand(command) is not null;
}
public static ConsoleCommand? GetCommand(string 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])
{
Logger.WriteLine();
item.Action(args);
}
}*/
public static async Task ExecuteCommad(string command)
{
if (!Logger.isConsole)
throw new Exception("Can not use console based commands on non console based application !");
var args = command.Split(' ');
foreach (var item in commandList.ToList())
if (item.CommandName == args[0])
{
item.Action.Invoke(args);
while (isDownloading) await Task.Delay(1000);
}
}
public bool HandleCommand(string command, bool removeCommandExecution = true)
{
if (!Logger.isConsole)
throw new Exception("Can not use console based commands on non console based application !");
Console.ForegroundColor = ConsoleColor.White;
var args = command.Split(' ');
foreach (var item in commandList.ToList())
if (item.CommandName == args[0])
{
if (args[0].StartsWith("_"))
throw new Exception("This command is reserved for internal worker and can not be executed manually !");
if (Logger.isConsole)
if (removeCommandExecution)
{
Console.SetCursorPosition(0, Console.CursorTop - 1);
for (var i = 0; i < command.Length + 30; i++)
Logger.Write(" ");
Console.SetCursorPosition(0, Console.CursorTop);
}
Logger.WriteLine();
item.Action(args);
return true;
}
return false;
//Logger.WriteLine($"Executing: {args[0]} with the following parameters: {args.MergeStrings(1)}");
}
}

View File

@@ -0,0 +1,72 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using PluginManager.Interfaces;
using PluginManager.Others;
namespace PluginManager.Loaders;
public class ActionsLoader
{
public delegate void ActionLoaded(string name, string typeName, bool success, Exception? e = null);
private readonly string actionExtension = "dll";
private readonly string actionFolder = @"./Data/Actions/";
public ActionsLoader(string path, string extension)
{
actionFolder = path;
actionExtension = extension;
}
public event ActionLoaded? ActionLoadedEvent;
public async Task<List<ICommandAction>?> Load()
{
Directory.CreateDirectory(actionFolder);
var files = Directory.GetFiles(actionFolder, $"*.{actionExtension}", SearchOption.AllDirectories);
var actions = new List<ICommandAction>();
foreach (var file in files)
try
{
Assembly.LoadFrom(file);
}
catch (Exception e)
{
ActionLoadedEvent?.Invoke(file, "", false, e);
}
var types = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(s => s.GetTypes())
.Where(p => typeof(ICommandAction).IsAssignableFrom(p) && !p.IsInterface);
foreach (var type in types)
try
{
var action = (ICommandAction)Activator.CreateInstance(type);
if (action.ActionName == null)
{
ActionLoadedEvent?.Invoke(action.ActionName, type.Name, false);
continue;
}
if (action.RunType == InternalActionRunType.ON_STARTUP)
await action.Execute(null);
ActionLoadedEvent?.Invoke(action.ActionName, type.Name, true);
actions.Add(action);
}
catch (Exception e)
{
ActionLoadedEvent?.Invoke(type.Name, type.Name, false, e);
}
return actions;
}
}

View File

@@ -1,63 +1,88 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Reflection; using System.Reflection;
using PluginManager.Interfaces;
using PluginManager.Others;
namespace PluginManager.Loaders; namespace PluginManager.Loaders;
internal class LoaderArgs : EventArgs internal class LoaderArgs : EventArgs
{ {
internal string? PluginName { get; init; } internal string? PluginName { get; init; }
internal string? TypeName { get; init; } internal string? TypeName { get; init; }
internal bool IsLoaded { get; init; } internal bool IsLoaded { get; init; }
internal Exception? Exception { get; init; } internal Exception? Exception { get; init; }
internal object? Plugin { get; init; } internal object? Plugin { get; init; }
} }
internal class Loader<T> internal class Loader
{ {
internal Loader(string path, string extension) internal Loader(string path, string extension)
{ {
this.path = path; this.path = path;
this.extension = extension; this.extension = extension;
} }
private string path { get; } private string path { get; }
private string extension { get; } private string extension { get; }
internal event FileLoadedEventHandler? FileLoaded; internal event FileLoadedEventHandler? FileLoaded;
internal event PluginLoadedEventHandler? PluginLoaded; internal event PluginLoadedEventHandler? PluginLoaded;
internal List<T>? Load()
internal (List<DBEvent>?, List<DBCommand>?, List<DBSlashCommand>?) Load()
{ {
var list = new List<T>(); List<DBEvent> events = new();
List<DBSlashCommand> slashCommands = new();
List<DBCommand> commands = new();
if (!Directory.Exists(path)) if (!Directory.Exists(path))
{ {
Directory.CreateDirectory(path); Directory.CreateDirectory(path);
return null; return (null, null, null);
} }
var files = Directory.GetFiles(path, $"*.{extension}", SearchOption.AllDirectories); var files = Directory.GetFiles(path, $"*.{extension}", SearchOption.AllDirectories);
foreach (var file in files) foreach (var file in files)
{ {
Assembly.LoadFrom(file); try
{
Assembly.LoadFrom(file);
}
catch (Exception ex)
{
Config.Logger.Log("PluginName: " + new FileInfo(file).Name.Split('.')[0] + " not loaded", this,
LogLevel.ERROR);
continue;
}
if (FileLoaded != null) if (FileLoaded != null)
{ {
var args = new LoaderArgs var args = new LoaderArgs
{ {
Exception = null, Exception = null,
TypeName = nameof(T), TypeName = null,
IsLoaded = false, IsLoaded = false,
PluginName = new FileInfo(file).Name.Split('.')[0], PluginName = new FileInfo(file).Name.Split('.')[0],
Plugin = null Plugin = null
}; };
FileLoaded.Invoke(args); FileLoaded.Invoke(args);
} }
} }
return (LoadItems<DBEvent>(), LoadItems<DBCommand>(), LoadItems<DBSlashCommand>());
}
internal List<T> LoadItems<T>()
{
List<T> list = new();
try try
{ {
var interfaceType = typeof(T); var interfaceType = typeof(T);
@@ -77,38 +102,44 @@ internal class Loader<T>
if (PluginLoaded != null) if (PluginLoaded != null)
PluginLoaded.Invoke(new LoaderArgs PluginLoaded.Invoke(new LoaderArgs
{ {
Exception = null, Exception = null,
IsLoaded = true, IsLoaded = true,
PluginName = type.FullName, PluginName = type.FullName,
TypeName = nameof(T), TypeName = typeof(T) == typeof(DBCommand) ? "DBCommand" :
Plugin = plugin typeof(T) == typeof(DBEvent) ? "DBEvent" :
} typeof(T) == typeof(DBSlashCommand) ? "DBSlashCommand" :
); null,
Plugin = plugin
}
);
} }
catch (Exception ex) catch (Exception ex)
{ {
if (PluginLoaded != null) if (PluginLoaded != null)
PluginLoaded.Invoke(new LoaderArgs PluginLoaded.Invoke(new LoaderArgs
{ {
Exception = ex, Exception = ex,
IsLoaded = false, IsLoaded = false,
PluginName = type.FullName, PluginName = type.FullName,
TypeName = nameof(T) TypeName = nameof(T)
}); });
} }
return list;
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.WriteErrFile(ex.ToString()); Config.Logger.Log(ex.Message, this, LogLevel.ERROR);
return null;
} }
return null;
return list;
} }
internal delegate void FileLoadedEventHandler(LoaderArgs args); internal delegate void FileLoadedEventHandler(LoaderArgs args);
internal delegate void PluginLoadedEventHandler(LoaderArgs args); internal delegate void PluginLoadedEventHandler(LoaderArgs args);
} }

View File

@@ -1,136 +0,0 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using PluginManager.Interfaces;
namespace PluginManager.Loaders
{
internal class LoaderV2
{
internal LoaderV2(string path, string extension)
{
this.path = path;
this.extension = extension;
}
private string path { get; }
private string extension { get; }
internal event FileLoadedEventHandler? FileLoaded;
internal event PluginLoadedEventHandler? PluginLoaded;
internal delegate void FileLoadedEventHandler(LoaderArgs args);
internal delegate void PluginLoadedEventHandler(LoaderArgs args);
internal (List<DBEvent>?, List<DBCommand>?, List<DBSlashCommand>?) Load()
{
List<DBEvent> events = new();
List<DBSlashCommand> slashCommands = new();
List<DBCommand> commands = new();
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
return (null, null, null);
}
var files = Directory.GetFiles(path, $"*.{extension}", SearchOption.AllDirectories);
foreach (var file in files)
{
try
{
Assembly.LoadFrom(file);
}
catch (Exception ex)
{
Logger.WriteLine(ex.Message);
Logger.WriteLine("PluginName: " + new FileInfo(file).Name.Split('.')[0] + " not loaded");
continue;
}
if (FileLoaded != null)
{
var args = new LoaderArgs
{
Exception = null,
TypeName = null,
IsLoaded = false,
PluginName = new FileInfo(file).Name.Split('.')[0],
Plugin = null
};
FileLoaded.Invoke(args);
}
}
return (LoadItems<DBEvent>(), LoadItems<DBCommand>(), LoadItems<DBSlashCommand>());
}
internal List<T> LoadItems<T>()
{
List<T> list = new();
try
{
var interfaceType = typeof(T);
var types = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(a => a.GetTypes())
.Where(p => interfaceType.IsAssignableFrom(p) && p.IsClass)
.ToArray();
list.Clear();
foreach (var type in types)
try
{
var plugin = (T)Activator.CreateInstance(type)!;
list.Add(plugin);
if (PluginLoaded != null)
PluginLoaded.Invoke(new LoaderArgs
{
Exception = null,
IsLoaded = true,
PluginName = type.FullName,
TypeName = typeof(T) == typeof(DBCommand) ? "DBCommand" : typeof(T) == typeof(DBEvent) ? "DBEvent" : "DBSlashCommand",
Plugin = plugin
}
);
}
catch (Exception ex)
{
if (PluginLoaded != null)
PluginLoaded.Invoke(new LoaderArgs
{
Exception = ex,
IsLoaded = false,
PluginName = type.FullName,
TypeName = nameof(T)
});
}
return list;
}
catch (Exception ex)
{
Logger.WriteErrFile(ex.ToString());
return null;
}
return null;
}
}
}

View File

@@ -1,15 +1,11 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO;
using System.Reflection; using System.Reflection;
using System.Threading.Tasks; using System.Threading.Tasks;
using Discord; using Discord;
using Discord.WebSocket; using Discord.WebSocket;
using PluginManager.Interfaces; using PluginManager.Interfaces;
using PluginManager.Online; using PluginManager.Others;
using PluginManager.Online.Updates;
namespace PluginManager.Loaders; namespace PluginManager.Loaders;
@@ -23,7 +19,7 @@ public class PluginLoader
private const string pluginFolder = @"./Data/Plugins/"; private const string pluginFolder = @"./Data/Plugins/";
internal const string pluginExtension = "dll"; internal const string pluginExtension = "dll";
private readonly DiscordSocketClient _client; private readonly DiscordSocketClient _client;
/// <summary> /// <summary>
@@ -62,53 +58,50 @@ public class PluginLoader
public static List<DBEvent>? Events { get; set; } public static List<DBEvent>? Events { get; set; }
/// <summary> /// <summary>
/// A list of <see cref="DBSlashCommand"/> commands /// A list of <see cref="DBSlashCommand" /> commands
/// </summary> /// </summary>
public static List<DBSlashCommand>? SlashCommands { get; set; } public static List<DBSlashCommand>? SlashCommands { get; set; }
public static int PluginsLoaded
{
get
{
var count = 0;
if (Commands is not null)
count += Commands.Count;
if (Events is not null)
count += Events.Count;
if (SlashCommands is not null)
count += SlashCommands.Count;
return count;
}
}
/// <summary> /// <summary>
/// The main mathod that is called to load all events /// The main mathod that is called to load all events
/// </summary> /// </summary>
public async void LoadPlugins() public async void LoadPlugins()
{ {
//Check for updates in commands
foreach (var file in Directory.GetFiles("./Data/Plugins/", $"*.{pluginExtension}",
SearchOption.AllDirectories))
await Task.Run(async () =>
{
var name = new FileInfo(file).Name.Split('.')[0];
var version = await ServerCom.GetVersionOfPackageFromWeb(name);
if (version is null)
return;
if (Config.Plugins.GetVersion(name) is not null)
Config.Plugins.SetVersion(name, version);
if (await PluginUpdater.CheckForUpdates(name))
await PluginUpdater.Download(name);
});
//Load all plugins //Load all plugins
Commands = new List<DBCommand>(); Commands = new List<DBCommand>();
Events = new List<DBEvent>(); Events = new List<DBEvent>();
SlashCommands = new List<DBSlashCommand>(); SlashCommands = new List<DBSlashCommand>();
Logger.WriteLogFile("Starting plugin loader ... Client: " + _client.CurrentUser.Username); Config.Logger.Log("Starting plugin loader ... Client: " + _client.CurrentUser.Username, this,
Logger.WriteLine("Loading plugins"); LogLevel.INFO);
var loader = new LoaderV2("./Data/Plugins", "dll"); var loader = new Loader("./Data/Plugins", "dll");
loader.FileLoaded += (args) => Logger.WriteLogFile($"{args.PluginName} file Loaded"); loader.FileLoaded += args => Config.Logger.Log($"{args.PluginName} file Loaded", this, LogLevel.INFO);
loader.PluginLoaded += Loader_PluginLoaded; loader.PluginLoaded += Loader_PluginLoaded;
var res = loader.Load(); var res = loader.Load();
Events = res.Item1; Events = res.Item1;
Commands = res.Item2; Commands = res.Item2;
SlashCommands = res.Item3; SlashCommands = res.Item3;
} }
private async void Loader_PluginLoaded(LoaderArgs args) private async void Loader_PluginLoaded(LoaderArgs args)
{ {
switch (args.TypeName) switch (args.TypeName)
{ {
case "DBCommand": case "DBCommand":
@@ -124,60 +117,67 @@ public class PluginLoader
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.WriteLine(ex.ToString()); Config.Logger.Log(ex.Message, this, LogLevel.ERROR);
Logger.WriteLine("Plugin: " + args.PluginName);
Logger.WriteLine("Type: " + args.TypeName);
Logger.WriteLine("IsLoaded: " + args.IsLoaded);
} }
break; break;
case "DBSlashCommand": case "DBSlashCommand":
if (args.IsLoaded) if (args.IsLoaded)
{ {
var slash = (DBSlashCommand)args.Plugin; var slash = (DBSlashCommand)args.Plugin;
SlashCommandBuilder builder = new SlashCommandBuilder(); var builder = new SlashCommandBuilder();
builder.WithName(slash.Name); builder.WithName(slash.Name);
builder.WithDescription(slash.Description); builder.WithDescription(slash.Description);
builder.WithDMPermission(slash.canUseDM); builder.WithDMPermission(slash.canUseDM);
builder.Options = slash.Options; builder.Options = slash.Options;
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());
} }
break; break;
} }
} }
public static async Task LoadPluginFromAssembly(Assembly asmb, DiscordSocketClient client) public static async Task LoadPluginFromAssembly(Assembly asmb, DiscordSocketClient client)
{ {
var types = asmb.GetTypes(); var types = asmb.GetTypes();
foreach (var type in types) foreach (var type in types)
if (type.IsClass && typeof(DBEvent).IsAssignableFrom(type)) try
{ {
var instance = (DBEvent)Activator.CreateInstance(type); if (type.IsClass && typeof(DBEvent).IsAssignableFrom(type))
instance.Start(client); {
PluginLoader.Events.Add(instance); var instance = (DBEvent)Activator.CreateInstance(type);
Logger.WriteLine($"[EVENT] Loaded external {type.FullName}!"); instance.Start(client);
} Events.Add(instance);
else if (type.IsClass && typeof(DBCommand).IsAssignableFrom(type)) Config.Logger.Log($"[EVENT] Loaded external {type.FullName}!", LogLevel.INFO);
{ }
var instance = (DBCommand)Activator.CreateInstance(type); else if (type.IsClass && typeof(DBCommand).IsAssignableFrom(type))
PluginLoader.Commands.Add(instance); {
Logger.WriteLine($"[CMD] Instance: {type.FullName} loaded !"); var instance = (DBCommand)Activator.CreateInstance(type);
} Commands.Add(instance);
else if (type.IsClass && typeof(DBSlashCommand).IsAssignableFrom(type)) Config.Logger.Log($"[CMD] Instance: {type.FullName} loaded !", LogLevel.INFO);
{ }
var instance = (DBSlashCommand)Activator.CreateInstance(type); else if (type.IsClass && typeof(DBSlashCommand).IsAssignableFrom(type))
SlashCommandBuilder builder = new SlashCommandBuilder(); {
builder.WithName(instance.Name); var instance = (DBSlashCommand)Activator.CreateInstance(type);
builder.WithDescription(instance.Description); var builder = new SlashCommandBuilder();
builder.WithDMPermission(instance.canUseDM); builder.WithName(instance.Name);
builder.Options = instance.Options; builder.WithDescription(instance.Description);
builder.WithDMPermission(instance.canUseDM);
await client.CreateGlobalApplicationCommandAsync(builder.Build()); builder.Options = instance.Options;
PluginLoader.SlashCommands.Add(instance);
Logger.WriteLine($"[SLASH] Instance: {type.FullName} loaded !");
await client.CreateGlobalApplicationCommandAsync(builder.Build());
SlashCommands.Add(instance);
Config.Logger.Log($"[SLASH] Instance: {type.FullName} loaded !", LogLevel.INFO);
}
} }
catch (Exception ex)
{
//Console.WriteLine(ex.Message);
Config.Logger.Error(ex);
}
} }
} }

View File

@@ -1,131 +0,0 @@
using System;
using System.IO;
using Discord;
namespace PluginManager
{
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.Variables.Exists("LogFolder"))
Config.Variables.Add("LogFolder", "./Data/Output/Logs/");
if (!Config.Variables.Exists("ErrorFolder"))
Config.Variables.Add("ErrorFolder", "./Data/Output/Errors/");
isInitialized = true;
logFolder = Config.Variables.GetValue("LogFolder");
errFolder = Config.Variables.GetValue("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}");
}
/// <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.AppendAllTextAsync(logsPath, LogMessage + " \n").Wait();
}
/// <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, ErrMessage + " \n");
}
public static void WriteErrFile(this Exception ex)
{
if (!isInitialized) throw new Exception("Logger is not initialized");
WriteErrFile(ex.ToString());
}
}
}

View File

@@ -3,7 +3,6 @@ using System.IO;
using System.Net.Http; using System.Net.Http;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using PluginManager.Others; using PluginManager.Others;
namespace PluginManager.Online.Helpers; namespace PluginManager.Online.Helpers;
@@ -19,10 +18,11 @@ internal static class OnlineFunctions
/// <param name="progress">The <see cref="IProgress{T}" /> that is used to track the download progress</param> /// <param name="progress">The <see cref="IProgress{T}" /> that is used to track the download progress</param>
/// <param name="cancellation">The cancellation token</param> /// <param name="cancellation">The cancellation token</param>
/// <returns></returns> /// <returns></returns>
internal static async Task DownloadFileAsync(this HttpClient client, string url, Stream destination, internal static async Task DownloadFileAsync(
IProgress<float>? progress = null, this HttpClient client, string url, Stream destination,
IProgress<long>? downloadedBytes = null, int bufferSize = 81920, IProgress<float>? progress = null,
CancellationToken cancellation = default) IProgress<long>? downloadedBytes = null, int bufferSize = 81920,
CancellationToken cancellation = default)
{ {
using (var response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, cancellation)) using (var response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, cancellation))
{ {
@@ -40,11 +40,12 @@ internal static class OnlineFunctions
// Convert absolute progress (bytes downloaded) into relative progress (0% - 100%) // Convert absolute progress (bytes downloaded) into relative progress (0% - 100%)
var relativeProgress = new Progress<long>(totalBytes => var relativeProgress = new Progress<long>(totalBytes =>
{ {
progress?.Report((float)totalBytes / contentLength.Value * 100); progress?.Report((float)totalBytes / contentLength.Value *
downloadedBytes?.Report(totalBytes); 100);
} downloadedBytes?.Report(totalBytes);
); }
);
// Use extension method to report progress while downloading // Use extension method to report progress while downloading
await download.CopyToOtherStreamAsync(destination, bufferSize, relativeProgress, cancellation); await download.CopyToOtherStreamAsync(destination, bufferSize, relativeProgress, cancellation);
@@ -64,4 +65,4 @@ internal static class OnlineFunctions
using var client = new HttpClient(); using var client = new HttpClient();
return await client.GetStringAsync(url, cancellation); return await client.GetStringAsync(url, cancellation);
} }
} }

View File

@@ -13,9 +13,23 @@ public class VersionString
var data = version.Split('.'); var data = version.Split('.');
try try
{ {
PackageVersionID = int.Parse(data[0]); if (data.Length == 3)
PackageMainVersion = int.Parse(data[1]); {
PackageCheckVersion = int.Parse(data[2]); PackageVersionID = int.Parse(data[0]);
PackageMainVersion = int.Parse(data[1]);
PackageCheckVersion = int.Parse(data[2]);
}
else if (data.Length == 4)
{
// ignore the first item data[0]
PackageVersionID = int.Parse(data[1]);
PackageMainVersion = int.Parse(data[2]);
PackageCheckVersion = int.Parse(data[3]);
}
else
{
throw new Exception("Invalid version string");
}
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -24,6 +38,25 @@ public class VersionString
} }
} }
private bool Equals(VersionString other)
{
return PackageCheckVersion == other.PackageCheckVersion && PackageMainVersion == other.PackageMainVersion &&
PackageVersionID == other.PackageVersionID;
}
public override bool Equals(object? obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != GetType()) return false;
return Equals((VersionString)obj);
}
public override int GetHashCode()
{
return HashCode.Combine(PackageCheckVersion, PackageMainVersion, PackageVersionID);
}
public override string ToString() public override string ToString()
{ {
return "{PackageID: " + PackageVersionID + ", PackageVersion: " + PackageMainVersion + return "{PackageID: " + PackageVersionID + ", PackageVersion: " + PackageMainVersion +
@@ -81,4 +114,4 @@ public class VersionString
} }
#endregion #endregion
} }

View File

@@ -1,10 +1,8 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Threading.Tasks; using System.Threading.Tasks;
using PluginManager.Online.Helpers; using PluginManager.Online.Helpers;
using PluginManager.Others; using PluginManager.Others;
using OperatingSystem = PluginManager.Others.OperatingSystem; using OperatingSystem = PluginManager.Others.OperatingSystem;
namespace PluginManager.Online; namespace PluginManager.Online;
@@ -14,10 +12,12 @@ public class PluginsManager
/// <summary> /// <summary>
/// The Plugin Manager constructor /// The Plugin Manager constructor
/// </summary> /// </summary>
/// <param name="link">The link to the file where all plugins are stored</param> /// <param name="plink">The link to the file where all plugins are stored</param>
public PluginsManager(string link) /// <param name="vlink">The link to the file where all plugin versions are stored</param>
public PluginsManager(string plink, string vlink)
{ {
PluginsLink = link; PluginsLink = plink;
VersionsLink = vlink;
} }
/// <summary> /// <summary>
@@ -25,31 +25,30 @@ public class PluginsManager
/// </summary> /// </summary>
public string PluginsLink { get; } public string PluginsLink { get; }
public string VersionsLink { get; }
/// <summary> /// <summary>
/// The method to load all plugins /// The method to load all plugins
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
public async Task ListAvailablePlugins() public async Task<List<string[]>> GetAvailablePlugins()
{ {
Config.Logger.Log("Got data from " + VersionsLink, this, LogLevel.INFO);
try try
{ {
var list = await ServerCom.ReadTextFromURL(PluginsLink); var list = await ServerCom.ReadTextFromURL(PluginsLink);
var lines = list.ToArray(); var lines = list.ToArray();
var data = new List<string[]>(); var data = new List<string[]>();
var op = Functions.GetOperatingSystem(); var op = Functions.GetOperatingSystem();
var len = lines.Length; var len = lines.Length;
string[] titles = { "Name", "Description", "Type", "Version" };
data.Add(new[] { "-", "-", "-", "-" });
data.Add(titles);
data.Add(new[] { "-", "-", "-", "-" });
for (var i = 0; i < len; i++) for (var i = 0; i < len; i++)
{ {
if (lines[i].Length <= 2) if (lines[i].Length <= 2)
continue; continue;
var content = lines[i].Split(','); var content = lines[i].Split(',');
var display = new string[titles.Length]; var display = new string[4]; // 4 columns
if (op == OperatingSystem.WINDOWS) if (op == OperatingSystem.WINDOWS)
{ {
if (content[4].Contains("Windows")) if (content[4].Contains("Windows"))
@@ -58,8 +57,8 @@ public class PluginsManager
display[1] = content[1]; display[1] = content[1];
display[2] = content[2]; display[2] = content[2];
display[3] = display[3] =
(await ServerCom.GetVersionOfPackageFromWeb(content[0]) ?? new VersionString("0.0.0")) (await GetVersionOfPackageFromWeb(content[0]) ?? new VersionString("0.0.0"))
.ToShortString(); .ToShortString();
data.Add(display); data.Add(display);
} }
} }
@@ -71,8 +70,8 @@ public class PluginsManager
display[1] = content[1]; display[1] = content[1];
display[2] = content[2]; display[2] = content[2];
display[3] = display[3] =
(await ServerCom.GetVersionOfPackageFromWeb(content[0]) ?? new VersionString("0.0.0")) (await GetVersionOfPackageFromWeb(content[0]) ?? new VersionString("0.0.0"))
.ToShortString(); .ToShortString();
data.Add(display); data.Add(display);
} }
} }
@@ -80,13 +79,34 @@ public class PluginsManager
data.Add(new[] { "-", "-", "-", "-" }); data.Add(new[] { "-", "-", "-", "-" });
Utilities.FormatAndAlignTable(data, TableFormat.CENTER_EACH_COLUMN_BASED); return data;
} }
catch (Exception exception) catch (Exception exception)
{ {
Logger.WriteLine("Failed to execute command: listplugs\nReason: " + exception.Message); Config.Logger.Log("Failed to execute command: listplugs\nReason: " + exception.Message, this,
Logger.WriteErrFile(exception.ToString()); LogLevel.ERROR);
} }
return null;
}
public async Task<VersionString?> GetVersionOfPackageFromWeb(string pakName)
{
var data = await ServerCom.ReadTextFromURL(VersionsLink);
foreach (var item in data)
{
if (item.StartsWith("#"))
continue;
var split = item.Split(',');
if (split[0] == pakName)
{
Config.Logger.Log("Searched for " + pakName + " and found " + split[1] + " as version.", LogLevel.INFO);
return new VersionString(split[1]);
}
}
return null;
} }
/// <summary> /// <summary>
@@ -98,13 +118,13 @@ public class PluginsManager
{ {
try try
{ {
var list = await ServerCom.ReadTextFromURL(PluginsLink); var list = await ServerCom.ReadTextFromURL(PluginsLink);
var lines = list.ToArray(); var lines = list.ToArray();
var len = lines.Length; var len = lines.Length;
for (var i = 0; i < len; i++) for (var i = 0; i < len; i++)
{ {
var contents = lines[i].Split(','); var contents = lines[i].Split(',');
if (contents[0] == name) if (contents[0].ToLowerInvariant() == name.ToLowerInvariant())
{ {
if (contents.Length == 6) if (contents.Length == 6)
return new[] { contents[2], contents[3], contents[5] }; return new[] { contents[2], contents[3], contents[5] };
@@ -116,10 +136,10 @@ public class PluginsManager
} }
catch (Exception exception) catch (Exception exception)
{ {
Logger.WriteLine("Failed to execute command: listplugs\nReason: " + exception.Message); Config.Logger.Log("Failed to execute command: listplugs\nReason: " + exception.Message, this,
Logger.WriteErrFile(exception.ToString()); LogLevel.ERROR);
} }
return new string[] { null!, null!, null! }; return null;
} }
} }

View File

@@ -1,13 +1,10 @@
using System; using System;
using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Net.Http; using System.Net.Http;
using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Collections.Generic;
using PluginManager.Online.Helpers; using PluginManager.Online.Helpers;
using PluginManager.Others;
namespace PluginManager.Online; namespace PluginManager.Online;
@@ -21,7 +18,7 @@ public static class ServerCom
public static async Task<List<string>> ReadTextFromURL(string link) public static async Task<List<string>> ReadTextFromURL(string link)
{ {
var response = await OnlineFunctions.DownloadStringAsync(link); var response = await OnlineFunctions.DownloadStringAsync(link);
var lines = response.Split('\n'); var lines = response.Split('\n');
return lines.ToList(); return lines.ToList();
} }
@@ -32,8 +29,9 @@ public static class ServerCom
/// <param name="location">The location where to store the downloaded data</param> /// <param name="location">The location where to store the downloaded data</param>
/// <param name="progress">The <see cref="IProgress{T}" /> to track the download</param> /// <param name="progress">The <see cref="IProgress{T}" /> to track the download</param>
/// <returns></returns> /// <returns></returns>
public static async Task DownloadFileAsync(string URL, string location, IProgress<float> progress, public static async Task DownloadFileAsync(
IProgress<long>? downloadedBytes = null) string URL, string location, IProgress<float> progress,
IProgress<long>? downloadedBytes)
{ {
using (var client = new HttpClient()) using (var client = new HttpClient())
{ {
@@ -46,69 +44,8 @@ public static class ServerCom
} }
} }
/// <summary> public static async Task DownloadFileAsync(string URl, string location, IProgress<float> progress)
/// Download file from url
/// </summary>
/// <param name="URL">The url to the file</param>
/// <param name="location">The location where to store the downloaded data</param>
/// <returns></returns>
public static async Task DownloadFileAsync(string URL, string location)
{ {
var isDownloading = true; await DownloadFileAsync(URl, location, progress, null);
float c_progress = 0;
var pbar = new Utilities.ProgressBar(ProgressBarType.NORMAL) { Max = 100f, NoColor = true };
IProgress<float> progress = new Progress<float>(percent => { c_progress = percent; });
var updateProgressBarTask = new Task(() =>
{
while (isDownloading)
{
pbar.Update(c_progress);
if (c_progress == 100f)
break;
Thread.Sleep(500);
}
}
);
new Thread(updateProgressBarTask.Start).Start();
await DownloadFileAsync(URL, location, progress);
c_progress = pbar.Max;
pbar.Update(100f);
isDownloading = false;
} }
}
public static async Task DownloadFileNoProgressAsync(string URL, string location)
{
IProgress<float> progress = new Progress<float>();
await DownloadFileAsync(URL, location, progress);
}
public static VersionString? GetVersionOfPackage(string pakName)
{
if (Config.Plugins.GetVersion(pakName) is null)
return null;
return new VersionString(Config.Plugins.GetVersion(pakName));
}
public static async Task<VersionString?> GetVersionOfPackageFromWeb(string pakName)
{
var url = "https://raw.githubusercontent.com/Wizzy69/installer/discord-bot-files/Versions";
var data = await ReadTextFromURL(url);
foreach (var item in data)
{
if (item.StartsWith("#"))
continue;
string[] split = item.Split(',');
if (split[0] == pakName)
return new VersionString(split[1]);
}
return null;
}
}

View File

@@ -1,52 +0,0 @@
using System;
using System.Threading.Tasks;
using System.Collections.Generic;
using PluginManager.Items;
using PluginManager.Others;
namespace PluginManager.Online.Updates;
public class PluginUpdater
{
public static async Task<bool> CheckForUpdates(string pakName)
{
try
{
var webV = await ServerCom.GetVersionOfPackageFromWeb(pakName);
var local = ServerCom.GetVersionOfPackage(pakName);
if (local is null) return true;
if (webV is null) return false;
if (webV == local) return false;
if (webV > local) return true;
}
catch (Exception ex)
{
Logger.LogError(ex);
}
return false;
}
public static async Task<List<string>> GetInfo(string pakName)
{
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());
List<string> fileInfo = await ServerCom.ReadTextFromURL("");
return fileInfo;
}
public static async Task Download(string pakName)
{
var pakUpdateInfo = await GetInfo(pakName);
Logger.Log(string.Join("\n", pakUpdateInfo));
await ConsoleCommandsHandler.ExecuteCommad("dwplug " + pakName);
}
}

View File

@@ -0,0 +1,58 @@
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using PluginManager.Interfaces;
using PluginManager.Loaders;
namespace PluginManager.Others.Actions;
public class InternalActionManager
{
public Dictionary<string, ICommandAction> Actions = new();
public ActionsLoader loader;
public InternalActionManager(string path, string extension)
{
loader = new ActionsLoader(path, extension);
}
public async Task Initialize()
{
loader.ActionLoadedEvent += OnActionLoaded;
var m_actions = await loader.Load();
if (m_actions == null) return;
foreach (var action in m_actions)
Actions.Add(action.ActionName, action);
}
private void OnActionLoaded(string name, string typeName, bool success, Exception? e)
{
if (!success)
{
Config.Logger.Error(e);
return;
}
Config.Logger.Log($"Action {name} loaded successfully", LogLevel.INFO, true);
}
public async Task<string> Execute(string actionName, params string[]? args)
{
if (!Actions.ContainsKey(actionName))
{
Config.Logger.Log($"Action {actionName} not found", "InternalActionManager", LogLevel.WARNING, true);
return "Action not found";
}
try
{
await Actions[actionName].Execute(args);
return "Action executed";
}
catch (Exception e)
{
Config.Logger.Log(e.Message, "InternalActionManager", LogLevel.ERROR);
return e.Message;
}
}
}

View File

@@ -2,138 +2,178 @@
using System.IO; using System.IO;
using System.IO.Compression; using System.IO.Compression;
using System.Linq; using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace PluginManager.Others namespace PluginManager.Others;
public static class ArchiveManager
{ {
public static class ArchiveManager private static string? archiveFolder;
public static bool isInitialized { get; private set; }
public static void Initialize()
{ {
public static bool isInitialized { get; private set; } if (isInitialized) throw new Exception("ArchiveManager is already initialized");
private static string archiveFolder;
public static void Initialize() if (!Config.AppSettings.ContainsKey("ArchiveFolder"))
Config.AppSettings["ArchiveFolder"] = "./Data/PAKS/";
archiveFolder = Config.AppSettings["ArchiveFolder"];
isInitialized = true;
}
/// <summary>
/// Read a file from a zip archive. The output is a byte array
/// </summary>
/// <param name="fileName">The file name in the archive</param>
/// <param name="archName">The archive location on the disk</param>
/// <returns>An array of bytes that represents the Stream value from the file that was read inside the archive</returns>
public async static Task<byte[]?> ReadStreamFromPakAsync(string fileName, string archName)
{
if (!isInitialized) throw new Exception("ArchiveManager is not initialized");
archName = archiveFolder + archName;
if (!File.Exists(archName))
throw new Exception("Failed to load file !");
byte[]? data = null;
using (var zip = ZipFile.OpenRead(archName))
{ {
if (isInitialized) throw new Exception("ArchiveManager is already initialized"); var entry = zip.Entries.FirstOrDefault(entry => entry.FullName == fileName || entry.Name == fileName);
if (entry is null) throw new Exception("File not found in archive");
if (!Config.Variables.Exists("ArchiveFolder"))
Config.Variables.Add("ArchiveFolder", "./Data/PAKS/"); var MemoryStream = new MemoryStream();
isInitialized = true; var stream = entry.Open();
archiveFolder = Config.Variables.GetValue("ArchiveFolder"); await stream.CopyToAsync(MemoryStream);
data = MemoryStream.ToArray();
stream.Close();
MemoryStream.Close();
} }
/// <summary>
/// Read data from a file that is inside an archive (ZIP format) return data;
/// </summary> }
/// <param name="FileName">The file name that is inside the archive or its full path</param>
/// <param name="archFile">The archive location from the PAKs folder</param> /// <summary>
/// <returns>A string that represents the content of the file or null if the file does not exists or it has no content</returns> /// Read data from a file that is inside an archive (ZIP format)
public static async Task<string> ReadFromPakAsync(string FileName, string archFile) /// </summary>
/// <param name="FileName">The file name that is inside the archive or its full path</param>
/// <param name="archFile">The archive location from the PAKs folder</param>
/// <returns>A string that represents the content of the file or null if the file does not exists or it has no content</returns>
public static async Task<string?> ReadFromPakAsync(string FileName, string archFile)
{
if (!isInitialized) throw new Exception("ArchiveManager is not initialized");
archFile = archiveFolder + archFile;
if (!File.Exists(archFile))
throw new Exception("Failed to load file !");
try
{ {
if (!isInitialized) throw new Exception("ArchiveManager is not initialized"); string? textValue = null;
archFile = archiveFolder + archFile; using (var fs = new FileStream(archFile, FileMode.Open))
if (!File.Exists(archFile)) using (var zip = new ZipArchive(fs, ZipArchiveMode.Read))
throw new Exception("Failed to load file !");
try
{ {
string textValue = null; foreach (var entry in zip.Entries)
using (var fs = new FileStream(archFile, FileMode.Open)) if (entry.Name == FileName || entry.FullName == FileName)
using (var zip = new ZipArchive(fs, ZipArchiveMode.Read)) using (var s = entry.Open())
{ using (var reader = new StreamReader(s))
foreach (var entry in zip.Entries)
if (entry.Name == FileName || entry.FullName == FileName)
using (var s = entry.Open())
using (var reader = new StreamReader(s))
{
textValue = await reader.ReadToEndAsync();
reader.Close();
s.Close();
fs.Close();
}
}
return textValue;
}
catch
{
await Task.Delay(100);
return await ReadFromPakAsync(FileName, archFile);
}
}
/// <summary>
/// Extract zip to location
/// </summary>
/// <param name="zip">The zip location</param>
/// <param name="folder">The target location</param>
/// <param name="progress">The progress that is updated as a file is processed</param>
/// <param name="type">The type of progress</param>
/// <returns></returns>
public static async Task ExtractArchive(string zip, string folder, IProgress<float> progress,
UnzipProgressType type)
{
if (!isInitialized) throw new Exception("ArchiveManager is not initialized");
Directory.CreateDirectory(folder);
using (var archive = ZipFile.OpenRead(zip))
{
if (type == UnzipProgressType.PercentageFromNumberOfFiles)
{
var totalZIPFiles = archive.Entries.Count();
var currentZIPFile = 0;
foreach (var entry in archive.Entries)
{
if (entry.FullName.EndsWith("/")) // it is a folder
Directory.CreateDirectory(Path.Combine(folder, entry.FullName));
else
try
{
entry.ExtractToFile(Path.Combine(folder, entry.FullName), true);
}
catch (Exception ex)
{
Logger.WriteLine($"Failed to extract {entry.Name}. Exception: {ex.Message}");
}
currentZIPFile++;
await Task.Delay(10);
if (progress != null)
progress.Report((float)currentZIPFile / totalZIPFiles * 100);
}
}
else if (type == UnzipProgressType.PercentageFromTotalSize)
{
ulong zipSize = 0;
foreach (var entry in archive.Entries)
zipSize += (ulong)entry.CompressedLength;
ulong currentSize = 0;
foreach (var entry in archive.Entries)
{
if (entry.FullName.EndsWith("/"))
{ {
Directory.CreateDirectory(Path.Combine(folder, entry.FullName)); textValue = await reader.ReadToEndAsync();
continue; reader.Close();
s.Close();
fs.Close();
} }
}
return textValue;
}
catch (Exception ex)
{
Config.Logger.Log(ex.Message, "Archive Manager", LogLevel.ERROR); // Write the error to a file
await Task.Delay(100);
return await ReadFromPakAsync(FileName, archFile);
}
}
/// <summary>
/// Extract zip to location
/// </summary>
/// <param name="zip">The zip location</param>
/// <param name="folder">The target location</param>
/// <param name="progress">The progress that is updated as a file is processed</param>
/// <param name="type">The type of progress</param>
/// <returns></returns>
public static async Task ExtractArchive(
string zip, string folder, IProgress<float> progress,
UnzipProgressType type)
{
if (!isInitialized) throw new Exception("ArchiveManager is not initialized");
Directory.CreateDirectory(folder);
using (var archive = ZipFile.OpenRead(zip))
{
if (type == UnzipProgressType.PERCENTAGE_FROM_NUMBER_OF_FILES)
{
var totalZIPFiles = archive.Entries.Count();
var currentZIPFile = 0;
foreach (var entry in archive.Entries)
{
if (entry.FullName.EndsWith("/")) // it is a folder
Directory.CreateDirectory(Path.Combine(folder, entry.FullName));
else
try try
{ {
entry.ExtractToFile(Path.Combine(folder, entry.FullName), true); entry.ExtractToFile(Path.Combine(folder, entry.FullName), true);
currentSize += (ulong)entry.CompressedLength;
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.WriteLine($"Failed to extract {entry.Name}. Exception: {ex.Message}"); Config.Logger.Log($"Failed to extract {entry.Name}. Exception: {ex.Message}",
"Archive Manager", LogLevel.ERROR);
} }
await Task.Delay(10); currentZIPFile++;
if (progress != null) await Task.Delay(10);
progress.Report((float)currentSize / zipSize * 100); if (progress != null)
progress.Report((float)currentZIPFile / totalZIPFiles * 100);
}
}
else if (type == UnzipProgressType.PERCENTAGE_FROM_TOTAL_SIZE)
{
ulong zipSize = 0;
foreach (var entry in archive.Entries)
zipSize += (ulong)entry.CompressedLength;
ulong currentSize = 0;
foreach (var entry in archive.Entries)
{
if (entry.FullName.EndsWith("/"))
{
Directory.CreateDirectory(Path.Combine(folder, entry.FullName));
continue;
} }
try
{
entry.ExtractToFile(Path.Combine(folder, entry.FullName), true);
currentSize += (ulong)entry.CompressedLength;
}
catch (Exception ex)
{
Config.Logger.Log($"Failed to extract {entry.Name}. Exception: {ex.Message}",
"Archive Manager", LogLevel.ERROR);
}
await Task.Delay(10);
if (progress != null)
progress.Report((float)currentSize / zipSize * 100);
} }
} }
} }
} }
} }

View File

@@ -1,19 +0,0 @@
using Discord.Commands;
using Discord.WebSocket;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PluginManager.Others
{
public class CmdArgs
{
public SocketCommandContext context { get; init; }
public string cleanContent { get; init; }
public string commandUsed { get;init; }
public string[] arguments { get;init; }
}
}

View File

@@ -1,368 +0,0 @@
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace PluginManager.Others;
public static class Utilities
{
private static Dictionary<char, ConsoleColor> Colors = new()
{
{ 'g', ConsoleColor.Green },
{ 'b', ConsoleColor.Blue },
{ 'r', ConsoleColor.Red },
{ 'm', ConsoleColor.Magenta },
{ 'y', ConsoleColor.Yellow }
};
private static char ColorPrefix = '&';
private static bool CanAproximateTo(this float f, float y)
{
return MathF.Abs(f - y) < 0.000001;
}
/// <summary>
/// A way to create a table based on input data
/// </summary>
/// <param name="data">The List of arrays of strings that represent the rows.</param>
public static void FormatAndAlignTable(List<string[]> data, TableFormat format)
{
if (format == TableFormat.CENTER_EACH_COLUMN_BASED)
{
var tableLine = '-';
var tableCross = '+';
var tableWall = '|';
var len = new int[data[0].Length];
foreach (var line in data)
for (var i = 0; i < line.Length; i++)
if (line[i].Length > len[i])
len[i] = line[i].Length;
foreach (var row in data)
{
if (row[0][0] == tableLine)
Logger.Write(tableCross);
else
Logger.Write(tableWall);
for (var l = 0; l < row.Length; l++)
{
if (row[l][0] == tableLine)
{
for (var i = 0; i < len[l] + 4; ++i)
Logger.Write(tableLine);
}
else if (row[l].Length == len[l])
{
Logger.Write(" ");
Logger.Write(row[l]);
Logger.Write(" ");
}
else
{
var lenHalf = row[l].Length / 2;
for (var i = 0; i < (len[l] + 4) / 2 - lenHalf; ++i)
Logger.Write(" ");
Logger.Write(row[l]);
for (var i = (len[l] + 4) / 2 + lenHalf + 1; i < len[l] + 4; ++i)
Logger.Write(" ");
if (row[l].Length % 2 == 0)
Logger.Write(" ");
}
Logger.Write(row[l][0] == tableLine ? tableCross : tableWall);
}
Logger.WriteLine(); //end line
}
return;
}
if (format == TableFormat.CENTER_OVERALL_LENGTH)
{
var maxLen = 0;
foreach (var row in data)
foreach (var s in row)
if (s.Length > maxLen)
maxLen = s.Length;
var div = (maxLen + 4) / 2;
foreach (var row in data)
{
Logger.Write("\t");
if (row[0] == "-")
Logger.Write("+");
else
Logger.Write("|");
foreach (var s in row)
{
if (s == "-")
{
for (var i = 0; i < maxLen + 4; ++i)
Logger.Write("-");
}
else if (s.Length == maxLen)
{
Logger.Write(" ");
Logger.Write(s);
Logger.Write(" ");
}
else
{
var lenHalf = s.Length / 2;
for (var i = 0; i < div - lenHalf; ++i)
Logger.Write(" ");
Logger.Write(s);
for (var i = div + lenHalf + 1; i < maxLen + 4; ++i)
Logger.Write(" ");
if (s.Length % 2 == 0)
Logger.Write(" ");
}
if (s == "-")
Logger.Write("+");
else
Logger.Write("|");
}
Logger.WriteLine(); //end line
}
return;
}
if (format == TableFormat.DEFAULT)
{
var widths = new int[data[0].Length];
var space_between_columns = 3;
for (var i = 0; i < data.Count; i++)
for (var j = 0; j < data[i].Length; j++)
if (data[i][j].Length > widths[j])
widths[j] = data[i][j].Length;
for (var i = 0; i < data.Count; i++)
{
for (var j = 0; j < data[i].Length; j++)
{
if (data[i][j] == "-")
data[i][j] = " ";
Logger.Write(data[i][j]);
for (var k = 0; k < widths[j] - data[i][j].Length + 1 + space_between_columns; k++)
Logger.Write(" ");
}
Logger.WriteLine();
}
return;
}
throw new Exception("Unknown type of table");
}
public static void WriteColorText(string text, bool appendNewLineAtEnd = true)
{
if (!Logger.isConsole)
{
foreach (var item in Colors)
text = text.Replace($"{ColorPrefix}{item.Key}", "").Replace("&c", "");
Logger.Write(text);
if (appendNewLineAtEnd)
Logger.WriteLine();
return;
}
var initialForeGround = Console.ForegroundColor;
var input = text.ToCharArray();
for (var i = 0; i < input.Length; i++)
if (input[i] == ColorPrefix)
{
if (i + 1 < input.Length)
{
if (Colors.ContainsKey(input[i + 1]))
{
Console.ForegroundColor = Colors[input[i + 1]];
i++;
}
else if (input[i + 1] == 'c')
{
Console.ForegroundColor = initialForeGround;
i++;
}
}
}
else
{
Logger.Write(input[i]);
}
Console.ForegroundColor = initialForeGround;
if (appendNewLineAtEnd)
Logger.WriteLine();
}
/// <summary>
/// Progress bar object
/// </summary>
public class ProgressBar
{
private readonly int BarLength = 32;
private bool isRunning;
private int position = 1;
private bool positive = true;
public ProgressBar(ProgressBarType type)
{
if (!Logger.isConsole)
throw new Exception("This class (or function) can be used with console only. For UI please use another approach.");
this.type = type;
}
public float Max { get; init; }
public ConsoleColor Color { get; init; }
public bool NoColor { get; init; }
public ProgressBarType type { get; set; }
public int TotalLength { get; private set; }
public async void Start()
{
if (type != ProgressBarType.NO_END)
throw new Exception("Only NO_END progress bar can use this method");
if (isRunning)
throw new Exception("This progress bar is already running");
isRunning = true;
while (isRunning)
{
UpdateNoEnd();
await Task.Delay(100);
}
}
public async void Start(string message)
{
if (type != ProgressBarType.NO_END)
throw new Exception("Only NO_END progress bar can use this method");
if (isRunning)
throw new Exception("This progress bar is already running");
isRunning = true;
TotalLength = message.Length + BarLength + 5;
while (isRunning)
{
UpdateNoEnd(message);
await Task.Delay(100);
}
}
public void Stop()
{
if (type != ProgressBarType.NO_END)
throw new Exception("Only NO_END progress bar can use this method");
if (!isRunning)
throw new Exception("Can not stop a progressbar that did not start");
isRunning = false;
}
public void Stop(string message)
{
Stop();
if (message is not null)
{
Console.CursorLeft = 0;
for (var i = 0; i < BarLength + message.Length + 1; i++)
Logger.Write(" ");
Console.CursorLeft = 0;
Logger.WriteLine(message);
}
}
public void Update(float progress)
{
if (type == ProgressBarType.NO_END)
throw new Exception("This function is for progress bars with end");
UpdateNormal(progress);
}
private void UpdateNoEnd(string message)
{
Console.CursorLeft = 0;
Logger.Write("[");
for (var i = 1; i <= position; i++)
Logger.Write(" ");
Logger.Write("<==()==>");
position += positive ? 1 : -1;
for (var i = position; i <= BarLength - 1 - (positive ? 0 : 2); i++)
Logger.Write(" ");
Logger.Write("] " + message);
if (position == BarLength - 1 || position == 1)
positive = !positive;
}
private void UpdateNoEnd()
{
Console.CursorLeft = 0;
Logger.Write("[");
for (var i = 1; i <= position; i++)
Logger.Write(" ");
Logger.Write("<==()==>");
position += positive ? 1 : -1;
for (var i = position; i <= BarLength - 1 - (positive ? 0 : 2); i++)
Logger.Write(" ");
Logger.Write("]");
if (position == BarLength - 1 || position == 1)
positive = !positive;
}
private void UpdateNormal(float progress)
{
Console.CursorLeft = 0;
Logger.Write("[");
Console.CursorLeft = BarLength;
Logger.Write("]");
Console.CursorLeft = 1;
var onechunk = 30.0f / Max;
var position = 1;
for (var i = 0; i < onechunk * progress; i++)
{
Console.BackgroundColor = NoColor ? ConsoleColor.Black : Color;
Console.CursorLeft = position++;
Logger.Write("#");
}
for (var i = position; i < BarLength; i++)
{
Console.BackgroundColor = NoColor ? ConsoleColor.Black : ConsoleColor.DarkGray;
Console.CursorLeft = position++;
Logger.Write(" ");
}
Console.CursorLeft = BarLength + 4;
Console.BackgroundColor = ConsoleColor.Black;
if (progress.CanAproximateTo(Max))
Logger.Write(progress + " % ✓");
else
Logger.Write(MathF.Round(progress, 2) + " % ");
}
}
}

View File

@@ -0,0 +1,20 @@
using Discord.Commands;
namespace PluginManager.Others;
public class DBCommandExecutingArguments
{
public DBCommandExecutingArguments(
SocketCommandContext context, string cleanContent, string commandUsed, string[]? arguments)
{
this.context = context;
this.cleanContent = cleanContent;
this.commandUsed = commandUsed;
this.arguments = arguments;
}
public SocketCommandContext context { get; init; }
public string cleanContent { get; init; }
public string commandUsed { get; init; }
public string[]? arguments { get; init; }
}

View File

@@ -11,25 +11,11 @@ public enum OperatingSystem
UNKNOWN UNKNOWN
} }
/// <summary>
/// A list with all errors
/// </summary>
public enum Error
{
UNKNOWN_ERROR,
GUILD_NOT_FOUND,
STREAM_NOT_FOUND,
INVALID_USER,
INVALID_CHANNEL,
INVALID_PERMISSIONS
}
/// <summary> /// <summary>
/// The output log type /// The output log type
/// </summary> /// </summary>
public enum OutputLogLevel public enum LogLevel
{ {
NONE,
INFO, INFO,
WARNING, WARNING,
ERROR, ERROR,
@@ -38,15 +24,8 @@ public enum OutputLogLevel
public enum UnzipProgressType public enum UnzipProgressType
{ {
PercentageFromNumberOfFiles, PERCENTAGE_FROM_NUMBER_OF_FILES,
PercentageFromTotalSize PERCENTAGE_FROM_TOTAL_SIZE
}
public enum TableFormat
{
CENTER_EACH_COLUMN_BASED,
CENTER_OVERALL_LENGTH,
DEFAULT
} }
public enum SaveType public enum SaveType
@@ -55,8 +34,14 @@ public enum SaveType
BACKUP BACKUP
} }
public enum ProgressBarType public enum InternalActionRunType
{ {
NORMAL, ON_STARTUP,
NO_END ON_CALL
} }
internal enum ExceptionExitCode : int
{
CONFIG_FAILED_TO_LOAD = 1,
CONFIG_KEY_NOT_FOUND = 2,
}

View File

@@ -0,0 +1,91 @@
using System;
using System.Collections.Generic;
using PluginManager.Interfaces.Exceptions;
namespace PluginManager.Others.Exceptions;
public class ConfigFailedToLoad : IException
{
public List<string>? Messages { get; set; }
public bool isFatal { get; private set; }
public string? File { get; }
public ConfigFailedToLoad(string message, bool isFatal, string file)
{
this.isFatal = isFatal;
Messages = new List<string>() {message};
this.File = file;
}
public ConfigFailedToLoad(string message, bool isFatal)
{
this.isFatal = isFatal;
Messages = new List<string>() {message};
this.File = null;
}
public ConfigFailedToLoad(string message)
{
this.isFatal = false;
Messages = new List<string>() {message};
this.File = null;
}
public string GenerateFullMessage()
{
string messages = "";
foreach (var message in Messages)
{
messages += message + "\n";
}
return $"\nMessage: {messages}\nIsFatal: {isFatal}\nFile: {File ?? "null"}";
}
public void HandleException()
{
if (isFatal)
{
Config.Logger.Log(GenerateFullMessage(), LogLevel.CRITICAL, true);
Environment.Exit((int)ExceptionExitCode.CONFIG_FAILED_TO_LOAD);
}
Config.Logger.Log(GenerateFullMessage(), LogLevel.WARNING);
}
public IException AppendError(string message)
{
Messages.Add(message);
return this;
}
public IException AppendError(List<string> messages)
{
Messages.AddRange(messages);
return this;
}
public IException IsFatal(bool isFatal = true)
{
this.isFatal = isFatal;
return this;
}
public static ConfigFailedToLoad CreateError(string message, bool isFatal, string? file = null)
{
if (file is not null)
return new ConfigFailedToLoad(message, isFatal, file);
return new ConfigFailedToLoad(message, isFatal);
}
public static ConfigFailedToLoad CreateError(string message)
{
return new ConfigFailedToLoad(message);
}
}

View File

@@ -0,0 +1,75 @@
using System;
using System.Collections.Generic;
using PluginManager.Interfaces.Exceptions;
namespace PluginManager.Others.Exceptions;
public class ConfigNoKeyWasPresent: IException
{
public List<string> Messages { get; set; }
public bool isFatal { get; private set; }
public ConfigNoKeyWasPresent(string message, bool isFatal)
{
this.Messages = new List<string>() { message };
this.isFatal = isFatal;
}
public ConfigNoKeyWasPresent(string message)
{
this.Messages = new List<string>() { message };
this.isFatal = false;
}
public string GenerateFullMessage()
{
string messages = "";
foreach (var message in Messages)
{
messages += message + "\n";
}
return $"\nMessage: {messages}\nIsFatal: {isFatal}";
}
public void HandleException()
{
if (isFatal)
{
Config.Logger.Log(GenerateFullMessage(), LogLevel.CRITICAL, true);
Environment.Exit((int)ExceptionExitCode.CONFIG_KEY_NOT_FOUND);
}
Config.Logger.Log(GenerateFullMessage(), LogLevel.WARNING);
}
public IException AppendError(string message)
{
Messages.Add(message);
return this;
}
public IException AppendError(List<string> messages)
{
Messages.AddRange(messages);
return this;
}
public IException IsFatal(bool isFatal = true)
{
this.isFatal = isFatal;
return this;
}
public static ConfigNoKeyWasPresent CreateError(string message)
{
return new ConfigNoKeyWasPresent(message);
}
public static ConfigNoKeyWasPresent CreateError(string message, bool isFatal)
{
return new ConfigNoKeyWasPresent(message, isFatal);
}
}

View File

@@ -1,16 +1,11 @@
using System; using System;
using System.Collections.Generic;
using System.IO; using System.IO;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Text; using System.Text;
using System.Text.Json; using System.Text.Json;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using Discord;
using Discord.WebSocket;
using PluginManager.Items;
namespace PluginManager.Others; namespace PluginManager.Others;
@@ -21,9 +16,19 @@ public static class Functions
{ {
/// <summary> /// <summary>
/// The location for the Resources folder /// The location for the Resources folder
/// String: ./Data/Resources/
/// </summary> /// </summary>
public static readonly string dataFolder = @"./Data/Resources/"; public static readonly string dataFolder = @"./Data/Resources/";
public static Color RandomColor
{
get
{
var random = new Random();
return new Color(random.Next(0, 255), random.Next(0, 255), random.Next(0, 255));
}
}
/// <summary> /// <summary>
/// Get the Operating system you are runnin on /// Get the Operating system you are runnin on
/// </summary> /// </summary>
@@ -48,9 +53,10 @@ public static class Functions
/// <exception cref="ArgumentOutOfRangeException">Triggered if <paramref name="bufferSize" /> is less then or equal to 0</exception> /// <exception cref="ArgumentOutOfRangeException">Triggered if <paramref name="bufferSize" /> is less then or equal to 0</exception>
/// <exception cref="InvalidOperationException">Triggered if <paramref name="stream" /> is not readable</exception> /// <exception cref="InvalidOperationException">Triggered if <paramref name="stream" /> is not readable</exception>
/// <exception cref="ArgumentException">Triggered in <paramref name="destination" /> is not writable</exception> /// <exception cref="ArgumentException">Triggered in <paramref name="destination" /> is not writable</exception>
public static async Task CopyToOtherStreamAsync(this Stream stream, Stream destination, int bufferSize, public static async Task CopyToOtherStreamAsync(
IProgress<long>? progress = null, this Stream stream, Stream destination, int bufferSize,
CancellationToken cancellationToken = default) IProgress<long>? progress = null,
CancellationToken cancellationToken = default)
{ {
if (stream == null) throw new ArgumentNullException(nameof(stream)); if (stream == null) throw new ArgumentNullException(nameof(stream));
if (destination == null) throw new ArgumentNullException(nameof(destination)); if (destination == null) throw new ArgumentNullException(nameof(destination));
@@ -59,50 +65,34 @@ public static class Functions
if (!destination.CanWrite) if (!destination.CanWrite)
throw new ArgumentException("Destination stream is not writable", nameof(destination)); throw new ArgumentException("Destination stream is not writable", nameof(destination));
var buffer = new byte[bufferSize]; var buffer = new byte[bufferSize];
long totalBytesRead = 0; long totalBytesRead = 0;
int bytesRead; int bytesRead;
while ((bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false)) != 0) while ((bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length, cancellationToken)
.ConfigureAwait(false)) != 0)
{ {
await destination.WriteAsync(buffer, 0, bytesRead, cancellationToken).ConfigureAwait(false); await destination.WriteAsync(buffer, 0, bytesRead, cancellationToken).ConfigureAwait(false);
totalBytesRead += bytesRead; totalBytesRead += bytesRead;
progress?.Report(totalBytesRead); progress?.Report(totalBytesRead);
} }
} }
/// <summary> public static T SelectRandomValueOf<T>()
/// Save to JSON file
/// </summary>
/// <typeparam name="T">The class type</typeparam>
/// <param name="file">The file path</param>
/// <param name="Data">The values</param>
/// <returns></returns>
public static async Task SaveToJsonFile<T>(string file, T Data)
{ {
var str = new MemoryStream(); var enums = Enum.GetValues(typeof(T));
await JsonSerializer.SerializeAsync(str, Data, typeof(T), new JsonSerializerOptions { WriteIndented = true }); var random = new Random();
await File.WriteAllBytesAsync(file, str.ToArray()); return (T)enums.GetValue(random.Next(enums.Length));
await str.FlushAsync();
str.Close();
} }
/// <summary> public static T RandomValue<T>(this T[] values)
/// Convert json text or file to some kind of data
/// </summary>
/// <typeparam name="T">The data type</typeparam>
/// <param name="input">The file or json text</param>
/// <returns></returns>
public static async Task<T> ConvertFromJson<T>(string input)
{ {
Stream text; Random random = new();
if (File.Exists(input)) return values[random.Next(values.Length)];
text = new MemoryStream(await File.ReadAllBytesAsync(input));
else
text = new MemoryStream(Encoding.ASCII.GetBytes(input));
text.Position = 0;
var obj = await JsonSerializer.DeserializeAsync<T>(text);
await text.FlushAsync();
text.Close();
return (obj ?? default)!;
} }
}
public static string ToResourcesPath(this string path)
{
return Path.Combine(dataFolder, path);
}
}

View File

@@ -0,0 +1,47 @@
using System;
using System.IO;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
namespace PluginManager;
public class JsonManager
{
/// <summary>
/// Save to JSON file
/// </summary>
/// <typeparam name="T">The class type</typeparam>
/// <param name="file">The file path</param>
/// <param name="Data">The values</param>
/// <returns></returns>
public static async Task SaveToJsonFile<T>(string file, T Data)
{
var str = new MemoryStream();
await JsonSerializer.SerializeAsync(str, Data, typeof(T), new JsonSerializerOptions { WriteIndented = true });
await File.WriteAllBytesAsync(file, str.ToArray());
await str.FlushAsync();
str.Close();
}
/// <summary>
/// Convert json text or file to some kind of data
/// </summary>
/// <typeparam name="T">The data type</typeparam>
/// <param name="input">The file or json text</param>
/// <returns></returns>
public static async Task<T> ConvertFromJson<T>(string input)
{
Stream text;
if (File.Exists(input))
text = new MemoryStream(await File.ReadAllBytesAsync(input));
else
text = new MemoryStream(Encoding.ASCII.GetBytes(input));
text.Position = 0;
var obj = await JsonSerializer.DeserializeAsync<T>(text);
await text.FlushAsync();
text.Close();
return (obj ?? default)!;
}
}

View File

@@ -0,0 +1,76 @@
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace PluginManager.Others.Logger;
public class DBLogger
{
public delegate void LogHandler(string message, LogLevel logType, bool isInternal = false);
private readonly string _errFolder;
private readonly string _logFolder;
private readonly List<LogMessage> ErrorHistory = new();
private readonly List<LogMessage> LogHistory = new();
public DBLogger()
{
_logFolder = Config.AppSettings["LogFolder"];
_errFolder = Config.AppSettings["ErrorFolder"];
}
public IReadOnlyList<LogMessage> Logs => LogHistory;
public IReadOnlyList<LogMessage> Errors => ErrorHistory;
public event LogHandler? LogEvent;
public void Log(string message, LogLevel type = LogLevel.INFO)
{
Log(new LogMessage(message, type));
}
public void Log(string message, LogLevel type= LogLevel.INFO, bool isInternal = false)
{
Log(new LogMessage(message, type,"unknown", isInternal));
}
public void Log(string message, string sender = "unknown", LogLevel type = LogLevel.INFO, bool isInternal = false)
{
Log(new LogMessage(message, type,sender,isInternal));
}
public void Log(string message, string sender = "unknown", LogLevel type = LogLevel.INFO)
{
Log(new LogMessage(message, type, sender));
}
public void Error(Exception? e)
{
Log(e.Message, e.Source, LogLevel.ERROR);
}
public void Log(LogMessage message)
{
LogEvent?.Invoke(message.Message, message.Type);
if (message.Type != LogLevel.ERROR && message.Type != LogLevel.CRITICAL)
LogHistory.Add(message);
else
ErrorHistory.Add(message);
}
public void Log(string message, object sender, LogLevel type = LogLevel.INFO)
{
Log(message, sender.GetType().Name, type);
}
public async Task SaveToFile(bool ErrorsOnly = true)
{
if(!ErrorsOnly)
await JsonManager.SaveToJsonFile(_logFolder + "/" + DateTime.Now.ToString("yyyy-MM-dd") + ".json",
LogHistory);
await JsonManager.SaveToJsonFile(_errFolder + "/" + DateTime.Now.ToString("yyyy-MM-dd") + ".json",
ErrorHistory);
}
}

View File

@@ -0,0 +1,51 @@
using System;
namespace PluginManager.Others.Logger;
public class LogMessage
{
public LogMessage(string message, LogLevel type)
{
Message = message;
Type = type;
Time = DateTime.Now.ToString("HH:mm:ss");
isInternal = false;
}
public LogMessage(string message, LogLevel type, string sender, bool isInternal) : this(message, type)
{
Sender = sender;
this.isInternal = isInternal;
}
public LogMessage(string message, LogLevel type, string sender) : this (message, type, sender, false)
{
}
public string Message { get; set; }
public LogLevel Type { get; set; }
public string Time { get; set; }
public string Sender { get; set; }
public bool isInternal { get; set; }
public override string ToString()
{
return $"[{Time}] {Message}";
}
public static explicit operator LogMessage(string message)
{
return new LogMessage(message, LogLevel.INFO);
}
public static explicit operator LogMessage((string message, LogLevel type) tuple)
{
return new LogMessage(tuple.message, tuple.type);
}
public static explicit operator LogMessage((string message, LogLevel type, string sender) tuple)
{
return new LogMessage(tuple.message, tuple.type, tuple.sender);
}
}

View File

@@ -1,5 +1,4 @@
using System.Linq; using System.Linq;
using Discord; using Discord;
using Discord.WebSocket; using Discord.WebSocket;
@@ -62,4 +61,4 @@ public static class DiscordPermissions
{ {
return isAdmin((SocketGuildUser)user); return isAdmin((SocketGuildUser)user);
} }
} }

View File

@@ -0,0 +1,141 @@
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using PluginManager.Others.Exceptions;
namespace PluginManager.Others;
public class SettingsDictionary<TKey, TValue> : IDictionary<TKey, TValue>
{
public string? _file { get; }
private IDictionary<TKey, TValue>? _dictionary;
public SettingsDictionary(string? file)
{
_file = file;
if (!LoadFromFile())
{
ConfigFailedToLoad.CreateError("Failed to load config")
.AppendError("The file is empty or does not exist")
.IsFatal()
.HandleException();
}
}
public async Task SaveToFile()
{
if (!string.IsNullOrEmpty(_file))
await JsonManager.SaveToJsonFile(_file, _dictionary);
}
private bool LoadFromFile()
{
if (!string.IsNullOrEmpty(_file))
try
{
if (File.Exists(_file))
{
string FileContent = File.ReadAllText(_file);
if (string.IsNullOrEmpty(FileContent))
File.WriteAllText(_file, "{}");
if(!FileContent.Contains("{") || !FileContent.Contains("}"))
File.WriteAllText(_file, "{}");
}
else
File.WriteAllText(_file, "{}");
_dictionary = JsonManager.ConvertFromJson<IDictionary<TKey, TValue>>(_file).Result;
return true;
}
catch
{
ConfigFailedToLoad
.CreateError("Failed to load config")
.IsFatal()
.HandleException();
return false;
}
return false;
}
public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
{
return _dictionary!.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable) _dictionary!).GetEnumerator();
}
public void Add(KeyValuePair<TKey, TValue> item)
{
this._dictionary!.Add(item);
}
public void Clear()
{
this._dictionary!.Clear();
}
public bool Contains(KeyValuePair<TKey, TValue> item)
{
return this._dictionary!.Contains(item);
}
public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
{
this._dictionary!.CopyTo(array, arrayIndex);
}
public bool Remove(KeyValuePair<TKey, TValue> item)
{
return this._dictionary!.Remove(item);
}
public int Count => _dictionary!.Count;
public bool IsReadOnly => _dictionary!.IsReadOnly;
public void Add(TKey key, TValue value)
{
this._dictionary!.Add(key, value);
}
public bool ContainsKey(TKey key)
{
return this._dictionary!.ContainsKey(key);
}
public bool Remove(TKey key)
{
return this._dictionary!.Remove(key);
}
public bool TryGetValue(TKey key, out TValue value)
{
return this._dictionary!.TryGetValue(key, out value);
}
public TValue this[TKey key]
{
get
{
if (this._dictionary!.ContainsKey(key))
if(this._dictionary[key] is string s && !string.IsNullOrEmpty(s) && !string.IsNullOrWhiteSpace(s))
return this._dictionary[key];
ConfigNoKeyWasPresent.CreateError($"Key {(key is string ? key : typeof(TKey).Name)} was not present in {_file ?? "config"}")
.AppendError("Deleting the file may fix this issue")
.IsFatal()
.HandleException();
return default!;
}
set => this._dictionary![key] = value;
}
public ICollection<TKey> Keys => _dictionary!.Keys;
public ICollection<TValue> Values => _dictionary!.Values;
}

View File

@@ -1,24 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<PropertyGroup> <TargetFramework>net6.0</TargetFramework>
<TargetFramework>net6.0</TargetFramework> <Nullable>enable</Nullable>
<Nullable>enable</Nullable> </PropertyGroup>
</PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<FileAlignment>512</FileAlignment>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'"> <DebugType>none</DebugType>
<FileAlignment>512</FileAlignment> <DebugSymbols>false</DebugSymbols>
<DebugType>none</DebugType> </PropertyGroup>
<DebugSymbols>false</DebugSymbols> <ItemGroup>
</PropertyGroup> <None Remove="BlankWindow1.xaml" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<None Remove="BlankWindow1.xaml" /> <PackageReference Include="Discord.Net" Version="3.11.0" />
</ItemGroup> <PackageReference Include="System.Data.SQLite.Core" Version="1.0.118" />
</ItemGroup>
<ItemGroup> </Project>
<PackageReference Include="Discord.Net" Version="3.8.1" />
<PackageReference Include="System.Data.SQLite.Core" Version="1.0.117" />
<PackageReference Include="Terminal.Gui" Version="1.8.2" />
</ItemGroup>
</Project>

View File

@@ -1,17 +0,0 @@
using PluginManager.Database;
namespace PluginManager
{
public class Settings
{
public static class Variables
{
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 SqlDatabase sqlDatabase;
}
}

View File

@@ -6,6 +6,8 @@ This project is based on:
- [.NET 6 (C#)](https://dotnet.microsoft.com/en-us/download/dotnet/6.0) - [.NET 6 (C#)](https://dotnet.microsoft.com/en-us/download/dotnet/6.0)
- [Discord.Net](https://github.com/discord-net/Discord.Net) - [Discord.Net](https://github.com/discord-net/Discord.Net)
- Some plugins can be found [here](https://github.com/andreitdr/SethPlugins).
## Plugins ## Plugins
#### Requirements: #### Requirements:
@@ -19,12 +21,12 @@ Plugin Types:
### How to create a plugin ### How to create a plugin
First of all, Create a new project (class library) in Visual Studio. First of all, create a new project (class library) in Visual Studio.
Then import the PluginManager.dll as project to your project. Then import the PluginManager as reference to your project.
## 1. Commands ## 1. Commands
Commands are loaded when all plugins are loaded into memory. When an user executes the command, only then the Execute function is called. Commands are loaded when all plugins are loaded into memory. The Execute method is called whenever any user (that respects the `requireAdmin` propery) calls the command using the bot prefix and the `Command`.
Commands are plugins that allow users to interact with them. Commands are plugins that allow users to interact with them.
Here is an example: Here is an example:
```cs ```cs
@@ -35,20 +37,21 @@ using PluginManager.Interfaces;
namespace LevelingSystem; namespace LevelingSystem;
internal class LevelCommand : DBCommand public class LevelCommand : DBCommand
{ {
public string Command => "level"; public string Command => "level";
public List<string> Aliases => new() { "lvl" }; public List<string> Aliases => new() { "lvl" };
public string Description => "Display tour current level"; public string Description => "Display your current level";
public string Usage => "level"; public string Usage => "level";
public bool requireAdmin => false; public bool requireAdmin => false;
public async void ExecuteServer(SocketCommandContext context) public async void ExecuteServer(DBCommandExecutingArguments context)
{ {
//Variables.database is a sql connection that is defined in an auxiliary file in the same napespace as this class
object[] user = await Variables.database.ReadDataArrayAsync($"SELECT * FROM Levels WHERE UserID='{context.Message.Author.Id}'"); object[] user = await Variables.database.ReadDataArrayAsync($"SELECT * FROM Levels WHERE UserID='{context.Message.Author.Id}'");
if (user is null) if (user is null)
{ {
@@ -69,6 +72,11 @@ internal class LevelCommand : DBCommand
builder.WithAuthor(context.Message.Author.Mention); builder.WithAuthor(context.Message.Author.Mention);
await context.Channel.SendMessageAsync(embed: builder.Build()); await context.Channel.SendMessageAsync(embed: builder.Build());
} }
//Optional method (tell the bot what should it do if the command is executed from a DM channel)
//public async void ExecuteDM(DBCommandExecutingArguments context) {
//
//}
} }
@@ -85,7 +93,7 @@ internal class LevelCommand : DBCommand
- context - the command context - context - the command context
From here on, start coding. When your plugin is done, build it as any DLL project then add it to the following path From here on, start coding. When your plugin is done, build it as any DLL project then add it to the following path
`{bot_executable}/Data/Plugins/<optional subfolder>/[your dll name].dll` `{bot_executable}/Data/Plugins/<optional subfolder>/[plugin name].dll`
Then, reload bot and execute command `lp` in bot's console. The plugin should be loaded into memory or an error is thrown if not. If an error is thrown, then Then, reload bot and execute command `lp` in bot's console. The plugin should be loaded into memory or an error is thrown if not. If an error is thrown, then
there is something wrong in your command's code. there is something wrong in your command's code.
@@ -107,8 +115,6 @@ public class OnUserJoin : DBEvent
public async void Start(Discord.WebSocket.DiscordSocketClient client) public async void Start(Discord.WebSocket.DiscordSocketClient client)
{ {
Console.WriteLine($"Hello World from {name}");
client.UserJoined += async (user) => { client.UserJoined += async (user) => {
await (await user.CreateDMChannelAsync()).SendMessageAsync("Welcome to server !"); await (await user.CreateDMChannelAsync()).SendMessageAsync("Welcome to server !");
}; };
@@ -148,7 +154,7 @@ namespace SlashCommands
public List<SlashCommandOptionBuilder> Options => new List<SlashCommandOptionBuilder>() public List<SlashCommandOptionBuilder> Options => new List<SlashCommandOptionBuilder>()
{ {
new SlashCommandOptionBuilder() {Name = "min-value", Description = "Minimum value", IsRequired=true, Type = ApplicationCommandOptionType.Integer, MinValue = 0, MaxValue = int.MaxValue-1}, new SlashCommandOptionBuilder() {Name = "min-value", Description = "Minimum value", IsRequired=true, Type = ApplicationCommandOptionType.Integer, MinValue = 0, MaxValue = int.MaxValue-1},
new SlashCommandOptionBuilder() {Name="max-value", Description = "Maximum value", IsRequired=true, Type=ApplicationCommandOptionType.Integer,MinValue = 0, MaxValue = int.MaxValue-1} new SlashCommandOptionBuilder() {Name = "max-value", Description = "Maximum value", IsRequired=true, Type=ApplicationCommandOptionType.Integer,MinValue = 0, MaxValue = int.MaxValue-1}
}; };
public async void ExecuteServer(SocketSlashCommand command) public async void ExecuteServer(SocketSlashCommand command)
@@ -180,3 +186,10 @@ namespace SlashCommands
- context - the command context - context - the command context
- ExecuteDM() - this function will be called if the command is invoked in a DM channel (optional) - ExecuteDM() - this function will be called if the command is invoked in a DM channel (optional)
- context - the command context - context - the command context
## Note:
You can create multiple commands, events and slash commands into one single plugin (class library). The PluginManager will detect the classes and load them individualy. If there are more commands (normal commands, events or slash commands) into a single project (class library) they can use the same resources (a class for example) that is contained within the plugin.
> Updated: 5.08.2023

View File

@@ -1,4 +1,4 @@
Microsoft Visual Studio Solution File, Format Version 12.00 Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17 # Visual Studio Version 17
VisualStudioVersion = 17.1.32421.90 VisualStudioVersion = 17.1.32421.90
@@ -7,15 +7,11 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DiscordBot", "DiscordBot\Di
EndProject EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "PluginManager", "PluginManager\PluginManager.csproj", "{EDD4D9B3-98DD-4367-A09F-D1C5ACB61132}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "PluginManager", "PluginManager\PluginManager.csproj", "{EDD4D9B3-98DD-4367-A09F-D1C5ACB61132}"
EndProject EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MusicLibrary", "..\DiscordBotItems\Plugins\MusicLibrary\MusicLibrary.csproj", "{878DFE01-4596-4EBC-9651-0679598CE794}" Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "SethPlugins", "SethPlugins", "{78B6D390-F61A-453F-B38D-E4C054321615}"
EndProject EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SlashCommands", "..\DiscordBotItems\Plugins\SlashCommands\SlashCommands.csproj", "{C2D73BE8-997B-4A4A-8EA5-989BE33EE1DD}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MusicPlayer", "..\SethPlugins\MusicPlayer\MusicPlayer.csproj", "{1690CBBC-BDC0-4DD8-B701-F8817189D9D5}"
EndProject EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "LevelingSystem", "..\DiscordBotItems\Plugins\LevelingSystem\LevelingSystem.csproj", "{0138F343-BBB9-4D5F-B499-D9C2978BE9AA}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LevelingSystem", "..\SethPlugins\LevelingSystem\LevelingSystem.csproj", "{BFE3491C-AC01-4252-B242-6451270FC548}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Roles", "..\DiscordBotItems\Roles\Roles.csproj", "{0900B4CB-B531-4A8D-98D8-E709A7C2E098}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DBEconomy", "..\DiscordBotItems\Plugins\DBEconomy\DBEconomy.csproj", "{0321365B-4ADC-4B1D-BD98-F573D36E83B2}"
EndProject EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution
@@ -31,30 +27,22 @@ Global
{EDD4D9B3-98DD-4367-A09F-D1C5ACB61132}.Debug|Any CPU.Build.0 = Debug|Any CPU {EDD4D9B3-98DD-4367-A09F-D1C5ACB61132}.Debug|Any CPU.Build.0 = Debug|Any CPU
{EDD4D9B3-98DD-4367-A09F-D1C5ACB61132}.Release|Any CPU.ActiveCfg = Release|Any CPU {EDD4D9B3-98DD-4367-A09F-D1C5ACB61132}.Release|Any CPU.ActiveCfg = Release|Any CPU
{EDD4D9B3-98DD-4367-A09F-D1C5ACB61132}.Release|Any CPU.Build.0 = Release|Any CPU {EDD4D9B3-98DD-4367-A09F-D1C5ACB61132}.Release|Any CPU.Build.0 = Release|Any CPU
{878DFE01-4596-4EBC-9651-0679598CE794}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {1690CBBC-BDC0-4DD8-B701-F8817189D9D5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{878DFE01-4596-4EBC-9651-0679598CE794}.Debug|Any CPU.Build.0 = Debug|Any CPU {1690CBBC-BDC0-4DD8-B701-F8817189D9D5}.Debug|Any CPU.Build.0 = Debug|Any CPU
{878DFE01-4596-4EBC-9651-0679598CE794}.Release|Any CPU.ActiveCfg = Release|Any CPU {1690CBBC-BDC0-4DD8-B701-F8817189D9D5}.Release|Any CPU.ActiveCfg = Release|Any CPU
{878DFE01-4596-4EBC-9651-0679598CE794}.Release|Any CPU.Build.0 = Release|Any CPU {1690CBBC-BDC0-4DD8-B701-F8817189D9D5}.Release|Any CPU.Build.0 = Release|Any CPU
{C2D73BE8-997B-4A4A-8EA5-989BE33EE1DD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {BFE3491C-AC01-4252-B242-6451270FC548}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C2D73BE8-997B-4A4A-8EA5-989BE33EE1DD}.Debug|Any CPU.Build.0 = Debug|Any CPU {BFE3491C-AC01-4252-B242-6451270FC548}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C2D73BE8-997B-4A4A-8EA5-989BE33EE1DD}.Release|Any CPU.ActiveCfg = Release|Any CPU {BFE3491C-AC01-4252-B242-6451270FC548}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C2D73BE8-997B-4A4A-8EA5-989BE33EE1DD}.Release|Any CPU.Build.0 = Release|Any CPU {BFE3491C-AC01-4252-B242-6451270FC548}.Release|Any CPU.Build.0 = Release|Any CPU
{0138F343-BBB9-4D5F-B499-D9C2978BE9AA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{0138F343-BBB9-4D5F-B499-D9C2978BE9AA}.Debug|Any CPU.Build.0 = Debug|Any CPU
{0138F343-BBB9-4D5F-B499-D9C2978BE9AA}.Release|Any CPU.ActiveCfg = Release|Any CPU
{0138F343-BBB9-4D5F-B499-D9C2978BE9AA}.Release|Any CPU.Build.0 = Release|Any CPU
{0900B4CB-B531-4A8D-98D8-E709A7C2E098}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{0900B4CB-B531-4A8D-98D8-E709A7C2E098}.Debug|Any CPU.Build.0 = Debug|Any CPU
{0900B4CB-B531-4A8D-98D8-E709A7C2E098}.Release|Any CPU.ActiveCfg = Release|Any CPU
{0900B4CB-B531-4A8D-98D8-E709A7C2E098}.Release|Any CPU.Build.0 = Release|Any CPU
{0321365B-4ADC-4B1D-BD98-F573D36E83B2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{0321365B-4ADC-4B1D-BD98-F573D36E83B2}.Debug|Any CPU.Build.0 = Debug|Any CPU
{0321365B-4ADC-4B1D-BD98-F573D36E83B2}.Release|Any CPU.ActiveCfg = Release|Any CPU
{0321365B-4ADC-4B1D-BD98-F573D36E83B2}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection EndGlobalSection
GlobalSection(SolutionProperties) = preSolution GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE HideSolutionNode = FALSE
EndGlobalSection EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{1690CBBC-BDC0-4DD8-B701-F8817189D9D5} = {78B6D390-F61A-453F-B38D-E4C054321615}
{BFE3491C-AC01-4252-B242-6451270FC548} = {78B6D390-F61A-453F-B38D-E4C054321615}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {3FB3C5DE-ED21-4D2E-ABDD-3A00EE4A2FFF} SolutionGuid = {3FB3C5DE-ED21-4D2E-ABDD-3A00EE4A2FFF}
EndGlobalSection EndGlobalSection