diff --git a/SupportChild/Config.cs b/SupportChild/Config.cs index 858e17b..69ad566 100644 --- a/SupportChild/Config.cs +++ b/SupportChild/Config.cs @@ -1,143 +1,95 @@ using System; -using System.Collections.Generic; using System.IO; -using System.Linq; using System.Text; -using DSharpPlus.Entities; +using DSharpPlus; +using Microsoft.Extensions.Logging; using Newtonsoft.Json.Linq; using SupportChild.Properties; using YamlDotNet.Serialization; -namespace SupportChild +namespace SupportChild; + +internal static class Config { - internal static class Config + internal static string token = ""; + internal static ulong logChannel; + internal static string welcomeMessage = ""; + internal static LogLevel logLevel = LogLevel.Information; + internal static TimestampFormat timestampFormat = TimestampFormat.RelativeTime; + internal static bool randomAssignment = false; + internal static bool randomAssignRoleOverride = false; + internal static string presenceType = "Playing"; + internal static string presenceText = ""; + internal static bool newCommandUsesSelector = false; + internal static int ticketLimit = 5; + + internal static bool ticketUpdatedNotifications = false; + internal static double ticketUpdatedNotificationDelay = 0.0; + internal static bool assignmentNotifications = false; + internal static bool closingNotifications = false; + + internal static string hostName = "127.0.0.1"; + internal static int port = 3306; + internal static string database = "supportchild"; + internal static string username = "supportchild"; + internal static string password = ""; + + public static void LoadConfig() { - internal static string token = ""; - internal static string prefix = ""; - internal static ulong logChannel; - internal static ulong ticketCategory; - internal static ulong reactionMessage; - internal static string welcomeMessage = ""; - internal static string logLevel = "Information"; - internal static string timestampFormat = "yyyy-MMM-dd HH:mm"; - internal static bool randomAssignment = false; - internal static bool randomAssignRoleOverride = false; - internal static string presenceType = "Playing"; - internal static string presenceText = ""; - - internal static bool ticketUpdatedNotifications = false; - internal static double ticketUpdatedNotificationDelay = 0.0; - internal static bool assignmentNotifications = false; - internal static bool closingNotifications = false; - - internal static string hostName = "127.0.0.1"; - internal static int port = 3306; - internal static string database = "supportbot"; - internal static string username = "supportbot"; - internal static string password = ""; - - private static readonly Dictionary permissions = new Dictionary + // Writes default config to file if it does not already exist + if (!File.Exists("./config.yml")) { - // Public commands - { "close", new ulong[]{ } }, - { "list", new ulong[]{ } }, - { "new", new ulong[]{ } }, - { "say", new ulong[]{ } }, - { "status", new ulong[]{ } }, - { "summary", new ulong[]{ } }, - { "transcript", new ulong[]{ } }, - // Moderator commands - { "add", new ulong[]{ } }, - { "addmessage", new ulong[]{ } }, - { "assign", new ulong[]{ } }, - { "blacklist", new ulong[]{ } }, - { "listassigned", new ulong[]{ } }, - { "listoldest", new ulong[]{ } }, - { "listunassigned", new ulong[]{ } }, - { "move", new ulong[]{ } }, - { "rassign", new ulong[]{ } }, - { "removemessage", new ulong[]{ } }, - { "setsummary", new ulong[]{ } }, - { "toggleactive", new ulong[]{ } }, - { "unassign", new ulong[]{ } }, - { "unblacklist", new ulong[]{ } }, - // Admin commands - { "addstaff", new ulong[]{ } }, - { "reload", new ulong[]{ } }, - { "removestaff", new ulong[]{ } }, - { "setticket", new ulong[]{ } }, - { "unsetticket", new ulong[]{ } }, - }; - - public static void LoadConfig() - { - // Writes default config to file if it does not already exist - if (!File.Exists("./config.yml")) - { - File.WriteAllText("./config.yml", Encoding.UTF8.GetString(Resources.default_config)); - } - - // Reads config contents into FileStream - FileStream stream = File.OpenRead("./config.yml"); - - // Converts the FileStream into a YAML object - IDeserializer deserializer = new DeserializerBuilder().Build(); - object yamlObject = deserializer.Deserialize(new StreamReader(stream)); - - // Converts the YAML object into a JSON object as the YAML ones do not support traversal or selection of nodes by name - ISerializer serializer = new SerializerBuilder().JsonCompatible().Build(); - JObject json = JObject.Parse(serializer.Serialize(yamlObject)); - - // Sets up the bot - token = json.SelectToken("bot.token").Value() ?? ""; - prefix = json.SelectToken("bot.prefix").Value() ?? ""; - logChannel = json.SelectToken("bot.log-channel").Value(); - ticketCategory = json.SelectToken("bot.ticket-category")?.Value() ?? 0; - reactionMessage = json.SelectToken("bot.reaction-message")?.Value() ?? 0; - welcomeMessage = json.SelectToken("bot.welcome-message").Value() ?? ""; - logLevel = json.SelectToken("bot.console-log-level").Value() ?? ""; - timestampFormat = json.SelectToken("bot.timestamp-format").Value() ?? "yyyy-MM-dd HH:mm"; - randomAssignment = json.SelectToken("bot.random-assignment")?.Value() ?? false; - randomAssignRoleOverride = json.SelectToken("bot.random-assign-role-override")?.Value() ?? false; - presenceType = json.SelectToken("bot.presence-type")?.Value() ?? "Playing"; - presenceText = json.SelectToken("bot.presence-text")?.Value() ?? ""; - - ticketUpdatedNotifications = json.SelectToken("notifications.ticket-updated")?.Value() ?? false; - ticketUpdatedNotificationDelay = json.SelectToken("notifications.ticket-updated-delay")?.Value() ?? 0.0; - assignmentNotifications = json.SelectToken("notifications.assignment")?.Value() ?? false; - closingNotifications = json.SelectToken("notifications.closing")?.Value() ?? false; - - // Reads database info - hostName = json.SelectToken("database.address")?.Value() ?? ""; - port = json.SelectToken("database.port")?.Value() ?? 3306; - database = json.SelectToken("database.name")?.Value() ?? "supportchild"; - username = json.SelectToken("database.user")?.Value() ?? "supportchild"; - password = json.SelectToken("database.password")?.Value() ?? ""; - - timestampFormat = timestampFormat.Trim(); - - foreach (KeyValuePair node in permissions.ToList()) - { - try - { - permissions[node.Key] = json.SelectToken("permissions." + node.Key).Value().Values().ToArray(); - } - catch (ArgumentNullException) - { - Console.WriteLine("Permission node '" + node.Key + "' was not found in the config, using default value: []"); - } - } + File.WriteAllText("./config.yml", Encoding.UTF8.GetString(Resources.default_config)); } - /// - /// Checks whether a user has a specific permission. - /// - /// The Discord user to check. - /// The permission name to check. - /// - public static bool HasPermission(DiscordMember member, string permission) + // Reads config contents into FileStream + FileStream stream = File.OpenRead("./config.yml"); + + // Converts the FileStream into a YAML object + IDeserializer deserializer = new DeserializerBuilder().Build(); + object yamlObject = deserializer.Deserialize(new StreamReader(stream)) ?? ""; + + // Converts the YAML object into a JSON object as the YAML ones do not support traversal or selection of nodes by name + ISerializer serializer = new SerializerBuilder().JsonCompatible().Build(); + JObject json = JObject.Parse(serializer.Serialize(yamlObject)); + + // Sets up the bot + token = json.SelectToken("bot.token")?.Value() ?? ""; + logChannel = json.SelectToken("bot.log-channel")?.Value() ?? 0; + welcomeMessage = json.SelectToken("bot.welcome-message")?.Value() ?? ""; + string stringLogLevel = json.SelectToken("bot.console-log-level")?.Value() ?? ""; + + if (!Enum.TryParse(stringLogLevel, true, out logLevel)) { - return member.Roles.Any(role => permissions[permission].Contains(role.Id)) || permissions[permission].Contains(member.Guild.Id); + logLevel = LogLevel.Information; + Logger.Warn("Log level '" + stringLogLevel + "' invalid, using 'Information' instead."); } + + string stringTimestampFormat = json.SelectToken("bot.timestamp-format")?.Value() ?? "RelativeTime"; + + if (!Enum.TryParse(stringTimestampFormat, true, out timestampFormat)) + { + timestampFormat = TimestampFormat.RelativeTime; + Logger.Warn("Timestamp '" + stringTimestampFormat + "' invalid, using 'RelativeTime' instead."); + } + + randomAssignment = json.SelectToken("bot.random-assignment")?.Value() ?? false; + randomAssignRoleOverride = json.SelectToken("bot.random-assign-role-override")?.Value() ?? false; + presenceType = json.SelectToken("bot.presence-type")?.Value() ?? "Playing"; + presenceText = json.SelectToken("bot.presence-text")?.Value() ?? ""; + newCommandUsesSelector = json.SelectToken("bot.new-command-uses-selector")?.Value() ?? false; + ticketLimit = json.SelectToken("bot.ticket-limit")?.Value() ?? 5; + + ticketUpdatedNotifications = json.SelectToken("notifications.ticket-updated")?.Value() ?? false; + ticketUpdatedNotificationDelay = json.SelectToken("notifications.ticket-updated-delay")?.Value() ?? 0.0; + assignmentNotifications = json.SelectToken("notifications.assignment")?.Value() ?? false; + closingNotifications = json.SelectToken("notifications.closing")?.Value() ?? false; + + // Reads database info + hostName = json.SelectToken("database.address")?.Value() ?? ""; + port = json.SelectToken("database.port")?.Value() ?? 3306; + database = json.SelectToken("database.name")?.Value() ?? "supportchild"; + username = json.SelectToken("database.user")?.Value() ?? "supportchild"; + password = json.SelectToken("database.password")?.Value() ?? ""; } } \ No newline at end of file diff --git a/SupportChild/Database.cs b/SupportChild/Database.cs index 57ecbca..e78160c 100644 --- a/SupportChild/Database.cs +++ b/SupportChild/Database.cs @@ -1,691 +1,818 @@ using System; using System.Linq; using System.Collections.Generic; +using DSharpPlus; using MySql.Data.MySqlClient; -namespace SupportChild +namespace SupportChild; + +public static class Database { - 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) { - private static string connectionString = ""; + connectionString = "server=" + host + + ";database=" + database + + ";port=" + port + + ";userid=" + username + + ";password=" + password; + } - private static Random random = new Random(); + public static MySqlConnection GetConnection() + { + return new MySqlConnection(connectionString); + } - public static void SetConnectionString(string host, int port, string database, string username, string password) + public static long GetNumberOfTickets() + { + try { - connectionString = "server=" + host + - ";database=" + database + - ";port=" + port + - ";userid=" + username + - ";password=" + password; + using MySqlConnection c = GetConnection(); + using MySqlCommand countTickets = new MySqlCommand("SELECT COUNT(*) FROM tickets", c); + c.Open(); + return (long)countTickets.ExecuteScalar(); } - public static MySqlConnection GetConnection() + catch (Exception e) { - return new MySqlConnection(connectionString); - } - public static long GetNumberOfTickets() - { - try - { - using (MySqlConnection c = GetConnection()) - { - MySqlCommand countTickets = new MySqlCommand("SELECT COUNT(*) FROM tickets", c); - c.Open(); - return (long)countTickets.ExecuteScalar(); - } - } - catch (Exception e) - { - Console.WriteLine("Error occured when attempting to count number of open tickets: " + e); - } - - return -1; - } - public static long GetNumberOfClosedTickets() - { - try - { - using (MySqlConnection c = GetConnection()) - { - MySqlCommand countTickets = new MySqlCommand("SELECT COUNT(*) FROM ticket_history", c); - c.Open(); - return (long)countTickets.ExecuteScalar(); - } - } - catch (Exception e) - { - Console.WriteLine("Error occured when attempting to count number of open tickets: " + e); - } - - return -1; - } - public static void SetupTables() - { - using (MySqlConnection c = GetConnection()) - { - 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); - 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); - 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); - 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); - 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); - c.Open(); - createTickets.ExecuteNonQuery(); - createBlacklisted.ExecuteNonQuery(); - createTicketHistory.ExecuteNonQuery(); - createStaffList.ExecuteNonQuery(); - createMessages.ExecuteNonQuery(); - } - } - public static bool IsOpenTicket(ulong channelID) - { - using (MySqlConnection c = GetConnection()) - { - c.Open(); - 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(); - 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(); - 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); - return true; - } - - ticket = null; - return false; - } - } - public static bool TryGetClosedTicket(uint id, out Ticket ticket) - { - using (MySqlConnection c = GetConnection()) - { - c.Open(); - 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); - return true; - } - - ticket = null; - return false; - } - } - public static bool TryGetOpenTickets(ulong userID, out List tickets) - { - tickets = null; - using (MySqlConnection c = GetConnection()) - { - c.Open(); - 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 TryGetOldestTickets(ulong userID, out List tickets, int listLimit) - { - tickets = null; - using (MySqlConnection c = GetConnection()) - { - c.Open(); - MySqlCommand selection = new MySqlCommand(@"SELECT * FROM tickets ORDER BY created_time ASC LIMIT @limit", c); - selection.Parameters.AddWithValue("@creator_id", userID); - selection.Parameters.AddWithValue("@limit", listLimit); - 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(); - 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(); - 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(); - 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; - } + Logger.Error("Error occured when attempting to count number of open tickets: " + e); } - public static void ArchiveTicket(Ticket ticket) + return -1; + } + + public static long GetNumberOfClosedTickets() + { + try { - // Check if ticket already exists in the archive - if (TryGetClosedTicket(ticket.id, out Ticket _)) - { - using (MySqlConnection c = GetConnection()) - { - 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(); - } - } - - using (MySqlConnection c = GetConnection()) - { - // Create an entry in the ticket history database - 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);", c); - archiveTicket.Parameters.AddWithValue("@id", ticket.id); - archiveTicket.Parameters.AddWithValue("@created_time", ticket.createdTime); - 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); - - c.Open(); - archiveTicket.Prepare(); - archiveTicket.ExecuteNonQuery(); - } + 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); } - public static void DeleteOpenTicket(uint ticketID) + 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()) { - using (MySqlConnection c = GetConnection()) - { - MySqlCommand deletion = new MySqlCommand(@"DELETE FROM tickets WHERE id=@id", c); - deletion.Parameters.AddWithValue("@id", ticketID); - - c.Open(); - deletion.Prepare(); - deletion.ExecuteNonQuery(); - } - } - - public static bool IsBlacklisted(ulong userID) - { - using (MySqlConnection c = GetConnection()) - { - c.Open(); - 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) + 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()) { - using (MySqlConnection c = GetConnection()) + 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) { - try - { - c.Open(); - 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; - } + first = false; + filterString += "AND user_id != " + userID; } - } - public static bool Unblacklist(ulong blacklistedID) - { - using (MySqlConnection c = GetConnection()) + else { - try - { - c.Open(); - 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) - { - using (MySqlConnection c = GetConnection()) - { - try - { - c.Open(); - 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 StaffMember GetRandomActiveStaff(ulong currentStaffID) - { - List staffMembers = GetActiveStaff(currentStaffID); - if (!staffMembers.Any()) - { - return null; - } - - return staffMembers[random.Next(staffMembers.Count)]; - } - - public static List GetActiveStaff(ulong currentStaffID = 0) - { - using (MySqlConnection c = GetConnection()) - { - c.Open(); - MySqlCommand selection = new MySqlCommand(@"SELECT * FROM staff WHERE active = true AND user_id != @user_id", c); - selection.Parameters.AddWithValue("@user_id", currentStaffID); - 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; + filterString += "&& user_id != " + userID; } } - public static List GetAllStaff(ulong currentStaffID = 0) + 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()) { - using (MySqlConnection c = GetConnection()) - { - c.Open(); - MySqlCommand selection = new MySqlCommand(@"SELECT * FROM staff WHERE user_id != @user_id", c); - selection.Parameters.AddWithValue("@user_id", currentStaffID); - 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; - } + return new List(); } - public static bool IsStaff(ulong staffID) + List staffMembers = new List { new StaffMember(results) }; + while (results.Read()) { - using (MySqlConnection c = GetConnection()) - { - c.Open(); - 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; - } + staffMembers.Add(new StaffMember(results)); } - public static bool TryGetStaff(ulong staffID, out StaffMember staffMember) - { - using (MySqlConnection c = GetConnection()) - { - c.Open(); - 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(); + results.Close(); - // Check if ticket exists in the database - if (!results.Read()) - { - staffMember = null; - return false; - } - staffMember = new StaffMember(results); - results.Close(); - return true; + 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; + } + } - public static List GetAllMessages() + + 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()) { - using (MySqlConnection c = GetConnection()) - { - c.Open(); - 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; - } + return new List(); } - public static bool TryGetMessage(string identifier, out Message message) + List staffMembers = new List { new StaffMember(results) }; + while (results.Read()) { - using (MySqlConnection c = GetConnection()) - { - c.Open(); - MySqlCommand selection = new MySqlCommand(@"SELECT * FROM messages WHERE identifier=@identifier", c); - selection.Parameters.AddWithValue("@identifier", identifier); - selection.Prepare(); - MySqlDataReader results = selection.ExecuteReader(); + staffMembers.Add(new StaffMember(results)); + } + results.Close(); - // Check if ticket exists in the database - if (!results.Read()) - { - message = null; - return false; - } - message = new Message(results); - results.Close(); - return true; - } + 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(); } - public static bool AddMessage(string identifier, ulong userID, string message) + List messages = new List { new Message(results) }; + while (results.Read()) { - using (MySqlConnection c = GetConnection()) - { - try - { - c.Open(); - 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; - } - } + 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(); } - public static bool RemoveMessage(string identifier) + List categories = new List { new Category(results) }; + while (results.Read()) { - using (MySqlConnection c = GetConnection()) - { - try - { - c.Open(); - 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; - } + 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 class Ticket + public string DiscordRelativeTime() { - public uint id; - public DateTime createdTime; - public ulong creatorID; - public ulong assignedStaffID; - public string summary; - public ulong channelID; - - public Ticket(MySqlDataReader reader) - { - this.id = reader.GetUInt32("id"); - this.createdTime = reader.GetDateTime("created_time"); - this.creatorID = reader.GetUInt64("creator_id"); - this.assignedStaffID = reader.GetUInt64("assigned_staff_id"); - this.summary = reader.GetString("summary"); - this.channelID = reader.GetUInt64("channel_id"); - } - - public string FormattedCreatedTime() - { - return this.createdTime.ToString(Config.timestampFormat); - } + return Formatter.Timestamp(channelID.GetSnowflakeTime(), Config.timestampFormat); } - public class StaffMember - { - public ulong userID; - public string name; - public bool active; + } + public class StaffMember + { + public ulong userID; + public string name; + public bool active; - public StaffMember(MySqlDataReader reader) - { - this.userID = reader.GetUInt64("user_id"); - this.name = reader.GetString("name"); - this.active = reader.GetBoolean("active"); - } + public StaffMember(MySqlDataReader reader) + { + userID = reader.GetUInt64("user_id"); + name = reader.GetString("name"); + active = reader.GetBoolean("active"); } + } - public class Message + public class Message + { + public string identifier; + public ulong userID; + public string message; + + public Message(MySqlDataReader reader) { - public string identifier; - public ulong userID; - public string message; + identifier = reader.GetString("identifier"); + userID = reader.GetUInt64("user_id"); + message = reader.GetString("message"); + } + } - public Message(MySqlDataReader reader) - { - this.identifier = reader.GetString("identifier"); - this.userID = reader.GetUInt64("user_id"); - this.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 e5f61f8..27b35a6 100644 --- a/SupportChild/EventHandler.cs +++ b/SupportChild/EventHandler.cs @@ -2,223 +2,153 @@ using System.Collections.Generic; using System.Threading.Tasks; using DSharpPlus; -using DSharpPlus.CommandsNext; -using DSharpPlus.CommandsNext.Attributes; -using DSharpPlus.CommandsNext.Exceptions; using DSharpPlus.Entities; using DSharpPlus.EventArgs; using DSharpPlus.Exceptions; -using Microsoft.Extensions.Logging; +using DSharpPlus.SlashCommands; +using DSharpPlus.SlashCommands.Attributes; +using DSharpPlus.SlashCommands.EventArgs; +using SupportChild.Commands; -namespace SupportChild +namespace SupportChild; + +internal static class EventHandler { - internal class EventHandler + internal static Task OnReady(DiscordClient client, ReadyEventArgs e) { - private DiscordClient discordClient; + Logger.Log("Client is ready to process events."); - //DateTime for the end of the cooldown - private static Dictionary reactionTicketCooldowns = new Dictionary(); - - public EventHandler(DiscordClient client) + // Checking activity type + if (!Enum.TryParse(Config.presenceType, true, out ActivityType activityType)) { - this.discordClient = client; + Logger.Log("Presence type '" + Config.presenceType + "' invalid, using 'Playing' instead."); + activityType = ActivityType.Playing; } - internal Task OnReady(DiscordClient client, ReadyEventArgs e) + 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); + + IReadOnlyDictionary roles = e.Guild.Roles; + + foreach ((ulong roleID, DiscordRole role) in roles) { - discordClient.Logger.Log(LogLevel.Information, "Client is ready to process events."); + Logger.Log(role.Name.PadRight(40, '.') + roleID); + } + return Task.CompletedTask; + } - // Checking activity type - if (!Enum.TryParse(Config.presenceType, true, out ActivityType activityType)) - { - Console.WriteLine("Presence type '" + Config.presenceType + "' invalid, using 'Playing' instead."); - activityType = ActivityType.Playing; - } + 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; + } - this.discordClient.UpdateStatusAsync(new DiscordActivity(Config.presenceText, activityType), UserStatus.Online); - return Task.CompletedTask; + internal static async Task OnMessageCreated(DiscordClient client, MessageCreateEventArgs e) + { + if (e.Author.IsBot) + { + return; } - internal Task OnGuildAvailable(DiscordClient client, GuildCreateEventArgs e) + // Check if ticket exists in the database and ticket notifications are enabled + if (!Database.TryGetOpenTicket(e.Channel.Id, out Database.Ticket ticket) || !Config.ticketUpdatedNotifications) { - discordClient.Logger.Log(LogLevel.Information, $"Guild available: {e.Guild.Name}"); - - IReadOnlyDictionary roles = e.Guild.Roles; - - foreach ((ulong roleID, DiscordRole role) in roles) - { - discordClient.Logger.Log(LogLevel.Information, role.Name.PadRight(40, '.') + roleID); - } - return Task.CompletedTask; + return; } - internal Task OnClientError(DiscordClient client, ClientErrorEventArgs e) + // 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)) { - discordClient.Logger.Log(LogLevel.Error, $"Exception occured: {e.Exception.GetType()}: {e.Exception}"); - - return Task.CompletedTask; - } - - internal async Task OnMessageCreated(DiscordClient client, MessageCreateEventArgs e) - { - if (e.Author.IsBot) + try { - 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 { - DiscordEmbed message = new DiscordEmbedBuilder - { - Color = DiscordColor.Green, - Description = "A ticket you are assigned to has been updated: " + e.Channel.Mention - }; - - DiscordMember staffMember = await e.Guild.GetMemberAsync(ticket.assignedStaffID); - await staffMember.SendMessageAsync(message); - } - catch (NotFoundException) { } - catch (UnauthorizedException) { } + Color = DiscordColor.Green, + Description = "A ticket you are assigned to has been updated: " + e.Channel.Mention + }); } + catch (NotFoundException) { } + catch (UnauthorizedException) { } } + } - internal Task OnCommandError(CommandsNextExtension commandSystem, CommandErrorEventArgs e) + internal static async Task OnCommandError(SlashCommandsExtension commandSystem, SlashCommandErrorEventArgs e) + { + switch (e.Exception) { - switch (e.Exception) - { - case CommandNotFoundException _: - return Task.CompletedTask; - case ChecksFailedException _: + case SlashExecutionChecksFailedException checksFailedException: + { + foreach (SlashCheckBaseAttribute attr in checksFailedException.FailedChecks) { - foreach (CheckBaseAttribute attr in ((ChecksFailedException)e.Exception).FailedChecks) - { - DiscordEmbed error = new DiscordEmbedBuilder - { - Color = DiscordColor.Red, - Description = this.ParseFailedCheck(attr) - }; - e.Context?.Channel?.SendMessageAsync(error); - } - return Task.CompletedTask; - } - - default: - { - discordClient.Logger.Log(LogLevel.Error, $"Exception occured: {e.Exception.GetType()}: {e.Exception}"); - DiscordEmbed error = new DiscordEmbedBuilder + await e.Context.Channel.SendMessageAsync(new DiscordEmbedBuilder { Color = DiscordColor.Red, - Description = "Internal error occured, please report this to the developer." - }; - e.Context?.Channel?.SendMessageAsync(error); - return Task.CompletedTask; + Description = ParseFailedCheck(attr) + }); } - } + 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; + } + } + } + + internal static async Task OnMemberAdded(DiscordClient client, GuildMemberAddEventArgs e) + { + if (!Database.TryGetOpenTickets(e.Member.Id, out List ownTickets)) + { + return; } - internal async Task OnReactionAdded(DiscordClient client, MessageReactionAddEventArgs e) + foreach (Database.Ticket ticket in ownTickets) { - if (e.Message.Id != Config.reactionMessage) return; - - DiscordGuild guild = e.Message.Channel.Guild; - DiscordMember member = await guild.GetMemberAsync(e.User.Id); - - if (!Config.HasPermission(member, "new") || Database.IsBlacklisted(member.Id)) return; - if (reactionTicketCooldowns.ContainsKey(member.Id)) + try { - if (reactionTicketCooldowns[member.Id] > DateTime.Now) return; // cooldown has not expired - else reactionTicketCooldowns.Remove(member.Id); // cooldown exists but has expired, delete it - } - - - DiscordChannel category = guild.GetChannel(Config.ticketCategory); - DiscordChannel ticketChannel = await guild.CreateChannelAsync("ticket", ChannelType.Text, category); - - if (ticketChannel == null) return; - - ulong staffID = 0; - if (Config.randomAssignment) - { - staffID = Database.GetRandomActiveStaff(0)?.userID ?? 0; - } - - long id = Database.NewTicket(member.Id, staffID, ticketChannel.Id); - reactionTicketCooldowns.Add(member.Id, DateTime.Now.AddSeconds(10)); // add a cooldown which expires in 10 seconds - string ticketID = id.ToString("00000"); - - await ticketChannel.ModifyAsync(model => model.Name = "ticket-" + ticketID); - await ticketChannel.AddOverwriteAsync(member, Permissions.AccessChannels, Permissions.None); - await ticketChannel.SendMessageAsync("Hello, " + member.Mention + "!\n" + Config.welcomeMessage); - - // Remove user's reaction - await e.Message.DeleteReactionAsync(e.Emoji, e.User); - - // Refreshes the channel as changes were made to it above - ticketChannel = await SupportChild.GetClient().GetChannelAsync(ticketChannel.Id); - - if (staffID != 0) - { - DiscordEmbed assignmentMessage = new DiscordEmbedBuilder + DiscordChannel channel = await client.GetChannelAsync(ticket.channelID); + if (channel?.GuildId == e.Guild.Id) { - Color = DiscordColor.Green, - Description = "Ticket was randomly assigned to <@" + staffID + ">." - }; - await ticketChannel.SendMessageAsync(assignmentMessage); - - if (Config.assignmentNotifications) - { - DiscordEmbed message = new DiscordEmbedBuilder + await channel.SendMessageAsync(new DiscordEmbedBuilder { Color = DiscordColor.Green, - Description = "You have been randomly assigned to a newly opened support ticket: " + - ticketChannel.Mention - }; - - try - { - DiscordMember staffMember = await guild.GetMemberAsync(staffID); - await staffMember.SendMessageAsync(message); - } - catch (NotFoundException) - { - } - catch (UnauthorizedException) - { - } + Description = "User '" + e.Member.Username + "#" + e.Member.Discriminator + "' has rejoined the server, and has been re-added to the ticket." + }); } } - - // Log it if the log channel exists - DiscordChannel logChannel = guild.GetChannel(Config.logChannel); - if (logChannel != null) - { - DiscordEmbed logMessage = new DiscordEmbedBuilder - { - Color = DiscordColor.Green, - Description = "Ticket " + ticketChannel.Mention + " opened by " + member.Mention + ".\n", - Footer = new DiscordEmbedBuilder.EmbedFooter {Text = "Ticket " + ticketID} - }; - await logChannel.SendMessageAsync(logMessage); - } + catch (Exception) { /* ignored */ } } + } - internal async Task OnMemberAdded(DiscordClient client, GuildMemberAddEventArgs e) + internal static async Task OnMemberRemoved(DiscordClient client, GuildMemberRemoveEventArgs e) + { + if (Database.TryGetOpenTickets(e.Member.Id, out List ownTickets)) { - if (!Database.TryGetOpenTickets(e.Member.Id, out List ownTickets)) - { - return; - } - foreach (Database.Ticket ticket in ownTickets) { try @@ -226,82 +156,120 @@ namespace SupportChild DiscordChannel channel = await client.GetChannelAsync(ticket.channelID); if (channel?.GuildId == e.Guild.Id) { - await channel.AddOverwriteAsync(e.Member, Permissions.AccessChannels, Permissions.None); - DiscordEmbed message = new DiscordEmbedBuilder() - .WithColor(DiscordColor.Green) - .WithDescription("User '" + e.Member.Username + "#" + e.Member.Discriminator + "' has rejoined the server, and has been re-added to the ticket."); - await channel.SendMessageAsync(message); + await channel.SendMessageAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "User '" + e.Member.Username + "#" + e.Member.Discriminator + "' has left the server." + }); } } - catch (Exception) { } + catch (Exception) { /* ignored */ } } } - internal async Task OnMemberRemoved(DiscordClient client, Guild​Member​Remove​Event​Args e) + if (Database.TryGetAssignedTickets(e.Member.Id, out List assignedTickets) && Config.logChannel != 0) { - if (Database.TryGetOpenTickets(e.Member.Id, out List ownTickets)) + DiscordChannel logChannel = await client.GetChannelAsync(Config.logChannel); + if (logChannel != null) { - foreach(Database.Ticket ticket in ownTickets) + foreach (Database.Ticket ticket in assignedTickets) { try { DiscordChannel channel = await client.GetChannelAsync(ticket.channelID); if (channel?.GuildId == e.Guild.Id) { - DiscordEmbed message = new DiscordEmbedBuilder() - .WithColor(DiscordColor.Red) - .WithDescription("User '" + e.Member.Username + "#" + e.Member.Discriminator + "' has left the server."); - await channel.SendMessageAsync(message); - } - } - catch (Exception) { } - } - } - - 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 { - DiscordEmbed message = new DiscordEmbedBuilder() - .WithColor(DiscordColor.Red) - .WithDescription("Assigned staff member '" + e.Member.Username + "#" + e.Member.Discriminator + "' has left the server: <#" + channel.Id + ">"); - await logChannel.SendMessageAsync(message); - } + Color = DiscordColor.Red, + Description = "Assigned staff member '" + e.Member.Username + "#" + e.Member.Discriminator + "' has left the server: <#" + channel.Id + ">" + }); } - catch (Exception) { } } + catch (Exception) { /* ignored */ } } } } - - private string ParseFailedCheck(CheckBaseAttribute attr) - { - switch (attr) - { - case CooldownAttribute _: - return "You cannot use do that so often!"; - case RequireOwnerAttribute _: - return "Only the server owner can use that command!"; - case RequirePermissionsAttribute _: - return "You don't have permission to do that!"; - case RequireRolesAttribute _: - return "You do not have a required role!"; - case RequireUserPermissionsAttribute _: - return "You don't have permission to do that!"; - case RequireNsfwAttribute _: - return "This command can only be used in an NSFW channel!"; - default: - return "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.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); + } + } + + 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/Logger.cs b/SupportChild/Logger.cs new file mode 100644 index 0000000..53d8f5e --- /dev/null +++ b/SupportChild/Logger.cs @@ -0,0 +1,68 @@ +using Microsoft.Extensions.Logging; +using System; +using System.Reflection; + +namespace SupportChild; + +public static class Logger +{ + public static void Debug(string message) + { + try + { + SupportChild.discordClient.Logger.Log(LogLevel.Debug, new EventId(420, Assembly.GetEntryAssembly()?.GetName().Name), message); + } + catch (NullReferenceException) + { + Console.WriteLine("[DEBUG] " + message); + } + } + + public static void Log(string message) + { + try + { + SupportChild.discordClient.Logger.Log(LogLevel.Information, new EventId(420, Assembly.GetEntryAssembly()?.GetName().Name), message); + } + catch (NullReferenceException) + { + Console.WriteLine("[INFO] " + message); + } + } + + public static void Warn(string message) + { + try + { + SupportChild.discordClient.Logger.Log(LogLevel.Warning, new EventId(420, Assembly.GetEntryAssembly()?.GetName().Name), message); + } + catch (NullReferenceException) + { + Console.WriteLine("[WARNING] " + message); + } + } + + public static void Error(string message) + { + try + { + SupportChild.discordClient.Logger.Log(LogLevel.Error, new EventId(420, Assembly.GetEntryAssembly()?.GetName().Name), message); + } + catch (NullReferenceException) + { + Console.WriteLine("[ERROR] " + message); + } + } + + public static void Fatal(string message) + { + try + { + SupportChild.discordClient.Logger.Log(LogLevel.Critical, new EventId(420, Assembly.GetEntryAssembly()?.GetName().Name), message); + } + catch (NullReferenceException) + { + Console.WriteLine("[CRITICAL] " + message); + } + } +} \ No newline at end of file diff --git a/SupportChild/SupportChild.cs b/SupportChild/SupportChild.cs index 3f3c1b2..4af79a3 100644 --- a/SupportChild/SupportChild.cs +++ b/SupportChild/SupportChild.cs @@ -3,161 +3,148 @@ using System.IO; using System.Reflection; using System.Threading.Tasks; using DSharpPlus; -using DSharpPlus.CommandsNext; +using DSharpPlus.Interactivity; +using DSharpPlus.Interactivity.Enums; +using DSharpPlus.Interactivity.Extensions; +using DSharpPlus.SlashCommands; using Microsoft.Extensions.Logging; using SupportChild.Commands; -namespace SupportChild +namespace SupportChild; + +internal static class SupportChild { - internal class SupportChild + // Sets up a dummy client to use for logging + public static DiscordClient discordClient = new DiscordClient(new DiscordConfiguration { Token = "DUMMY_TOKEN", TokenType = TokenType.Bot, MinimumLogLevel = LogLevel.Debug }); + private static SlashCommandsExtension commands = null; + + private static void Main() { - internal static SupportChild instance; + MainAsync().GetAwaiter().GetResult(); + } - private DiscordClient discordClient = null; - private CommandsNextExtension commands = null; - private EventHandler eventHandler; - - static void Main(string[] args) + private static async Task MainAsync() + { + Logger.Log("Starting " + Assembly.GetEntryAssembly()?.GetName().Name + " version " + GetVersion() + "..."); + try { - new SupportChild().MainAsync().GetAwaiter().GetResult(); + Reload(); + + // Block this task until the program is closed. + await Task.Delay(-1); } - - private async Task MainAsync() + catch (Exception e) { - instance = this; - - Console.WriteLine("Starting SupportChild version " + GetVersion() + "..."); - try - { - this.Reload(); - - // Block this task until the program is closed. - await Task.Delay(-1); - } - catch (Exception e) - { - Console.WriteLine("Fatal error:"); - Console.WriteLine(e); - Console.ReadLine(); - } - } - - public static DiscordClient GetClient() - { - return instance.discordClient; - } - - public static string GetVersion() - { - Version version = Assembly.GetEntryAssembly()?.GetName().Version; - return version?.Major + "." + version?.Minor + "." + version?.Build + (version?.Revision == 0 ? "" : "-" + (char)(64 + version?.Revision ?? 0)); - } - - public async void Reload() - { - if (this.discordClient != null) - { - await this.discordClient.DisconnectAsync(); - this.discordClient.Dispose(); - Console.WriteLine("Discord client disconnected."); - } - - Console.WriteLine("Loading config \"" + Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar + "config.yml\""); - Config.LoadConfig(); - - // Check if token is unset - if (Config.token == "" || Config.token == "") - { - Console.WriteLine("You need to set your bot token in the config and start the bot again."); - throw new ArgumentException("Invalid Discord bot token"); - } - - // Database connection and setup - try - { - Console.WriteLine("Connecting to database... (" + Config.hostName + ":" + Config.port + ")"); - Database.SetConnectionString(Config.hostName, Config.port, Config.database, Config.username, Config.password); - Database.SetupTables(); - } - catch (Exception e) - { - Console.WriteLine("Could not set up database tables, please confirm connection settings, status of the server and permissions of MySQL user. Error: " + e); - throw; - } - - Console.WriteLine("Setting up Discord client..."); - - // Checking log level - if (!Enum.TryParse(Config.logLevel, true, out LogLevel logLevel)) - { - Console.WriteLine("Log level '" + Config.logLevel + "' invalid, using 'Information' instead."); - logLevel = LogLevel.Information; - } - - // Setting up client configuration - DiscordConfiguration cfg = new DiscordConfiguration - { - Token = Config.token, - TokenType = TokenType.Bot, - MinimumLogLevel = logLevel, - AutoReconnect = true, - Intents = DiscordIntents.All - }; - - this.discordClient = new DiscordClient(cfg); - - this.eventHandler = new EventHandler(this.discordClient); - - Console.WriteLine("Hooking events..."); - this.discordClient.Ready += this.eventHandler.OnReady; - this.discordClient.GuildAvailable += this.eventHandler.OnGuildAvailable; - this.discordClient.ClientErrored += this.eventHandler.OnClientError; - this.discordClient.MessageCreated += this.eventHandler.OnMessageCreated; - this.discordClient.GuildMemberAdded += this.eventHandler.OnMemberAdded; - this.discordClient.GuildMemberRemoved += this.eventHandler.OnMemberRemoved; - if (Config.reactionMessage != 0) - { - this.discordClient.MessageReactionAdded += this.eventHandler.OnReactionAdded; - } - - Console.WriteLine("Registering commands..."); - commands = discordClient.UseCommandsNext(new CommandsNextConfiguration - { - StringPrefixes = new []{ Config.prefix } - }); - - this.commands.RegisterCommands(); - this.commands.RegisterCommands(); - this.commands.RegisterCommands(); - this.commands.RegisterCommands(); - this.commands.RegisterCommands(); - this.commands.RegisterCommands(); - this.commands.RegisterCommands(); - this.commands.RegisterCommands(); - this.commands.RegisterCommands(); - this.commands.RegisterCommands(); - this.commands.RegisterCommands(); - this.commands.RegisterCommands(); - this.commands.RegisterCommands(); - this.commands.RegisterCommands(); - this.commands.RegisterCommands(); - this.commands.RegisterCommands(); - this.commands.RegisterCommands(); - this.commands.RegisterCommands(); - this.commands.RegisterCommands(); - this.commands.RegisterCommands(); - this.commands.RegisterCommands(); - this.commands.RegisterCommands(); - this.commands.RegisterCommands(); - this.commands.RegisterCommands(); - this.commands.RegisterCommands(); - this.commands.RegisterCommands(); - - Console.WriteLine("Hooking command events..."); - this.commands.CommandErrored += this.eventHandler.OnCommandError; - - Console.WriteLine("Connecting to Discord..."); - await this.discordClient.ConnectAsync(); + Logger.Fatal("Fatal error:\n" + e); + Console.ReadLine(); } } + + public static string GetVersion() + { + Version version = Assembly.GetEntryAssembly()?.GetName().Version; + return version?.Major + "." + version?.Minor + "." + version?.Build + (version?.Revision == 0 ? "" : "-" + (char)(64 + version?.Revision ?? 0)); + } + + public static async void Reload() + { + if (discordClient != null) + { + await discordClient.DisconnectAsync(); + discordClient.Dispose(); + Logger.Log("Discord client disconnected."); + } + + Logger.Log("Loading config \"" + Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar + "config.yml\""); + Config.LoadConfig(); + + // Check if token is unset + if (Config.token is "" or "") + { + Logger.Fatal("You need to set your bot token in the config and start the bot again."); + throw new ArgumentException("Invalid Discord bot token"); + } + + // Database connection and setup + try + { + Logger.Log("Connecting to database... (" + Config.hostName + ":" + Config.port + ")"); + Database.SetConnectionString(Config.hostName, Config.port, Config.database, Config.username, Config.password); + Database.SetupTables(); + } + catch (Exception e) + { + Logger.Fatal("Could not set up database tables, please confirm connection settings, status of the server and permissions of MySQL user. Error: " + e); + throw; + } + + Logger.Log("Setting up Discord client..."); + + // Setting up client configuration + DiscordConfiguration cfg = new DiscordConfiguration + { + Token = Config.token, + TokenType = TokenType.Bot, + MinimumLogLevel = Config.logLevel, + AutoReconnect = true, + Intents = DiscordIntents.All + }; + + discordClient = new DiscordClient(cfg); + + Logger.Log("Hooking events..."); + discordClient.Ready += EventHandler.OnReady; + discordClient.GuildAvailable += EventHandler.OnGuildAvailable; + discordClient.ClientErrored += EventHandler.OnClientError; + discordClient.MessageCreated += EventHandler.OnMessageCreated; + discordClient.GuildMemberAdded += EventHandler.OnMemberAdded; + discordClient.GuildMemberRemoved += EventHandler.OnMemberRemoved; + discordClient.ComponentInteractionCreated += EventHandler.OnComponentInteractionCreated; + + discordClient.UseInteractivity(new InteractivityConfiguration + { + AckPaginationButtons = true, + PaginationBehaviour = PaginationBehaviour.Ignore, + PaginationDeletion = PaginationDeletion.DeleteMessage, + Timeout = TimeSpan.FromMinutes(15) + }); + + Logger.Log("Registering commands..."); + commands = discordClient.UseSlashCommands(); + + commands.RegisterCommands(); + commands.RegisterCommands(); + commands.RegisterCommands(); + commands.RegisterCommands(); + commands.RegisterCommands(); + commands.RegisterCommands(); + commands.RegisterCommands(); + commands.RegisterCommands(); + commands.RegisterCommands(); + commands.RegisterCommands(); + commands.RegisterCommands(); + commands.RegisterCommands(); + commands.RegisterCommands(); + commands.RegisterCommands(); + commands.RegisterCommands(); + commands.RegisterCommands(); + commands.RegisterCommands(); + commands.RegisterCommands(); + commands.RegisterCommands(); + commands.RegisterCommands(); + commands.RegisterCommands(); + commands.RegisterCommands(); + commands.RegisterCommands(); + commands.RegisterCommands(); + commands.RegisterCommands(); + commands.RegisterCommands(); + commands.RegisterCommands(); + commands.RegisterCommands(); + + Logger.Log("Hooking command events..."); + commands.SlashCommandErrored += EventHandler.OnCommandError; + + Logger.Log("Connecting to Discord..."); + await discordClient.ConnectAsync(); + } } \ No newline at end of file diff --git a/SupportChild/SupportChild.csproj b/SupportChild/SupportChild.csproj index 5b31187..ea42f5f 100644 --- a/SupportChild/SupportChild.csproj +++ b/SupportChild/SupportChild.csproj @@ -5,7 +5,7 @@ ellie_icon.ico net6.0 win-x64;linux-x64 - 1.2.0 + SupportChild.SupportChild EmotionChild @@ -13,58 +13,58 @@ https://github.com/EmotionChild/SupportChild Git LICENSE - https://cdn.emotionchild.com/Ellie.png - A Discord support bot build for the Ellie's Home Discord server - 2.6.1.1 - 2.6.1.1 + 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.2.0 + 3.0.0.1 + 1.3.0 + 3.0.0.1 + 3.0.0.1 + + + + full - + + - + - + + - - True - True - Resources.resx - + + ResXFileCodeGenerator + Resources.Designer.cs + + + + + - - ResXFileCodeGenerator - Resources.Designer.cs - + + lib\DiscordChatExporter.Core.dll + - - True - - + + True + True + Resources.resx + - - - - - - - lib\DiscordChatExporter.Core.dll - - - - + \ No newline at end of file diff --git a/SupportChild/Transcriber.cs b/SupportChild/Transcriber.cs index 9b10e62..0fd0d5c 100644 --- a/SupportChild/Transcriber.cs +++ b/SupportChild/Transcriber.cs @@ -3,60 +3,51 @@ using System.Threading.Tasks; using DiscordChatExporter.Core.Discord; using DiscordChatExporter.Core.Discord.Data; -using DiscordChatExporter.Core.Exceptions; using DiscordChatExporter.Core.Exporting; using DiscordChatExporter.Core.Exporting.Filtering; using DiscordChatExporter.Core.Exporting.Partitioning; -using DiscordChatExporter.Core.Utils.Extensions; -namespace SupportChild +namespace SupportChild; + +internal static class Transcriber { - internal static class Transcriber - { - internal static async Task ExecuteAsync(ulong channelID, uint ticketID) - { - DiscordClient discordClient = new DiscordClient(new AuthToken(AuthTokenKind.Bot, Config.token)); - ChannelExporter Exporter = new ChannelExporter(discordClient); + internal static async Task ExecuteAsync(ulong channelID, uint ticketID) + { + DiscordClient discordClient = new DiscordClient(Config.token); + ChannelExporter exporter = new ChannelExporter(discordClient); - if (!Directory.Exists("./transcripts")) - { - Directory.CreateDirectory("./transcripts"); - } + if (!Directory.Exists("./transcripts")) + { + Directory.CreateDirectory("./transcripts"); + } - string dateFormat = "yyyy-MMM-dd HH:mm"; + Channel channel = await discordClient.GetChannelAsync(new Snowflake(channelID)); + Guild guild = await discordClient.GetGuildAsync(channel.GuildId); - // Configure settings - if (Config.timestampFormat != "") - dateFormat = Config.timestampFormat; + ExportRequest request = new ExportRequest( + Guild: guild, + Channel: channel, + OutputPath: GetPath(ticketID), + Format: ExportFormat.HtmlDark, + After: null, + Before: null, + PartitionLimit: PartitionLimit.Null, + MessageFilter: MessageFilter.Null, + ShouldDownloadMedia: false, + ShouldReuseMedia: false, + DateFormat: "yyyy-MMM-dd HH:mm" + ); - Channel channel = await discordClient.GetChannelAsync(new Snowflake(channelID)); - Guild guild = await discordClient.GetGuildAsync(channel.GuildId); + await exporter.ExportChannelAsync(request); + } - ExportRequest request = new ExportRequest( - guild: guild, - channel: channel, - outputPath: GetPath(ticketID), - format: ExportFormat.HtmlDark, - after: null, - before: null, - partitionLimit: PartitionLimit.Null, - messageFilter: MessageFilter.Null, - shouldDownloadMedia: false, - shouldReuseMedia: false, - dateFormat: dateFormat - ); + internal static string GetPath(uint ticketNumber) + { + return "./transcripts/" + GetFilename(ticketNumber); + } - await Exporter.ExportChannelAsync(request); - } - - internal static string GetPath(uint ticketNumber) - { - return "./transcripts/" + GetFilename(ticketNumber); - } - - internal static string GetFilename(uint ticketNumber) - { - return "ticket-" + ticketNumber.ToString("00000") + ".html"; - } - } + internal static string GetFilename(uint ticketNumber) + { + return "ticket-" + ticketNumber.ToString("00000") + ".html"; + } } \ No newline at end of file diff --git a/SupportChild/Utilities.cs b/SupportChild/Utilities.cs index 06099d1..b554cfc 100644 --- a/SupportChild/Utilities.cs +++ b/SupportChild/Utilities.cs @@ -1,71 +1,65 @@ using System; using System.Collections.Generic; -using System.Security.Cryptography; +using System.Threading.Tasks; using DSharpPlus.Entities; -namespace SupportChild +namespace SupportChild; + +public static class Utilities { - public static class Utilities - { - public static List RandomizeList(List list) - { - RNGCryptoServiceProvider provider = new RNGCryptoServiceProvider(); - int n = list.Count; - while (n > 1) - { - byte[] box = new byte[1]; - do provider.GetBytes(box); - while (!(box[0] < n * (Byte.MaxValue / n))); - int k = (box[0] % n); - n--; - T value = list[k]; - list[k] = list[n]; - list[n] = value; - } + private static readonly Random rng = new Random(); - return list; - } + public static void Shuffle(this IList list) + { + int n = list.Count; + while (n > 1) + { + n--; + int k = rng.Next(n + 1); + (list[k], list[n]) = (list[n], list[k]); + } + } - public static string[] ParseIDs(string args) - { - if (string.IsNullOrEmpty(args)) - { - return new string[0]; - } - return args.Trim().Replace("<@!", "").Replace("<@", "").Replace(">", "").Split(); - } + public static LinkedList ParseListIntoMessages(List listItems) + { + LinkedList messages = new LinkedList(); - public static LinkedList ParseListIntoMessages(List listItems) - { - LinkedList messages = new LinkedList(); + foreach (string listItem in listItems) + { + if (messages.Last?.Value?.Length + listItem?.Length < 2048) + { + messages.Last.Value += listItem; + } + else + { + messages.AddLast(listItem); + } + } - foreach (string listItem in listItems) - { - if (messages.Last?.Value?.Length + listItem?.Length < 2048) - { - messages.Last.Value += listItem; - } - else - { - messages.AddLast(listItem); - } - } + return messages; + } - return messages; - } + public static async Task> GetVerifiedChannels() + { + List verifiedCategories = new List(); + foreach (Database.Category category in Database.GetAllCategories()) + { + DiscordChannel channel = null; + try + { + channel = await SupportChild.discordClient.GetChannelAsync(category.id); + } + catch (Exception) { /*ignored*/ } - public static DiscordRole GetRoleByName(DiscordGuild guild, string Name) - { - Name = Name.Trim().ToLower(); - foreach (DiscordRole role in guild.Roles.Values) - { - if (role.Name.ToLower().StartsWith(Name)) - { - return role; - } - } - - return null; - } - } + if (channel != null) + { + verifiedCategories.Add(category); + } + else + { + Logger.Warn("Category '" + category.name + "' (" + category.id + ") no longer exists! Ignoring..."); + } + } + return verifiedCategories; + } } \ No newline at end of file diff --git a/SupportChild/default_config.yml b/SupportChild/default_config.yml index 8dcb6e8..b24019a 100644 --- a/SupportChild/default_config.yml +++ b/SupportChild/default_config.yml @@ -1,84 +1,48 @@ bot: - # Bot token. - token: "" - # Command prefix. - prefix: "-" - # Channel where ticket logs are posted (recommended) - log-channel: 000000000000000000 - # Category where the ticket will be created, it will have the same permissions of that ticket plus read permissions for the user opening the ticket (recommended) - ticket-category: 000000000000000000 - # A message which will open new tickets when users react to it (optional) - reaction-message: 000000000000000000 - # Message posted when a ticket is opened. - welcome-message: "Please describe your issue below, and include all information needed for us to help you." - # Decides what messages are shown in console - # Possible values are: Critical, Error, Warning, Information, Debug. - console-log-level: "Information" - # Format for timestamps in transcripts and google sheets if used - timestamp-format: "yyyy-MM-dd HH:mm" - # Whether or not staff members should be randomly assigned tickets when they are made. Individual staff members can opt out using the toggleactive command. - random-assignment: true - # If set to true the rasssign command will include staff members set as inactive if a specific role is specified in the command. - # This can be useful if you have admins set as inactive to not automatically recieve tickets and then have moderators elevate tickets when needed. - random-assign-role-override: true - # Sets the type of activity for the bot to display in its presence status - # Possible values are: Playing, Streaming, ListeningTo, Watching, Competing - presence-type: "ListeningTo" - # Sets the activity text shown in the bot's status - presence-text: "-new" + # Bot token. + token: "" + # Channel where ticket logs are posted (recommended) + log-channel: 000000000000000000 + # Message posted when a ticket is opened. + welcome-message: "Please describe your issue below, and include all information needed for us to take action." + # Decides what messages are shown in console + # Possible values are: Critical, Error, Warning, Information, Debug. + console-log-level: "Information" + # One of the following: LongDate, LongDateTime, LongTime, RelativeTime, ShortDate, ShortDateTime, ShortTime + # More info: https://dsharpplus.github.io/api/DSharpPlus.TimestampFormat.html + timestamp-format: "RelativeTime" + # Whether or not staff members should be randomly assigned tickets when they are made. Individual staff members can opt out using the toggleactive command. + random-assignment: true + # If set to true the rasssign command will include staff members set as inactive if a specific role is specified in the command. + # This can be useful if you have admins set as inactive to not automatically receive tickets and then have moderators elevate tickets when needed. + random-assign-role-override: true + # Sets the type of activity for the bot to display in its presence status + # Possible values are: Playing, Streaming, ListeningTo, Watching, Competing + presence-type: "ListeningTo" + # Sets the activity text shown in the bot's status + presence-text: "/new" + # Set to true if you want the /new command to show a selection box instead of a series of buttons + new-command-uses-selector: false + # Number of tickets a single user can have open at a time, staff members are excluded from this + ticket-limit: 5 notifications: - # Notifies the assigned staff member when a new message is posted in a ticket if the ticket has been silent for a configurable amount of time - # Other staff members and bots do not trigger this. - ticket-updated: true - # The above notification will only be sent if the ticket has been silent for more than this amount of days. Default is 0.5 days. - ticket-updated-delay: 0.5 - # Notifies staff when they are assigned to tickets - assignment: true - # Notifies the user opening the ticket that their ticket was closed and includes the transcript - closing: true + # Notifies the assigned staff member when a new message is posted in a ticket if the ticket has been silent for a configurable amount of time + # Other staff members and bots do not trigger this. + ticket-updated: true + # The above notification will only be sent if the ticket has been silent for more than this amount of days. Default is 0.5 days. + ticket-updated-delay: 0.5 + # Notifies staff when they are assigned to tickets + assignment: true + # Notifies the user opening the ticket that their ticket was closed and includes the transcript + closing: true database: - # Address and port of the mysql server - address: "127.0.0.1" - port: 3306 - # Name of the database to use - name: "supportchild" - # Username and password for authentication - user: "" - password: "" - -# Set up which roles are allowed to use different commands. -# Example: -# new: [ 000000000000000000, 111111111111111111 ] -# They are grouped into suggested command groups below for first time setup. -permissions: - # Public commands - close: [] - list: [] - new: [] - say: [] - status: [] - summary: [] - transcript: [] - # Moderator commands - add: [] - addmessage: [] - assign: [] - blacklist: [] - listassigned: [] - listoldest: [] - listunassigned: [] - move: [] - rassign: [] - removemessage: [] - setsummary: [] - toggleactive: [] - unassign: [] - unblacklist: [] - # Admin commands - addstaff: [] - reload: [] - removestaff: [] - setticket: [] - unsetticket: [] \ No newline at end of file + # Address and port of the mysql server + address: "127.0.0.1" + port: 3306 + # Name of the database to use + name: "supportchild" + # Username and password for authentication + user: "" + password: "" \ No newline at end of file