From acf63a745b3c9b7d95f722aa013fd4091a659dc6 Mon Sep 17 00:00:00 2001 From: Emotion Date: Fri, 24 Mar 2023 01:21:20 +1300 Subject: [PATCH] Fixed some stuff Signed-off-by: Emotion --- SupportChild/Commands/AddStaffCommand.cs | 2 +- SupportChild/Commands/CloseCommand.cs | 4 +- SupportChild/Commands/NewCommand.cs | 2 +- SupportChild/Commands/RemoveStaffCommand.cs | 2 +- SupportChild/Commands/SetSummaryCommand.cs | 2 +- SupportChild/Commands/TranscriptCommand.cs | 4 +- SupportChild/Database.cs | 1617 ++++++++++--------- SupportChild/EventHandler.cs | 490 +++--- SupportChild/SupportChild.csproj | 16 +- 9 files changed, 1075 insertions(+), 1064 deletions(-) diff --git a/SupportChild/Commands/AddStaffCommand.cs b/SupportChild/Commands/AddStaffCommand.cs index f0e48ea..224fb1e 100644 --- a/SupportChild/Commands/AddStaffCommand.cs +++ b/SupportChild/Commands/AddStaffCommand.cs @@ -3,7 +3,7 @@ using System.Threading.Tasks; using DSharpPlus.Entities; using DSharpPlus.SlashCommands; using DSharpPlus.SlashCommands.Attributes; -using MySql.Data.MySqlClient; +using MySqlConnector; namespace SupportChild.Commands; diff --git a/SupportChild/Commands/CloseCommand.cs b/SupportChild/Commands/CloseCommand.cs index 5ef8913..69a6e39 100644 --- a/SupportChild/Commands/CloseCommand.cs +++ b/SupportChild/Commands/CloseCommand.cs @@ -86,7 +86,7 @@ public class CloseCommand : ApplicationCommandModule await using FileStream file = new FileStream(Transcriber.GetPath(ticket.id), FileMode.Open, FileAccess.Read); DiscordMessageBuilder message = new DiscordMessageBuilder(); message.WithEmbed(embed); - message.WithFiles(new Dictionary { { Transcriber.GetFilename(ticket.id), file } }); + message.AddFiles(new Dictionary { { Transcriber.GetFilename(ticket.id), file } }); await logChannel.SendMessageAsync(message); } @@ -107,7 +107,7 @@ public class CloseCommand : ApplicationCommandModule DiscordMessageBuilder message = new DiscordMessageBuilder(); message.WithEmbed(embed); - message.WithFiles(new Dictionary { { Transcriber.GetFilename(ticket.id), file } }); + message.AddFiles(new Dictionary { { Transcriber.GetFilename(ticket.id), file } }); await staffMember.SendMessageAsync(message); } diff --git a/SupportChild/Commands/NewCommand.cs b/SupportChild/Commands/NewCommand.cs index 739174d..2257fe9 100644 --- a/SupportChild/Commands/NewCommand.cs +++ b/SupportChild/Commands/NewCommand.cs @@ -105,7 +105,7 @@ public class NewCommand : ApplicationCommandModule case ComponentType.Button: stringID = interaction.Data.CustomId.Replace("supportchild_newcommandbutton ", ""); break; - case ComponentType.Select: + case ComponentType.StringSelect: if (interaction.Data.Values == null || interaction.Data.Values.Length <= 0) return; stringID = interaction.Data.Values[0]; break; diff --git a/SupportChild/Commands/RemoveStaffCommand.cs b/SupportChild/Commands/RemoveStaffCommand.cs index 70e2162..a038918 100644 --- a/SupportChild/Commands/RemoveStaffCommand.cs +++ b/SupportChild/Commands/RemoveStaffCommand.cs @@ -2,7 +2,7 @@ using DSharpPlus.Entities; using DSharpPlus.SlashCommands; using DSharpPlus.SlashCommands.Attributes; -using MySql.Data.MySqlClient; +using MySqlConnector; namespace SupportChild.Commands; diff --git a/SupportChild/Commands/SetSummaryCommand.cs b/SupportChild/Commands/SetSummaryCommand.cs index 6d9e87e..106fd9e 100644 --- a/SupportChild/Commands/SetSummaryCommand.cs +++ b/SupportChild/Commands/SetSummaryCommand.cs @@ -2,7 +2,7 @@ using DSharpPlus.Entities; using DSharpPlus.SlashCommands; using DSharpPlus.SlashCommands.Attributes; -using MySql.Data.MySqlClient; +using MySqlConnector; namespace SupportChild.Commands; diff --git a/SupportChild/Commands/TranscriptCommand.cs b/SupportChild/Commands/TranscriptCommand.cs index 0eb4bfc..4303168 100644 --- a/SupportChild/Commands/TranscriptCommand.cs +++ b/SupportChild/Commands/TranscriptCommand.cs @@ -90,7 +90,7 @@ public class TranscriptCommand : ApplicationCommandModule Description = "Ticket " + ticket.id.ToString("00000") + " transcript generated by " + command.Member.Mention + ".\n", Footer = new DiscordEmbedBuilder.EmbedFooter { Text = '#' + command.Channel.Name } }); - message.WithFiles(new Dictionary { { Transcriber.GetFilename(ticket.id), file } }); + message.AddFiles(new Dictionary { { Transcriber.GetFilename(ticket.id), file } }); await logChannel.SendMessageAsync(message); } @@ -106,7 +106,7 @@ public class TranscriptCommand : ApplicationCommandModule Color = DiscordColor.Green, Description = "Transcript generated!\n" }); - directMessage.WithFiles(new Dictionary { { Transcriber.GetFilename(ticket.id), file } }); + directMessage.AddFiles(new Dictionary { { Transcriber.GetFilename(ticket.id), file } }); await command.Member.SendMessageAsync(directMessage); } diff --git a/SupportChild/Database.cs b/SupportChild/Database.cs index e78160c..f263972 100644 --- a/SupportChild/Database.cs +++ b/SupportChild/Database.cs @@ -2,817 +2,818 @@ using System.Linq; using System.Collections.Generic; using DSharpPlus; -using MySql.Data.MySqlClient; +using MySqlConnector; namespace SupportChild; public static class Database { - private static string connectionString = ""; - - private static readonly Random random = new Random(); - - public static void SetConnectionString(string host, int port, string database, string username, string password) - { - connectionString = "server=" + host + - ";database=" + database + - ";port=" + port + - ";userid=" + username + - ";password=" + password; - } - - public static MySqlConnection GetConnection() - { - return new MySqlConnection(connectionString); - } - - public static long GetNumberOfTickets() - { - try - { - using MySqlConnection c = GetConnection(); - using MySqlCommand countTickets = new MySqlCommand("SELECT COUNT(*) FROM tickets", c); - c.Open(); - return (long)countTickets.ExecuteScalar(); - } - catch (Exception e) - { - Logger.Error("Error occured when attempting to count number of open tickets: " + e); - } - - return -1; - } - - public static long GetNumberOfClosedTickets() - { - try - { - using MySqlConnection c = GetConnection(); - using MySqlCommand countTickets = new MySqlCommand("SELECT COUNT(*) FROM ticket_history", c); - c.Open(); - return (long)countTickets.ExecuteScalar(); - } - catch (Exception e) - { - Logger.Error("Error occured when attempting to count number of open tickets: " + e); - } - - return -1; - } - - public static void SetupTables() - { - using MySqlConnection c = GetConnection(); - using MySqlCommand createTickets = new MySqlCommand( - "CREATE TABLE IF NOT EXISTS tickets(" + - "id INT UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT," + - "created_time DATETIME NOT NULL," + - "creator_id BIGINT UNSIGNED NOT NULL," + - "assigned_staff_id BIGINT UNSIGNED NOT NULL DEFAULT 0," + - "summary VARCHAR(5000) NOT NULL," + - "channel_id BIGINT UNSIGNED NOT NULL UNIQUE," + - "INDEX(created_time, assigned_staff_id, channel_id))", - c); - using MySqlCommand createTicketHistory = new MySqlCommand( - "CREATE TABLE IF NOT EXISTS ticket_history(" + - "id INT UNSIGNED NOT NULL PRIMARY KEY," + - "created_time DATETIME NOT NULL," + - "closed_time DATETIME NOT NULL," + - "creator_id BIGINT UNSIGNED NOT NULL," + - "assigned_staff_id BIGINT UNSIGNED NOT NULL DEFAULT 0," + - "summary VARCHAR(5000) NOT NULL," + - "channel_id BIGINT UNSIGNED NOT NULL UNIQUE," + - "INDEX(created_time, closed_time, channel_id))", - c); - using MySqlCommand createBlacklisted = new MySqlCommand( - "CREATE TABLE IF NOT EXISTS blacklisted_users(" + - "user_id BIGINT UNSIGNED NOT NULL PRIMARY KEY," + - "time DATETIME NOT NULL," + - "moderator_id BIGINT UNSIGNED NOT NULL," + - "INDEX(user_id, time))", - c); - using MySqlCommand createStaffList = new MySqlCommand( - "CREATE TABLE IF NOT EXISTS staff(" + - "user_id BIGINT UNSIGNED NOT NULL PRIMARY KEY," + - "name VARCHAR(256) NOT NULL," + - "active BOOLEAN NOT NULL DEFAULT true)", - c); - using MySqlCommand createMessages = new MySqlCommand( - "CREATE TABLE IF NOT EXISTS messages(" + - "identifier VARCHAR(256) NOT NULL PRIMARY KEY," + - "user_id BIGINT UNSIGNED NOT NULL," + - "message VARCHAR(5000) NOT NULL)", - c); - using MySqlCommand createCategories = new MySqlCommand( - "CREATE TABLE IF NOT EXISTS categories(" + - "name VARCHAR(256) NOT NULL UNIQUE," + - "category_id BIGINT UNSIGNED NOT NULL PRIMARY KEY)", - c); - c.Open(); - createTickets.ExecuteNonQuery(); - createBlacklisted.ExecuteNonQuery(); - createTicketHistory.ExecuteNonQuery(); - createStaffList.ExecuteNonQuery(); - createMessages.ExecuteNonQuery(); - createCategories.ExecuteNonQuery(); - } - - public static bool IsOpenTicket(ulong channelID) - { - using MySqlConnection c = GetConnection(); - c.Open(); - using MySqlCommand selection = new MySqlCommand(@"SELECT * FROM tickets WHERE channel_id=@channel_id", c); - selection.Parameters.AddWithValue("@channel_id", channelID); - selection.Prepare(); - MySqlDataReader results = selection.ExecuteReader(); - - // Check if ticket exists in the database - if (!results.Read()) - { - return false; - } - results.Close(); - return true; - } - - public static bool TryGetOpenTicket(ulong channelID, out Ticket ticket) - { - using MySqlConnection c = GetConnection(); - c.Open(); - using MySqlCommand selection = new MySqlCommand(@"SELECT * FROM tickets WHERE channel_id=@channel_id", c); - selection.Parameters.AddWithValue("@channel_id", channelID); - selection.Prepare(); - MySqlDataReader results = selection.ExecuteReader(); - - // Check if ticket exists in the database - if (!results.Read()) - { - ticket = null; - return false; - } - - ticket = new Ticket(results); - results.Close(); - return true; - } - - public static bool TryGetOpenTicketByID(uint id, out Ticket ticket) - { - using MySqlConnection c = GetConnection(); - c.Open(); - using MySqlCommand selection = new MySqlCommand(@"SELECT * FROM tickets WHERE id=@id", c); - selection.Parameters.AddWithValue("@id", id); - selection.Prepare(); - MySqlDataReader results = selection.ExecuteReader(); - - // Check if open ticket exists in the database - if (results.Read()) - { - ticket = new Ticket(results); - results.Close(); - return true; - } - - results.Close(); - ticket = null; - return false; - } - - public static bool TryGetClosedTicket(uint id, out Ticket ticket) - { - using MySqlConnection c = GetConnection(); - c.Open(); - using MySqlCommand selection = new MySqlCommand(@"SELECT * FROM ticket_history WHERE id=@id", c); - selection.Parameters.AddWithValue("@id", id); - selection.Prepare(); - MySqlDataReader results = selection.ExecuteReader(); - - // Check if closed ticket exists in the database - if (results.Read()) - { - ticket = new Ticket(results); - results.Close(); - return true; - } - - ticket = null; - results.Close(); - return false; - } - - public static bool TryGetOpenTickets(ulong userID, out List tickets) - { - tickets = null; - using MySqlConnection c = GetConnection(); - c.Open(); - using MySqlCommand selection = new MySqlCommand(@"SELECT * FROM tickets WHERE creator_id=@creator_id", c); - selection.Parameters.AddWithValue("@creator_id", userID); - selection.Prepare(); - MySqlDataReader results = selection.ExecuteReader(); - - if (!results.Read()) - { - return false; - } - - tickets = new List { new Ticket(results) }; - while (results.Read()) - { - tickets.Add(new Ticket(results)); - } - results.Close(); - return true; - } - - public static bool TryGetOpenTickets(out List tickets) - { - tickets = null; - using MySqlConnection c = GetConnection(); - c.Open(); - using MySqlCommand selection = new MySqlCommand(@"SELECT * FROM tickets ORDER BY channel_id ASC", c); - selection.Prepare(); - MySqlDataReader results = selection.ExecuteReader(); - - if (!results.Read()) - { - return false; - } - - tickets = new List { new Ticket(results) }; - while (results.Read()) - { - tickets.Add(new Ticket(results)); - } - results.Close(); - return true; - } - - public static bool TryGetClosedTickets(ulong userID, out List tickets) - { - tickets = null; - using MySqlConnection c = GetConnection(); - c.Open(); - using MySqlCommand selection = new MySqlCommand(@"SELECT * FROM ticket_history WHERE creator_id=@creator_id", c); - selection.Parameters.AddWithValue("@creator_id", userID); - selection.Prepare(); - MySqlDataReader results = selection.ExecuteReader(); - - if (!results.Read()) - { - return false; - } - - tickets = new List { new Ticket(results) }; - while (results.Read()) - { - tickets.Add(new Ticket(results)); - } - results.Close(); - return true; - } - - public static bool TryGetAssignedTickets(ulong staffID, out List tickets) - { - tickets = null; - using MySqlConnection c = GetConnection(); - c.Open(); - using MySqlCommand selection = new MySqlCommand(@"SELECT * FROM tickets WHERE assigned_staff_id=@assigned_staff_id", c); - selection.Parameters.AddWithValue("@assigned_staff_id", staffID); - selection.Prepare(); - MySqlDataReader results = selection.ExecuteReader(); - - if (!results.Read()) - { - return false; - } - - tickets = new List { new Ticket(results) }; - while (results.Read()) - { - tickets.Add(new Ticket(results)); - } - results.Close(); - return true; - } - - public static long NewTicket(ulong memberID, ulong staffID, ulong ticketID) - { - using MySqlConnection c = GetConnection(); - c.Open(); - using MySqlCommand cmd = new MySqlCommand(@"INSERT INTO tickets (created_time, creator_id, assigned_staff_id, summary, channel_id) VALUES (UTC_TIMESTAMP(), @creator_id, @assigned_staff_id, @summary, @channel_id);", c); - cmd.Parameters.AddWithValue("@creator_id", memberID); - cmd.Parameters.AddWithValue("@assigned_staff_id", staffID); - cmd.Parameters.AddWithValue("@summary", ""); - cmd.Parameters.AddWithValue("@channel_id", ticketID); - cmd.ExecuteNonQuery(); - return cmd.LastInsertedId; - } - - public static void ArchiveTicket(Ticket ticket) - { - // Check if ticket already exists in the archive - if (TryGetClosedTicket(ticket.id, out Ticket _)) - { - using MySqlConnection c = GetConnection(); - using MySqlCommand deleteTicket = new MySqlCommand(@"DELETE FROM ticket_history WHERE id=@id OR channel_id=@channel_id", c); - deleteTicket.Parameters.AddWithValue("@id", ticket.id); - deleteTicket.Parameters.AddWithValue("@channel_id", ticket.channelID); - - c.Open(); - deleteTicket.Prepare(); - deleteTicket.ExecuteNonQuery(); - } - - // Create an entry in the ticket history database - using MySqlConnection conn = GetConnection(); - using MySqlCommand archiveTicket = new MySqlCommand(@"INSERT INTO ticket_history (id, created_time, closed_time, creator_id, assigned_staff_id, summary, channel_id) VALUES (@id, @created_time, UTC_TIMESTAMP(), @creator_id, @assigned_staff_id, @summary, @channel_id);", conn); - archiveTicket.Parameters.AddWithValue("@id", ticket.id); - archiveTicket.Parameters.AddWithValue("@created_time", ticket.channelID.GetSnowflakeTime()); - archiveTicket.Parameters.AddWithValue("@creator_id", ticket.creatorID); - archiveTicket.Parameters.AddWithValue("@assigned_staff_id", ticket.assignedStaffID); - archiveTicket.Parameters.AddWithValue("@summary", ticket.summary); - archiveTicket.Parameters.AddWithValue("@channel_id", ticket.channelID); - - conn.Open(); - archiveTicket.Prepare(); - archiveTicket.ExecuteNonQuery(); - } - - public static bool DeleteOpenTicket(uint ticketID) - { - try - { - using MySqlConnection c = GetConnection(); - using MySqlCommand deletion = new MySqlCommand(@"DELETE FROM tickets WHERE id=@id", c); - deletion.Parameters.AddWithValue("@id", ticketID); - - c.Open(); - deletion.Prepare(); - return deletion.ExecuteNonQuery() > 0; - } - catch (MySqlException) - { - return false; - } - } - - public static bool IsBlacklisted(ulong userID) - { - using MySqlConnection c = GetConnection(); - c.Open(); - using MySqlCommand selection = new MySqlCommand(@"SELECT * FROM blacklisted_users WHERE user_id=@user_id", c); - selection.Parameters.AddWithValue("@user_id", userID); - selection.Prepare(); - MySqlDataReader results = selection.ExecuteReader(); - - // Check if user is blacklisted - if (results.Read()) - { - return true; - } - results.Close(); - - return false; - } - - public static bool Blacklist(ulong blacklistedID, ulong staffID) - { - try - { - using MySqlConnection c = GetConnection(); - c.Open(); - using MySqlCommand cmd = new MySqlCommand(@"INSERT INTO blacklisted_users (user_id,time,moderator_id) VALUES (@user_id, UTC_TIMESTAMP(), @moderator_id);", c); - cmd.Parameters.AddWithValue("@user_id", blacklistedID); - cmd.Parameters.AddWithValue("@moderator_id", staffID); - cmd.Prepare(); - return cmd.ExecuteNonQuery() > 0; - } - catch (MySqlException) - { - return false; - } - } - - public static bool Unblacklist(ulong blacklistedID) - { - try - { - using MySqlConnection c = GetConnection(); - c.Open(); - using MySqlCommand cmd = new MySqlCommand(@"DELETE FROM blacklisted_users WHERE user_id=@user_id", c); - cmd.Parameters.AddWithValue("@user_id", blacklistedID); - cmd.Prepare(); - return cmd.ExecuteNonQuery() > 0; - } - catch (MySqlException) - { - return false; - } - } - - public static bool AssignStaff(Ticket ticket, ulong staffID) - { - try - { - using MySqlConnection c = GetConnection(); - c.Open(); - using MySqlCommand update = new MySqlCommand(@"UPDATE tickets SET assigned_staff_id = @assigned_staff_id WHERE id = @id", c); - update.Parameters.AddWithValue("@assigned_staff_id", staffID); - update.Parameters.AddWithValue("@id", ticket.id); - update.Prepare(); - return update.ExecuteNonQuery() > 0; - } - catch (MySqlException) - { - return false; - } - } - - public static bool UnassignStaff(Ticket ticket) - { - return AssignStaff(ticket, 0); - } - - public static bool SetStaffActive(ulong staffID, bool active) - { - try - { - using MySqlConnection c = GetConnection(); - c.Open(); - MySqlCommand update = new MySqlCommand(@"UPDATE staff SET active = @active WHERE user_id = @user_id", c); - update.Parameters.AddWithValue("@user_id", staffID); - update.Parameters.AddWithValue("@active", active); - update.Prepare(); - return update.ExecuteNonQuery() > 0; - } - catch (MySqlException) - { - return false; - } - } - - public static StaffMember GetRandomActiveStaff(params ulong[] ignoredUserIDs) - { - List staffMembers = GetActiveStaff(ignoredUserIDs); - return staffMembers.Any() ? staffMembers[random.Next(staffMembers.Count)] : null; - } - - public static List GetActiveStaff(params ulong[] ignoredUserIDs) - { - bool first = true; - string filterString = ""; - foreach (ulong userID in ignoredUserIDs) - { - if (first) - { - first = false; - filterString += "AND user_id != " + userID; - } - else - { - filterString += "&& user_id != " + userID; - } - } - - using MySqlConnection c = GetConnection(); - c.Open(); - using MySqlCommand selection = new MySqlCommand(@"SELECT * FROM staff WHERE active = true " + filterString, c); - selection.Prepare(); - MySqlDataReader results = selection.ExecuteReader(); - - // Check if staff exists in the database - if (!results.Read()) - { - return new List(); - } - - List staffMembers = new List { new StaffMember(results) }; - while (results.Read()) - { - staffMembers.Add(new StaffMember(results)); - } - results.Close(); - - return staffMembers; - } - - public static List GetAllStaff(params ulong[] ignoredUserIDs) - { - bool first = true; - string filterString = ""; - foreach (ulong userID in ignoredUserIDs) - { - if (first) - { - first = false; - filterString += "WHERE user_id != " + userID; - } - else - { - filterString += "&& user_id != " + userID; - } - - } - - - using MySqlConnection c = GetConnection(); - c.Open(); - using MySqlCommand selection = new MySqlCommand(@"SELECT * FROM staff " + filterString, c); - selection.Prepare(); - MySqlDataReader results = selection.ExecuteReader(); - - // Check if staff exist in the database - if (!results.Read()) - { - return new List(); - } - - List staffMembers = new List { new StaffMember(results) }; - while (results.Read()) - { - staffMembers.Add(new StaffMember(results)); - } - results.Close(); - - return staffMembers; - } - - public static bool IsStaff(ulong staffID) - { - using MySqlConnection c = GetConnection(); - c.Open(); - using MySqlCommand selection = new MySqlCommand(@"SELECT * FROM staff WHERE user_id=@user_id", c); - selection.Parameters.AddWithValue("@user_id", staffID); - selection.Prepare(); - MySqlDataReader results = selection.ExecuteReader(); - - // Check if ticket exists in the database - if (!results.Read()) - { - return false; - } - results.Close(); - return true; - } - - public static bool TryGetStaff(ulong staffID, out StaffMember staffMember) - { - using MySqlConnection c = GetConnection(); - c.Open(); - using MySqlCommand selection = new MySqlCommand(@"SELECT * FROM staff WHERE user_id=@user_id", c); - selection.Parameters.AddWithValue("@user_id", staffID); - selection.Prepare(); - MySqlDataReader results = selection.ExecuteReader(); - - // Check if ticket exists in the database - if (!results.Read()) - { - staffMember = null; - return false; - } - staffMember = new StaffMember(results); - results.Close(); - return true; - } - - public static List GetAllMessages() - { - using MySqlConnection c = GetConnection(); - c.Open(); - using MySqlCommand selection = new MySqlCommand(@"SELECT * FROM messages", c); - selection.Prepare(); - MySqlDataReader results = selection.ExecuteReader(); - - // Check if messages exist in the database - if (!results.Read()) - { - return new List(); - } - - List messages = new List { new Message(results) }; - while (results.Read()) - { - messages.Add(new Message(results)); - } - results.Close(); - - return messages; - } - - public static bool TryGetMessage(string identifier, out Message message) - { - using MySqlConnection c = GetConnection(); - c.Open(); - using MySqlCommand selection = new MySqlCommand(@"SELECT * FROM messages WHERE identifier=@identifier", c); - selection.Parameters.AddWithValue("@identifier", identifier); - selection.Prepare(); - MySqlDataReader results = selection.ExecuteReader(); - - // Check if ticket exists in the database - if (!results.Read()) - { - message = null; - return false; - } - message = new Message(results); - results.Close(); - return true; - } - - public static bool AddMessage(string identifier, ulong userID, string message) - { - try - { - using MySqlConnection c = GetConnection(); - c.Open(); - using MySqlCommand cmd = new MySqlCommand(@"INSERT INTO messages (identifier,user_id,message) VALUES (@identifier, @user_id, @message);", c); - cmd.Parameters.AddWithValue("@identifier", identifier); - cmd.Parameters.AddWithValue("@user_id", userID); - cmd.Parameters.AddWithValue("@message", message); - cmd.Prepare(); - return cmd.ExecuteNonQuery() > 0; - } - catch (MySqlException) - { - return false; - } - } - - public static bool RemoveMessage(string identifier) - { - try - { - using MySqlConnection c = GetConnection(); - c.Open(); - using MySqlCommand cmd = new MySqlCommand(@"DELETE FROM messages WHERE identifier=@identifier", c); - cmd.Parameters.AddWithValue("@identifier", identifier); - cmd.Prepare(); - return cmd.ExecuteNonQuery() > 0; - } - catch (MySqlException) - { - return false; - } - } - - public static List GetAllCategories() - { - using MySqlConnection c = GetConnection(); - c.Open(); - using MySqlCommand selection = new MySqlCommand(@"SELECT * FROM categories", c); - selection.Prepare(); - MySqlDataReader results = selection.ExecuteReader(); - - // Check if messages exist in the database - if (!results.Read()) - { - return new List(); - } - - List categories = new List { new Category(results) }; - while (results.Read()) - { - categories.Add(new Category(results)); - } - results.Close(); - - return categories; - } - - public static bool TryGetCategory(ulong categoryID, out Category message) - { - using MySqlConnection c = GetConnection(); - c.Open(); - using MySqlCommand selection = new MySqlCommand(@"SELECT * FROM categories WHERE category_id=@category_id", c); - selection.Parameters.AddWithValue("@category_id", categoryID); - selection.Prepare(); - MySqlDataReader results = selection.ExecuteReader(); - - // Check if ticket exists in the database - if (!results.Read()) - { - message = null; - return false; - } - message = new Category(results); - results.Close(); - return true; - } - - public static bool TryGetCategory(string name, out Category message) - { - using MySqlConnection c = GetConnection(); - c.Open(); - using MySqlCommand selection = new MySqlCommand(@"SELECT * FROM categories WHERE name=@name", c); - selection.Parameters.AddWithValue("@name", name); - selection.Prepare(); - MySqlDataReader results = selection.ExecuteReader(); - - // Check if ticket exists in the database - if (!results.Read()) - { - message = null; - return false; - } - message = new Category(results); - results.Close(); - return true; - } - - public static bool AddCategory(string name, ulong categoryID) - { - try - { - using MySqlConnection c = GetConnection(); - c.Open(); - using MySqlCommand cmd = new MySqlCommand(@"INSERT INTO categories (name,category_id) VALUES (@name, @category_id);", c); - cmd.Parameters.AddWithValue("@name", name); - cmd.Parameters.AddWithValue("@category_id", categoryID); - cmd.Prepare(); - return cmd.ExecuteNonQuery() > 0; - } - catch (MySqlException) - { - return false; - } - } - - public static bool RemoveCategory(ulong categoryID) - { - try - { - using MySqlConnection c = GetConnection(); - c.Open(); - using MySqlCommand cmd = new MySqlCommand(@"DELETE FROM categories WHERE category_id=@category_id", c); - cmd.Parameters.AddWithValue("@category_id", categoryID); - cmd.Prepare(); - return cmd.ExecuteNonQuery() > 0; - } - catch (MySqlException) - { - return false; - } - } - - public class Ticket - { - public uint id; - public ulong creatorID; - public ulong assignedStaffID; - public string summary; - public ulong channelID; - - public Ticket(MySqlDataReader reader) - { - id = reader.GetUInt32("id"); - creatorID = reader.GetUInt64("creator_id"); - assignedStaffID = reader.GetUInt64("assigned_staff_id"); - summary = reader.GetString("summary"); - channelID = reader.GetUInt64("channel_id"); - } - - public string DiscordRelativeTime() - { - return Formatter.Timestamp(channelID.GetSnowflakeTime(), Config.timestampFormat); - } - } - public class StaffMember - { - public ulong userID; - public string name; - public bool active; - - public StaffMember(MySqlDataReader reader) - { - userID = reader.GetUInt64("user_id"); - name = reader.GetString("name"); - active = reader.GetBoolean("active"); - } - } - - public class Message - { - public string identifier; - public ulong userID; - public string message; - - public Message(MySqlDataReader reader) - { - identifier = reader.GetString("identifier"); - userID = reader.GetUInt64("user_id"); - message = reader.GetString("message"); - } - } - - public class Category - { - public string name; - public ulong id; - - public Category(MySqlDataReader reader) - { - name = reader.GetString("name"); - id = reader.GetUInt64("category_id"); - } - } + private static string connectionString = ""; + + private static readonly Random random = new Random(); + + public static void SetConnectionString(string host, int port, string database, string username, string password) + { + connectionString = "server=" + host + + ";database=" + database + + ";port=" + port + + ";userid=" + username + + ";password=" + password; + } + + public static MySqlConnection GetConnection() + { + return new MySqlConnection(connectionString); + } + + public static long GetNumberOfTickets() + { + try + { + using MySqlConnection c = GetConnection(); + using MySqlCommand countTickets = new MySqlCommand("SELECT COUNT(*) FROM tickets", c); + c.Open(); + return (long)countTickets.ExecuteScalar(); + } + catch (Exception e) + { + Logger.Error("Error occured when attempting to count number of open tickets: " + e); + } + + return -1; + } + + public static long GetNumberOfClosedTickets() + { + try + { + using MySqlConnection c = GetConnection(); + using MySqlCommand countTickets = new MySqlCommand("SELECT COUNT(*) FROM ticket_history", c); + c.Open(); + return (long)countTickets.ExecuteScalar(); + } + catch (Exception e) + { + Logger.Error("Error occured when attempting to count number of open tickets: " + e); + } + + return -1; + } + + public static void SetupTables() + { + using MySqlConnection c = GetConnection(); + using MySqlCommand createTickets = new MySqlCommand( + "CREATE TABLE IF NOT EXISTS tickets(" + + "id INT UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT," + + "created_time DATETIME NOT NULL," + + "creator_id BIGINT UNSIGNED NOT NULL," + + "assigned_staff_id BIGINT UNSIGNED NOT NULL DEFAULT 0," + + "summary VARCHAR(5000) NOT NULL," + + "channel_id BIGINT UNSIGNED NOT NULL UNIQUE," + + "INDEX(created_time, assigned_staff_id, channel_id))", + c); + using MySqlCommand createTicketHistory = new MySqlCommand( + "CREATE TABLE IF NOT EXISTS ticket_history(" + + "id INT UNSIGNED NOT NULL PRIMARY KEY," + + "created_time DATETIME NOT NULL," + + "closed_time DATETIME NOT NULL," + + "creator_id BIGINT UNSIGNED NOT NULL," + + "assigned_staff_id BIGINT UNSIGNED NOT NULL DEFAULT 0," + + "summary VARCHAR(5000) NOT NULL," + + "channel_id BIGINT UNSIGNED NOT NULL UNIQUE," + + "INDEX(created_time, closed_time, channel_id))", + c); + using MySqlCommand createBlacklisted = new MySqlCommand( + "CREATE TABLE IF NOT EXISTS blacklisted_users(" + + "user_id BIGINT UNSIGNED NOT NULL PRIMARY KEY," + + "time DATETIME NOT NULL," + + "moderator_id BIGINT UNSIGNED NOT NULL," + + "INDEX(user_id, time))", + c); + using MySqlCommand createStaffList = new MySqlCommand( + "CREATE TABLE IF NOT EXISTS staff(" + + "user_id BIGINT UNSIGNED NOT NULL PRIMARY KEY," + + "name VARCHAR(256) NOT NULL," + + "active BOOLEAN NOT NULL DEFAULT true)", + c); + using MySqlCommand createMessages = new MySqlCommand( + "CREATE TABLE IF NOT EXISTS messages(" + + "identifier VARCHAR(256) NOT NULL PRIMARY KEY," + + "user_id BIGINT UNSIGNED NOT NULL," + + "message VARCHAR(5000) NOT NULL)", + c); + using MySqlCommand createCategories = new MySqlCommand( + "CREATE TABLE IF NOT EXISTS categories(" + + "name VARCHAR(256) NOT NULL UNIQUE," + + "category_id BIGINT UNSIGNED NOT NULL PRIMARY KEY)", + c); + c.Open(); + createTickets.ExecuteNonQuery(); + createBlacklisted.ExecuteNonQuery(); + createTicketHistory.ExecuteNonQuery(); + createStaffList.ExecuteNonQuery(); + createMessages.ExecuteNonQuery(); + createCategories.ExecuteNonQuery(); + } + + public static bool IsOpenTicket(ulong channelID) + { + using MySqlConnection c = GetConnection(); + c.Open(); + using MySqlCommand selection = new MySqlCommand(@"SELECT * FROM tickets WHERE channel_id=@channel_id", c); + selection.Parameters.AddWithValue("@channel_id", channelID); + selection.Prepare(); + MySqlDataReader results = selection.ExecuteReader(); + + // Check if ticket exists in the database + if (!results.Read()) + { + return false; + } + results.Close(); + return true; + } + + public static bool TryGetOpenTicket(ulong channelID, out Ticket ticket) + { + using MySqlConnection c = GetConnection(); + c.Open(); + using MySqlCommand selection = new MySqlCommand(@"SELECT * FROM tickets WHERE channel_id=@channel_id", c); + selection.Parameters.AddWithValue("@channel_id", channelID); + selection.Prepare(); + MySqlDataReader results = selection.ExecuteReader(); + + // Check if ticket exists in the database + if (!results.Read()) + { + ticket = null; + return false; + } + + ticket = new Ticket(results); + results.Close(); + return true; + } + + public static bool TryGetOpenTicketByID(uint id, out Ticket ticket) + { + using MySqlConnection c = GetConnection(); + c.Open(); + using MySqlCommand selection = new MySqlCommand(@"SELECT * FROM tickets WHERE id=@id", c); + selection.Parameters.AddWithValue("@id", id); + selection.Prepare(); + MySqlDataReader results = selection.ExecuteReader(); + + // Check if open ticket exists in the database + if (results.Read()) + { + ticket = new Ticket(results); + results.Close(); + return true; + } + + results.Close(); + ticket = null; + return false; + } + + public static bool TryGetClosedTicket(uint id, out Ticket ticket) + { + using MySqlConnection c = GetConnection(); + c.Open(); + using MySqlCommand selection = new MySqlCommand(@"SELECT * FROM ticket_history WHERE id=@id", c); + selection.Parameters.AddWithValue("@id", id); + selection.Prepare(); + MySqlDataReader results = selection.ExecuteReader(); + + // Check if closed ticket exists in the database + if (results.Read()) + { + ticket = new Ticket(results); + results.Close(); + return true; + } + + ticket = null; + results.Close(); + return false; + } + + public static bool TryGetOpenTickets(ulong userID, out List tickets) + { + tickets = null; + using MySqlConnection c = GetConnection(); + c.Open(); + using MySqlCommand selection = new MySqlCommand(@"SELECT * FROM tickets WHERE creator_id=@creator_id", c); + selection.Parameters.AddWithValue("@creator_id", userID); + selection.Prepare(); + MySqlDataReader results = selection.ExecuteReader(); + + if (!results.Read()) + { + return false; + } + + tickets = new List { new Ticket(results) }; + while (results.Read()) + { + tickets.Add(new Ticket(results)); + } + results.Close(); + return true; + } + + public static bool TryGetOpenTickets(out List tickets) + { + tickets = null; + using MySqlConnection c = GetConnection(); + c.Open(); + using MySqlCommand selection = new MySqlCommand(@"SELECT * FROM tickets ORDER BY channel_id ASC", c); + selection.Prepare(); + MySqlDataReader results = selection.ExecuteReader(); + + if (!results.Read()) + { + return false; + } + + tickets = new List { new Ticket(results) }; + while (results.Read()) + { + tickets.Add(new Ticket(results)); + } + results.Close(); + return true; + } + + public static bool TryGetClosedTickets(ulong userID, out List tickets) + { + tickets = null; + using MySqlConnection c = GetConnection(); + c.Open(); + using MySqlCommand selection = new MySqlCommand(@"SELECT * FROM ticket_history WHERE creator_id=@creator_id", c); + selection.Parameters.AddWithValue("@creator_id", userID); + selection.Prepare(); + MySqlDataReader results = selection.ExecuteReader(); + + if (!results.Read()) + { + return false; + } + + tickets = new List { new Ticket(results) }; + while (results.Read()) + { + tickets.Add(new Ticket(results)); + } + results.Close(); + return true; + } + + public static bool TryGetAssignedTickets(ulong staffID, out List tickets) + { + tickets = null; + using MySqlConnection c = GetConnection(); + c.Open(); + using MySqlCommand selection = new MySqlCommand(@"SELECT * FROM tickets WHERE assigned_staff_id=@assigned_staff_id", c); + selection.Parameters.AddWithValue("@assigned_staff_id", staffID); + selection.Prepare(); + MySqlDataReader results = selection.ExecuteReader(); + + if (!results.Read()) + { + return false; + } + + tickets = new List { new Ticket(results) }; + while (results.Read()) + { + tickets.Add(new Ticket(results)); + } + results.Close(); + return true; + } + + public static long NewTicket(ulong memberID, ulong staffID, ulong ticketID) + { + using MySqlConnection c = GetConnection(); + c.Open(); + using MySqlCommand cmd = new MySqlCommand(@"INSERT INTO tickets (created_time, creator_id, assigned_staff_id, summary, channel_id) VALUES (UTC_TIMESTAMP(), @creator_id, @assigned_staff_id, @summary, @channel_id);", c); + cmd.Parameters.AddWithValue("@creator_id", memberID); + cmd.Parameters.AddWithValue("@assigned_staff_id", staffID); + cmd.Parameters.AddWithValue("@summary", ""); + cmd.Parameters.AddWithValue("@channel_id", ticketID); + cmd.ExecuteNonQuery(); + return cmd.LastInsertedId; + } + + public static void ArchiveTicket(Ticket ticket) + { + // Check if ticket already exists in the archive + if (TryGetClosedTicket(ticket.id, out Ticket _)) + { + using MySqlConnection c = GetConnection(); + using MySqlCommand deleteTicket = new MySqlCommand(@"DELETE FROM ticket_history WHERE id=@id OR channel_id=@channel_id", c); + deleteTicket.Parameters.AddWithValue("@id", ticket.id); + deleteTicket.Parameters.AddWithValue("@channel_id", ticket.channelID); + + c.Open(); + deleteTicket.Prepare(); + deleteTicket.ExecuteNonQuery(); + } + + // Create an entry in the ticket history database + using MySqlConnection conn = GetConnection(); + using MySqlCommand archiveTicket = new MySqlCommand(@"INSERT INTO ticket_history (id, created_time, closed_time, creator_id, assigned_staff_id, summary, channel_id) VALUES (@id, @created_time, UTC_TIMESTAMP(), @creator_id, @assigned_staff_id, @summary, @channel_id);", conn); + archiveTicket.Parameters.AddWithValue("@id", ticket.id); + archiveTicket.Parameters.AddWithValue("@created_time", ticket.channelID.GetSnowflakeTime()); + archiveTicket.Parameters.AddWithValue("@creator_id", ticket.creatorID); + archiveTicket.Parameters.AddWithValue("@assigned_staff_id", ticket.assignedStaffID); + archiveTicket.Parameters.AddWithValue("@summary", ticket.summary); + archiveTicket.Parameters.AddWithValue("@channel_id", ticket.channelID); + + conn.Open(); + archiveTicket.Prepare(); + archiveTicket.ExecuteNonQuery(); + } + + public static bool DeleteOpenTicket(uint ticketID) + { + try + { + using MySqlConnection c = GetConnection(); + using MySqlCommand deletion = new MySqlCommand(@"DELETE FROM tickets WHERE id=@id", c); + deletion.Parameters.AddWithValue("@id", ticketID); + + c.Open(); + deletion.Prepare(); + return deletion.ExecuteNonQuery() > 0; + } + catch (MySqlException) + { + return false; + } + } + + public static bool IsBlacklisted(ulong userID) + { + using MySqlConnection c = GetConnection(); + c.Open(); + using MySqlCommand selection = new MySqlCommand(@"SELECT * FROM blacklisted_users WHERE user_id=@user_id", c); + selection.Parameters.AddWithValue("@user_id", userID); + selection.Prepare(); + MySqlDataReader results = selection.ExecuteReader(); + + // Check if user is blacklisted + if (results.Read()) + { + results.Close(); + return true; + } + results.Close(); + + return false; + } + + public static bool Blacklist(ulong blacklistedID, ulong staffID) + { + try + { + using MySqlConnection c = GetConnection(); + c.Open(); + using MySqlCommand cmd = new MySqlCommand(@"INSERT INTO blacklisted_users (user_id,time,moderator_id) VALUES (@user_id, UTC_TIMESTAMP(), @moderator_id);", c); + cmd.Parameters.AddWithValue("@user_id", blacklistedID); + cmd.Parameters.AddWithValue("@moderator_id", staffID); + cmd.Prepare(); + return cmd.ExecuteNonQuery() > 0; + } + catch (MySqlException) + { + return false; + } + } + + public static bool Unblacklist(ulong blacklistedID) + { + try + { + using MySqlConnection c = GetConnection(); + c.Open(); + using MySqlCommand cmd = new MySqlCommand(@"DELETE FROM blacklisted_users WHERE user_id=@user_id", c); + cmd.Parameters.AddWithValue("@user_id", blacklistedID); + cmd.Prepare(); + return cmd.ExecuteNonQuery() > 0; + } + catch (MySqlException) + { + return false; + } + } + + public static bool AssignStaff(Ticket ticket, ulong staffID) + { + try + { + using MySqlConnection c = GetConnection(); + c.Open(); + using MySqlCommand update = new MySqlCommand(@"UPDATE tickets SET assigned_staff_id = @assigned_staff_id WHERE id = @id", c); + update.Parameters.AddWithValue("@assigned_staff_id", staffID); + update.Parameters.AddWithValue("@id", ticket.id); + update.Prepare(); + return update.ExecuteNonQuery() > 0; + } + catch (MySqlException) + { + return false; + } + } + + public static bool UnassignStaff(Ticket ticket) + { + return AssignStaff(ticket, 0); + } + + public static bool SetStaffActive(ulong staffID, bool active) + { + try + { + using MySqlConnection c = GetConnection(); + c.Open(); + MySqlCommand update = new MySqlCommand(@"UPDATE staff SET active = @active WHERE user_id = @user_id", c); + update.Parameters.AddWithValue("@user_id", staffID); + update.Parameters.AddWithValue("@active", active); + update.Prepare(); + return update.ExecuteNonQuery() > 0; + } + catch (MySqlException) + { + return false; + } + } + + public static StaffMember GetRandomActiveStaff(params ulong[] ignoredUserIDs) + { + List staffMembers = GetActiveStaff(ignoredUserIDs); + return staffMembers.Any() ? staffMembers[random.Next(staffMembers.Count)] : null; + } + + public static List GetActiveStaff(params ulong[] ignoredUserIDs) + { + bool first = true; + string filterString = ""; + foreach (ulong userID in ignoredUserIDs) + { + if (first) + { + first = false; + filterString += "AND user_id != " + userID; + } + else + { + filterString += "&& user_id != " + userID; + } + } + + using MySqlConnection c = GetConnection(); + c.Open(); + using MySqlCommand selection = new MySqlCommand(@"SELECT * FROM staff WHERE active = true " + filterString, c); + selection.Prepare(); + MySqlDataReader results = selection.ExecuteReader(); + + // Check if staff exists in the database + if (!results.Read()) + { + return new List(); + } + + List staffMembers = new List { new StaffMember(results) }; + while (results.Read()) + { + staffMembers.Add(new StaffMember(results)); + } + results.Close(); + + return staffMembers; + } + + public static List GetAllStaff(params ulong[] ignoredUserIDs) + { + bool first = true; + string filterString = ""; + foreach (ulong userID in ignoredUserIDs) + { + if (first) + { + first = false; + filterString += "WHERE user_id != " + userID; + } + else + { + filterString += "&& user_id != " + userID; + } + + } + + + using MySqlConnection c = GetConnection(); + c.Open(); + using MySqlCommand selection = new MySqlCommand(@"SELECT * FROM staff " + filterString, c); + selection.Prepare(); + MySqlDataReader results = selection.ExecuteReader(); + + // Check if staff exist in the database + if (!results.Read()) + { + return new List(); + } + + List staffMembers = new List { new StaffMember(results) }; + while (results.Read()) + { + staffMembers.Add(new StaffMember(results)); + } + results.Close(); + + return staffMembers; + } + + public static bool IsStaff(ulong staffID) + { + using MySqlConnection c = GetConnection(); + c.Open(); + using MySqlCommand selection = new MySqlCommand(@"SELECT * FROM staff WHERE user_id=@user_id", c); + selection.Parameters.AddWithValue("@user_id", staffID); + selection.Prepare(); + MySqlDataReader results = selection.ExecuteReader(); + + // Check if ticket exists in the database + if (!results.Read()) + { + return false; + } + results.Close(); + return true; + } + + public static bool TryGetStaff(ulong staffID, out StaffMember staffMember) + { + using MySqlConnection c = GetConnection(); + c.Open(); + using MySqlCommand selection = new MySqlCommand(@"SELECT * FROM staff WHERE user_id=@user_id", c); + selection.Parameters.AddWithValue("@user_id", staffID); + selection.Prepare(); + MySqlDataReader results = selection.ExecuteReader(); + + // Check if ticket exists in the database + if (!results.Read()) + { + staffMember = null; + return false; + } + staffMember = new StaffMember(results); + results.Close(); + return true; + } + + public static List GetAllMessages() + { + using MySqlConnection c = GetConnection(); + c.Open(); + using MySqlCommand selection = new MySqlCommand(@"SELECT * FROM messages", c); + selection.Prepare(); + MySqlDataReader results = selection.ExecuteReader(); + + // Check if messages exist in the database + if (!results.Read()) + { + return new List(); + } + + List messages = new List { new Message(results) }; + while (results.Read()) + { + messages.Add(new Message(results)); + } + results.Close(); + + return messages; + } + + public static bool TryGetMessage(string identifier, out Message message) + { + using MySqlConnection c = GetConnection(); + c.Open(); + using MySqlCommand selection = new MySqlCommand(@"SELECT * FROM messages WHERE identifier=@identifier", c); + selection.Parameters.AddWithValue("@identifier", identifier); + selection.Prepare(); + MySqlDataReader results = selection.ExecuteReader(); + + // Check if ticket exists in the database + if (!results.Read()) + { + message = null; + return false; + } + message = new Message(results); + results.Close(); + return true; + } + + public static bool AddMessage(string identifier, ulong userID, string message) + { + try + { + using MySqlConnection c = GetConnection(); + c.Open(); + using MySqlCommand cmd = new MySqlCommand(@"INSERT INTO messages (identifier,user_id,message) VALUES (@identifier, @user_id, @message);", c); + cmd.Parameters.AddWithValue("@identifier", identifier); + cmd.Parameters.AddWithValue("@user_id", userID); + cmd.Parameters.AddWithValue("@message", message); + cmd.Prepare(); + return cmd.ExecuteNonQuery() > 0; + } + catch (MySqlException) + { + return false; + } + } + + public static bool RemoveMessage(string identifier) + { + try + { + using MySqlConnection c = GetConnection(); + c.Open(); + using MySqlCommand cmd = new MySqlCommand(@"DELETE FROM messages WHERE identifier=@identifier", c); + cmd.Parameters.AddWithValue("@identifier", identifier); + cmd.Prepare(); + return cmd.ExecuteNonQuery() > 0; + } + catch (MySqlException) + { + return false; + } + } + + public static List GetAllCategories() + { + using MySqlConnection c = GetConnection(); + c.Open(); + using MySqlCommand selection = new MySqlCommand(@"SELECT * FROM categories", c); + selection.Prepare(); + MySqlDataReader results = selection.ExecuteReader(); + + // Check if messages exist in the database + if (!results.Read()) + { + return new List(); + } + + List categories = new List { new Category(results) }; + while (results.Read()) + { + categories.Add(new Category(results)); + } + results.Close(); + + return categories; + } + + public static bool TryGetCategory(ulong categoryID, out Category message) + { + using MySqlConnection c = GetConnection(); + c.Open(); + using MySqlCommand selection = new MySqlCommand(@"SELECT * FROM categories WHERE category_id=@category_id", c); + selection.Parameters.AddWithValue("@category_id", categoryID); + selection.Prepare(); + MySqlDataReader results = selection.ExecuteReader(); + + // Check if ticket exists in the database + if (!results.Read()) + { + message = null; + return false; + } + message = new Category(results); + results.Close(); + return true; + } + + public static bool TryGetCategory(string name, out Category message) + { + using MySqlConnection c = GetConnection(); + c.Open(); + using MySqlCommand selection = new MySqlCommand(@"SELECT * FROM categories WHERE name=@name", c); + selection.Parameters.AddWithValue("@name", name); + selection.Prepare(); + MySqlDataReader results = selection.ExecuteReader(); + + // Check if ticket exists in the database + if (!results.Read()) + { + message = null; + return false; + } + message = new Category(results); + results.Close(); + return true; + } + + public static bool AddCategory(string name, ulong categoryID) + { + try + { + using MySqlConnection c = GetConnection(); + c.Open(); + using MySqlCommand cmd = new MySqlCommand(@"INSERT INTO categories (name,category_id) VALUES (@name, @category_id);", c); + cmd.Parameters.AddWithValue("@name", name); + cmd.Parameters.AddWithValue("@category_id", categoryID); + cmd.Prepare(); + return cmd.ExecuteNonQuery() > 0; + } + catch (MySqlException) + { + return false; + } + } + + public static bool RemoveCategory(ulong categoryID) + { + try + { + using MySqlConnection c = GetConnection(); + c.Open(); + using MySqlCommand cmd = new MySqlCommand(@"DELETE FROM categories WHERE category_id=@category_id", c); + cmd.Parameters.AddWithValue("@category_id", categoryID); + cmd.Prepare(); + return cmd.ExecuteNonQuery() > 0; + } + catch (MySqlException) + { + return false; + } + } + + public class Ticket + { + public uint id; + public ulong creatorID; + public ulong assignedStaffID; + public string summary; + public ulong channelID; + + public Ticket(MySqlDataReader reader) + { + id = reader.GetUInt32("id"); + creatorID = reader.GetUInt64("creator_id"); + assignedStaffID = reader.GetUInt64("assigned_staff_id"); + summary = reader.GetString("summary"); + channelID = reader.GetUInt64("channel_id"); + } + + public string DiscordRelativeTime() + { + return Formatter.Timestamp(channelID.GetSnowflakeTime(), Config.timestampFormat); + } + } + public class StaffMember + { + public ulong userID; + public string name; + public bool active; + + public StaffMember(MySqlDataReader reader) + { + userID = reader.GetUInt64("user_id"); + name = reader.GetString("name"); + active = reader.GetBoolean("active"); + } + } + + public class Message + { + public string identifier; + public ulong userID; + public string message; + + public Message(MySqlDataReader reader) + { + identifier = reader.GetString("identifier"); + userID = reader.GetUInt64("user_id"); + message = reader.GetString("message"); + } + } + + public class Category + { + public string name; + public ulong id; + + public Category(MySqlDataReader reader) + { + name = reader.GetString("name"); + id = reader.GetUInt64("category_id"); + } + } } \ No newline at end of file diff --git a/SupportChild/EventHandler.cs b/SupportChild/EventHandler.cs index 27b35a6..e1ace25 100644 --- a/SupportChild/EventHandler.cs +++ b/SupportChild/EventHandler.cs @@ -14,262 +14,272 @@ namespace SupportChild; internal static class EventHandler { - internal static Task OnReady(DiscordClient client, ReadyEventArgs e) - { - Logger.Log("Client is ready to process events."); + internal static Task OnReady(DiscordClient client, ReadyEventArgs e) + { + Logger.Log("Client is ready to process events."); - // Checking activity type - if (!Enum.TryParse(Config.presenceType, true, out ActivityType activityType)) - { - Logger.Log("Presence type '" + Config.presenceType + "' invalid, using 'Playing' instead."); - activityType = ActivityType.Playing; - } + // Checking activity type + if (!Enum.TryParse(Config.presenceType, true, out ActivityType activityType)) + { + Logger.Log("Presence type '" + Config.presenceType + "' invalid, using 'Playing' instead."); + activityType = ActivityType.Playing; + } - client.UpdateStatusAsync(new DiscordActivity(Config.presenceText, activityType), UserStatus.Online); - return Task.CompletedTask; - } + client.UpdateStatusAsync(new DiscordActivity(Config.presenceText, activityType), UserStatus.Online); + return Task.CompletedTask; + } - internal static Task OnGuildAvailable(DiscordClient _, GuildCreateEventArgs e) - { - Logger.Log("Guild available: " + e.Guild.Name); + internal static Task OnGuildAvailable(DiscordClient _, GuildCreateEventArgs e) + { + Logger.Log("Guild available: " + e.Guild.Name); - IReadOnlyDictionary roles = e.Guild.Roles; + IReadOnlyDictionary roles = e.Guild.Roles; - foreach ((ulong roleID, DiscordRole role) in roles) - { - Logger.Log(role.Name.PadRight(40, '.') + roleID); - } - return Task.CompletedTask; - } + foreach ((ulong roleID, DiscordRole role) in roles) + { + Logger.Log(role.Name.PadRight(40, '.') + roleID); + } + return Task.CompletedTask; + } - internal static Task OnClientError(DiscordClient _, ClientErrorEventArgs e) - { - Logger.Error("Client exception occured:\n" + e.Exception); - switch (e.Exception) - { - case BadRequestException ex: - Logger.Error("JSON Message: " + ex.JsonMessage); - break; - } - return Task.CompletedTask; - } + internal static Task OnClientError(DiscordClient _, ClientErrorEventArgs e) + { + Logger.Error("Client exception occured:\n" + e.Exception); + switch (e.Exception) + { + case BadRequestException ex: + Logger.Error("JSON Message: " + ex.JsonMessage); + break; + } + return Task.CompletedTask; + } - internal static async Task OnMessageCreated(DiscordClient client, MessageCreateEventArgs e) - { - if (e.Author.IsBot) - { - return; - } + internal static async Task OnMessageCreated(DiscordClient client, MessageCreateEventArgs e) + { + if (e.Author.IsBot) + { + return; + } - // Check if ticket exists in the database and ticket notifications are enabled - if (!Database.TryGetOpenTicket(e.Channel.Id, out Database.Ticket ticket) || !Config.ticketUpdatedNotifications) - { - return; - } + // Check if ticket exists in the database and ticket notifications are enabled + if (!Database.TryGetOpenTicket(e.Channel.Id, out Database.Ticket ticket) || !Config.ticketUpdatedNotifications) + { + return; + } - // Sends a DM to the assigned staff member if at least a day has gone by since the last message and the user sending the message isn't staff - IReadOnlyList messages = await e.Channel.GetMessagesAsync(2); - if (messages.Count > 1 && messages[1].Timestamp < DateTimeOffset.UtcNow.AddDays(Config.ticketUpdatedNotificationDelay * -1) && !Database.IsStaff(e.Author.Id)) - { - try - { - DiscordMember staffMember = await e.Guild.GetMemberAsync(ticket.assignedStaffID); - await staffMember.SendMessageAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Green, - Description = "A ticket you are assigned to has been updated: " + e.Channel.Mention - }); - } - catch (NotFoundException) { } - catch (UnauthorizedException) { } - } - } + // Sends a DM to the assigned staff member if at least a day has gone by since the last message and the user sending the message isn't staff + IReadOnlyList messages = await e.Channel.GetMessagesAsync(2); + if (messages.Count > 1 && messages[1].Timestamp < DateTimeOffset.UtcNow.AddDays(Config.ticketUpdatedNotificationDelay * -1) && !Database.IsStaff(e.Author.Id)) + { + try + { + DiscordMember staffMember = await e.Guild.GetMemberAsync(ticket.assignedStaffID); + await staffMember.SendMessageAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Green, + Description = "A ticket you are assigned to has been updated: " + e.Channel.Mention + }); + } + catch (NotFoundException) { } + catch (UnauthorizedException) { } + } + } - internal static async Task OnCommandError(SlashCommandsExtension commandSystem, SlashCommandErrorEventArgs e) - { - switch (e.Exception) - { - case SlashExecutionChecksFailedException checksFailedException: - { - foreach (SlashCheckBaseAttribute attr in checksFailedException.FailedChecks) - { - await e.Context.Channel.SendMessageAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Red, - Description = ParseFailedCheck(attr) - }); - } - return; - } + internal static async Task OnCommandError(SlashCommandsExtension commandSystem, SlashCommandErrorEventArgs e) + { + switch (e.Exception) + { + case SlashExecutionChecksFailedException checksFailedException: + { + foreach (SlashCheckBaseAttribute attr in checksFailedException.FailedChecks) + { + await e.Context.Channel.SendMessageAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = ParseFailedCheck(attr) + }); + } + return; + } - case BadRequestException ex: - Logger.Error("Command exception occured:\n" + e.Exception); - Logger.Error("JSON Message: " + ex.JsonMessage); - return; + case BadRequestException ex: + Logger.Error("Command exception occured:\n" + e.Exception); + Logger.Error("JSON Message: " + ex.JsonMessage); + return; - default: - { - Logger.Error("Exception occured: " + e.Exception.GetType() + ": " + e.Exception); - await e.Context.Channel.SendMessageAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Red, - Description = "Internal error occured, please report this to the developer." - }); - return; - } - } - } + default: + { + Logger.Error("Exception occured: " + e.Exception.GetType() + ": " + e.Exception); + await e.Context.Channel.SendMessageAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "Internal error occured, please report this to the developer." + }); + return; + } + } + } - internal static async Task OnMemberAdded(DiscordClient client, GuildMemberAddEventArgs e) - { - if (!Database.TryGetOpenTickets(e.Member.Id, out List ownTickets)) - { - return; - } + internal static async Task OnMemberAdded(DiscordClient client, GuildMemberAddEventArgs e) + { + if (!Database.TryGetOpenTickets(e.Member.Id, out List ownTickets)) + { + return; + } - foreach (Database.Ticket ticket in ownTickets) - { - try - { - DiscordChannel channel = await client.GetChannelAsync(ticket.channelID); - if (channel?.GuildId == e.Guild.Id) - { - await channel.SendMessageAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Green, - Description = "User '" + e.Member.Username + "#" + e.Member.Discriminator + "' has rejoined the server, and has been re-added to the ticket." - }); - } - } - catch (Exception) { /* ignored */ } - } - } + foreach (Database.Ticket ticket in ownTickets) + { + try + { + DiscordChannel channel = await client.GetChannelAsync(ticket.channelID); + if (channel?.GuildId == e.Guild.Id) + { + try + { + await channel.AddOverwriteAsync(e.Member, Permissions.AccessChannels); + await channel.SendMessageAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Green, + Description = "User '" + e.Member.Username + "#" + e.Member.Discriminator + "' has rejoined the server, and has been re-added to the ticket." + }); + } + catch (DiscordException ex) + { + Logger.Error("Exception occurred trying to add channel permissions: " + ex); + Logger.Error("JsomMessage: " + ex.JsonMessage); + } - internal static async Task OnMemberRemoved(DiscordClient client, GuildMemberRemoveEventArgs e) - { - if (Database.TryGetOpenTickets(e.Member.Id, out List ownTickets)) - { - foreach (Database.Ticket ticket in ownTickets) - { - try - { - DiscordChannel channel = await client.GetChannelAsync(ticket.channelID); - if (channel?.GuildId == e.Guild.Id) - { - await channel.SendMessageAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Red, - Description = "User '" + e.Member.Username + "#" + e.Member.Discriminator + "' has left the server." - }); - } - } - catch (Exception) { /* ignored */ } - } - } + } + } + catch (Exception) { /* ignored */ } + } + } - if (Database.TryGetAssignedTickets(e.Member.Id, out List assignedTickets) && Config.logChannel != 0) - { - DiscordChannel logChannel = await client.GetChannelAsync(Config.logChannel); - if (logChannel != null) - { - foreach (Database.Ticket ticket in assignedTickets) - { - try - { - DiscordChannel channel = await client.GetChannelAsync(ticket.channelID); - if (channel?.GuildId == e.Guild.Id) - { - await logChannel.SendMessageAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Red, - Description = "Assigned staff member '" + e.Member.Username + "#" + e.Member.Discriminator + "' has left the server: <#" + channel.Id + ">" - }); - } - } - catch (Exception) { /* ignored */ } - } - } - } - } + internal static async Task OnMemberRemoved(DiscordClient client, GuildMemberRemoveEventArgs e) + { + if (Database.TryGetOpenTickets(e.Member.Id, out List ownTickets)) + { + foreach (Database.Ticket ticket in ownTickets) + { + try + { + DiscordChannel channel = await client.GetChannelAsync(ticket.channelID); + if (channel?.GuildId == e.Guild.Id) + { + await channel.SendMessageAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "User '" + e.Member.Username + "#" + e.Member.Discriminator + "' has left the server." + }); + } + } + catch (Exception) { /* ignored */ } + } + } - internal static async Task OnComponentInteractionCreated(DiscordClient client, ComponentInteractionCreateEventArgs e) - { - try - { - switch (e.Interaction.Data.ComponentType) - { - case ComponentType.Button: - switch (e.Id) - { - case "supportchild_closeconfirm": - await CloseCommand.OnConfirmed(e.Interaction); - return; - case { } when e.Id.StartsWith("supportchild_newcommandbutton"): - await NewCommand.OnCategorySelection(e.Interaction); - return; - case { } when e.Id.StartsWith("supportchild_newticketbutton"): - await CreateButtonPanelCommand.OnButtonUsed(e.Interaction); - return; - case "right": - return; - case "left": - return; - case "rightskip": - return; - case "leftskip": - return; - case "stop": - return; - default: - Logger.Warn("Unknown button press received! '" + e.Id + "'"); - return; - } - case ComponentType.Select: - switch (e.Id) - { - case { } when e.Id.StartsWith("supportchild_newcommandselector"): - await NewCommand.OnCategorySelection(e.Interaction); - return; - case { } when e.Id.StartsWith("supportchild_newticketselector"): - await CreateSelectionBoxPanelCommand.OnSelectionMenuUsed(e.Interaction); - return; - default: - Logger.Warn("Unknown selection box option received! '" + e.Id + "'"); - return; - } - case ComponentType.ActionRow: - Logger.Warn("Unknown action row received! '" + e.Id + "'"); - return; - case ComponentType.FormInput: - Logger.Warn("Unknown form input received! '" + e.Id + "'"); - return; - default: - Logger.Warn("Unknown interaction type received! '" + e.Interaction.Data.ComponentType + "'"); - break; - } - } - catch (DiscordException ex) - { - Logger.Error("Interaction Exception occurred: " + ex); - Logger.Error("JsomMessage: " + ex.JsonMessage); - } - catch (Exception ex) - { - Logger.Error("Interaction Exception occured: " + ex.GetType() + ": " + ex); - } - } + if (Database.TryGetAssignedTickets(e.Member.Id, out List assignedTickets) && Config.logChannel != 0) + { + DiscordChannel logChannel = await client.GetChannelAsync(Config.logChannel); + if (logChannel != null) + { + foreach (Database.Ticket ticket in assignedTickets) + { + try + { + DiscordChannel channel = await client.GetChannelAsync(ticket.channelID); + if (channel?.GuildId == e.Guild.Id) + { + await logChannel.SendMessageAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "Assigned staff member '" + e.Member.Username + "#" + e.Member.Discriminator + "' has left the server: <#" + channel.Id + ">" + }); + } + } + catch (Exception) { /* ignored */ } + } + } + } + } - private static string ParseFailedCheck(SlashCheckBaseAttribute attr) - { - return attr switch - { - SlashRequireDirectMessageAttribute => "This command can only be used in direct messages!", - SlashRequireOwnerAttribute => "Only the server owner can use that command!", - SlashRequirePermissionsAttribute => "You don't have permission to do that!", - SlashRequireBotPermissionsAttribute => "The bot doesn't have the required permissions to do that!", - SlashRequireUserPermissionsAttribute => "You don't have permission to do that!", - SlashRequireGuildAttribute => "This command has to be used in a Discord server!", - _ => "Unknown Discord API error occured, please try again later." - }; - } + internal static async Task OnComponentInteractionCreated(DiscordClient client, ComponentInteractionCreateEventArgs e) + { + try + { + switch (e.Interaction.Data.ComponentType) + { + case ComponentType.Button: + switch (e.Id) + { + case "supportchild_closeconfirm": + await CloseCommand.OnConfirmed(e.Interaction); + return; + case { } when e.Id.StartsWith("supportchild_newcommandbutton"): + await NewCommand.OnCategorySelection(e.Interaction); + return; + case { } when e.Id.StartsWith("supportchild_newticketbutton"): + await CreateButtonPanelCommand.OnButtonUsed(e.Interaction); + return; + case "right": + return; + case "left": + return; + case "rightskip": + return; + case "leftskip": + return; + case "stop": + return; + default: + Logger.Warn("Unknown button press received! '" + e.Id + "'"); + return; + } + case ComponentType.StringSelect: + switch (e.Id) + { + case { } when e.Id.StartsWith("supportchild_newcommandselector"): + await NewCommand.OnCategorySelection(e.Interaction); + return; + case { } when e.Id.StartsWith("supportchild_newticketselector"): + await CreateSelectionBoxPanelCommand.OnSelectionMenuUsed(e.Interaction); + return; + default: + Logger.Warn("Unknown selection box option received! '" + e.Id + "'"); + return; + } + case ComponentType.ActionRow: + Logger.Warn("Unknown action row received! '" + e.Id + "'"); + return; + case ComponentType.FormInput: + Logger.Warn("Unknown form input received! '" + e.Id + "'"); + return; + default: + Logger.Warn("Unknown interaction type received! '" + e.Interaction.Data.ComponentType + "'"); + break; + } + } + catch (DiscordException ex) + { + Logger.Error("Interaction Exception occurred: " + ex); + Logger.Error("JsomMessage: " + ex.JsonMessage); + } + catch (Exception ex) + { + Logger.Error("Interaction Exception occured: " + ex.GetType() + ": " + ex); + } + } + + private static string ParseFailedCheck(SlashCheckBaseAttribute attr) + { + return attr switch + { + SlashRequireDirectMessageAttribute => "This command can only be used in direct messages!", + SlashRequireOwnerAttribute => "Only the server owner can use that command!", + SlashRequirePermissionsAttribute => "You don't have permission to do that!", + SlashRequireBotPermissionsAttribute => "The bot doesn't have the required permissions to do that!", + SlashRequireUserPermissionsAttribute => "You don't have permission to do that!", + SlashRequireGuildAttribute => "This command has to be used in a Discord server!", + _ => "Unknown Discord API error occured, please try again later." + }; + } } \ No newline at end of file diff --git a/SupportChild/SupportChild.csproj b/SupportChild/SupportChild.csproj index 3020989..e8c7a63 100644 --- a/SupportChild/SupportChild.csproj +++ b/SupportChild/SupportChild.csproj @@ -1,4 +1,4 @@ - + Exe @@ -16,8 +16,8 @@ https://cdn.discordapp.com/attachments/765441543100170271/914327948667011132/Ellie_Concept_2_transparent_ver.png A Discord support ticket bot built for the Ellie's home server en - 1.3.0 - 1.3.0 + 1.3.1 + 1.3.1 3.0.0.1 3.0.0.1 @@ -27,19 +27,19 @@ - - - + + + - + - +