Improved command structure

This commit is contained in:
Stone-Red-Code
2021-02-13 00:30:33 +01:00
parent aae747f49d
commit 717b3233d6
17 changed files with 229 additions and 216 deletions
+1 -1
View File
@@ -1 +1 @@
token.txt
token.env
Binary file not shown.
BIN
View File
Binary file not shown.
+18 -140
View File
@@ -12,22 +12,21 @@ namespace Discord_Simple_Embed_Bot
{
public static class CommandHandler
{
public static DiscordSocketClient Client;
private static readonly SqlManager sqlManager = new SqlManager();
public static DiscordSocketClient Client { get; set; }
static readonly Dictionary<string, Command> _commands = new()
public static readonly Dictionary<string, Command> CommandList = new()
{
{ "help", new Command { Fun = Help, Desc = "Lists all commands", Usage = "<command>" } },
{ "prefix", new Command { Fun = ChangePrefix, Desc = "Changes prefix", Usage = "<prefix>" } },
{ "help", new Command { Fun = Commands.Help, Desc = "Lists all commands", Usage = "<command>" } },
{ "prefix", new Command { Fun = Commands.ChangePrefix, Desc = "Changes prefix", Usage = "<prefix>" } },
{
"new",
new Command
{
Fun = CreateEmbed,
Fun = Commands.CreateEmbed,
Desc = "Creats new embed",
Usage = "<title>\n<hex color>\n<description>\n<field>",
Example = "Title"
+ "\n#FFFFFF"
+ "\n#EEEEEE"
+ "\nDescription"
+ "\n++Field name"
+ "\nField content"
@@ -42,15 +41,17 @@ namespace Discord_Simple_Embed_Bot
public static async Task HandleCommand(SocketMessage messageParam)
{
SocketUserMessage message = messageParam as SocketUserMessage;
if (message == null) return;
if (message is null) return;
int argPos = 0;
string prefix = PrefixFromMessage(message);
if (message.MentionedUsers.Any(x => x.Discriminator == Client.CurrentUser.Discriminator))
{
EmbedBuilder eb = new EmbedBuilder();
eb.Color = Color.Blue;
eb.Description = $"Use `{prefix} help` to list all commands.";
EmbedBuilder eb = new EmbedBuilder
{
Color = Color.Blue,
Description = $"Use `{prefix} help` to list all commands."
};
await message.Channel.SendMessageAsync("", false, eb.Build());
return;
}
@@ -65,12 +66,12 @@ namespace Discord_Simple_Embed_Bot
if (command.Contains(" "))
command = command.Substring(0, command.IndexOf(" "));
if (_commands.ContainsKey(command))
if (CommandList.ContainsKey(command))
{
SocketGuildUser socketGuildUser = message.Author as SocketGuildUser;
if (socketGuildUser.GuildPermissions.Administrator)
{
await _commands[command].Fun(message);
await CommandList[command].Fun(message);
}
}
else
@@ -79,17 +80,17 @@ namespace Discord_Simple_Embed_Bot
}
}
static string PrefixFromMessage(SocketUserMessage message)
public static string PrefixFromMessage(SocketUserMessage message)
{
string prefix = sqlManager.GetData((message.Channel as SocketGuildChannel).Guild.Id, 'p').Result;
string prefix = SqlManager.GetData((message.Channel as SocketGuildChannel).Guild.Id, 'p').Result;
GC.Collect();
GC.WaitForPendingFinalizers();
return prefix;
}
static string[] CheckCommandArgs(string content, int min, int max, string prefix)
public static string[] CheckCommandArgs(string content, int min, int max, string prefix)
{
content = content.Trim();
content = content.Remove(0, prefix.Length).Trim();
@@ -107,130 +108,7 @@ namespace Discord_Simple_Embed_Bot
return null;
}
static public async Task Help(SocketUserMessage message)
{
EmbedBuilder eb = new EmbedBuilder();
eb.Color = Color.Blue;
string[] args = CheckCommandArgs(message.Content, 0, 1, PrefixFromMessage(message));
if (args == null)
{
eb.Title = "Commands:";
foreach (var item in _commands)
{
eb.AddField(item.Key, item.Value.Desc);
}
}
else if (args.Length > 0)
{
if (_commands.ContainsKey(args[0].ToLower()))
{
eb.Title = args[0].ToLower();
eb.AddField("Parameters", _commands[args[0].ToLower()].Usage);
if (!string.IsNullOrWhiteSpace(_commands[args[0].ToLower()].Example))
{
eb.AddField("Example", $"```{PrefixFromMessage(message)} {args[0].ToLower()} {_commands[args[0].ToLower()].Example}```");
}
}
else
{
eb.WithDescription("Command not found!");
}
}
await message.Channel.SendMessageAsync("", false, eb.Build());
}
static public async Task ChangePrefix(SocketUserMessage message)
{
string prefix = "";
if (message.Content.Contains(" "))
prefix = message.Content[message.Content.LastIndexOf(" ")..].Trim();
if (prefix.Length <= 0)
{
await message.Channel.SendMessageAsync($"Prefix not valid!");
return;
}
await sqlManager.SetData((message.Channel as SocketGuildChannel).Guild.Id, prefix, 'p');
await message.Channel.SendMessageAsync($"Prefix changed to: `{prefix}`");
}
static public async Task CreateEmbed(SocketUserMessage message)
{
string prefix = PrefixFromMessage(message);
string content = message.Content[prefix.Length..].Trim()[3..];
string[] lines = content.Split("\n");
await message.DeleteAsync();
EmbedBuilder eb = new EmbedBuilder();
eb.Title = lines[0];
if (lines.Length > 1)
{
try
{
if (!lines[1].Contains("#"))
lines[1] = "#" + lines[1];
System.Drawing.Color col = (System.Drawing.Color)new System.Drawing.ColorConverter().ConvertFromString(lines[1]);
eb.Color = new Color(col.R, col.G, col.B);
}
catch { }
}
if (lines.Length > 2)
{
eb.Description = lines[2];
}
EmbedFieldBuilder efb = null;
foreach (string line in lines.Skip(3))
{
if (line.StartsWith("++"))
{
if (efb is not null)
eb.AddField(efb);
efb = new EmbedFieldBuilder();
efb.IsInline = false;
efb.Name = line.Remove(0, 2);
}
else if (line.StartsWith("--"))
{
if (efb is not null)
eb.AddField(efb);
efb = new EmbedFieldBuilder();
efb.IsInline = true;
efb.Name = line.Remove(0, 2);
}
else if (efb is not null && !string.IsNullOrWhiteSpace(line))
{
efb.Value += line + "\n";
}
}
if (eb is not null)
eb.AddField(efb);
for (int i = 0; i < eb.Fields.Count; i++)
{
if (string.IsNullOrWhiteSpace(eb.Fields[i].Value as string))
{
eb.Fields[i].Value = "-";
}
}
try
{
await message.Channel.SendMessageAsync("", false, eb.Build());
}
catch (Exception ex)
{
await Logging.Log(new LogMessage(LogSeverity.Debug, "CMD Handler", "", ex));
}
}
class Command
public class Command
{
public string Desc { get; set; }
public string Usage { get; set; }
+134
View File
@@ -0,0 +1,134 @@
using Discord;
using Discord.WebSocket;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Discord_Simple_Embed_Bot
{
static class Commands
{
static public async Task Help(SocketUserMessage message)
{
EmbedBuilder eb = new EmbedBuilder();
eb.Color = Color.Blue;
string[] args = CommandHandler.CheckCommandArgs(message.Content, 0, 1, CommandHandler.PrefixFromMessage(message));
if (args == null)
{
eb.Title = "Commands:";
foreach (var item in CommandHandler.CommandList)
{
eb.AddField(item.Key, item.Value.Desc);
}
}
else if (args.Length > 0)
{
if (CommandHandler.CommandList.ContainsKey(args[0].ToLower()))
{
eb.Title = args[0].ToLower();
eb.AddField("Parameters", CommandHandler.CommandList[args[0].ToLower()].Usage);
if (!string.IsNullOrWhiteSpace(CommandHandler.CommandList[args[0].ToLower()].Example))
{
eb.AddField("Example", $"```{CommandHandler.PrefixFromMessage(message)} {args[0].ToLower()} {CommandHandler.CommandList[args[0].ToLower()].Example}```");
}
}
else
{
eb.WithDescription("Command not found!");
}
}
await message.Channel.SendMessageAsync("", false, eb.Build());
}
static public async Task ChangePrefix(SocketUserMessage message)
{
string prefix = "";
if (message.Content.Contains(" "))
prefix = message.Content[message.Content.LastIndexOf(" ")..].Trim();
if (prefix.Length <= 0)
{
await message.Channel.SendMessageAsync($"Prefix not valid!");
return;
}
await SqlManager.SetData((message.Channel as SocketGuildChannel).Guild.Id, prefix, 'p');
await message.Channel.SendMessageAsync($"Prefix changed to: `{prefix}`");
}
static public async Task CreateEmbed(SocketUserMessage message)
{
string prefix = CommandHandler.PrefixFromMessage(message);
string content = message.Content[prefix.Length..].Trim()[3..];
string[] lines = content.Split("\n");
await message.DeleteAsync();
EmbedBuilder eb = new EmbedBuilder();
eb.Title = lines[0];
if (lines.Length > 1)
{
try
{
if (!lines[1].Contains("#"))
lines[1] = "#" + lines[1];
System.Drawing.Color col = (System.Drawing.Color)new System.Drawing.ColorConverter().ConvertFromString(lines[1]);
eb.Color = new Color(col.R, col.G, col.B);
}
catch { }
}
if (lines.Length > 2)
{
eb.Description = lines[2];
}
EmbedFieldBuilder efb = null;
foreach (string line in lines.Skip(3))
{
if (line.StartsWith("++"))
{
if (efb is not null)
eb.AddField(efb);
efb = new EmbedFieldBuilder();
efb.IsInline = false;
efb.Name = line.Remove(0, 2);
}
else if (line.StartsWith("--"))
{
if (efb is not null)
eb.AddField(efb);
efb = new EmbedFieldBuilder();
efb.IsInline = true;
efb.Name = line.Remove(0, 2);
}
else if (efb is not null && !string.IsNullOrWhiteSpace(line))
{
efb.Value += line + "\n";
}
}
if (eb is not null)
eb.AddField(efb);
for (int i = 0; i < eb.Fields.Count; i++)
{
if (string.IsNullOrWhiteSpace(eb.Fields[i].Value as string))
{
eb.Fields[i].Value = "-";
}
}
try
{
await message.Channel.SendMessageAsync("", false, eb.Build());
}
catch (Exception ex)
{
await Logging.Log(new LogMessage(LogSeverity.Debug, "CMD Handler", "", ex));
}
}
}
}
+8 -8
View File
@@ -13,7 +13,7 @@ namespace Discord_Simple_Embed_Bot
public async Task MainAsync()
{
string tokenPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "token.txt");
string tokenPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "token.env");
if (!File.Exists(tokenPath))
File.Create(tokenPath).Close();
@@ -65,14 +65,14 @@ namespace Discord_Simple_Embed_Bot
private static ConsoleColor GetColor(LogSeverity logSeverity)
{
switch (logSeverity)
return logSeverity switch
{
case LogSeverity.Critical: return ConsoleColor.DarkRed;
case LogSeverity.Error: return ConsoleColor.Red;
case LogSeverity.Warning: return ConsoleColor.DarkYellow;
case LogSeverity.Info: return ConsoleColor.Green;
default: return ConsoleColor.White;
}
LogSeverity.Critical => ConsoleColor.DarkRed,
LogSeverity.Error => ConsoleColor.Red,
LogSeverity.Warning => ConsoleColor.DarkYellow,
LogSeverity.Info => ConsoleColor.Green,
_ => ConsoleColor.White,
};
}
}
}
+13 -12
View File
@@ -7,10 +7,11 @@ using System.Threading.Tasks;
namespace Discord_Simple_Embed_Bot
{
class SqlManager {
readonly string sqlConnectionString;
readonly string databasePath;
public SqlManager()
static class SqlManager
{
static readonly string sqlConnectionString;
static readonly string databasePath;
static SqlManager()
{
databasePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory + "MainDatabase.sqlite");
sqlConnectionString = "Data Source = " + databasePath + "; Version = 3";
@@ -36,19 +37,16 @@ namespace Discord_Simple_Embed_Bot
m_dbConnection.Close();
}
public async Task SetData(ulong serverId, string data, char type)
public static async Task SetData(ulong serverId, string data, char type)
{
await Task.Run(() =>
{
SQLiteConnection dbConnection = new SQLiteConnection(sqlConnectionString);
SQLiteCommand command = new SQLiteCommand();
command.CommandText = "INSERT OR REPLACE INTO Settings (ServerId,Data) values (@serverId, @prefix)";
SQLiteCommand command = new SQLiteCommand("INSERT OR REPLACE INTO Settings (ServerId,Data) values (@serverId, @prefix)", dbConnection);
command.Parameters.Add(new SQLiteParameter("@serverId", serverId + type));
command.Parameters.Add(new SQLiteParameter("@prefix", data));
dbConnection.Open();
command.Connection = dbConnection;
command.ExecuteNonQuery();
@@ -56,16 +54,19 @@ namespace Discord_Simple_Embed_Bot
});
}
public async Task<string> GetData(ulong serverId, char type)
public static async Task<string> GetData(ulong serverId, char type)
{
return await Task<string>.Run(() =>
{
string data = null;
using (SQLiteConnection dbConnection = new SQLiteConnection(sqlConnectionString))
{
dbConnection.Open();
SQLiteCommand command = new SQLiteCommand($"SELECT * FROM Settings WHERE ServerId=@type", dbConnection);
command.Parameters.Add(new SQLiteParameter("@type", serverId + type));
dbConnection.Open();
SQLiteDataReader dr = command.ExecuteReader();
if (dr.Read())
{
@@ -84,5 +85,5 @@ namespace Discord_Simple_Embed_Bot
return data;
});
}
}
}
}
@@ -1 +1 @@
1eb6d2e13bbb6a533f4118a46962c1047e1cffb0
fce56c50dd4c34795ae563c97b2bd30baf9ffcb4