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 class CommandHandler
{ {
public static DiscordSocketClient Client; public static DiscordSocketClient Client { get; set; }
private static readonly SqlManager sqlManager = new SqlManager();
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>" } }, { "help", new Command { Fun = Commands.Help, Desc = "Lists all commands", Usage = "<command>" } },
{ "prefix", new Command { Fun = ChangePrefix, Desc = "Changes prefix", Usage = "<prefix>" } }, { "prefix", new Command { Fun = Commands.ChangePrefix, Desc = "Changes prefix", Usage = "<prefix>" } },
{ {
"new", "new",
new Command new Command
{ {
Fun = CreateEmbed, Fun = Commands.CreateEmbed,
Desc = "Creats new embed", Desc = "Creats new embed",
Usage = "<title>\n<hex color>\n<description>\n<field>", Usage = "<title>\n<hex color>\n<description>\n<field>",
Example = "Title" Example = "Title"
+ "\n#FFFFFF" + "\n#EEEEEE"
+ "\nDescription" + "\nDescription"
+ "\n++Field name" + "\n++Field name"
+ "\nField content" + "\nField content"
@@ -42,15 +41,17 @@ namespace Discord_Simple_Embed_Bot
public static async Task HandleCommand(SocketMessage messageParam) public static async Task HandleCommand(SocketMessage messageParam)
{ {
SocketUserMessage message = messageParam as SocketUserMessage; SocketUserMessage message = messageParam as SocketUserMessage;
if (message == null) return; if (message is null) return;
int argPos = 0; int argPos = 0;
string prefix = PrefixFromMessage(message); string prefix = PrefixFromMessage(message);
if (message.MentionedUsers.Any(x => x.Discriminator == Client.CurrentUser.Discriminator)) if (message.MentionedUsers.Any(x => x.Discriminator == Client.CurrentUser.Discriminator))
{ {
EmbedBuilder eb = new EmbedBuilder(); EmbedBuilder eb = new EmbedBuilder
eb.Color = Color.Blue; {
eb.Description = $"Use `{prefix} help` to list all commands."; Color = Color.Blue,
Description = $"Use `{prefix} help` to list all commands."
};
await message.Channel.SendMessageAsync("", false, eb.Build()); await message.Channel.SendMessageAsync("", false, eb.Build());
return; return;
} }
@@ -65,12 +66,12 @@ namespace Discord_Simple_Embed_Bot
if (command.Contains(" ")) if (command.Contains(" "))
command = command.Substring(0, command.IndexOf(" ")); command = command.Substring(0, command.IndexOf(" "));
if (_commands.ContainsKey(command)) if (CommandList.ContainsKey(command))
{ {
SocketGuildUser socketGuildUser = message.Author as SocketGuildUser; SocketGuildUser socketGuildUser = message.Author as SocketGuildUser;
if (socketGuildUser.GuildPermissions.Administrator) if (socketGuildUser.GuildPermissions.Administrator)
{ {
await _commands[command].Fun(message); await CommandList[command].Fun(message);
} }
} }
else 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.Collect();
GC.WaitForPendingFinalizers(); GC.WaitForPendingFinalizers();
return prefix; 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.Trim();
content = content.Remove(0, prefix.Length).Trim(); content = content.Remove(0, prefix.Length).Trim();
@@ -107,130 +108,7 @@ namespace Discord_Simple_Embed_Bot
return null; return null;
} }
static public async Task Help(SocketUserMessage message) public class Command
{
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 string Desc { get; set; } public string Desc { get; set; }
public string Usage { 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() 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)) if (!File.Exists(tokenPath))
File.Create(tokenPath).Close(); File.Create(tokenPath).Close();
@@ -65,14 +65,14 @@ namespace Discord_Simple_Embed_Bot
private static ConsoleColor GetColor(LogSeverity logSeverity) private static ConsoleColor GetColor(LogSeverity logSeverity)
{ {
switch (logSeverity) return logSeverity switch
{ {
case LogSeverity.Critical: return ConsoleColor.DarkRed; LogSeverity.Critical => ConsoleColor.DarkRed,
case LogSeverity.Error: return ConsoleColor.Red; LogSeverity.Error => ConsoleColor.Red,
case LogSeverity.Warning: return ConsoleColor.DarkYellow; LogSeverity.Warning => ConsoleColor.DarkYellow,
case LogSeverity.Info: return ConsoleColor.Green; LogSeverity.Info => ConsoleColor.Green,
default: return ConsoleColor.White; _ => ConsoleColor.White,
} };
} }
} }
} }
+67 -66
View File
@@ -7,82 +7,83 @@ using System.Threading.Tasks;
namespace Discord_Simple_Embed_Bot namespace Discord_Simple_Embed_Bot
{ {
class SqlManager { static class SqlManager
readonly string sqlConnectionString;
readonly string databasePath;
public SqlManager()
{ {
databasePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory + "MainDatabase.sqlite"); static readonly string sqlConnectionString;
sqlConnectionString = "Data Source = " + databasePath + "; Version = 3"; static readonly string databasePath;
static SqlManager()
//Create SQLite database file
if (!File.Exists(databasePath))
{ {
SQLiteConnection.CreateFile(databasePath); databasePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory + "MainDatabase.sqlite");
sqlConnectionString = "Data Source = " + databasePath + "; Version = 3";
//Create SQLite database file
if (!File.Exists(databasePath))
{
SQLiteConnection.CreateFile(databasePath);
}
string sqlCommand1 = "CREATE TABLE IF NOT EXISTS Events (ServerId INTEGER,ChannelID INTEGER,EndDate TEXT)";
string sqlCommand2 = "CREATE TABLE IF NOT EXISTS Settings (ServerId INTEGER PRIMARY KEY,Data TEXT)";
SQLiteConnection m_dbConnection = new SQLiteConnection(sqlConnectionString);
m_dbConnection.Open();
SQLiteCommand command = new SQLiteCommand(m_dbConnection);
command.CommandText = sqlCommand1;
command.ExecuteNonQuery();
command.CommandText = sqlCommand2;
command.ExecuteNonQuery();
m_dbConnection.Close();
} }
string sqlCommand1 = "CREATE TABLE IF NOT EXISTS Events (ServerId INTEGER,ChannelID INTEGER,EndDate TEXT)"; public static async Task SetData(ulong serverId, string data, char type)
string sqlCommand2 = "CREATE TABLE IF NOT EXISTS Settings (ServerId INTEGER PRIMARY KEY,Data TEXT)";
SQLiteConnection m_dbConnection = new SQLiteConnection(sqlConnectionString);
m_dbConnection.Open();
SQLiteCommand command = new SQLiteCommand(m_dbConnection);
command.CommandText = sqlCommand1;
command.ExecuteNonQuery();
command.CommandText = sqlCommand2;
command.ExecuteNonQuery();
m_dbConnection.Close();
}
public async Task SetData(ulong serverId, string data, char type)
{
await Task.Run(() =>
{ {
SQLiteConnection dbConnection = new SQLiteConnection(sqlConnectionString); await Task.Run(() =>
SQLiteCommand command = new SQLiteCommand();
command.CommandText = "INSERT OR REPLACE INTO Settings (ServerId,Data) values (@serverId, @prefix)";
command.Parameters.Add(new SQLiteParameter("@serverId", serverId + type));
command.Parameters.Add(new SQLiteParameter("@prefix", data));
dbConnection.Open();
command.Connection = dbConnection;
command.ExecuteNonQuery();
dbConnection.Close();
});
}
public async Task<string> GetData(ulong serverId, char type)
{
return await Task<string>.Run(() =>
{
string data = null;
using (SQLiteConnection dbConnection = new SQLiteConnection(sqlConnectionString))
{ {
SQLiteConnection dbConnection = new SQLiteConnection(sqlConnectionString);
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(); dbConnection.Open();
SQLiteCommand command = new SQLiteCommand($"SELECT * FROM Settings WHERE ServerId=@type", dbConnection); command.Connection = dbConnection;
command.Parameters.Add(new SQLiteParameter("@type", serverId + type)); command.ExecuteNonQuery();
SQLiteDataReader dr = command.ExecuteReader();
if (dr.Read())
{
data = dr.GetString(1);
}
dbConnection.Close(); dbConnection.Close();
} });
if (data == null) }
public static async Task<string> GetData(ulong serverId, char type)
{
return await Task<string>.Run(() =>
{ {
switch (type) string data = null;
using (SQLiteConnection dbConnection = new SQLiteConnection(sqlConnectionString))
{ {
case 'p': return "eb!";
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())
{
data = dr.GetString(1);
}
dbConnection.Close();
} }
} if (data == null)
return data; {
}); switch (type)
{
case 'p': return "eb!";
}
}
return data;
});
}
} }
} }
}
@@ -1 +1 @@
1eb6d2e13bbb6a533f4118a46962c1047e1cffb0 fce56c50dd4c34795ae563c97b2bd30baf9ffcb4