2 Commits

Author SHA1 Message Date
a9ce01e7c9 2022-05-26 20:58:53 +03:00
e6692e4263 Added possibility to add external console commands 2022-05-26 20:53:25 +03:00
5 changed files with 383 additions and 355 deletions

Binary file not shown.

View File

@@ -6,27 +6,21 @@ using System.Threading.Tasks;
using PluginManager.Core;
using PluginManager.Others;
using PluginManager.Loaders;
using PluginManager.LanguageSystem;
using PluginManager.Online;
using System.Diagnostics;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using PluginManager.Items;
namespace DiscordBot
{
public class Program
{
private static PluginsManager manager = new PluginsManager("https://sethdiscordbot.000webhostapp.com/Storage/Discord%20Bot/Plugins");
private static LanguageManager languageManager = new LanguageManager("https://sethdiscordbot.000webhostapp.com/Storage/Discord%20Bot/Languages");
private static bool loadPluginsOnStartup = false;
private static bool listPluginsAtStartup = false;
private static bool listLanguagAtStartup = false;
private static bool PluginsLoaded = false;
private static bool ShowStartupMessage = true;
/// <summary>
@@ -80,324 +74,20 @@ namespace DiscordBot
/// <param name="discordbooter">The discord booter used to start the application</param>
private static async Task NoGUI(Boot discordbooter)
{
LoadLanguage();
if (loadPluginsOnStartup)
LoadPlugins(discordbooter);
if (listPluginsAtStartup)
await manager.ListAvailablePlugins();
if (listLanguagAtStartup)
await languageManager.ListAllLanguages();
Language.LoadLanguage();
ConsoleCommandsHandler consoleCommandsHandler = new ConsoleCommandsHandler(discordbooter.client);
if (loadPluginsOnStartup)
consoleCommandsHandler.HandleCommand("lp");
if (listPluginsAtStartup)
consoleCommandsHandler.HandleCommand("listplugs");
if (listLanguagAtStartup)
consoleCommandsHandler.HandleCommand("listlang");
while (true)
{
Console.ForegroundColor = ConsoleColor.White;
Console_Utilities.WriteColorText("&mConsole ", false);
string[] data = Console.ReadLine().Split(' ');
if (data[0].Length < 2)
continue; // The input command is less then 2 characters long
switch (data[0])
{
case "shutdown":
case "sd":
if (discordbooter.client.ConnectionState == ConnectionState.Connected)
await discordbooter.ShutDown().ContinueWith(t => { Environment.Exit(0); });
break;
case "reload":
case "rl":
if (Environment.OSVersion.Platform != PlatformID.Win32NT)
{
Console.WriteLine("This command is for windows users ONLY");
break;
}
Process.Start("./DiscordBot.exe", "--cmd lp");
if (discordbooter.client.ConnectionState == ConnectionState.Connected)
await discordbooter.ShutDown();
else Environment.Exit(0);
break;
case "listplugs":
await manager.ListAvailablePlugins();
break;
case "dwplug":
string name = data.MergeStrings(1);
// info[0] = plugin type
// info[1] = plugin link
// info[2] = if others are required, or string.Empty if none
string[] info = await manager.GetPluginLinkByName(name);
if (info[1] == null) // link is null
{
if (name == "")
{
Console_Utilities.WriteColorText($"Name is invalid");
break;
}
Console_Utilities.WriteColorText($"Failed to find plugin &b{name} &c! Use &glistplugs &ccommand to display all available plugins !");
break;
}
string path;
if (info[0] == "Command" || info[0] == "Event")
path = "./Data/Plugins/" + info[0] + "s/" + name + ".dll";
else path = $"./{info[1].Split('/')[info[1].Split('/').Length - 1]}";
await ServerCom.DownloadFileAsync(info[1], path);
Console.WriteLine("\n");
// check requirements if any
if (info.Length == 3 && info[2] != string.Empty && info[2] != null)
{
Console.WriteLine($"Downloading requirements for plugin : {name}");
List<string> lines = await ServerCom.ReadTextFromFile(info[2]);
foreach (var line in lines)
{
string[] split = line.Split(',');
Console.WriteLine($"\nDownloading item: {split[1]}");
await ServerCom.DownloadFileAsync(split[0], "./" + split[1]);
Console.WriteLine();
if (split[0].EndsWith(".zip"))
{
Console.WriteLine($"Extracting {split[1]}");
double proc = 0d;
bool isExtracting = true;
Console_Utilities.ProgressBar bar = new Console_Utilities.ProgressBar(100, "");
IProgress<float> extractProgress = new Progress<float>(value =>
{
proc = value;
});
new Thread(new Task(() =>
{
while (isExtracting)
{
bar.Update((int)proc);
if (proc >= 99.9f)
break;
Thread.Sleep(500);
}
}).Start).Start();
await Functions.ExtractArchive("./" + split[1], "./", extractProgress);
bar.Update(100);
isExtracting = false;
await Task.Delay(1000);
bar.Update(100);
Console.WriteLine("\n");
File.Delete("./" + split[1]);
}
if (name == "DBUI")
{
Console.WriteLine("Reload with GUI ?[y/n]");
if (Console.ReadKey().Key == ConsoleKey.Y)
{
Process.Start("./DiscordBotGUI.exe");
Environment.Exit(0);
}
}
}
Console.WriteLine();
break;
}
break;
case "setlang":
if (data.Length == 2)
SetLanguage(data[1]);
else Console.WriteLine("Invalid arguments");
break;
case "set-setting":
if (data.Length >= 3)
Functions.WriteToSettingsFast(data[1], Functions.MergeStrings(data, 2));
else Console.WriteLine("Failed to write to settings. Invalid params");
break;
case "listlang":
await languageManager.ListAllLanguages();
break;
case "dwlang":
string Lname = data.MergeStrings(1);
string[] link = await languageManager.GetDownloadLink(Lname);
try
{
if (link[0] is null || link is null)
{
if (Lname == "")
{
Console_Utilities.WriteColorText($"Name is invalid");
break;
}
Console_Utilities.WriteColorText("Failed to find language &b" + Lname + " &c! Use &glistlang &ccommand to display all available languages !");
break;
}
if (link[1].Contains("CrossPlatform") || link[1].Contains("cp"))
{
string path2 = Functions.langFolder + Lname + ".lng";
await ServerCom.DownloadFileAsync(link[0], path2);
Console.WriteLine("\n");
}
else Console_Utilities.WriteColorText("The language you are trying to download (&b" + Lname + "&c) is not compatible with the version of this bot. User &glistlang &ccommand in order to see all available languages for your current version !\n" + link[1]);
break;
}
catch
{
if (Lname == "")
{
Console_Utilities.WriteColorText($"Name is invalid");
break;
}
Console_Utilities.WriteColorText("Failed to find language &b" + Lname + " &c! Use &glistlang &ccommand to display all available languages !");
break;
}
case "loadplugins":
case "lp":
if (PluginsLoaded)
{
Console_Utilities.WriteColorText("&rPlugins are already loaded");
break;
}
LoadPlugins(discordbooter);
break;
case "help":
Console.ForegroundColor = ConsoleColor.DarkYellow;
Console.WriteLine
(
"lp | loadplugins -> load all plugins\n" +
"sd | shutdown->close connection to the server(stop bot)\n" +
"token -> display the current token\n" +
"listplugs -> list all available plugins\n" +
"dwplug [name] -> download plugin by name\n" +
"listlang -> list all available languages\n" +
"dwlang -> download language by name\n" +
"setlang [name] -> set language from the downloaded languages\n" +
"set-setting [setting.path] [value] -> set setting value"
);
Console.ForegroundColor = ConsoleColor.White;
break;
case "token":
if (File.Exists("./Data/Resources/DiscordBotCore.data"))
Console.WriteLine("Token: " + Functions.readCodeFromFile("./Data/Resources/DiscordBotCore.data", "BOT_TOKEN", '='));
else Console.WriteLine("File could not be found. Please register token");
break;
default:
goto case "help";
}
}
}
private static void LoadPlugins(Boot discordbooter)
{
var loader = new PluginLoader(discordbooter.client);
loader.onCMDLoad += (name, typeName, success, exception) =>
{
Console.ForegroundColor = ConsoleColor.Green;
if (name == null || name.Length < 2)
name = typeName;
if (success)
if (Language.ActiveLanguage == null)
Console.WriteLine("[CMD] Successfully loaded command : " + name);
else Console.WriteLine(Language.ActiveLanguage.FormatText(Language.ActiveLanguage.LanguageWords["COMMAND_LOAD_SUCCESS"], name));
else
if (Language.ActiveLanguage == null)
Console.WriteLine("[CMD] Failed to load command : " + name + " because " + exception.Message);
else
Console.WriteLine(Language.ActiveLanguage.FormatText(Language.ActiveLanguage.LanguageWords["COMMAND_LOAD_FAIL"], name, exception.Message));
Console.ForegroundColor = ConsoleColor.Red;
};
loader.onEVELoad += (name, typeName, success, exception) =>
{
if (name == null || name.Length < 2)
name = typeName;
Console.ForegroundColor = ConsoleColor.Green;
if (success)
if (Language.ActiveLanguage == null)
Console.WriteLine("[EVENT] Successfully loaded event : " + name);
else
Console.WriteLine(Language.ActiveLanguage.FormatText(Language.ActiveLanguage.LanguageWords["EVENT_LOAD_SUCCESS"], name));
else
if (Language.ActiveLanguage == null)
Console.WriteLine("[EVENT] Failed to load event : " + name + " because " + exception.Message);
else
Console.WriteLine(Language.ActiveLanguage.FormatText(Language.ActiveLanguage.LanguageWords["EVENT_LOAD_FAIL"], name, exception.Message));
Console.ForegroundColor = ConsoleColor.Red;
};
loader.LoadPlugins();
PluginsLoaded = true;
}
/// <summary>
/// Load the language from the specified file
/// </summary>
private static bool LoadLanguage()
{
string folder = Functions.langFolder;
string langSettings = "./Data/Resources/Language.txt";
if (!File.Exists(langSettings))
File.WriteAllText(langSettings, "Language=English");
//Load language from the specified file ...
Language.ActiveLanguage = null;
string langname = Functions.readCodeFromFile(langSettings, "Language", '=');
if (langname == "English")
{
Language.ActiveLanguage = null;
return true;
}
foreach (var file in Directory.GetFiles(folder))
{
if (Functions.readCodeFromFile(file, "LANGUAGE_NAME", '=') == langname)
{
Language.ActiveLanguage = Language.CreateLanguageFromFile(file);
return true;
}
}
if (Language.ActiveLanguage == null)
{
File.WriteAllText(langSettings, "Language=English");
Console_Utilities.WriteColorText($"Failed to find language &r{langname} &c! Check available languages using command: &glistlang");
return false;
}
return false;
}
public static void SetLanguage(string LanguageName)
{
string langSettings = Functions.dataFolder + "Language.txt";
File.WriteAllText(langSettings, "Language=" + LanguageName);
try
{
bool success = LoadLanguage();
if (success)
{
Console_Utilities.WriteColorText($"Language has been setted to: &g{LanguageName}");
return;
}
}
catch (Exception ex)
{
Console_Utilities.WriteColorText($"Could not find language &r{LanguageName}.");
Functions.WriteErrFile(ex.ToString());
File.WriteAllText(langSettings, "Language=English");
LoadLanguage();
consoleCommandsHandler.HandleCommand(Console.ReadLine());
}
}
@@ -455,23 +145,6 @@ namespace DiscordBot
private static async Task HandleInput(string[] args)
{
/* if (args.Length > 0)
if (args[0] == "progress")
{
Console_Utilities.ProgressBar bar = new Console_Utilities.ProgressBar(100, "Download");
for (int i = 0; i <= 100; i++)
{
bar.Update(i);
await Task.Delay(10);
}
return;
}
else if (args[0] == "test")
{
return;
}*/
if (args.Length == 0)
{
if (File.Exists("./ref/startupArguments.txt"))

View File

@@ -47,23 +47,5 @@ namespace PluginManager.Items
this.CommandName = data[0].Substring(1);
this.PrefixUsed = data[0][0];
}
/// <summary>
/// The Command class contructor
/// </summary>
/// <param name="message">The message string itself</param>
/// <param name="hasPrefix">True if the message has a prefix, false if not</param>
public Command(string message, bool hasPrefix)
{
string[] data = message.Split(' ');
this.Author = null;
this.Arguments = new List<string>(data.MergeStrings(1).Split(' '));
this.CommandName = data[0].Substring(1);
if (hasPrefix)
this.PrefixUsed = data[0][0];
else this.PrefixUsed = '\0'; //null
}
}
}

View File

@@ -0,0 +1,310 @@
using Discord.WebSocket;
using PluginManager.Loaders;
using PluginManager.Online;
using PluginManager.Others;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading.Tasks;
using System.Threading;
using PluginManager.LanguageSystem;
namespace PluginManager.Items
{
public class ConsoleCommandsHandler
{
private static PluginsManager manager = new PluginsManager("https://sethdiscordbot.000webhostapp.com/Storage/Discord%20Bot/Plugins");
private static LanguageManager languageManager = new LanguageManager("https://sethdiscordbot.000webhostapp.com/Storage/Discord%20Bot/Languages");
public static List<Tuple<string, string, Action<string[]>>> commandList = new List<Tuple<string, string, Action<string[]>>>();
private DiscordSocketClient client;
public ConsoleCommandsHandler(DiscordSocketClient client)
{
this.client = client;
//commandList = new List<Tuple<string, string, Action<string[]>>>();
InitializeBasicCommands();
//Console.WriteLine("ConsoleCommandsHandler enabled");
}
private void InitializeBasicCommands()
{
bool pluginsLoaded = false;
AddCommand("help", "Show help", (args) =>
{
if (args.Length == 1)
{
Console.WriteLine("Available commands:");
foreach (var command in commandList)
{
Console.WriteLine("\t" + command.Item1 + " - " + command.Item2);
}
}
else
{
foreach (var command in commandList)
{
if (command.Item1 == args[0])
{
Console.WriteLine(command.Item2);
return;
}
}
Console.WriteLine("Command not found");
}
});
AddCommand("lp", "Load plugins", () =>
{
if (pluginsLoaded) return;
var loader = new PluginLoader(client);
loader.onCMDLoad += (name, typeName, success, exception) =>
{
Console.ForegroundColor = ConsoleColor.Green;
if (name == null || name.Length < 2)
name = typeName;
if (success)
if (LanguageSystem.Language.ActiveLanguage == null)
Console.WriteLine("[CMD] Successfully loaded command : " + name);
else Console.WriteLine(LanguageSystem.Language.ActiveLanguage.FormatText(LanguageSystem.Language.ActiveLanguage.LanguageWords["COMMAND_LOAD_SUCCESS"], name));
else
if (LanguageSystem.Language.ActiveLanguage == null)
Console.WriteLine("[CMD] Failed to load command : " + name + " because " + exception.Message);
else
Console.WriteLine(LanguageSystem.Language.ActiveLanguage.FormatText(LanguageSystem.Language.ActiveLanguage.LanguageWords["COMMAND_LOAD_FAIL"], name, exception.Message));
Console.ForegroundColor = ConsoleColor.Red;
};
loader.onEVELoad += (name, typeName, success, exception) =>
{
if (name == null || name.Length < 2)
name = typeName;
Console.ForegroundColor = ConsoleColor.Green;
if (success)
if (LanguageSystem.Language.ActiveLanguage == null)
Console.WriteLine("[EVENT] Successfully loaded event : " + name);
else
Console.WriteLine(LanguageSystem.Language.ActiveLanguage.FormatText(LanguageSystem.Language.ActiveLanguage.LanguageWords["EVENT_LOAD_SUCCESS"], name));
else
if (LanguageSystem.Language.ActiveLanguage == null)
Console.WriteLine("[EVENT] Failed to load event : " + name + " because " + exception.Message);
else
Console.WriteLine(LanguageSystem.Language.ActiveLanguage.FormatText(LanguageSystem.Language.ActiveLanguage.LanguageWords["EVENT_LOAD_FAIL"], name, exception.Message));
Console.ForegroundColor = ConsoleColor.Red;
};
loader.LoadPlugins();
pluginsLoaded = true;
});
AddCommand("listplugs", "list available plugins", async () =>
{
await manager.ListAvailablePlugins();
});
AddCommand("dwplug", "download plugin", async (args) =>
{
if (args.Length == 1)
{
Console.WriteLine("Please specify plugin name");
return;
}
string name = args.MergeStrings(1);
// info[0] = plugin type
// info[1] = plugin link
// info[2] = if others are required, or string.Empty if none
string[] info = await manager.GetPluginLinkByName(name);
if (info[1] == null) // link is null
{
if (name == "")
{
Console_Utilities.WriteColorText($"Name is invalid");
return;
}
Console_Utilities.WriteColorText($"Failed to find plugin &b{name} &c!" +
$" Use &glistplugs &ccommand to display all available plugins !");
return;
}
string path;
if (info[0] == "Command" || info[0] == "Event")
path = "./Data/Plugins/" + info[0] + "s/" + name + ".dll";
else path = $"./{info[1].Split('/')[info[1].Split('/').Length - 1]}";
await ServerCom.DownloadFileAsync(info[1], path);
Console.WriteLine("\n");
// check requirements if any
if (info.Length == 3 && info[2] != string.Empty && info[2] != null)
{
Console.WriteLine($"Downloading requirements for plugin : {name}");
List<string> lines = await ServerCom.ReadTextFromFile(info[2]);
foreach (var line in lines)
{
string[] split = line.Split(',');
Console.WriteLine($"\nDownloading item: {split[1]}");
await ServerCom.DownloadFileAsync(split[0], "./" + split[1]);
Console.WriteLine();
if (split[0].EndsWith(".zip"))
{
Console.WriteLine($"Extracting {split[1]}");
double proc = 0d;
bool isExtracting = true;
Console_Utilities.ProgressBar bar = new Console_Utilities.ProgressBar(100, "");
IProgress<float> extractProgress = new Progress<float>(value =>
{
proc = value;
});
new Thread(new Task(() =>
{
while (isExtracting)
{
bar.Update((int)proc);
if (proc >= 99.9f)
break;
Thread.Sleep(500);
}
}).Start).Start();
await Functions.ExtractArchive("./" + split[1], "./", extractProgress);
bar.Update(100);
isExtracting = false;
await Task.Delay(1000);
bar.Update(100);
Console.WriteLine("\n");
System.IO.File.Delete("./" + split[1]);
}
if (name == "DBUI")
{
Console.WriteLine("Reload with GUI ?[y/n]");
if (Console.ReadKey().Key == ConsoleKey.Y)
{
Process.Start("./DiscordBotGUI.exe");
Environment.Exit(0);
}
}
}
Console.WriteLine();
}
});
AddCommand("setlang", "set language", (args) =>
{
if (args.Length == 1)
{
Console.WriteLine("Please specify language");
return;
}
Language.SetLanguage(args[0]);
});
AddCommand("listlang", "List all available languages", async () =>
{
await languageManager.ListAllLanguages();
});
AddCommand("dwlang", "Download language", async (args) =>
{
if (args.Length == 1)
{
Console.WriteLine("Please specify language");
return;
}
string Lname = args.MergeStrings(1);
string[] link = await languageManager!.GetDownloadLink(Lname);
try
{
if (link[0] is null || link is null)
{
if (Lname == "")
{
Console_Utilities.WriteColorText($"Name is invalid");
return;
}
Console_Utilities.WriteColorText("Failed to find language &b" + Lname + " &c! Use &glistlang &ccommand to display all available languages !");
return;
}
if (link[1].Contains("CrossPlatform") || link[1].Contains("cp"))
{
string path2 = Functions.langFolder + Lname + ".lng";
await ServerCom.DownloadFileAsync(link[0], path2);
Console.WriteLine("\n");
}
else Console_Utilities.WriteColorText("The language you are trying to download (&b" + Lname + "&c) is not compatible with the version of this bot. User &glistlang &ccommand in order to see all available languages for your current version !\n" + link[1]);
return;
}
catch
{
if (Lname == "")
{
Console_Utilities.WriteColorText($"Name is invalid");
return;
}
Console_Utilities.WriteColorText("Failed to find language &b" + Lname + " &c! Use &glistlang &ccommand to display all available languages !");
return;
}
});
AddCommand("token", "Display the token used by the bot", () =>
{
if (System.IO.File.Exists("./Data/Resources/DiscordBotCore.data"))
Console.WriteLine("Token: " + Functions.readCodeFromFile("./Data/Resources/DiscordBotCore.data", "BOT_TOKEN", '='));
else Console.WriteLine("File could not be found. Please register token");
});
}
public static void AddCommand(string command, string description, Action<string[]> action)
{
commandList.Add(new Tuple<string, string, Action<string[]>>(command, description, action));
Console_Utilities.WriteColorText($"Command &r{command} &cadded to the list of commands");
}
public static void AddCommand(string command, string description, Action action)
{
AddCommand(command, description, (args) =>
{
action();
});
/* Console.WriteLine("Added command: " + command);*/
}
public static void RemoveCommand(string command)
{
commandList.RemoveAll(x => x.Item1 == command);
}
public void HandleCommand(string command)
{
string[] args = command.Split(' ');
foreach (var item in commandList)
{
if (item.Item1 == args[0])
{
item.Item3(args);
return;
}
}
}
}
}

View File

@@ -3,6 +3,7 @@ using System.Collections.Generic;
using System;
using System.IO;
using System.Threading.Tasks;
namespace PluginManager.LanguageSystem
{
@@ -94,5 +95,67 @@ namespace PluginManager.LanguageSystem
for (var i = 0; i < l; i++) text = text.Replace($"{i}", args[i]);
return text;
}
public static bool LoadLanguage()
{
string folder = Functions.langFolder;
string langSettings = "./Data/Resources/Language.txt";
if (!File.Exists(langSettings))
File.WriteAllText(langSettings, "Language=English");
//Load language from the specified file ...
Language.ActiveLanguage = null;
string langname = Functions.readCodeFromFile(langSettings, "Language", '=');
if (langname == "English")
{
Language.ActiveLanguage = null;
return true;
}
foreach (var file in Directory.GetFiles(folder))
{
if (Functions.readCodeFromFile(file, "LANGUAGE_NAME", '=') == langname)
{
Language.ActiveLanguage = Language.CreateLanguageFromFile(file);
return true;
}
}
if (Language.ActiveLanguage == null)
{
File.WriteAllText(langSettings, "Language=English");
Console_Utilities.WriteColorText($"Failed to find language &r{langname} &c! Check available languages using command: &glistlang");
return false;
}
return false;
}
public static void SetLanguage(string LanguageName)
{
string langSettings = Functions.dataFolder + "Language.txt";
File.WriteAllText(langSettings, "Language=" + LanguageName);
try
{
bool success = LoadLanguage();
if (success)
{
Console_Utilities.WriteColorText($"Language has been setted to: &g{LanguageName}");
return;
}
}
catch (Exception ex)
{
Console_Utilities.WriteColorText($"Could not find language &r{LanguageName}.");
Functions.WriteErrFile(ex.ToString());
File.WriteAllText(langSettings, "Language=English");
LoadLanguage();
}
}
}
}