19 Commits

Author SHA1 Message Date
0d5c90323a 2023-02-12 12:25:53 +02:00
5b01b15216 Merge branch 'preview' of https://github.com/Wizzy69/DiscordBotWithAPI into preview 2023-01-31 16:08:02 +02:00
4f18f505f4 Updated to allow mention as command prefix. Updated DBCommand 2023-01-31 16:07:53 +02:00
2d3566a01a 2023-01-12 15:21:45 +02:00
22f2cd4e59 linux updater 2023-01-10 19:42:10 +02:00
1683234376 updater for linux is now working 2023-01-10 19:41:03 +02:00
69d99b4189 Updated Logger and message handler. Updated to latest Discord.Net version 2023-01-01 21:55:29 +02:00
4a5e0ef2f3 2022-12-17 12:38:21 +02:00
79731a9704 2022-12-17 12:35:26 +02:00
bd53d099d1 2022-12-09 14:49:05 +02:00
de61f5de88 2022-12-09 14:49:03 +02:00
0527d43dd2 patch 2022-12-09 14:46:10 +02:00
e3511cd96b 2022-11-18 10:45:43 +02:00
d355d3c9b7 2022-11-18 10:38:47 +02:00
5bb13aa4a6 The library can now be used for Windows exclusive bots (Made with WinForm or Wpf) 2022-11-13 16:28:44 +02:00
655f5e2ce0 2022-11-12 12:20:02 +02:00
9014d78a7d 2022-11-04 14:08:35 +02:00
1c026e7f49 patch 2022-11-02 19:42:58 +02:00
d32b3902c9 2022-11-02 18:59:33 +02:00
34 changed files with 1089 additions and 989 deletions

1
.gitignore vendored
View File

@@ -98,6 +98,7 @@ StyleCopReport.xml
*.pidb
*.svclog
*.scc
*.code-workspace
# Chutzpah Test files
_Chutzpah*

View File

@@ -1,8 +1,8 @@
using System.Collections.Generic;
using System;
using System.Collections.Generic;
using Discord;
using Discord.Commands;
using PluginManager;
using PluginManager.Interfaces;
using PluginManager.Loaders;
@@ -41,19 +41,16 @@ internal class Help : DBCommand
/// The main body of the command
/// </summary>
/// <param name="context">The command context</param>
public void ExecuteServer(SocketCommandContext context)
public void ExecuteServer(CmdArgs args)
{
var args = Functions.GetArguments(context.Message);
if (args.Count != 0)
if (args.arguments is not null)
{
foreach (var item in args)
{
var e = GenerateHelpCommand(item);
if (e is null)
context.Channel.SendMessageAsync("Unknown Command " + item);
else
context.Channel.SendMessageAsync(embed: e.Build());
}
var e = GenerateHelpCommand(args.arguments[0]);
if (e is null)
args.context.Channel.SendMessageAsync("Unknown Command " + args.arguments[0]);
else
args.context.Channel.SendMessageAsync(embed: e.Build());
return;
}
@@ -69,9 +66,12 @@ internal class Help : DBCommand
else
normalCommands += cmd.Command + " ";
embedBuilder.AddField("Admin Commands", adminCommands);
embedBuilder.AddField("Normal Commands", normalCommands);
context.Channel.SendMessageAsync(embed: embedBuilder.Build());
if(adminCommands.Length > 0)
embedBuilder.AddField("Admin Commands", adminCommands);
if(normalCommands.Length > 0)
embedBuilder.AddField("Normal Commands", normalCommands);
args.context.Channel.SendMessageAsync(embed: embedBuilder.Build());
}
private EmbedBuilder GenerateHelpCommand(string command)

View File

@@ -1,100 +0,0 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using PluginManager.Interfaces;
using PluginManager.Others;
using DiscordLibCommands = Discord.Commands;
using DiscordLib = Discord;
using OperatingSystem = PluginManager.Others.OperatingSystem;
namespace DiscordBot.Discord.Commands;
internal class Restart : DBCommand
{
/// <summary>
/// Command name
/// </summary>
public string Command => "restart";
public List<string> Aliases => null;
/// <summary>
/// Command Description
/// </summary>
public string Description => "Restart the bot";
/// <summary>
/// Command usage
/// </summary>
public string Usage => "restart [-p | -c | -args | -cmd] <args>";
/// <summary>
/// Check if the command require administrator to be executed
/// </summary>
public bool requireAdmin => true;
/// <summary>
/// The main body of the command
/// </summary>
/// <param name="context">The command context</param>
public async void ExecuteServer(DiscordLibCommands.SocketCommandContext context)
{
var args = Functions.GetArguments(context.Message);
var OS = Functions.GetOperatingSystem();
if (args.Count == 0)
{
switch (OS)
{
case OperatingSystem.WINDOWS:
Process.Start("./DiscordBot.exe");
break;
case OperatingSystem.LINUX:
case OperatingSystem.MAC_OS:
Process.Start("./DiscordBot");
break;
default:
return;
}
return;
}
switch (args[0])
{
case "-p":
case "-poweroff":
case "-c":
case "-close":
Environment.Exit(0);
break;
case "-cmd":
case "-args":
var cmd = "--args";
if (args.Count > 1)
for (var i = 1; i < args.Count; i++)
cmd += $" {args[i]}";
switch (OS)
{
case OperatingSystem.WINDOWS:
Functions.WriteLogFile("Restarting the bot with the following arguments: \"" + cmd + "\"");
Process.Start("./DiscordBot.exe", cmd);
break;
case OperatingSystem.LINUX:
//case PluginManager.Others.OperatingSystem.MAC_OS: ?? - not tested
Process.Start("./DiscordBot", cmd);
break;
default:
return;
}
Environment.Exit(0);
break;
default:
await context.Channel.SendMessageAsync("Invalid argument. Use `help restart` to see the usage.");
break;
}
}
}

View File

@@ -5,7 +5,7 @@ using Discord;
using Discord.Commands;
using Discord.WebSocket;
using static PluginManager.Others.Functions;
using PluginManager;
namespace DiscordBot.Discord.Core;
@@ -66,7 +66,9 @@ internal class Boot
AlwaysDownloadUsers = true,
//Disable system clock checkup (for responses at slash commands)
UseInteractionSnowflakeDate = false
UseInteractionSnowflakeDate = false,
GatewayIntents = GatewayIntents.All
};
client = new DiscordSocketClient(config);
@@ -79,6 +81,7 @@ internal class Boot
await client.StartAsync();
commandServiceHandler = new CommandHandler(client, service, botPrefix);
await commandServiceHandler.InstallCommandsAsync();
@@ -94,30 +97,38 @@ internal class Boot
client.Log += Log;
client.LoggedIn += LoggedIn;
client.Ready += Ready;
client.Disconnected += Client_Disconnected;
}
private Task Client_Disconnected(Exception arg)
{
if (arg.Message.Contains("401"))
{
Config.Variables.RemoveKey("token");
Program.GenerateStartUI("The token is invalid");
}
Logger.WriteErrFile(arg);
return Task.CompletedTask;
}
private async Task Client_LoggedOut()
{
WriteLogFile("Successfully Logged Out");
Logger.WriteLine("Successfully Logged Out");
await Log(new LogMessage(LogSeverity.Info, "Boot", "Successfully logged out from discord !"));
/* var cmds = await client.GetGlobalApplicationCommandsAsync();
foreach (var cmd in cmds)
await cmd.DeleteAsync();*/
}
private async Task Ready()
private Task Ready()
{
Console.Title = "ONLINE";
isReady = true;
return Task.CompletedTask;
}
private Task LoggedIn()
{
Console.Title = "CONNECTED";
WriteLogFile("The bot has been logged in at " + DateTime.Now.ToShortDateString() + " (" +
Logger.WriteLine("The bot has been logged in at " + DateTime.Now.ToShortDateString() + " (" +
DateTime.Now.ToShortTimeString() + ")"
);
return Task.CompletedTask;
@@ -129,7 +140,7 @@ internal class Boot
{
case LogSeverity.Error:
case LogSeverity.Critical:
WriteErrFile(message.Message);
Logger.WriteErrFile(message.Message);
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("[ERROR] " + message.Message);
@@ -139,7 +150,7 @@ internal class Boot
case LogSeverity.Info:
case LogSeverity.Debug:
WriteLogFile(message.Message);
Logger.WriteLogFile(message.Message);
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine("[INFO] " + message.Message);

View File

@@ -5,11 +5,13 @@ using System.Threading.Tasks;
using Discord.Commands;
using Discord.WebSocket;
using PluginManager.Interfaces;
using PluginManager.Loaders;
using PluginManager.Others;
using PluginManager.Others.Permissions;
using static PluginManager.Logger;
namespace DiscordBot.Discord.Core;
internal class CommandHandler
@@ -29,6 +31,7 @@ internal class CommandHandler
this.client = client;
this.commandService = commandService;
this.botPrefix = botPrefix;
}
/// <summary>
@@ -42,7 +45,7 @@ internal class CommandHandler
await commandService.AddModulesAsync(Assembly.GetEntryAssembly(), null);
}
private async Task Client_SlashCommandExecuted(SocketSlashCommand arg)
private Task Client_SlashCommandExecuted(SocketSlashCommand arg)
{
try
{
@@ -50,7 +53,8 @@ internal class CommandHandler
.Where(p => p.Name == arg.Data.Name)
.FirstOrDefault();
if (plugin is null) throw new Exception("Failed to run command. !");
if (plugin is null)
throw new Exception("Failed to run command. !");
if (arg.Channel is SocketDMChannel)
@@ -64,6 +68,8 @@ internal class CommandHandler
ex.WriteErrFile();
}
return Task.CompletedTask;
}
/// <summary>
@@ -73,54 +79,89 @@ internal class CommandHandler
/// <returns></returns>
private async Task MessageHandler(SocketMessage Message)
{
try
{
if (Message.Author.IsBot)
return;
if (Message as SocketUserMessage == null)
return;
var message = Message as SocketUserMessage;
if (message == null)
return;
if (!message.Content.StartsWith(botPrefix))
if (message is null)
return;
var argPos = 0;
if (message.HasMentionPrefix(client.CurrentUser, ref argPos))
{
await message.Channel.SendMessageAsync("Can not exec mentioned commands !");
return;
}
if (message.Author.IsBot)
if (!message.Content.StartsWith(botPrefix) && !message.HasMentionPrefix(client.CurrentUser, ref argPos))
return;
var context = new SocketCommandContext(client, message);
await commandService.ExecuteAsync(context, argPos, null);
var plugin = PluginLoader.Commands!
.Where(
p => p.Command == message.Content.Split(' ')[0].Substring(botPrefix.Length) ||
(p.Aliases is not null &&
p.Aliases.Contains(
message.Content.Split(' ')[0].Substring(botPrefix.Length))))
.FirstOrDefault();
DBCommand plugin;
string cleanMessage = "";
if (plugin is null) throw new Exception("Failed to run command. !");
if (message.HasMentionPrefix(client.CurrentUser, ref argPos))
{
string mentionPrefix = "<@" + client.CurrentUser.Id + ">";
plugin = PluginLoader.Commands!
.Where
(
plug => plug.Command == message.Content.Substring(mentionPrefix.Length+1).Split(' ')[0] ||
(
plug.Aliases is not null &&
plug.Aliases.Contains(message.CleanContent.Substring(mentionPrefix.Length+1).Split(' ')[0])
)
)
.FirstOrDefault();
cleanMessage = message.Content.Substring(mentionPrefix.Length + 1);
}
else
{
plugin = PluginLoader.Commands!
.Where(
p => p.Command == message.Content.Split(' ')[0].Substring(botPrefix.Length) ||
(p.Aliases is not null &&
p.Aliases.Contains(
message.Content.Split(' ')[0].Substring(botPrefix.Length))))
.FirstOrDefault();
cleanMessage = message.Content.Substring(botPrefix.Length);
}
if (plugin is null)
throw new Exception($"Failed to run command ! " + message.CleanContent);
if (plugin.requireAdmin && !context.Message.Author.isAdmin())
return;
string[] split = cleanMessage.Split(' ');
string[] argsClean = null;
if(split.Length > 1)
argsClean = string.Join(' ', split, 1, split.Length-1).Split(' ');
CmdArgs cmd = new() {
context = context,
cleanContent = cleanMessage,
commandUsed = split[0],
arguments = argsClean
};
if (context.Channel is SocketDMChannel)
plugin.ExecuteDM(context);
else plugin.ExecuteServer(context);
plugin.ExecuteDM(cmd);
else plugin.ExecuteServer(cmd);
}
catch (Exception ex)
{
ex.WriteErrFile();
Console.WriteLine(ex.ToString());
}
}
}

View File

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

View File

@@ -8,7 +8,7 @@
<StartupObject />
<SignAssembly>False</SignAssembly>
<IsPublishable>True</IsPublishable>
<AssemblyVersion>1.0.1.0</AssemblyVersion>
<AssemblyVersion>1.0.1.2</AssemblyVersion>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
@@ -38,11 +38,11 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="Discord.Net" Version="3.7.2" />
<PackageReference Include="Discord.Net" Version="3.9.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\PluginManager\PluginManager.csproj" />
<ProjectReference Include="..\PluginManager\PluginManager.csproj" />
</ItemGroup>
</Project>

View File

@@ -1,13 +1,16 @@
using System;
using PluginManager.Others;
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
namespace DiscordBot
{
public class Entry
{
[STAThread]
internal static StartupArguments startupArguments;
public static void Main(string[] args)
{
AppDomain currentDomain = AppDomain.CurrentDomain;

View File

@@ -1,4 +1,5 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
@@ -23,8 +24,8 @@ namespace DiscordBot;
public class Program
{
private static bool loadPluginsOnStartup;
private static bool listPluginsAtStartup;
private static ConsoleCommandsHandler consoleCommandsHandler;
//private static bool isUI_ON;
/// <summary>
/// The main entry point for the application.
@@ -32,8 +33,7 @@ public class Program
[STAThread]
public static void Startup(string[] args)
{
PreLoadComponents().Wait();
PreLoadComponents(args).Wait();
if (!Config.Variables.Exists("ServerID") || !Config.Variables.Exists("token") ||
Config.Variables.GetValue("token") == null ||
@@ -42,147 +42,7 @@ public class Program
Config.Variables.GetValue("prefix")?.Length != 1 ||
(args.Length == 1 && args[0] == "/reset"))
{
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(
"Configuration file not found or invalid. " +
"Please fill the following fields to create a new configuration file."
)
{
X = Pos.Center(),
Y = 2
};
var labelToken = new Label("Please insert your token here: ")
{
X = 5,
Y = 5
};
var textFiledToken = new TextField("")
{
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("")
{
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("")
{
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();
GenerateStartUI("First time setup. Please fill the following with your discord bot data.\nThis are saved ONLY on YOUR computer.");
}
HandleInput(args).Wait();
@@ -194,12 +54,13 @@ public class Program
private static void NoGUI()
{
#if DEBUG
Settings.Variables.outputStream.WriteLine();
ConsoleCommandsHandler.ExecuteCommad("lp").Wait();
#else
if (loadPluginsOnStartup) consoleCommandsHandler.HandleCommand("lp");
if (listPluginsAtStartup) consoleCommandsHandler.HandleCommand("listplugs");
Logger.WriteLine();
Logger.WriteLine("Debug mode enabled");
Logger.WriteLine();
#endif
if (loadPluginsOnStartup)
consoleCommandsHandler.HandleCommand("lp");
while (true)
{
@@ -210,7 +71,7 @@ public class Program
#endif
) && cmd.Length > 0)
Settings.Variables.outputStream.WriteLine("Failed to run command " + cmd);
Logger.WriteLine("Failed to run command " + cmd);
}
}
@@ -228,11 +89,11 @@ public class Program
"https://raw.githubusercontent.com/Wizzy69/installer/discord-bot-files/StartupMessage");
foreach (var message in startupMessageList)
Settings.Variables.outputStream.WriteLine(message);
Logger.WriteLine(message);
Settings.Variables.outputStream.WriteLine(
Logger.WriteLine(
$"Running on version: {Assembly.GetExecutingAssembly().GetName().Version}");
Settings.Variables.outputStream.WriteLine($"Git URL: {Settings.Variables.WebsiteURL}");
Logger.WriteLine($"Git URL: {Settings.Variables.WebsiteURL}");
Utilities.WriteColorText(
"&rRemember to close the bot using the ShutDown command (&ysd&r) or some settings won't be saved\n");
@@ -244,18 +105,14 @@ public class Program
Utilities.WriteColorText(
"Please note that the bot saves a backup save file every time you are using the shudown command (&ysd&c)");
Settings.Variables.outputStream.WriteLine("============================ LOG ============================");
Logger.WriteLine("============================ LOG ============================");
try
{
string token = "";
#if DEBUG
if (await Settings.sqlDatabase.TableExistsAsync("BetaTest"))
{
Settings.Variables.outputStream.WriteLine("Starting in DEBUG MODE");
token = await Settings.sqlDatabase.GetValueAsync("BetaTest", "VariableName", "Token", "Value");
}
if (File.Exists("./Data/Resources/token.txt")) token = File.ReadAllText("./Data/Resources/token.txt");
else token = Config.Variables.GetValue("token");
#else
token = Config.Variables.GetValue("token");
#endif
@@ -266,7 +123,7 @@ public class Program
}
catch (Exception ex)
{
Settings.Variables.outputStream.WriteLine(ex);
Logger.LogError(ex);
return null;
}
}
@@ -282,16 +139,17 @@ public class Program
var b = await StartNoGui();
consoleCommandsHandler = new ConsoleCommandsHandler(b.client);
if (Entry.startupArguments.loadPluginsAtStartup) { loadPluginsOnStartup = true; }
if (len > 0 && args[0] == "/remplug")
{
var plugName = string.Join(' ', args, 1, args.Length - 1);
Settings.Variables.outputStream.WriteLine("Starting to remove " + plugName);
Logger.WriteLine("Starting to remove " + plugName);
await ConsoleCommandsHandler.ExecuteCommad("remplug " + plugName);
loadPluginsOnStartup = true;
}
if (len > 0 && args[0] == "/lp")
loadPluginsOnStartup = true;
var mainThread = new Thread(() =>
{
@@ -305,31 +163,43 @@ public class Program
{
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);
Functions.WriteErrFile(ex.ToString());
"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()
private static async Task PreLoadComponents(string[] args)
{
Settings.Variables.outputStream = Console.Out;
Settings.Variables.outputStream.WriteLine("Loading resources ...");
var main = new Utilities.ProgressBar(ProgressBarType.NO_END);
main.Start();
Directory.CreateDirectory("./Data/Resources");
Directory.CreateDirectory("./Data/Plugins");
Directory.CreateDirectory("./Data/PAKS");
Settings.sqlDatabase = new SqlDatabase(Functions.dataFolder + "SetDB.dat");
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");
Settings.sqlDatabase = new SqlDatabase("SetDB.dat");
await Settings.sqlDatabase.Open();
await Config.Initialize();
Logger.Initialize(true);
ArchiveManager.Initialize();
Logger.LogEvent += (message) => { Console.Write(message); };
Logger.WriteLine("Loading resources ...");
var main = new Utilities.ProgressBar(ProgressBarType.NO_END);
main.Start();
if (await Config.Variables.ExistsAsync("DeleteLogsAtStartup"))
if (await Config.Variables.GetValueAsync("DeleteLogsAtStartup") == "true")
@@ -341,9 +211,11 @@ public class Program
if (!await Config.Variables.ExistsAsync("Version"))
await Config.Variables.AddAsync("Version", Assembly.GetExecutingAssembly().GetName().Version.ToString(), false);
await Config.Variables.AddAsync("Version", Assembly.GetExecutingAssembly().GetName().Version.ToString(),
false);
else
await Config.Variables.SetValueAsync("Version", Assembly.GetExecutingAssembly().GetName().Version.ToString());
await Config.Variables.SetValueAsync(
"Version", Assembly.GetExecutingAssembly().GetName().Version.ToString());
foreach (var key in OnlineDefaultKeys)
@@ -358,7 +230,7 @@ public class Program
}
catch (Exception ex)
{
Functions.WriteErrFile(ex.Message);
Logger.WriteErrFile(ex.Message);
}
}
@@ -386,23 +258,68 @@ public class Program
break;
}
if (Functions.GetOperatingSystem() == OperatingSystem.WINDOWS)
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)
Utilities.WriteColorText(item);
Logger.WriteLine("Do you want to update the bot ? (y/n)");
if (Console.ReadKey().Key == ConsoleKey.Y)
{
var url =
$"https://github.com/Wizzy69/SethDiscordBot/releases/download/v{newVersion}/net6.0.zip";
Process.Start(".\\Updater\\Updater.exe",
$"{newVersion} {url} {Process.GetCurrentProcess().ProcessName}");
}
else
{
var url =
$"https://github.com/Wizzy69/SethDiscordBot/releases/download/v{newVersion}/net6.0_linux.zip";
Settings.Variables.outputStream.WriteLine("Downloading update ...");
await ServerCom.DownloadFileNoProgressAsync(url, "./update.zip");
await File.WriteAllTextAsync("Install.sh",
"#!/bin/bash\nunzip -qq update.zip -d ./\nrm update.zip\nchmod +x SethDiscordBot\n./DiscordBot");
Process.Start("Install.sh").WaitForExit();
Environment.Exit(0);
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}% "); }));
await File.WriteAllTextAsync("Install.sh",
"#!/bin/bash\nunzip -qq -o update.zip \nrm update.zip\nchmod a+x DiscordBot");
Logger.WriteLine();
try
{
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}");
}
}
}
@@ -415,20 +332,19 @@ public class Program
if (!await Config.Variables.ExistsAsync("UpdaterVersion"))
await Config.Variables.AddAsync("UpdaterVersion", "0.0.0.0", false);
if (await Config.Variables.GetValueAsync("UpdaterVersion") != updaternewversion ||
!Directory.Exists("./Updater") ||
!File.Exists("./Updater/Updater.exe"))
!File.Exists(Functions.dataFolder+"Applications/Updater.exe"))
{
Console.Clear();
Settings.Variables.outputStream.WriteLine("Installing updater ...\nDo NOT close the bot during update !");
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.zip",
"./Updater.zip");
await Functions.ExtractArchive("./Updater.zip", "./", null,
UnzipProgressType.PercentageFromTotalSize);
"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");
// File.Delete("Updater.zip");
bar.Stop("Updater has been updated !");
Console.Clear();
}
@@ -436,6 +352,149 @@ public class Program
break;
}
}
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

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

@@ -120,6 +120,9 @@ public static class Config
throw new Exception("Config is not loaded");
if (Exists(VarName))
{
if (GetValue(VarName) == Value)
return;
SetValue(VarName, Value);
SetReadOnly(VarName, ReadOnly);
return;

View File

@@ -2,6 +2,7 @@
using System.Data.SQLite;
using System.IO;
using System.Threading.Tasks;
namespace PluginManager.Database
{
public class SqlDatabase
@@ -11,12 +12,15 @@ namespace PluginManager.Database
public SqlDatabase(string fileName)
{
if (!fileName.StartsWith("./Data/Resources/"))
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();
@@ -26,7 +30,6 @@ namespace PluginManager.Database
public async Task InsertAsync(string tableName, params string[] values)
{
string query = $"INSERT INTO {tableName} VALUES (";
for (int i = 0; i < values.Length; i++)
{
@@ -34,6 +37,7 @@ namespace PluginManager.Database
if (i != values.Length - 1)
query += ", ";
}
query += ")";
SQLiteCommand command = new SQLiteCommand(query, Connection);
@@ -42,7 +46,6 @@ namespace PluginManager.Database
public void Insert(string tableName, params string[] values)
{
string query = $"INSERT INTO {tableName} VALUES (";
for (int i = 0; i < values.Length; i++)
{
@@ -50,34 +53,27 @@ namespace PluginManager.Database
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();
}
@@ -99,19 +95,21 @@ namespace PluginManager.Database
return true;
return false;
}
public async Task SetValueAsync(string tableName, string keyName, string KeyValue, string ResultColumnName, string ResultColumnValue)
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}'");
await ExecuteAsync(
$"UPDATE {tableName} SET {ResultColumnName}='{ResultColumnValue}' WHERE {keyName}='{KeyValue}'");
}
public void SetValue(string tableName, string keyName, string KeyValue, string ResultColumnName, string ResultColumnValue)
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");
@@ -120,7 +118,8 @@ namespace PluginManager.Database
}
public async Task<string> GetValueAsync(string tableName, string keyName, string KeyValue, string ResultColumnName)
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");
@@ -128,7 +127,7 @@ namespace PluginManager.Database
return await ReadDataAsync($"SELECT {ResultColumnName} FROM {tableName} WHERE {keyName}='{KeyValue}'");
}
public string GetValue(string tableName, string keyName, string KeyValue, string ResultColumnName)
public string? GetValue(string tableName, string keyName, string KeyValue, string ResultColumnName)
{
if (!TableExists(tableName))
throw new System.Exception($"Table {tableName} does not exist");
@@ -143,7 +142,6 @@ namespace PluginManager.Database
public async Task AddColumnsToTableAsync(string tableName, string[] columns)
{
var command = Connection.CreateCommand();
command.CommandText = $"SELECT * FROM {tableName}";
var reader = await command.ExecuteReaderAsync();
@@ -163,7 +161,6 @@ namespace PluginManager.Database
public void AddColumnsToTable(string tableName, string[] columns)
{
var command = Connection.CreateCommand();
command.CommandText = $"SELECT * FROM {tableName}";
var reader = command.ExecuteReader();
@@ -179,12 +176,10 @@ namespace PluginManager.Database
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();
@@ -196,7 +191,6 @@ namespace PluginManager.Database
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();
@@ -208,20 +202,16 @@ namespace PluginManager.Database
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)
@@ -243,7 +233,7 @@ namespace PluginManager.Database
return r;
}
public async Task<string> ReadDataAsync(string query)
public async Task<string?> ReadDataAsync(string query)
{
if (!Connection.State.HasFlag(System.Data.ConnectionState.Open))
await Connection.OpenAsync();
@@ -256,10 +246,11 @@ namespace PluginManager.Database
reader.GetValues(values);
return string.Join<object>(" ", values);
}
return null;
}
public string ReadData(string query)
public string? ReadData(string query)
{
if (!Connection.State.HasFlag(System.Data.ConnectionState.Open))
Connection.Open();
@@ -272,10 +263,11 @@ namespace PluginManager.Database
reader.GetValues(values);
return string.Join<object>(" ", values);
}
return null;
}
public async Task<object[]> ReadDataArrayAsync(string query)
public async Task<object[]?> ReadDataArrayAsync(string query)
{
if (!Connection.State.HasFlag(System.Data.ConnectionState.Open))
await Connection.OpenAsync();
@@ -288,10 +280,34 @@ namespace PluginManager.Database
reader.GetValues(values);
return values;
}
return null;
}
public object[] ReadDataArray(string query)
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();
@@ -304,6 +320,7 @@ namespace PluginManager.Database
reader.GetValues(values);
return values;
}
return null;
}
}

View File

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

View File

@@ -1,50 +1,14 @@
using System;
using System.Collections.Generic;
using Discord.Commands;
using Discord.WebSocket;
namespace PluginManager.Items;
public class Command
{
/// <summary>
/// The author of the command
/// </summary>
public SocketUser? Author;
/// <summary>
/// The Command class contructor
/// </summary>
/// <param name="message">The message that was sent</param>
public Command(SocketMessage message)
{
Author = message.Author;
var data = message.Content.Split(' ');
Arguments = data.Length > 1 ? new List<string>(string.Join(' ', data, 1, data.Length - 1).Split(' ')) : new List<string>();
CommandName = data[0].Substring(1);
PrefixUsed = data[0][0];
}
/// <summary>
/// The list of arguments
/// </summary>
public List<string> Arguments { get; }
/// <summary>
/// The command that is executed
/// </summary>
public string CommandName { get; }
/// <summary>
/// The prefix that is used for the command
/// </summary>
public char PrefixUsed { get; }
}
public class ConsoleCommand
{
public string CommandName { get; init; }
public string Description { get; init; }
public string Usage { get; init; }
public Action<string[]> Action { get; init; }
public string? CommandName { get; init; }
public string? Description { get; init; }
public string? Usage { get; init; }
public Action<string[]>? Action { get; init; }
}

View File

@@ -9,7 +9,6 @@ using System.Threading.Tasks;
using Discord.WebSocket;
using PluginManager.Interfaces;
using PluginManager.Loaders;
using PluginManager.Online;
using PluginManager.Others;
@@ -32,11 +31,12 @@ public class ConsoleCommandsHandler
public ConsoleCommandsHandler(DiscordSocketClient client)
{
if (!Logger.isConsole) throw new Exception("Can not use ConsoleCommandsHandler for Non console apps");
this.client = client;
InitializeBasicCommands();
//Settings.Variables.outputStream.WriteLine("Initialized console command handler !");
//Logger.WriteLine("Initialized console command handler !");
}
private void InitializeBasicCommands()
@@ -47,7 +47,7 @@ public class ConsoleCommandsHandler
{
if (args.Length <= 1)
{
Settings.Variables.outputStream.WriteLine("Available commands:");
Logger.WriteLine("Available commands:");
var items = new List<string[]>();
items.Add(new[] { "-", "-", "-" });
items.Add(new[] { "Command", "Description", "Usage" });
@@ -56,10 +56,8 @@ public class ConsoleCommandsHandler
foreach (var command in commandList)
{
var pa = from p in command.Action.Method.GetParameters()
where p.Name != null
select p.ParameterType.FullName;
items.Add(new[] { command.CommandName, command.Description, command.Usage });
if (!command.CommandName.StartsWith("_"))
items.Add(new[] { command.CommandName, command.Description, command.Usage });
}
items.Add(new[] { "-", "-", "-" });
@@ -70,12 +68,12 @@ public class ConsoleCommandsHandler
foreach (var command in commandList)
if (command.CommandName == args[1])
{
Settings.Variables.outputStream.WriteLine("Command description: " + command.Description);
Settings.Variables.outputStream.WriteLine("Command execution format:" + command.Usage);
Logger.WriteLine("Command description: " + command.Description);
Logger.WriteLine("Command execution format:" + command.Usage);
return;
}
Settings.Variables.outputStream.WriteLine("Command not found");
Logger.WriteLine("Command not found");
}
}
);
@@ -94,16 +92,16 @@ public class ConsoleCommandsHandler
if (success)
{
Console.ForegroundColor = ConsoleColor.Green;
Settings.Variables.outputStream.WriteLine("[CMD] Successfully loaded command : " + name);
Logger.WriteLine("[CMD] Successfully loaded command : " + name);
}
else
{
Console.ForegroundColor = ConsoleColor.Red;
if (exception is null)
Settings.Variables.outputStream.WriteLine("An error occured while loading: " + name);
Logger.WriteLine("An error occured while loading: " + name);
else
Settings.Variables.outputStream.WriteLine("[CMD] Failed to load command : " + name + " because " + exception!.Message);
Logger.WriteLine("[CMD] Failed to load command : " + name + " because " + exception!.Message);
}
Console.ForegroundColor = cc;
@@ -116,12 +114,12 @@ public class ConsoleCommandsHandler
if (success)
{
Console.ForegroundColor = ConsoleColor.Green;
Settings.Variables.outputStream.WriteLine("[EVENT] Successfully loaded event : " + name);
Logger.WriteLine("[EVENT] Successfully loaded event : " + name);
}
else
{
Console.ForegroundColor = ConsoleColor.Red;
Settings.Variables.outputStream.WriteLine("[EVENT] Failed to load event : " + name + " because " + exception!.Message);
Logger.WriteLine("[EVENT] Failed to load event : " + name + " because " + exception!.Message);
}
Console.ForegroundColor = cc;
@@ -135,12 +133,12 @@ public class ConsoleCommandsHandler
if (success)
{
Console.ForegroundColor = ConsoleColor.Green;
Settings.Variables.outputStream.WriteLine("[SLASH] Successfully loaded command : " + name);
Logger.WriteLine("[SLASH] Successfully loaded command : " + name);
}
else
{
Console.ForegroundColor = ConsoleColor.Red;
Settings.Variables.outputStream.WriteLine("[SLASH] Failed to load command : " + name + " because " + exception!.Message);
Logger.WriteLine("[SLASH] Failed to load command : " + name + " because " + exception!.Message);
}
Console.ForegroundColor = cc;
@@ -160,7 +158,7 @@ public class ConsoleCommandsHandler
if (args.Length == 1)
{
isDownloading = false;
Settings.Variables.outputStream.WriteLine("Please specify plugin name");
Logger.WriteLine("Please specify plugin name");
return;
}
@@ -203,13 +201,13 @@ public class ConsoleCommandsHandler
}
Settings.Variables.outputStream.WriteLine("\n");
Logger.WriteLine("\n");
// check requirements if any
if (info.Length == 3 && info[2] != string.Empty && info[2] != null)
{
Settings.Variables.outputStream.WriteLine($"Downloading requirements for plugin : {name}");
Logger.WriteLine($"Downloading requirements for plugin : {name}");
var lines = await ServerCom.ReadTextFromURL(info[2]);
@@ -218,7 +216,7 @@ public class ConsoleCommandsHandler
if (!(line.Length > 0 && line.Contains(",")))
continue;
var split = line.Split(',');
Settings.Variables.outputStream.WriteLine($"\nDownloading item: {split[1]}");
Logger.WriteLine($"\nDownloading item: {split[1]}");
if (File.Exists("./" + split[1])) File.Delete("./" + split[1]);
if (OperatingSystem.WINDOWS == Functions.GetOperatingSystem())
{
@@ -232,26 +230,26 @@ public class ConsoleCommandsHandler
bar.Stop("Item downloaded !");
}
Settings.Variables.outputStream.WriteLine();
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"))
{
Settings.Variables.outputStream.WriteLine($"Extracting {split[1]} ...");
Logger.WriteLine($"Extracting {split[1]} ...");
var bar = new Utilities.ProgressBar(
ProgressBarType.NO_END);
bar.Start();
await Functions.ExtractArchive("./" + split[1], "./", null,
await ArchiveManager.ExtractArchive("./" + split[1], "./", null,
UnzipProgressType.PercentageFromTotalSize);
bar.Stop("Extracted");
Settings.Variables.outputStream.WriteLine("\n");
Logger.WriteLine("\n");
File.Delete("./" + split[1]);
}
}
Settings.Variables.outputStream.WriteLine();
Logger.WriteLine();
}
var ver = await ServerCom.GetVersionOfPackageFromWeb(name);
@@ -259,6 +257,8 @@ public class ConsoleCommandsHandler
await Config.Plugins.SetVersionAsync(name, ver);
isDownloading = false;
await ExecuteCommad("localload " + name);
}
);
@@ -271,7 +271,7 @@ public class ConsoleCommandsHandler
return;
var data = Config.Variables.GetValue(args[1]);
Settings.Variables.outputStream.WriteLine($"{args[1]} => {data}");
Logger.WriteLine($"{args[1]} => {data}");
}
);
@@ -286,11 +286,11 @@ public class ConsoleCommandsHandler
try
{
Config.Variables.Add(key, value, isReadOnly);
Settings.Variables.outputStream.WriteLine($"Updated config file with the following command: {args[1]} => {value}");
Logger.WriteLine($"Updated config file with the following command: {args[1]} => {value}");
}
catch (Exception ex)
{
Settings.Variables.outputStream.WriteLine(ex.ToString());
Logger.WriteLine(ex.ToString());
}
}
);
@@ -307,15 +307,10 @@ public class ConsoleCommandsHandler
{
if (client is null)
return;
var bar = new Utilities.ProgressBar(ProgressBarType.NO_END);
bar.Start();
bar.Stop("Saved config !");
Settings.Variables.outputStream.WriteLine();
Settings.sqlDatabase.Stop();
await client.StopAsync();
await client.DisposeAsync();
await Task.Delay(1000);
Environment.Exit(0);
}
@@ -327,31 +322,40 @@ public class ConsoleCommandsHandler
try
{
var pName = string.Join(' ', args, 1, args.Length - 1);
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());
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);
}
var types = asmb.GetTypes();
foreach (var type in types)
if (type.IsClass && typeof(DBEvent).IsAssignableFrom(type))
{
var instance = (DBEvent)Activator.CreateInstance(type);
instance.Start(this.client);
Settings.Variables.outputStream.WriteLine($"[EVENT] Loaded external {type.FullName}!");
}
else if (type.IsClass && typeof(DBCommand).IsAssignableFrom(type))
{
var instance = (DBCommand)Activator.CreateInstance(type);
Settings.Variables.outputStream.WriteLine($"[CMD] Instance: {type.FullName} loaded !");
}
}
catch (Exception ex)
{
Settings.Variables.outputStream.WriteLine(ex.Message);
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);
}
});
@@ -385,13 +389,13 @@ public class ConsoleCommandsHandler
if (!File.Exists(location))
{
Settings.Variables.outputStream.WriteLine("The plugin does not exist");
Logger.WriteLine("The plugin does not exist");
return;
}
File.Delete(location);
Settings.Variables.outputStream.WriteLine("Removed the plugin DLL. Checking for other files ...");
Logger.WriteLine("Removed the plugin DLL. Checking for other files ...");
var info = await manager.GetPluginLinkByName(plugName);
if (info[2] != string.Empty)
@@ -406,7 +410,7 @@ public class ConsoleCommandsHandler
File.Delete("./" + split[1]);
Settings.Variables.outputStream.WriteLine("Removed: " + split[1]);
Logger.WriteLine("Removed: " + split[1]);
}
if (Directory.Exists($"./Data/Plugins/{plugName}"))
@@ -417,11 +421,12 @@ public class ConsoleCommandsHandler
}
isDownloading = false;
Settings.Variables.outputStream.WriteLine(plugName + " has been successfully deleted !");
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");
@@ -429,8 +434,8 @@ public class ConsoleCommandsHandler
}
else
{
Process.Start("./DiscordBot", "lp");
HandleCommand("sd");
//HandleCommand("sd");
Console.WriteLine("This command can not be used outside of Windows yet. Please restart the bot using the manual way");
}
});
@@ -468,8 +473,24 @@ public class ConsoleCommandsHandler
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])
@@ -481,26 +502,32 @@ public class ConsoleCommandsHandler
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 (removeCommandExecution)
{
Console.SetCursorPosition(0, Console.CursorTop - 1);
for (var i = 0; i < command.Length + 30; i++)
Settings.Variables.outputStream.Write(" ");
Console.SetCursorPosition(0, Console.CursorTop);
}
if (args[0].StartsWith("_"))
throw new Exception("This command is reserved for internal worker and can not be executed manually !");
Settings.Variables.outputStream.WriteLine();
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;
//Settings.Variables.outputStream.WriteLine($"Executing: {args[0]} with the following parameters: {args.MergeStrings(1)}");
//Logger.WriteLine($"Executing: {args[0]} with the following parameters: {args.MergeStrings(1)}");
}
}

View File

@@ -4,8 +4,6 @@ using System.IO;
using System.Linq;
using System.Reflection;
using PluginManager.Others;
namespace PluginManager.Loaders;
internal class LoaderArgs : EventArgs
@@ -102,7 +100,7 @@ internal class Loader<T>
}
catch (Exception ex)
{
Functions.WriteErrFile(ex.ToString());
Logger.WriteErrFile(ex.ToString());
}

View File

@@ -5,7 +5,6 @@ using System.Linq;
using System.Reflection;
using PluginManager.Interfaces;
using PluginManager.Others;
namespace PluginManager.Loaders
{
@@ -47,7 +46,17 @@ namespace PluginManager.Loaders
var files = Directory.GetFiles(path, $"*.{extension}", SearchOption.AllDirectories);
foreach (var file in files)
{
Assembly.LoadFrom(file);
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
@@ -116,7 +125,7 @@ namespace PluginManager.Loaders
}
catch (Exception ex)
{
Functions.WriteErrFile(ex.ToString());
Logger.WriteErrFile(ex.ToString());
return null;
}

View File

@@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Threading.Tasks;
using Discord;
@@ -9,7 +10,6 @@ using Discord.WebSocket;
using PluginManager.Interfaces;
using PluginManager.Online;
using PluginManager.Online.Updates;
using PluginManager.Others;
namespace PluginManager.Loaders;
@@ -94,11 +94,11 @@ public class PluginLoader
Events = new List<DBEvent>();
SlashCommands = new List<DBSlashCommand>();
Functions.WriteLogFile("Starting plugin loader ... Client: " + _client.CurrentUser.Username);
Settings.Variables.outputStream.WriteLine("Loading plugins");
Logger.WriteLogFile("Starting plugin loader ... Client: " + _client.CurrentUser.Username);
Logger.WriteLine("Loading plugins");
var loader = new LoaderV2("./Data/Plugins", "dll");
loader.FileLoaded += (args) => Functions.WriteLogFile($"{args.PluginName} file Loaded");
loader.FileLoaded += (args) => Logger.WriteLogFile($"{args.PluginName} file Loaded");
loader.PluginLoaded += Loader_PluginLoaded;
var res = loader.Load();
Events = res.Item1;
@@ -108,7 +108,7 @@ public class PluginLoader
private async void Loader_PluginLoaded(LoaderArgs args)
{
// Settings.Variables.outputStream.WriteLine(args.TypeName);
switch (args.TypeName)
{
case "DBCommand":
@@ -124,10 +124,10 @@ public class PluginLoader
}
catch (Exception ex)
{
Settings.Variables.outputStream.WriteLine(ex.ToString());
Settings.Variables.outputStream.WriteLine("Plugin: " + args.PluginName);
Settings.Variables.outputStream.WriteLine("Type: " + args.TypeName);
Settings.Variables.outputStream.WriteLine("IsLoaded: " + args.IsLoaded);
Logger.WriteLine(ex.ToString());
Logger.WriteLine("Plugin: " + args.PluginName);
Logger.WriteLine("Type: " + args.TypeName);
Logger.WriteLine("IsLoaded: " + args.IsLoaded);
}
break;
case "DBSlashCommand":
@@ -139,7 +139,7 @@ public class PluginLoader
builder.WithDescription(slash.Description);
builder.WithDMPermission(slash.canUseDM);
builder.Options = slash.Options;
//Settings.Variables.outputStream.WriteLine("Loaded " + slash.Name);
onSLSHLoad?.Invoke(((DBSlashCommand)args.Plugin!).Name, args.TypeName, args.IsLoaded, args.Exception);
await _client.CreateGlobalApplicationCommandAsync(builder.Build());
@@ -148,4 +148,36 @@ public class PluginLoader
break;
}
}
public static async Task LoadPluginFromAssembly(Assembly asmb, DiscordSocketClient client)
{
var types = asmb.GetTypes();
foreach (var type in types)
if (type.IsClass && typeof(DBEvent).IsAssignableFrom(type))
{
var instance = (DBEvent)Activator.CreateInstance(type);
instance.Start(client);
PluginLoader.Events.Add(instance);
Logger.WriteLine($"[EVENT] Loaded external {type.FullName}!");
}
else if (type.IsClass && typeof(DBCommand).IsAssignableFrom(type))
{
var instance = (DBCommand)Activator.CreateInstance(type);
PluginLoader.Commands.Add(instance);
Logger.WriteLine($"[CMD] Instance: {type.FullName} loaded !");
}
else if (type.IsClass && typeof(DBSlashCommand).IsAssignableFrom(type))
{
var instance = (DBSlashCommand)Activator.CreateInstance(type);
SlashCommandBuilder builder = new SlashCommandBuilder();
builder.WithName(instance.Name);
builder.WithDescription(instance.Description);
builder.WithDMPermission(instance.canUseDM);
builder.Options = instance.Options;
await client.CreateGlobalApplicationCommandAsync(builder.Build());
PluginLoader.SlashCommands.Add(instance);
Logger.WriteLine($"[SLASH] Instance: {type.FullName} loaded !");
}
}
}

131
PluginManager/Logger.cs Normal file
View File

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

View File

@@ -84,8 +84,8 @@ public class PluginsManager
}
catch (Exception exception)
{
Settings.Variables.outputStream.WriteLine("Failed to execute command: listplugs\nReason: " + exception.Message);
Functions.WriteErrFile(exception.ToString());
Logger.WriteLine("Failed to execute command: listplugs\nReason: " + exception.Message);
Logger.WriteErrFile(exception.ToString());
}
}
@@ -116,8 +116,8 @@ public class PluginsManager
}
catch (Exception exception)
{
Settings.Variables.outputStream.WriteLine("Failed to execute command: listplugs\nReason: " + exception.Message);
Functions.WriteErrFile(exception.ToString());
Logger.WriteLine("Failed to execute command: listplugs\nReason: " + exception.Message);
Logger.WriteErrFile(exception.ToString());
}
return new string[] { null!, null!, null! };

View File

@@ -1,10 +1,10 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
using PluginManager.Online.Helpers;
using PluginManager.Others;

View File

@@ -1,5 +1,7 @@
using System;
using System.Threading.Tasks;
using System.Collections.Generic;
using PluginManager.Items;
using PluginManager.Others;
@@ -11,7 +13,7 @@ public class PluginUpdater
{
try
{
var webV = await ServerCom.GetVersionOfPackageFromWeb(pakName);
var webV = await ServerCom.GetVersionOfPackageFromWeb(pakName);
var local = ServerCom.GetVersionOfPackage(pakName);
if (local is null) return true;
@@ -22,30 +24,29 @@ public class PluginUpdater
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Logger.LogError(ex);
}
return false;
}
public static async Task<Update> DownloadUpdateInfo(string pakName)
public static async Task<List<string>> GetInfo(string pakName)
{
var url = "https://raw.githubusercontent.com/Wizzy69/installer/discord-bot-files/Versions";
var info = await ServerCom.ReadTextFromURL(url);
var version = await ServerCom.GetVersionOfPackageFromWeb(pakName);
if (version is null) return Update.Empty;
var update = new Update(pakName, string.Join('\n', info), version);
return update;
}
public static async Task Download(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

@@ -1,34 +0,0 @@
using System;
using PluginManager.Online.Helpers;
namespace PluginManager.Online.Updates;
public class Update
{
public static Update Empty = new(null, null, null);
private readonly bool isEmpty;
public VersionString newVersion;
public string pakName;
public string UpdateMessage;
public Update(string pakName, string updateMessage, VersionString newVersion)
{
this.pakName = pakName;
UpdateMessage = updateMessage;
this.newVersion = newVersion;
if (pakName is null && updateMessage is null && newVersion is null)
isEmpty = true;
}
public override string ToString()
{
if (isEmpty)
throw new Exception("The update is EMPTY. Can not print information about an empty update !");
return $"Package Name: {pakName}\n" +
$"Update Message: {UpdateMessage}\n" +
$"Version: {newVersion}";
}
}

View File

@@ -0,0 +1,139 @@
using System;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Threading.Tasks;
namespace PluginManager.Others
{
public static class ArchiveManager
{
public static bool isInitialized { get; private set; }
private static string archiveFolder;
public static void Initialize()
{
if (isInitialized) throw new Exception("ArchiveManager is already initialized");
if (!Config.Variables.Exists("ArchiveFolder"))
Config.Variables.Add("ArchiveFolder", "./Data/PAKS/");
isInitialized = true;
archiveFolder = Config.Variables.GetValue("ArchiveFolder");
}
/// <summary>
/// Read data from a file that is inside an archive (ZIP format)
/// </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
{
string textValue = null;
using (var fs = new FileStream(archFile, FileMode.Open))
using (var zip = new ZipArchive(fs, ZipArchiveMode.Read))
{
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));
continue;
}
try
{
entry.ExtractToFile(Path.Combine(folder, entry.FullName), true);
currentSize += (ulong)entry.CompressedLength;
}
catch (Exception ex)
{
Logger.WriteLine($"Failed to extract {entry.Name}. Exception: {ex.Message}");
}
await Task.Delay(10);
if (progress != null)
progress.Report((float)currentSize / zipSize * 100);
}
}
}
}
}
}

View File

@@ -1,60 +0,0 @@
using System.Threading.Tasks;
using Discord;
namespace PluginManager.Others;
/// <summary>
/// A class that handles the sending of messages to the user.
/// </summary>
public static class ChannelManagement
{
/// <summary>
/// Get the text channel by name from server
/// </summary>
/// <param name="server">The server</param>
/// <param name="name">The channel name</param>
/// <returns>
/// <see cref="IGuildChannel" />
/// </returns>
public static IGuildChannel GetTextChannel(this IGuild server, string name)
{
return server.GetTextChannel(name);
}
/// <summary>
/// Get the voice channel by name from server
/// </summary>
/// <param name="server">The server</param>
/// <param name="name">The channel name</param>
/// <returns>
/// <see cref="IGuildChannel" />
/// </returns>
public static IGuildChannel GetVoiceChannel(this IGuild server, string name)
{
return server.GetVoiceChannel(name);
}
/// <summary>
/// Get the DM channel between <see cref="Discord.WebSocket.DiscordSocketClient" /> and <see cref="IGuildUser" />
/// </summary>
/// <param name="user"></param>
/// <returns>
/// <see cref="IDMChannel" />
/// </returns>
public static async Task<IDMChannel> GetDMChannel(IGuildUser user)
{
return await user.CreateDMChannelAsync();
}
/// <summary>
/// Get the channel where the message was sent
/// </summary>
/// <param name="message">The message</param>
/// <returns>
/// <see cref="IChannel" />
/// </returns>
public static IChannel GetChannel(IMessage message)
{
return message.Channel;
}
}

View File

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

@@ -46,38 +46,38 @@ public static class Utilities
foreach (var row in data)
{
if (row[0][0] == tableLine)
Settings.Variables.outputStream.Write(tableCross);
Logger.Write(tableCross);
else
Settings.Variables.outputStream.Write(tableWall);
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)
Settings.Variables.outputStream.Write(tableLine);
Logger.Write(tableLine);
}
else if (row[l].Length == len[l])
{
Settings.Variables.outputStream.Write(" ");
Settings.Variables.outputStream.Write(row[l]);
Settings.Variables.outputStream.Write(" ");
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)
Settings.Variables.outputStream.Write(" ");
Settings.Variables.outputStream.Write(row[l]);
Logger.Write(" ");
Logger.Write(row[l]);
for (var i = (len[l] + 4) / 2 + lenHalf + 1; i < len[l] + 4; ++i)
Settings.Variables.outputStream.Write(" ");
Logger.Write(" ");
if (row[l].Length % 2 == 0)
Settings.Variables.outputStream.Write(" ");
Logger.Write(" ");
}
Settings.Variables.outputStream.Write(row[l][0] == tableLine ? tableCross : tableWall);
Logger.Write(row[l][0] == tableLine ? tableCross : tableWall);
}
Settings.Variables.outputStream.WriteLine(); //end line
Logger.WriteLine(); //end line
}
return;
@@ -95,44 +95,44 @@ public static class Utilities
foreach (var row in data)
{
Settings.Variables.outputStream.Write("\t");
Logger.Write("\t");
if (row[0] == "-")
Settings.Variables.outputStream.Write("+");
Logger.Write("+");
else
Settings.Variables.outputStream.Write("|");
Logger.Write("|");
foreach (var s in row)
{
if (s == "-")
{
for (var i = 0; i < maxLen + 4; ++i)
Settings.Variables.outputStream.Write("-");
Logger.Write("-");
}
else if (s.Length == maxLen)
{
Settings.Variables.outputStream.Write(" ");
Settings.Variables.outputStream.Write(s);
Settings.Variables.outputStream.Write(" ");
Logger.Write(" ");
Logger.Write(s);
Logger.Write(" ");
}
else
{
var lenHalf = s.Length / 2;
for (var i = 0; i < div - lenHalf; ++i)
Settings.Variables.outputStream.Write(" ");
Settings.Variables.outputStream.Write(s);
Logger.Write(" ");
Logger.Write(s);
for (var i = div + lenHalf + 1; i < maxLen + 4; ++i)
Settings.Variables.outputStream.Write(" ");
Logger.Write(" ");
if (s.Length % 2 == 0)
Settings.Variables.outputStream.Write(" ");
Logger.Write(" ");
}
if (s == "-")
Settings.Variables.outputStream.Write("+");
Logger.Write("+");
else
Settings.Variables.outputStream.Write("|");
Logger.Write("|");
}
Settings.Variables.outputStream.WriteLine(); //end line
Logger.WriteLine(); //end line
}
return;
@@ -153,12 +153,12 @@ public static class Utilities
{
if (data[i][j] == "-")
data[i][j] = " ";
Settings.Variables.outputStream.Write(data[i][j]);
Logger.Write(data[i][j]);
for (var k = 0; k < widths[j] - data[i][j].Length + 1 + space_between_columns; k++)
Settings.Variables.outputStream.Write(" ");
Logger.Write(" ");
}
Settings.Variables.outputStream.WriteLine();
Logger.WriteLine();
}
return;
@@ -169,12 +169,15 @@ public static class Utilities
public static void WriteColorText(string text, bool appendNewLineAtEnd = true)
{
if (Console.Out != Settings.Variables.outputStream)
if (!Logger.isConsole)
{
Settings.Variables.outputStream.Write(text);
foreach (var item in Colors)
text = text.Replace($"{ColorPrefix}{item.Key}", "").Replace("&c", "");
Logger.Write(text);
if (appendNewLineAtEnd)
Settings.Variables.outputStream.WriteLine();
Logger.WriteLine();
return;
}
var initialForeGround = Console.ForegroundColor;
var input = text.ToCharArray();
@@ -197,12 +200,12 @@ public static class Utilities
}
else
{
Settings.Variables.outputStream.Write(input[i]);
Logger.Write(input[i]);
}
Console.ForegroundColor = initialForeGround;
if (appendNewLineAtEnd)
Settings.Variables.outputStream.WriteLine();
Logger.WriteLine();
}
@@ -219,7 +222,7 @@ public static class Utilities
public ProgressBar(ProgressBarType type)
{
if (Settings.Variables.outputStream != Console.Out)
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;
}
@@ -281,9 +284,9 @@ public static class Utilities
{
Console.CursorLeft = 0;
for (var i = 0; i < BarLength + message.Length + 1; i++)
Settings.Variables.outputStream.Write(" ");
Logger.Write(" ");
Console.CursorLeft = 0;
Settings.Variables.outputStream.WriteLine(message);
Logger.WriteLine(message);
}
}
@@ -298,14 +301,14 @@ public static class Utilities
private void UpdateNoEnd(string message)
{
Console.CursorLeft = 0;
Settings.Variables.outputStream.Write("[");
Logger.Write("[");
for (var i = 1; i <= position; i++)
Settings.Variables.outputStream.Write(" ");
Settings.Variables.outputStream.Write("<==()==>");
Logger.Write(" ");
Logger.Write("<==()==>");
position += positive ? 1 : -1;
for (var i = position; i <= BarLength - 1 - (positive ? 0 : 2); i++)
Settings.Variables.outputStream.Write(" ");
Settings.Variables.outputStream.Write("] " + message);
Logger.Write(" ");
Logger.Write("] " + message);
if (position == BarLength - 1 || position == 1)
@@ -315,14 +318,14 @@ public static class Utilities
private void UpdateNoEnd()
{
Console.CursorLeft = 0;
Settings.Variables.outputStream.Write("[");
Logger.Write("[");
for (var i = 1; i <= position; i++)
Settings.Variables.outputStream.Write(" ");
Settings.Variables.outputStream.Write("<==()==>");
Logger.Write(" ");
Logger.Write("<==()==>");
position += positive ? 1 : -1;
for (var i = position; i <= BarLength - 1 - (positive ? 0 : 2); i++)
Settings.Variables.outputStream.Write(" ");
Settings.Variables.outputStream.Write("]");
Logger.Write(" ");
Logger.Write("]");
if (position == BarLength - 1 || position == 1)
@@ -332,9 +335,9 @@ public static class Utilities
private void UpdateNormal(float progress)
{
Console.CursorLeft = 0;
Settings.Variables.outputStream.Write("[");
Logger.Write("[");
Console.CursorLeft = BarLength;
Settings.Variables.outputStream.Write("]");
Logger.Write("]");
Console.CursorLeft = 1;
var onechunk = 30.0f / Max;
@@ -344,22 +347,22 @@ public static class Utilities
{
Console.BackgroundColor = NoColor ? ConsoleColor.Black : Color;
Console.CursorLeft = position++;
Settings.Variables.outputStream.Write("#");
Logger.Write("#");
}
for (var i = position; i < BarLength; i++)
{
Console.BackgroundColor = NoColor ? ConsoleColor.Black : ConsoleColor.DarkGray;
Console.CursorLeft = position++;
Settings.Variables.outputStream.Write(" ");
Logger.Write(" ");
}
Console.CursorLeft = BarLength + 4;
Console.BackgroundColor = ConsoleColor.Black;
if (progress.CanAproximateTo(Max))
Settings.Variables.outputStream.Write(progress + " % ✓");
Logger.Write(progress + " % ✓");
else
Settings.Variables.outputStream.Write(MathF.Round(progress, 2) + " % ");
Logger.Write(MathF.Round(progress, 2) + " % ");
}
}
}

View File

@@ -1,10 +1,7 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Threading;
@@ -14,6 +11,7 @@ using Discord.WebSocket;
using PluginManager.Items;
namespace PluginManager.Others;
/// <summary>
@@ -26,95 +24,6 @@ public static class Functions
/// </summary>
public static readonly string dataFolder = @"./Data/Resources/";
/// <summary>
/// The location for all logs
/// </summary>
public static readonly string logFolder = @"./Data/Output/Logs/";
/// <summary>
/// The location for all errors
/// </summary>
public static readonly string errFolder = @"./Data/Output/Errors/";
/// <summary>
/// Archives folder
/// </summary>
public static readonly string pakFolder = @"./Data/PAKS/";
/// <summary>
/// Beta testing folder
/// </summary>
public static readonly string betaFolder = @"./Data/BetaTest/";
/// <summary>
/// Read data from a file that is inside an archive (ZIP format)
/// </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)
{
archFile = pakFolder + archFile;
if (!File.Exists(archFile))
throw new Exception("Failed to load file !");
try
{
string textValue = null;
using (var fs = new FileStream(archFile, FileMode.Open))
using (var zip = new ZipArchive(fs, ZipArchiveMode.Read))
{
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>
/// Write logs to file
/// </summary>
/// <param name="LogMessage">The message to be wrote</param>
public static void WriteLogFile(string LogMessage)
{
var logsPath = logFolder + $"{DateTime.Today.ToShortDateString().Replace("/", "-").Replace("\\", "-")} Log.txt";
Directory.CreateDirectory(logFolder);
File.AppendAllText(logsPath, LogMessage + " \n");
}
/// <summary>
/// Write error to file
/// </summary>
/// <param name="ErrMessage">The message to be wrote</param>
public static void WriteErrFile(string ErrMessage)
{
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)
{
WriteErrFile(ex.ToString());
}
/// <summary>
/// Get the Operating system you are runnin on
/// </summary>
@@ -127,12 +36,6 @@ public static class Functions
return OperatingSystem.UNKNOWN;
}
public static List<string> GetArguments(SocketMessage message)
{
var command = new Command(message);
return command.Arguments;
}
/// <summary>
/// Copy one Stream to another <see langword="async" />
/// </summary>
@@ -167,79 +70,6 @@ public static class Functions
}
}
/// <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)
{
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)
{
Settings.Variables.outputStream.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));
continue;
}
try
{
entry.ExtractToFile(Path.Combine(folder, entry.FullName), true);
currentSize += (ulong)entry.CompressedLength;
}
catch (Exception ex)
{
Settings.Variables.outputStream.WriteLine($"Failed to extract {entry.Name}. Exception: {ex.Message}");
}
await Task.Delay(10);
if (progress != null)
progress.Report((float)currentSize / zipSize * 100);
}
}
}
}
/// <summary>
/// Save to JSON file
/// </summary>
@@ -252,6 +82,8 @@ public static class Functions
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>
@@ -269,32 +101,8 @@ public static class Functions
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 bool TryReadValueFromJson(string input, string codeName, out JsonElement element)
{
Stream text;
if (File.Exists(input))
text = File.OpenRead(input);
else
text = new MemoryStream(Encoding.ASCII.GetBytes(input));
var jsonObject = JsonDocument.Parse(text);
var data = jsonObject.RootElement.TryGetProperty(codeName, out element);
return data;
}
public static string CreateMD5(string input)
{
using (var md5 = MD5.Create())
{
var inputBytes = Encoding.ASCII.GetBytes(input);
var hashBytes = md5.ComputeHash(inputBytes);
return Convert.ToHexString(hashBytes);
}
}
}

View File

@@ -1,4 +1,5 @@
using System.Linq;
using Discord;
using Discord.WebSocket;

View File

@@ -16,8 +16,8 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="Discord.Net" Version="3.7.2" />
<PackageReference Include="System.Data.SQLite" Version="1.0.116" />
<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>

View File

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

147
README.md
View File

@@ -15,84 +15,81 @@ This project is based on:
Plugin Types:
1. Commands
2. Events
3. Slash Commands
### How to create a plugin
First of all, Create a new project (class library) in Visual Studio.
![Imgur Image](https://i.imgur.com/KUqzKsB.png)
Then import the PluginManager.dll as project to your project.
![Imgur Image](https://i.imgur.com/JzpEViR.png)
![Imgur Image](https://i.imgur.com/vtoEepX.png)
![Imgur Image](https://i.imgur.com/ceaVR2R.png)
Now, let's add the PluginManager reference. It can be found inside the bot's main folder under
`DiscordBot/bin/Debug/net6.0/PluginManager.dll` or `PluginManager/bin/Debug/net6.0/PluginManager.dll`
after one successfull build.
![Imgur Image](https://i.imgur.com/UMSitk4.png)
![Imgur Image](https://i.imgur.com/GEjShdl.png)
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 plugins that allow users to interact with them.
Here is an example of class that is a command class
Here is an example:
```cs
using Discord;
using Discord.Commands;
using Discord.WebSocket;
using PluginManager.Interfaces;
namespace CMD_Utils
namespace LevelingSystem;
internal class LevelCommand : DBCommand
{
class FlipCoin : DBCommand
public string Command => "level";
public List<string> Aliases => new() { "lvl" };
public string Description => "Display tour current level";
public string Usage => "level";
public bool requireAdmin => false;
public async void ExecuteServer(SocketCommandContext context)
{
public string Command => "flip";
public string Description => "Flip a coin";
public string Usage => "flip";
public bool canUseDM => true;
public bool canUseServer => true;
public bool requireAdmin => false;
public async void Execute(SocketCommandContext context, SocketMessage message, DiscordSocketClient client, bool isDM)
object[] user = await Variables.database.ReadDataArrayAsync($"SELECT * FROM Levels WHERE UserID='{context.Message.Author.Id}'");
if (user is null)
{
System.Random random = new System.Random();
int r = random.Next(1, 3);
if (r == 1)
await message.Channel.SendMessageAsync("Heads");
else await message.Channel.SendMessageAsync("Tails");
await context.Channel.SendMessageAsync("You are now unranked !");
return;
}
int level = (int)user[1];
int exp = (int)user[2];
var builder = new EmbedBuilder();
var r = new Random();
builder.WithColor(r.Next(256), r.Next(256), r.Next(256));
builder.AddField("Current Level", level, true)
.AddField("Current EXP", exp, true)
.AddField("Required Exp", (level * 8 + 24).ToString(), true);
builder.WithTimestamp(DateTimeOffset.Now);
builder.WithAuthor(context.Message.Author.Mention);
await context.Channel.SendMessageAsync(embed: builder.Build());
}
}
```
#### Code description:
- Command - The keyword that triggers the execution for the command. This is what players must type in order to execute your command
- Aliases - The aliases that can be used instead of the full name to execute the command
- Description - The description of your command. Can be anything you like
- Usage - The usage of your command. This is what `help [Command]` command will display
- canUseDM - true if you plan to let users execute this command in DM chat with bot
- canUseServer - true if you plan to let the users execute this command in a server chat
- requireAdmin - true if this command requres an user with Administrator permission in the server
- Execute () - the function of your command.
- ExecuteServer () - the function that is executed only when the command is invoked in a server channel. (optional)
- context - the command context
- ExecuteDM () - the function that is executed only when the command is invoked in a private (DM) channel. (optional)
- context - the command context
- message - the message itself
- client - the discord bot client
- isDM - true if the message was sent from DM chat
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/Commands/<optional subfolder>/yourDLLName.dll`
`{bot_executable}/Data/Plugins/<optional subfolder>/[your dll 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
there is something wrong in your command's code.
2. Events
## 2. Events
Events are loaded when all plugins are loaded. At the moment when they are loaded, the Start function is called.
Events are used if you want the bot to do something when something happens in server. The following example shows you how to catch when a user joins the server
@@ -125,3 +122,61 @@ public class OnUserJoin : DBEvent
- Start() - The main body of your event. This is executed when the bot loads all plugins
- client - the discord bot client
## 3. Slash Commands
Slash commands are server based commands. They work the same way as normal commands, but they require the `/` prefix as they are integrated
with the UI of Discord.
Here is an example:
```cs
using Discord;
using Discord.WebSocket;
using PluginManager.Interfaces;
namespace SlashCommands
{
public class Random : DBSlashCommand
{
public string Name => "random";
public string Description => "Generates a random nunber between 2 values";
public bool canUseDM => true;
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="max-value", Description = "Maximum value", IsRequired=true, Type=ApplicationCommandOptionType.Integer,MinValue = 0, MaxValue = int.MaxValue-1}
};
public async void ExecuteServer(SocketSlashCommand command)
{
var rnd = new System.Random();
var options = command.Data.Options.ToArray();
if (options.Count() != 2)
{
await command.RespondAsync("Invalid parameters", ephemeral: true);
return;
}
Int64 numberOne = (Int64)options[0].Value;
Int64 numberTwo = (Int64)options[1].Value;
await command.RespondAsync("Your generated number is " + rnd.Next((int)numberOne, (int)numberTwo), ephemeral: true);
}
}
}
```
#### Code description:
- Name - the command name (execute with /{Name})
- Description - The description of the command
- canUseDM - true id this command can be activated in DM chat, false otherwise
- Options - the arguments of the command
- ExecuteServer() - this function will be called if the command is invoked in a server channel (optional)
- context - the command context
- ExecuteDM() - this function will be called if the command is invoked in a DM channel (optional)
- context - the command context

View File

@@ -13,6 +13,10 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SlashCommands", "..\Discord
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "LevelingSystem", "..\DiscordBotItems\Plugins\LevelingSystem\LevelingSystem.csproj", "{0138F343-BBB9-4D5F-B499-D9C2978BE9AA}"
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
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@@ -39,6 +43,14 @@ Global
{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
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE