This commit is contained in:
2022-06-08 18:54:58 +03:00
parent c66ff52d94
commit 531edcd3cc
55 changed files with 2253 additions and 2360 deletions

Binary file not shown.

Binary file not shown.

View File

@@ -1,17 +1,12 @@
using System; using Discord;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Discord;
using Discord.Commands; using Discord.Commands;
using Discord.WebSocket; using Discord.WebSocket;
using PluginManager; using PluginManager;
using PluginManager.Interfaces; using PluginManager.Interfaces;
using PluginManager.Others; using PluginManager.Others;
namespace CMD_LevelingSystem namespace CMD_LevelingSystem;
{
internal class Level : DBCommand internal class Level : DBCommand
{ {
public string Command => "level"; public string Command => "level";
@@ -28,7 +23,7 @@ namespace CMD_LevelingSystem
public async void Execute(SocketCommandContext context, SocketMessage message, DiscordSocketClient client, bool isDM) public async void Execute(SocketCommandContext context, SocketMessage message, DiscordSocketClient client, bool isDM)
{ {
User user = await Functions.ConvertFromJson<User>(Config.GetValue("LevelingSystemPath") + $"/{message.Author.Id}.dat"); var user = await Functions.ConvertFromJson<User>(Config.GetValue<string>("LevelingSystemPath") + $"/{message.Author.Id}.dat");
if (user == null) if (user == null)
{ {
await context.Channel.SendMessageAsync("You are now unranked !"); await context.Channel.SendMessageAsync("You are now unranked !");
@@ -36,7 +31,7 @@ namespace CMD_LevelingSystem
} }
var builder = new EmbedBuilder(); var builder = new EmbedBuilder();
Random r = new Random(); var r = new Random();
builder.WithColor(r.Next(256), r.Next(256), r.Next(256)); builder.WithColor(r.Next(256), r.Next(256), r.Next(256));
builder.AddField("Current Level", user.CurrentLevel, true) builder.AddField("Current Level", user.CurrentLevel, true)
.AddField("Current EXP", user.CurrentEXP, true) .AddField("Current EXP", user.CurrentEXP, true)
@@ -45,4 +40,3 @@ namespace CMD_LevelingSystem
await context.Channel.SendMessageAsync(embed: builder.Build()); await context.Channel.SendMessageAsync(embed: builder.Build());
} }
} }
}

View File

@@ -1,16 +1,9 @@
using System; namespace CMD_LevelingSystem;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CMD_LevelingSystem
{
public class User public class User
{ {
public string userID { get; set; } public string userID { get; set; }
public int CurrentLevel { get; set; } public int CurrentLevel { get; set; }
public Int64 CurrentEXP { get; set; } public long CurrentEXP { get; set; }
public Int64 RequiredEXPToLevelUp { get; set; } public long RequiredEXPToLevelUp { get; set; }
}
} }

View File

@@ -1,6 +1,5 @@
using Discord.Commands; using Discord.Commands;
using Discord.WebSocket; using Discord.WebSocket;
using PluginManager.Interfaces; using PluginManager.Interfaces;
internal class Echo : DBCommand internal class Echo : DBCommand
@@ -18,7 +17,7 @@ internal class Echo : DBCommand
public async void Execute(SocketCommandContext context, SocketMessage message, DiscordSocketClient client, bool isDM) public async void Execute(SocketCommandContext context, SocketMessage message, DiscordSocketClient client, bool isDM)
{ {
string m = message.Content.Substring(6); var m = message.Content.Substring(6);
await message.Channel.SendMessageAsync(m); await message.Channel.SendMessageAsync(m);
} }
} }

View File

@@ -1,17 +1,10 @@
using System; using Discord.Commands;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Discord.Commands;
using Discord.WebSocket; using Discord.WebSocket;
using PluginManager.Interfaces; using PluginManager.Interfaces;
namespace CMD_Utils namespace CMD_Utils;
{
class FlipCoin : DBCommand internal class FlipCoin : DBCommand
{ {
public string Command => "flip"; public string Command => "flip";
@@ -27,11 +20,11 @@ namespace CMD_Utils
public async void Execute(SocketCommandContext context, SocketMessage message, DiscordSocketClient client, bool isDM) public async void Execute(SocketCommandContext context, SocketMessage message, DiscordSocketClient client, bool isDM)
{ {
System.Random random = new System.Random(); var random = new System.Random();
int r = random.Next(1, 3); var r = random.Next(1, 3);
if (r == 1) if (r == 1)
await message.Channel.SendMessageAsync("Heads"); await message.Channel.SendMessageAsync("Heads");
else await message.Channel.SendMessageAsync("Tails"); else
} await message.Channel.SendMessageAsync("Tails");
} }
} }

View File

@@ -1,17 +1,12 @@
using System; using System.Collections.Generic;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Discord; using Discord;
using Discord.Commands; using Discord.Commands;
using Discord.WebSocket; using Discord.WebSocket;
using PluginManager.Interfaces; using PluginManager.Interfaces;
using PluginManager.Others;
namespace CMD_Utils;
namespace CMD_Utils
{
public class Poll : DBCommand public class Poll : DBCommand
{ {
public string Command => "poll"; public string Command => "poll";
@@ -29,16 +24,15 @@ namespace CMD_Utils
public async void Execute(SocketCommandContext context, SocketMessage message, DiscordSocketClient client, bool isDM) public async void Execute(SocketCommandContext context, SocketMessage message, DiscordSocketClient client, bool isDM)
{ {
if (isDM) return; if (isDM) return;
string question = message.Content.Split(' ')[1].Replace('-', ' '); var question = message.Content.Split(' ')[1].Replace('-', ' ');
string[] answers = PluginManager.Others.Functions.MergeStrings(message.Content.Split(' '), 2).Split(' '); var answers = Functions.MergeStrings(message.Content.Split(' '), 2).Split(' ');
EmbedBuilder embedBuilder = new EmbedBuilder(); var embedBuilder = new EmbedBuilder();
embedBuilder.Title = question; embedBuilder.Title = question;
int len = answers.Length; var len = answers.Length;
for (int i = 0; i < len; i++) for (var i = 0; i < len; i++) embedBuilder.AddField($"Answer {i + 1}", answers[i].Replace('-', ' '), true);
embedBuilder.AddField($"Answer {i + 1}", answers[i].Replace('-', ' '), true);
var msg = await context.Channel.SendMessageAsync(embed: embedBuilder.Build()); var msg = await context.Channel.SendMessageAsync(embed: embedBuilder.Build());
List<IEmote> emotes = new List<IEmote>(); var emotes = new List<IEmote>();
emotes.Add(Emoji.Parse(":one:")); emotes.Add(Emoji.Parse(":one:"));
emotes.Add(Emoji.Parse(":two:")); emotes.Add(Emoji.Parse(":two:"));
emotes.Add(Emoji.Parse(":three:")); emotes.Add(Emoji.Parse(":three:"));
@@ -46,8 +40,6 @@ namespace CMD_Utils
emotes.Add(Emoji.Parse(":five:")); emotes.Add(Emoji.Parse(":five:"));
emotes.Add(Emoji.Parse(":six:")); emotes.Add(Emoji.Parse(":six:"));
for (int i = 0; i < len; i++) for (var i = 0; i < len; i++) await msg.AddReactionAsync(emotes[i]);
await msg.AddReactionAsync(emotes[i]);
}
} }
} }

View File

@@ -1,6 +1,5 @@
using Discord.Commands; using Discord.Commands;
using Discord.WebSocket; using Discord.WebSocket;
using PluginManager.Interfaces; using PluginManager.Interfaces;
public class Random : DBCommand public class Random : DBCommand
@@ -19,19 +18,18 @@ public class Random : DBCommand
{ {
try try
{ {
string msg = message.Content; var msg = message.Content;
int a = int.Parse(msg.Split(' ')[1]); var a = int.Parse(msg.Split(' ')[1]);
int b = int.Parse(msg.Split(' ')[2]); var b = int.Parse(msg.Split(' ')[2]);
if (a > b) if (a > b)
{ {
int x = a; var x = a;
a = b; a = b;
b = x; b = x;
} }
await message.Channel.SendMessageAsync("Your random generated number is " + new System.Random().Next(a, b)); await message.Channel.SendMessageAsync("Your random generated number is " + new System.Random().Next(a, b));
} }
catch catch
{ {

View File

@@ -2,6 +2,3 @@
<assemblyIdentity name="System.Runtime" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" /> <assemblyIdentity name="System.Runtime" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="4.0.0.0" /> <bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="4.0.0.0" />
</dependentAssembly> </dependentAssembly>

View File

@@ -1,16 +1,12 @@
using Discord; using Discord;
using Discord.Commands; using Discord.Commands;
using Discord.WebSocket; using Discord.WebSocket;
using PluginManager.Loaders;
using PluginManager.Interfaces; using PluginManager.Interfaces;
using PluginManager.Others.Permissions; using PluginManager.Loaders;
using PluginManager.Others; using PluginManager.Others;
using System.Collections.Generic; namespace DiscordBot.Discord.Commands;
namespace DiscordBot.Discord.Commands
{
/// <summary> /// <summary>
/// The help command /// The help command
/// </summary> /// </summary>
@@ -55,10 +51,9 @@ namespace DiscordBot.Discord.Commands
/// <param name="isDM">True if the message was sent from a DM channel, false otherwise</param> /// <param name="isDM">True if the message was sent from a DM channel, false otherwise</param>
public void Execute(SocketCommandContext context, SocketMessage message, DiscordSocketClient client, bool isDM) public void Execute(SocketCommandContext context, SocketMessage message, DiscordSocketClient client, bool isDM)
{ {
List<string> args = Functions.GetArguments(message); var args = Functions.GetArguments(message);
if (args.Count != 0) if (args.Count != 0)
{ {
foreach (var item in args) foreach (var item in args)
{ {
var e = GenerateHelpCommand(item); var e = GenerateHelpCommand(item);
@@ -67,13 +62,15 @@ namespace DiscordBot.Discord.Commands
else else
context.Channel.SendMessageAsync("Unknown Command " + item); context.Channel.SendMessageAsync("Unknown Command " + item);
} }
return; return;
} }
EmbedBuilder embedBuilder = new EmbedBuilder();
string adminCommands = ""; var embedBuilder = new EmbedBuilder();
string normalCommands = "";
string DMCommands = ""; var adminCommands = "";
var normalCommands = "";
var DMCommands = "";
foreach (var cmd in PluginLoader.Commands!) foreach (var cmd in PluginLoader.Commands!)
{ {
@@ -87,15 +84,13 @@ namespace DiscordBot.Discord.Commands
embedBuilder.AddField("Normal Commands", normalCommands); embedBuilder.AddField("Normal Commands", normalCommands);
embedBuilder.AddField("DM Commands", DMCommands); embedBuilder.AddField("DM Commands", DMCommands);
context.Channel.SendMessageAsync(embed: embedBuilder.Build()); context.Channel.SendMessageAsync(embed: embedBuilder.Build());
} }
private EmbedBuilder GenerateHelpCommand(string command) private EmbedBuilder GenerateHelpCommand(string command)
{ {
EmbedBuilder embedBuilder = new EmbedBuilder(); var embedBuilder = new EmbedBuilder();
DBCommand cmd = PluginLoader.Commands.Find(p => p.Command == command); var cmd = PluginLoader.Commands.Find(p => p.Command == command);
if (cmd == null) if (cmd == null) return null;
return null;
embedBuilder.AddField("Usage", cmd.Usage); embedBuilder.AddField("Usage", cmd.Usage);
embedBuilder.AddField("Description", cmd.Description); embedBuilder.AddField("Description", cmd.Description);
@@ -103,4 +98,3 @@ namespace DiscordBot.Discord.Commands
return embedBuilder; return embedBuilder;
} }
} }
}

View File

@@ -1,16 +1,15 @@
using System; using System;
using System.Diagnostics; using System.Diagnostics;
using Discord.WebSocket; using Discord.WebSocket;
using PluginManager.Interfaces;
using PluginManager.Others;
using PluginManager.Others.Permissions;
using DiscordLibCommands = Discord.Commands; using DiscordLibCommands = Discord.Commands;
using DiscordLib = Discord; using DiscordLib = Discord;
using OperatingSystem = PluginManager.Others.OperatingSystem;
using PluginManager.Interfaces; namespace DiscordBot.Discord.Commands;
using PluginManager.Others.Permissions;
using PluginManager.Others;
namespace DiscordBot.Discord.Commands
{
internal class Restart : DBCommand internal class Restart : DBCommand
{ {
/// <summary> /// <summary>
@@ -42,6 +41,7 @@ namespace DiscordBot.Discord.Commands
/// Check if the command require administrator to be executed /// Check if the command require administrator to be executed
/// </summary> /// </summary>
public bool requireAdmin => false; public bool requireAdmin => false;
/// <summary> /// <summary>
/// The main body of the command /// The main body of the command
/// </summary> /// </summary>
@@ -51,25 +51,27 @@ namespace DiscordBot.Discord.Commands
/// <param name="isDM">True if the message was sent from a DM channel, false otherwise</param> /// <param name="isDM">True if the message was sent from a DM channel, false otherwise</param>
public async void Execute(DiscordLibCommands.SocketCommandContext context, SocketMessage message, DiscordSocketClient client, bool isDM) public async void Execute(DiscordLibCommands.SocketCommandContext context, SocketMessage message, DiscordSocketClient client, bool isDM)
{ {
if (!DiscordPermissions.hasPermission(message.Author as SocketGuildUser, DiscordLib.GuildPermission.Administrator)) return; if (!(message.Author as SocketGuildUser).hasPermission(DiscordLib.GuildPermission.Administrator)) return;
var args = Functions.GetArguments(message); var args = Functions.GetArguments(message);
var OS = Functions.GetOperatingSystem(); var OS = Functions.GetOperatingSystem();
if (args.Count == 0) if (args.Count == 0)
{ {
switch (OS) switch (OS)
{ {
case PluginManager.Others.OperatingSystem.WINDOWS: case OperatingSystem.WINDOWS:
Process.Start("./DiscordBot.exe"); Process.Start("./DiscordBot.exe");
break; break;
case PluginManager.Others.OperatingSystem.LINUX: case OperatingSystem.LINUX:
case PluginManager.Others.OperatingSystem.MAC_OS: case OperatingSystem.MAC_OS:
Process.Start("./DiscordBot"); Process.Start("./DiscordBot");
break; break;
default: default:
return; return;
} }
return; return;
} }
switch (args[0]) switch (args[0])
{ {
case "-p": case "-p":
@@ -80,35 +82,32 @@ namespace DiscordBot.Discord.Commands
break; break;
case "-cmd": case "-cmd":
case "-args": case "-args":
string cmd = "--args"; var cmd = "--args";
if (args.Count > 1) if (args.Count > 1)
for (int i = 1; i < args.Count; i++) for (var i = 1; i < args.Count; i++)
cmd += $" {args[i]}"; cmd += $" {args[i]}";
switch (OS) switch (OS)
{ {
case PluginManager.Others.OperatingSystem.WINDOWS: case OperatingSystem.WINDOWS:
Functions.WriteLogFile("Restarting the bot with the following arguments: \"" + cmd + "\""); Functions.WriteLogFile("Restarting the bot with the following arguments: \"" + cmd + "\"");
Process.Start("./DiscordBot.exe", cmd); Process.Start("./DiscordBot.exe", cmd);
break; break;
case PluginManager.Others.OperatingSystem.LINUX: case OperatingSystem.LINUX:
//case PluginManager.Others.OperatingSystem.MAC_OS: ?? - not tested //case PluginManager.Others.OperatingSystem.MAC_OS: ?? - not tested
Process.Start("./DiscordBot", cmd); Process.Start("./DiscordBot", cmd);
break; break;
default: default:
return; return;
} }
Environment.Exit(0); Environment.Exit(0);
break; break;
default: default:
await context.Channel.SendMessageAsync("Invalid argument. Use `help restart` to see the usage."); await context.Channel.SendMessageAsync("Invalid argument. Use `help restart` to see the usage.");
break; break;
}
} }
} }
} }

View File

@@ -1,22 +1,14 @@
using System; using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Discord; using Discord;
using Discord.Commands; using Discord.Commands;
using Discord.WebSocket; using Discord.WebSocket;
using DiscordBot.Discord.Core;
using PluginManager; using PluginManager;
using PluginManager.Interfaces; using PluginManager.Interfaces;
using PluginManager.Others;
using PluginManager.Others.Permissions;
namespace DiscordBot.Discord.Commands namespace DiscordBot.Discord.Commands;
{
class Settings : DBCommand
{
internal class Settings : DBCommand
{
/// <summary> /// <summary>
/// Command name /// Command name
/// </summary> /// </summary>
@@ -59,9 +51,9 @@ namespace DiscordBot.Discord.Commands
var channel = message.Channel; var channel = message.Channel;
try try
{ {
string content = message.Content; var content = message.Content;
string[] data = content.Split(' '); var data = content.Split(' ');
string keyword = data[1]; var keyword = data[1];
if (keyword.ToLower() == "help") if (keyword.ToLower() == "help")
{ {
await channel.SendMessageAsync("set token [new value] -- set the value of the new token (require restart)"); await channel.SendMessageAsync("set token [new value] -- set the value of the new token (require restart)");
@@ -101,7 +93,5 @@ namespace DiscordBot.Discord.Commands
Console.WriteLine(ex.Message); Console.WriteLine(ex.Message);
await channel.SendMessageAsync("Unknown usage to this command !\nUsage: " + Usage); await channel.SendMessageAsync("Unknown usage to this command !\nUsage: " + Usage);
} }
}
} }
} }

View File

@@ -1,14 +1,14 @@
using Discord; using System;
using Discord.Commands;
using Discord.WebSocket;
using System;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using Discord;
using Discord.Commands;
using Discord.WebSocket;
using PluginManager; using PluginManager;
using static PluginManager.Others.Functions; using static PluginManager.Others.Functions;
namespace DiscordBot.Discord.Core namespace DiscordBot.Discord.Core;
{
internal class Boot internal class Boot
{ {
/// <summary> /// <summary>
@@ -21,13 +21,6 @@ namespace DiscordBot.Discord.Core
/// </summary> /// </summary>
public readonly string botToken; public readonly string botToken;
/// <summary>
/// Checks if the bot is ready
/// </summary>
/// <value> true if the bot is ready, othwerwise false </value>
public bool isReady { get; private set; } = false;
/// <summary> /// <summary>
/// The bot client /// The bot client
/// </summary> /// </summary>
@@ -54,6 +47,13 @@ namespace DiscordBot.Discord.Core
this.botToken = botToken; this.botToken = botToken;
} }
/// <summary>
/// Checks if the bot is ready
/// </summary>
/// <value> true if the bot is ready, othwerwise false </value>
public bool isReady { get; private set; }
/// <summary> /// <summary>
/// The start method for the bot. This method is used to load the bot /// The start method for the bot. This method is used to load the bot
/// </summary> /// </summary>
@@ -73,7 +73,6 @@ namespace DiscordBot.Discord.Core
await Task.Delay(2000); await Task.Delay(2000);
while (!isReady) ; while (!isReady) ;
} }
private void CommonTasks() private void CommonTasks()
@@ -114,7 +113,8 @@ namespace DiscordBot.Discord.Core
{ {
Console.Title = "CONNECTED"; Console.Title = "CONNECTED";
WriteLogFile("The bot has been logged in at " + DateTime.Now.ToShortDateString() + " (" + WriteLogFile("The bot has been logged in at " + DateTime.Now.ToShortDateString() + " (" +
DateTime.Now.ToShortTimeString() + ")"); DateTime.Now.ToShortTimeString() + ")"
);
return Task.CompletedTask; return Task.CompletedTask;
} }
@@ -147,4 +147,3 @@ namespace DiscordBot.Discord.Core
return Task.CompletedTask; return Task.CompletedTask;
} }
} }
}

View File

@@ -1,25 +1,19 @@
using Discord.Commands; using System.Linq;
using Discord.WebSocket;
using PluginManager.Interfaces;
using System.Reflection; using System.Reflection;
using System.Threading.Tasks;
using Discord.Commands;
using Discord.WebSocket;
using PluginManager.Loaders;
using PluginManager.Others; using PluginManager.Others;
using PluginManager.Others.Permissions; using PluginManager.Others.Permissions;
using PluginManager.Loaders;
using System.Threading.Tasks; namespace DiscordBot.Discord.Core;
using System.Linq;
using Discord;
using System;
namespace DiscordBot.Discord.Core
{
internal class CommandHandler internal class CommandHandler
{ {
private readonly string botPrefix;
private readonly DiscordSocketClient client; private readonly DiscordSocketClient client;
private readonly CommandService commandService; private readonly CommandService commandService;
private readonly string botPrefix;
/// <summary> /// <summary>
/// Command handler constructor /// Command handler constructor
@@ -41,7 +35,7 @@ namespace DiscordBot.Discord.Core
public async Task InstallCommandsAsync() public async Task InstallCommandsAsync()
{ {
client.MessageReceived += MessageHandler; client.MessageReceived += MessageHandler;
await commandService.AddModulesAsync(assembly: Assembly.GetEntryAssembly(), services: null); await commandService.AddModulesAsync(Assembly.GetEntryAssembly(), null);
} }
/// <summary> /// <summary>
@@ -53,8 +47,7 @@ namespace DiscordBot.Discord.Core
{ {
try try
{ {
if (Message as SocketUserMessage == null) if (Message as SocketUserMessage == null) return;
return;
var message = Message as SocketUserMessage; var message = Message as SocketUserMessage;
@@ -62,7 +55,7 @@ namespace DiscordBot.Discord.Core
if (!message.Content.StartsWith(botPrefix)) return; if (!message.Content.StartsWith(botPrefix)) return;
int argPos = 0; var argPos = 0;
if (message.HasMentionPrefix(client.CurrentUser, ref argPos)) if (message.HasMentionPrefix(client.CurrentUser, ref argPos))
{ {
@@ -75,12 +68,12 @@ namespace DiscordBot.Discord.Core
var context = new SocketCommandContext(client, message); var context = new SocketCommandContext(client, message);
await commandService.ExecuteAsync( await commandService.ExecuteAsync(
context: context, context,
argPos: argPos, argPos,
services: null null
); );
DBCommand plugin = PluginLoader.Commands!.Where(p => p.Command == (message.Content.Split(' ')[0]).Substring(botPrefix.Length)).FirstOrDefault(); var plugin = PluginLoader.Commands!.Where(p => p.Command == message.Content.Split(' ')[0].Substring(botPrefix.Length)).FirstOrDefault();
if (plugin != null) if (plugin != null)
@@ -97,9 +90,11 @@ namespace DiscordBot.Discord.Core
Functions.WriteLogFile($"[{message.Author.Id}] Executed command (DM) : " + plugin.Command); Functions.WriteLogFile($"[{message.Author.Id}] Executed command (DM) : " + plugin.Command);
return; return;
} }
await message.Channel.SendMessageAsync("This command is for administrators only !"); await message.Channel.SendMessageAsync("This command is for administrators only !");
return; return;
} }
plugin.Execute(context, message, client, true); plugin.Execute(context, message, client, true);
Functions.WriteLogFile($"[{message.Author.Id}] Executed command (DM) : " + plugin.Command); Functions.WriteLogFile($"[{message.Author.Id}] Executed command (DM) : " + plugin.Command);
return; return;
@@ -108,6 +103,7 @@ namespace DiscordBot.Discord.Core
await message.Channel.SendMessageAsync("This command is not for DMs"); await message.Channel.SendMessageAsync("This command is not for DMs");
return; return;
} }
if (plugin.canUseServer) if (plugin.canUseServer)
{ {
if (plugin.requireAdmin) if (plugin.requireAdmin)
@@ -118,19 +114,19 @@ namespace DiscordBot.Discord.Core
Functions.WriteLogFile($"[{message.Author.Id}] Executed command : " + plugin.Command); Functions.WriteLogFile($"[{message.Author.Id}] Executed command : " + plugin.Command);
return; return;
} }
await message.Channel.SendMessageAsync("This command is for administrators only !"); await message.Channel.SendMessageAsync("This command is for administrators only !");
return; return;
} }
plugin.Execute(context, message, client, false); plugin.Execute(context, message, client, false);
Functions.WriteLogFile($"[{message.Author.Id}] Executed command : " + plugin.Command); Functions.WriteLogFile($"[{message.Author.Id}] Executed command : " + plugin.Command);
return; return;
} }
return;
} }
} }
catch { } catch
{
} }
} }
} }

View File

@@ -6,6 +6,7 @@ using System;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
using PluginManager.Online;
namespace DiscordBot namespace DiscordBot
{ {
@@ -14,8 +15,6 @@ namespace DiscordBot
private static bool loadPluginsOnStartup = false; private static bool loadPluginsOnStartup = false;
private static bool listPluginsAtStartup = false; private static bool listPluginsAtStartup = false;
private static bool listLanguagAtStartup = false;
/// <summary> /// <summary>
/// The main entry point for the application. /// The main entry point for the application.
/// </summary> /// </summary>
@@ -27,13 +26,7 @@ namespace DiscordBot
Directory.CreateDirectory("./Data/Languages"); Directory.CreateDirectory("./Data/Languages");
Directory.CreateDirectory("./Data/Plugins/Commands"); Directory.CreateDirectory("./Data/Plugins/Commands");
Directory.CreateDirectory("./Data/Plugins/Events"); Directory.CreateDirectory("./Data/Plugins/Events");
Config.LoadConfig().Wait(); PreLoadComponents();
if (Config.ContainsKey("DeleteLogsAtStartup"))
if (Config.GetValue<bool>("DeleteLogsAtStartup"))
foreach (string file in Directory.GetFiles("./Output/Logs/"))
File.Delete(file);
if (!Config.ContainsKey("token") || Config.GetValue<string>("token") == null || Config.GetValue<string>("token")?.Length != 70) if (!Config.ContainsKey("token") || Config.GetValue<string>("token") == null || Config.GetValue<string>("token")?.Length != 70)
{ {
@@ -84,7 +77,6 @@ namespace DiscordBot
ConsoleCommandsHandler consoleCommandsHandler = new ConsoleCommandsHandler(discordbooter.client); ConsoleCommandsHandler consoleCommandsHandler = new ConsoleCommandsHandler(discordbooter.client);
if (loadPluginsOnStartup) consoleCommandsHandler.HandleCommand("lp"); if (loadPluginsOnStartup) consoleCommandsHandler.HandleCommand("lp");
if (listPluginsAtStartup) consoleCommandsHandler.HandleCommand("listplugs"); if (listPluginsAtStartup) consoleCommandsHandler.HandleCommand("listplugs");
if (listLanguagAtStartup) consoleCommandsHandler.HandleCommand("listlang");
Config.SaveConfig(); Config.SaveConfig();
while (true) while (true)
{ {
@@ -165,12 +157,20 @@ namespace DiscordBot
return; return;
} }
if (len == 3 && args[0] == "/download")
{
string url = args[1];
string location = args[2];
await ServerCom.DownloadFileAsync(url, location);
return;
}
if (len > 0 && (args.Contains("--cmd") || args.Contains("--args") || args.Contains("--nomessage"))) if (len > 0 && (args.Contains("--cmd") || args.Contains("--args") || args.Contains("--nomessage")))
{ {
if (args.Contains("lp") || args.Contains("loadplugins")) loadPluginsOnStartup = true; if (args.Contains("lp") || args.Contains("loadplugins")) loadPluginsOnStartup = true;
if (args.Contains("listplugs")) listPluginsAtStartup = true; if (args.Contains("listplugs")) listPluginsAtStartup = true;
if (args.Contains("listlang")) listLanguagAtStartup = true;
//if (args.Contains("--nomessage")) ShowStartupMessage = false;
len = 0; len = 0;
} }
@@ -182,6 +182,7 @@ namespace DiscordBot
return; return;
} }
Console.ForegroundColor = ConsoleColor.DarkYellow; Console.ForegroundColor = ConsoleColor.DarkYellow;
Console.WriteLine("Execute command interface noGUI\n\n"); Console.WriteLine("Execute command interface noGUI\n\n");
Console.WriteLine( Console.WriteLine(
@@ -240,11 +241,22 @@ namespace DiscordBot
Boot booter = await StartNoGUI(); Boot booter = await StartNoGUI();
await NoGUI(booter); await NoGUI(booter);
return; return;
default: default:
Console.WriteLine("Failed to execute command " + message[0]); Console.WriteLine("Failed to execute command " + message[0]);
break; break;
} }
} }
} }
private static async Task PreLoadComponents()
{
Config.LoadConfig().Wait();
if (Config.ContainsKey("DeleteLogsAtStartup"))
if (Config.GetValue<bool>("DeleteLogsAtStartup"))
foreach (string file in Directory.GetFiles("./Output/Logs/"))
File.Delete(file);
}
} }
} }

View File

@@ -1,12 +1,11 @@
using System.IO;
using Avalonia; using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.ApplicationLifetimes; using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Markup.Xaml; using Avalonia.Markup.Xaml;
using PluginManager.Others;
namespace DiscordBotGUI namespace DiscordBotGUI;
{
public partial class App : Application public class App : Application
{ {
public override void Initialize() public override void Initialize()
{ {
@@ -15,9 +14,8 @@ namespace DiscordBotGUI
public override void OnFrameworkInitializationCompleted() public override void OnFrameworkInitializationCompleted()
{ {
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop) { desktop.MainWindow = new AppUpdater() { Width = 300, Height = 50, WindowStartupLocation = Avalonia.Controls.WindowStartupLocation.CenterScreen }; } if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop) desktop.MainWindow = new AppUpdater { Width = 300, Height = 50, WindowStartupLocation = WindowStartupLocation.CenterScreen };
base.OnFrameworkInitializationCompleted(); base.OnFrameworkInitializationCompleted();
} }
} }
}

View File

@@ -7,10 +7,11 @@
Title="AppUpdater" Title="AppUpdater"
Background="Transparent" Background="Transparent"
TransparencyLevelHint="AcrylicBlur" TransparencyLevelHint="AcrylicBlur"
HasSystemDecorations="False"> SystemDecorations="BorderOnly">
<StackPanel Margin="10"> <StackPanel Margin="10">
<TextBlock x:Class="DiscordBotGUI.AppUpdater" x:Name="textBox1" Text="Checking for updates..." /> <TextBlock x:Class="DiscordBotGUI.AppUpdater" x:Name="textBox1" Text="Checking for updates..." />
<ProgressBar IsIndeterminate="True" x:Class="DiscordBotGUI.AppUpdater" x:Name="progressBar1" Foreground="Yellow" /> <ProgressBar IsIndeterminate="True" x:Class="DiscordBotGUI.AppUpdater" x:Name="progressBar1"
Foreground="Yellow" />
</StackPanel> </StackPanel>
</Window> </Window>

View File

@@ -11,7 +11,7 @@ namespace DiscordBotGUI
{ {
public partial class AppUpdater : Window public partial class AppUpdater : Window
{ {
private string _version; private string _version = "";
public AppUpdater() public AppUpdater()
{ {
@@ -149,7 +149,7 @@ namespace DiscordBotGUI
{ {
try try
{ {
string current_version = Config.GetValue("Version"); string current_version = Config.GetValue<string>("Version");
if (current_version == null) if (current_version == null)
if (!Config.SetValue("Version", "0")) if (!Config.SetValue("Version", "0"))
Config.AddValueToVariables("Version", "0", false); Config.AddValueToVariables("Version", "0", false);

View File

@@ -15,22 +15,25 @@
<MenuItem Header="Commands" x:Class="DiscordBotGUI.MainWindow" x:Name="commandsSettingMenuItem" /> <MenuItem Header="Commands" x:Class="DiscordBotGUI.MainWindow" x:Name="commandsSettingMenuItem" />
<MenuItem Header="Events" x:Class="DiscordBotGUI.MainWindow" x:Name="eventsSettingMenuItem" /> <MenuItem Header="Events" x:Class="DiscordBotGUI.MainWindow" x:Name="eventsSettingMenuItem" />
</MenuItem> </MenuItem>
<MenuItem Header="Application Variables" x:Class="DiscordBotGUI.MainWindow" x:Name="applicationVariablesMenuItem"/> <MenuItem Header="Application Variables" x:Class="DiscordBotGUI.MainWindow"
x:Name="applicationVariablesMenuItem" />
</Menu> </Menu>
<Label x:Class="DiscordBotGUI.MainWindow" x:Name="label1" Content="Discord Token" /> <Label x:Class="DiscordBotGUI.MainWindow" x:Name="label1" Content="Discord Token" />
<TextBox x:Class="DiscordBotGUI.MainWindow" x:Name="textBox1" IsReadOnly="True" TextAlignment="Center" Text="" /> <TextBox x:Class="DiscordBotGUI.MainWindow" x:Name="textBox1" IsReadOnly="True" TextAlignment="Center" Text="" />
<Label x:Class="DiscordBotGUI.MainWindow" x:Name="label2" Content="Bot Prefix" /> <Label x:Class="DiscordBotGUI.MainWindow" x:Name="label2" Content="Bot Prefix" />
<TextBox x:Class="DiscordBotGUI.MainWindow" x:Name="textBox2" TextAlignment="Center" HorizontalAlignment="Left" IsReadOnly="True" Text=""/> <TextBox x:Class="DiscordBotGUI.MainWindow" x:Name="textBox2" TextAlignment="Center" HorizontalAlignment="Left"
IsReadOnly="True" Text="" />
<Border Background="Black" Padding="0.5" Margin="25" /> <Border Background="Black" Padding="0.5" Margin="25" />
<Label x:Class="DiscordBotGUI.MainWindow" x:Name="label3" Content="Start Arguments: " /> <Label x:Class="DiscordBotGUI.MainWindow" x:Name="label3" Content="Start Arguments: " />
<TextBox x:Class="DiscordBotGUI.MainWindow" x:Name="textBox3" Width="250" TextAlignment="Center" HorizontalAlignment="Left" IsReadOnly="False" Text=""/> <TextBox x:Class="DiscordBotGUI.MainWindow" x:Name="textBox3" Width="250" TextAlignment="Center"
HorizontalAlignment="Left" IsReadOnly="False" Text="" />
<Label x:Class="DiscordBotGUI.MainWindow" x:Name="label4" Content="" Foreground="Red" Margin="10" /> <Label x:Class="DiscordBotGUI.MainWindow" x:Name="label4" Content="" Foreground="Red" Margin="10" />
<Button x:Class="DiscordBotGUI.MainWindow" x:Name="button1" HorizontalAlignment="Center" VerticalAlignment="Bottom" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" Width="200" Content="Start Bot" Margin="0,75,0,0" /> <Button x:Class="DiscordBotGUI.MainWindow" x:Name="button1" HorizontalAlignment="Center"
<Label x:Class="DiscordBotGUI.MainWindow" x:Name="label5" Content="" VerticalAlignment="Bottom" HorizontalAlignment="Right" Margin="0,0,0,0"/> VerticalAlignment="Bottom" HorizontalContentAlignment="Center" VerticalContentAlignment="Center"
Width="200" Content="Start Bot" Margin="0,75,0,0" />
<Label x:Class="DiscordBotGUI.MainWindow" x:Name="label5" Content="" VerticalAlignment="Bottom"
HorizontalAlignment="Right" Margin="0,0,0,0" />
</StackPanel> </StackPanel>
</Window> </Window>

View File

@@ -1,15 +1,13 @@
using Avalonia.Controls;
using System.Threading.Tasks;
using PluginManager.Others;
using System.IO;
using System;
using System.Diagnostics; using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;
using Avalonia.Controls;
using DiscordBotGUI.Settings; using DiscordBotGUI.Settings;
using Avalonia.Themes.Fluent;
using PluginManager; using PluginManager;
using PluginManager.Others;
namespace DiscordBotGUI;
namespace DiscordBotGUI
{
public partial class MainWindow : Window public partial class MainWindow : Window
{ {
public MainWindow() public MainWindow()
@@ -17,20 +15,17 @@ namespace DiscordBotGUI
InitializeComponent(); InitializeComponent();
LoadElements(); LoadElements();
} }
private void LoadElements() private void LoadElements()
{ {
textBox3.Watermark = "Insert start arguments"; textBox3.Watermark = "Insert start arguments";
if (File.Exists("./Version.txt")) label5.Content = Config.GetValue("Version"); if (File.Exists("./Version.txt")) label5.Content = Config.GetValue<string>("Version");
button1.Click += async (sender, e) => button1.Click += async (sender, e) =>
{ {
var token = textBox1.Text;
string token = textBox1.Text; var prefix = textBox2.Text;
string prefix = textBox2.Text; var args = "--nomessage " + textBox3.Text;
string args = "--nomessage " + textBox3.Text;
if (!((token.Length == 70 || token.Length == 59) && prefix.Length == 1)) if (!((token.Length == 70 || token.Length == 59) && prefix.Length == 1))
{ {
@@ -43,26 +38,24 @@ namespace DiscordBotGUI
Config.SetValue("token", token); Config.SetValue("token", token);
Config.SetValue("prefix", prefix); Config.SetValue("prefix", prefix);
RunDiscordBot(args); RunDiscordBot(args);
}; };
commandsSettingMenuItem.Click += (sender, e) => new Commands() /*{ Height = 200, Width = 550 }*/.ShowDialog(this); commandsSettingMenuItem.Click += (sender, e) => new Commands() /*{ Height = 200, Width = 550 }*/.ShowDialog(this);
eventsSettingMenuItem.Click += (sender, e) => new Events() /*{ Height = 200, Width = 550 }*/.ShowDialog(this); eventsSettingMenuItem.Click += (sender, e) => new Events() /*{ Height = 200, Width = 550 }*/.ShowDialog(this);
applicationVariablesMenuItem.Click += (sender, e) => new ApplicationVariables().ShowDialog(this); applicationVariablesMenuItem.Click += (sender, e) => new ApplicationVariables().ShowDialog(this);
string folder = $"{Functions.dataFolder}DiscordBotCore.data"; var folder = $"{Functions.dataFolder}DiscordBotCore.data";
Directory.CreateDirectory(Functions.dataFolder); Directory.CreateDirectory(Functions.dataFolder);
try try
{ {
string? botToken = Config.GetValue("token") as string; var botToken = Config.GetValue<string>("token");
string? botPrefix = Config.GetValue("prefix") as string; var botPrefix = Config.GetValue<string>("prefix");
if (botToken == null || botPrefix == null) if (botToken == null || botPrefix == null)
{ {
textBox1.IsReadOnly = false; textBox1.IsReadOnly = false;
textBox2.IsReadOnly = false; textBox2.IsReadOnly = false;
textBox1.Watermark = "Insert Bot Token Here"; textBox1.Watermark = "Insert Bot Token Here";
textBox2.Watermark = "Insert Bot Prefix Here"; textBox2.Watermark = "Insert Bot Prefix Here";
} }
else else
{ {
@@ -77,23 +70,17 @@ namespace DiscordBotGUI
textBox1.Watermark = "Insert Bot Token Here"; textBox1.Watermark = "Insert Bot Token Here";
textBox2.Watermark = "Insert Bot Prefix Here"; textBox2.Watermark = "Insert Bot Prefix Here";
} }
} }
private void RunDiscordBot(string args) private void RunDiscordBot(string args)
{ {
var os = Functions.GetOperatingSystem(); var os = Functions.GetOperatingSystem();
if (os == PluginManager.Others.OperatingSystem.WINDOWS) if (os == OperatingSystem.WINDOWS)
Process.Start("./DiscordBot.exe", args); Process.Start("./DiscordBot.exe", args);
else if (os == PluginManager.Others.OperatingSystem.LINUX) else if (os == OperatingSystem.LINUX)
Process.Start("./DiscordBot", args); Process.Start("./DiscordBot", args);
else if (os == PluginManager.Others.OperatingSystem.MAC_OS) else if (os == OperatingSystem.MAC_OS) Process.Start("./DiscordBot.app/Contents/MacOS/DiscordBot", args);
Process.Start("./DiscordBot.app/Contents/MacOS/DiscordBot", args);
Close(); Close();
return;
}
} }
} }

View File

@@ -1,13 +1,8 @@
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.ApplicationLifetimes;
using System; using System;
using System.IO; using Avalonia;
using System.Threading.Tasks;
namespace DiscordBotGUI;
namespace DiscordBotGUI
{
internal class Program internal class Program
{ {
// Initialization code. Don't use any Avalonia, third-party APIs or any // Initialization code. Don't use any Avalonia, third-party APIs or any
@@ -22,7 +17,8 @@ namespace DiscordBotGUI
// Avalonia configuration, don't remove; also used by visual designer. // Avalonia configuration, don't remove; also used by visual designer.
public static AppBuilder BuildAvaloniaApp() public static AppBuilder BuildAvaloniaApp()
=> AppBuilder.Configure<App>() {
return AppBuilder.Configure<App>()
.UsePlatformDetect() .UsePlatformDetect()
.LogToTrace(); .LogToTrace();
} }

View File

@@ -1,10 +1,8 @@
using Avalonia;
using Avalonia.Controls; using Avalonia.Controls;
using Avalonia.Markup.Xaml;
using PluginManager; using PluginManager;
namespace DiscordBotGUI.Settings namespace DiscordBotGUI.Settings;
{
public partial class ApplicationVariables : Window public partial class ApplicationVariables : Window
{ {
public ApplicationVariables() public ApplicationVariables()
@@ -18,14 +16,14 @@ namespace DiscordBotGUI.Settings
ClearEverything(); ClearEverything();
button1.Click += (sedner, e) => button1.Click += (sedner, e) =>
{ {
string key = textBox2.Text; var key = textBox2.Text;
if (Config.ContainsKey(key)) if (Config.ContainsKey(key))
{ {
ClearEverything(); ClearEverything();
return; return;
} }
string value = textBox3.Text; var value = textBox3.Text;
Config.AddValueToVariables(key, value, checkBox1.IsChecked!.Value); Config.AddValueToVariables(key, value, checkBox1.IsChecked!.Value);
ClearEverything(); ClearEverything();
}; };
@@ -41,4 +39,3 @@ namespace DiscordBotGUI.Settings
foreach (var kvp in allvars) textBox1.Text += kvp.Key + " => " + kvp.Value + "\n"; foreach (var kvp in allvars) textBox1.Text += kvp.Key + " => " + kvp.Value + "\n";
} }
} }
}

View File

@@ -12,10 +12,13 @@
<Label Content="Installed Commands" /> <Label Content="Installed Commands" />
<TextBox x:Class="DiscordBotGUI.Settings.Commands" x:Name="textbox1" TextAlignment="Left" IsReadOnly="True" /> <TextBox x:Class="DiscordBotGUI.Settings.Commands" x:Name="textbox1" TextAlignment="Left" IsReadOnly="True" />
<Label Content="Install another command" /> <Label Content="Install another command" />
<ComboBox x:Class="DiscordBotGUI.Settings.Commands" x:Name="comboBox1" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="0,10" Padding="200,0" /> <ComboBox x:Class="DiscordBotGUI.Settings.Commands" x:Name="comboBox1" HorizontalAlignment="Left"
VerticalAlignment="Top" Margin="0,10" Padding="200,0" />
<Button x:Class="DiscordBotGUI.Settings.Commands" x:Name="button1" HorizontalAlignment="Left" Content="Install" /> <Button x:Class="DiscordBotGUI.Settings.Commands" x:Name="button1" HorizontalAlignment="Left" Content="Install" />
<ProgressBar x:Class="DiscordBotGUI.Settings.Commands" x:Name="progressBar1" HorizontalAlignment="Left" Margin="0,10" Foreground="Yellow" /> <ProgressBar x:Class="DiscordBotGUI.Settings.Commands" x:Name="progressBar1" HorizontalAlignment="Left"
<Label x:Class="DiscordBotGUI.Settings.Commands" x:Name="label1" Content="" HorizontalAlignment="Left" Margin="0,10" /> Margin="0,10" Foreground="Yellow" />
<Label x:Class="DiscordBotGUI.Settings.Commands" x:Name="label1" Content="" HorizontalAlignment="Left"
Margin="0,10" />
</StackPanel> </StackPanel>
</Window> </Window>

View File

@@ -1,30 +1,26 @@
using Avalonia;
using Avalonia.Controls;
using Avalonia.Markup.Xaml;
using PluginManager.Others;
using System.Linq;
using System.Collections.Generic;
using System.Threading.Tasks;
using System; using System;
using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Avalonia.Controls;
using PluginManager.Online;
using PluginManager.Others;
using OperatingSystem = PluginManager.Others.OperatingSystem;
namespace DiscordBotGUI.Settings;
namespace DiscordBotGUI.Settings
{
public partial class Commands : Window public partial class Commands : Window
{ {
List<string> commands = new List<string>(); private List<string> commands = new();
public Commands() public Commands()
{ {
InitializeComponent(); InitializeComponent();
LoadData(); LoadData();
LoadComboBox(); LoadComboBox();
button1.Click += async (sender, e) => button1.Click += async (sender, e) => { await Download(); };
{
await Download();
};
} }
@@ -34,39 +30,42 @@ namespace DiscordBotGUI.Settings
{ {
textbox1.Text = ""; textbox1.Text = "";
Directory.CreateDirectory("./Data/Plugins/Commands/"); Directory.CreateDirectory("./Data/Plugins/Commands/");
var files = System.IO.Directory.EnumerateFiles("./Data/Plugins/Commands/"); var files = Directory.EnumerateFiles("./Data/Plugins/Commands/");
if (files == null || files.Count() < 1) return; if (files == null || files.Count() < 1) return;
foreach (var file in files) foreach (var file in files) textbox1.Text += file.Split('/')[file.Split('/').Length - 1] + "\n";
textbox1.Text += file.Split('/')[file.Split('/').Length - 1] + "\n"; }
catch
{
} }
catch { }
} }
private async void LoadComboBox() private async void LoadComboBox()
{ {
comboBox1.Items = null; comboBox1.Items = null;
commands = await PluginManager.Online.ServerCom.ReadTextFromFile("https://sethdiscordbot.000webhostapp.com/Storage/Discord%20Bot/Plugins"); commands = await ServerCom.ReadTextFromFile("https://sethdiscordbot.000webhostapp.com/Storage/Discord%20Bot/Plugins");
if (commands == null) return; if (commands == null) return;
string[] plugins = commands.ToArray(); var plugins = commands.ToArray();
string OS; string OS;
var OSG = Functions.GetOperatingSystem(); var OSG = Functions.GetOperatingSystem();
if (OSG == PluginManager.Others.OperatingSystem.WINDOWS) OS = "Windows"; if (OSG == OperatingSystem.WINDOWS)
else if (OSG == PluginManager.Others.OperatingSystem.LINUX) OS = "Linux"; OS = "Windows";
else OS = "MAC_OS"; else if (OSG == OperatingSystem.LINUX)
List<string> data = new List<string>(); OS = "Linux";
for (int i = 0; i < plugins.Length; i++) else
OS = "MAC_OS";
var data = new List<string>();
for (var i = 0; i < plugins.Length; i++)
{ {
if (!plugins[i].Contains(OS) || !plugins[i].Contains("Commands")) if (!plugins[i].Contains(OS) || !plugins[i].Contains("Commands")) continue;
continue;
string[] info = plugins[i].Split(','); var info = plugins[i].Split(',');
try try
{ {
if (Directory.EnumerateFiles("./Data/Plugins/Commands/").Any(x => x.EndsWith(info[0] + ".dll"))) continue;
if (System.IO.Directory.EnumerateFiles("./Data/Plugins/Commands/").Any(x => x.EndsWith(info[0] + ".dll"))) }
continue; catch
{
} }
catch { }
data.Add($"{info[0]} - {info[1]} - {info[2]}"); data.Add($"{info[0]} - {info[1]} - {info[2]}");
} }
@@ -77,12 +76,11 @@ namespace DiscordBotGUI.Settings
private async Task Download() private async Task Download()
{ {
if (comboBox1 == null || comboBox1.SelectedIndex == -1 || comboBox1.SelectedItem == null) if (comboBox1 == null || comboBox1.SelectedIndex == -1 || comboBox1.SelectedItem == null) return;
return; var pluginName = comboBox1?.SelectedItem?.ToString()?.Split('-')[0].Trim();
string? pluginName = comboBox1?.SelectedItem?.ToString()?.Split('-')[0].Trim();
if (pluginName == null) return; if (pluginName == null) return;
string? URL = (from s in commands var URL = (from s in commands
where s.StartsWith(pluginName) where s.StartsWith(pluginName)
select s.Split(',')[3].Trim()).FirstOrDefault(); select s.Split(',')[3].Trim()).FirstOrDefault();
@@ -101,24 +99,26 @@ namespace DiscordBotGUI.Settings
await Task.Delay(5000); await Task.Delay(5000);
label1.Content = ""; label1.Content = "";
} }
progressBar1.Value = value;
});
await PluginManager.Online.ServerCom.DownloadFileAsync(URL, "./Data/Plugins/Commands/" + pluginName + ".dll", progress); progressBar1.Value = value;
string? requirements = (from s in commands }
);
await ServerCom.DownloadFileAsync(URL, "./Data/Plugins/Commands/" + pluginName + ".dll", progress);
var requirements = (from s in commands
where s.StartsWith(pluginName) && s.Split(',').Length == 6 where s.StartsWith(pluginName) && s.Split(',').Length == 6
select s.Split(',')[5].Trim()).FirstOrDefault(); select s.Split(',')[5].Trim()).FirstOrDefault();
if (requirements == null) return; if (requirements == null) return;
List<string> req = await PluginManager.Online.ServerCom.ReadTextFromFile(requirements); var req = await ServerCom.ReadTextFromFile(requirements);
if (req == null) return; if (req == null) return;
foreach (var requirement in req) foreach (var requirement in req)
{ {
string[] info = requirement.Split(','); var info = requirement.Split(',');
pluginName = info[1]; pluginName = info[1];
progress.Report(0); progress.Report(0);
await PluginManager.Online.ServerCom.DownloadFileAsync(info[0], $"./{info[1]}", progress); await ServerCom.DownloadFileAsync(info[0], $"./{info[1]}", progress);
await Task.Delay(1000); await Task.Delay(1000);
@@ -127,7 +127,6 @@ namespace DiscordBotGUI.Settings
await Functions.ExtractArchive("./" + info[1], "./", progress); await Functions.ExtractArchive("./" + info[1], "./", progress);
await Task.Delay(1000); await Task.Delay(1000);
} }
} }
progress.Report(100f); progress.Report(100f);
@@ -135,4 +134,3 @@ namespace DiscordBotGUI.Settings
progressBar1.Value = 100; progressBar1.Value = 100;
} }
} }
}

View File

@@ -12,9 +12,12 @@
<Label Content="Installed Events" /> <Label Content="Installed Events" />
<TextBox x:Class="DiscordBotGUI.Settings.Events" x:Name="textbox1" TextAlignment="Left" IsReadOnly="True" /> <TextBox x:Class="DiscordBotGUI.Settings.Events" x:Name="textbox1" TextAlignment="Left" IsReadOnly="True" />
<Label Content="Install another Events" /> <Label Content="Install another Events" />
<ComboBox x:Class="DiscordBotGUI.Settings.Events" x:Name="comboBox1" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="0,10" Padding="200,0" /> <ComboBox x:Class="DiscordBotGUI.Settings.Events" x:Name="comboBox1" HorizontalAlignment="Left"
VerticalAlignment="Top" Margin="0,10" Padding="200,0" />
<Button x:Class="DiscordBotGUI.Settings.Events" x:Name="button1" HorizontalAlignment="Left" Content="Install" /> <Button x:Class="DiscordBotGUI.Settings.Events" x:Name="button1" HorizontalAlignment="Left" Content="Install" />
<ProgressBar x:Class="DiscordBotGUI.Settings.Events" x:Name="progressBar1" HorizontalAlignment="Left" Margin="0,10" Foreground="Yellow" /> <ProgressBar x:Class="DiscordBotGUI.Settings.Events" x:Name="progressBar1" HorizontalAlignment="Left"
<Label x:Class="DiscordBotGUI.Settings.Events" x:Name="label1" Content="" HorizontalAlignment="Left" Margin="0,10" /> Margin="0,10" Foreground="Yellow" />
<Label x:Class="DiscordBotGUI.Settings.Events" x:Name="label1" Content="" HorizontalAlignment="Left"
Margin="0,10" />
</StackPanel> </StackPanel>
</Window> </Window>

View File

@@ -1,33 +1,25 @@
using Avalonia;
using Avalonia.Controls;
using Avalonia.Markup.Xaml;
using PluginManager.Others;
using System.Collections.Generic;
using System; using System;
using System.Linq; using System.Collections.Generic;
using System.Reflection.Emit;
using System.Threading.Tasks;
using static PluginManager.Others.Console_Utilities;
using System.IO; using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Avalonia.Controls;
using PluginManager.Online;
using PluginManager.Others;
using OperatingSystem = PluginManager.Others.OperatingSystem;
namespace DiscordBotGUI.Settings;
namespace DiscordBotGUI.Settings
{
public partial class Events : Window public partial class Events : Window
{ {
List<string> events = new List<string>(); private List<string> events = new();
public Events() public Events()
{ {
InitializeComponent(); InitializeComponent();
LoadData(); LoadData();
LoadComboBox(); LoadComboBox();
button1.Click += async (sender, e) => button1.Click += async (sender, e) => { await Download(); };
{
await Download();
};
} }
private void LoadData() private void LoadData()
@@ -39,37 +31,42 @@ namespace DiscordBotGUI.Settings
Directory.CreateDirectory("./Data/Plugins/Events/"); Directory.CreateDirectory("./Data/Plugins/Events/");
textbox1.IsReadOnly = false; textbox1.IsReadOnly = false;
textbox1.Text = ""; textbox1.Text = "";
var files = System.IO.Directory.EnumerateFiles("./Data/Plugins/Events/"); var files = Directory.EnumerateFiles("./Data/Plugins/Events/");
if (files == null || files.Count() < 1) return; if (files == null || files.Count() < 1) return;
foreach (var file in files) foreach (var file in files) textbox1.Text += file.Split('/')[file.Split('/').Length - 1] + "\n";
textbox1.Text += file.Split('/')[file.Split('/').Length - 1] + "\n";
} }
catch { } catch
{
} }
}
private async void LoadComboBox() private async void LoadComboBox()
{ {
comboBox1.Items = null; comboBox1.Items = null;
events = await PluginManager.Online.ServerCom.ReadTextFromFile("https://sethdiscordbot.000webhostapp.com/Storage/Discord%20Bot/Plugins"); events = await ServerCom.ReadTextFromFile("https://sethdiscordbot.000webhostapp.com/Storage/Discord%20Bot/Plugins");
if (events == null) return; if (events == null) return;
string[] plugins = events.ToArray(); var plugins = events.ToArray();
string OS; string OS;
var OSG = Functions.GetOperatingSystem(); var OSG = Functions.GetOperatingSystem();
if (OSG == PluginManager.Others.OperatingSystem.WINDOWS) OS = "Windows"; if (OSG == OperatingSystem.WINDOWS)
else if (OSG == PluginManager.Others.OperatingSystem.LINUX) OS = "Linux"; OS = "Windows";
else OS = "MAC_OS"; else if (OSG == OperatingSystem.LINUX)
List<string> data = new List<string>(); OS = "Linux";
for (int i = 0; i < plugins.Length; i++) else
OS = "MAC_OS";
var data = new List<string>();
for (var i = 0; i < plugins.Length; i++)
{ {
if (!plugins[i].Contains(OS) || !plugins[i].Contains("Event")) if (!plugins[i].Contains(OS) || !plugins[i].Contains("Event")) continue;
continue;
string[] info = plugins[i].Split(','); var info = plugins[i].Split(',');
try try
{ {
if (System.IO.Directory.EnumerateFiles("./Data/Plugins/Events/").Any(x => x.EndsWith(info[0] + ".dll"))) if (Directory.EnumerateFiles("./Data/Plugins/Events/").Any(x => x.EndsWith(info[0] + ".dll"))) continue;
continue; }
catch
{
} }
catch { }
data.Add($"{info[0]} - {info[1]} - {info[2]}"); data.Add($"{info[0]} - {info[1]} - {info[2]}");
@@ -77,14 +74,14 @@ namespace DiscordBotGUI.Settings
comboBox1.Items = data; comboBox1.Items = data;
} }
private async Task Download() private async Task Download()
{ {
if (comboBox1 == null || comboBox1.SelectedIndex == -1 || comboBox1.SelectedItem == null) if (comboBox1 == null || comboBox1.SelectedIndex == -1 || comboBox1.SelectedItem == null) return;
return; var pluginName = comboBox1?.SelectedItem?.ToString()?.Split('-')[0].Trim();
string? pluginName = comboBox1?.SelectedItem?.ToString()?.Split('-')[0].Trim();
if (pluginName == null) return; if (pluginName == null) return;
string? URL = (from s in events var URL = (from s in events
where s.StartsWith(pluginName) where s.StartsWith(pluginName)
select s.Split(',')[3].Trim()).FirstOrDefault(); select s.Split(',')[3].Trim()).FirstOrDefault();
@@ -103,24 +100,26 @@ namespace DiscordBotGUI.Settings
await Task.Delay(5000); await Task.Delay(5000);
label1.Content = ""; label1.Content = "";
} }
progressBar1.Value = value;
});
await PluginManager.Online.ServerCom.DownloadFileAsync(URL, "./Data/Plugins/Events/" + pluginName + ".dll", progress); progressBar1.Value = value;
string? requirements = (from s in events }
);
await ServerCom.DownloadFileAsync(URL, "./Data/Plugins/Events/" + pluginName + ".dll", progress);
var requirements = (from s in events
where s.StartsWith(pluginName) && s.Split(',').Length == 6 where s.StartsWith(pluginName) && s.Split(',').Length == 6
select s.Split(',')[5].Trim()).FirstOrDefault(); select s.Split(',')[5].Trim()).FirstOrDefault();
if (requirements == null) return; if (requirements == null) return;
List<string> req = await PluginManager.Online.ServerCom.ReadTextFromFile(requirements); var req = await ServerCom.ReadTextFromFile(requirements);
if (req == null) return; if (req == null) return;
foreach (var requirement in req) foreach (var requirement in req)
{ {
string[] info = requirement.Split(','); var info = requirement.Split(',');
pluginName = info[1]; pluginName = info[1];
progress.Report(0); progress.Report(0);
await PluginManager.Online.ServerCom.DownloadFileAsync(info[0], $"./{info[1]}", progress); await ServerCom.DownloadFileAsync(info[0], $"./{info[1]}", progress);
await Task.Delay(1000); await Task.Delay(1000);
@@ -129,11 +128,8 @@ namespace DiscordBotGUI.Settings
await Functions.ExtractArchive("./" + info[1], "./", progress); await Functions.ExtractArchive("./" + info[1], "./", progress);
await Task.Delay(1000); await Task.Delay(1000);
} }
} }
label1.Content = ""; label1.Content = "";
}
} }
} }

View File

@@ -19,13 +19,13 @@ namespace EVE_LevelingSystem
Config.AddValueToVariables("LevelingSystemPath", "./Data/Resources/LevelingSystem", true); Config.AddValueToVariables("LevelingSystemPath", "./Data/Resources/LevelingSystem", true);
Config.AddValueToVariables("LevelingSystemSettingsFile", "./Data/Resources/LevelingSystemSettings.txt", true); Config.AddValueToVariables("LevelingSystemSettingsFile", "./Data/Resources/LevelingSystemSettings.txt", true);
if (!File.Exists(Config.GetValue("LevelingSystemSettingsFile"))) if (!File.Exists(Config.GetValue<string>("LevelingSystemSettingsFile")))
{ {
globalSettings = new Settings { TimeToWaitBetweenMessages = 5 }; globalSettings = new Settings { TimeToWaitBetweenMessages = 5 };
await Functions.SaveToJsonFile<Settings>(Config.GetValue("LevelingSystemSettingsFile"), globalSettings); await Functions.SaveToJsonFile<Settings>(Config.GetValue<string>("LevelingSystemSettingsFile"), globalSettings);
} }
else else
globalSettings = await Functions.ConvertFromJson<Settings>(Config.GetValue("LevelingSystemSettingsFile")); globalSettings = await Functions.ConvertFromJson<Settings>(Config.GetValue<string>("LevelingSystemSettingsFile"));
// Console.WriteLine(globalSettings.TimeToWaitBetweenMessages); // Console.WriteLine(globalSettings.TimeToWaitBetweenMessages);
client.MessageReceived += ClientOnMessageReceived; client.MessageReceived += ClientOnMessageReceived;
@@ -33,21 +33,21 @@ namespace EVE_LevelingSystem
private async Task ClientOnMessageReceived(SocketMessage arg) private async Task ClientOnMessageReceived(SocketMessage arg)
{ {
if (arg.Author.IsBot || arg.IsTTS || arg.Content.StartsWith(Config.GetValue("prefix"))) return; if (arg.Author.IsBot || arg.IsTTS || arg.Content.StartsWith(Config.GetValue<string>("prefix"))) return;
string userID = arg.Author.Id.ToString(); string userID = arg.Author.Id.ToString();
User user; User user;
if (File.Exists($"{Config.GetValue("LevelingSystemPath")}/{userID}.dat")) if (File.Exists($"{Config.GetValue<string>("LevelingSystemPath")}/{userID}.dat"))
{ {
user = await Functions.ConvertFromJson<User>(Config.GetValue("LevelingSystemPath")! + $"/{userID}.dat"); user = await Functions.ConvertFromJson<User>(Config.GetValue<string>("LevelingSystemPath")! + $"/{userID}.dat");
// Console.WriteLine(Config.GetValue("LevelingSystemPath")); // Console.WriteLine(Config.GetValue("LevelingSystemPath"));
if (user.AddEXP()) await arg.Channel.SendMessageAsync($"{arg.Author.Mention} is now level {user.CurrentLevel}"); if (user.AddEXP()) await arg.Channel.SendMessageAsync($"{arg.Author.Mention} is now level {user.CurrentLevel}");
await Functions.SaveToJsonFile(Config.GetValue("LevelingSystemPath") + $"/{userID}.dat", user); await Functions.SaveToJsonFile(Config.GetValue<string>("LevelingSystemPath") + $"/{userID}.dat", user);
return; return;
} }
user = new User() { CurrentEXP = 0, CurrentLevel = 1, RequiredEXPToLevelUp = LevelCalculator.GetNextLevelRequiredEXP(1), userID = userID }; user = new User() { CurrentEXP = 0, CurrentLevel = 1, RequiredEXPToLevelUp = LevelCalculator.GetNextLevelRequiredEXP(1), userID = userID };
if (user.AddEXP()) await arg.Channel.SendMessageAsync($"{arg.Author.Mention} is now level {user.CurrentLevel}"); if (user.AddEXP()) await arg.Channel.SendMessageAsync($"{arg.Author.Mention} is now level {user.CurrentLevel}");
await Functions.SaveToJsonFile($"{Config.GetValue("LevelingSystemPath")}/{userID}.dat", user); await Functions.SaveToJsonFile($"{Config.GetValue<string>("LevelingSystemPath")}/{userID}.dat", user);
} }
} }
} }

View File

@@ -1,16 +1,9 @@
using System; namespace EVE_LevelingSystem.LevelingSystemCore;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EVE_LevelingSystem.LevelingSystemCore
{
public class User public class User
{ {
public string userID { get; set; } public string userID { get; set; }
public int CurrentLevel { get; set; } public int CurrentLevel { get; set; }
public Int64 CurrentEXP { get; set; } public long CurrentEXP { get; set; }
public Int64 RequiredEXPToLevelUp { get; set; } public long RequiredEXPToLevelUp { get; set; }
}
} }

View File

@@ -1,10 +1,9 @@
using Discord; using Discord;
using Discord.Audio; using Discord.Audio;
using MusicCommands; using MusicCommands;
namespace CMD_Utils.Music namespace CMD_Utils.Music;
{
internal static class Data internal static class Data
{ {
internal static IAudioClient audioClient = null; internal static IAudioClient audioClient = null;
@@ -12,4 +11,3 @@ namespace CMD_Utils.Music
internal static MusicPlayer CurrentlyRunning = null; internal static MusicPlayer CurrentlyRunning = null;
} }
}

View File

@@ -1,17 +1,10 @@
using Discord.Commands; using Discord.Commands;
using Discord.WebSocket; using Discord.WebSocket;
using PluginManager.Interfaces; using PluginManager.Interfaces;
using System; namespace CMD_Utils.Music;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CMD_Utils.Music internal class Leave : DBCommand
{
class Leave : DBCommand
{ {
public string Command => "leave"; public string Command => "leave";
@@ -36,4 +29,3 @@ namespace CMD_Utils.Music
} }
} }
} }
}

View File

@@ -1,21 +1,15 @@
using CMD_Utils.Music; using System;
using PluginManager.Others;
using System;
using System.IO; using System.IO;
using System.Net;
using System.Net.Http; using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using CMD_Utils.Music;
using PluginManager.Others;
namespace MusicCommands namespace MusicCommands;
internal class MusicPlayer
{ {
class MusicPlayer
{
public Stream inputStream { get; private set; } // from FFMPEG
public Stream outputStream { get; private set; } // to Voice Channel
public MusicPlayer(Stream input, Stream output) public MusicPlayer(Stream input, Stream output)
{ {
inputStream = input; inputStream = input;
@@ -28,8 +22,12 @@ namespace MusicCommands
outputStream = output; outputStream = output;
} }
public Stream inputStream { get; } // from FFMPEG
public Stream outputStream { get; } // to Voice Channel
public bool Paused { get; set; } public bool Paused { get; set; }
private bool _stop { get; set; } private bool _stop { get; set; }
public void Stop() public void Stop()
{ {
_stop = true; _stop = true;
@@ -37,7 +35,6 @@ namespace MusicCommands
public async Task StartSendAudioFromLink(string URL) public async Task StartSendAudioFromLink(string URL)
{ {
/* using (HttpClient client = new HttpClient()) /* using (HttpClient client = new HttpClient())
using (HttpResponseMessage response = await client.GetAsync(URL)) using (HttpResponseMessage response = await client.GetAsync(URL))
using (var content = response.Content) using (var content = response.Content)
@@ -47,13 +44,13 @@ namespace MusicCommands
Stream ms = new MemoryStream(); Stream ms = new MemoryStream();
int bsize = 512; var bsize = 512;
new Thread(async delegate(object o) new Thread(async delegate(object o)
{ {
var response = await new HttpClient().GetAsync(URL); var response = await new HttpClient().GetAsync(URL);
using (var stream = await response.Content.ReadAsStreamAsync()) using (var stream = await response.Content.ReadAsStreamAsync())
{ {
byte[] buffer = new byte[bsize]; var buffer = new byte[bsize];
int read; int read;
while ((read = stream.Read(buffer, 0, buffer.Length)) > 0) while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
{ {
@@ -63,7 +60,8 @@ namespace MusicCommands
ms.Position = pos; ms.Position = pos;
} }
} }
}).Start(); }
).Start();
Console.Write("Reading data: "); Console.Write("Reading data: ");
while (ms.Length < bsize * 10) while (ms.Length < bsize * 10)
{ {
@@ -71,6 +69,7 @@ namespace MusicCommands
Console.Title = "Reading data: " + ms.Length + " bytes read of " + bsize * 10; Console.Title = "Reading data: " + ms.Length + " bytes read of " + bsize * 10;
Console.Write("."); Console.Write(".");
} }
Console.WriteLine("\nDone"); Console.WriteLine("\nDone");
ms.Position = 0; ms.Position = 0;
@@ -80,14 +79,13 @@ namespace MusicCommands
while (!_stop) while (!_stop)
{ {
if (Paused) continue; if (Paused) continue;
byte[] buffer = new byte[bsize]; var buffer = new byte[bsize];
int read = await ms.ReadAsync(buffer, 0, buffer.Length); var read = await ms.ReadAsync(buffer, 0, buffer.Length);
if (read > 0) if (read > 0)
await outputStream.WriteAsync(buffer, 0, read); await outputStream.WriteAsync(buffer, 0, read);
else break; else
break;
} }
} }
public async Task StartSendAudio() public async Task StartSendAudio()
@@ -97,8 +95,8 @@ namespace MusicCommands
while (!_stop) while (!_stop)
{ {
if (Paused) continue; if (Paused) continue;
int bsize = 512; var bsize = 512;
byte[] buffer = new byte[bsize]; var buffer = new byte[bsize];
var bcount = await inputStream.ReadAsync(buffer, 0, bsize); var bcount = await inputStream.ReadAsync(buffer, 0, bsize);
if (bcount <= 0) if (bcount <= 0)
{ {
@@ -106,6 +104,7 @@ namespace MusicCommands
Data.CurrentlyRunning = null; Data.CurrentlyRunning = null;
break; break;
} }
try try
{ {
await outputStream.WriteAsync(buffer, 0, bcount); await outputStream.WriteAsync(buffer, 0, bcount);
@@ -115,8 +114,6 @@ namespace MusicCommands
await outputStream.FlushAsync(); await outputStream.FlushAsync();
Functions.WriteLogFile(ex.ToString()); Functions.WriteLogFile(ex.ToString());
} }
}
} }
} }
} }

View File

@@ -1,11 +1,10 @@
using Discord.Commands; using Discord.Commands;
using Discord.WebSocket; using Discord.WebSocket;
using PluginManager.Interfaces; using PluginManager.Interfaces;
namespace CMD_Utils.Music namespace CMD_Utils.Music;
{
class Pause : DBCommand internal class Pause : DBCommand
{ {
public string Command => "pause"; public string Command => "pause";
@@ -24,4 +23,3 @@ namespace CMD_Utils.Music
Data.CurrentlyRunning.Paused = true; Data.CurrentlyRunning.Paused = true;
} }
} }
}

View File

@@ -1,20 +1,17 @@
using Discord; using System;
using System.Diagnostics;
using System.IO;
using Discord;
using Discord.Audio; using Discord.Audio;
using Discord.Commands; using Discord.Commands;
using Discord.WebSocket; using Discord.WebSocket;
using MusicCommands; using MusicCommands;
using PluginManager.Interfaces; using PluginManager.Interfaces;
using PluginManager.Others; using PluginManager.Others;
using System; namespace CMD_Utils.Music;
using System.Diagnostics;
using System.IO;
namespace CMD_Utils.Music internal class Play : DBCommand
{
class Play : DBCommand
{ {
public string Command => "fplay"; public string Command => "fplay";
@@ -30,8 +27,8 @@ namespace CMD_Utils.Music
public async void Execute(SocketCommandContext context, SocketMessage message, DiscordSocketClient client, bool isDM) public async void Execute(SocketCommandContext context, SocketMessage message, DiscordSocketClient client, bool isDM)
{ {
string path = "./Music"; var path = "./Music";
string FileName = Functions.GetArguments(message).ToArray().MergeStrings(0); var FileName = Functions.GetArguments(message).ToArray().MergeStrings(0);
path += "/" + FileName + ".mp3"; path += "/" + FileName + ".mp3";
if (!File.Exists(path)) if (!File.Exists(path))
{ {
@@ -41,7 +38,11 @@ namespace CMD_Utils.Music
Data.voiceChannel = (context.User as IGuildUser)?.VoiceChannel; Data.voiceChannel = (context.User as IGuildUser)?.VoiceChannel;
if (Data.voiceChannel == null) { await context.Channel.SendMessageAsync("User must be in a voice channel, or a voice channel must be passed as an argument."); return; } if (Data.voiceChannel == null)
{
await context.Channel.SendMessageAsync("User must be in a voice channel, or a voice channel must be passed as an argument.");
return;
}
Data.audioClient = await Data.voiceChannel.ConnectAsync(); Data.audioClient = await Data.voiceChannel.ConnectAsync();
@@ -49,8 +50,7 @@ namespace CMD_Utils.Music
using (var output = ffmpeg.StandardOutput.BaseStream) using (var output = ffmpeg.StandardOutput.BaseStream)
using (var discord = Data.audioClient.CreatePCMStream(AudioApplication.Mixed)) using (var discord = Data.audioClient.CreatePCMStream(AudioApplication.Mixed))
{ {
if (Data.CurrentlyRunning != null) if (Data.CurrentlyRunning != null) Data.CurrentlyRunning.Stop();
Data.CurrentlyRunning.Stop();
Data.CurrentlyRunning = new MusicPlayer(output, discord); Data.CurrentlyRunning = new MusicPlayer(output, discord);
await Data.CurrentlyRunning.StartSendAudio(); await Data.CurrentlyRunning.StartSendAudio();
} }
@@ -58,13 +58,6 @@ namespace CMD_Utils.Music
private Process CreateStream(string path) private Process CreateStream(string path)
{ {
return Process.Start(new ProcessStartInfo return Process.Start(new ProcessStartInfo { FileName = "ffmpeg", Arguments = $"-hide_banner -loglevel panic -i \"{path}\" -ac 2 -f s16le -ar 48000 pipe:1", UseShellExecute = false, RedirectStandardOutput = true });
{
FileName = "ffmpeg",
Arguments = $"-hide_banner -loglevel panic -i \"{path}\" -ac 2 -f s16le -ar 48000 pipe:1",
UseShellExecute = false,
RedirectStandardOutput = true,
});
}
} }
} }

View File

@@ -1,19 +1,11 @@
using CMD_Utils.Music; using CMD_Utils.Music;
using Discord.Commands; using Discord.Commands;
using Discord.WebSocket; using Discord.WebSocket;
using PluginManager.Interfaces; using PluginManager.Interfaces;
using System; namespace MusicCommands;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MusicCommands internal class Unpause : DBCommand
{
class Unpause : DBCommand
{ {
public string Command => "unpause"; public string Command => "unpause";
@@ -32,4 +24,3 @@ namespace MusicCommands
Data.CurrentlyRunning.Paused = false; Data.CurrentlyRunning.Paused = false;
} }
} }
}

View File

@@ -1,14 +1,13 @@
using CMD_Utils.Music; using CMD_Utils.Music;
using Discord;
using Discord.Audio; using Discord.Audio;
using Discord.Commands; using Discord.Commands;
using Discord.WebSocket; using Discord.WebSocket;
using Discord;
using PluginManager.Interfaces; using PluginManager.Interfaces;
namespace MusicCommands namespace MusicCommands;
{
class lplay : DBCommand internal class lplay : DBCommand
{ {
public string Command => "lplay"; public string Command => "lplay";
@@ -24,7 +23,7 @@ namespace MusicCommands
public async void Execute(SocketCommandContext context, SocketMessage message, DiscordSocketClient client, bool isDM) public async void Execute(SocketCommandContext context, SocketMessage message, DiscordSocketClient client, bool isDM)
{ {
string URL = message.Content.Split(' ')[1]; var URL = message.Content.Split(' ')[1];
if (!URL.EndsWith(".mp3") && !URL.EndsWith(".wav") && !URL.EndsWith(".flac") && !URL.EndsWith(".ogg")) if (!URL.EndsWith(".mp3") && !URL.EndsWith(".wav") && !URL.EndsWith(".flac") && !URL.EndsWith(".ogg"))
{ {
await message.Channel.SendMessageAsync("Invalid URL"); await message.Channel.SendMessageAsync("Invalid URL");
@@ -32,21 +31,20 @@ namespace MusicCommands
} }
Data.voiceChannel = (context.User as IGuildUser)?.VoiceChannel; Data.voiceChannel = (context.User as IGuildUser)?.VoiceChannel;
if (Data.voiceChannel == null) { await context.Channel.SendMessageAsync("User must be in a voice channel, or a voice channel must be passed as an argument."); return; } if (Data.voiceChannel == null)
{
await context.Channel.SendMessageAsync("User must be in a voice channel, or a voice channel must be passed as an argument.");
return;
}
Data.audioClient = await Data.voiceChannel.ConnectAsync(); Data.audioClient = await Data.voiceChannel.ConnectAsync();
using (var discord = Data.audioClient.CreatePCMStream(AudioApplication.Mixed)) using (var discord = Data.audioClient.CreatePCMStream(AudioApplication.Mixed))
{ {
await message.Channel.SendMessageAsync("Loading..."); await message.Channel.SendMessageAsync("Loading...");
Data.CurrentlyRunning = new MusicPlayer(discord); Data.CurrentlyRunning = new MusicPlayer(discord);
await Data.CurrentlyRunning.StartSendAudioFromLink(URL); await Data.CurrentlyRunning.StartSendAudioFromLink(URL);
} }
} }
}
} }

View File

@@ -16,7 +16,7 @@ namespace PluginManager
public static class Config public static class Config
{ {
private static AppConfig appConfig = null; private static AppConfig appConfig;
public static bool AddValueToVariables<T>(string key, T value, bool isProtected) public static bool AddValueToVariables<T>(string key, T value, bool isProtected)
{ {

View File

@@ -1,5 +1,8 @@
namespace PluginManager.Interfaces using Discord.Commands;
{ using Discord.WebSocket;
namespace PluginManager.Interfaces;
public interface DBCommand public interface DBCommand
{ {
/// <summary> /// <summary>
@@ -41,9 +44,8 @@
/// <param name="message">The message that the user types</param> /// <param name="message">The message that the user types</param>
/// <param name="client">The discord client of the bot</param> /// <param name="client">The discord client of the bot</param>
/// <param name="isDM">true if the message was sent from DM, otherwise false. It is always false if canUseDM is false</param> /// <param name="isDM">true if the message was sent from DM, otherwise false. It is always false if canUseDM is false</param>
void Execute(Discord.Commands.SocketCommandContext context, void Execute(SocketCommandContext context,
Discord.WebSocket.SocketMessage message, SocketMessage message,
Discord.WebSocket.DiscordSocketClient client, DiscordSocketClient client,
bool isDM); bool isDM);
} }
}

View File

@@ -1,7 +1,7 @@
using Discord.WebSocket; using Discord.WebSocket;
namespace PluginManager.Interfaces namespace PluginManager.Interfaces;
{
public interface DBEvent public interface DBEvent
{ {
/// <summary> /// <summary>
@@ -20,4 +20,3 @@ namespace PluginManager.Interfaces
/// <param name="client">The discord bot client</param> /// <param name="client">The discord bot client</param>
void Start(DiscordSocketClient client); void Start(DiscordSocketClient client);
} }
}

View File

@@ -1,16 +1,9 @@
using Discord.WebSocket; using System.Collections.Generic;
using Discord.WebSocket;
using PluginManager.Loaders;
using PluginManager.Others; using PluginManager.Others;
using System; namespace PluginManager.Items;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PluginManager.Items
{
internal class Command internal class Command
{ {
/// <summary> /// <summary>
@@ -18,34 +11,34 @@ namespace PluginManager.Items
/// </summary> /// </summary>
public SocketUser? Author; public SocketUser? Author;
/// <summary>
/// The list of arguments
/// </summary>
public List<string> Arguments { get; private set; }
/// <summary>
/// The command that is executed
/// </summary>
public string CommandName { get; private set; }
/// <summary>
/// The prefix that is used for the command
/// </summary>
public char PrefixUsed { get; private set; }
/// <summary> /// <summary>
/// The Command class contructor /// The Command class contructor
/// </summary> /// </summary>
/// <param name="message">The message that was sent</param> /// <param name="message">The message that was sent</param>
public Command(SocketMessage message) public Command(SocketMessage message)
{ {
this.Author = message.Author; Author = message.Author;
string[] data = message.Content.Split(' '); var data = message.Content.Split(' ');
if (data.Length > 1) if (data.Length > 1)
this.Arguments = new List<string>(data.MergeStrings(1).Split(' ')); Arguments = new List<string>(data.MergeStrings(1).Split(' '));
else this.Arguments = new List<string>(); else
this.CommandName = data[0].Substring(1); Arguments = new List<string>();
this.PrefixUsed = data[0][0]; 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; }
} }

View File

@@ -1,24 +1,23 @@
using Discord.WebSocket; using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Discord.WebSocket;
using PluginManager.Loaders; using PluginManager.Loaders;
using PluginManager.Online; using PluginManager.Online;
using PluginManager.Others; using PluginManager.Others;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading.Tasks;
using System.Threading;
using System.Linq;
using System.Reflection.Metadata.Ecma335;
using Newtonsoft.Json.Converters;
namespace PluginManager.Items namespace PluginManager.Items;
{
public class ConsoleCommandsHandler public class ConsoleCommandsHandler
{ {
private static PluginsManager manager = new("https://sethdiscordbot.000webhostapp.com/Storage/Discord%20Bot/Plugins"); private static readonly PluginsManager manager = new("https://sethdiscordbot.000webhostapp.com/Storage/Discord%20Bot/Plugins");
public static List<Tuple<string, string, Action<string[]>>>? commandList = new List<Tuple<string, string, Action<string[]>>>(); public static List<Tuple<string, string, Action<string[]>>> commandList = new();
private DiscordSocketClient client; private readonly DiscordSocketClient? client;
public ConsoleCommandsHandler(DiscordSocketClient client) public ConsoleCommandsHandler(DiscordSocketClient client)
{ {
@@ -29,33 +28,29 @@ namespace PluginManager.Items
private void InitializeBasicCommands() private void InitializeBasicCommands()
{ {
var pluginsLoaded = false;
bool pluginsLoaded = false;
commandList.Clear(); commandList.Clear();
AddCommand("help", "Show help", (args) => AddCommand("help", "Show help", args =>
{ {
if (args.Length <= 1) if (args.Length <= 1)
{ {
Console.WriteLine("Available commands:"); Console.WriteLine("Available commands:");
foreach (var command in commandList) foreach (var command in commandList) Console.WriteLine("\t" + command.Item1 + " - " + command.Item2);
{
Console.WriteLine("\t" + command.Item1 + " - " + command.Item2);
}
} }
else else
{ {
foreach (var command in commandList) foreach (var command in commandList)
{
if (command.Item1 == args[1]) if (command.Item1 == args[1])
{ {
Console.WriteLine(command.Item2); Console.WriteLine(command.Item2);
return; return;
} }
}
Console.WriteLine("Command not found"); Console.WriteLine("Command not found");
} }
}); }
);
AddCommand("lp", "Load plugins", () => AddCommand("lp", "Load plugins", () =>
{ {
@@ -64,35 +59,31 @@ namespace PluginManager.Items
loader.onCMDLoad += (name, typeName, success, exception) => loader.onCMDLoad += (name, typeName, success, exception) =>
{ {
Console.ForegroundColor = ConsoleColor.Green; Console.ForegroundColor = ConsoleColor.Green;
if (name == null || name.Length < 2) if (name == null || name.Length < 2) name = typeName;
name = typeName;
if (success) if (success)
Console.WriteLine("[CMD] Successfully loaded command : " + name); Console.WriteLine("[CMD] Successfully loaded command : " + name);
else else
Console.WriteLine("[CMD] Failed to load command : " + name + " because " + exception.Message); Console.WriteLine("[CMD] Failed to load command : " + name + " because " + exception!.Message);
Console.ForegroundColor = ConsoleColor.Red; Console.ForegroundColor = ConsoleColor.Red;
}; };
loader.onEVELoad += (name, typeName, success, exception) => loader.onEVELoad += (name, typeName, success, exception) =>
{ {
if (name == null || name.Length < 2) if (name == null || name.Length < 2) name = typeName;
name = typeName;
Console.ForegroundColor = ConsoleColor.Green; Console.ForegroundColor = ConsoleColor.Green;
if (success) if (success)
Console.WriteLine("[EVENT] Successfully loaded event : " + name); Console.WriteLine("[EVENT] Successfully loaded event : " + name);
else else
Console.WriteLine("[EVENT] Failed to load event : " + name + " because " + exception.Message); Console.WriteLine("[EVENT] Failed to load event : " + name + " because " + exception!.Message);
Console.ForegroundColor = ConsoleColor.Red; Console.ForegroundColor = ConsoleColor.Red;
}; };
loader.LoadPlugins(); loader.LoadPlugins();
pluginsLoaded = true; pluginsLoaded = true;
}); }
);
AddCommand("listplugs", "list available plugins", async () => AddCommand("listplugs", "list available plugins", async () => { await manager.ListAvailablePlugins(); });
{
await manager.ListAvailablePlugins();
});
AddCommand("dwplug", "download plugin", async (args) => AddCommand("dwplug", "download plugin", async args =>
{ {
if (args.Length == 1) if (args.Length == 1)
{ {
@@ -100,27 +91,30 @@ namespace PluginManager.Items
return; return;
} }
string name = args.MergeStrings(1); var name = args.MergeStrings(1);
// info[0] = plugin type // info[0] = plugin type
// info[1] = plugin link // info[1] = plugin link
// info[2] = if others are required, or string.Empty if none // info[2] = if others are required, or string.Empty if none
string[] info = await manager.GetPluginLinkByName(name); var info = await manager.GetPluginLinkByName(name);
if (info[1] == null) // link is null if (info[1] == null) // link is null
{ {
if (name == "") if (name == "")
{ {
Console_Utilities.WriteColorText($"Name is invalid"); Console_Utilities.WriteColorText("Name is invalid");
return; return;
} }
Console_Utilities.WriteColorText($"Failed to find plugin &b{name} &c!" +
$" Use &glistplugs &ccommand to display all available plugins !");
return;
Console_Utilities.WriteColorText($"Failed to find plugin &b{name} &c!" +
" Use &glistplugs &ccommand to display all available plugins !"
);
return;
} }
string path; string path;
if (info[0] == "Command" || info[0] == "Event") if (info[0] == "Command" || info[0] == "Event")
path = "./Data/Plugins/" + info[0] + "s/" + name + ".dll"; path = "./Data/Plugins/" + info[0] + "s/" + name + ".dll";
else path = $"./{info[1].Split('/')[info[1].Split('/').Length - 1]}"; else
path = $"./{info[1].Split('/')[info[1].Split('/').Length - 1]}";
await ServerCom.DownloadFileAsync(info[1], path); await ServerCom.DownloadFileAsync(info[1], path);
Console.WriteLine("\n"); Console.WriteLine("\n");
@@ -130,47 +124,41 @@ namespace PluginManager.Items
{ {
Console.WriteLine($"Downloading requirements for plugin : {name}"); Console.WriteLine($"Downloading requirements for plugin : {name}");
List<string> lines = await ServerCom.ReadTextFromFile(info[2]); var lines = await ServerCom.ReadTextFromFile(info[2]);
foreach (var line in lines) foreach (var line in lines)
{ {
string[] split = line.Split(','); var split = line.Split(',');
Console.WriteLine($"\nDownloading item: {split[1]}"); Console.WriteLine($"\nDownloading item: {split[1]}");
await ServerCom.DownloadFileAsync(split[0], "./" + split[1]); await ServerCom.DownloadFileAsync(split[0], "./" + split[1]);
Console.WriteLine(); Console.WriteLine();
if (split[0].EndsWith(".zip")) if (split[0].EndsWith(".zip"))
{ {
Console.WriteLine($"Extracting {split[1]}"); Console.WriteLine($"Extracting {split[1]}");
double proc = 0d; var proc = 0d;
bool isExtracting = true; var isExtracting = true;
Console_Utilities.ProgressBar bar = new Console_Utilities.ProgressBar(100, ""); var bar = new Console_Utilities.ProgressBar { Max = 100, Color = ConsoleColor.Green };
IProgress<float> extractProgress = new Progress<float>(value => IProgress<float> extractProgress = new Progress<float>(value => { proc = value; });
{
proc = value;
});
new Thread(new Task(() => new Thread(new Task(() =>
{ {
while (isExtracting) while (isExtracting)
{ {
bar.Update((int)proc); bar.Update((int)proc);
if (proc >= 99.9f) if (proc >= 99.9f) break;
break;
Thread.Sleep(500); Thread.Sleep(500);
} }
}).Start).Start(); }
).Start
).Start();
await Functions.ExtractArchive("./" + split[1], "./", extractProgress); await Functions.ExtractArchive("./" + split[1], "./", extractProgress);
bar.Update(100); bar.Update(100);
isExtracting = false; isExtracting = false;
await Task.Delay(1000); await Task.Delay(1000);
bar.Update(100); bar.Update(100);
Console.WriteLine("\n"); Console.WriteLine("\n");
System.IO.File.Delete("./" + split[1]); File.Delete("./" + split[1]);
} }
if (name == "DBUI") if (name == "DBUI")
@@ -183,45 +171,46 @@ namespace PluginManager.Items
} }
} }
} }
Console.WriteLine(); Console.WriteLine();
} }
}
}); );
AddCommand("value", "read value from VariableStack", (args) => AddCommand("value", "read value from VariableStack", args =>
{ {
if (args.Length != 2) return; if (args.Length != 2) return;
if (!Config.ContainsKey(args[1])) return; if (!Config.ContainsKey(args[1])) return;
string data = Config.GetValue<string>(args[1]); var data = Config.GetValue<string>(args[1]);
Console.WriteLine($"{args[1]} => {data}"); Console.WriteLine($"{args[1]} => {data}");
} }
); );
AddCommand("add", "add variable to the system variables\nadd [key] [value] [isReadOnly=true/false]", async (args) => AddCommand("add", "add variable to the system variables\nadd [key] [value] [isReadOnly=true/false]", async args =>
{ {
if (args.Length < 4) return; if (args.Length < 4) return;
string key = args[1]; var key = args[1];
string value = args[2]; var value = args[2];
bool isReadOnly = args[3].Equals("true", StringComparison.CurrentCultureIgnoreCase); var isReadOnly = args[3].Equals("true", StringComparison.CurrentCultureIgnoreCase);
try try
{ {
if (Config.ContainsKey(key)) return; if (Config.ContainsKey(key)) return;
if (int.TryParse(value, out int intValue)) if (int.TryParse(value, out var intValue))
Config.AddValueToVariables(key, intValue, isReadOnly); Config.AddValueToVariables(key, intValue, isReadOnly);
else if (bool.TryParse(value, out bool boolValue)) else if (bool.TryParse(value, out var boolValue))
Config.AddValueToVariables(key, boolValue, isReadOnly); Config.AddValueToVariables(key, boolValue, isReadOnly);
else if (float.TryParse(value, out float floatValue)) else if (float.TryParse(value, out var floatValue))
Config.AddValueToVariables(key, floatValue, isReadOnly); Config.AddValueToVariables(key, floatValue, isReadOnly);
else if (double.TryParse(value, out double doubleValue)) else if (double.TryParse(value, out var doubleValue))
Config.AddValueToVariables(key, doubleValue, isReadOnly); Config.AddValueToVariables(key, doubleValue, isReadOnly);
else if (uint.TryParse(value, out uint uintValue)) else if (uint.TryParse(value, out var uintValue))
Config.AddValueToVariables(key, uintValue, isReadOnly); Config.AddValueToVariables(key, uintValue, isReadOnly);
else if (long.TryParse(value, out long longValue)) else if (long.TryParse(value, out var longValue))
Config.AddValueToVariables(key, longValue, isReadOnly); Config.AddValueToVariables(key, longValue, isReadOnly);
else if (byte.TryParse(value, out byte byteValue)) else if (byte.TryParse(value, out var byteValue))
Config.AddValueToVariables(key, byteValue, isReadOnly); Config.AddValueToVariables(key, byteValue, isReadOnly);
else else
Config.AddValueToVariables(key, value, isReadOnly); Config.AddValueToVariables(key, value, isReadOnly);
@@ -234,7 +223,7 @@ namespace PluginManager.Items
} }
); );
AddCommand("remv", "remove variable from system variables", (args) => AddCommand("remv", "remove variable from system variables", args =>
{ {
if (args.Length < 2) return; if (args.Length < 2) return;
Config.RemoveKey(args[1]); Config.RemoveKey(args[1]);
@@ -244,18 +233,19 @@ namespace PluginManager.Items
AddCommand("vars", "Display all variables", () => AddCommand("vars", "Display all variables", () =>
{ {
var d = Config.GetAllVariables(); var d = Config.GetAllVariables();
List<string[]> data = new List<string[]>(); var data = new List<string[]>();
data.Add(new string[] { "-", "-" }); data.Add(new[] { "-", "-" });
data.Add(new string[] { "Key", "Value" }); data.Add(new[] { "Key", "Value" });
data.Add(new string[] { "-", "-" }); data.Add(new[] { "-", "-" });
foreach (var kvp in d) data.Add(new string[] { kvp.Key, kvp.Value.ToString() }); foreach (var kvp in d) data.Add(new[] { kvp.Key, kvp.Value.ToString() });
data.Add(new string[] { "-", "-" }); data.Add(new[] { "-", "-" });
Console_Utilities.FormatAndAlignTable(data); Console_Utilities.FormatAndAlignTable(data);
} }
); );
AddCommand("sd", "Shuts down the discord bot", async () => AddCommand("sd", "Shuts down the discord bot", async () =>
{ {
if (client is null) return;
await client.StopAsync(); await client.StopAsync();
await client.DisposeAsync(); await client.DisposeAsync();
Config.SaveConfig(); Config.SaveConfig();
@@ -273,7 +263,7 @@ namespace PluginManager.Items
public static void AddCommand(string command, string description, Action action) public static void AddCommand(string command, string description, Action action)
{ {
AddCommand(command, description, (args) => action()); AddCommand(command, description, args => action());
} }
public static void RemoveCommand(string command) public static void RemoveCommand(string command)
@@ -281,23 +271,22 @@ namespace PluginManager.Items
commandList.RemoveAll(x => x.Item1 == command); commandList.RemoveAll(x => x.Item1 == command);
} }
public static Tuple<string, string, Action<string[]>>? SearchCommand(string command) public static bool CommandExists(string command)
{
return !(GetCommand(command) is null);
}
public static Tuple<string, string, Action<string[]>>? GetCommand(string command)
{ {
return commandList.FirstOrDefault(t => t.Item1 == command); return commandList.FirstOrDefault(t => t.Item1 == command);
} }
public void HandleCommand(string command) public void HandleCommand(string command)
{ {
string[] args = command.Split(' '); var args = command.Split(' ');
foreach (var item in commandList.ToList()) foreach (var item in commandList.ToList())
{
if (item.Item1 == args[0]) if (item.Item1 == args[0])
{
item.Item3(args); item.Item3(args);
//Console.WriteLine($"Executing: {args[0]} with the following parameters: {args.MergeStrings(1)}"); //Console.WriteLine($"Executing: {args[0]} with the following parameters: {args.MergeStrings(1)}");
} }
} }
}
}
}

View File

@@ -1,8 +1,9 @@
using System; using System;
using System.Threading.Tasks; using System.Threading.Tasks;
using PluginManager.Others.Exceptions;
namespace PluginManager.Items;
namespace PluginManager.Items
{
public class Spinner public class Spinner
{ {
/// <summary> /// <summary>
@@ -24,18 +25,27 @@ namespace PluginManager.Items
public async void Start() public async void Start()
{ {
isSpinning = true; isSpinning = true;
int cnt = 0; var cnt = 0;
while (isSpinning) while (isSpinning)
{ {
cnt++; cnt++;
switch (cnt % 4) switch (cnt % 4)
{ {
case 0: Console.Write("/"); break; case 0:
case 1: Console.Write("-"); break; Console.Write("/");
case 2: Console.Write("\\"); break; break;
case 3: Console.Write("|"); break; case 1:
Console.Write("-");
break;
case 2:
Console.Write("\\");
break;
case 3:
Console.Write("|");
break;
} }
Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop); Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop);
await Task.Delay(250); await Task.Delay(250);
} }
@@ -46,9 +56,7 @@ namespace PluginManager.Items
/// </summary> /// </summary>
public void Stop() public void Stop()
{ {
if (!isSpinning) if (!isSpinning) throw new APIException("Spinner was not spinning", GetType());
throw new Others.Exceptions.APIException("Spinner was not spinning", GetType());
isSpinning = false; isSpinning = false;
} }
} }
}

View File

@@ -3,12 +3,10 @@ using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Reflection; using System.Reflection;
using System.Runtime.CompilerServices;
using PluginManager.Interfaces;
using PluginManager.Others; using PluginManager.Others;
namespace PluginManager.Loaders namespace PluginManager.Loaders;
{
internal class LoaderArgs : EventArgs internal class LoaderArgs : EventArgs
{ {
internal string? PluginName { get; init; } internal string? PluginName { get; init; }
@@ -20,41 +18,36 @@ namespace PluginManager.Loaders
internal class Loader<T> internal class Loader<T>
{ {
internal delegate void FileLoadedEventHandler(LoaderArgs args);
internal event FileLoadedEventHandler? FileLoaded;
internal delegate void PluginLoadedEventHandler(LoaderArgs args);
internal event PluginLoadedEventHandler? PluginLoaded;
private string path { get; }
private string extension { get; }
internal Loader(string path, string extension) internal Loader(string path, string extension)
{ {
this.path = path; this.path = path;
this.extension = extension; this.extension = extension;
} }
private string path { get; }
private string extension { get; }
internal event FileLoadedEventHandler? FileLoaded;
internal event PluginLoadedEventHandler? PluginLoaded;
internal List<T>? Load() internal List<T>? Load()
{ {
List<T> list = new List<T>(); var list = new List<T>();
if (!Directory.Exists(path)) if (!Directory.Exists(path))
{ {
Directory.CreateDirectory(path); Directory.CreateDirectory(path);
return null; return null;
} }
string[] files = Directory.GetFiles(path, $"*.{extension}", SearchOption.AllDirectories); var files = Directory.GetFiles(path, $"*.{extension}", SearchOption.AllDirectories);
foreach (var file in files) foreach (var file in files)
{ {
Assembly.LoadFrom(file); Assembly.LoadFrom(file);
if (FileLoaded != null) if (FileLoaded != null)
{ {
LoaderArgs args = new LoaderArgs() var args = new LoaderArgs
{ {
Exception = null, Exception = null,
TypeName = nameof(T), TypeName = nameof(T),
@@ -68,25 +61,23 @@ namespace PluginManager.Loaders
try try
{ {
Type interfaceType = typeof(T); var interfaceType = typeof(T);
Type[] types = AppDomain.CurrentDomain.GetAssemblies() var types = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(a => a.GetTypes()) .SelectMany(a => a.GetTypes())
.Where(p => interfaceType.IsAssignableFrom(p) && p.IsClass) .Where(p => interfaceType.IsAssignableFrom(p) && p.IsClass)
.ToArray(); .ToArray();
list.Clear(); list.Clear();
foreach (Type type in types) foreach (var type in types)
{
try try
{ {
T plugin = (T)(Activator.CreateInstance(type)!); var plugin = (T)Activator.CreateInstance(type)!;
list.Add(plugin); list.Add(plugin);
if (PluginLoaded != null) if (PluginLoaded != null)
{ PluginLoaded.Invoke(new LoaderArgs
PluginLoaded.Invoke(new()
{ {
Exception = null, Exception = null,
IsLoaded = true, IsLoaded = true,
@@ -96,14 +87,9 @@ namespace PluginManager.Loaders
} }
); );
} }
}
catch (Exception ex) catch (Exception ex)
{ {
if (PluginLoaded != null) if (PluginLoaded != null) PluginLoaded.Invoke(new LoaderArgs { Exception = ex, IsLoaded = false, PluginName = type.FullName, TypeName = nameof(T) });
{
PluginLoaded.Invoke(new() { Exception = ex, IsLoaded = false, PluginName = type.FullName, TypeName = nameof(T) });
}
}
} }
} }
catch (Exception ex) catch (Exception ex)
@@ -114,5 +100,8 @@ namespace PluginManager.Loaders
return list; return list;
} }
}
internal delegate void FileLoadedEventHandler(LoaderArgs args);
internal delegate void PluginLoadedEventHandler(LoaderArgs args);
} }

View File

@@ -1,42 +1,23 @@
using Discord.WebSocket; using System;
using System.Collections.Generic;
using Discord.WebSocket;
using PluginManager.Interfaces; using PluginManager.Interfaces;
using PluginManager.Others; using PluginManager.Others;
using System;
using System.Collections.Generic;
namespace PluginManager.Loaders namespace PluginManager.Loaders;
{
public class PluginLoader public class PluginLoader
{ {
private readonly DiscordSocketClient _client; public delegate void CMDLoaded(string name, string typeName, bool success, Exception? e = null);
/// <summary> public delegate void EVELoaded(string name, string typeName, bool success, Exception? e = null);
/// The Plugin Loader constructor
/// </summary>
/// <param name="discordSocketClient">The discord bot client where the plugins will pe attached to</param>
public PluginLoader(DiscordSocketClient discordSocketClient) { this._client = discordSocketClient; }
private const string pluginCMDFolder = @"./Data/Plugins/Commands/"; private const string pluginCMDFolder = @"./Data/Plugins/Commands/";
private const string pluginEVEFolder = @"./Data/Plugins/Events/"; private const string pluginEVEFolder = @"./Data/Plugins/Events/";
private const string pluginCMDExtension = "dll"; private const string pluginCMDExtension = "dll";
private const string pluginEVEExtension = "dll"; private const string pluginEVEExtension = "dll";
private readonly DiscordSocketClient _client;
/// <summary>
/// A list of <see cref="DBCommand"/> commands
/// </summary>
public static List<DBCommand>? Commands { get; set; }
/// <summary>
/// A list of <see cref="DBEvent"/> commands
/// </summary>
public static List<DBEvent>? Events { get; set; }
public delegate void CMDLoaded(string name, string typeName, bool success, Exception? e = null);
public delegate void EVELoaded(string name, string typeName, bool success, Exception? e = null);
/// <summary> /// <summary>
/// Event that is fired when a <see cref="DBCommand" /> is successfully loaded into commands list /// Event that is fired when a <see cref="DBCommand" /> is successfully loaded into commands list
@@ -48,6 +29,26 @@ namespace PluginManager.Loaders
/// </summary> /// </summary>
public EVELoaded? onEVELoad; public EVELoaded? onEVELoad;
/// <summary>
/// The Plugin Loader constructor
/// </summary>
/// <param name="discordSocketClient">The discord bot client where the plugins will pe attached to</param>
public PluginLoader(DiscordSocketClient discordSocketClient)
{
_client = discordSocketClient;
}
/// <summary>
/// A list of <see cref="DBCommand" /> commands
/// </summary>
public static List<DBCommand>? Commands { get; set; }
/// <summary>
/// A list of <see cref="DBEvent" /> commands
/// </summary>
public static List<DBEvent>? Events { get; set; }
/// <summary> /// <summary>
/// The main mathod that is called to load all events /// The main mathod that is called to load all events
/// </summary> /// </summary>
@@ -59,8 +60,8 @@ namespace PluginManager.Loaders
Functions.WriteLogFile("Starting plugin loader ... Client: " + _client.CurrentUser.Username); Functions.WriteLogFile("Starting plugin loader ... Client: " + _client.CurrentUser.Username);
Console.WriteLine("Loading plugins"); Console.WriteLine("Loading plugins");
Loader<DBCommand> commandsLoader = new Loader<DBCommand>(pluginCMDFolder, pluginCMDExtension); var commandsLoader = new Loader<DBCommand>(pluginCMDFolder, pluginCMDExtension);
Loader<DBEvent> eventsLoader = new Loader<DBEvent>(pluginEVEFolder, pluginEVEExtension); var eventsLoader = new Loader<DBEvent>(pluginEVEFolder, pluginEVEExtension);
commandsLoader.FileLoaded += OnCommandFileLoaded; commandsLoader.FileLoaded += OnCommandFileLoaded;
commandsLoader.PluginLoaded += OnCommandLoaded; commandsLoader.PluginLoaded += OnCommandLoaded;
@@ -84,7 +85,7 @@ namespace PluginManager.Loaders
private void OnEventLoaded(LoaderArgs e) private void OnEventLoaded(LoaderArgs e)
{ {
if (e.IsLoaded) { ((DBEvent)e.Plugin!).Start(_client); } if (e.IsLoaded) ((DBEvent)e.Plugin!).Start(_client);
if (onEVELoad != null) onEVELoad.Invoke(((DBEvent)e.Plugin!).name, e.TypeName!, e.IsLoaded, e.Exception); if (onEVELoad != null) onEVELoad.Invoke(((DBEvent)e.Plugin!).name, e.TypeName!, e.IsLoaded, e.Exception);
} }
@@ -94,4 +95,3 @@ namespace PluginManager.Loaders
if (onCMDLoad != null) onCMDLoad.Invoke(((DBCommand)e.Plugin!).Command, e.TypeName!, e.IsLoaded, e.Exception); if (onCMDLoad != null) onCMDLoad.Invoke(((DBCommand)e.Plugin!).Command, e.TypeName!, e.IsLoaded, e.Exception);
} }
} }
}

View File

@@ -1,22 +1,22 @@
using System; using System;
using System.IO;
using System.Threading.Tasks;
using System.Net;
using System.Collections.Generic; using System.Collections.Generic;
using System.Threading.Tasks;
using PluginManager.Others; using PluginManager.Others;
namespace PluginManager.Online namespace PluginManager.Online;
{
public class LanguageManager public class LanguageManager
{ {
private string link; private readonly string link;
/// <summary> /// <summary>
/// The Language Manager constructor /// The Language Manager constructor
/// </summary> /// </summary>
/// <param name="link">The link to where all the languages for the bot are stored</param> /// <param name="link">The link to where all the languages for the bot are stored</param>
public LanguageManager(string link) => this.link = link; public LanguageManager(string link)
{
this.link = link;
}
/// <summary> /// <summary>
/// The method to list all languages /// The method to list all languages
@@ -24,33 +24,31 @@ namespace PluginManager.Online
/// <returns></returns> /// <returns></returns>
public async Task ListAllLanguages() public async Task ListAllLanguages()
{ {
try try
{ {
List<string> list = await ServerCom.ReadTextFromFile(link); var list = await ServerCom.ReadTextFromFile(link);
string[] lines = list.ToArray(); var lines = list.ToArray();
List<string[]> info = new List<string[]>(); var info = new List<string[]>();
info.Add(new string[] { "-", "-" }); info.Add(new[] { "-", "-" });
info.Add(new string[] { "Language Name", "File Size" }); info.Add(new[] { "Language Name", "File Size" });
info.Add(new string[] { "-", "-" }); info.Add(new[] { "-", "-" });
foreach (var line in lines) foreach (var line in lines)
{ {
if (line.Length <= 2) continue; if (line.Length <= 2) continue;
string[] d = line.Split(','); var d = line.Split(',');
if (d[3].Contains("cp") || d[3].Contains("CrossPlatform")) if (d[3].Contains("cp") || d[3].Contains("CrossPlatform")) info.Add(new[] { d[0], d[1] });
info.Add(new string[] { d[0], d[1] });
} }
info.Add(new string[] { "-", "-" });
info.Add(new[] { "-", "-" });
Console_Utilities.FormatAndAlignTable(info); Console_Utilities.FormatAndAlignTable(info);
} }
catch (Exception exception) catch (Exception exception)
{ {
Console.WriteLine("Failed to execute command: listlang\nReason: " + exception.Message); Console.WriteLine("Failed to execute command: listlang\nReason: " + exception.Message);
Others.Functions.WriteErrFile(exception.ToString()); Functions.WriteErrFile(exception.ToString());
} }
} }
/// <summary> /// <summary>
@@ -62,25 +60,23 @@ namespace PluginManager.Online
{ {
try try
{ {
List<string> list = await ServerCom.ReadTextFromFile(link); var list = await ServerCom.ReadTextFromFile(link);
string[] lines = list.ToArray(); var lines = list.ToArray();
foreach (var line in lines) foreach (var line in lines)
{ {
if (line.Length <= 2) continue; if (line.Length <= 2) continue;
string[] d = line.Split(','); var d = line.Split(',');
if (d[0].Equals(langName) && (d[3].Contains("cp") || d[3].Contains("CrossPlatform"))) if (d[0].Equals(langName) && (d[3].Contains("cp") || d[3].Contains("CrossPlatform"))) return new[] { d[2], d[3] };
return new string[] { d[2], d[3] };
} }
} }
catch (Exception exception) catch (Exception exception)
{ {
Console.WriteLine("Failed to execute command: listlang\nReason: " + exception.Message); Console.WriteLine("Failed to execute command: listlang\nReason: " + exception.Message);
Others.Functions.WriteErrFile(exception.ToString()); Functions.WriteErrFile(exception.ToString());
} }
return null; return null;
} }
} }
}

View File

@@ -1,20 +1,13 @@
using System; using System;
using System.IO;
using System.Net;
using System.Threading.Tasks;
using System.Collections.Generic; using System.Collections.Generic;
using System.Threading.Tasks;
using PluginManager.Others; using PluginManager.Others;
using OperatingSystem = PluginManager.Others.OperatingSystem;
namespace PluginManager.Online;
namespace PluginManager.Online
{
public class PluginsManager public class PluginsManager
{ {
/// <summary>
/// The URL of the server
/// </summary>
public string PluginsLink { get; private set; }
/// <summary> /// <summary>
/// The Plugin Manager constructor /// The Plugin Manager constructor
/// </summary> /// </summary>
@@ -24,6 +17,11 @@ namespace PluginManager.Online
PluginsLink = link; PluginsLink = link;
} }
/// <summary>
/// The URL of the server
/// </summary>
public string PluginsLink { get; }
/// <summary> /// <summary>
/// The method to load all plugins /// The method to load all plugins
/// </summary> /// </summary>
@@ -32,23 +30,23 @@ namespace PluginManager.Online
{ {
try try
{ {
List<string> list = await ServerCom.ReadTextFromFile(PluginsLink); var list = await ServerCom.ReadTextFromFile(PluginsLink);
string[] lines = list.ToArray(); var lines = list.ToArray();
List<string[]> data = new List<string[]>(); var data = new List<string[]>();
var op = Functions.GetOperatingSystem(); var op = Functions.GetOperatingSystem();
int len = lines.Length; var len = lines.Length;
string[] titles = { "Name", "Description", "Plugin Type", "Libraries" }; string[] titles = { "Name", "Description", "Plugin Type", "Libraries" };
data.Add(new string[] { "-", "-", "-", "-" }); data.Add(new[] { "-", "-", "-", "-" });
data.Add(titles); data.Add(titles);
data.Add(new string[] { "-", "-", "-", "-" }); data.Add(new[] { "-", "-", "-", "-" });
for (int i = 0; i < len; i++) for (var i = 0; i < len; i++)
{ {
if (lines[i].Length <= 2) continue; if (lines[i].Length <= 2) continue;
string[] content = lines[i].Split(','); var content = lines[i].Split(',');
string[] display = new string[4]; var display = new string[4];
if (op == Others.OperatingSystem.WINDOWS) if (op == OperatingSystem.WINDOWS)
{ {
if (content[4].Contains("Windows")) if (content[4].Contains("Windows"))
{ {
@@ -58,12 +56,12 @@ namespace PluginManager.Online
if (content.Length == 6 && (content[5] != null || content[5].Length > 2)) if (content.Length == 6 && (content[5] != null || content[5].Length > 2))
display[3] = ((await ServerCom.ReadTextFromFile(content[5])).Count + 1).ToString(); display[3] = ((await ServerCom.ReadTextFromFile(content[5])).Count + 1).ToString();
else display[3] = "1"; else
display[3] = "1";
data.Add(display); data.Add(display);
continue;
} }
} }
else if (op == Others.OperatingSystem.LINUX) else if (op == OperatingSystem.LINUX)
{ {
if (content[4].Contains("Linux")) if (content[4].Contains("Linux"))
{ {
@@ -71,21 +69,19 @@ namespace PluginManager.Online
display[1] = content[1]; display[1] = content[1];
display[2] = content[2]; display[2] = content[2];
data.Add(display); data.Add(display);
continue;
} }
} }
} }
data.Add(new string[] { "-", "-", "-", "-" }); data.Add(new[] { "-", "-", "-", "-" });
Console_Utilities.FormatAndAlignTable(data); Console_Utilities.FormatAndAlignTable(data);
} }
catch (Exception exception) catch (Exception exception)
{ {
Console.WriteLine("Failed to execute command: listlang\nReason: " + exception.Message); Console.WriteLine("Failed to execute command: listlang\nReason: " + exception.Message);
Others.Functions.WriteErrFile(exception.ToString()); Functions.WriteErrFile(exception.ToString());
} }
} }
/// <summary> /// <summary>
@@ -97,32 +93,26 @@ namespace PluginManager.Online
{ {
try try
{ {
List<string> list = await ServerCom.ReadTextFromFile(PluginsLink); var list = await ServerCom.ReadTextFromFile(PluginsLink);
string[] lines = list.ToArray(); var lines = list.ToArray();
int len = lines.Length; var len = lines.Length;
for (int i = 0; i < len; i++) for (var i = 0; i < len; i++)
{ {
string[] contents = lines[i].Split(','); var contents = lines[i].Split(',');
if (contents[0] == name) if (contents[0] == name)
{ {
if (contents.Length == 6) if (contents.Length == 6) return new[] { contents[2], contents[3], contents[5] };
return new string[] { contents[2], contents[3], contents[5] }; if (contents.Length == 5) return new[] { contents[2], contents[3], string.Empty };
else if (contents.Length == 5) throw new Exception("Failed to download plugin. Invalid Argument Length");
return new string[] { contents[2], contents[3], string.Empty };
else throw new Exception("Failed to download plugin. Invalid Argument Length");
} }
} }
} }
catch (Exception exception) catch (Exception exception)
{ {
Console.WriteLine("Failed to execute command: listplugs\nReason: " + exception.Message); Console.WriteLine("Failed to execute command: listplugs\nReason: " + exception.Message);
Others.Functions.WriteErrFile(exception.ToString()); Functions.WriteErrFile(exception.ToString());
} }
return new string[] { null!, null!, null! }; return new string[] { null!, null!, null! };
} }
}
} }

View File

@@ -1,10 +1,11 @@
using PluginManager.Online.Helpers; using PluginManager.Online.Helpers;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using PluginManager.Others;
namespace PluginManager.Online namespace PluginManager.Online
{ {
@@ -54,34 +55,32 @@ namespace PluginManager.Online
bool isDownloading = true; bool isDownloading = true;
int c_progress = 0; int c_progress = 0;
Others.Console_Utilities.ProgressBar pbar = new Others.Console_Utilities.ProgressBar(100, ""); Console_Utilities.ProgressBar pbar = new Console_Utilities.ProgressBar { Max = 100, NoColor = true };
IProgress<float> progress = new Progress<float>(percent => IProgress<float> progress = new Progress<float>(percent =>
{ {
c_progress = (int)percent; c_progress = (int)percent;
}); });
Task updateProgressBarTask = new Task(() => Task updateProgressBarTask = new Task(() =>
{ {
while (isDownloading) while (isDownloading)
{ {
pbar.Update(c_progress); pbar.Update(c_progress);
if (c_progress == 100) if (c_progress == 100) break;
break; Thread.Sleep(500);
System.Threading.Thread.Sleep(500);
} }
}); }
);
new System.Threading.Thread(updateProgressBarTask.Start).Start(); new Thread(updateProgressBarTask.Start).Start();
await DownloadFileAsync(URL, location, progress); await DownloadFileAsync(URL, location, progress);
c_progress = 100; c_progress = 100;
pbar.Update(100); pbar.Update(100);
isDownloading = false; isDownloading = false;
}
}
} }
} }

View File

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

View File

@@ -10,23 +10,13 @@ namespace PluginManager.Others
/// </summary> /// </summary>
public class ProgressBar public class ProgressBar
{ {
public int Max { get; set; } public int Max { get; init; }
public string Message { get; set; }
public ConsoleColor Color { get; init; } public ConsoleColor Color { get; init; }
public bool NoColor { get; init; }
public ProgressBar(int max, string message)
{
Max = max;
Message = message;
var consoleColors = Enum.GetValues(typeof(ConsoleColor));
while ((Color = (ConsoleColor)consoleColors.GetValue(new Random().Next(consoleColors.Length))!) == ConsoleColor.White && Color != ConsoleColor.Black) ;
}
public void Update(int progress, double speed = -1, string? unit = null) public void Update(int progress, double speed = -1, string? unit = null)
{ {
//progress bar
Console.CursorLeft = 0; Console.CursorLeft = 0;
Console.Write("["); Console.Write("[");
Console.CursorLeft = 32; Console.CursorLeft = 32;
@@ -38,14 +28,20 @@ namespace PluginManager.Others
for (int i = 0; i < onechunk * progress; i++) for (int i = 0; i < onechunk * progress; i++)
{ {
if (NoColor)
Console.BackgroundColor = ConsoleColor.Black; //this.Color
else
Console.BackgroundColor = this.Color; Console.BackgroundColor = this.Color;
Console.CursorLeft = position++; Console.CursorLeft = position++;
Console.Write(" "); Console.Write("#");
} }
for (int i = position; i <= 31; i++) for (int i = position; i <= 31; i++)
{ {
Console.BackgroundColor = ConsoleColor.Gray; if (NoColor)
Console.BackgroundColor = ConsoleColor.Black; // background of empty bar
else
Console.BackgroundColor = ConsoleColor.DarkGray;
Console.CursorLeft = position++; Console.CursorLeft = position++;
Console.Write(" "); Console.Write(" ");
} }

View File

@@ -1,10 +1,13 @@
using System; using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace PluginManager.Others;
namespace PluginManager.Others
{
public class Cryptography public class Cryptography
{ {
/// <summary> /// <summary>
/// Translate hex to string /// Translate hex to string
/// </summary> /// </summary>
@@ -13,12 +16,9 @@ namespace PluginManager.Others
public static string FromHexToString(string hexString) public static string FromHexToString(string hexString)
{ {
var bytes = new byte[hexString.Length / 2]; var bytes = new byte[hexString.Length / 2];
for (var i = 0; i < bytes.Length; i++) for (var i = 0; i < bytes.Length; i++) bytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
{
bytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
}
return System.Text.Encoding.Unicode.GetString(bytes); return Encoding.Unicode.GetString(bytes);
} }
/// <summary> /// <summary>
@@ -28,13 +28,10 @@ namespace PluginManager.Others
/// <returns></returns> /// <returns></returns>
public static string ToHexString(string str) public static string ToHexString(string str)
{ {
var sb = new System.Text.StringBuilder(); var sb = new StringBuilder();
var bytes = System.Text.Encoding.Unicode.GetBytes(str); var bytes = Encoding.Unicode.GetBytes(str);
foreach (var t in bytes) foreach (var t in bytes) sb.Append(t.ToString("X2"));
{
sb.Append(t.ToString("X2"));
}
return sb.ToString(); return sb.ToString();
} }
@@ -44,15 +41,15 @@ namespace PluginManager.Others
/// </summary> /// </summary>
/// <param name="text">The text to encrypt</param> /// <param name="text">The text to encrypt</param>
/// <returns></returns> /// <returns></returns>
public static async System.Threading.Tasks.Task<string> CreateMD5(string text) public static async Task<string> CreateMD5(string text)
{ {
string output = ""; var output = "";
using (System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create()) using (var md5 = MD5.Create())
{ {
using (var s = GenerateStreamFromString(text)) using (var s = GenerateStreamFromString(text))
{ {
byte[] t = await md5.ComputeHashAsync(s); var t = await md5.ComputeHashAsync(s);
output = System.Convert.ToBase64String(t); output = Convert.ToBase64String(t);
} }
} }
@@ -64,28 +61,28 @@ namespace PluginManager.Others
/// </summary> /// </summary>
/// <param name="text">The text to encrypt</param> /// <param name="text">The text to encrypt</param>
/// <returns></returns> /// <returns></returns>
public static async System.Threading.Tasks.Task<string> CreateSHA256(string text) public static async Task<string> CreateSHA256(string text)
{ {
string output = ""; var output = "";
using (System.Security.Cryptography.SHA256 sha = System.Security.Cryptography.SHA256.Create()) using (var sha = SHA256.Create())
{ {
using (var s = GenerateStreamFromString(text)) using (var s = GenerateStreamFromString(text))
{ {
byte[] t = await sha.ComputeHashAsync(s); var t = await sha.ComputeHashAsync(s);
output = System.Convert.ToBase64String(t); output = Convert.ToBase64String(t);
} }
} }
return output; return output;
} }
private static System.IO.Stream GenerateStreamFromString(string s) private static Stream GenerateStreamFromString(string s)
{ {
var stream = new System.IO.MemoryStream(); var stream = new MemoryStream();
var writer = new System.IO.StreamWriter(stream); var writer = new StreamWriter(stream);
writer.Write(s); writer.Write(s);
writer.Flush(); writer.Flush();
stream.Position = 0; stream.Position = 0;
return stream; return stream;
} }
} }
}

View File

@@ -1,20 +1,22 @@
namespace PluginManager.Others namespace PluginManager.Others;
{
/// <summary> /// <summary>
/// A list of operating systems /// A list of operating systems
/// </summary> /// </summary>
public enum OperatingSystem public enum OperatingSystem
{ WINDOWS, LINUX, MAC_OS, UNKNOWN } {
WINDOWS, LINUX, MAC_OS, UNKNOWN
}
/// <summary> /// <summary>
/// A list with all errors /// A list with all errors
/// </summary> /// </summary>
public enum Error public enum Error
{ UNKNOWN_ERROR, GUILD_NOT_FOUND, STREAM_NOT_FOUND, INVALID_USER, INVALID_CHANNEL, INVALID_PERMISSIONS } {
UNKNOWN_ERROR, GUILD_NOT_FOUND, STREAM_NOT_FOUND, INVALID_USER, INVALID_CHANNEL, INVALID_PERMISSIONS
}
/// <summary> /// <summary>
/// The output log type /// The output log type
/// </summary> /// </summary>
public enum OutputLogLevel { NONE, INFO, WARNING, ERROR, CRITICAL } public enum OutputLogLevel { NONE, INFO, WARNING, ERROR, CRITICAL }
}

View File

@@ -1,29 +1,13 @@
using System; using System;
namespace PluginManager.Others.Exceptions namespace PluginManager.Others.Exceptions;
{
/// <summary> /// <summary>
/// Custom Exception for PluginManager /// Custom Exception for PluginManager
/// </summary> /// </summary>
[Serializable] [Serializable]
public class APIException : Exception public class APIException : Exception
{ {
/// <summary>
/// The function where the error occurred
/// </summary>
public string? Function { get; } = "not specified";
/// <summary>
/// The error code
/// </summary>
public Error? ErrorCode { get; } = Error.UNKNOWN_ERROR;
/// <summary>
/// The possible cause that determined the error
/// </summary>
public string? PossibleCause { get; } = "not specified";
/// <summary> /// <summary>
/// The APIException contructor /// The APIException contructor
/// </summary> /// </summary>
@@ -49,6 +33,7 @@ namespace PluginManager.Others.Exceptions
ErrorCode = errorCode; ErrorCode = errorCode;
Function = function; Function = function;
} }
/// <summary> /// <summary>
/// The APIException contructor /// The APIException contructor
/// </summary> /// </summary>
@@ -58,13 +43,13 @@ namespace PluginManager.Others.Exceptions
{ {
Function = function; Function = function;
} }
/// <summary> /// <summary>
/// The APIException contructor /// The APIException contructor
/// </summary> /// </summary>
/// <param name="message">The error message</param> /// <param name="message">The error message</param>
public APIException(string message) : base(message) public APIException(string message) : base(message)
{ {
} }
/// <summary> /// <summary>
@@ -77,6 +62,21 @@ namespace PluginManager.Others.Exceptions
Function = errorLocation.FullName; Function = errorLocation.FullName;
} }
/// <summary>
/// The function where the error occurred
/// </summary>
public string? Function { get; } = "not specified";
/// <summary>
/// The error code
/// </summary>
public Error? ErrorCode { get; } = Error.UNKNOWN_ERROR;
/// <summary>
/// The possible cause that determined the error
/// </summary>
public string? PossibleCause { get; } = "not specified";
/// <summary> /// <summary>
/// Method to print the error to <see cref="Console" /> /// Method to print the error to <see cref="Console" />
/// </summary> /// </summary>
@@ -84,11 +84,8 @@ namespace PluginManager.Others.Exceptions
{ {
Console.WriteLine("Message Content: " + Message); Console.WriteLine("Message Content: " + Message);
Console.WriteLine("Function: " + Function); Console.WriteLine("Function: " + Function);
Console.WriteLine("Error Code: " + ErrorCode.ToString()); Console.WriteLine("Error Code: " + ErrorCode);
Console.WriteLine("Possible cause: " + PossibleCause); Console.WriteLine("Possible cause: " + PossibleCause);
if (this.StackTrace != null) if (StackTrace != null) Functions.WriteErrFile(StackTrace);
Functions.WriteErrFile(this.StackTrace);
} }
} }
}

View File

@@ -212,11 +212,22 @@ namespace PluginManager.Others
/// <returns></returns> /// <returns></returns>
public static (double, string) ConvertBytes(long bytes) public static (double, string) ConvertBytes(long bytes)
{ {
if (bytes < 1024) return (bytes, "B"); List<string> units = new List<string>()
if (bytes < 1024 * 1024) return (bytes / 1024.0, "KB"); {
if (bytes < 1024 * 1024 * 1024) return (bytes / 1024.0 / 1024.0, "MB"); "B",
return (bytes / 1024.0 / 1024.0 / 1024.0, "GB"); "KB",
"MB",
"GB",
"TB"
};
int i = 0;
while (bytes >= 1024)
{
i++;
bytes /= 1024;
}
return (bytes, units[i]);
} }
/// <summary> /// <summary>

View File

@@ -1,10 +1,9 @@
using Discord; using System.Linq;
using Discord;
using Discord.WebSocket; using Discord.WebSocket;
using System.Linq; namespace PluginManager.Others.Permissions;
namespace PluginManager.Others.Permissions
{
/// <summary> /// <summary>
/// A class whith all discord permissions /// A class whith all discord permissions
/// </summary> /// </summary>
@@ -16,7 +15,10 @@ namespace PluginManager.Others.Permissions
/// <param name="role">The role</param> /// <param name="role">The role</param>
/// <param name="permission">The permission</param> /// <param name="permission">The permission</param>
/// <returns></returns> /// <returns></returns>
public static bool hasPermission(this IRole role, GuildPermission permission) => role.Permissions.Has(permission); public static bool hasPermission(this IRole role, GuildPermission permission)
{
return role.Permissions.Has(permission);
}
/// <summary> /// <summary>
/// Check if user has the specified role /// Check if user has the specified role
@@ -24,7 +26,10 @@ namespace PluginManager.Others.Permissions
/// <param name="user">The user</param> /// <param name="user">The user</param>
/// <param name="role">The role</param> /// <param name="role">The role</param>
/// <returns></returns> /// <returns></returns>
public static bool hasRole(this SocketGuildUser user, IRole role) => user.Roles.Contains(role); public static bool hasRole(this SocketGuildUser user, IRole role)
{
return user.Roles.Contains(role);
}
/// <summary> /// <summary>
/// Check if user has the specified permission /// Check if user has the specified permission
@@ -33,23 +38,27 @@ namespace PluginManager.Others.Permissions
/// <param name="permission">The permission</param> /// <param name="permission">The permission</param>
/// <returns></returns> /// <returns></returns>
public static bool hasPermission(this SocketGuildUser user, GuildPermission permission) public static bool hasPermission(this SocketGuildUser user, GuildPermission permission)
=> user.Roles.Where(role => role.hasPermission(permission)).Any() || user.Guild.Owner == user; {
/// <summary> return user.Roles.Where(role => role.hasPermission(permission)).Any() || user.Guild.Owner == user;
/// Check if user is administrator of server }
/// </summary>
/// <param name="user">The user</param>
/// <returns></returns>
public static bool isAdmin(this SocketGuildUser user) => user.hasPermission(GuildPermission.Administrator);
/// <summary> /// <summary>
/// Check if user is administrator of server /// Check if user is administrator of server
/// </summary> /// </summary>
/// <param name="user">The user</param> /// <param name="user">The user</param>
/// <returns></returns> /// <returns></returns>
public static bool isAdmin(this SocketUser user) => isAdmin((SocketGuildUser)user); public static bool isAdmin(this SocketGuildUser user)
{
return user.hasPermission(GuildPermission.Administrator);
} }
/// <summary>
/// Check if user is administrator of server
/// </summary>
/// <param name="user">The user</param>
/// <returns></returns>
public static bool isAdmin(this SocketUser user)
{
return isAdmin((SocketGuildUser)user);
}
} }