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.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 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 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;
@ -32,43 +30,10 @@ namespace SupportChild
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 database = "supportchild";
internal static string username = "supportchild";
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()
{
// Writes default config to file if it does not already exist
@ -82,25 +47,38 @@ namespace SupportChild
// Converts the FileStream into a YAML object
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
ISerializer serializer = new SerializerBuilder().JsonCompatible().Build();
JObject json = JObject.Parse(serializer.Serialize(yamlObject));
// Sets up the bot
token = json.SelectToken("bot.token").Value<string>() ?? "";
prefix = json.SelectToken("bot.prefix").Value<string>() ?? "";
logChannel = json.SelectToken("bot.log-channel").Value<ulong>();
ticketCategory = json.SelectToken("bot.ticket-category")?.Value<ulong>() ?? 0;
reactionMessage = json.SelectToken("bot.reaction-message")?.Value<ulong>() ?? 0;
welcomeMessage = json.SelectToken("bot.welcome-message").Value<string>() ?? "";
logLevel = json.SelectToken("bot.console-log-level").Value<string>() ?? "";
timestampFormat = json.SelectToken("bot.timestamp-format").Value<string>() ?? "yyyy-MM-dd HH:mm";
token = json.SelectToken("bot.token")?.Value<string>() ?? "";
logChannel = json.SelectToken("bot.log-channel")?.Value<ulong>() ?? 0;
welcomeMessage = json.SelectToken("bot.welcome-message")?.Value<string>() ?? "";
string stringLogLevel = json.SelectToken("bot.console-log-level")?.Value<string>() ?? "";
if (!Enum.TryParse(stringLogLevel, true, out logLevel))
{
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;
randomAssignRoleOverride = json.SelectToken("bot.random-assign-role-override")?.Value<bool>() ?? false;
presenceType = json.SelectToken("bot.presence-type")?.Value<string>() ?? "Playing";
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;
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";
username = json.SelectToken("database.user")?.Value<string>() ?? "supportchild";
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.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 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)
{
@ -19,51 +20,50 @@ namespace SupportChild
";userid=" + username +
";password=" + password;
}
public static MySqlConnection GetConnection()
{
return new MySqlConnection(connectionString);
}
public static long GetNumberOfTickets()
{
try
{
using (MySqlConnection c = GetConnection())
{
MySqlCommand countTickets = new MySqlCommand("SELECT COUNT(*) FROM tickets", c);
using MySqlConnection c = GetConnection();
using 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);
Logger.Error("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);
using MySqlConnection c = GetConnection();
using 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);
Logger.Error("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(
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," +
@ -73,7 +73,7 @@ namespace SupportChild
"channel_id BIGINT UNSIGNED NOT NULL UNIQUE," +
"INDEX(created_time, assigned_staff_id, channel_id))",
c);
MySqlCommand createTicketHistory = new MySqlCommand(
using MySqlCommand createTicketHistory = new MySqlCommand(
"CREATE TABLE IF NOT EXISTS ticket_history(" +
"id INT UNSIGNED NOT NULL PRIMARY KEY," +
"created_time DATETIME NOT NULL," +
@ -84,39 +84,44 @@ namespace SupportChild
"channel_id BIGINT UNSIGNED NOT NULL UNIQUE," +
"INDEX(created_time, closed_time, channel_id))",
c);
MySqlCommand createBlacklisted = new MySqlCommand(
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);
MySqlCommand createStaffList = new MySqlCommand(
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);
MySqlCommand createMessages = new MySqlCommand(
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())
{
using MySqlConnection c = GetConnection();
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.Prepare();
MySqlDataReader results = selection.ExecuteReader();
@ -127,15 +132,14 @@ namespace SupportChild
return false;
}
results.Close();
}
return true;
}
public static bool TryGetOpenTicket(ulong channelID, out Ticket ticket)
{
using (MySqlConnection c = GetConnection())
{
using MySqlConnection c = GetConnection();
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.Prepare();
MySqlDataReader results = selection.ExecuteReader();
@ -151,13 +155,12 @@ namespace SupportChild
results.Close();
return true;
}
}
public static bool TryGetOpenTicketByID(uint id, out Ticket ticket)
{
using (MySqlConnection c = GetConnection())
{
using MySqlConnection c = GetConnection();
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.Prepare();
MySqlDataReader results = selection.ExecuteReader();
@ -166,19 +169,20 @@ namespace SupportChild
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())
{
using MySqlConnection c = GetConnection();
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.Prepare();
MySqlDataReader results = selection.ExecuteReader();
@ -187,20 +191,21 @@ namespace SupportChild
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<Ticket> tickets)
{
tickets = null;
using (MySqlConnection c = GetConnection())
{
using MySqlConnection c = GetConnection();
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.Prepare();
MySqlDataReader results = selection.ExecuteReader();
@ -218,16 +223,13 @@ namespace SupportChild
results.Close();
return true;
}
}
public static bool TryGetOldestTickets(ulong userID, out List<Ticket> tickets, int listLimit)
public static bool TryGetOpenTickets(out List<Ticket> tickets)
{
tickets = null;
using (MySqlConnection c = GetConnection())
{
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);
using MySqlCommand selection = new MySqlCommand(@"SELECT * FROM tickets ORDER BY channel_id ASC", c);
selection.Prepare();
MySqlDataReader results = selection.ExecuteReader();
@ -244,14 +246,13 @@ namespace SupportChild
results.Close();
return true;
}
}
public static bool TryGetClosedTickets(ulong userID, out List<Ticket> tickets)
{
tickets = null;
using (MySqlConnection c = GetConnection())
{
using MySqlConnection c = GetConnection();
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.Prepare();
MySqlDataReader results = selection.ExecuteReader();
@ -269,14 +270,13 @@ namespace SupportChild
results.Close();
return true;
}
}
public static bool TryGetAssignedTickets(ulong staffID, out List<Ticket> tickets)
{
tickets = null;
using (MySqlConnection c = GetConnection())
{
using MySqlConnection c = GetConnection();
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.Prepare();
MySqlDataReader results = selection.ExecuteReader();
@ -294,15 +294,12 @@ namespace SupportChild
results.Close();
return true;
}
}
public static long NewTicket(ulong memberID, ulong staffID, ulong ticketID)
{
using (MySqlConnection c = GetConnection())
{
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);
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", "");
@ -310,16 +307,14 @@ namespace SupportChild
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())
{
MySqlCommand deleteTicket = new MySqlCommand(@"DELETE FROM ticket_history WHERE id=@id OR channel_id=@channel_id", c);
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);
@ -327,44 +322,45 @@ namespace SupportChild
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);
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.createdTime);
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);
c.Open();
conn.Open();
archiveTicket.Prepare();
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);
c.Open();
deletion.Prepare();
deletion.ExecuteNonQuery();
return deletion.ExecuteNonQuery() > 0;
}
catch (MySqlException)
{
return false;
}
}
public static bool IsBlacklisted(ulong userID)
{
using (MySqlConnection c = GetConnection())
{
using MySqlConnection c = GetConnection();
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.Prepare();
MySqlDataReader results = selection.ExecuteReader();
@ -375,18 +371,17 @@ namespace SupportChild
return true;
}
results.Close();
}
return false;
}
public static bool Blacklist(ulong blacklistedID, ulong staffID)
{
using (MySqlConnection c = GetConnection())
{
try
{
using MySqlConnection c = GetConnection();
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("@moderator_id", staffID);
cmd.Prepare();
@ -397,15 +392,14 @@ namespace SupportChild
return false;
}
}
}
public static bool Unblacklist(ulong blacklistedID)
{
using (MySqlConnection c = GetConnection())
{
try
{
using MySqlConnection c = GetConnection();
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.Prepare();
return cmd.ExecuteNonQuery() > 0;
@ -414,17 +408,15 @@ namespace SupportChild
{
return false;
}
}
}
}
public static bool AssignStaff(Ticket ticket, ulong staffID)
{
using (MySqlConnection c = GetConnection())
{
try
{
using MySqlConnection c = GetConnection();
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("@id", ticket.id);
update.Prepare();
@ -434,31 +426,57 @@ namespace SupportChild
{
return false;
}
}
}
}
public static bool UnassignStaff(Ticket ticket)
{
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 List<StaffMember> GetActiveStaff(ulong currentStaffID = 0)
public static bool SetStaffActive(ulong staffID, bool active)
{
using (MySqlConnection c = GetConnection())
try
{
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);
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<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();
MySqlDataReader results = selection.ExecuteReader();
@ -477,15 +495,29 @@ namespace SupportChild
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();
MySqlCommand selection = new MySqlCommand(@"SELECT * FROM staff WHERE user_id != @user_id", c);
selection.Parameters.AddWithValue("@user_id", currentStaffID);
using MySqlCommand selection = new MySqlCommand(@"SELECT * FROM staff " + filterString, c);
selection.Prepare();
MySqlDataReader results = selection.ExecuteReader();
@ -504,14 +536,12 @@ namespace SupportChild
return staffMembers;
}
}
public static bool IsStaff(ulong staffID)
{
using (MySqlConnection c = GetConnection())
{
using MySqlConnection c = GetConnection();
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.Prepare();
MySqlDataReader results = selection.ExecuteReader();
@ -524,13 +554,12 @@ namespace SupportChild
results.Close();
return true;
}
}
public static bool TryGetStaff(ulong staffID, out StaffMember staffMember)
{
using (MySqlConnection c = GetConnection())
{
using MySqlConnection c = GetConnection();
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.Prepare();
MySqlDataReader results = selection.ExecuteReader();
@ -545,14 +574,12 @@ namespace SupportChild
results.Close();
return true;
}
}
public static List<Message> GetAllMessages()
{
using (MySqlConnection c = GetConnection())
{
using MySqlConnection c = GetConnection();
c.Open();
MySqlCommand selection = new MySqlCommand(@"SELECT * FROM messages", c);
using MySqlCommand selection = new MySqlCommand(@"SELECT * FROM messages", c);
selection.Prepare();
MySqlDataReader results = selection.ExecuteReader();
@ -571,14 +598,12 @@ namespace SupportChild
return messages;
}
}
public static bool TryGetMessage(string identifier, out Message message)
{
using (MySqlConnection c = GetConnection())
{
using MySqlConnection c = GetConnection();
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.Prepare();
MySqlDataReader results = selection.ExecuteReader();
@ -593,16 +618,14 @@ namespace SupportChild
results.Close();
return true;
}
}
public static bool AddMessage(string identifier, ulong userID, string message)
{
using (MySqlConnection c = GetConnection())
{
try
{
using MySqlConnection c = GetConnection();
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("@user_id", userID);
cmd.Parameters.AddWithValue("@message", message);
@ -614,16 +637,14 @@ namespace SupportChild
return false;
}
}
}
public static bool RemoveMessage(string identifier)
{
using (MySqlConnection c = GetConnection())
{
try
{
using MySqlConnection c = GetConnection();
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.Prepare();
return cmd.ExecuteNonQuery() > 0;
@ -632,14 +653,110 @@ namespace SupportChild
{
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 uint id;
public DateTime createdTime;
public ulong creatorID;
public ulong assignedStaffID;
public string summary;
@ -647,17 +764,16 @@ namespace SupportChild
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");
id = reader.GetUInt32("id");
creatorID = reader.GetUInt64("creator_id");
assignedStaffID = reader.GetUInt64("assigned_staff_id");
summary = reader.GetString("summary");
channelID = reader.GetUInt64("channel_id");
}
public string FormattedCreatedTime()
public string DiscordRelativeTime()
{
return this.createdTime.ToString(Config.timestampFormat);
return Formatter.Timestamp(channelID.GetSnowflakeTime(), Config.timestampFormat);
}
}
public class StaffMember
@ -668,9 +784,9 @@ namespace SupportChild
public StaffMember(MySqlDataReader reader)
{
this.userID = reader.GetUInt64("user_id");
this.name = reader.GetString("name");
this.active = reader.GetBoolean("active");
userID = reader.GetUInt64("user_id");
name = reader.GetString("name");
active = reader.GetBoolean("active");
}
}
@ -682,10 +798,21 @@ namespace SupportChild
public Message(MySqlDataReader reader)
{
this.identifier = reader.GetString("identifier");
this.userID = reader.GetUInt64("user_id");
this.message = reader.GetString("message");
identifier = reader.GetString("identifier");
userID = reader.GetUInt64("user_id");
message = reader.GetString("message");
}
}
public class Category
{
public string name;
public ulong id;
public Category(MySqlDataReader reader)
{
name = reader.GetString("name");
id = reader.GetUInt64("category_id");
}
}
}

View file

@ -2,64 +2,59 @@
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;
//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.");
Logger.Log("Client is ready to process events.");
// Checking activity type
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;
}
this.discordClient.UpdateStatusAsync(new DiscordActivity(Config.presenceText, activityType), UserStatus.Online);
client.UpdateStatusAsync(new DiscordActivity(Config.presenceText, activityType), UserStatus.Online);
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;
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;
}
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;
}
internal async Task OnMessageCreated(DiscordClient client, MessageCreateEventArgs e)
internal static async Task OnMessageCreated(DiscordClient client, MessageCreateEventArgs e)
{
if (e.Author.IsBot)
{
@ -78,141 +73,54 @@ namespace SupportChild
{
try
{
DiscordEmbed message = new DiscordEmbedBuilder
DiscordMember staffMember = await e.Guild.GetMemberAsync(ticket.assignedStaffID);
await staffMember.SendMessageAsync(new DiscordEmbedBuilder
{
Color = DiscordColor.Green,
Description = "A ticket you are assigned to has been updated: " + e.Channel.Mention
};
DiscordMember staffMember = await e.Guild.GetMemberAsync(ticket.assignedStaffID);
await staffMember.SendMessageAsync(message);
});
}
catch (NotFoundException) { }
catch (UnauthorizedException) { }
}
}
internal Task OnCommandError(CommandsNextExtension commandSystem, CommandErrorEventArgs e)
internal static async Task OnCommandError(SlashCommandsExtension commandSystem, SlashCommandErrorEventArgs e)
{
switch (e.Exception)
{
case CommandNotFoundException _:
return Task.CompletedTask;
case ChecksFailedException _:
case SlashExecutionChecksFailedException 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,
Description = this.ParseFailedCheck(attr)
};
e.Context?.Channel?.SendMessageAsync(error);
Description = ParseFailedCheck(attr)
});
}
return Task.CompletedTask;
return;
}
case BadRequestException ex:
Logger.Error("Command exception occured:\n" + e.Exception);
Logger.Error("JSON Message: " + ex.JsonMessage);
return;
default:
{
discordClient.Logger.Log(LogLevel.Error, $"Exception occured: {e.Exception.GetType()}: {e.Exception}");
DiscordEmbed error = new DiscordEmbedBuilder
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."
};
e.Context?.Channel?.SendMessageAsync(error);
return Task.CompletedTask;
});
return;
}
}
}
internal async Task OnReactionAdded(DiscordClient client, MessageReactionAddEventArgs 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)
internal static async Task OnMemberAdded(DiscordClient client, GuildMemberAddEventArgs e)
{
if (!Database.TryGetOpenTickets(e.Member.Id, out List<Database.Ticket> ownTickets))
{
@ -226,35 +134,36 @@ 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.Green,
Description = "User '" + e.Member.Username + "#" + e.Member.Discriminator + "' has rejoined the server, and has been re-added to the ticket."
});
}
}
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))
{
foreach(Database.Ticket ticket in ownTickets)
foreach (Database.Ticket ticket in ownTickets)
{
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);
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 */ }
}
}
@ -263,7 +172,6 @@ namespace SupportChild
DiscordChannel logChannel = await client.GetChannelAsync(Config.logChannel);
if (logChannel != null)
{
foreach (Database.Ticket ticket in assignedTickets)
{
try
@ -271,37 +179,97 @@ namespace SupportChild
DiscordChannel channel = await client.GetChannelAsync(ticket.channelID);
if (channel?.GuildId == e.Guild.Id)
{
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);
await logChannel.SendMessageAsync(new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = "Assigned staff member '" + e.Member.Username + "#" + e.Member.Discriminator + "' has left the server: <#" + channel.Id + ">"
});
}
}
catch (Exception) { }
catch (Exception) { /* ignored */ }
}
}
}
}
private string ParseFailedCheck(CheckBaseAttribute attr)
internal static async Task OnComponentInteractionCreated(DiscordClient client, ComponentInteractionCreateEventArgs e)
{
switch (attr)
try
{
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!";
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:
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.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
{
internal static SupportChild instance;
// 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 DiscordClient discordClient = null;
private CommandsNextExtension commands = null;
private EventHandler eventHandler;
static void Main(string[] args)
private static void Main()
{
new SupportChild().MainAsync().GetAwaiter().GetResult();
MainAsync().GetAwaiter().GetResult();
}
private async Task MainAsync()
private static async Task MainAsync()
{
instance = this;
Console.WriteLine("Starting SupportChild version " + GetVersion() + "...");
Logger.Log("Starting " + Assembly.GetEntryAssembly()?.GetName().Name + " version " + GetVersion() + "...");
try
{
this.Reload();
Reload();
// Block this task until the program is closed.
await Task.Delay(-1);
}
catch (Exception e)
{
Console.WriteLine("Fatal error:");
Console.WriteLine(e);
Logger.Fatal("Fatal error:\n" + 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()
public static async void Reload()
{
if (this.discordClient != null)
if (discordClient != null)
{
await this.discordClient.DisconnectAsync();
this.discordClient.Dispose();
Console.WriteLine("Discord client disconnected.");
await discordClient.DisconnectAsync();
discordClient.Dispose();
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();
// 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");
}
// Database connection and setup
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.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);
Logger.Fatal("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;
}
Logger.Log("Setting up Discord client...");
// Setting up client configuration
DiscordConfiguration cfg = new DiscordConfiguration
{
Token = Config.token,
TokenType = TokenType.Bot,
MinimumLogLevel = logLevel,
MinimumLogLevel = Config.logLevel,
AutoReconnect = true,
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...");
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)
discordClient.UseInteractivity(new InteractivityConfiguration
{
this.discordClient.MessageReactionAdded += this.eventHandler.OnReactionAdded;
}
Console.WriteLine("Registering commands...");
commands = discordClient.UseCommandsNext(new CommandsNextConfiguration
{
StringPrefixes = new []{ Config.prefix }
AckPaginationButtons = true,
PaginationBehaviour = PaginationBehaviour.Ignore,
PaginationDeletion = PaginationDeletion.DeleteMessage,
Timeout = TimeSpan.FromMinutes(15)
});
this.commands.RegisterCommands<AddCommand>();
this.commands.RegisterCommands<AddMessageCommand>();
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>();
Logger.Log("Registering commands...");
commands = discordClient.UseSlashCommands();
Console.WriteLine("Hooking command events...");
this.commands.CommandErrored += this.eventHandler.OnCommandError;
commands.RegisterCommands<AddCategoryCommand>();
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...");
await this.discordClient.ConnectAsync();
}
Logger.Log("Hooking command events...");
commands.SlashCommandErrored += EventHandler.OnCommandError;
Logger.Log("Connecting to Discord...");
await discordClient.ConnectAsync();
}
}

View file

@ -5,7 +5,7 @@
<ApplicationIcon>ellie_icon.ico</ApplicationIcon>
<TargetFramework>net6.0</TargetFramework>
<RuntimeIdentifiers>win-x64;linux-x64</RuntimeIdentifiers>
<Version>1.2.0</Version>
<StartupObject>SupportChild.SupportChild</StartupObject>
<Authors>EmotionChild</Authors>
<Product />
@ -13,34 +13,33 @@
<RepositoryUrl>https://github.com/EmotionChild/SupportChild</RepositoryUrl>
<RepositoryType>Git</RepositoryType>
<PackageLicenseFile>LICENSE</PackageLicenseFile>
<PackageIconUrl>https://cdn.emotionchild.com/Ellie.png</PackageIconUrl>
<Description>A Discord support bot build for the Ellie's Home Discord server</Description>
<AssemblyVersion>2.6.1.1</AssemblyVersion>
<FileVersion>2.6.1.1</FileVersion>
<PackageIconUrl>https://cdn.discordapp.com/attachments/765441543100170271/914327948667011132/Ellie_Concept_2_transparent_ver.png</PackageIconUrl>
<Description>A Discord support ticket bot built for the Ellie's home server</Description>
<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>
<ItemGroup>
<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.SlashCommands" Version="4.2.0" />
<PackageReference Include="Gress" Version="2.0.1" />
<PackageReference Include="JsonExtensions" Version="1.2.0" />
<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="Polly" Version="7.2.3" />
<PackageReference Include="Superpower" Version="3.0.0" />
<PackageReference Include="Tyrrrz.Extensions" Version="1.6.5" />
<PackageReference Include="YamlDotNet" Version="11.2.1" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
<PackageReference Include="WebMarkupMin.Core" Version="2.9.0" />
<PackageReference Include="YamlDotNet" Version="12.0.0" />
</ItemGroup>
<ItemGroup>
@ -50,13 +49,6 @@
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Include="..\LICENSE">
<Pack>True</Pack>
<PackagePath></PackagePath>
</None>
</ItemGroup>
<ItemGroup>
<Folder Include="lib\" />
</ItemGroup>
@ -67,4 +59,12 @@
</Reference>
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
</ItemGroup>
</Project>

View file

@ -3,50 +3,42 @@ 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);
DiscordClient discordClient = new DiscordClient(Config.token);
ChannelExporter exporter = new ChannelExporter(discordClient);
if (!Directory.Exists("./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));
Guild guild = await discordClient.GetGuildAsync(channel.GuildId);
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
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"
);
await Exporter.ExportChannelAsync(request);
await exporter.ExportChannelAsync(request);
}
internal static string GetPath(uint ticketNumber)
@ -58,5 +50,4 @@ namespace SupportChild
{
return "ticket-" + ticketNumber.ToString("00000") + ".html";
}
}
}

View file

@ -1,38 +1,23 @@
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
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;
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;
int k = rng.Next(n + 1);
(list[k], list[n]) = (list[n], list[k]);
}
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)
@ -54,18 +39,27 @@ namespace SupportChild
return messages;
}
public static DiscordRole GetRoleByName(DiscordGuild guild, string Name)
public static async Task<List<Database.Category>> GetVerifiedChannels()
{
Name = Name.Trim().ToLower();
foreach (DiscordRole role in guild.Roles.Values)
List<Database.Category> verifiedCategories = new List<Database.Category>();
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 token.
token: "<add-token-here>"
# 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."
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"
# Format for timestamps in transcripts and google sheets if used
timestamp-format: "yyyy-MM-dd HH:mm"
# 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 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
# 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"
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
@ -47,38 +46,3 @@ database:
# 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: []