Updated to allow mention as command prefix. Updated DBCommand

This commit is contained in:
2023-01-31 16:07:53 +02:00
parent 22f2cd4e59
commit 4f18f505f4
12 changed files with 299 additions and 342 deletions

View File

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

View File

@@ -1,102 +0,0 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using PluginManager;
using PluginManager.Interfaces;
using PluginManager.Others;
using DiscordLibCommands = Discord.Commands;
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:
Logger.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

@@ -81,6 +81,7 @@ internal class Boot
await client.StartAsync(); await client.StartAsync();
commandServiceHandler = new CommandHandler(client, service, botPrefix); commandServiceHandler = new CommandHandler(client, service, botPrefix);
await commandServiceHandler.InstallCommandsAsync(); await commandServiceHandler.InstallCommandsAsync();
@@ -96,16 +97,25 @@ internal class Boot
client.Log += Log; client.Log += Log;
client.LoggedIn += LoggedIn; client.LoggedIn += LoggedIn;
client.Ready += Ready; 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() private async Task Client_LoggedOut()
{ {
Logger.WriteLine("Successfully Logged Out"); Logger.WriteLine("Successfully Logged Out");
await Log(new LogMessage(LogSeverity.Info, "Boot", "Successfully logged out from discord !")); 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 Task Ready() private Task Ready()

View File

@@ -5,8 +5,9 @@ using System.Threading.Tasks;
using Discord.Commands; using Discord.Commands;
using Discord.WebSocket; using Discord.WebSocket;
using PluginManager.Interfaces;
using PluginManager.Loaders; using PluginManager.Loaders;
using PluginManager.Others;
using PluginManager.Others.Permissions; using PluginManager.Others.Permissions;
using static PluginManager.Logger; using static PluginManager.Logger;
@@ -78,9 +79,12 @@ internal class CommandHandler
/// <returns></returns> /// <returns></returns>
private async Task MessageHandler(SocketMessage Message) private async Task MessageHandler(SocketMessage Message)
{ {
try try
{ {
if (Message.Author.IsBot) return; if (Message.Author.IsBot)
return;
if (Message as SocketUserMessage == null) if (Message as SocketUserMessage == null)
return; return;
@@ -89,41 +93,75 @@ internal class CommandHandler
if (message is null) if (message is null)
return; return;
if (!message.Content.StartsWith(botPrefix))
return;
var argPos = 0; var argPos = 0;
if (message.HasMentionPrefix(client.CurrentUser, ref argPos)) if (!message.Content.StartsWith(botPrefix) && !message.HasMentionPrefix(client.CurrentUser, ref argPos))
{
await message.Channel.SendMessageAsync("Can not exec mentioned commands !");
return; return;
}
var context = new SocketCommandContext(client, message); var context = new SocketCommandContext(client, message);
await commandService.ExecuteAsync(context, argPos, null); await commandService.ExecuteAsync(context, argPos, null);
var plugin = PluginLoader.Commands! DBCommand plugin;
.Where( string cleanMessage = "";
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();
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()) if (plugin.requireAdmin && !context.Message.Author.isAdmin())
return; 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) if (context.Channel is SocketDMChannel)
plugin.ExecuteDM(context); plugin.ExecuteDM(cmd);
else plugin.ExecuteServer(context); else plugin.ExecuteServer(cmd);
} }
catch (Exception ex) catch (Exception ex)
{ {
ex.WriteErrFile(); ex.WriteErrFile();
Console.WriteLine(ex.ToString());
} }
} }
} }

View File

@@ -1,12 +1,16 @@
using System; using PluginManager.Others;
using System;
using System.IO; using System.IO;
using System.Linq;
using System.Reflection; using System.Reflection;
using System.Threading.Tasks;
namespace DiscordBot namespace DiscordBot
{ {
public class Entry public class Entry
{ {
internal static StartupArguments startupArguments;
[STAThread] [STAThread]
public static void Main(string[] args) public static void Main(string[] args)
{ {
@@ -22,7 +26,16 @@ namespace DiscordBot
return assembly; return assembly;
} }
Program.Startup(args); Task.Run(async () => {
if (!File.Exists(Functions.dataFolder + "loader.json"))
{
startupArguments = new StartupArguments();
await Functions.SaveToJsonFile(Functions.dataFolder + "loader.json", startupArguments);
}
else
startupArguments = await Functions.ConvertFromJson<StartupArguments>(Functions.dataFolder + "loader.json");
}).Wait();
Program.Startup(args.Concat(startupArguments.runArgs.Split(' ')).ToArray());
} }
} }

View File

@@ -25,6 +25,7 @@ public class Program
{ {
private static bool loadPluginsOnStartup; private static bool loadPluginsOnStartup;
private static ConsoleCommandsHandler consoleCommandsHandler; private static ConsoleCommandsHandler consoleCommandsHandler;
//private static bool isUI_ON;
/// <summary> /// <summary>
/// The main entry point for the application. /// The main entry point for the application.
@@ -41,147 +42,7 @@ public class Program
Config.Variables.GetValue("prefix")?.Length != 1 || Config.Variables.GetValue("prefix")?.Length != 1 ||
(args.Length == 1 && args[0] == "/reset")) (args.Length == 1 && args[0] == "/reset"))
{ {
Application.Init(); GenerateStartUI("First time setup. Please fill the following with your discord bot data.\nThis are saved ONLY on YOUR computer.");
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();
} }
HandleInput(args).Wait(); HandleInput(args).Wait();
@@ -196,10 +57,10 @@ public class Program
Logger.WriteLine(); Logger.WriteLine();
Logger.WriteLine("Debug mode enabled"); Logger.WriteLine("Debug mode enabled");
Logger.WriteLine(); Logger.WriteLine();
loadPluginsOnStartup = true;
#else
if (loadPluginsOnStartup) consoleCommandsHandler.HandleCommand("lp");
#endif #endif
if (loadPluginsOnStartup)
consoleCommandsHandler.HandleCommand("lp");
while (true) while (true)
{ {
@@ -278,6 +139,8 @@ public class Program
var b = await StartNoGui(); var b = await StartNoGui();
consoleCommandsHandler = new ConsoleCommandsHandler(b.client); consoleCommandsHandler = new ConsoleCommandsHandler(b.client);
if (Entry.startupArguments.loadPluginsAtStartup) { loadPluginsOnStartup = true; }
if (len > 0 && args[0] == "/remplug") if (len > 0 && args[0] == "/remplug")
{ {
var plugName = string.Join(' ', args, 1, args.Length - 1); var plugName = string.Join(' ', args, 1, args.Length - 1);
@@ -286,8 +149,7 @@ public class Program
loadPluginsOnStartup = true; loadPluginsOnStartup = true;
} }
if (len > 0 && args[0] == "/lp")
loadPluginsOnStartup = true;
var mainThread = new Thread(() => var mainThread = new Thread(() =>
{ {
@@ -410,7 +272,7 @@ public class Program
{ {
var url = var url =
$"https://github.com/Wizzy69/SethDiscordBot/releases/download/v{newVersion}/net6.0.zip"; $"https://github.com/Wizzy69/SethDiscordBot/releases/download/v{newVersion}/net6.0.zip";
Process.Start(".\\Updater\\Updater.exe", Process.Start($"{Functions.dataFolder}Applications/Updater.exe",
$"{newVersion} {url} {Process.GetCurrentProcess().ProcessName}"); $"{newVersion} {url} {Process.GetCurrentProcess().ProcessName}");
} }
else else
@@ -461,20 +323,19 @@ public class Program
if (!await Config.Variables.ExistsAsync("UpdaterVersion")) if (!await Config.Variables.ExistsAsync("UpdaterVersion"))
await Config.Variables.AddAsync("UpdaterVersion", "0.0.0.0", false); await Config.Variables.AddAsync("UpdaterVersion", "0.0.0.0", false);
if (await Config.Variables.GetValueAsync("UpdaterVersion") != updaternewversion || if (await Config.Variables.GetValueAsync("UpdaterVersion") != updaternewversion ||
!Directory.Exists("./Updater") || !File.Exists(Functions.dataFolder+"Applications/Updater.exe"))
!File.Exists("./Updater/Updater.exe"))
{ {
Console.Clear(); Console.Clear();
Logger.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); var bar = new Utilities.ProgressBar(ProgressBarType.NO_END);
bar.Start(); bar.Start();
await ServerCom.DownloadFileNoProgressAsync( await ServerCom.DownloadFileNoProgressAsync(
"https://github.com/Wizzy69/installer/releases/download/release-1-discordbot/Updater.zip", "https://github.com/Wizzy69/installer/releases/download/release-1-discordbot/Updater.exe",
"./Updater.zip"); $"{Functions.dataFolder}Applications/Updater.exe");
await ArchiveManager.ExtractArchive("./Updater.zip", "./", null, //await ArchiveManager.ExtractArchive("./Updater.zip", "./", null,
UnzipProgressType.PercentageFromTotalSize); // UnzipProgressType.PercentageFromTotalSize);
await Config.Variables.SetValueAsync("UpdaterVersion", updaternewversion); await Config.Variables.SetValueAsync("UpdaterVersion", updaternewversion);
File.Delete("Updater.zip"); // File.Delete("Updater.zip");
bar.Stop("Updater has been updated !"); bar.Stop("Updater has been updated !");
Console.Clear(); Console.Clear();
} }
@@ -485,4 +346,146 @@ public class Program
Console.Clear(); Console.Clear();
} }
public static void GenerateStartUI(string titleMessage)
{
Application.Init();
var top = Application.Top;
var win = new Window("Discord Bot Config - " + Assembly.GetExecutingAssembly().GetName().Version)
{
X = 0,
Y = 1,
Width = Dim.Fill(),
Height = Dim.Fill()
};
top.Add(win);
var labelInfo = new Label(titleMessage)
{
X = Pos.Center(),
Y = 2
};
var labelToken = new Label("Please insert your token here: ")
{
X = 5,
Y = 5
};
var textFiledToken = new TextField(Config.Variables.GetValue("token") ?? "")
{
X = Pos.Left(labelToken) + labelToken.Text.Length + 2,
Y = labelToken.Y,
Width = 70
};
var labelPrefix = new Label("Please insert your prefix here: ")
{
X = 5,
Y = 8
};
var textFiledPrefix = new TextField(Config.Variables.GetValue("prefix") ?? "")
{
X = Pos.Left(labelPrefix) + labelPrefix.Text.Length + 2,
Y = labelPrefix.Y,
Width = 1
};
var labelServerid = new Label("Please insert your server id here (optional): ")
{
X = 5,
Y = 11
};
var textFiledServerID = new TextField(Config.Variables.GetValue("ServerID") ?? "")
{
X = Pos.Left(labelServerid) + labelServerid.Text.Length + 2,
Y = labelServerid.Y,
Width = 18
};
var button = new Button("Submit")
{
X = Pos.Center() - 10,
Y = 16
};
var button2 = new Button("License")
{
X = Pos.Center() + 10,
Y = 16
};
var button3 = new Button("ⓘ")
{
X = Pos.Left(textFiledServerID) + 20,
Y = textFiledServerID.Y
};
Console.CancelKeyPress += (sender, e) => { top.Running = false; };
button.Clicked += () =>
{
var passMessage = "";
if (textFiledToken.Text.Length != 70 && textFiledToken.Text.Length != 59)
passMessage += "Invalid token, ";
if (textFiledPrefix.Text.ContainsAny("0123456789/\\ ") || textFiledPrefix.Text.Length != 1)
passMessage += "Invalid prefix, ";
if (textFiledServerID.Text.Length != 18 && textFiledServerID.Text.Length > 0)
passMessage += "Invalid serverID";
if (passMessage != "")
{
MessageBox.ErrorQuery("Discord Bot Settings",
"Failed to pass check. Invalid information given:\n" + passMessage, "Retry");
return;
}
Config.Variables.Add("ServerID", (string)textFiledServerID.Text, true);
Config.Variables.Add("token", (string)textFiledToken.Text, true);
Config.Variables.Add("prefix", (string)textFiledPrefix.Text, true);
MessageBox.Query("Discord Bot Settings", "Successfully saved config !\nJust start the bot :D",
"Start :D");
top.Running = false;
};
button2.Clicked += async () =>
{
var license =
await ServerCom.ReadTextFromURL(
"https://raw.githubusercontent.com/Wizzy69/installer/discord-bot-files/LICENSE.txt");
var ProductLicense =
"Seth Discord Bot\n\nDeveloped by Wizzy#9181\nThis application can be used and modified by anyone. Plugin development for this application is also free and supported";
var r = MessageBox.Query("Discord Bot Settings", ProductLicense, "Close", "Read about libraries used");
if (r == 1)
{
var i = 0;
while (i < license.Count)
{
var print_message = license[i++] + "\n";
for (; i < license.Count && !license[i].StartsWith("-----------"); i++)
print_message += license[i] + "\n";
if (print_message.Contains("https://"))
print_message += "\n\nCTRL + Click on a link to open it";
if (MessageBox.Query("Licenses", print_message, "Next", "Quit") == 1) break;
}
}
};
button3.Clicked += () =>
{
MessageBox.Query("Discord Bot Settings",
"Server ID can be found in Server settings => Widget => Server ID",
"Close");
};
win.Add(labelInfo, labelPrefix, labelServerid, labelToken);
win.Add(textFiledToken, textFiledPrefix, textFiledServerID, button3);
win.Add(button, button2);
Application.Run();
Application.Shutdown();
}
} }

View File

@@ -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"); throw new Exception("Config is not loaded");
if (Exists(VarName)) if (Exists(VarName))
{ {
if (GetValue(VarName) == Value)
return;
SetValue(VarName, Value); SetValue(VarName, Value);
SetReadOnly(VarName, ReadOnly); SetReadOnly(VarName, ReadOnly);
return; return;

View File

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

View File

@@ -1,46 +1,10 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using Discord.Commands;
using Discord.WebSocket; using Discord.WebSocket;
namespace PluginManager.Items; 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 class ConsoleCommand
{ {
public string? CommandName { get; init; } public string? CommandName { get; init; }

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

@@ -36,12 +36,6 @@ public static class Functions
return OperatingSystem.UNKNOWN; return OperatingSystem.UNKNOWN;
} }
public static List<string> GetArguments(SocketMessage message)
{
var command = new Command(message);
return command.Arguments;
}
/// <summary> /// <summary>
/// Copy one Stream to another <see langword="async" /> /// Copy one Stream to another <see langword="async" />
/// </summary> /// </summary>