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,143 +1,95 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using DSharpPlus.Entities;
using DSharpPlus;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Linq;
using SupportChild.Properties;
using YamlDotNet.Serialization;
namespace SupportChild
namespace SupportChild;
internal static class Config
{
internal static class Config
internal static string token = "";
internal static ulong logChannel;
internal static string welcomeMessage = "";
internal static LogLevel logLevel = LogLevel.Information;
internal static TimestampFormat timestampFormat = TimestampFormat.RelativeTime;
internal static bool randomAssignment = false;
internal static bool randomAssignRoleOverride = false;
internal static string presenceType = "Playing";
internal static string presenceText = "";
internal static bool newCommandUsesSelector = false;
internal static int ticketLimit = 5;
internal static bool ticketUpdatedNotifications = false;
internal static double ticketUpdatedNotificationDelay = 0.0;
internal static bool assignmentNotifications = false;
internal static bool closingNotifications = false;
internal static string hostName = "127.0.0.1";
internal static int port = 3306;
internal static string database = "supportchild";
internal static string username = "supportchild";
internal static string password = "";
public static void LoadConfig()
{
internal static string token = "";
internal static string prefix = "";
internal static ulong logChannel;
internal static ulong ticketCategory;
internal static ulong reactionMessage;
internal static string welcomeMessage = "";
internal static string logLevel = "Information";
internal static string timestampFormat = "yyyy-MMM-dd HH:mm";
internal static bool randomAssignment = false;
internal static bool randomAssignRoleOverride = false;
internal static string presenceType = "Playing";
internal static string presenceText = "";
internal static bool ticketUpdatedNotifications = false;
internal static double ticketUpdatedNotificationDelay = 0.0;
internal static bool assignmentNotifications = false;
internal static bool closingNotifications = false;
internal static string hostName = "127.0.0.1";
internal static int port = 3306;
internal static string database = "supportbot";
internal static string username = "supportbot";
internal static string password = "";
private static readonly Dictionary<string, ulong[]> permissions = new Dictionary<string, ulong[]>
// Writes default config to file if it does not already exist
if (!File.Exists("./config.yml"))
{
// Public commands
{ "close", new ulong[]{ } },
{ "list", new ulong[]{ } },
{ "new", new ulong[]{ } },
{ "say", new ulong[]{ } },
{ "status", new ulong[]{ } },
{ "summary", new ulong[]{ } },
{ "transcript", new ulong[]{ } },
// Moderator commands
{ "add", new ulong[]{ } },
{ "addmessage", new ulong[]{ } },
{ "assign", new ulong[]{ } },
{ "blacklist", new ulong[]{ } },
{ "listassigned", new ulong[]{ } },
{ "listoldest", new ulong[]{ } },
{ "listunassigned", new ulong[]{ } },
{ "move", new ulong[]{ } },
{ "rassign", new ulong[]{ } },
{ "removemessage", new ulong[]{ } },
{ "setsummary", new ulong[]{ } },
{ "toggleactive", new ulong[]{ } },
{ "unassign", new ulong[]{ } },
{ "unblacklist", new ulong[]{ } },
// Admin commands
{ "addstaff", new ulong[]{ } },
{ "reload", new ulong[]{ } },
{ "removestaff", new ulong[]{ } },
{ "setticket", new ulong[]{ } },
{ "unsetticket", new ulong[]{ } },
};
public static void LoadConfig()
{
// Writes default config to file if it does not already exist
if (!File.Exists("./config.yml"))
{
File.WriteAllText("./config.yml", Encoding.UTF8.GetString(Resources.default_config));
}
// Reads config contents into FileStream
FileStream stream = File.OpenRead("./config.yml");
// Converts the FileStream into a YAML object
IDeserializer deserializer = new DeserializerBuilder().Build();
object yamlObject = deserializer.Deserialize(new StreamReader(stream));
// Converts the YAML object into a JSON object as the YAML ones do not support traversal or selection of nodes by name
ISerializer serializer = new SerializerBuilder().JsonCompatible().Build();
JObject json = JObject.Parse(serializer.Serialize(yamlObject));
// Sets up the bot
token = json.SelectToken("bot.token").Value<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";
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>() ?? "";
ticketUpdatedNotifications = json.SelectToken("notifications.ticket-updated")?.Value<bool>() ?? false;
ticketUpdatedNotificationDelay = json.SelectToken("notifications.ticket-updated-delay")?.Value<double>() ?? 0.0;
assignmentNotifications = json.SelectToken("notifications.assignment")?.Value<bool>() ?? false;
closingNotifications = json.SelectToken("notifications.closing")?.Value<bool>() ?? false;
// Reads database info
hostName = json.SelectToken("database.address")?.Value<string>() ?? "";
port = json.SelectToken("database.port")?.Value<int>() ?? 3306;
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: []");
}
}
File.WriteAllText("./config.yml", Encoding.UTF8.GetString(Resources.default_config));
}
/// <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)
// Reads config contents into FileStream
FileStream stream = File.OpenRead("./config.yml");
// Converts the FileStream into a YAML object
IDeserializer deserializer = new DeserializerBuilder().Build();
object yamlObject = deserializer.Deserialize(new StreamReader(stream)) ?? "";
// Converts the YAML object into a JSON object as the YAML ones do not support traversal or selection of nodes by name
ISerializer serializer = new SerializerBuilder().JsonCompatible().Build();
JObject json = JObject.Parse(serializer.Serialize(yamlObject));
// Sets up the bot
token = json.SelectToken("bot.token")?.Value<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))
{
return member.Roles.Any(role => permissions[permission].Contains(role.Id)) || permissions[permission].Contains(member.Guild.Id);
logLevel = LogLevel.Information;
Logger.Warn("Log level '" + stringLogLevel + "' invalid, using 'Information' instead.");
}
string stringTimestampFormat = json.SelectToken("bot.timestamp-format")?.Value<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;
assignmentNotifications = json.SelectToken("notifications.assignment")?.Value<bool>() ?? false;
closingNotifications = json.SelectToken("notifications.closing")?.Value<bool>() ?? false;
// Reads database info
hostName = json.SelectToken("database.address")?.Value<string>() ?? "";
port = json.SelectToken("database.port")?.Value<int>() ?? 3306;
database = json.SelectToken("database.name")?.Value<string>() ?? "supportchild";
username = json.SelectToken("database.user")?.Value<string>() ?? "supportchild";
password = json.SelectToken("database.password")?.Value<string>() ?? "";
}
}

File diff suppressed because it is too large Load diff

View file

@ -2,223 +2,153 @@
using System.Collections.Generic;
using System.Threading.Tasks;
using DSharpPlus;
using DSharpPlus.CommandsNext;
using DSharpPlus.CommandsNext.Attributes;
using DSharpPlus.CommandsNext.Exceptions;
using DSharpPlus.Entities;
using DSharpPlus.EventArgs;
using DSharpPlus.Exceptions;
using Microsoft.Extensions.Logging;
using DSharpPlus.SlashCommands;
using DSharpPlus.SlashCommands.Attributes;
using DSharpPlus.SlashCommands.EventArgs;
using SupportChild.Commands;
namespace SupportChild
namespace SupportChild;
internal static class EventHandler
{
internal class EventHandler
internal static Task OnReady(DiscordClient client, ReadyEventArgs e)
{
private DiscordClient discordClient;
Logger.Log("Client is ready to process events.");
//DateTime for the end of the cooldown
private static Dictionary<ulong, DateTime> reactionTicketCooldowns = new Dictionary<ulong, DateTime>();
public EventHandler(DiscordClient client)
// Checking activity type
if (!Enum.TryParse(Config.presenceType, true, out ActivityType activityType))
{
this.discordClient = client;
Logger.Log("Presence type '" + Config.presenceType + "' invalid, using 'Playing' instead.");
activityType = ActivityType.Playing;
}
internal Task OnReady(DiscordClient client, ReadyEventArgs e)
client.UpdateStatusAsync(new DiscordActivity(Config.presenceText, activityType), UserStatus.Online);
return Task.CompletedTask;
}
internal static Task OnGuildAvailable(DiscordClient _, GuildCreateEventArgs e)
{
Logger.Log("Guild available: " + e.Guild.Name);
IReadOnlyDictionary<ulong, DiscordRole> roles = e.Guild.Roles;
foreach ((ulong roleID, DiscordRole role) in roles)
{
discordClient.Logger.Log(LogLevel.Information, "Client is ready to process events.");
Logger.Log(role.Name.PadRight(40, '.') + roleID);
}
return Task.CompletedTask;
}
// Checking activity type
if (!Enum.TryParse(Config.presenceType, true, out ActivityType activityType))
{
Console.WriteLine("Presence type '" + Config.presenceType + "' invalid, using 'Playing' instead.");
activityType = ActivityType.Playing;
}
internal static Task OnClientError(DiscordClient _, ClientErrorEventArgs e)
{
Logger.Error("Client exception occured:\n" + e.Exception);
switch (e.Exception)
{
case BadRequestException ex:
Logger.Error("JSON Message: " + ex.JsonMessage);
break;
}
return Task.CompletedTask;
}
this.discordClient.UpdateStatusAsync(new DiscordActivity(Config.presenceText, activityType), UserStatus.Online);
return Task.CompletedTask;
internal static async Task OnMessageCreated(DiscordClient client, MessageCreateEventArgs e)
{
if (e.Author.IsBot)
{
return;
}
internal Task OnGuildAvailable(DiscordClient client, GuildCreateEventArgs e)
// Check if ticket exists in the database and ticket notifications are enabled
if (!Database.TryGetOpenTicket(e.Channel.Id, out Database.Ticket ticket) || !Config.ticketUpdatedNotifications)
{
discordClient.Logger.Log(LogLevel.Information, $"Guild available: {e.Guild.Name}");
IReadOnlyDictionary<ulong, DiscordRole> roles = e.Guild.Roles;
foreach ((ulong roleID, DiscordRole role) in roles)
{
discordClient.Logger.Log(LogLevel.Information, role.Name.PadRight(40, '.') + roleID);
}
return Task.CompletedTask;
return;
}
internal Task OnClientError(DiscordClient client, ClientErrorEventArgs e)
// Sends a DM to the assigned staff member if at least a day has gone by since the last message and the user sending the message isn't staff
IReadOnlyList<DiscordMessage> messages = await e.Channel.GetMessagesAsync(2);
if (messages.Count > 1 && messages[1].Timestamp < DateTimeOffset.UtcNow.AddDays(Config.ticketUpdatedNotificationDelay * -1) && !Database.IsStaff(e.Author.Id))
{
discordClient.Logger.Log(LogLevel.Error, $"Exception occured: {e.Exception.GetType()}: {e.Exception}");
return Task.CompletedTask;
}
internal async Task OnMessageCreated(DiscordClient client, MessageCreateEventArgs e)
{
if (e.Author.IsBot)
try
{
return;
}
// Check if ticket exists in the database and ticket notifications are enabled
if (!Database.TryGetOpenTicket(e.Channel.Id, out Database.Ticket ticket) || !Config.ticketUpdatedNotifications)
{
return;
}
// Sends a DM to the assigned staff member if at least a day has gone by since the last message and the user sending the message isn't staff
IReadOnlyList<DiscordMessage> messages = await e.Channel.GetMessagesAsync(2);
if (messages.Count > 1 && messages[1].Timestamp < DateTimeOffset.UtcNow.AddDays(Config.ticketUpdatedNotificationDelay * -1) && !Database.IsStaff(e.Author.Id))
{
try
DiscordMember staffMember = await e.Guild.GetMemberAsync(ticket.assignedStaffID);
await staffMember.SendMessageAsync(new DiscordEmbedBuilder
{
DiscordEmbed message = new DiscordEmbedBuilder
{
Color = DiscordColor.Green,
Description = "A ticket you are assigned to has been updated: " + e.Channel.Mention
};
DiscordMember staffMember = await e.Guild.GetMemberAsync(ticket.assignedStaffID);
await staffMember.SendMessageAsync(message);
}
catch (NotFoundException) { }
catch (UnauthorizedException) { }
Color = DiscordColor.Green,
Description = "A ticket you are assigned to has been updated: " + e.Channel.Mention
});
}
catch (NotFoundException) { }
catch (UnauthorizedException) { }
}
}
internal Task OnCommandError(CommandsNextExtension commandSystem, CommandErrorEventArgs e)
internal static async Task OnCommandError(SlashCommandsExtension commandSystem, SlashCommandErrorEventArgs e)
{
switch (e.Exception)
{
switch (e.Exception)
{
case CommandNotFoundException _:
return Task.CompletedTask;
case ChecksFailedException _:
case SlashExecutionChecksFailedException checksFailedException:
{
foreach (SlashCheckBaseAttribute attr in checksFailedException.FailedChecks)
{
foreach (CheckBaseAttribute attr in ((ChecksFailedException)e.Exception).FailedChecks)
{
DiscordEmbed error = new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = this.ParseFailedCheck(attr)
};
e.Context?.Channel?.SendMessageAsync(error);
}
return Task.CompletedTask;
}
default:
{
discordClient.Logger.Log(LogLevel.Error, $"Exception occured: {e.Exception.GetType()}: {e.Exception}");
DiscordEmbed error = new DiscordEmbedBuilder
await e.Context.Channel.SendMessageAsync(new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = "Internal error occured, please report this to the developer."
};
e.Context?.Channel?.SendMessageAsync(error);
return Task.CompletedTask;
Description = ParseFailedCheck(attr)
});
}
}
return;
}
case BadRequestException ex:
Logger.Error("Command exception occured:\n" + e.Exception);
Logger.Error("JSON Message: " + ex.JsonMessage);
return;
default:
{
Logger.Error("Exception occured: " + e.Exception.GetType() + ": " + e.Exception);
await e.Context.Channel.SendMessageAsync(new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = "Internal error occured, please report this to the developer."
});
return;
}
}
}
internal static async Task OnMemberAdded(DiscordClient client, GuildMemberAddEventArgs e)
{
if (!Database.TryGetOpenTickets(e.Member.Id, out List<Database.Ticket> ownTickets))
{
return;
}
internal async Task OnReactionAdded(DiscordClient client, MessageReactionAddEventArgs e)
foreach (Database.Ticket ticket in ownTickets)
{
if (e.Message.Id != Config.reactionMessage) return;
DiscordGuild guild = e.Message.Channel.Guild;
DiscordMember member = await guild.GetMemberAsync(e.User.Id);
if (!Config.HasPermission(member, "new") || Database.IsBlacklisted(member.Id)) return;
if (reactionTicketCooldowns.ContainsKey(member.Id))
try
{
if (reactionTicketCooldowns[member.Id] > DateTime.Now) return; // cooldown has not expired
else reactionTicketCooldowns.Remove(member.Id); // cooldown exists but has expired, delete it
}
DiscordChannel category = guild.GetChannel(Config.ticketCategory);
DiscordChannel ticketChannel = await guild.CreateChannelAsync("ticket", ChannelType.Text, category);
if (ticketChannel == null) return;
ulong staffID = 0;
if (Config.randomAssignment)
{
staffID = Database.GetRandomActiveStaff(0)?.userID ?? 0;
}
long id = Database.NewTicket(member.Id, staffID, ticketChannel.Id);
reactionTicketCooldowns.Add(member.Id, DateTime.Now.AddSeconds(10)); // add a cooldown which expires in 10 seconds
string ticketID = id.ToString("00000");
await ticketChannel.ModifyAsync(model => model.Name = "ticket-" + ticketID);
await ticketChannel.AddOverwriteAsync(member, Permissions.AccessChannels, Permissions.None);
await ticketChannel.SendMessageAsync("Hello, " + member.Mention + "!\n" + Config.welcomeMessage);
// Remove user's reaction
await e.Message.DeleteReactionAsync(e.Emoji, e.User);
// Refreshes the channel as changes were made to it above
ticketChannel = await SupportChild.GetClient().GetChannelAsync(ticketChannel.Id);
if (staffID != 0)
{
DiscordEmbed assignmentMessage = new DiscordEmbedBuilder
DiscordChannel channel = await client.GetChannelAsync(ticket.channelID);
if (channel?.GuildId == e.Guild.Id)
{
Color = DiscordColor.Green,
Description = "Ticket was randomly assigned to <@" + staffID + ">."
};
await ticketChannel.SendMessageAsync(assignmentMessage);
if (Config.assignmentNotifications)
{
DiscordEmbed message = new DiscordEmbedBuilder
await channel.SendMessageAsync(new DiscordEmbedBuilder
{
Color = DiscordColor.Green,
Description = "You have been randomly assigned to a newly opened support ticket: " +
ticketChannel.Mention
};
try
{
DiscordMember staffMember = await guild.GetMemberAsync(staffID);
await staffMember.SendMessageAsync(message);
}
catch (NotFoundException)
{
}
catch (UnauthorizedException)
{
}
Description = "User '" + e.Member.Username + "#" + e.Member.Discriminator + "' has rejoined the server, and has been re-added to the ticket."
});
}
}
// Log it if the log channel exists
DiscordChannel logChannel = guild.GetChannel(Config.logChannel);
if (logChannel != null)
{
DiscordEmbed logMessage = new DiscordEmbedBuilder
{
Color = DiscordColor.Green,
Description = "Ticket " + ticketChannel.Mention + " opened by " + member.Mention + ".\n",
Footer = new DiscordEmbedBuilder.EmbedFooter {Text = "Ticket " + ticketID}
};
await logChannel.SendMessageAsync(logMessage);
}
catch (Exception) { /* ignored */ }
}
}
internal async Task OnMemberAdded(DiscordClient client, GuildMemberAddEventArgs e)
internal static async Task OnMemberRemoved(DiscordClient client, GuildMemberRemoveEventArgs e)
{
if (Database.TryGetOpenTickets(e.Member.Id, out List<Database.Ticket> ownTickets))
{
if (!Database.TryGetOpenTickets(e.Member.Id, out List<Database.Ticket> ownTickets))
{
return;
}
foreach (Database.Ticket ticket in ownTickets)
{
try
@ -226,82 +156,120 @@ namespace SupportChild
DiscordChannel channel = await client.GetChannelAsync(ticket.channelID);
if (channel?.GuildId == e.Guild.Id)
{
await channel.AddOverwriteAsync(e.Member, Permissions.AccessChannels, Permissions.None);
DiscordEmbed message = new DiscordEmbedBuilder()
.WithColor(DiscordColor.Green)
.WithDescription("User '" + e.Member.Username + "#" + e.Member.Discriminator + "' has rejoined the server, and has been re-added to the ticket.");
await channel.SendMessageAsync(message);
await channel.SendMessageAsync(new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = "User '" + e.Member.Username + "#" + e.Member.Discriminator + "' has left the server."
});
}
}
catch (Exception) { }
catch (Exception) { /* ignored */ }
}
}
internal async Task OnMemberRemoved(DiscordClient client, GuildMemberRemoveEventArgs e)
if (Database.TryGetAssignedTickets(e.Member.Id, out List<Database.Ticket> assignedTickets) && Config.logChannel != 0)
{
if (Database.TryGetOpenTickets(e.Member.Id, out List<Database.Ticket> ownTickets))
DiscordChannel logChannel = await client.GetChannelAsync(Config.logChannel);
if (logChannel != null)
{
foreach(Database.Ticket ticket in ownTickets)
foreach (Database.Ticket ticket in assignedTickets)
{
try
{
DiscordChannel channel = await client.GetChannelAsync(ticket.channelID);
if (channel?.GuildId == e.Guild.Id)
{
DiscordEmbed message = new DiscordEmbedBuilder()
.WithColor(DiscordColor.Red)
.WithDescription("User '" + e.Member.Username + "#" + e.Member.Discriminator + "' has left the server.");
await channel.SendMessageAsync(message);
}
}
catch (Exception) { }
}
}
if (Database.TryGetAssignedTickets(e.Member.Id, out List<Database.Ticket> assignedTickets) && Config.logChannel != 0)
{
DiscordChannel logChannel = await client.GetChannelAsync(Config.logChannel);
if (logChannel != null)
{
foreach (Database.Ticket ticket in assignedTickets)
{
try
{
DiscordChannel channel = await client.GetChannelAsync(ticket.channelID);
if (channel?.GuildId == e.Guild.Id)
await logChannel.SendMessageAsync(new DiscordEmbedBuilder
{
DiscordEmbed message = new DiscordEmbedBuilder()
.WithColor(DiscordColor.Red)
.WithDescription("Assigned staff member '" + e.Member.Username + "#" + e.Member.Discriminator + "' has left the server: <#" + channel.Id + ">");
await logChannel.SendMessageAsync(message);
}
Color = DiscordColor.Red,
Description = "Assigned staff member '" + e.Member.Username + "#" + e.Member.Discriminator + "' has left the server: <#" + channel.Id + ">"
});
}
catch (Exception) { }
}
catch (Exception) { /* ignored */ }
}
}
}
private string ParseFailedCheck(CheckBaseAttribute attr)
{
switch (attr)
{
case CooldownAttribute _:
return "You cannot use do that so often!";
case RequireOwnerAttribute _:
return "Only the server owner can use that command!";
case RequirePermissionsAttribute _:
return "You don't have permission to do that!";
case RequireRolesAttribute _:
return "You do not have a required role!";
case RequireUserPermissionsAttribute _:
return "You don't have permission to do that!";
case RequireNsfwAttribute _:
return "This command can only be used in an NSFW channel!";
default:
return "Unknown Discord API error occured, please try again later.";
}
}
}
internal static async Task OnComponentInteractionCreated(DiscordClient client, ComponentInteractionCreateEventArgs e)
{
try
{
switch (e.Interaction.Data.ComponentType)
{
case ComponentType.Button:
switch (e.Id)
{
case "supportchild_closeconfirm":
await CloseCommand.OnConfirmed(e.Interaction);
return;
case { } when e.Id.StartsWith("supportchild_newcommandbutton"):
await NewCommand.OnCategorySelection(e.Interaction);
return;
case { } when e.Id.StartsWith("supportchild_newticketbutton"):
await CreateButtonPanelCommand.OnButtonUsed(e.Interaction);
return;
case "right":
return;
case "left":
return;
case "rightskip":
return;
case "leftskip":
return;
case "stop":
return;
default:
Logger.Warn("Unknown button press received! '" + e.Id + "'");
return;
}
case ComponentType.Select:
switch (e.Id)
{
case { } when e.Id.StartsWith("supportchild_newcommandselector"):
await NewCommand.OnCategorySelection(e.Interaction);
return;
case { } when e.Id.StartsWith("supportchild_newticketselector"):
await CreateSelectionBoxPanelCommand.OnSelectionMenuUsed(e.Interaction);
return;
default:
Logger.Warn("Unknown selection box option received! '" + e.Id + "'");
return;
}
case ComponentType.ActionRow:
Logger.Warn("Unknown action row received! '" + e.Id + "'");
return;
case ComponentType.FormInput:
Logger.Warn("Unknown form input received! '" + e.Id + "'");
return;
default:
Logger.Warn("Unknown interaction type received! '" + e.Interaction.Data.ComponentType + "'");
break;
}
}
catch (DiscordException ex)
{
Logger.Error("Interaction Exception occurred: " + ex);
Logger.Error("JsomMessage: " + ex.JsonMessage);
}
catch (Exception ex)
{
Logger.Error("Interaction Exception occured: " + ex.GetType() + ": " + ex);
}
}
private static string ParseFailedCheck(SlashCheckBaseAttribute attr)
{
return attr switch
{
SlashRequireDirectMessageAttribute => "This command can only be used in direct messages!",
SlashRequireOwnerAttribute => "Only the server owner can use that command!",
SlashRequirePermissionsAttribute => "You don't have permission to do that!",
SlashRequireBotPermissionsAttribute => "The bot doesn't have the required permissions to do that!",
SlashRequireUserPermissionsAttribute => "You don't have permission to do that!",
SlashRequireGuildAttribute => "This command has to be used in a Discord server!",
_ => "Unknown Discord API error occured, please try again later."
};
}
}

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
// Sets up a dummy client to use for logging
public static DiscordClient discordClient = new DiscordClient(new DiscordConfiguration { Token = "DUMMY_TOKEN", TokenType = TokenType.Bot, MinimumLogLevel = LogLevel.Debug });
private static SlashCommandsExtension commands = null;
private static void Main()
{
internal static SupportChild instance;
MainAsync().GetAwaiter().GetResult();
}
private DiscordClient discordClient = null;
private CommandsNextExtension commands = null;
private EventHandler eventHandler;
static void Main(string[] args)
private static async Task MainAsync()
{
Logger.Log("Starting " + Assembly.GetEntryAssembly()?.GetName().Name + " version " + GetVersion() + "...");
try
{
new SupportChild().MainAsync().GetAwaiter().GetResult();
Reload();
// Block this task until the program is closed.
await Task.Delay(-1);
}
private async Task MainAsync()
catch (Exception e)
{
instance = this;
Console.WriteLine("Starting SupportChild version " + GetVersion() + "...");
try
{
this.Reload();
// Block this task until the program is closed.
await Task.Delay(-1);
}
catch (Exception e)
{
Console.WriteLine("Fatal error:");
Console.WriteLine(e);
Console.ReadLine();
}
}
public static DiscordClient GetClient()
{
return instance.discordClient;
}
public static string GetVersion()
{
Version version = Assembly.GetEntryAssembly()?.GetName().Version;
return version?.Major + "." + version?.Minor + "." + version?.Build + (version?.Revision == 0 ? "" : "-" + (char)(64 + version?.Revision ?? 0));
}
public async void Reload()
{
if (this.discordClient != null)
{
await this.discordClient.DisconnectAsync();
this.discordClient.Dispose();
Console.WriteLine("Discord client disconnected.");
}
Console.WriteLine("Loading config \"" + Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar + "config.yml\"");
Config.LoadConfig();
// Check if token is unset
if (Config.token == "<add-token-here>" || Config.token == "")
{
Console.WriteLine("You need to set your bot token in the config and start the bot again.");
throw new ArgumentException("Invalid Discord bot token");
}
// Database connection and setup
try
{
Console.WriteLine("Connecting to database... (" + Config.hostName + ":" + Config.port + ")");
Database.SetConnectionString(Config.hostName, Config.port, Config.database, Config.username, Config.password);
Database.SetupTables();
}
catch (Exception e)
{
Console.WriteLine("Could not set up database tables, please confirm connection settings, status of the server and permissions of MySQL user. Error: " + e);
throw;
}
Console.WriteLine("Setting up Discord client...");
// Checking log level
if (!Enum.TryParse(Config.logLevel, true, out LogLevel logLevel))
{
Console.WriteLine("Log level '" + Config.logLevel + "' invalid, using 'Information' instead.");
logLevel = LogLevel.Information;
}
// Setting up client configuration
DiscordConfiguration cfg = new DiscordConfiguration
{
Token = Config.token,
TokenType = TokenType.Bot,
MinimumLogLevel = logLevel,
AutoReconnect = true,
Intents = DiscordIntents.All
};
this.discordClient = new DiscordClient(cfg);
this.eventHandler = new EventHandler(this.discordClient);
Console.WriteLine("Hooking events...");
this.discordClient.Ready += this.eventHandler.OnReady;
this.discordClient.GuildAvailable += this.eventHandler.OnGuildAvailable;
this.discordClient.ClientErrored += this.eventHandler.OnClientError;
this.discordClient.MessageCreated += this.eventHandler.OnMessageCreated;
this.discordClient.GuildMemberAdded += this.eventHandler.OnMemberAdded;
this.discordClient.GuildMemberRemoved += this.eventHandler.OnMemberRemoved;
if (Config.reactionMessage != 0)
{
this.discordClient.MessageReactionAdded += this.eventHandler.OnReactionAdded;
}
Console.WriteLine("Registering commands...");
commands = discordClient.UseCommandsNext(new CommandsNextConfiguration
{
StringPrefixes = new []{ Config.prefix }
});
this.commands.RegisterCommands<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>();
Console.WriteLine("Hooking command events...");
this.commands.CommandErrored += this.eventHandler.OnCommandError;
Console.WriteLine("Connecting to Discord...");
await this.discordClient.ConnectAsync();
Logger.Fatal("Fatal error:\n" + e);
Console.ReadLine();
}
}
public static string GetVersion()
{
Version version = Assembly.GetEntryAssembly()?.GetName().Version;
return version?.Major + "." + version?.Minor + "." + version?.Build + (version?.Revision == 0 ? "" : "-" + (char)(64 + version?.Revision ?? 0));
}
public static async void Reload()
{
if (discordClient != null)
{
await discordClient.DisconnectAsync();
discordClient.Dispose();
Logger.Log("Discord client disconnected.");
}
Logger.Log("Loading config \"" + Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar + "config.yml\"");
Config.LoadConfig();
// Check if token is unset
if (Config.token is "<add-token-here>" or "")
{
Logger.Fatal("You need to set your bot token in the config and start the bot again.");
throw new ArgumentException("Invalid Discord bot token");
}
// Database connection and setup
try
{
Logger.Log("Connecting to database... (" + Config.hostName + ":" + Config.port + ")");
Database.SetConnectionString(Config.hostName, Config.port, Config.database, Config.username, Config.password);
Database.SetupTables();
}
catch (Exception e)
{
Logger.Fatal("Could not set up database tables, please confirm connection settings, status of the server and permissions of MySQL user. Error: " + e);
throw;
}
Logger.Log("Setting up Discord client...");
// Setting up client configuration
DiscordConfiguration cfg = new DiscordConfiguration
{
Token = Config.token,
TokenType = TokenType.Bot,
MinimumLogLevel = Config.logLevel,
AutoReconnect = true,
Intents = DiscordIntents.All
};
discordClient = new DiscordClient(cfg);
Logger.Log("Hooking events...");
discordClient.Ready += EventHandler.OnReady;
discordClient.GuildAvailable += EventHandler.OnGuildAvailable;
discordClient.ClientErrored += EventHandler.OnClientError;
discordClient.MessageCreated += EventHandler.OnMessageCreated;
discordClient.GuildMemberAdded += EventHandler.OnMemberAdded;
discordClient.GuildMemberRemoved += EventHandler.OnMemberRemoved;
discordClient.ComponentInteractionCreated += EventHandler.OnComponentInteractionCreated;
discordClient.UseInteractivity(new InteractivityConfiguration
{
AckPaginationButtons = true,
PaginationBehaviour = PaginationBehaviour.Ignore,
PaginationDeletion = PaginationDeletion.DeleteMessage,
Timeout = TimeSpan.FromMinutes(15)
});
Logger.Log("Registering commands...");
commands = discordClient.UseSlashCommands();
commands.RegisterCommands<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>();
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,58 +13,58 @@
<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" />
<PackageReference Include="WebMarkupMin.Core" Version="2.9.0" />
<PackageReference Include="YamlDotNet" Version="12.0.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
<EmbeddedResource Update="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
</EmbeddedResource>
<Folder Include="lib\" />
</ItemGroup>
<ItemGroup>
<None Include="..\LICENSE">
<Pack>True</Pack>
<PackagePath></PackagePath>
</None>
<Reference Include="DiscordChatExporter.Core">
<HintPath>lib\DiscordChatExporter.Core.dll</HintPath>
</Reference>
</ItemGroup>
<ItemGroup>
<Folder Include="lib\" />
</ItemGroup>
<ItemGroup>
<Reference Include="DiscordChatExporter.Core">
<HintPath>lib\DiscordChatExporter.Core.dll</HintPath>
</Reference>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
</ItemGroup>
</Project>

View file

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

View file

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

View file

@ -1,84 +1,48 @@
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."
# Decides what messages are shown in console
# Possible values are: Critical, Error, Warning, Information, Debug.
console-log-level: "Information"
# Format for timestamps in transcripts and google sheets if used
timestamp-format: "yyyy-MM-dd HH:mm"
# Whether or not staff members should be randomly assigned tickets when they are made. Individual staff members can opt out using the toggleactive command.
random-assignment: true
# If set to true the rasssign command will include staff members set as inactive if a specific role is specified in the command.
# This can be useful if you have admins set as inactive to not automatically recieve tickets and then have moderators elevate tickets when needed.
random-assign-role-override: true
# Sets the type of activity for the bot to display in its presence status
# Possible values are: Playing, Streaming, ListeningTo, Watching, Competing
presence-type: "ListeningTo"
# Sets the activity text shown in the bot's status
presence-text: "-new"
# Bot token.
token: "<add-token-here>"
# Channel where ticket logs are posted (recommended)
log-channel: 000000000000000000
# Message posted when a ticket is opened.
welcome-message: "Please describe your issue below, and include all information needed for us to take action."
# Decides what messages are shown in console
# Possible values are: Critical, Error, Warning, Information, Debug.
console-log-level: "Information"
# One of the following: LongDate, LongDateTime, LongTime, RelativeTime, ShortDate, ShortDateTime, ShortTime
# More info: https://dsharpplus.github.io/api/DSharpPlus.TimestampFormat.html
timestamp-format: "RelativeTime"
# Whether or not staff members should be randomly assigned tickets when they are made. Individual staff members can opt out using the toggleactive command.
random-assignment: true
# If set to true the rasssign command will include staff members set as inactive if a specific role is specified in the command.
# This can be useful if you have admins set as inactive to not automatically receive tickets and then have moderators elevate tickets when needed.
random-assign-role-override: true
# Sets the type of activity for the bot to display in its presence status
# Possible values are: Playing, Streaming, ListeningTo, Watching, Competing
presence-type: "ListeningTo"
# Sets the activity text shown in the bot's status
presence-text: "/new"
# Set to true if you want the /new command to show a selection box instead of a series of buttons
new-command-uses-selector: false
# Number of tickets a single user can have open at a time, staff members are excluded from this
ticket-limit: 5
notifications:
# Notifies the assigned staff member when a new message is posted in a ticket if the ticket has been silent for a configurable amount of time
# Other staff members and bots do not trigger this.
ticket-updated: true
# The above notification will only be sent if the ticket has been silent for more than this amount of days. Default is 0.5 days.
ticket-updated-delay: 0.5
# Notifies staff when they are assigned to tickets
assignment: true
# Notifies the user opening the ticket that their ticket was closed and includes the transcript
closing: true
# Notifies the assigned staff member when a new message is posted in a ticket if the ticket has been silent for a configurable amount of time
# Other staff members and bots do not trigger this.
ticket-updated: true
# The above notification will only be sent if the ticket has been silent for more than this amount of days. Default is 0.5 days.
ticket-updated-delay: 0.5
# Notifies staff when they are assigned to tickets
assignment: true
# Notifies the user opening the ticket that their ticket was closed and includes the transcript
closing: true
database:
# Address and port of the mysql server
address: "127.0.0.1"
port: 3306
# Name of the database to use
name: "supportchild"
# Username and password for authentication
user: ""
password: ""
# Set up which roles are allowed to use different commands.
# Example:
# new: [ 000000000000000000, 111111111111111111 ]
# They are grouped into suggested command groups below for first time setup.
permissions:
# Public commands
close: []
list: []
new: []
say: []
status: []
summary: []
transcript: []
# Moderator commands
add: []
addmessage: []
assign: []
blacklist: []
listassigned: []
listoldest: []
listunassigned: []
move: []
rassign: []
removemessage: []
setsummary: []
toggleactive: []
unassign: []
unblacklist: []
# Admin commands
addstaff: []
reload: []
removestaff: []
setticket: []
unsetticket: []
# Address and port of the mysql server
address: "127.0.0.1"
port: 3306
# Name of the database to use
name: "supportchild"
# Username and password for authentication
user: ""
password: ""