Updated general files

This commit is contained in:
EmotionChild 2022-08-21 19:33:27 +12:00
parent d4651ee055
commit 0e5a93a6a6
No known key found for this signature in database
GPG key ID: C0FA13E96E2C16CA
9 changed files with 1405 additions and 1354 deletions

View file

@ -1,29 +1,27 @@
using System; using System;
using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq;
using System.Text; using System.Text;
using DSharpPlus.Entities; using DSharpPlus;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq;
using SupportChild.Properties; using SupportChild.Properties;
using YamlDotNet.Serialization; using YamlDotNet.Serialization;
namespace SupportChild namespace SupportChild;
internal static class Config
{ {
internal static class Config
{
internal static string token = ""; internal static string token = "";
internal static string prefix = "";
internal static ulong logChannel; internal static ulong logChannel;
internal static ulong ticketCategory;
internal static ulong reactionMessage;
internal static string welcomeMessage = ""; internal static string welcomeMessage = "";
internal static string logLevel = "Information"; internal static LogLevel logLevel = LogLevel.Information;
internal static string timestampFormat = "yyyy-MMM-dd HH:mm"; internal static TimestampFormat timestampFormat = TimestampFormat.RelativeTime;
internal static bool randomAssignment = false; internal static bool randomAssignment = false;
internal static bool randomAssignRoleOverride = false; internal static bool randomAssignRoleOverride = false;
internal static string presenceType = "Playing"; internal static string presenceType = "Playing";
internal static string presenceText = ""; internal static string presenceText = "";
internal static bool newCommandUsesSelector = false;
internal static int ticketLimit = 5;
internal static bool ticketUpdatedNotifications = false; internal static bool ticketUpdatedNotifications = false;
internal static double ticketUpdatedNotificationDelay = 0.0; internal static double ticketUpdatedNotificationDelay = 0.0;
@ -32,43 +30,10 @@ namespace SupportChild
internal static string hostName = "127.0.0.1"; internal static string hostName = "127.0.0.1";
internal static int port = 3306; internal static int port = 3306;
internal static string database = "supportbot"; internal static string database = "supportchild";
internal static string username = "supportbot"; internal static string username = "supportchild";
internal static string password = ""; internal static string password = "";
private static readonly Dictionary<string, ulong[]> permissions = new Dictionary<string, ulong[]>
{
// 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() public static void LoadConfig()
{ {
// Writes default config to file if it does not already exist // Writes default config to file if it does not already exist
@ -82,25 +47,38 @@ namespace SupportChild
// Converts the FileStream into a YAML object // Converts the FileStream into a YAML object
IDeserializer deserializer = new DeserializerBuilder().Build(); IDeserializer deserializer = new DeserializerBuilder().Build();
object yamlObject = deserializer.Deserialize(new StreamReader(stream)); 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 // 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(); ISerializer serializer = new SerializerBuilder().JsonCompatible().Build();
JObject json = JObject.Parse(serializer.Serialize(yamlObject)); JObject json = JObject.Parse(serializer.Serialize(yamlObject));
// Sets up the bot // Sets up the bot
token = json.SelectToken("bot.token").Value<string>() ?? ""; token = json.SelectToken("bot.token")?.Value<string>() ?? "";
prefix = json.SelectToken("bot.prefix").Value<string>() ?? ""; logChannel = json.SelectToken("bot.log-channel")?.Value<ulong>() ?? 0;
logChannel = json.SelectToken("bot.log-channel").Value<ulong>(); welcomeMessage = json.SelectToken("bot.welcome-message")?.Value<string>() ?? "";
ticketCategory = json.SelectToken("bot.ticket-category")?.Value<ulong>() ?? 0; string stringLogLevel = json.SelectToken("bot.console-log-level")?.Value<string>() ?? "";
reactionMessage = json.SelectToken("bot.reaction-message")?.Value<ulong>() ?? 0;
welcomeMessage = json.SelectToken("bot.welcome-message").Value<string>() ?? ""; if (!Enum.TryParse(stringLogLevel, true, out logLevel))
logLevel = json.SelectToken("bot.console-log-level").Value<string>() ?? ""; {
timestampFormat = json.SelectToken("bot.timestamp-format").Value<string>() ?? "yyyy-MM-dd HH:mm"; logLevel = LogLevel.Information;
Logger.Warn("Log level '" + stringLogLevel + "' invalid, using 'Information' instead.");
}
string stringTimestampFormat = json.SelectToken("bot.timestamp-format")?.Value<string>() ?? "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<bool>() ?? false; randomAssignment = json.SelectToken("bot.random-assignment")?.Value<bool>() ?? false;
randomAssignRoleOverride = json.SelectToken("bot.random-assign-role-override")?.Value<bool>() ?? false; randomAssignRoleOverride = json.SelectToken("bot.random-assign-role-override")?.Value<bool>() ?? false;
presenceType = json.SelectToken("bot.presence-type")?.Value<string>() ?? "Playing"; presenceType = json.SelectToken("bot.presence-type")?.Value<string>() ?? "Playing";
presenceText = json.SelectToken("bot.presence-text")?.Value<string>() ?? ""; presenceText = json.SelectToken("bot.presence-text")?.Value<string>() ?? "";
newCommandUsesSelector = json.SelectToken("bot.new-command-uses-selector")?.Value<bool>() ?? false;
ticketLimit = json.SelectToken("bot.ticket-limit")?.Value<int>() ?? 5;
ticketUpdatedNotifications = json.SelectToken("notifications.ticket-updated")?.Value<bool>() ?? false; ticketUpdatedNotifications = json.SelectToken("notifications.ticket-updated")?.Value<bool>() ?? false;
ticketUpdatedNotificationDelay = json.SelectToken("notifications.ticket-updated-delay")?.Value<double>() ?? 0.0; ticketUpdatedNotificationDelay = json.SelectToken("notifications.ticket-updated-delay")?.Value<double>() ?? 0.0;
@ -113,31 +91,5 @@ namespace SupportChild
database = json.SelectToken("database.name")?.Value<string>() ?? "supportchild"; database = json.SelectToken("database.name")?.Value<string>() ?? "supportchild";
username = json.SelectToken("database.user")?.Value<string>() ?? "supportchild"; username = json.SelectToken("database.user")?.Value<string>() ?? "supportchild";
password = json.SelectToken("database.password")?.Value<string>() ?? ""; password = json.SelectToken("database.password")?.Value<string>() ?? "";
timestampFormat = timestampFormat.Trim();
foreach (KeyValuePair<string, ulong[]> node in permissions.ToList())
{
try
{
permissions[node.Key] = json.SelectToken("permissions." + node.Key).Value<JArray>().Values<ulong>().ToArray();
}
catch (ArgumentNullException)
{
Console.WriteLine("Permission node '" + node.Key + "' was not found in the config, using default value: []");
}
}
}
/// <summary>
/// Checks whether a user has a specific permission.
/// </summary>
/// <param name="member">The Discord user to check.</param>
/// <param name="permission">The permission name to check.</param>
/// <returns></returns>
public static bool HasPermission(DiscordMember member, string permission)
{
return member.Roles.Any(role => permissions[permission].Contains(role.Id)) || permissions[permission].Contains(member.Guild.Id);
}
} }
} }

View file

@ -1,15 +1,16 @@
using System; using System;
using System.Linq; using System.Linq;
using System.Collections.Generic; using System.Collections.Generic;
using DSharpPlus;
using MySql.Data.MySqlClient; using MySql.Data.MySqlClient;
namespace SupportChild namespace SupportChild;
public static class Database
{ {
public static class Database
{
private static string connectionString = ""; private static string connectionString = "";
private static Random random = new Random(); private static readonly Random random = new Random();
public static void SetConnectionString(string host, int port, string database, string username, string password) public static void SetConnectionString(string host, int port, string database, string username, string password)
{ {
@ -19,51 +20,50 @@ namespace SupportChild
";userid=" + username + ";userid=" + username +
";password=" + password; ";password=" + password;
} }
public static MySqlConnection GetConnection() public static MySqlConnection GetConnection()
{ {
return new MySqlConnection(connectionString); return new MySqlConnection(connectionString);
} }
public static long GetNumberOfTickets() public static long GetNumberOfTickets()
{ {
try try
{ {
using (MySqlConnection c = GetConnection()) using MySqlConnection c = GetConnection();
{ using MySqlCommand countTickets = new MySqlCommand("SELECT COUNT(*) FROM tickets", c);
MySqlCommand countTickets = new MySqlCommand("SELECT COUNT(*) FROM tickets", c);
c.Open(); c.Open();
return (long)countTickets.ExecuteScalar(); return (long)countTickets.ExecuteScalar();
} }
}
catch (Exception e) catch (Exception e)
{ {
Console.WriteLine("Error occured when attempting to count number of open tickets: " + e); Logger.Error("Error occured when attempting to count number of open tickets: " + e);
} }
return -1; return -1;
} }
public static long GetNumberOfClosedTickets() public static long GetNumberOfClosedTickets()
{ {
try try
{ {
using (MySqlConnection c = GetConnection()) using MySqlConnection c = GetConnection();
{ using MySqlCommand countTickets = new MySqlCommand("SELECT COUNT(*) FROM ticket_history", c);
MySqlCommand countTickets = new MySqlCommand("SELECT COUNT(*) FROM ticket_history", c);
c.Open(); c.Open();
return (long)countTickets.ExecuteScalar(); return (long)countTickets.ExecuteScalar();
} }
}
catch (Exception e) catch (Exception e)
{ {
Console.WriteLine("Error occured when attempting to count number of open tickets: " + e); Logger.Error("Error occured when attempting to count number of open tickets: " + e);
} }
return -1; return -1;
} }
public static void SetupTables() public static void SetupTables()
{ {
using (MySqlConnection c = GetConnection()) using MySqlConnection c = GetConnection();
{ using MySqlCommand createTickets = new MySqlCommand(
MySqlCommand createTickets = new MySqlCommand(
"CREATE TABLE IF NOT EXISTS tickets(" + "CREATE TABLE IF NOT EXISTS tickets(" +
"id INT UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT," + "id INT UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT," +
"created_time DATETIME NOT NULL," + "created_time DATETIME NOT NULL," +
@ -73,7 +73,7 @@ namespace SupportChild
"channel_id BIGINT UNSIGNED NOT NULL UNIQUE," + "channel_id BIGINT UNSIGNED NOT NULL UNIQUE," +
"INDEX(created_time, assigned_staff_id, channel_id))", "INDEX(created_time, assigned_staff_id, channel_id))",
c); c);
MySqlCommand createTicketHistory = new MySqlCommand( using MySqlCommand createTicketHistory = new MySqlCommand(
"CREATE TABLE IF NOT EXISTS ticket_history(" + "CREATE TABLE IF NOT EXISTS ticket_history(" +
"id INT UNSIGNED NOT NULL PRIMARY KEY," + "id INT UNSIGNED NOT NULL PRIMARY KEY," +
"created_time DATETIME NOT NULL," + "created_time DATETIME NOT NULL," +
@ -84,39 +84,44 @@ namespace SupportChild
"channel_id BIGINT UNSIGNED NOT NULL UNIQUE," + "channel_id BIGINT UNSIGNED NOT NULL UNIQUE," +
"INDEX(created_time, closed_time, channel_id))", "INDEX(created_time, closed_time, channel_id))",
c); c);
MySqlCommand createBlacklisted = new MySqlCommand( using MySqlCommand createBlacklisted = new MySqlCommand(
"CREATE TABLE IF NOT EXISTS blacklisted_users(" + "CREATE TABLE IF NOT EXISTS blacklisted_users(" +
"user_id BIGINT UNSIGNED NOT NULL PRIMARY KEY," + "user_id BIGINT UNSIGNED NOT NULL PRIMARY KEY," +
"time DATETIME NOT NULL," + "time DATETIME NOT NULL," +
"moderator_id BIGINT UNSIGNED NOT NULL," + "moderator_id BIGINT UNSIGNED NOT NULL," +
"INDEX(user_id, time))", "INDEX(user_id, time))",
c); c);
MySqlCommand createStaffList = new MySqlCommand( using MySqlCommand createStaffList = new MySqlCommand(
"CREATE TABLE IF NOT EXISTS staff(" + "CREATE TABLE IF NOT EXISTS staff(" +
"user_id BIGINT UNSIGNED NOT NULL PRIMARY KEY," + "user_id BIGINT UNSIGNED NOT NULL PRIMARY KEY," +
"name VARCHAR(256) NOT NULL," + "name VARCHAR(256) NOT NULL," +
"active BOOLEAN NOT NULL DEFAULT true)", "active BOOLEAN NOT NULL DEFAULT true)",
c); c);
MySqlCommand createMessages = new MySqlCommand( using MySqlCommand createMessages = new MySqlCommand(
"CREATE TABLE IF NOT EXISTS messages(" + "CREATE TABLE IF NOT EXISTS messages(" +
"identifier VARCHAR(256) NOT NULL PRIMARY KEY," + "identifier VARCHAR(256) NOT NULL PRIMARY KEY," +
"user_id BIGINT UNSIGNED NOT NULL," + "user_id BIGINT UNSIGNED NOT NULL," +
"message VARCHAR(5000) NOT NULL)", "message VARCHAR(5000) NOT NULL)",
c); 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(); c.Open();
createTickets.ExecuteNonQuery(); createTickets.ExecuteNonQuery();
createBlacklisted.ExecuteNonQuery(); createBlacklisted.ExecuteNonQuery();
createTicketHistory.ExecuteNonQuery(); createTicketHistory.ExecuteNonQuery();
createStaffList.ExecuteNonQuery(); createStaffList.ExecuteNonQuery();
createMessages.ExecuteNonQuery(); createMessages.ExecuteNonQuery();
createCategories.ExecuteNonQuery();
} }
}
public static bool IsOpenTicket(ulong channelID) public static bool IsOpenTicket(ulong channelID)
{ {
using (MySqlConnection c = GetConnection()) using MySqlConnection c = GetConnection();
{
c.Open(); c.Open();
MySqlCommand selection = new MySqlCommand(@"SELECT * FROM tickets WHERE channel_id=@channel_id", c); using MySqlCommand selection = new MySqlCommand(@"SELECT * FROM tickets WHERE channel_id=@channel_id", c);
selection.Parameters.AddWithValue("@channel_id", channelID); selection.Parameters.AddWithValue("@channel_id", channelID);
selection.Prepare(); selection.Prepare();
MySqlDataReader results = selection.ExecuteReader(); MySqlDataReader results = selection.ExecuteReader();
@ -127,15 +132,14 @@ namespace SupportChild
return false; return false;
} }
results.Close(); results.Close();
}
return true; return true;
} }
public static bool TryGetOpenTicket(ulong channelID, out Ticket ticket) public static bool TryGetOpenTicket(ulong channelID, out Ticket ticket)
{ {
using (MySqlConnection c = GetConnection()) using MySqlConnection c = GetConnection();
{
c.Open(); c.Open();
MySqlCommand selection = new MySqlCommand(@"SELECT * FROM tickets WHERE channel_id=@channel_id", c); using MySqlCommand selection = new MySqlCommand(@"SELECT * FROM tickets WHERE channel_id=@channel_id", c);
selection.Parameters.AddWithValue("@channel_id", channelID); selection.Parameters.AddWithValue("@channel_id", channelID);
selection.Prepare(); selection.Prepare();
MySqlDataReader results = selection.ExecuteReader(); MySqlDataReader results = selection.ExecuteReader();
@ -151,13 +155,12 @@ namespace SupportChild
results.Close(); results.Close();
return true; return true;
} }
}
public static bool TryGetOpenTicketByID(uint id, out Ticket ticket) public static bool TryGetOpenTicketByID(uint id, out Ticket ticket)
{ {
using (MySqlConnection c = GetConnection()) using MySqlConnection c = GetConnection();
{
c.Open(); c.Open();
MySqlCommand selection = new MySqlCommand(@"SELECT * FROM tickets WHERE id=@id", c); using MySqlCommand selection = new MySqlCommand(@"SELECT * FROM tickets WHERE id=@id", c);
selection.Parameters.AddWithValue("@id", id); selection.Parameters.AddWithValue("@id", id);
selection.Prepare(); selection.Prepare();
MySqlDataReader results = selection.ExecuteReader(); MySqlDataReader results = selection.ExecuteReader();
@ -166,19 +169,20 @@ namespace SupportChild
if (results.Read()) if (results.Read())
{ {
ticket = new Ticket(results); ticket = new Ticket(results);
results.Close();
return true; return true;
} }
results.Close();
ticket = null; ticket = null;
return false; return false;
} }
}
public static bool TryGetClosedTicket(uint id, out Ticket ticket) public static bool TryGetClosedTicket(uint id, out Ticket ticket)
{ {
using (MySqlConnection c = GetConnection()) using MySqlConnection c = GetConnection();
{
c.Open(); c.Open();
MySqlCommand selection = new MySqlCommand(@"SELECT * FROM ticket_history WHERE id=@id", c); using MySqlCommand selection = new MySqlCommand(@"SELECT * FROM ticket_history WHERE id=@id", c);
selection.Parameters.AddWithValue("@id", id); selection.Parameters.AddWithValue("@id", id);
selection.Prepare(); selection.Prepare();
MySqlDataReader results = selection.ExecuteReader(); MySqlDataReader results = selection.ExecuteReader();
@ -187,20 +191,21 @@ namespace SupportChild
if (results.Read()) if (results.Read())
{ {
ticket = new Ticket(results); ticket = new Ticket(results);
results.Close();
return true; return true;
} }
ticket = null; ticket = null;
results.Close();
return false; return false;
} }
}
public static bool TryGetOpenTickets(ulong userID, out List<Ticket> tickets) public static bool TryGetOpenTickets(ulong userID, out List<Ticket> tickets)
{ {
tickets = null; tickets = null;
using (MySqlConnection c = GetConnection()) using MySqlConnection c = GetConnection();
{
c.Open(); c.Open();
MySqlCommand selection = new MySqlCommand(@"SELECT * FROM tickets WHERE creator_id=@creator_id", c); using MySqlCommand selection = new MySqlCommand(@"SELECT * FROM tickets WHERE creator_id=@creator_id", c);
selection.Parameters.AddWithValue("@creator_id", userID); selection.Parameters.AddWithValue("@creator_id", userID);
selection.Prepare(); selection.Prepare();
MySqlDataReader results = selection.ExecuteReader(); MySqlDataReader results = selection.ExecuteReader();
@ -218,16 +223,13 @@ namespace SupportChild
results.Close(); results.Close();
return true; return true;
} }
}
public static bool TryGetOldestTickets(ulong userID, out List<Ticket> tickets, int listLimit) public static bool TryGetOpenTickets(out List<Ticket> tickets)
{ {
tickets = null; tickets = null;
using (MySqlConnection c = GetConnection()) using MySqlConnection c = GetConnection();
{
c.Open(); c.Open();
MySqlCommand selection = new MySqlCommand(@"SELECT * FROM tickets ORDER BY created_time ASC LIMIT @limit", c); using MySqlCommand selection = new MySqlCommand(@"SELECT * FROM tickets ORDER BY channel_id ASC", c);
selection.Parameters.AddWithValue("@creator_id", userID);
selection.Parameters.AddWithValue("@limit", listLimit);
selection.Prepare(); selection.Prepare();
MySqlDataReader results = selection.ExecuteReader(); MySqlDataReader results = selection.ExecuteReader();
@ -244,14 +246,13 @@ namespace SupportChild
results.Close(); results.Close();
return true; return true;
} }
}
public static bool TryGetClosedTickets(ulong userID, out List<Ticket> tickets) public static bool TryGetClosedTickets(ulong userID, out List<Ticket> tickets)
{ {
tickets = null; tickets = null;
using (MySqlConnection c = GetConnection()) using MySqlConnection c = GetConnection();
{
c.Open(); c.Open();
MySqlCommand selection = new MySqlCommand(@"SELECT * FROM ticket_history WHERE creator_id=@creator_id", c); using MySqlCommand selection = new MySqlCommand(@"SELECT * FROM ticket_history WHERE creator_id=@creator_id", c);
selection.Parameters.AddWithValue("@creator_id", userID); selection.Parameters.AddWithValue("@creator_id", userID);
selection.Prepare(); selection.Prepare();
MySqlDataReader results = selection.ExecuteReader(); MySqlDataReader results = selection.ExecuteReader();
@ -269,14 +270,13 @@ namespace SupportChild
results.Close(); results.Close();
return true; return true;
} }
}
public static bool TryGetAssignedTickets(ulong staffID, out List<Ticket> tickets) public static bool TryGetAssignedTickets(ulong staffID, out List<Ticket> tickets)
{ {
tickets = null; tickets = null;
using (MySqlConnection c = GetConnection()) using MySqlConnection c = GetConnection();
{
c.Open(); c.Open();
MySqlCommand selection = new MySqlCommand(@"SELECT * FROM tickets WHERE assigned_staff_id=@assigned_staff_id", c); using MySqlCommand selection = new MySqlCommand(@"SELECT * FROM tickets WHERE assigned_staff_id=@assigned_staff_id", c);
selection.Parameters.AddWithValue("@assigned_staff_id", staffID); selection.Parameters.AddWithValue("@assigned_staff_id", staffID);
selection.Prepare(); selection.Prepare();
MySqlDataReader results = selection.ExecuteReader(); MySqlDataReader results = selection.ExecuteReader();
@ -294,15 +294,12 @@ namespace SupportChild
results.Close(); results.Close();
return true; return true;
} }
}
public static long NewTicket(ulong memberID, ulong staffID, ulong ticketID) public static long NewTicket(ulong memberID, ulong staffID, ulong ticketID)
{ {
using (MySqlConnection c = GetConnection()) using MySqlConnection c = GetConnection();
{
c.Open(); c.Open();
MySqlCommand cmd = new MySqlCommand( 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);
@"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("@creator_id", memberID);
cmd.Parameters.AddWithValue("@assigned_staff_id", staffID); cmd.Parameters.AddWithValue("@assigned_staff_id", staffID);
cmd.Parameters.AddWithValue("@summary", ""); cmd.Parameters.AddWithValue("@summary", "");
@ -310,16 +307,14 @@ namespace SupportChild
cmd.ExecuteNonQuery(); cmd.ExecuteNonQuery();
return cmd.LastInsertedId; return cmd.LastInsertedId;
} }
}
public static void ArchiveTicket(Ticket ticket) public static void ArchiveTicket(Ticket ticket)
{ {
// Check if ticket already exists in the archive // Check if ticket already exists in the archive
if (TryGetClosedTicket(ticket.id, out Ticket _)) if (TryGetClosedTicket(ticket.id, out Ticket _))
{ {
using (MySqlConnection c = GetConnection()) using MySqlConnection c = GetConnection();
{ using MySqlCommand deleteTicket = new MySqlCommand(@"DELETE FROM ticket_history WHERE id=@id OR channel_id=@channel_id", c);
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("@id", ticket.id);
deleteTicket.Parameters.AddWithValue("@channel_id", ticket.channelID); deleteTicket.Parameters.AddWithValue("@channel_id", ticket.channelID);
@ -327,44 +322,45 @@ namespace SupportChild
deleteTicket.Prepare(); deleteTicket.Prepare();
deleteTicket.ExecuteNonQuery(); deleteTicket.ExecuteNonQuery();
} }
}
using (MySqlConnection c = GetConnection())
{
// Create an entry in the ticket history database // 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); 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("@id", ticket.id);
archiveTicket.Parameters.AddWithValue("@created_time", ticket.createdTime); archiveTicket.Parameters.AddWithValue("@created_time", ticket.channelID.GetSnowflakeTime());
archiveTicket.Parameters.AddWithValue("@creator_id", ticket.creatorID); archiveTicket.Parameters.AddWithValue("@creator_id", ticket.creatorID);
archiveTicket.Parameters.AddWithValue("@assigned_staff_id", ticket.assignedStaffID); archiveTicket.Parameters.AddWithValue("@assigned_staff_id", ticket.assignedStaffID);
archiveTicket.Parameters.AddWithValue("@summary", ticket.summary); archiveTicket.Parameters.AddWithValue("@summary", ticket.summary);
archiveTicket.Parameters.AddWithValue("@channel_id", ticket.channelID); archiveTicket.Parameters.AddWithValue("@channel_id", ticket.channelID);
c.Open(); conn.Open();
archiveTicket.Prepare(); archiveTicket.Prepare();
archiveTicket.ExecuteNonQuery(); archiveTicket.ExecuteNonQuery();
} }
}
public static void DeleteOpenTicket(uint ticketID) public static bool DeleteOpenTicket(uint ticketID)
{ {
using (MySqlConnection c = GetConnection()) try
{ {
MySqlCommand deletion = new MySqlCommand(@"DELETE FROM tickets WHERE id=@id", c); using MySqlConnection c = GetConnection();
using MySqlCommand deletion = new MySqlCommand(@"DELETE FROM tickets WHERE id=@id", c);
deletion.Parameters.AddWithValue("@id", ticketID); deletion.Parameters.AddWithValue("@id", ticketID);
c.Open(); c.Open();
deletion.Prepare(); deletion.Prepare();
deletion.ExecuteNonQuery(); return deletion.ExecuteNonQuery() > 0;
}
catch (MySqlException)
{
return false;
} }
} }
public static bool IsBlacklisted(ulong userID) public static bool IsBlacklisted(ulong userID)
{ {
using (MySqlConnection c = GetConnection()) using MySqlConnection c = GetConnection();
{
c.Open(); c.Open();
MySqlCommand selection = new MySqlCommand(@"SELECT * FROM blacklisted_users WHERE user_id=@user_id", c); using MySqlCommand selection = new MySqlCommand(@"SELECT * FROM blacklisted_users WHERE user_id=@user_id", c);
selection.Parameters.AddWithValue("@user_id", userID); selection.Parameters.AddWithValue("@user_id", userID);
selection.Prepare(); selection.Prepare();
MySqlDataReader results = selection.ExecuteReader(); MySqlDataReader results = selection.ExecuteReader();
@ -375,18 +371,17 @@ namespace SupportChild
return true; return true;
} }
results.Close(); results.Close();
}
return false; return false;
} }
public static bool Blacklist(ulong blacklistedID, ulong staffID) public static bool Blacklist(ulong blacklistedID, ulong staffID)
{
using (MySqlConnection c = GetConnection())
{ {
try try
{ {
using MySqlConnection c = GetConnection();
c.Open(); c.Open();
MySqlCommand cmd = new MySqlCommand(@"INSERT INTO blacklisted_users (user_id,time,moderator_id) VALUES (@user_id, UTC_TIMESTAMP(), @moderator_id);", c); 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("@user_id", blacklistedID);
cmd.Parameters.AddWithValue("@moderator_id", staffID); cmd.Parameters.AddWithValue("@moderator_id", staffID);
cmd.Prepare(); cmd.Prepare();
@ -397,15 +392,14 @@ namespace SupportChild
return false; return false;
} }
} }
}
public static bool Unblacklist(ulong blacklistedID) public static bool Unblacklist(ulong blacklistedID)
{
using (MySqlConnection c = GetConnection())
{ {
try try
{ {
using MySqlConnection c = GetConnection();
c.Open(); c.Open();
MySqlCommand cmd = new MySqlCommand(@"DELETE FROM blacklisted_users WHERE user_id=@user_id", c); using MySqlCommand cmd = new MySqlCommand(@"DELETE FROM blacklisted_users WHERE user_id=@user_id", c);
cmd.Parameters.AddWithValue("@user_id", blacklistedID); cmd.Parameters.AddWithValue("@user_id", blacklistedID);
cmd.Prepare(); cmd.Prepare();
return cmd.ExecuteNonQuery() > 0; return cmd.ExecuteNonQuery() > 0;
@ -414,17 +408,15 @@ namespace SupportChild
{ {
return false; return false;
} }
}
}
}
public static bool AssignStaff(Ticket ticket, ulong staffID) public static bool AssignStaff(Ticket ticket, ulong staffID)
{
using (MySqlConnection c = GetConnection())
{ {
try try
{ {
using MySqlConnection c = GetConnection();
c.Open(); c.Open();
MySqlCommand update = new MySqlCommand(@"UPDATE tickets SET assigned_staff_id = @assigned_staff_id WHERE id = @id", c); 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("@assigned_staff_id", staffID);
update.Parameters.AddWithValue("@id", ticket.id); update.Parameters.AddWithValue("@id", ticket.id);
update.Prepare(); update.Prepare();
@ -434,31 +426,57 @@ namespace SupportChild
{ {
return false; return false;
} }
}
}
}
public static bool UnassignStaff(Ticket ticket) public static bool UnassignStaff(Ticket ticket)
{ {
return AssignStaff(ticket, 0); return AssignStaff(ticket, 0);
} }
public static StaffMember GetRandomActiveStaff(ulong currentStaffID)
{
List<StaffMember> staffMembers = GetActiveStaff(currentStaffID);
if (!staffMembers.Any())
{
return null;
}
return staffMembers[random.Next(staffMembers.Count)]; public static bool SetStaffActive(ulong staffID, bool active)
}
public static List<StaffMember> GetActiveStaff(ulong currentStaffID = 0)
{ {
using (MySqlConnection c = GetConnection()) try
{ {
using MySqlConnection c = GetConnection();
c.Open(); c.Open();
MySqlCommand selection = new MySqlCommand(@"SELECT * FROM staff WHERE active = true AND user_id != @user_id", c); MySqlCommand update = new MySqlCommand(@"UPDATE staff SET active = @active WHERE user_id = @user_id", c);
selection.Parameters.AddWithValue("@user_id", currentStaffID); 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<StaffMember> staffMembers = GetActiveStaff(ignoredUserIDs);
return staffMembers.Any() ? staffMembers[random.Next(staffMembers.Count)] : null;
}
public static List<StaffMember> 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(); selection.Prepare();
MySqlDataReader results = selection.ExecuteReader(); MySqlDataReader results = selection.ExecuteReader();
@ -477,15 +495,29 @@ namespace SupportChild
return staffMembers; return staffMembers;
} }
public static List<StaffMember> 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<StaffMember> GetAllStaff(ulong currentStaffID = 0) }
{
using (MySqlConnection c = GetConnection())
{ using MySqlConnection c = GetConnection();
c.Open(); c.Open();
MySqlCommand selection = new MySqlCommand(@"SELECT * FROM staff WHERE user_id != @user_id", c); using MySqlCommand selection = new MySqlCommand(@"SELECT * FROM staff " + filterString, c);
selection.Parameters.AddWithValue("@user_id", currentStaffID);
selection.Prepare(); selection.Prepare();
MySqlDataReader results = selection.ExecuteReader(); MySqlDataReader results = selection.ExecuteReader();
@ -504,14 +536,12 @@ namespace SupportChild
return staffMembers; return staffMembers;
} }
}
public static bool IsStaff(ulong staffID) public static bool IsStaff(ulong staffID)
{ {
using (MySqlConnection c = GetConnection()) using MySqlConnection c = GetConnection();
{
c.Open(); c.Open();
MySqlCommand selection = new MySqlCommand(@"SELECT * FROM staff WHERE user_id=@user_id", c); using MySqlCommand selection = new MySqlCommand(@"SELECT * FROM staff WHERE user_id=@user_id", c);
selection.Parameters.AddWithValue("@user_id", staffID); selection.Parameters.AddWithValue("@user_id", staffID);
selection.Prepare(); selection.Prepare();
MySqlDataReader results = selection.ExecuteReader(); MySqlDataReader results = selection.ExecuteReader();
@ -524,13 +554,12 @@ namespace SupportChild
results.Close(); results.Close();
return true; return true;
} }
}
public static bool TryGetStaff(ulong staffID, out StaffMember staffMember) public static bool TryGetStaff(ulong staffID, out StaffMember staffMember)
{ {
using (MySqlConnection c = GetConnection()) using MySqlConnection c = GetConnection();
{
c.Open(); c.Open();
MySqlCommand selection = new MySqlCommand(@"SELECT * FROM staff WHERE user_id=@user_id", c); using MySqlCommand selection = new MySqlCommand(@"SELECT * FROM staff WHERE user_id=@user_id", c);
selection.Parameters.AddWithValue("@user_id", staffID); selection.Parameters.AddWithValue("@user_id", staffID);
selection.Prepare(); selection.Prepare();
MySqlDataReader results = selection.ExecuteReader(); MySqlDataReader results = selection.ExecuteReader();
@ -545,14 +574,12 @@ namespace SupportChild
results.Close(); results.Close();
return true; return true;
} }
}
public static List<Message> GetAllMessages() public static List<Message> GetAllMessages()
{ {
using (MySqlConnection c = GetConnection()) using MySqlConnection c = GetConnection();
{
c.Open(); c.Open();
MySqlCommand selection = new MySqlCommand(@"SELECT * FROM messages", c); using MySqlCommand selection = new MySqlCommand(@"SELECT * FROM messages", c);
selection.Prepare(); selection.Prepare();
MySqlDataReader results = selection.ExecuteReader(); MySqlDataReader results = selection.ExecuteReader();
@ -571,14 +598,12 @@ namespace SupportChild
return messages; return messages;
} }
}
public static bool TryGetMessage(string identifier, out Message message) public static bool TryGetMessage(string identifier, out Message message)
{ {
using (MySqlConnection c = GetConnection()) using MySqlConnection c = GetConnection();
{
c.Open(); c.Open();
MySqlCommand selection = new MySqlCommand(@"SELECT * FROM messages WHERE identifier=@identifier", c); using MySqlCommand selection = new MySqlCommand(@"SELECT * FROM messages WHERE identifier=@identifier", c);
selection.Parameters.AddWithValue("@identifier", identifier); selection.Parameters.AddWithValue("@identifier", identifier);
selection.Prepare(); selection.Prepare();
MySqlDataReader results = selection.ExecuteReader(); MySqlDataReader results = selection.ExecuteReader();
@ -593,16 +618,14 @@ namespace SupportChild
results.Close(); results.Close();
return true; return true;
} }
}
public static bool AddMessage(string identifier, ulong userID, string message) public static bool AddMessage(string identifier, ulong userID, string message)
{
using (MySqlConnection c = GetConnection())
{ {
try try
{ {
using MySqlConnection c = GetConnection();
c.Open(); c.Open();
MySqlCommand cmd = new MySqlCommand(@"INSERT INTO messages (identifier,user_id,message) VALUES (@identifier, @user_id, @message);", c); 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("@identifier", identifier);
cmd.Parameters.AddWithValue("@user_id", userID); cmd.Parameters.AddWithValue("@user_id", userID);
cmd.Parameters.AddWithValue("@message", message); cmd.Parameters.AddWithValue("@message", message);
@ -614,16 +637,14 @@ namespace SupportChild
return false; return false;
} }
} }
}
public static bool RemoveMessage(string identifier) public static bool RemoveMessage(string identifier)
{
using (MySqlConnection c = GetConnection())
{ {
try try
{ {
using MySqlConnection c = GetConnection();
c.Open(); c.Open();
MySqlCommand cmd = new MySqlCommand(@"DELETE FROM messages WHERE identifier=@identifier", c); using MySqlCommand cmd = new MySqlCommand(@"DELETE FROM messages WHERE identifier=@identifier", c);
cmd.Parameters.AddWithValue("@identifier", identifier); cmd.Parameters.AddWithValue("@identifier", identifier);
cmd.Prepare(); cmd.Prepare();
return cmd.ExecuteNonQuery() > 0; return cmd.ExecuteNonQuery() > 0;
@ -632,14 +653,110 @@ namespace SupportChild
{ {
return false; return false;
} }
}
public static List<Category> 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<Category>();
}
List<Category> categories = new List<Category> { 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 class Ticket
{ {
public uint id; public uint id;
public DateTime createdTime;
public ulong creatorID; public ulong creatorID;
public ulong assignedStaffID; public ulong assignedStaffID;
public string summary; public string summary;
@ -647,17 +764,16 @@ namespace SupportChild
public Ticket(MySqlDataReader reader) public Ticket(MySqlDataReader reader)
{ {
this.id = reader.GetUInt32("id"); id = reader.GetUInt32("id");
this.createdTime = reader.GetDateTime("created_time"); creatorID = reader.GetUInt64("creator_id");
this.creatorID = reader.GetUInt64("creator_id"); assignedStaffID = reader.GetUInt64("assigned_staff_id");
this.assignedStaffID = reader.GetUInt64("assigned_staff_id"); summary = reader.GetString("summary");
this.summary = reader.GetString("summary"); channelID = reader.GetUInt64("channel_id");
this.channelID = reader.GetUInt64("channel_id");
} }
public string FormattedCreatedTime() public string DiscordRelativeTime()
{ {
return this.createdTime.ToString(Config.timestampFormat); return Formatter.Timestamp(channelID.GetSnowflakeTime(), Config.timestampFormat);
} }
} }
public class StaffMember public class StaffMember
@ -668,9 +784,9 @@ namespace SupportChild
public StaffMember(MySqlDataReader reader) public StaffMember(MySqlDataReader reader)
{ {
this.userID = reader.GetUInt64("user_id"); userID = reader.GetUInt64("user_id");
this.name = reader.GetString("name"); name = reader.GetString("name");
this.active = reader.GetBoolean("active"); active = reader.GetBoolean("active");
} }
} }
@ -682,10 +798,21 @@ namespace SupportChild
public Message(MySqlDataReader reader) public Message(MySqlDataReader reader)
{ {
this.identifier = reader.GetString("identifier"); identifier = reader.GetString("identifier");
this.userID = reader.GetUInt64("user_id"); userID = reader.GetUInt64("user_id");
this.message = reader.GetString("message"); 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");
}
} }
} }

View file

@ -2,64 +2,59 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Threading.Tasks; using System.Threading.Tasks;
using DSharpPlus; using DSharpPlus;
using DSharpPlus.CommandsNext;
using DSharpPlus.CommandsNext.Attributes;
using DSharpPlus.CommandsNext.Exceptions;
using DSharpPlus.Entities; using DSharpPlus.Entities;
using DSharpPlus.EventArgs; using DSharpPlus.EventArgs;
using DSharpPlus.Exceptions; 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<ulong, DateTime> reactionTicketCooldowns = new Dictionary<ulong, DateTime>();
public EventHandler(DiscordClient client)
{
this.discordClient = client;
}
internal Task OnReady(DiscordClient client, ReadyEventArgs e)
{
discordClient.Logger.Log(LogLevel.Information, "Client is ready to process events.");
// Checking activity type // Checking activity type
if (!Enum.TryParse(Config.presenceType, true, out ActivityType activityType)) if (!Enum.TryParse(Config.presenceType, true, out ActivityType activityType))
{ {
Console.WriteLine("Presence type '" + Config.presenceType + "' invalid, using 'Playing' instead."); Logger.Log("Presence type '" + Config.presenceType + "' invalid, using 'Playing' instead.");
activityType = ActivityType.Playing; activityType = ActivityType.Playing;
} }
this.discordClient.UpdateStatusAsync(new DiscordActivity(Config.presenceText, activityType), UserStatus.Online); client.UpdateStatusAsync(new DiscordActivity(Config.presenceText, activityType), UserStatus.Online);
return Task.CompletedTask; return Task.CompletedTask;
} }
internal Task OnGuildAvailable(DiscordClient client, GuildCreateEventArgs e) internal static Task OnGuildAvailable(DiscordClient _, GuildCreateEventArgs e)
{ {
discordClient.Logger.Log(LogLevel.Information, $"Guild available: {e.Guild.Name}"); Logger.Log("Guild available: " + e.Guild.Name);
IReadOnlyDictionary<ulong, DiscordRole> roles = e.Guild.Roles; IReadOnlyDictionary<ulong, DiscordRole> roles = e.Guild.Roles;
foreach ((ulong roleID, DiscordRole role) in roles) foreach ((ulong roleID, DiscordRole role) in roles)
{ {
discordClient.Logger.Log(LogLevel.Information, role.Name.PadRight(40, '.') + roleID); Logger.Log(role.Name.PadRight(40, '.') + roleID);
} }
return Task.CompletedTask; return Task.CompletedTask;
} }
internal Task OnClientError(DiscordClient client, ClientErrorEventArgs e) internal static Task OnClientError(DiscordClient _, ClientErrorEventArgs e)
{ {
discordClient.Logger.Log(LogLevel.Error, $"Exception occured: {e.Exception.GetType()}: {e.Exception}"); Logger.Error("Client exception occured:\n" + e.Exception);
switch (e.Exception)
{
case BadRequestException ex:
Logger.Error("JSON Message: " + ex.JsonMessage);
break;
}
return Task.CompletedTask; return Task.CompletedTask;
} }
internal async Task OnMessageCreated(DiscordClient client, MessageCreateEventArgs e) internal static async Task OnMessageCreated(DiscordClient client, MessageCreateEventArgs e)
{ {
if (e.Author.IsBot) if (e.Author.IsBot)
{ {
@ -78,141 +73,54 @@ namespace SupportChild
{ {
try try
{ {
DiscordEmbed message = new DiscordEmbedBuilder DiscordMember staffMember = await e.Guild.GetMemberAsync(ticket.assignedStaffID);
await staffMember.SendMessageAsync(new DiscordEmbedBuilder
{ {
Color = DiscordColor.Green, Color = DiscordColor.Green,
Description = "A ticket you are assigned to has been updated: " + e.Channel.Mention 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 (NotFoundException) { }
catch (UnauthorizedException) { } 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 _: case SlashExecutionChecksFailedException checksFailedException:
return Task.CompletedTask;
case ChecksFailedException _:
{ {
foreach (CheckBaseAttribute attr in ((ChecksFailedException)e.Exception).FailedChecks) foreach (SlashCheckBaseAttribute attr in checksFailedException.FailedChecks)
{ {
DiscordEmbed error = new DiscordEmbedBuilder await e.Context.Channel.SendMessageAsync(new DiscordEmbedBuilder
{ {
Color = DiscordColor.Red, Color = DiscordColor.Red,
Description = this.ParseFailedCheck(attr) Description = ParseFailedCheck(attr)
}; });
e.Context?.Channel?.SendMessageAsync(error);
} }
return Task.CompletedTask; return;
} }
case BadRequestException ex:
Logger.Error("Command exception occured:\n" + e.Exception);
Logger.Error("JSON Message: " + ex.JsonMessage);
return;
default: default:
{ {
discordClient.Logger.Log(LogLevel.Error, $"Exception occured: {e.Exception.GetType()}: {e.Exception}"); Logger.Error("Exception occured: " + e.Exception.GetType() + ": " + e.Exception);
DiscordEmbed error = new DiscordEmbedBuilder await e.Context.Channel.SendMessageAsync(new DiscordEmbedBuilder
{ {
Color = DiscordColor.Red, Color = DiscordColor.Red,
Description = "Internal error occured, please report this to the developer." Description = "Internal error occured, please report this to the developer."
}; });
e.Context?.Channel?.SendMessageAsync(error); return;
return Task.CompletedTask;
} }
} }
} }
internal async Task OnReactionAdded(DiscordClient client, MessageReactionAddEventArgs e) internal static async Task OnMemberAdded(DiscordClient client, GuildMemberAddEventArgs e)
{
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))
{
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
{
Color = DiscordColor.Green,
Description = "Ticket was randomly assigned to <@" + staffID + ">."
};
await ticketChannel.SendMessageAsync(assignmentMessage);
if (Config.assignmentNotifications)
{
DiscordEmbed message = 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)
{
}
}
}
// 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);
}
}
internal async Task OnMemberAdded(DiscordClient client, GuildMemberAddEventArgs e)
{ {
if (!Database.TryGetOpenTickets(e.Member.Id, out List<Database.Ticket> ownTickets)) if (!Database.TryGetOpenTickets(e.Member.Id, out List<Database.Ticket> ownTickets))
{ {
@ -226,35 +134,36 @@ namespace SupportChild
DiscordChannel channel = await client.GetChannelAsync(ticket.channelID); DiscordChannel channel = await client.GetChannelAsync(ticket.channelID);
if (channel?.GuildId == e.Guild.Id) if (channel?.GuildId == e.Guild.Id)
{ {
await channel.AddOverwriteAsync(e.Member, Permissions.AccessChannels, Permissions.None); await channel.SendMessageAsync(new DiscordEmbedBuilder
DiscordEmbed message = new DiscordEmbedBuilder() {
.WithColor(DiscordColor.Green) Color = DiscordColor.Green,
.WithDescription("User '" + e.Member.Username + "#" + e.Member.Discriminator + "' has rejoined the server, and has been re-added to the ticket."); Description = "User '" + e.Member.Username + "#" + e.Member.Discriminator + "' has rejoined the server, and has been re-added to the ticket."
await channel.SendMessageAsync(message); });
} }
} }
catch (Exception) { } catch (Exception) { /* ignored */ }
} }
} }
internal async Task OnMemberRemoved(DiscordClient client, GuildMemberRemoveEventArgs e) internal static async Task OnMemberRemoved(DiscordClient client, GuildMemberRemoveEventArgs e)
{ {
if (Database.TryGetOpenTickets(e.Member.Id, out List<Database.Ticket> ownTickets)) if (Database.TryGetOpenTickets(e.Member.Id, out List<Database.Ticket> ownTickets))
{ {
foreach(Database.Ticket ticket in ownTickets) foreach (Database.Ticket ticket in ownTickets)
{ {
try try
{ {
DiscordChannel channel = await client.GetChannelAsync(ticket.channelID); DiscordChannel channel = await client.GetChannelAsync(ticket.channelID);
if (channel?.GuildId == e.Guild.Id) if (channel?.GuildId == e.Guild.Id)
{ {
DiscordEmbed message = new DiscordEmbedBuilder() await channel.SendMessageAsync(new DiscordEmbedBuilder
.WithColor(DiscordColor.Red) {
.WithDescription("User '" + e.Member.Username + "#" + e.Member.Discriminator + "' has left the server."); Color = DiscordColor.Red,
await channel.SendMessageAsync(message); Description = "User '" + e.Member.Username + "#" + e.Member.Discriminator + "' has left the server."
});
} }
} }
catch (Exception) { } catch (Exception) { /* ignored */ }
} }
} }
@ -263,7 +172,6 @@ namespace SupportChild
DiscordChannel logChannel = await client.GetChannelAsync(Config.logChannel); DiscordChannel logChannel = await client.GetChannelAsync(Config.logChannel);
if (logChannel != null) if (logChannel != null)
{ {
foreach (Database.Ticket ticket in assignedTickets) foreach (Database.Ticket ticket in assignedTickets)
{ {
try try
@ -271,37 +179,97 @@ namespace SupportChild
DiscordChannel channel = await client.GetChannelAsync(ticket.channelID); DiscordChannel channel = await client.GetChannelAsync(ticket.channelID);
if (channel?.GuildId == e.Guild.Id) if (channel?.GuildId == e.Guild.Id)
{ {
DiscordEmbed message = new DiscordEmbedBuilder() await logChannel.SendMessageAsync(new DiscordEmbedBuilder
.WithColor(DiscordColor.Red) {
.WithDescription("Assigned staff member '" + e.Member.Username + "#" + e.Member.Discriminator + "' has left the server: <#" + channel.Id + ">"); Color = DiscordColor.Red,
await logChannel.SendMessageAsync(message); 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) internal static async Task OnComponentInteractionCreated(DiscordClient client, ComponentInteractionCreateEventArgs e)
{ {
switch (attr) try
{ {
case CooldownAttribute _: switch (e.Interaction.Data.ComponentType)
return "You cannot use do that so often!"; {
case RequireOwnerAttribute _: case ComponentType.Button:
return "Only the server owner can use that command!"; switch (e.Id)
case RequirePermissionsAttribute _: {
return "You don't have permission to do that!"; case "supportchild_closeconfirm":
case RequireRolesAttribute _: await CloseCommand.OnConfirmed(e.Interaction);
return "You do not have a required role!"; return;
case RequireUserPermissionsAttribute _: case { } when e.Id.StartsWith("supportchild_newcommandbutton"):
return "You don't have permission to do that!"; await NewCommand.OnCategorySelection(e.Interaction);
case RequireNsfwAttribute _: return;
return "This command can only be used in an NSFW channel!"; 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: default:
return "Unknown Discord API error occured, please try again later."; 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."
};
} }
} }

68
SupportChild/Logger.cs Normal file
View file

@ -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);
}
}
}

View file

@ -3,161 +3,148 @@ using System.IO;
using System.Reflection; using System.Reflection;
using System.Threading.Tasks; using System.Threading.Tasks;
using DSharpPlus; using DSharpPlus;
using DSharpPlus.CommandsNext; using DSharpPlus.Interactivity;
using DSharpPlus.Interactivity.Enums;
using DSharpPlus.Interactivity.Extensions;
using DSharpPlus.SlashCommands;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using SupportChild.Commands; 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 });
internal static SupportChild instance; private static SlashCommandsExtension commands = null;
private DiscordClient discordClient = null; private static void Main()
private CommandsNextExtension commands = null;
private EventHandler eventHandler;
static void Main(string[] args)
{ {
new SupportChild().MainAsync().GetAwaiter().GetResult(); MainAsync().GetAwaiter().GetResult();
} }
private async Task MainAsync() private static async Task MainAsync()
{ {
instance = this; Logger.Log("Starting " + Assembly.GetEntryAssembly()?.GetName().Name + " version " + GetVersion() + "...");
Console.WriteLine("Starting SupportChild version " + GetVersion() + "...");
try try
{ {
this.Reload(); Reload();
// Block this task until the program is closed. // Block this task until the program is closed.
await Task.Delay(-1); await Task.Delay(-1);
} }
catch (Exception e) catch (Exception e)
{ {
Console.WriteLine("Fatal error:"); Logger.Fatal("Fatal error:\n" + e);
Console.WriteLine(e);
Console.ReadLine(); Console.ReadLine();
} }
} }
public static DiscordClient GetClient()
{
return instance.discordClient;
}
public static string GetVersion() public static string GetVersion()
{ {
Version version = Assembly.GetEntryAssembly()?.GetName().Version; Version version = Assembly.GetEntryAssembly()?.GetName().Version;
return version?.Major + "." + version?.Minor + "." + version?.Build + (version?.Revision == 0 ? "" : "-" + (char)(64 + version?.Revision ?? 0)); return version?.Major + "." + version?.Minor + "." + version?.Build + (version?.Revision == 0 ? "" : "-" + (char)(64 + version?.Revision ?? 0));
} }
public async void Reload() public static async void Reload()
{ {
if (this.discordClient != null) if (discordClient != null)
{ {
await this.discordClient.DisconnectAsync(); await discordClient.DisconnectAsync();
this.discordClient.Dispose(); discordClient.Dispose();
Console.WriteLine("Discord client disconnected."); Logger.Log("Discord client disconnected.");
} }
Console.WriteLine("Loading config \"" + Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar + "config.yml\""); Logger.Log("Loading config \"" + Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar + "config.yml\"");
Config.LoadConfig(); Config.LoadConfig();
// Check if token is unset // Check if token is unset
if (Config.token == "<add-token-here>" || Config.token == "") if (Config.token is "<add-token-here>" or "")
{ {
Console.WriteLine("You need to set your bot token in the config and start the bot again."); Logger.Fatal("You need to set your bot token in the config and start the bot again.");
throw new ArgumentException("Invalid Discord bot token"); throw new ArgumentException("Invalid Discord bot token");
} }
// Database connection and setup // Database connection and setup
try try
{ {
Console.WriteLine("Connecting to database... (" + Config.hostName + ":" + Config.port + ")"); Logger.Log("Connecting to database... (" + Config.hostName + ":" + Config.port + ")");
Database.SetConnectionString(Config.hostName, Config.port, Config.database, Config.username, Config.password); Database.SetConnectionString(Config.hostName, Config.port, Config.database, Config.username, Config.password);
Database.SetupTables(); Database.SetupTables();
} }
catch (Exception e) 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); Logger.Fatal("Could not set up database tables, please confirm connection settings, status of the server and permissions of MySQL user. Error: " + e);
throw; throw;
} }
Console.WriteLine("Setting up Discord client..."); Logger.Log("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 // Setting up client configuration
DiscordConfiguration cfg = new DiscordConfiguration DiscordConfiguration cfg = new DiscordConfiguration
{ {
Token = Config.token, Token = Config.token,
TokenType = TokenType.Bot, TokenType = TokenType.Bot,
MinimumLogLevel = logLevel, MinimumLogLevel = Config.logLevel,
AutoReconnect = true, AutoReconnect = true,
Intents = DiscordIntents.All Intents = DiscordIntents.All
}; };
this.discordClient = new DiscordClient(cfg); discordClient = new DiscordClient(cfg);
this.eventHandler = new EventHandler(this.discordClient); 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;
Console.WriteLine("Hooking events..."); discordClient.UseInteractivity(new InteractivityConfiguration
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; AckPaginationButtons = true,
} PaginationBehaviour = PaginationBehaviour.Ignore,
PaginationDeletion = PaginationDeletion.DeleteMessage,
Console.WriteLine("Registering commands..."); Timeout = TimeSpan.FromMinutes(15)
commands = discordClient.UseCommandsNext(new CommandsNextConfiguration
{
StringPrefixes = new []{ Config.prefix }
}); });
this.commands.RegisterCommands<AddCommand>(); Logger.Log("Registering commands...");
this.commands.RegisterCommands<AddMessageCommand>(); commands = discordClient.UseSlashCommands();
this.commands.RegisterCommands<AddStaffCommand>();
this.commands.RegisterCommands<AssignCommand>();
this.commands.RegisterCommands<BlacklistCommand>();
this.commands.RegisterCommands<CloseCommand>();
this.commands.RegisterCommands<ListAssignedCommand>();
this.commands.RegisterCommands<ListCommand>();
this.commands.RegisterCommands<ListOldestCommand>();
this.commands.RegisterCommands<ListUnassignedCommand>();
this.commands.RegisterCommands<MoveCommand>();
this.commands.RegisterCommands<NewCommand>();
this.commands.RegisterCommands<RandomAssignCommand>();
this.commands.RegisterCommands<ReloadCommand>();
this.commands.RegisterCommands<RemoveMessageCommand>();
this.commands.RegisterCommands<RemoveStaffCommand>();
this.commands.RegisterCommands<SayCommand>();
this.commands.RegisterCommands<SetSummaryCommand>();
this.commands.RegisterCommands<SetTicketCommand>();
this.commands.RegisterCommands<StatusCommand>();
this.commands.RegisterCommands<SummaryCommand>();
this.commands.RegisterCommands<ToggleActiveCommand>();
this.commands.RegisterCommands<TranscriptCommand>();
this.commands.RegisterCommands<UnassignCommand>();
this.commands.RegisterCommands<UnblacklistCommand>();
this.commands.RegisterCommands<UnsetTicketCommand>();
Console.WriteLine("Hooking command events..."); commands.RegisterCommands<AddCategoryCommand>();
this.commands.CommandErrored += this.eventHandler.OnCommandError; commands.RegisterCommands<AddCommand>();
commands.RegisterCommands<AddMessageCommand>();
commands.RegisterCommands<AddStaffCommand>();
commands.RegisterCommands<AssignCommand>();
commands.RegisterCommands<BlacklistCommand>();
commands.RegisterCommands<CloseCommand>();
commands.RegisterCommands<CreateButtonPanelCommand>();
commands.RegisterCommands<CreateSelectionBoxPanelCommand>();
commands.RegisterCommands<ListAssignedCommand>();
commands.RegisterCommands<ListCommand>();
commands.RegisterCommands<ListOpen>();
commands.RegisterCommands<ListUnassignedCommand>();
commands.RegisterCommands<MoveCommand>();
commands.RegisterCommands<NewCommand>();
commands.RegisterCommands<RandomAssignCommand>();
commands.RegisterCommands<RemoveCategoryCommand>();
commands.RegisterCommands<RemoveMessageCommand>();
commands.RegisterCommands<RemoveStaffCommand>();
commands.RegisterCommands<SayCommand>();
commands.RegisterCommands<SetSummaryCommand>();
commands.RegisterCommands<StatusCommand>();
commands.RegisterCommands<SummaryCommand>();
commands.RegisterCommands<ToggleActiveCommand>();
commands.RegisterCommands<TranscriptCommand>();
commands.RegisterCommands<UnassignCommand>();
commands.RegisterCommands<UnblacklistCommand>();
commands.RegisterCommands<AdminCommands>();
Console.WriteLine("Connecting to Discord..."); Logger.Log("Hooking command events...");
await this.discordClient.ConnectAsync(); commands.SlashCommandErrored += EventHandler.OnCommandError;
}
Logger.Log("Connecting to Discord...");
await discordClient.ConnectAsync();
} }
} }

View file

@ -5,7 +5,7 @@
<ApplicationIcon>ellie_icon.ico</ApplicationIcon> <ApplicationIcon>ellie_icon.ico</ApplicationIcon>
<TargetFramework>net6.0</TargetFramework> <TargetFramework>net6.0</TargetFramework>
<RuntimeIdentifiers>win-x64;linux-x64</RuntimeIdentifiers> <RuntimeIdentifiers>win-x64;linux-x64</RuntimeIdentifiers>
<Version>1.2.0</Version>
<StartupObject>SupportChild.SupportChild</StartupObject> <StartupObject>SupportChild.SupportChild</StartupObject>
<Authors>EmotionChild</Authors> <Authors>EmotionChild</Authors>
<Product /> <Product />
@ -13,34 +13,33 @@
<RepositoryUrl>https://github.com/EmotionChild/SupportChild</RepositoryUrl> <RepositoryUrl>https://github.com/EmotionChild/SupportChild</RepositoryUrl>
<RepositoryType>Git</RepositoryType> <RepositoryType>Git</RepositoryType>
<PackageLicenseFile>LICENSE</PackageLicenseFile> <PackageLicenseFile>LICENSE</PackageLicenseFile>
<PackageIconUrl>https://cdn.emotionchild.com/Ellie.png</PackageIconUrl> <PackageIconUrl>https://cdn.discordapp.com/attachments/765441543100170271/914327948667011132/Ellie_Concept_2_transparent_ver.png</PackageIconUrl>
<Description>A Discord support bot build for the Ellie's Home Discord server</Description> <Description>A Discord support ticket bot built for the Ellie's home server</Description>
<AssemblyVersion>2.6.1.1</AssemblyVersion>
<FileVersion>2.6.1.1</FileVersion>
<NeutralLanguage>en</NeutralLanguage> <NeutralLanguage>en</NeutralLanguage>
<PackageVersion>1.2.0</PackageVersion> <Version>3.0.0.1</Version>
<PackageVersion>1.3.0</PackageVersion>
<AssemblyVersion>3.0.0.1</AssemblyVersion>
<FileVersion>3.0.0.1</FileVersion>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Debug' ">
<DebugType>full</DebugType>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="DSharpPlus" Version="4.2.0" /> <PackageReference Include="DSharpPlus" Version="4.2.0" />
<PackageReference Include="DSharpPlus.CommandsNext" Version="4.2.0" />
<PackageReference Include="DSharpPlus.Interactivity" Version="4.2.0" /> <PackageReference Include="DSharpPlus.Interactivity" Version="4.2.0" />
<PackageReference Include="DSharpPlus.SlashCommands" Version="4.2.0" />
<PackageReference Include="Gress" Version="2.0.1" />
<PackageReference Include="JsonExtensions" Version="1.2.0" /> <PackageReference Include="JsonExtensions" Version="1.2.0" />
<PackageReference Include="MiniRazor.CodeGen" Version="2.2.1" /> <PackageReference Include="MiniRazor.CodeGen" Version="2.2.1" />
<PackageReference Include="MySql.Data" Version="8.0.29" /> <PackageReference Include="MySql.Data" Version="8.0.30" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" /> <PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
<PackageReference Include="Polly" Version="7.2.3" /> <PackageReference Include="Polly" Version="7.2.3" />
<PackageReference Include="Superpower" Version="3.0.0" /> <PackageReference Include="Superpower" Version="3.0.0" />
<PackageReference Include="Tyrrrz.Extensions" Version="1.6.5" /> <PackageReference Include="Tyrrrz.Extensions" Version="1.6.5" />
<PackageReference Include="YamlDotNet" Version="11.2.1" /> <PackageReference Include="WebMarkupMin.Core" Version="2.9.0" />
</ItemGroup> <PackageReference Include="YamlDotNet" Version="12.0.0" />
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
@ -50,13 +49,6 @@
</EmbeddedResource> </EmbeddedResource>
</ItemGroup> </ItemGroup>
<ItemGroup>
<None Include="..\LICENSE">
<Pack>True</Pack>
<PackagePath></PackagePath>
</None>
</ItemGroup>
<ItemGroup> <ItemGroup>
<Folder Include="lib\" /> <Folder Include="lib\" />
</ItemGroup> </ItemGroup>
@ -67,4 +59,12 @@
</Reference> </Reference>
</ItemGroup> </ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
</ItemGroup>
</Project> </Project>

View file

@ -3,50 +3,42 @@ using System.Threading.Tasks;
using DiscordChatExporter.Core.Discord; using DiscordChatExporter.Core.Discord;
using DiscordChatExporter.Core.Discord.Data; using DiscordChatExporter.Core.Discord.Data;
using DiscordChatExporter.Core.Exceptions;
using DiscordChatExporter.Core.Exporting; using DiscordChatExporter.Core.Exporting;
using DiscordChatExporter.Core.Exporting.Filtering; using DiscordChatExporter.Core.Exporting.Filtering;
using DiscordChatExporter.Core.Exporting.Partitioning; 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) internal static async Task ExecuteAsync(ulong channelID, uint ticketID)
{ {
DiscordClient discordClient = new DiscordClient(new AuthToken(AuthTokenKind.Bot, Config.token)); DiscordClient discordClient = new DiscordClient(Config.token);
ChannelExporter Exporter = new ChannelExporter(discordClient); ChannelExporter exporter = new ChannelExporter(discordClient);
if (!Directory.Exists("./transcripts")) if (!Directory.Exists("./transcripts"))
{ {
Directory.CreateDirectory("./transcripts"); Directory.CreateDirectory("./transcripts");
} }
string dateFormat = "yyyy-MMM-dd HH:mm";
// Configure settings
if (Config.timestampFormat != "")
dateFormat = Config.timestampFormat;
Channel channel = await discordClient.GetChannelAsync(new Snowflake(channelID)); Channel channel = await discordClient.GetChannelAsync(new Snowflake(channelID));
Guild guild = await discordClient.GetGuildAsync(channel.GuildId); Guild guild = await discordClient.GetGuildAsync(channel.GuildId);
ExportRequest request = new ExportRequest( ExportRequest request = new ExportRequest(
guild: guild, Guild: guild,
channel: channel, Channel: channel,
outputPath: GetPath(ticketID), OutputPath: GetPath(ticketID),
format: ExportFormat.HtmlDark, Format: ExportFormat.HtmlDark,
after: null, After: null,
before: null, Before: null,
partitionLimit: PartitionLimit.Null, PartitionLimit: PartitionLimit.Null,
messageFilter: MessageFilter.Null, MessageFilter: MessageFilter.Null,
shouldDownloadMedia: false, ShouldDownloadMedia: false,
shouldReuseMedia: false, ShouldReuseMedia: false,
dateFormat: dateFormat DateFormat: "yyyy-MMM-dd HH:mm"
); );
await Exporter.ExportChannelAsync(request); await exporter.ExportChannelAsync(request);
} }
internal static string GetPath(uint ticketNumber) internal static string GetPath(uint ticketNumber)
@ -58,5 +50,4 @@ namespace SupportChild
{ {
return "ticket-" + ticketNumber.ToString("00000") + ".html"; return "ticket-" + ticketNumber.ToString("00000") + ".html";
} }
}
} }

View file

@ -1,38 +1,23 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Security.Cryptography; using System.Threading.Tasks;
using DSharpPlus.Entities; using DSharpPlus.Entities;
namespace SupportChild namespace SupportChild;
public static class Utilities
{ {
public static class Utilities private static readonly Random rng = new Random();
public static void Shuffle<T>(this IList<T> list)
{ {
public static List<T> RandomizeList<T>(List<T> list)
{
RNGCryptoServiceProvider provider = new RNGCryptoServiceProvider();
int n = list.Count; int n = list.Count;
while (n > 1) 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--; n--;
T value = list[k]; int k = rng.Next(n + 1);
list[k] = list[n]; (list[k], list[n]) = (list[n], list[k]);
list[n] = value;
} }
return list;
}
public static string[] ParseIDs(string args)
{
if (string.IsNullOrEmpty(args))
{
return new string[0];
}
return args.Trim().Replace("<@!", "").Replace("<@", "").Replace(">", "").Split();
} }
public static LinkedList<string> ParseListIntoMessages(List<string> listItems) public static LinkedList<string> ParseListIntoMessages(List<string> listItems)
@ -54,18 +39,27 @@ namespace SupportChild
return messages; return messages;
} }
public static DiscordRole GetRoleByName(DiscordGuild guild, string Name) public static async Task<List<Database.Category>> GetVerifiedChannels()
{ {
Name = Name.Trim().ToLower(); List<Database.Category> verifiedCategories = new List<Database.Category>();
foreach (DiscordRole role in guild.Roles.Values) foreach (Database.Category category in Database.GetAllCategories())
{ {
if (role.Name.ToLower().StartsWith(Name)) DiscordChannel channel = null;
try
{ {
return role; channel = await SupportChild.discordClient.GetChannelAsync(category.id);
}
} }
catch (Exception) { /*ignored*/ }
return null; if (channel != null)
{
verifiedCategories.Add(category);
} }
else
{
Logger.Warn("Category '" + category.name + "' (" + category.id + ") no longer exists! Ignoring...");
}
}
return verifiedCategories;
} }
} }

View file

@ -1,31 +1,30 @@
bot: bot:
# Bot token. # Bot token.
token: "<add-token-here>" token: "<add-token-here>"
# Command prefix.
prefix: "-"
# Channel where ticket logs are posted (recommended) # Channel where ticket logs are posted (recommended)
log-channel: 000000000000000000 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. # Message posted when a ticket is opened.
welcome-message: "Please describe your issue below, and include all information needed for us to help you." welcome-message: "Please describe your issue below, and include all information needed for us to take action."
# Decides what messages are shown in console # Decides what messages are shown in console
# Possible values are: Critical, Error, Warning, Information, Debug. # Possible values are: Critical, Error, Warning, Information, Debug.
console-log-level: "Information" console-log-level: "Information"
# Format for timestamps in transcripts and google sheets if used # One of the following: LongDate, LongDateTime, LongTime, RelativeTime, ShortDate, ShortDateTime, ShortTime
timestamp-format: "yyyy-MM-dd HH:mm" # 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. # 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 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. # 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. # 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 random-assign-role-override: true
# Sets the type of activity for the bot to display in its presence status # Sets the type of activity for the bot to display in its presence status
# Possible values are: Playing, Streaming, ListeningTo, Watching, Competing # Possible values are: Playing, Streaming, ListeningTo, Watching, Competing
presence-type: "ListeningTo" presence-type: "ListeningTo"
# Sets the activity text shown in the bot's status # Sets the activity text shown in the bot's status
presence-text: "-new" 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: 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 # 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
@ -47,38 +46,3 @@ database:
# Username and password for authentication # Username and password for authentication
user: "" user: ""
password: "" 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: []