diff --git a/BUILDS/net6.0/MusicCommands.dll b/BUILDS/net6.0/MusicCommands.dll index c9f7661..dac55eb 100644 Binary files a/BUILDS/net6.0/MusicCommands.dll and b/BUILDS/net6.0/MusicCommands.dll differ diff --git a/BUILDS/net6.0/PluginManager.dll b/BUILDS/net6.0/PluginManager.dll index 7cc60a0..6be9c72 100644 Binary files a/BUILDS/net6.0/PluginManager.dll and b/BUILDS/net6.0/PluginManager.dll differ diff --git a/CMD_LevelingSystem/Level.cs b/CMD_LevelingSystem/Level.cs index 85b341f..22f30e3 100644 --- a/CMD_LevelingSystem/Level.cs +++ b/CMD_LevelingSystem/Level.cs @@ -1,48 +1,42 @@ -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.WebSocket; using PluginManager; using PluginManager.Interfaces; using PluginManager.Others; -namespace CMD_LevelingSystem +namespace CMD_LevelingSystem; + +internal class Level : DBCommand { - internal class Level : DBCommand + public string Command => "level"; + + public string Description => "Display tour current level"; + + public string Usage => "level"; + + public bool canUseDM => false; + + public bool canUseServer => true; + + public bool requireAdmin => false; + + public async void Execute(SocketCommandContext context, SocketMessage message, DiscordSocketClient client, bool isDM) { - public string Command => "level"; - - public string Description => "Display tour current level"; - - public string Usage => "level"; - - public bool canUseDM => false; - - public bool canUseServer => true; - - public bool requireAdmin => false; - - public async void Execute(SocketCommandContext context, SocketMessage message, DiscordSocketClient client, bool isDM) + var user = await Functions.ConvertFromJson(Config.GetValue("LevelingSystemPath") + $"/{message.Author.Id}.dat"); + if (user == null) { - User user = await Functions.ConvertFromJson(Config.GetValue("LevelingSystemPath") + $"/{message.Author.Id}.dat"); - if (user == null) - { - await context.Channel.SendMessageAsync("You are now unranked !"); - return; - } - - var builder = new EmbedBuilder(); - Random r = new Random(); - builder.WithColor(r.Next(256), r.Next(256), r.Next(256)); - builder.AddField("Current Level", user.CurrentLevel, true) - .AddField("Current EXP", user.CurrentEXP, true) - .AddField("Required Exp", user.RequiredEXPToLevelUp, true); - builder.WithTimestamp(DateTimeOffset.Now); - await context.Channel.SendMessageAsync(embed: builder.Build()); + await context.Channel.SendMessageAsync("You are now unranked !"); + return; } + + var builder = new EmbedBuilder(); + var r = new Random(); + builder.WithColor(r.Next(256), r.Next(256), r.Next(256)); + builder.AddField("Current Level", user.CurrentLevel, true) + .AddField("Current EXP", user.CurrentEXP, true) + .AddField("Required Exp", user.RequiredEXPToLevelUp, true); + builder.WithTimestamp(DateTimeOffset.Now); + await context.Channel.SendMessageAsync(embed: builder.Build()); } } diff --git a/CMD_LevelingSystem/User.cs b/CMD_LevelingSystem/User.cs index 679a5d5..1b0736a 100644 --- a/CMD_LevelingSystem/User.cs +++ b/CMD_LevelingSystem/User.cs @@ -1,16 +1,9 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +namespace CMD_LevelingSystem; -namespace CMD_LevelingSystem +public class User { - public class User - { - public string userID { get; set; } - public int CurrentLevel { get; set; } - public Int64 CurrentEXP { get; set; } - public Int64 RequiredEXPToLevelUp { get; set; } - } + public string userID { get; set; } + public int CurrentLevel { get; set; } + public long CurrentEXP { get; set; } + public long RequiredEXPToLevelUp { get; set; } } diff --git a/CMD_Utils/Echo.cs b/CMD_Utils/Echo.cs index fdf7fe1..83ec899 100644 --- a/CMD_Utils/Echo.cs +++ b/CMD_Utils/Echo.cs @@ -1,6 +1,5 @@ using Discord.Commands; using Discord.WebSocket; - using PluginManager.Interfaces; internal class Echo : DBCommand @@ -11,14 +10,14 @@ internal class Echo : DBCommand public string Usage => "echo [message]"; - public bool canUseDM => true; + public bool canUseDM => true; public bool canUseServer => true; public bool requireAdmin => false; 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); } } diff --git a/CMD_Utils/FlipCoin.cs b/CMD_Utils/FlipCoin.cs index e84f83b..0057f33 100644 --- a/CMD_Utils/FlipCoin.cs +++ b/CMD_Utils/FlipCoin.cs @@ -1,37 +1,30 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -using Discord.Commands; +using Discord.Commands; using Discord.WebSocket; - using PluginManager.Interfaces; -namespace CMD_Utils +namespace CMD_Utils; + +internal class FlipCoin : DBCommand { - class FlipCoin : DBCommand + public string Command => "flip"; + + public string Description => "Flip a coin"; + + public string Usage => "flip"; + + public bool canUseDM => true; + + public bool canUseServer => true; + + public bool requireAdmin => false; + + public async void Execute(SocketCommandContext context, SocketMessage message, DiscordSocketClient client, bool isDM) { - public string Command => "flip"; - - public string Description => "Flip a coin"; - - public string Usage => "flip"; - - public bool canUseDM => true; - - public bool canUseServer => true; - - public bool requireAdmin => false; - - public async void Execute(SocketCommandContext context, SocketMessage message, DiscordSocketClient client, bool isDM) - { - System.Random random = new System.Random(); - int r = random.Next(1, 3); - if (r == 1) - await message.Channel.SendMessageAsync("Heads"); - else await message.Channel.SendMessageAsync("Tails"); - } + var random = new System.Random(); + var r = random.Next(1, 3); + if (r == 1) + await message.Channel.SendMessageAsync("Heads"); + else + await message.Channel.SendMessageAsync("Tails"); } } diff --git a/CMD_Utils/Poll.cs b/CMD_Utils/Poll.cs index bf81df5..c3624c6 100644 --- a/CMD_Utils/Poll.cs +++ b/CMD_Utils/Poll.cs @@ -1,53 +1,45 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - +using System.Collections.Generic; using Discord; using Discord.Commands; using Discord.WebSocket; - 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 Description => "Create a poll with options"; + + public string Usage => "poll [This-is-question] [This-is-answer-1] [This-is-answer-2] ... "; + + public bool canUseDM => false; + + public bool canUseServer => true; + + public bool requireAdmin => true; + + public async void Execute(SocketCommandContext context, SocketMessage message, DiscordSocketClient client, bool isDM) { - public string Command => "poll"; + if (isDM) return; + var question = message.Content.Split(' ')[1].Replace('-', ' '); + var answers = Functions.MergeStrings(message.Content.Split(' '), 2).Split(' '); + var embedBuilder = new EmbedBuilder(); + embedBuilder.Title = question; + var len = answers.Length; + for (var i = 0; i < len; i++) embedBuilder.AddField($"Answer {i + 1}", answers[i].Replace('-', ' '), true); + var msg = await context.Channel.SendMessageAsync(embed: embedBuilder.Build()); - public string Description => "Create a poll with options"; + var emotes = new List(); + emotes.Add(Emoji.Parse(":one:")); + emotes.Add(Emoji.Parse(":two:")); + emotes.Add(Emoji.Parse(":three:")); + emotes.Add(Emoji.Parse(":four:")); + emotes.Add(Emoji.Parse(":five:")); + emotes.Add(Emoji.Parse(":six:")); - public string Usage => "poll [This-is-question] [This-is-answer-1] [This-is-answer-2] ... "; - - public bool canUseDM => false; - - public bool canUseServer => true; - - public bool requireAdmin => true; - - public async void Execute(SocketCommandContext context, SocketMessage message, DiscordSocketClient client, bool isDM) - { - if (isDM) return; - string question = message.Content.Split(' ')[1].Replace('-', ' '); - string[] answers = PluginManager.Others.Functions.MergeStrings(message.Content.Split(' '), 2).Split(' '); - EmbedBuilder embedBuilder = new EmbedBuilder(); - embedBuilder.Title = question; - int len = answers.Length; - for (int i = 0; i < len; i++) - embedBuilder.AddField($"Answer {i + 1}", answers[i].Replace('-', ' '), true); - var msg = await context.Channel.SendMessageAsync(embed: embedBuilder.Build()); - - List emotes = new List(); - emotes.Add(Emoji.Parse(":one:")); - emotes.Add(Emoji.Parse(":two:")); - emotes.Add(Emoji.Parse(":three:")); - emotes.Add(Emoji.Parse(":four:")); - emotes.Add(Emoji.Parse(":five:")); - emotes.Add(Emoji.Parse(":six:")); - - for (int i = 0; i < len; i++) - await msg.AddReactionAsync(emotes[i]); - } + for (var i = 0; i < len; i++) await msg.AddReactionAsync(emotes[i]); } } diff --git a/CMD_Utils/Random.cs b/CMD_Utils/Random.cs index 4075588..2cbc564 100644 --- a/CMD_Utils/Random.cs +++ b/CMD_Utils/Random.cs @@ -1,6 +1,5 @@ using Discord.Commands; using Discord.WebSocket; - using PluginManager.Interfaces; public class Random : DBCommand @@ -11,7 +10,7 @@ public class Random : DBCommand public string Usage => "random [number1] [number2]"; - public bool canUseDM => true; + public bool canUseDM => true; public bool canUseServer => true; public bool requireAdmin => false; @@ -19,19 +18,18 @@ public class Random : DBCommand { try { - string msg = message.Content; - int a = int.Parse(msg.Split(' ')[1]); - int b = int.Parse(msg.Split(' ')[2]); + var msg = message.Content; + var a = int.Parse(msg.Split(' ')[1]); + var b = int.Parse(msg.Split(' ')[2]); if (a > b) { - int x = a; + var x = a; a = b; b = x; } await message.Channel.SendMessageAsync("Your random generated number is " + new System.Random().Next(a, b)); - } catch { diff --git a/DiscordBot/App.config b/DiscordBot/App.config index 828bd34..d78bbbb 100644 --- a/DiscordBot/App.config +++ b/DiscordBot/App.config @@ -1,7 +1,4 @@ - - - - - - - + + + + \ No newline at end of file diff --git a/DiscordBot/Discord/Commands/Help.cs b/DiscordBot/Discord/Commands/Help.cs index 26a1c51..11fb0f9 100644 --- a/DiscordBot/Discord/Commands/Help.cs +++ b/DiscordBot/Discord/Commands/Help.cs @@ -1,106 +1,100 @@ using Discord; using Discord.Commands; using Discord.WebSocket; - -using PluginManager.Loaders; using PluginManager.Interfaces; -using PluginManager.Others.Permissions; +using PluginManager.Loaders; using PluginManager.Others; -using System.Collections.Generic; +namespace DiscordBot.Discord.Commands; -namespace DiscordBot.Discord.Commands +/// +/// The help command +/// +internal class Help : DBCommand { /// - /// The help command + /// Command name /// - internal class Help : DBCommand + public string Command => "help"; + + /// + /// Command Description + /// + public string Description => "This command allows you to check all loadded commands"; + + /// + /// Command usage + /// + public string Usage => "help"; + + /// + /// Check if the command can be used /> + /// + public bool canUseDM => true; + + /// + /// Check if the command can be used in a server + /// + public bool canUseServer => true; + + /// + /// Check if the command require administrator to be executed + /// + public bool requireAdmin => false; + + /// + /// The main body of the command + /// + /// The command context + /// The command message + /// The discord bot client + /// True if the message was sent from a DM channel, false otherwise + public void Execute(SocketCommandContext context, SocketMessage message, DiscordSocketClient client, bool isDM) { - /// - /// Command name - /// - public string Command => "help"; - - /// - /// Command Description - /// - public string Description => "This command allows you to check all loadded commands"; - - /// - /// Command usage - /// - public string Usage => "help"; - - /// - /// Check if the command can be used /> - /// - public bool canUseDM => true; - - /// - /// Check if the command can be used in a server - /// - public bool canUseServer => true; - - /// - /// Check if the command require administrator to be executed - /// - public bool requireAdmin => false; - - /// - /// The main body of the command - /// - /// The command context - /// The command message - /// The discord bot client - /// True if the message was sent from a DM channel, false otherwise - public void Execute(SocketCommandContext context, SocketMessage message, DiscordSocketClient client, bool isDM) + var args = Functions.GetArguments(message); + if (args.Count != 0) { - List args = Functions.GetArguments(message); - if (args.Count != 0) + foreach (var item in args) { - - foreach (var item in args) - { - var e = GenerateHelpCommand(item); - if (e != null) - context.Channel.SendMessageAsync(embed: e.Build()); - else - context.Channel.SendMessageAsync("Unknown Command " + item); - } - return; - } - EmbedBuilder embedBuilder = new EmbedBuilder(); - - string adminCommands = ""; - string normalCommands = ""; - string DMCommands = ""; - - foreach (var cmd in PluginLoader.Commands!) - { - if (cmd.canUseDM) DMCommands += cmd.Command + " "; - if (cmd.requireAdmin) - adminCommands += cmd.Command + " "; - else if (cmd.canUseServer) normalCommands += cmd.Command + " "; + var e = GenerateHelpCommand(item); + if (e != null) + context.Channel.SendMessageAsync(embed: e.Build()); + else + context.Channel.SendMessageAsync("Unknown Command " + item); } - embedBuilder.AddField("Admin Commands", adminCommands); - embedBuilder.AddField("Normal Commands", normalCommands); - embedBuilder.AddField("DM Commands", DMCommands); - context.Channel.SendMessageAsync(embed: embedBuilder.Build()); - + return; } - private EmbedBuilder GenerateHelpCommand(string command) + var embedBuilder = new EmbedBuilder(); + + var adminCommands = ""; + var normalCommands = ""; + var DMCommands = ""; + + foreach (var cmd in PluginLoader.Commands!) { - EmbedBuilder embedBuilder = new EmbedBuilder(); - DBCommand cmd = PluginLoader.Commands.Find(p => p.Command == command); - if (cmd == null) - return null; - - embedBuilder.AddField("Usage", cmd.Usage); - embedBuilder.AddField("Description", cmd.Description); - - return embedBuilder; + if (cmd.canUseDM) DMCommands += cmd.Command + " "; + if (cmd.requireAdmin) + adminCommands += cmd.Command + " "; + else if (cmd.canUseServer) normalCommands += cmd.Command + " "; } + + embedBuilder.AddField("Admin Commands", adminCommands); + embedBuilder.AddField("Normal Commands", normalCommands); + embedBuilder.AddField("DM Commands", DMCommands); + context.Channel.SendMessageAsync(embed: embedBuilder.Build()); } -} \ No newline at end of file + + private EmbedBuilder GenerateHelpCommand(string command) + { + var embedBuilder = new EmbedBuilder(); + var cmd = PluginLoader.Commands.Find(p => p.Command == command); + if (cmd == null) return null; + + embedBuilder.AddField("Usage", cmd.Usage); + embedBuilder.AddField("Description", cmd.Description); + + return embedBuilder; + } +} diff --git a/DiscordBot/Discord/Commands/Restart.cs b/DiscordBot/Discord/Commands/Restart.cs index 3808118..a567783 100644 --- a/DiscordBot/Discord/Commands/Restart.cs +++ b/DiscordBot/Discord/Commands/Restart.cs @@ -1,114 +1,113 @@ using System; using System.Diagnostics; - using Discord.WebSocket; +using PluginManager.Interfaces; +using PluginManager.Others; +using PluginManager.Others.Permissions; using DiscordLibCommands = Discord.Commands; using DiscordLib = Discord; +using OperatingSystem = PluginManager.Others.OperatingSystem; -using PluginManager.Interfaces; -using PluginManager.Others.Permissions; -using PluginManager.Others; +namespace DiscordBot.Discord.Commands; -namespace DiscordBot.Discord.Commands +internal class Restart : DBCommand { - internal class Restart : DBCommand + /// + /// Command name + /// + public string Command => "restart"; + + /// + /// Command Description + /// + public string Description => "Restart the bot"; + + /// + /// Command usage + /// + public string Usage => "restart [-p | -c | -args | -cmd] "; + + /// + /// Check if the command can be used /> + /// + public bool canUseDM => false; + + /// + /// Check if the command can be used in a server + /// + public bool canUseServer => true; + + /// + /// Check if the command require administrator to be executed + /// + public bool requireAdmin => false; + + /// + /// The main body of the command + /// + /// The command context + /// The command message + /// The discord bot client + /// True if the message was sent from a DM channel, false otherwise + public async void Execute(DiscordLibCommands.SocketCommandContext context, SocketMessage message, DiscordSocketClient client, bool isDM) { - /// - /// Command name - /// - public string Command => "restart"; - - /// - /// Command Description - /// - public string Description => "Restart the bot"; - - /// - /// Command usage - /// - public string Usage => "restart [-p | -c | -args | -cmd] "; - - /// - /// Check if the command can be used /> - /// - public bool canUseDM => false; - - /// - /// Check if the command can be used in a server - /// - public bool canUseServer => true; - - /// - /// Check if the command require administrator to be executed - /// - public bool requireAdmin => false; - /// - /// The main body of the command - /// - /// The command context - /// The command message - /// The discord bot client - /// True if the message was sent from a DM channel, false otherwise - public async void Execute(DiscordLibCommands.SocketCommandContext context, SocketMessage message, DiscordSocketClient client, bool isDM) + if (!(message.Author as SocketGuildUser).hasPermission(DiscordLib.GuildPermission.Administrator)) return; + var args = Functions.GetArguments(message); + var OS = Functions.GetOperatingSystem(); + if (args.Count == 0) { - if (!DiscordPermissions.hasPermission(message.Author as SocketGuildUser, DiscordLib.GuildPermission.Administrator)) return; - var args = Functions.GetArguments(message); - var OS = Functions.GetOperatingSystem(); - if (args.Count == 0) + switch (OS) { + case OperatingSystem.WINDOWS: + Process.Start("./DiscordBot.exe"); + break; + case OperatingSystem.LINUX: + case OperatingSystem.MAC_OS: + Process.Start("./DiscordBot"); + break; + default: + return; + } + + return; + } + + switch (args[0]) + { + case "-p": + case "-poweroff": + case "-c": + case "-close": + Environment.Exit(0); + break; + case "-cmd": + case "-args": + var cmd = "--args"; + + if (args.Count > 1) + for (var i = 1; i < args.Count; i++) + cmd += $" {args[i]}"; + + switch (OS) { - case PluginManager.Others.OperatingSystem.WINDOWS: - Process.Start("./DiscordBot.exe"); + case OperatingSystem.WINDOWS: + Functions.WriteLogFile("Restarting the bot with the following arguments: \"" + cmd + "\""); + Process.Start("./DiscordBot.exe", cmd); break; - case PluginManager.Others.OperatingSystem.LINUX: - case PluginManager.Others.OperatingSystem.MAC_OS: - Process.Start("./DiscordBot"); + case OperatingSystem.LINUX: + //case PluginManager.Others.OperatingSystem.MAC_OS: ?? - not tested + Process.Start("./DiscordBot", cmd); break; default: return; } - return; - } - switch (args[0]) - { - case "-p": - case "-poweroff": - case "-c": - case "-close": - Environment.Exit(0); - break; - case "-cmd": - case "-args": - string cmd = "--args"; - - if (args.Count > 1) - for (int i = 1; i < args.Count; i++) - cmd += $" {args[i]}"; - - - switch (OS) - { - case PluginManager.Others.OperatingSystem.WINDOWS: - Functions.WriteLogFile("Restarting the bot with the following arguments: \"" + cmd + "\""); - Process.Start("./DiscordBot.exe", cmd); - break; - case PluginManager.Others.OperatingSystem.LINUX: - //case PluginManager.Others.OperatingSystem.MAC_OS: ?? - not tested - Process.Start("./DiscordBot", cmd); - break; - default: - return; - } - Environment.Exit(0); - break; - default: - await context.Channel.SendMessageAsync("Invalid argument. Use `help restart` to see the usage."); - break; - - - } + Environment.Exit(0); + break; + default: + await context.Channel.SendMessageAsync("Invalid argument. Use `help restart` to see the usage."); + break; } } } diff --git a/DiscordBot/Discord/Commands/Settings.cs b/DiscordBot/Discord/Commands/Settings.cs index a432c96..044a2fd 100644 --- a/DiscordBot/Discord/Commands/Settings.cs +++ b/DiscordBot/Discord/Commands/Settings.cs @@ -1,107 +1,97 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; using Discord; using Discord.Commands; using Discord.WebSocket; -using DiscordBot.Discord.Core; using PluginManager; using PluginManager.Interfaces; -using PluginManager.Others; -using PluginManager.Others.Permissions; -namespace DiscordBot.Discord.Commands +namespace DiscordBot.Discord.Commands; + +internal class Settings : DBCommand { - class Settings : DBCommand + /// + /// Command name + /// + public string Command => "set"; + + /// + /// Command Description + /// + public string Description => "This command allows you change all settings. Use \"set help\" to show details"; + + /// + /// Command usage + /// + public string Usage => "set [keyword] [new Value]"; + + /// + /// Check if the command can be used /> + /// + public bool canUseDM => true; + + /// + /// Check if the command can be used in a server + /// + public bool canUseServer => true; + + /// + /// Check if the command require administrator to be executed + /// + public bool requireAdmin => true; + + /// + /// The main body of the command + /// + /// The command context + /// The command message + /// The discord bot client + /// True if the message was sent from a DM channel, false otherwise + public async void Execute(SocketCommandContext context, SocketMessage message, DiscordSocketClient client, bool isDM) { - - /// - /// Command name - /// - public string Command => "set"; - - /// - /// Command Description - /// - public string Description => "This command allows you change all settings. Use \"set help\" to show details"; - - /// - /// Command usage - /// - public string Usage => "set [keyword] [new Value]"; - - /// - /// Check if the command can be used /> - /// - public bool canUseDM => true; - - /// - /// Check if the command can be used in a server - /// - public bool canUseServer => true; - - /// - /// Check if the command require administrator to be executed - /// - public bool requireAdmin => true; - - /// - /// The main body of the command - /// - /// The command context - /// The command message - /// The discord bot client - /// True if the message was sent from a DM channel, false otherwise - public async void Execute(SocketCommandContext context, SocketMessage message, DiscordSocketClient client, bool isDM) + var channel = message.Channel; + try { - var channel = message.Channel; - try + var content = message.Content; + var data = content.Split(' '); + var keyword = data[1]; + if (keyword.ToLower() == "help") { - string content = message.Content; - string[] data = content.Split(' '); - string keyword = data[1]; - if (keyword.ToLower() == "help") - { - await channel.SendMessageAsync("set token [new value] -- set the value of the new token (require restart)"); - await channel.SendMessageAsync("set prefix [new value] -- set the value of the new preifx (require restart)"); + await channel.SendMessageAsync("set token [new value] -- set the value of the new token (require restart)"); + await channel.SendMessageAsync("set prefix [new value] -- set the value of the new preifx (require restart)"); - return; - } + return; + } - switch (keyword.ToLower()) - { - case "token": - if (data.Length != 3) - { - await channel.SendMessageAsync("Invalid token !"); - return; - } - - Config.SetValue("token", data[2]); - break; - case "prefix": - if (data.Length != 3) - { - await channel.SendMessageAsync("Invalid token !"); - return; - } - - Config.SetValue("token", data[2]); - break; - default: + switch (keyword.ToLower()) + { + case "token": + if (data.Length != 3) + { + await channel.SendMessageAsync("Invalid token !"); return; - } + } - await channel.SendMessageAsync("Restart required ..."); - } - catch (Exception ex) - { - Console.WriteLine(ex.Message); - await channel.SendMessageAsync("Unknown usage to this command !\nUsage: " + Usage); + Config.SetValue("token", data[2]); + break; + case "prefix": + if (data.Length != 3) + { + await channel.SendMessageAsync("Invalid token !"); + return; + } + + Config.SetValue("token", data[2]); + break; + default: + return; } + await channel.SendMessageAsync("Restart required ..."); + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + await channel.SendMessageAsync("Unknown usage to this command !\nUsage: " + Usage); } } } diff --git a/DiscordBot/Discord/Core/Boot.cs b/DiscordBot/Discord/Core/Boot.cs index 942178f..af38879 100644 --- a/DiscordBot/Discord/Core/Boot.cs +++ b/DiscordBot/Discord/Core/Boot.cs @@ -1,150 +1,149 @@ -using Discord; -using Discord.Commands; -using Discord.WebSocket; -using System; +using System; using System.Threading; using System.Threading.Tasks; +using Discord; +using Discord.Commands; +using Discord.WebSocket; using PluginManager; using static PluginManager.Others.Functions; -namespace DiscordBot.Discord.Core +namespace DiscordBot.Discord.Core; + +internal class Boot { - internal class Boot + /// + /// The bot prefix + /// + public readonly string botPrefix; + + /// + /// The bot token + /// + public readonly string botToken; + + /// + /// The bot client + /// + public DiscordSocketClient client; + + /// + /// The bot command handler + /// + private CommandHandler commandServiceHandler; + + /// + /// The command service + /// + private CommandService service; + + /// + /// The main Boot constructor + /// + /// The bot token + /// The bot prefix + public Boot(string botToken, string botPrefix) { - /// - /// The bot prefix - /// - public readonly string botPrefix; - - /// - /// The bot token - /// - public readonly string botToken; + this.botPrefix = botPrefix; + this.botToken = botToken; + } - /// - /// Checks if the bot is ready - /// - /// true if the bot is ready, othwerwise false - public bool isReady { get; private set; } = false; + /// + /// Checks if the bot is ready + /// + /// true if the bot is ready, othwerwise false + public bool isReady { get; private set; } - /// - /// The bot client - /// - public DiscordSocketClient client; + /// + /// The start method for the bot. This method is used to load the bot + /// + /// Task + public async Task Awake() + { + client = new DiscordSocketClient(); + service = new CommandService(); - /// - /// The bot command handler - /// - private CommandHandler commandServiceHandler; + CommonTasks(); - /// - /// The command service - /// - private CommandService service; + await client.LoginAsync(TokenType.Bot, botToken); + await client.StartAsync(); - /// - /// The main Boot constructor - /// - /// The bot token - /// The bot prefix - public Boot(string botToken, string botPrefix) - { - this.botPrefix = botPrefix; - this.botToken = botToken; - } + commandServiceHandler = new CommandHandler(client, service, botPrefix); + await commandServiceHandler.InstallCommandsAsync(); - /// - /// The start method for the bot. This method is used to load the bot - /// - /// Task - public async Task Awake() - { - client = new DiscordSocketClient(); - service = new CommandService(); + await Task.Delay(2000); + while (!isReady) ; + } - CommonTasks(); + private void CommonTasks() + { + if (client == null) return; + client.LoggedOut += Client_LoggedOut; + client.Log += Log; + client.LoggedIn += LoggedIn; + client.Ready += Ready; + } - await client.LoginAsync(TokenType.Bot, botToken); - await client.StartAsync(); + private Task Client_LoggedOut() + { + WriteLogFile("Successfully Logged Out"); + Log(new LogMessage(LogSeverity.Info, "Boot", "Successfully logged out from discord !")); + return Task.CompletedTask; + } - commandServiceHandler = new CommandHandler(client, service, botPrefix); - await commandServiceHandler.InstallCommandsAsync(); + private Task Ready() + { + Console.Title = "ONLINE"; + isReady = true; - await Task.Delay(2000); - while (!isReady) ; - - } - - private void CommonTasks() - { - if (client == null) return; - client.LoggedOut += Client_LoggedOut; - client.Log += Log; - client.LoggedIn += LoggedIn; - client.Ready += Ready; - } - - private Task Client_LoggedOut() - { - WriteLogFile("Successfully Logged Out"); - Log(new LogMessage(LogSeverity.Info, "Boot", "Successfully logged out from discord !")); - return Task.CompletedTask; - } - - private Task Ready() - { - Console.Title = "ONLINE"; - isReady = true; - - new Thread(async () => - { - while (true) - { - Config.SaveConfig(); - Thread.Sleep(10000); - } - } - ).Start(); - - return Task.CompletedTask; - } - - private Task LoggedIn() - { - Console.Title = "CONNECTED"; - WriteLogFile("The bot has been logged in at " + DateTime.Now.ToShortDateString() + " (" + - DateTime.Now.ToShortTimeString() + ")"); - return Task.CompletedTask; - } - - private Task Log(LogMessage message) - { - switch (message.Severity) + new Thread(async () => { - case LogSeverity.Error: - case LogSeverity.Critical: - WriteErrFile(message.Message); - - Console.ForegroundColor = ConsoleColor.Red; - Console.WriteLine("[ERROR] " + message.Message); - Console.ForegroundColor = ConsoleColor.White; - - break; - - case LogSeverity.Info: - case LogSeverity.Debug: - WriteLogFile(message.Message); - - Console.ForegroundColor = ConsoleColor.Cyan; - Console.WriteLine("[INFO] " + message.Message); - Console.ForegroundColor = ConsoleColor.White; - - - break; + while (true) + { + Config.SaveConfig(); + Thread.Sleep(10000); + } } + ).Start(); - return Task.CompletedTask; + return Task.CompletedTask; + } + + private Task LoggedIn() + { + Console.Title = "CONNECTED"; + WriteLogFile("The bot has been logged in at " + DateTime.Now.ToShortDateString() + " (" + + DateTime.Now.ToShortTimeString() + ")" + ); + return Task.CompletedTask; + } + + private Task Log(LogMessage message) + { + switch (message.Severity) + { + case LogSeverity.Error: + case LogSeverity.Critical: + WriteErrFile(message.Message); + + Console.ForegroundColor = ConsoleColor.Red; + Console.WriteLine("[ERROR] " + message.Message); + Console.ForegroundColor = ConsoleColor.White; + + break; + + case LogSeverity.Info: + case LogSeverity.Debug: + WriteLogFile(message.Message); + + Console.ForegroundColor = ConsoleColor.Cyan; + Console.WriteLine("[INFO] " + message.Message); + Console.ForegroundColor = ConsoleColor.White; + + + break; } + + return Task.CompletedTask; } } diff --git a/DiscordBot/Discord/Core/CommandHandler.cs b/DiscordBot/Discord/Core/CommandHandler.cs index 16ed690..b876858 100644 --- a/DiscordBot/Discord/Core/CommandHandler.cs +++ b/DiscordBot/Discord/Core/CommandHandler.cs @@ -1,136 +1,132 @@ -using Discord.Commands; -using Discord.WebSocket; - -using PluginManager.Interfaces; - +using System.Linq; using System.Reflection; +using System.Threading.Tasks; +using Discord.Commands; +using Discord.WebSocket; +using PluginManager.Loaders; using PluginManager.Others; using PluginManager.Others.Permissions; -using PluginManager.Loaders; -using System.Threading.Tasks; -using System.Linq; -using Discord; -using System; +namespace DiscordBot.Discord.Core; -namespace DiscordBot.Discord.Core +internal class CommandHandler { - internal class CommandHandler + private readonly string botPrefix; + private readonly DiscordSocketClient client; + private readonly CommandService commandService; + + /// + /// Command handler constructor + /// + /// The discord bot client + /// The discord bot command service + /// The prefix to watch for + public CommandHandler(DiscordSocketClient client, CommandService commandService, string botPrefix) { - private readonly DiscordSocketClient client; - private readonly CommandService commandService; - private readonly string botPrefix; + this.client = client; + this.commandService = commandService; + this.botPrefix = botPrefix; + } - /// - /// Command handler constructor - /// - /// The discord bot client - /// The discord bot command service - /// The prefix to watch for - public CommandHandler(DiscordSocketClient client, CommandService commandService, string botPrefix) - { - this.client = client; - this.commandService = commandService; - this.botPrefix = botPrefix; - } + /// + /// The method to initialize all commands + /// + /// + public async Task InstallCommandsAsync() + { + client.MessageReceived += MessageHandler; + await commandService.AddModulesAsync(Assembly.GetEntryAssembly(), null); + } - /// - /// The method to initialize all commands - /// - /// - public async Task InstallCommandsAsync() + /// + /// The message handler for the bot + /// + /// The message got from the user in discord chat + /// + private async Task MessageHandler(SocketMessage Message) + { + try { - client.MessageReceived += MessageHandler; - await commandService.AddModulesAsync(assembly: Assembly.GetEntryAssembly(), services: null); - } + if (Message as SocketUserMessage == null) return; - /// - /// The message handler for the bot - /// - /// The message got from the user in discord chat - /// - private async Task MessageHandler(SocketMessage Message) - { - try + var message = Message as SocketUserMessage; + + if (message == null) return; + + if (!message.Content.StartsWith(botPrefix)) return; + + var argPos = 0; + + if (message.HasMentionPrefix(client.CurrentUser, ref argPos)) { - if (Message as SocketUserMessage == null) - return; + await message.Channel.SendMessageAsync("Can not exec mentioned commands !"); + return; + } - var message = Message as SocketUserMessage; + if (message.Author.IsBot) return; - if (message == null) return; + var context = new SocketCommandContext(client, message); - if (!message.Content.StartsWith(botPrefix)) return; + await commandService.ExecuteAsync( + context, + argPos, + null + ); - int argPos = 0; + var plugin = PluginLoader.Commands!.Where(p => p.Command == message.Content.Split(' ')[0].Substring(botPrefix.Length)).FirstOrDefault(); - if (message.HasMentionPrefix(client.CurrentUser, ref argPos)) + + if (plugin != null) + { + if (message.Channel == await message.Author.CreateDMChannelAsync()) { - await message.Channel.SendMessageAsync("Can not exec mentioned commands !"); - return; - } - - if (message.Author.IsBot) return; - - var context = new SocketCommandContext(client, message); - - await commandService.ExecuteAsync( - context: context, - argPos: argPos, - services: null - ); - - DBCommand plugin = PluginLoader.Commands!.Where(p => p.Command == (message.Content.Split(' ')[0]).Substring(botPrefix.Length)).FirstOrDefault(); - - - if (plugin != null) - { - if (message.Channel == await message.Author.CreateDMChannelAsync()) - { - if (plugin.canUseDM) - { - if (plugin.requireAdmin) - { - if (message.Author.isAdmin()) - { - plugin.Execute(context, message, client, true); - Functions.WriteLogFile($"[{message.Author.Id}] Executed command (DM) : " + plugin.Command); - return; - } - await message.Channel.SendMessageAsync("This command is for administrators only !"); - return; - } - plugin.Execute(context, message, client, true); - Functions.WriteLogFile($"[{message.Author.Id}] Executed command (DM) : " + plugin.Command); - return; - } - - await message.Channel.SendMessageAsync("This command is not for DMs"); - return; - } - if (plugin.canUseServer) + if (plugin.canUseDM) { if (plugin.requireAdmin) { if (message.Author.isAdmin()) { - plugin.Execute(context, message, client, false); - Functions.WriteLogFile($"[{message.Author.Id}] Executed command : " + plugin.Command); + plugin.Execute(context, message, client, true); + Functions.WriteLogFile($"[{message.Author.Id}] Executed command (DM) : " + plugin.Command); return; } + await message.Channel.SendMessageAsync("This command is for administrators only !"); return; } - plugin.Execute(context, message, client, false); - Functions.WriteLogFile($"[{message.Author.Id}] Executed command : " + plugin.Command); + + plugin.Execute(context, message, client, true); + Functions.WriteLogFile($"[{message.Author.Id}] Executed command (DM) : " + plugin.Command); return; } - return; + await message.Channel.SendMessageAsync("This command is not for DMs"); + return; + } + + if (plugin.canUseServer) + { + if (plugin.requireAdmin) + { + if (message.Author.isAdmin()) + { + plugin.Execute(context, message, client, false); + Functions.WriteLogFile($"[{message.Author.Id}] Executed command : " + plugin.Command); + return; + } + + await message.Channel.SendMessageAsync("This command is for administrators only !"); + return; + } + + plugin.Execute(context, message, client, false); + Functions.WriteLogFile($"[{message.Author.Id}] Executed command : " + plugin.Command); + return; } } - catch { } - + } + catch + { } } -} \ No newline at end of file +} diff --git a/DiscordBot/Program.cs b/DiscordBot/Program.cs index 28d6370..909558e 100644 --- a/DiscordBot/Program.cs +++ b/DiscordBot/Program.cs @@ -6,15 +6,14 @@ using System; using System.IO; using System.Linq; using System.Threading.Tasks; +using PluginManager.Online; namespace DiscordBot { public class Program { - private static bool loadPluginsOnStartup = false; - private static bool listPluginsAtStartup = false; - - private static bool listLanguagAtStartup = false; + private static bool loadPluginsOnStartup = false; + private static bool listPluginsAtStartup = false; /// /// The main entry point for the application. @@ -27,13 +26,7 @@ namespace DiscordBot Directory.CreateDirectory("./Data/Languages"); Directory.CreateDirectory("./Data/Plugins/Commands"); Directory.CreateDirectory("./Data/Plugins/Events"); - Config.LoadConfig().Wait(); - - if (Config.ContainsKey("DeleteLogsAtStartup")) - if (Config.GetValue("DeleteLogsAtStartup")) - foreach (string file in Directory.GetFiles("./Output/Logs/")) - File.Delete(file); - + PreLoadComponents(); if (!Config.ContainsKey("token") || Config.GetValue("token") == null || Config.GetValue("token")?.Length != 70) { @@ -84,7 +77,6 @@ namespace DiscordBot ConsoleCommandsHandler consoleCommandsHandler = new ConsoleCommandsHandler(discordbooter.client); if (loadPluginsOnStartup) consoleCommandsHandler.HandleCommand("lp"); if (listPluginsAtStartup) consoleCommandsHandler.HandleCommand("listplugs"); - if (listLanguagAtStartup) consoleCommandsHandler.HandleCommand("listlang"); Config.SaveConfig(); while (true) { @@ -165,12 +157,20 @@ namespace DiscordBot 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 (args.Contains("lp") || args.Contains("loadplugins")) loadPluginsOnStartup = true; if (args.Contains("listplugs")) listPluginsAtStartup = true; - if (args.Contains("listlang")) listLanguagAtStartup = true; - //if (args.Contains("--nomessage")) ShowStartupMessage = false; len = 0; } @@ -182,6 +182,7 @@ namespace DiscordBot return; } + Console.ForegroundColor = ConsoleColor.DarkYellow; Console.WriteLine("Execute command interface noGUI\n\n"); Console.WriteLine( @@ -240,11 +241,22 @@ namespace DiscordBot Boot booter = await StartNoGUI(); await NoGUI(booter); return; + default: Console.WriteLine("Failed to execute command " + message[0]); break; } } } + + private static async Task PreLoadComponents() + { + Config.LoadConfig().Wait(); + + if (Config.ContainsKey("DeleteLogsAtStartup")) + if (Config.GetValue("DeleteLogsAtStartup")) + foreach (string file in Directory.GetFiles("./Output/Logs/")) + File.Delete(file); + } } } diff --git a/DiscordBotGUI/App.axaml b/DiscordBotGUI/App.axaml index 7d4aeba..49aa2e5 100644 --- a/DiscordBotGUI/App.axaml +++ b/DiscordBotGUI/App.axaml @@ -1,7 +1,7 @@ - - - - + + + + \ No newline at end of file diff --git a/DiscordBotGUI/App.axaml.cs b/DiscordBotGUI/App.axaml.cs index 456aca5..983b886 100644 --- a/DiscordBotGUI/App.axaml.cs +++ b/DiscordBotGUI/App.axaml.cs @@ -1,23 +1,21 @@ -using System.IO; using Avalonia; +using Avalonia.Controls; using Avalonia.Controls.ApplicationLifetimes; using Avalonia.Markup.Xaml; -using PluginManager.Others; -namespace DiscordBotGUI +namespace DiscordBotGUI; + +public class App : Application { - public partial class App : Application + public override void Initialize() { - public override void Initialize() - { - AvaloniaXamlLoader.Load(this); - } + AvaloniaXamlLoader.Load(this); + } - public override void OnFrameworkInitializationCompleted() - { - if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop) { desktop.MainWindow = new AppUpdater() { Width = 300, Height = 50, WindowStartupLocation = Avalonia.Controls.WindowStartupLocation.CenterScreen }; } + public override void OnFrameworkInitializationCompleted() + { + if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop) desktop.MainWindow = new AppUpdater { Width = 300, Height = 50, WindowStartupLocation = WindowStartupLocation.CenterScreen }; - base.OnFrameworkInitializationCompleted(); - } + base.OnFrameworkInitializationCompleted(); } } diff --git a/DiscordBotGUI/AppUpdater.axaml b/DiscordBotGUI/AppUpdater.axaml index c20c2e5..939c0d6 100644 --- a/DiscordBotGUI/AppUpdater.axaml +++ b/DiscordBotGUI/AppUpdater.axaml @@ -5,12 +5,13 @@ mc:Ignorable="d" d:DesignWidth="250" d:DesignHeight="50" x:Class="DiscordBotGUI.AppUpdater" Title="AppUpdater" - Background="Transparent" - TransparencyLevelHint="AcrylicBlur" - HasSystemDecorations="False"> + Background="Transparent" + TransparencyLevelHint="AcrylicBlur" + SystemDecorations="BorderOnly"> - - - - - + + + + + \ No newline at end of file diff --git a/DiscordBotGUI/AppUpdater.axaml.cs b/DiscordBotGUI/AppUpdater.axaml.cs index 662e2c8..fcf519f 100644 --- a/DiscordBotGUI/AppUpdater.axaml.cs +++ b/DiscordBotGUI/AppUpdater.axaml.cs @@ -11,7 +11,7 @@ namespace DiscordBotGUI { public partial class AppUpdater : Window { - private string _version; + private string _version = ""; public AppUpdater() { @@ -149,7 +149,7 @@ namespace DiscordBotGUI { try { - string current_version = Config.GetValue("Version"); + string current_version = Config.GetValue("Version"); if (current_version == null) if (!Config.SetValue("Version", "0")) Config.AddValueToVariables("Version", "0", false); diff --git a/DiscordBotGUI/MainWindow.axaml b/DiscordBotGUI/MainWindow.axaml index b3f98c7..c011ce7 100644 --- a/DiscordBotGUI/MainWindow.axaml +++ b/DiscordBotGUI/MainWindow.axaml @@ -5,32 +5,35 @@ mc:Ignorable="d" d:DesignWidth="500" d:DesignHeight="425" x:Class="DiscordBotGUI.MainWindow" Title="DiscordBotGUI" - Background="Transparent" - TransparencyLevelHint="AcrylicBlur" - ExtendClientAreaToDecorationsHint="True" > + Background="Transparent" + TransparencyLevelHint="AcrylicBlur" + ExtendClientAreaToDecorationsHint="True"> - - - - - + + + + + - - - + public class ProgressBar { - public int Max { get; set; } - public string Message { get; set; } + public int Max { 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) { - - //progress bar Console.CursorLeft = 0; Console.Write("["); Console.CursorLeft = 32; @@ -38,15 +28,21 @@ namespace PluginManager.Others for (int i = 0; i < onechunk * progress; i++) { - Console.BackgroundColor = this.Color; + if (NoColor) + Console.BackgroundColor = ConsoleColor.Black; //this.Color + else + Console.BackgroundColor = this.Color; Console.CursorLeft = position++; - Console.Write(" "); + Console.Write("#"); } for (int i = position; i <= 31; i++) { - Console.BackgroundColor = ConsoleColor.Gray; - Console.CursorLeft = position++; + if (NoColor) + Console.BackgroundColor = ConsoleColor.Black; // background of empty bar + else + Console.BackgroundColor = ConsoleColor.DarkGray; + Console.CursorLeft = position++; Console.Write(" "); } diff --git a/PluginManager/Others/Cryptography.cs b/PluginManager/Others/Cryptography.cs index e2c13de..04864ae 100644 --- a/PluginManager/Others/Cryptography.cs +++ b/PluginManager/Others/Cryptography.cs @@ -1,91 +1,88 @@ 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 + /// + /// Translate hex to string + /// + /// The encrypted string + /// + public static string FromHexToString(string hexString) { + var bytes = new byte[hexString.Length / 2]; + for (var i = 0; i < bytes.Length; i++) bytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16); - /// - /// Translate hex to string - /// - /// The encrypted string - /// - public static string FromHexToString(string hexString) - { - var bytes = new byte[hexString.Length / 2]; - for (var i = 0; i < bytes.Length; i++) - { - bytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16); - } - - return System.Text.Encoding.Unicode.GetString(bytes); - } - - /// - /// Translate string to hex - /// - /// The string to encrypt - /// - public static string ToHexString(string str) - { - var sb = new System.Text.StringBuilder(); - - var bytes = System.Text.Encoding.Unicode.GetBytes(str); - foreach (var t in bytes) - { - sb.Append(t.ToString("X2")); - } - - return sb.ToString(); - } - - /// - /// Create MD5 hash - /// - /// The text to encrypt - /// - public static async System.Threading.Tasks.Task CreateMD5(string text) - { - string output = ""; - using (System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create()) - { - using (var s = GenerateStreamFromString(text)) - { - byte[] t = await md5.ComputeHashAsync(s); - output = System.Convert.ToBase64String(t); - } - } - - return output; - } - - /// - /// Create SHA256 hash - /// - /// The text to encrypt - /// - public static async System.Threading.Tasks.Task CreateSHA256(string text) - { - string output = ""; - using (System.Security.Cryptography.SHA256 sha = System.Security.Cryptography.SHA256.Create()) - { - using (var s = GenerateStreamFromString(text)) - { - byte[] t = await sha.ComputeHashAsync(s); - output = System.Convert.ToBase64String(t); - } - } - return output; - } - - private static System.IO.Stream GenerateStreamFromString(string s) - { - var stream = new System.IO.MemoryStream(); - var writer = new System.IO.StreamWriter(stream); - writer.Write(s); - writer.Flush(); - stream.Position = 0; - return stream; - } + return Encoding.Unicode.GetString(bytes); } -} \ No newline at end of file + + /// + /// Translate string to hex + /// + /// The string to encrypt + /// + public static string ToHexString(string str) + { + var sb = new StringBuilder(); + + var bytes = Encoding.Unicode.GetBytes(str); + foreach (var t in bytes) sb.Append(t.ToString("X2")); + + return sb.ToString(); + } + + /// + /// Create MD5 hash + /// + /// The text to encrypt + /// + public static async Task CreateMD5(string text) + { + var output = ""; + using (var md5 = MD5.Create()) + { + using (var s = GenerateStreamFromString(text)) + { + var t = await md5.ComputeHashAsync(s); + output = Convert.ToBase64String(t); + } + } + + return output; + } + + /// + /// Create SHA256 hash + /// + /// The text to encrypt + /// + public static async Task CreateSHA256(string text) + { + var output = ""; + using (var sha = SHA256.Create()) + { + using (var s = GenerateStreamFromString(text)) + { + var t = await sha.ComputeHashAsync(s); + output = Convert.ToBase64String(t); + } + } + + return output; + } + + private static Stream GenerateStreamFromString(string s) + { + var stream = new MemoryStream(); + var writer = new StreamWriter(stream); + writer.Write(s); + writer.Flush(); + stream.Position = 0; + return stream; + } +} diff --git a/PluginManager/Others/Enums.cs b/PluginManager/Others/Enums.cs index 222e169..d8b22fb 100644 --- a/PluginManager/Others/Enums.cs +++ b/PluginManager/Others/Enums.cs @@ -1,20 +1,22 @@ -namespace PluginManager.Others +namespace PluginManager.Others; + +/// +/// A list of operating systems +/// +public enum OperatingSystem { + WINDOWS, LINUX, MAC_OS, UNKNOWN +} - /// - /// A list of operating systems - /// - public enum OperatingSystem - { WINDOWS, LINUX, MAC_OS, UNKNOWN } +/// +/// A list with all errors +/// +public enum Error +{ + UNKNOWN_ERROR, GUILD_NOT_FOUND, STREAM_NOT_FOUND, INVALID_USER, INVALID_CHANNEL, INVALID_PERMISSIONS +} - /// - /// A list with all errors - /// - public enum Error - { UNKNOWN_ERROR, GUILD_NOT_FOUND, STREAM_NOT_FOUND, INVALID_USER, INVALID_CHANNEL, INVALID_PERMISSIONS } - - /// - /// The output log type - /// - public enum OutputLogLevel { NONE, INFO, WARNING, ERROR, CRITICAL } -} \ No newline at end of file +/// +/// The output log type +/// +public enum OutputLogLevel { NONE, INFO, WARNING, ERROR, CRITICAL } diff --git a/PluginManager/Others/Exceptions/APIException.cs b/PluginManager/Others/Exceptions/APIException.cs index 990704f..37264c1 100644 --- a/PluginManager/Others/Exceptions/APIException.cs +++ b/PluginManager/Others/Exceptions/APIException.cs @@ -1,94 +1,91 @@ using System; -namespace PluginManager.Others.Exceptions +namespace PluginManager.Others.Exceptions; + +/// +/// Custom Exception for PluginManager +/// +[Serializable] +public class APIException : Exception { /// - /// Custom Exception for PluginManager + /// The APIException contructor /// - [Serializable] - - public class APIException : Exception + /// The error message + /// The function where the message was triggered + /// The possible cause of the error + /// The error code + public APIException(string message, string? function, string possible_cause, Error error) : base(message) { - /// - /// The function where the error occurred - /// - public string? Function { get; } = "not specified"; - - /// - /// The error code - /// - public Error? ErrorCode { get; } = Error.UNKNOWN_ERROR; - - /// - /// The possible cause that determined the error - /// - public string? PossibleCause { get; } = "not specified"; - - /// - /// The APIException contructor - /// - /// The error message - /// The function where the message was triggered - /// The possible cause of the error - /// The error code - public APIException(string message, string? function, string possible_cause, Error error) : base(message) - { - ErrorCode = error; - Function = function; - PossibleCause = possible_cause; - } - - /// - /// The APIException contructor - /// - /// The error message - /// The function where the message was triggered - /// The error code - public APIException(string message, string? function, Error? errorCode) : base(message) - { - ErrorCode = errorCode; - Function = function; - } - /// - /// The APIException contructor - /// - /// The error message - /// The function where the message was triggered - public APIException(string message, string? function) : base(message) - { - Function = function; - } - /// - /// The APIException contructor - /// - /// The error message - public APIException(string message) : base(message) - { - - } - - /// - /// The APIException constructor - /// - /// The error message - /// The class where the error was thrown - public APIException(string message, Type errorLocation) : base(message) - { - Function = errorLocation.FullName; - } - - /// - /// Method to print the error to - /// - public void Print() - { - Console.WriteLine("Message Content: " + Message); - Console.WriteLine("Function: " + Function); - Console.WriteLine("Error Code: " + ErrorCode.ToString()); - Console.WriteLine("Possible cause: " + PossibleCause); - if (this.StackTrace != null) - Functions.WriteErrFile(this.StackTrace); - } + ErrorCode = error; + Function = function; + PossibleCause = possible_cause; } -} \ No newline at end of file + /// + /// The APIException contructor + /// + /// The error message + /// The function where the message was triggered + /// The error code + public APIException(string message, string? function, Error? errorCode) : base(message) + { + ErrorCode = errorCode; + Function = function; + } + + /// + /// The APIException contructor + /// + /// The error message + /// The function where the message was triggered + public APIException(string message, string? function) : base(message) + { + Function = function; + } + + /// + /// The APIException contructor + /// + /// The error message + public APIException(string message) : base(message) + { + } + + /// + /// The APIException constructor + /// + /// The error message + /// The class where the error was thrown + public APIException(string message, Type errorLocation) : base(message) + { + Function = errorLocation.FullName; + } + + /// + /// The function where the error occurred + /// + public string? Function { get; } = "not specified"; + + /// + /// The error code + /// + public Error? ErrorCode { get; } = Error.UNKNOWN_ERROR; + + /// + /// The possible cause that determined the error + /// + public string? PossibleCause { get; } = "not specified"; + + /// + /// Method to print the error to + /// + public void Print() + { + Console.WriteLine("Message Content: " + Message); + Console.WriteLine("Function: " + Function); + Console.WriteLine("Error Code: " + ErrorCode); + Console.WriteLine("Possible cause: " + PossibleCause); + if (StackTrace != null) Functions.WriteErrFile(StackTrace); + } +} diff --git a/PluginManager/Others/Functions.cs b/PluginManager/Others/Functions.cs index 0baf0c1..93e85d9 100644 --- a/PluginManager/Others/Functions.cs +++ b/PluginManager/Others/Functions.cs @@ -212,11 +212,22 @@ namespace PluginManager.Others /// public static (double, string) ConvertBytes(long bytes) { - if (bytes < 1024) return (bytes, "B"); - if (bytes < 1024 * 1024) return (bytes / 1024.0, "KB"); - if (bytes < 1024 * 1024 * 1024) return (bytes / 1024.0 / 1024.0, "MB"); - return (bytes / 1024.0 / 1024.0 / 1024.0, "GB"); + List units = new List() + { + "B", + "KB", + "MB", + "GB", + "TB" + }; + int i = 0; + while (bytes >= 1024) + { + i++; + bytes /= 1024; + } + return (bytes, units[i]); } /// diff --git a/PluginManager/Others/Permissions/DiscordPermissions.cs b/PluginManager/Others/Permissions/DiscordPermissions.cs index be55780..e8fae3b 100644 --- a/PluginManager/Others/Permissions/DiscordPermissions.cs +++ b/PluginManager/Others/Permissions/DiscordPermissions.cs @@ -1,55 +1,64 @@ -using Discord; +using System.Linq; +using Discord; using Discord.WebSocket; -using System.Linq; +namespace PluginManager.Others.Permissions; -namespace PluginManager.Others.Permissions +/// +/// A class whith all discord permissions +/// +public static class DiscordPermissions { /// - /// A class whith all discord permissions + /// Checks if the role has the specified permission /// - public static class DiscordPermissions + /// The role + /// The permission + /// + public static bool hasPermission(this IRole role, GuildPermission permission) { - /// - /// Checks if the role has the specified permission - /// - /// The role - /// The permission - /// - public static bool hasPermission(this IRole role, GuildPermission permission) => role.Permissions.Has(permission); - - /// - /// Check if user has the specified role - /// - /// The user - /// The role - /// - public static bool hasRole(this SocketGuildUser user, IRole role) => user.Roles.Contains(role); - - /// - /// Check if user has the specified permission - /// - /// The user - /// The permission - /// - public static bool hasPermission(this SocketGuildUser user, GuildPermission permission) - => user.Roles.Where(role => role.hasPermission(permission)).Any() || user.Guild.Owner == user; - /// - /// Check if user is administrator of server - /// - /// The user - /// - public static bool isAdmin(this SocketGuildUser user) => user.hasPermission(GuildPermission.Administrator); - - /// - /// Check if user is administrator of server - /// - /// The user - /// - public static bool isAdmin(this SocketUser user) => isAdmin((SocketGuildUser)user); + return role.Permissions.Has(permission); } + /// + /// Check if user has the specified role + /// + /// The user + /// The role + /// + public static bool hasRole(this SocketGuildUser user, IRole role) + { + return user.Roles.Contains(role); + } + /// + /// Check if user has the specified permission + /// + /// The user + /// The permission + /// + public static bool hasPermission(this SocketGuildUser user, GuildPermission permission) + { + return user.Roles.Where(role => role.hasPermission(permission)).Any() || user.Guild.Owner == user; + } + /// + /// Check if user is administrator of server + /// + /// The user + /// + public static bool isAdmin(this SocketGuildUser user) + { + return user.hasPermission(GuildPermission.Administrator); + } -} \ No newline at end of file + /// + /// Check if user is administrator of server + /// + /// The user + /// + public static bool isAdmin(this SocketUser user) + { + return isAdmin((SocketGuildUser)user); + } +}