diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..1ff0c42 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,63 @@ +############################################################################### +# Set default behavior to automatically normalize line endings. +############################################################################### +* text=auto + +############################################################################### +# Set default behavior for command prompt diff. +# +# This is need for earlier builds of msysgit that does not have it on by +# default for csharp files. +# Note: This is only used by command line +############################################################################### +#*.cs diff=csharp + +############################################################################### +# Set the merge driver for project and solution files +# +# Merging from the command prompt will add diff markers to the files if there +# are conflicts (Merging from VS is not affected by the settings below, in VS +# the diff markers are never inserted). Diff markers may cause the following +# file extensions to fail to load in VS. An alternative would be to treat +# these files as binary and thus will always conflict and require user +# intervention with every merge. To do so, just uncomment the entries below +############################################################################### +#*.sln merge=binary +#*.csproj merge=binary +#*.vbproj merge=binary +#*.vcxproj merge=binary +#*.vcproj merge=binary +#*.dbproj merge=binary +#*.fsproj merge=binary +#*.lsproj merge=binary +#*.wixproj merge=binary +#*.modelproj merge=binary +#*.sqlproj merge=binary +#*.wwaproj merge=binary + +############################################################################### +# behavior for image files +# +# image files are treated as binary by default. +############################################################################### +#*.jpg binary +#*.png binary +#*.gif binary + +############################################################################### +# diff behavior for common document formats +# +# Convert binary document formats to text before diffing them. This feature +# is only available from the command line. Turn it on by uncommenting the +# entries below. +############################################################################### +#*.doc diff=astextplain +#*.DOC diff=astextplain +#*.docx diff=astextplain +#*.DOCX diff=astextplain +#*.dot diff=astextplain +#*.DOT diff=astextplain +#*.pdf diff=astextplain +#*.PDF diff=astextplain +#*.rtf diff=astextplain +#*.RTF diff=astextplain diff --git a/.gitignore b/.gitignore index 1806fcf..f8206f5 100644 --- a/.gitignore +++ b/.gitignore @@ -1,10 +1,369 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore -/.idea -/.vs -/bin -/obj +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates -/config.yml -/transcripts -/Linux-x64 -/Windows-x64 \ No newline at end of file +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Oo]ut/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd + +# Manually added folders +Windows-x64/ +Linux-x64/ +.idea +.vs diff --git a/Commands/AddCategoryCommand.cs b/Commands/AddCategoryCommand.cs deleted file mode 100644 index 650f8f0..0000000 --- a/Commands/AddCategoryCommand.cs +++ /dev/null @@ -1,71 +0,0 @@ -using System.Threading.Tasks; -using DSharpPlus.Entities; -using DSharpPlus.SlashCommands; -using DSharpPlus.SlashCommands.Attributes; - -namespace SupportChild.Commands; - -public class AddCategoryCommand : ApplicationCommandModule -{ - [SlashRequireGuild] - [SlashCommand("addcategory", "Adds a category to the ticket bot letting users open tickets in them.")] - public async Task OnExecute(InteractionContext command, [Option("Title", "The name to display on buttons and in selection boxes.")] string title, [Option("Category", "The category to add.")] DiscordChannel category) - { - if (!category.IsCategory) - { - await command.CreateResponseAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Red, - Description = "That channel is not a category." - }, true); - return; - } - - if (string.IsNullOrWhiteSpace(title)) - { - await command.CreateResponseAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Red, - Description = "Invalid category title specified." - }, true); - return; - } - - if (Database.TryGetCategory(category.Id, out Database.Category _)) - { - await command.CreateResponseAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Red, - Description = "That category is already registered." - }, true); - return; - } - - if (Database.TryGetCategory(title, out Database.Category _)) - { - await command.CreateResponseAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Red, - Description = "There is already a category with that title." - }, true); - return; - } - - if (Database.AddCategory(title, category.Id)) - { - await command.CreateResponseAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Green, - Description = "Category added." - }, true); - } - else - { - await command.CreateResponseAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Red, - Description = "Error: Failed adding the category to the database." - }, true); - } - } -} \ No newline at end of file diff --git a/Commands/AddCommand.cs b/Commands/AddCommand.cs deleted file mode 100644 index a404c37..0000000 --- a/Commands/AddCommand.cs +++ /dev/null @@ -1,82 +0,0 @@ -using System; -using System.Threading.Tasks; -using DSharpPlus; -using DSharpPlus.Entities; -using DSharpPlus.SlashCommands; -using DSharpPlus.SlashCommands.Attributes; - -namespace SupportChild.Commands; - -public class AddCommand : ApplicationCommandModule -{ - [SlashRequireGuild] - [SlashCommand("add", "Adds a user to a ticket")] - public async Task OnExecute(InteractionContext command, [Option("User", "User to add to ticket.")] DiscordUser user) - { - // Check if ticket exists in the database - if (!Database.IsOpenTicket(command.Channel.Id)) - { - await command.CreateResponseAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Red, - Description = "This channel is not a ticket." - }, true); - return; - } - - DiscordMember member; - try - { - member = (user == null ? command.Member : await command.Guild.GetMemberAsync(user.Id)); - - if (member == null) - { - await command.CreateResponseAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Red, - Description = "Could not find that user in this server." - }, true); - return; - } - } - catch (Exception) - { - await command.CreateResponseAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Red, - Description = "Could not find that user in this server." - }, true); - return; - } - - try - { - await command.Channel.AddOverwriteAsync(member, Permissions.AccessChannels); - await command.CreateResponseAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Green, - Description = "Added " + member.Mention + " to ticket." - }); - - // Log it if the log channel exists - DiscordChannel logChannel = command.Guild.GetChannel(Config.logChannel); - if (logChannel != null) - { - await logChannel.SendMessageAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Green, - Description = member.Mention + " was added to " + command.Channel.Mention + - " by " + command.Member.Mention + "." - }); - } - } - catch (Exception) - { - await command.CreateResponseAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Red, - Description = "Could not add " + member.Mention + " to ticket, unknown error occured." - }, true); - } - } -} \ No newline at end of file diff --git a/Commands/AddMessageCommand.cs b/Commands/AddMessageCommand.cs deleted file mode 100644 index f9ee009..0000000 --- a/Commands/AddMessageCommand.cs +++ /dev/null @@ -1,53 +0,0 @@ -using DSharpPlus.Entities; -using System.Threading.Tasks; -using DSharpPlus.SlashCommands; -using DSharpPlus.SlashCommands.Attributes; - -namespace SupportChild.Commands; - -public class AddMessageCommand : ApplicationCommandModule -{ - [SlashRequireGuild] - [SlashCommand("addmessage", "Adds a new message for the 'say' command.")] - public async Task OnExecute(InteractionContext command, - [Option("Identifier", "The identifier word used in the /say command.")] string identifier, - [Option("Message", "The message the /say command will return.")] string message) - { - if (string.IsNullOrEmpty(message)) - { - await command.CreateResponseAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Red, - Description = "No message specified." - }, true); - return; - } - - if (Database.TryGetMessage(identifier.ToLower(), out Database.Message _)) - { - await command.CreateResponseAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Red, - Description = "There is already a message with that identifier." - }, true); - return; - } - - if (Database.AddMessage(identifier, command.Member.Id, message)) - { - await command.CreateResponseAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Green, - Description = "Message added." - }, true); - } - else - { - await command.CreateResponseAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Red, - Description = "Error: Failed adding the message to the database." - }, true); - } - } -} \ No newline at end of file diff --git a/Commands/AddStaffCommand.cs b/Commands/AddStaffCommand.cs deleted file mode 100644 index f8fa8d0..0000000 --- a/Commands/AddStaffCommand.cs +++ /dev/null @@ -1,67 +0,0 @@ -using System; -using System.Threading.Tasks; -using DSharpPlus.Entities; -using DSharpPlus.SlashCommands; -using DSharpPlus.SlashCommands.Attributes; -using MySqlConnector; - -namespace SupportChild.Commands; - -public class AddStaffCommand : ApplicationCommandModule -{ - [SlashRequireGuild] - [SlashCommand("addstaff", "Adds a new staff member.")] - public async Task OnExecute(InteractionContext command, [Option("User", "User to add to staff.")] DiscordUser user) - { - DiscordMember staffMember = null; - try - { - staffMember = user == null ? command.Member : await command.Guild.GetMemberAsync(user.Id); - - if (staffMember == null) - { - await command.CreateResponseAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Red, - Description = "Could not find that user in this server." - }, true); - return; - } - } - catch (Exception) - { - await command.CreateResponseAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Red, - Description = "Could not find that user in this server." - }, true); - return; - } - - await using MySqlConnection c = Database.GetConnection(); - MySqlCommand cmd = Database.IsStaff(staffMember.Id) ? new MySqlCommand(@"UPDATE staff SET name = @name WHERE user_id = @user_id", c) : new MySqlCommand(@"INSERT INTO staff (user_id, name) VALUES (@user_id, @name);", c); - - c.Open(); - cmd.Parameters.AddWithValue("@user_id", staffMember.Id); - cmd.Parameters.AddWithValue("@name", staffMember.DisplayName); - cmd.ExecuteNonQuery(); - cmd.Dispose(); - - await command.CreateResponseAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Green, - Description = staffMember.Mention + " was added to staff." - }); - - // Log it if the log channel exists - DiscordChannel logChannel = command.Guild.GetChannel(Config.logChannel); - if (logChannel != null) - { - await logChannel.SendMessageAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Green, - Description = staffMember.Mention + " was added to staff.\n" - }); - } - } -} \ No newline at end of file diff --git a/Commands/AdminCommands.cs b/Commands/AdminCommands.cs deleted file mode 100644 index d4f0aa2..0000000 --- a/Commands/AdminCommands.cs +++ /dev/null @@ -1,200 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using DSharpPlus.Entities; -using DSharpPlus.Interactivity; -using DSharpPlus.Interactivity.Extensions; -using DSharpPlus.SlashCommands; -using DSharpPlus.SlashCommands.Attributes; - -namespace SupportChild.Commands; - -[SlashCommandGroup("admin", "Administrative commands.")] -public class AdminCommands : ApplicationCommandModule -{ - [SlashRequireGuild] - [SlashCommand("listinvalid", "List tickets which channels have been deleted. Use /admin unsetticket to remove them.")] - public async Task ListInvalid(InteractionContext command) - { - if (!Database.TryGetOpenTickets(out List openTickets)) - { - await command.CreateResponseAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Red, - Description = "Could not get any open tickets from database." - }, true); - } - - // Get all channels in all guilds the bot is part of - List allChannels = new List(); - foreach (KeyValuePair guild in SupportChild.discordClient.Guilds) - { - try - { - allChannels.AddRange(await guild.Value.GetChannelsAsync()); - } - catch (Exception) { /*ignored*/ } - } - - // Check which tickets channels no longer exist - List listItems = new List(); - foreach (Database.Ticket ticket in openTickets) - { - if (allChannels.All(channel => channel.Id != ticket.channelID)) - { - listItems.Add("ID: **" + ticket.id.ToString("00000") + ":** <#" + ticket.channelID + ">\n"); - } - } - - if (listItems.Count == 0) - { - await command.CreateResponseAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Green, - Description = "All tickets are valid!" - }, true); - return; - } - - List embeds = new List(); - foreach (string message in Utilities.ParseListIntoMessages(listItems)) - { - embeds.Add(new DiscordEmbedBuilder - { - Title = "Invalid tickets:", - Color = DiscordColor.Red, - Description = message - }); - } - - // Add the footers - for (int i = 0; i < embeds.Count; i++) - { - embeds[i].Footer = new DiscordEmbedBuilder.EmbedFooter - { - Text = $"Page {i + 1} / {embeds.Count}" - }; - } - - List listPages = new List(); - foreach (DiscordEmbedBuilder embed in embeds) - { - listPages.Add(new Page("", embed)); - } - - await command.Interaction.SendPaginatedResponseAsync(true, command.User, listPages); - } - - [SlashRequireGuild] - [SlashCommand("setticket", "Turns a channel into a ticket WARNING: Anyone will be able to delete the channel using /close.")] - public async Task SetTicket(InteractionContext command, [Option("User", "(Optional) The owner of the ticket.")] DiscordUser user = null) - { - // Check if ticket exists in the database - if (Database.IsOpenTicket(command.Channel.Id)) - { - await command.CreateResponseAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Red, - Description = "This channel is already a ticket." - }, true); - return; - } - - DiscordUser ticketUser = (user == null ? command.User : user); - - long id = Database.NewTicket(ticketUser.Id, 0, command.Channel.Id); - string ticketID = id.ToString("00000"); - await command.CreateResponseAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Green, - Description = "Channel has been designated ticket " + ticketID + "." - }); - - // Log it if the log channel exists - DiscordChannel logChannel = command.Guild.GetChannel(Config.logChannel); - if (logChannel != null) - { - await logChannel.SendMessageAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Green, - Description = command.Channel.Mention + " has been designated ticket " + ticketID + " by " + command.Member.Mention + "." - }); - } - } - - [SlashRequireGuild] - [SlashCommand("unsetticket", "Deletes a ticket from the ticket system without deleting the channel.")] - public async Task UnsetTicket(InteractionContext command, [Option("TicketID", "(Optional) Ticket to unset. Uses the channel you are in by default.")] long ticketID = 0) - { - Database.Ticket ticket; - - if (ticketID == 0) - { - // Check if ticket exists in the database - if (!Database.TryGetOpenTicket(command.Channel.Id, out ticket)) - { - await command.CreateResponseAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Red, - Description = "This channel is not a ticket!" - }, true); - return; - } - } - else - { - // Check if ticket exists in the database - if (!Database.TryGetOpenTicketByID((uint)ticketID, out ticket)) - { - await command.CreateResponseAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Red, - Description = "There is no ticket with this ticket ID." - }, true); - return; - } - } - - - if (Database.DeleteOpenTicket(ticket.id)) - { - await command.CreateResponseAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Green, - Description = "Channel has been undesignated as a ticket." - }); - - // Log it if the log channel exists - DiscordChannel logChannel = command.Guild.GetChannel(Config.logChannel); - if (logChannel != null) - { - await logChannel.SendMessageAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Green, - Description = command.Channel.Mention + " has been undesignated as a ticket by " + command.Member.Mention + "." - }); - } - } - else - { - await command.CreateResponseAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Red, - Description = "Error: Failed removing ticket from database." - }, true); - } - } - - [SlashCommand("reload", "Reloads the bot config.")] - public async Task Reload(InteractionContext command) - { - await command.CreateResponseAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Green, - Description = "Reloading bot application..." - }); - Logger.Log("Reloading bot..."); - SupportChild.Reload(); - } -} \ No newline at end of file diff --git a/Commands/AssignCommand.cs b/Commands/AssignCommand.cs deleted file mode 100644 index 0e04060..0000000 --- a/Commands/AssignCommand.cs +++ /dev/null @@ -1,102 +0,0 @@ -using System; -using System.Threading.Tasks; -using DSharpPlus.Entities; -using DSharpPlus.Exceptions; -using DSharpPlus.SlashCommands; -using DSharpPlus.SlashCommands.Attributes; - -namespace SupportChild.Commands; - -public class AssignCommand : ApplicationCommandModule -{ - [SlashRequireGuild] - [SlashCommand("assign", "Assigns a staff member to this ticket.")] - public async Task OnExecute(InteractionContext command, [Option("User", "(Optional) User to assign to this ticket.")] DiscordUser user = null) - { - DiscordMember member = null; - try - { - member = user == null ? command.Member : await command.Guild.GetMemberAsync(user.Id); - - if (member == null) - { - await command.CreateResponseAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Red, - Description = "Could not find that user in this server." - }, true); - return; - } - } - catch (Exception) - { - await command.CreateResponseAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Red, - Description = "Could not find that user in this server." - }, true); - return; - } - - // Check if ticket exists in the database - if (!Database.TryGetOpenTicket(command.Channel.Id, out Database.Ticket ticket)) - { - await command.CreateResponseAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Red, - Description = "This channel is not a ticket." - }, true); - return; - } - - if (!Database.IsStaff(member.Id)) - { - await command.CreateResponseAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Red, - Description = "Error: User is not registered as staff." - }, true); - return; - } - - if (!Database.AssignStaff(ticket, member.Id)) - { - await command.CreateResponseAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Red, - Description = "Error: Failed to assign " + member.Mention + " to ticket." - }, true); - return; - } - - await command.CreateResponseAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Green, - Description = "Assigned " + member.Mention + " to ticket." - }); - - if (Config.assignmentNotifications) - { - try - { - await member.SendMessageAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Green, - Description = "You have been assigned to a support ticket: " + command.Channel.Mention - }); - } - catch (UnauthorizedException) { } - } - - // Log it if the log channel exists - DiscordChannel logChannel = command.Guild.GetChannel(Config.logChannel); - if (logChannel != null) - { - await logChannel.SendMessageAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Green, - Description = member.Mention + " was assigned to " + command.Channel.Mention + " by " + command.Member.Mention + "." - }); - } - } -} \ No newline at end of file diff --git a/Commands/BlacklistCommand.cs b/Commands/BlacklistCommand.cs deleted file mode 100644 index abfe22f..0000000 --- a/Commands/BlacklistCommand.cs +++ /dev/null @@ -1,54 +0,0 @@ -using System; -using System.Threading.Tasks; -using DSharpPlus.Entities; -using DSharpPlus.SlashCommands; -using DSharpPlus.SlashCommands.Attributes; - -namespace SupportChild.Commands; - -public class BlacklistCommand : ApplicationCommandModule -{ - [SlashRequireGuild] - [SlashCommand("blacklist", "Blacklists a user from opening tickets.")] - public async Task OnExecute(InteractionContext command, [Option("User", "User to blacklist.")] DiscordUser user) - { - try - { - if (!Database.Blacklist(user.Id, command.User.Id)) - { - await command.CreateResponseAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Red, - Description = user.Mention + " is already blacklisted." - }, true); - return; - } - - await command.CreateResponseAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Green, - Description = "Blacklisted " + user.Mention + "." - }, true); - - // Log it if the log channel exists - DiscordChannel logChannel = command.Guild.GetChannel(Config.logChannel); - if (logChannel != null) - { - await logChannel.SendMessageAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Green, - Description = user.Mention + " was blacklisted from opening tickets by " + command.Member.Mention + "." - }); - } - } - catch (Exception) - { - await command.CreateResponseAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Red, - Description = "Error occured while blacklisting " + user.Mention + "." - }, true); - throw; - } - } -} \ No newline at end of file diff --git a/Commands/CloseCommand.cs b/Commands/CloseCommand.cs deleted file mode 100644 index e020554..0000000 --- a/Commands/CloseCommand.cs +++ /dev/null @@ -1,146 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Threading.Tasks; -using DSharpPlus; -using DSharpPlus.Entities; -using DSharpPlus.Exceptions; -using DSharpPlus.SlashCommands; -using DSharpPlus.SlashCommands.Attributes; - -namespace SupportChild.Commands; - -public class CloseCommand : ApplicationCommandModule -{ - private static Dictionary closeReasons = new Dictionary(); - - [SlashRequireGuild] - [SlashCommand("close", "Closes a ticket.")] - public async Task OnExecute(InteractionContext command, [Option("Reason", "(Optional) Reason for closing the ticket.")] string reason = "") - { - // Check if ticket exists in the database - if (!Database.TryGetOpenTicket(command.Channel.Id, out Database.Ticket _)) - { - await command.CreateResponseAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Red, - Description = "This channel is not a ticket." - }); - return; - } - - DiscordInteractionResponseBuilder confirmation = new DiscordInteractionResponseBuilder() - .AddEmbed(new DiscordEmbedBuilder - { - Color = DiscordColor.Cyan, - Description = "Are you sure you wish to close this ticket? You cannot re-open it again later." - }) - .AddComponents(new DiscordButtonComponent(ButtonStyle.Danger, "supportchild_closeconfirm", "Confirm")); - - await command.CreateResponseAsync(confirmation); - closeReasons.Add(command.Channel.Id, reason); - } - - public static async Task OnConfirmed(DiscordInteraction interaction) - { - await interaction.CreateResponseAsync(InteractionResponseType.DeferredMessageUpdate); - ulong channelID = interaction.Channel.Id; - string channelName = interaction.Channel.Name; - - // Check if ticket exists in the database - if (!Database.TryGetOpenTicket(channelID, out Database.Ticket ticket)) - { - await interaction.EditOriginalResponseAsync(new DiscordWebhookBuilder().AddEmbed(new DiscordEmbedBuilder - { - Color = DiscordColor.Red, - Description = "This channel is not a ticket." - })); - return; - } - - // Build transcript - try - { - await Transcriber.ExecuteAsync(interaction.Channel.Id, ticket.id); - } - catch (Exception e) - { - Logger.Error("Exception occured when trying to save transcript while closing ticket: " + e); - await interaction.EditOriginalResponseAsync(new DiscordWebhookBuilder().AddEmbed(new DiscordEmbedBuilder - { - Color = DiscordColor.Red, - Description = "ERROR: Could not save transcript file. Aborting..." - })); - return; - } - - string closeReason = ""; - if (closeReasons.TryGetValue(channelID, out string cachedReason)) - { - closeReason = "\nReason: " + cachedReason + "\n"; - } - - // Log it if the log channel exists - DiscordChannel logChannel = interaction.Guild.GetChannel(Config.logChannel); - if (logChannel != null) - { - DiscordEmbed embed = new DiscordEmbedBuilder - { - Color = DiscordColor.Green, - Description = "Ticket " + ticket.id.ToString("00000") + " closed by " + - interaction.User.Mention + ".\n" + closeReason, - Footer = new DiscordEmbedBuilder.EmbedFooter { Text = '#' + channelName } - }; - - await using FileStream file = new FileStream(Transcriber.GetPath(ticket.id), FileMode.Open, FileAccess.Read); - DiscordMessageBuilder message = new DiscordMessageBuilder(); - message.AddEmbed(embed); - message.AddFiles(new Dictionary { { Transcriber.GetFilename(ticket.id), file } }); - - await logChannel.SendMessageAsync(message); - } - - if (Config.closingNotifications) - { - DiscordEmbed embed = new DiscordEmbedBuilder - { - Color = DiscordColor.Green, - Description = "Ticket " + ticket.id.ToString("00000") + " which you opened has now been closed, " + - "check the transcript for more info.\n" + closeReason, - Footer = new DiscordEmbedBuilder.EmbedFooter { Text = '#' + channelName } - }; - - try - { - DiscordMember staffMember = await interaction.Guild.GetMemberAsync(ticket.creatorID); - await using FileStream file = new FileStream(Transcriber.GetPath(ticket.id), FileMode.Open, FileAccess.Read); - - DiscordMessageBuilder message = new DiscordMessageBuilder(); - message.AddEmbed(embed); - message.AddFiles(new Dictionary { { Transcriber.GetFilename(ticket.id), file } }); - - await staffMember.SendMessageAsync(message); - } - catch (NotFoundException) { } - catch (UnauthorizedException) { } - } - - Database.ArchiveTicket(ticket); - - await interaction.EditOriginalResponseAsync(new DiscordWebhookBuilder().AddEmbed(new DiscordEmbedBuilder - { - Color = DiscordColor.Green, - Description = "Channel will be deleted in 3 seconds..." - })); - - - await Task.Delay(3000); - - // Delete the channel and database entry - await interaction.Channel.DeleteAsync("Ticket closed."); - - Database.DeleteOpenTicket(ticket.id); - - closeReasons.Remove(channelID); - } -} \ No newline at end of file diff --git a/Commands/CreateButtonPanelCommand.cs b/Commands/CreateButtonPanelCommand.cs deleted file mode 100644 index e022519..0000000 --- a/Commands/CreateButtonPanelCommand.cs +++ /dev/null @@ -1,81 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using DSharpPlus; -using DSharpPlus.Entities; -using DSharpPlus.SlashCommands; -using DSharpPlus.SlashCommands.Attributes; - -namespace SupportChild.Commands; - -public class CreateButtonPanelCommand : ApplicationCommandModule -{ - [SlashRequireGuild] - [SlashCommand("createbuttonpanel", "Creates a series of buttons which users can use to open new tickets in specific categories.")] - public async Task OnExecute(InteractionContext command) - { - DiscordMessageBuilder builder = new DiscordMessageBuilder().WithContent(" "); - List verifiedCategories = await Utilities.GetVerifiedChannels(); - - if (verifiedCategories.Count == 0) - { - await command.CreateResponseAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Red, - Description = "Error: No registered categories found." - }, true); - return; - } - - verifiedCategories = verifiedCategories.OrderBy(x => x.name).ToList(); - - int nrOfButtons = 0; - for (int nrOfButtonRows = 0; nrOfButtonRows < 5 && nrOfButtons < verifiedCategories.Count; nrOfButtonRows++) - { - List buttonRow = new List(); - - for (; nrOfButtons < 5 * (nrOfButtonRows + 1) && nrOfButtons < verifiedCategories.Count; nrOfButtons++) - { - buttonRow.Add(new DiscordButtonComponent(ButtonStyle.Primary, "supportchild_newticketbutton " + verifiedCategories[nrOfButtons].id, verifiedCategories[nrOfButtons].name)); - } - builder.AddComponents(buttonRow); - } - - await command.Channel.SendMessageAsync(builder); - await command.CreateResponseAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Green, - Description = "Successfully created message, make sure to run this command again if you add new categories to the bot." - }, true); - } - - public static async Task OnButtonUsed(DiscordInteraction interaction) - { - await interaction.CreateResponseAsync(InteractionResponseType.DeferredChannelMessageWithSource, new DiscordInteractionResponseBuilder().AsEphemeral()); - - if (!ulong.TryParse(interaction.Data.CustomId.Replace("supportchild_newticketbutton ", ""), out ulong categoryID) || categoryID == 0) - { - Logger.Warn("Invalid ID: " + interaction.Data.CustomId.Replace("supportchild_newticketbutton ", "")); - return; - } - - (bool success, string message) = await NewCommand.OpenNewTicket(interaction.User.Id, interaction.ChannelId, categoryID); - - if (success) - { - await interaction.CreateFollowupMessageAsync(new DiscordFollowupMessageBuilder().AddEmbed(new DiscordEmbedBuilder - { - Color = DiscordColor.Green, - Description = message - })); - } - else - { - await interaction.CreateFollowupMessageAsync(new DiscordFollowupMessageBuilder().AddEmbed(new DiscordEmbedBuilder - { - Color = DiscordColor.Red, - Description = message - })); - } - } -} \ No newline at end of file diff --git a/Commands/CreateSelectionBoxPanelCommand.cs b/Commands/CreateSelectionBoxPanelCommand.cs deleted file mode 100644 index 573073b..0000000 --- a/Commands/CreateSelectionBoxPanelCommand.cs +++ /dev/null @@ -1,89 +0,0 @@ -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using DSharpPlus; -using DSharpPlus.Entities; -using DSharpPlus.SlashCommands; -using DSharpPlus.SlashCommands.Attributes; - -namespace SupportChild.Commands; - -public class CreateSelectionBoxPanelCommand : ApplicationCommandModule -{ - [SlashRequireGuild] - [SlashCommand("createselectionboxpanel", "Creates a selection box which users can use to open new tickets in specific categories.")] - public async Task OnExecute(InteractionContext command, [Option("Message", "(Optional) The message to show in the selection box.")] string message = null) - { - DiscordMessageBuilder builder = new DiscordMessageBuilder() - .WithContent(" ") - .AddComponents(await GetSelectComponents(command, message ?? "Open new ticket...")); - - await command.Channel.SendMessageAsync(builder); - await command.CreateResponseAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Green, - Description = "Successfully created message, make sure to run this command again if you add new categories to the bot." - }, true); - } - - public static async Task> GetSelectComponents(InteractionContext command, string placeholder) - { - List verifiedCategories = await Utilities.GetVerifiedChannels(); - - if (verifiedCategories.Count == 0) - { - return new List(); - } - - verifiedCategories = verifiedCategories.OrderBy(x => x.name).ToList(); - List selectionComponents = new List(); - - int selectionOptions = 0; - for (int selectionBoxes = 0; selectionBoxes < 5 && selectionOptions < verifiedCategories.Count; selectionBoxes++) - { - List categoryOptions = new List(); - - for (; selectionOptions < 25 * (selectionBoxes + 1) && selectionOptions < verifiedCategories.Count; selectionOptions++) - { - categoryOptions.Add(new DiscordSelectComponentOption(verifiedCategories[selectionOptions].name, verifiedCategories[selectionOptions].id.ToString())); - } - selectionComponents.Add(new DiscordSelectComponent("supportchild_newticketselector" + selectionBoxes, placeholder, categoryOptions, false, 0, 1)); - } - - return selectionComponents; - } - - public static async Task OnSelectionMenuUsed(DiscordInteraction interaction) - { - if (interaction.Data.Values == null || interaction.Data.Values.Length <= 0) - { - return; - } - - if (!ulong.TryParse(interaction.Data.Values[0], out ulong categoryID) || categoryID == 0) - { - return; - } - - await interaction.CreateResponseAsync(InteractionResponseType.DeferredChannelMessageWithSource, new DiscordInteractionResponseBuilder().AsEphemeral()); - - (bool success, string message) = await NewCommand.OpenNewTicket(interaction.User.Id, interaction.ChannelId, categoryID); - - if (success) - { - await interaction.CreateFollowupMessageAsync(new DiscordFollowupMessageBuilder().AddEmbed(new DiscordEmbedBuilder - { - Color = DiscordColor.Green, - Description = message - }).AsEphemeral()); - } - else - { - await interaction.CreateFollowupMessageAsync(new DiscordFollowupMessageBuilder().AddEmbed(new DiscordEmbedBuilder - { - Color = DiscordColor.Red, - Description = message - }).AsEphemeral()); - } - } -} \ No newline at end of file diff --git a/Commands/ListAssignedCommand.cs b/Commands/ListAssignedCommand.cs deleted file mode 100644 index e47fe0c..0000000 --- a/Commands/ListAssignedCommand.cs +++ /dev/null @@ -1,63 +0,0 @@ -using System.Collections.Generic; -using System.Threading.Tasks; -using DSharpPlus.Entities; -using DSharpPlus.Interactivity; -using DSharpPlus.Interactivity.Extensions; -using DSharpPlus.SlashCommands; -using DSharpPlus.SlashCommands.Attributes; - -namespace SupportChild.Commands; - -public class ListAssignedCommand : ApplicationCommandModule -{ - [SlashRequireGuild] - [SlashCommand("listassigned", "Lists tickets assigned to a user.")] - public async Task OnExecute(InteractionContext command, [Option("User", "(Optional) User to list tickets for.")] DiscordUser user = null) - { - DiscordUser listUser = user == null ? command.User : user; - - if (!Database.TryGetAssignedTickets(listUser.Id, out List assignedTickets)) - { - await command.CreateResponseAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Red, - Description = "User does not have any assigned tickets." - }); - return; - } - - List listItems = new List(); - foreach (Database.Ticket ticket in assignedTickets) - { - listItems.Add("**" + ticket.DiscordRelativeTime() + ":** <#" + ticket.channelID + "> by <@" + ticket.creatorID + ">\n"); - } - - List embeds = new List(); - foreach (string message in Utilities.ParseListIntoMessages(listItems)) - { - embeds.Add(new DiscordEmbedBuilder - { - Title = "Assigned tickets: ", - Color = DiscordColor.Green, - Description = message - }); - } - - // Add the footers - for (int i = 0; i < embeds.Count; i++) - { - embeds[i].Footer = new DiscordEmbedBuilder.EmbedFooter - { - Text = $"Page {i + 1} / {embeds.Count}" - }; - } - - List listPages = new List(); - foreach (DiscordEmbedBuilder embed in embeds) - { - listPages.Add(new Page("", embed)); - } - - await command.Interaction.SendPaginatedResponseAsync(true, command.User, listPages); - } -} \ No newline at end of file diff --git a/Commands/ListCommand.cs b/Commands/ListCommand.cs deleted file mode 100644 index 4c6fd8f..0000000 --- a/Commands/ListCommand.cs +++ /dev/null @@ -1,99 +0,0 @@ -using System.Collections.Generic; -using System.Threading.Tasks; -using DSharpPlus.Entities; -using DSharpPlus.Interactivity; -using DSharpPlus.Interactivity.Extensions; -using DSharpPlus.SlashCommands; -using DSharpPlus.SlashCommands.Attributes; - -namespace SupportChild.Commands; - -public class ListCommand : ApplicationCommandModule -{ - [SlashRequireGuild] - [SlashCommand("list", "Lists tickets opened by a user.")] - public async Task OnExecute(InteractionContext command, [Option("User", "(Optional) The user to get tickets by.")] DiscordUser user = null) - { - DiscordUser listUser = user == null ? command.User : user; - - List openEmbeds = new List(); - if (Database.TryGetOpenTickets(listUser.Id, out List openTickets)) - { - List listItems = new List(); - foreach (Database.Ticket ticket in openTickets) - { - listItems.Add("**" + ticket.DiscordRelativeTime() + ":** <#" + ticket.channelID + ">\n"); - } - - foreach (string message in Utilities.ParseListIntoMessages(listItems)) - { - openEmbeds.Add(new DiscordEmbedBuilder - { - Color = DiscordColor.Green, - Description = message - }); - } - - // Add the titles - for (int i = 0; i < openEmbeds.Count; i++) - { - openEmbeds[i].Title = $"Open tickets ({i + 1}/{openEmbeds.Count})"; - } - } - - List closedEmbeds = new List(); - if (Database.TryGetClosedTickets(listUser.Id, out List closedTickets)) - { - List listItems = new List(); - foreach (Database.Ticket ticket in closedTickets) - { - listItems.Add("**" + ticket.DiscordRelativeTime() + ":** Ticket " + ticket.id.ToString("00000") + "\n"); - } - - foreach (string message in Utilities.ParseListIntoMessages(listItems)) - { - closedEmbeds.Add(new DiscordEmbedBuilder - { - Color = DiscordColor.Red, - Description = message - }); - } - - // Add the titles - for (int i = 0; i < closedEmbeds.Count; i++) - { - closedEmbeds[i].Title = $"Closed tickets ({i + 1}/{closedEmbeds.Count})"; - } - } - - // Merge the embed lists and add the footers - List embeds = new List(); - embeds.AddRange(openEmbeds); - embeds.AddRange(closedEmbeds); - for (int i = 0; i < embeds.Count; i++) - { - embeds[i].Footer = new DiscordEmbedBuilder.EmbedFooter - { - Text = $"Page {i + 1} / {embeds.Count}" - }; - } - - if (embeds.Count == 0) - { - await command.CreateResponseAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Cyan, - Description = "User does not have any open or closed tickets." - }); - return; - } - - List listPages = new List(); - foreach (DiscordEmbedBuilder embed in embeds) - { - listPages.Add(new Page("", embed)); - } - - await command.Interaction.SendPaginatedResponseAsync(true, command.User, listPages); - } -} \ No newline at end of file diff --git a/Commands/ListOpen.cs b/Commands/ListOpen.cs deleted file mode 100644 index d484ced..0000000 --- a/Commands/ListOpen.cs +++ /dev/null @@ -1,60 +0,0 @@ -using System.Collections.Generic; -using System.Threading.Tasks; -using DSharpPlus.Entities; -using DSharpPlus.Interactivity; -using DSharpPlus.Interactivity.Extensions; -using DSharpPlus.SlashCommands; -using DSharpPlus.SlashCommands.Attributes; - -namespace SupportChild.Commands; - -public class ListOpen : ApplicationCommandModule -{ - [SlashRequireGuild] - [SlashCommand("listopen", "Lists all open tickets, oldest first.")] - public async Task OnExecute(InteractionContext command) - { - if (!Database.TryGetOpenTickets(out List openTickets)) - { - await command.CreateResponseAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Red, - Description = "Could not fetch any open tickets." - }); - return; - } - - List listItems = new List(); - foreach (Database.Ticket ticket in openTickets) - { - listItems.Add("**" + ticket.DiscordRelativeTime() + ":** <#" + ticket.channelID + "> by <@" + ticket.creatorID + ">\n"); - } - - List embeds = new List(); - foreach (string message in Utilities.ParseListIntoMessages(listItems)) - { - embeds.Add(new DiscordEmbedBuilder - { - Color = DiscordColor.Green, - Description = message - }); - } - - // Add the footers - for (int i = 0; i < embeds.Count; i++) - { - embeds[i].Footer = new DiscordEmbedBuilder.EmbedFooter - { - Text = $"Page {i + 1} / {embeds.Count}" - }; - } - - List listPages = new List(); - foreach (DiscordEmbedBuilder embed in embeds) - { - listPages.Add(new Page("", embed)); - } - - await command.Interaction.SendPaginatedResponseAsync(true, command.User, listPages); - } -} \ No newline at end of file diff --git a/Commands/ListUnassignedCommand.cs b/Commands/ListUnassignedCommand.cs deleted file mode 100644 index 14ee13b..0000000 --- a/Commands/ListUnassignedCommand.cs +++ /dev/null @@ -1,61 +0,0 @@ -using System.Collections.Generic; -using System.Threading.Tasks; -using DSharpPlus.Entities; -using DSharpPlus.Interactivity; -using DSharpPlus.Interactivity.Extensions; -using DSharpPlus.SlashCommands; -using DSharpPlus.SlashCommands.Attributes; - -namespace SupportChild.Commands; - -public class ListUnassignedCommand : ApplicationCommandModule -{ - [SlashRequireGuild] - [SlashCommand("listunassigned", "Lists unassigned tickets.")] - public async Task OnExecute(InteractionContext command) - { - if (!Database.TryGetAssignedTickets(0, out List unassignedTickets)) - { - await command.CreateResponseAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Green, - Description = "There are no unassigned tickets." - }); - return; - } - - List listItems = new List(); - foreach (Database.Ticket ticket in unassignedTickets) - { - listItems.Add("**" + ticket.DiscordRelativeTime() + ":** <#" + ticket.channelID + "> by <@" + ticket.creatorID + ">\n"); - } - - List embeds = new List(); - foreach (string message in Utilities.ParseListIntoMessages(listItems)) - { - embeds.Add(new DiscordEmbedBuilder - { - Title = "Unassigned tickets: ", - Color = DiscordColor.Green, - Description = message - }); - } - - // Add the footers - for (int i = 0; i < embeds.Count; i++) - { - embeds[i].Footer = new DiscordEmbedBuilder.EmbedFooter - { - Text = $"Page {i + 1} / {embeds.Count}" - }; - } - - List listPages = new List(); - foreach (DiscordEmbedBuilder embed in embeds) - { - listPages.Add(new Page("", embed)); - } - - await command.Interaction.SendPaginatedResponseAsync(true, command.User, listPages); - } -} \ No newline at end of file diff --git a/Commands/MoveCommand.cs b/Commands/MoveCommand.cs deleted file mode 100644 index 97d70c6..0000000 --- a/Commands/MoveCommand.cs +++ /dev/null @@ -1,83 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using DSharpPlus.Entities; -using DSharpPlus.Exceptions; -using DSharpPlus.SlashCommands; -using DSharpPlus.SlashCommands.Attributes; - -namespace SupportChild.Commands; - -public class MoveCommand : ApplicationCommandModule -{ - [SlashRequireGuild] - [SlashCommand("move", "Moves a ticket to another category.")] - public async Task OnExecute(InteractionContext command, [Option("Category", "The category to move the ticket to. Only has to be the beginning of the name.")] string category) - { - // Check if ticket exists in the database - if (!Database.TryGetOpenTicket(command.Channel.Id, out Database.Ticket _)) - { - await command.CreateResponseAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Red, - Description = "This channel is not a ticket." - }, true); - return; - } - - if (string.IsNullOrEmpty(category)) - { - await command.CreateResponseAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Red, - Description = "Error: No category provided." - }, true); - return; - } - - IReadOnlyList channels = await command.Guild.GetChannelsAsync(); - IEnumerable categories = channels.Where(x => x.IsCategory); - DiscordChannel categoryChannel = categories.FirstOrDefault(x => x.Name.StartsWith(category.Trim(), StringComparison.OrdinalIgnoreCase)); - - if (categoryChannel == null) - { - await command.CreateResponseAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Red, - Description = "Error: Could not find a category by that name." - }, true); - return; - } - - if (command.Channel.Id == categoryChannel.Id) - { - await command.CreateResponseAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Red, - Description = "Error: The ticket is already in that category." - }, true); - return; - } - - try - { - await command.Channel.ModifyAsync(modifiedAttributes => modifiedAttributes.Parent = categoryChannel); - } - catch (UnauthorizedException) - { - await command.CreateResponseAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Red, - Description = "Error: Not authorized to move this ticket to that category." - }, true); - return; - } - - await command.CreateResponseAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Green, - Description = "Ticket was moved to " + categoryChannel.Mention - }); - } -} \ No newline at end of file diff --git a/Commands/NewCommand.cs b/Commands/NewCommand.cs deleted file mode 100644 index c914f3a..0000000 --- a/Commands/NewCommand.cs +++ /dev/null @@ -1,284 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using DSharpPlus; -using DSharpPlus.Entities; -using DSharpPlus.Exceptions; -using DSharpPlus.SlashCommands; -using DSharpPlus.SlashCommands.Attributes; - -namespace SupportChild.Commands; - -public class NewCommand : ApplicationCommandModule -{ - [SlashRequireGuild] - [SlashCommand("new", "Opens a new ticket.")] - public async Task OnExecute(InteractionContext command) - { - List verifiedCategories = await Utilities.GetVerifiedChannels(); - switch (verifiedCategories.Count) - { - case 0: - await command.CreateResponseAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Red, - Description = "Error: No registered categories found." - }, true); - return; - case 1: - await command.DeferAsync(true); - (bool success, string message) = await OpenNewTicket(command.User.Id, command.Channel.Id, verifiedCategories[0].id); - - if (success) - { - await command.FollowUpAsync(new DiscordFollowupMessageBuilder().AddEmbed(new DiscordEmbedBuilder - { - Color = DiscordColor.Green, - Description = message - }).AsEphemeral()); - } - else - { - await command.FollowUpAsync(new DiscordFollowupMessageBuilder().AddEmbed(new DiscordEmbedBuilder - { - Color = DiscordColor.Red, - Description = message - }).AsEphemeral()); - } - return; - default: - if (Config.newCommandUsesSelector) - { - await CreateSelector(command, verifiedCategories); - } - else - { - await CreateButtons(command, verifiedCategories); - } - return; - } - } - - public static async Task CreateButtons(InteractionContext command, List verifiedCategories) - { - DiscordInteractionResponseBuilder builder = new DiscordInteractionResponseBuilder().WithContent(" "); - - int nrOfButtons = 0; - for (int nrOfButtonRows = 0; nrOfButtonRows < 5 && nrOfButtons < verifiedCategories.Count; nrOfButtonRows++) - { - List buttonRow = new List(); - - for (; nrOfButtons < 5 * (nrOfButtonRows + 1) && nrOfButtons < verifiedCategories.Count; nrOfButtons++) - { - buttonRow.Add(new DiscordButtonComponent(ButtonStyle.Primary, "supportchild_newcommandbutton " + verifiedCategories[nrOfButtons].id, verifiedCategories[nrOfButtons].name)); - } - builder.AddComponents(buttonRow); - } - - await command.CreateResponseAsync(builder.AsEphemeral()); - } - - public static async Task CreateSelector(InteractionContext command, List verifiedCategories) - { - verifiedCategories = verifiedCategories.OrderBy(x => x.name).ToList(); - List selectionComponents = new List(); - - int selectionOptions = 0; - for (int selectionBoxes = 0; selectionBoxes < 5 && selectionOptions < verifiedCategories.Count; selectionBoxes++) - { - List categoryOptions = new List(); - - for (; selectionOptions < 25 * (selectionBoxes + 1) && selectionOptions < verifiedCategories.Count; selectionOptions++) - { - categoryOptions.Add(new DiscordSelectComponentOption(verifiedCategories[selectionOptions].name, verifiedCategories[selectionOptions].id.ToString())); - } - selectionComponents.Add(new DiscordSelectComponent("supportchild_newcommandselector" + selectionBoxes, "Open new ticket...", categoryOptions, false, 0, 1)); - } - - await command.CreateResponseAsync(new DiscordInteractionResponseBuilder().AddComponents(selectionComponents).AsEphemeral()); - } - - public static async Task OnCategorySelection(DiscordInteraction interaction) - { - string stringID; - switch (interaction.Data.ComponentType) - { - case ComponentType.Button: - stringID = interaction.Data.CustomId.Replace("supportchild_newcommandbutton ", ""); - break; - case ComponentType.StringSelect: - if (interaction.Data.Values == null || interaction.Data.Values.Length <= 0) - { - return; - } - stringID = interaction.Data.Values[0]; - break; - - case ComponentType.ActionRow: - case ComponentType.FormInput: - default: - return; - } - - if (!ulong.TryParse(stringID, out ulong categoryID) || categoryID == 0) - { - return; - } - - await interaction.CreateResponseAsync(InteractionResponseType.DeferredMessageUpdate, new DiscordInteractionResponseBuilder().AsEphemeral()); - - (bool success, string message) = await OpenNewTicket(interaction.User.Id, interaction.ChannelId, categoryID); - - if (success) - { - await interaction.EditOriginalResponseAsync(new DiscordWebhookBuilder().AddEmbed(new DiscordEmbedBuilder - { - Color = DiscordColor.Green, - Description = message - })); - } - else - { - await interaction.EditOriginalResponseAsync(new DiscordWebhookBuilder().AddEmbed(new DiscordEmbedBuilder - { - Color = DiscordColor.Red, - Description = message - })); - } - } - - public static async Task<(bool, string)> OpenNewTicket(ulong userID, ulong commandChannelID, ulong categoryID) - { - // Check if user is blacklisted - if (Database.IsBlacklisted(userID)) - { - return (false, "You are banned from opening tickets."); - } - - if (Database.IsOpenTicket(commandChannelID)) - { - return (false, "You cannot use this command in a ticket channel."); - } - - if (!Database.IsStaff(userID) && Database.TryGetOpenTickets(userID, out List ownTickets) && ownTickets.Count >= Config.ticketLimit) - { - return (false, "You have reached the limit for maximum open tickets."); - } - - DiscordChannel category = null; - try - { - category = await SupportChild.discordClient.GetChannelAsync(categoryID); - } - catch (Exception) { /*ignored*/ } - - if (category == null) - { - return (false, "Error: Could not find the category to place the ticket in."); - } - - DiscordMember member = null; - try - { - member = await category.Guild.GetMemberAsync(userID); - } - catch (Exception) { /*ignored*/ } - - if (member == null) - { - return (false, "Error: Could not find you on the Discord server."); - } - - DiscordChannel ticketChannel = null; - - try - { - ticketChannel = await category.Guild.CreateChannelAsync("ticket", ChannelType.Text, category); - } - catch (Exception) { /* ignored */ } - - if (ticketChannel == null) - { - return (false, "Error occured while creating ticket, " + member.Mention + - "!\nIs the channel limit reached in the server or ticket category?"); - } - - ulong staffID = 0; - if (Config.randomAssignment) - { - staffID = Database.GetRandomActiveStaff(0)?.userID ?? 0; - } - - long id = Database.NewTicket(member.Id, staffID, ticketChannel.Id); - string ticketID = id.ToString("00000"); - - try - { - await ticketChannel.ModifyAsync(modifiedAttributes => modifiedAttributes.Name = "ticket-" + ticketID); - } - catch (DiscordException e) - { - Logger.Error("Exception occurred trying to modify channel: " + e); - Logger.Error("JsomMessage: " + e.JsonMessage); - } - - try - { - await ticketChannel.AddOverwriteAsync(member, Permissions.AccessChannels); - } - catch (DiscordException e) - { - Logger.Error("Exception occurred trying to add channel permissions: " + e); - Logger.Error("JsomMessage: " + e.JsonMessage); - } - - await ticketChannel.SendMessageAsync("Hello, " + member.Mention + "!\n" + Config.welcomeMessage); - - // Refreshes the channel as changes were made to it above - ticketChannel = await SupportChild.discordClient.GetChannelAsync(ticketChannel.Id); - - if (staffID != 0) - { - await ticketChannel.SendMessageAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Green, - Description = "Ticket was randomly assigned to <@" + staffID + ">." - }); - - if (Config.assignmentNotifications) - { - try - { - DiscordMember staffMember = await category.Guild.GetMemberAsync(staffID); - await staffMember.SendMessageAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Green, - Description = "You have been randomly assigned to a newly opened support ticket: " + - ticketChannel.Mention - }); - } - catch (DiscordException e) - { - Logger.Error("Exception occurred assign random staff member: " + e); - Logger.Error("JsomMessage: " + e.JsonMessage); - } - } - } - - // Log it if the log channel exists - DiscordChannel logChannel = category.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); - } - - return (true, "Ticket opened, " + member.Mention + "!\n" + ticketChannel.Mention); - } -} \ No newline at end of file diff --git a/Commands/RandomAssignCommand.cs b/Commands/RandomAssignCommand.cs deleted file mode 100644 index dcacc3c..0000000 --- a/Commands/RandomAssignCommand.cs +++ /dev/null @@ -1,139 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using DSharpPlus.Entities; -using DSharpPlus.Exceptions; -using DSharpPlus.SlashCommands; -using DSharpPlus.SlashCommands.Attributes; -using Microsoft.Extensions.Logging; - -namespace SupportChild.Commands; - -public class RandomAssignCommand : ApplicationCommandModule -{ - [SlashRequireGuild] - [SlashCommand("rassign", "Randomly assigns a staff member to a ticket.")] - public async Task OnExecute(InteractionContext command, [Option("Role", "(Optional) Limit the random assignment to a specific role.")] DiscordRole role = null) - { - // Check if ticket exists in the database - if (!Database.TryGetOpenTicket(command.Channel.Id, out Database.Ticket ticket)) - { - await command.CreateResponseAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Red, - Description = "Error: This channel is not a ticket." - }, true); - return; - } - - // Get a random staff member who is verified to have the correct role if applicable - DiscordMember staffMember = await GetRandomVerifiedStaffMember(command, role, ticket); - if (staffMember == null) - { - return; - } - - // Attempt to assign the staff member to the ticket - if (!Database.AssignStaff(ticket, staffMember.Id)) - { - await command.CreateResponseAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Red, - Description = "Error: Failed to assign " + staffMember.Mention + " to ticket." - }, true); - return; - } - - // Respond that the command was successful - await command.CreateResponseAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Green, - Description = "Randomly assigned " + staffMember.Mention + " to ticket." - }); - - // Send a notification to the staff member if applicable - if (Config.assignmentNotifications) - { - try - { - await staffMember.SendMessageAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Green, - Description = "You have been randomly assigned to a support ticket: " + command.Channel.Mention - }); - } - catch (UnauthorizedException) { } - } - - // Log it if the log channel exists - DiscordChannel logChannel = command.Guild.GetChannel(Config.logChannel); - if (logChannel != null) - { - await logChannel.SendMessageAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Green, - Description = staffMember.Mention + " was randomly assigned to " + command.Channel.Mention + " by " + command.Member.Mention + "." - }); - } - } - - private static async Task GetRandomVerifiedStaffMember(InteractionContext command, DiscordRole targetRole, Database.Ticket ticket) - { - if (targetRole != null) // A role was provided - { - // Check if role rassign should override staff's active status - List staffMembers = Config.randomAssignRoleOverride - ? Database.GetAllStaff(ticket.assignedStaffID, ticket.creatorID) - : Database.GetActiveStaff(ticket.assignedStaffID, ticket.creatorID); - - // Randomize the list before checking for roles in order to reduce number of API calls - staffMembers.Shuffle(); - - // Get the first staff member that has the role - foreach (Database.StaffMember sm in staffMembers) - { - try - { - DiscordMember verifiedMember = await command.Guild.GetMemberAsync(sm.userID); - if (verifiedMember?.Roles?.Any(role => role.Id == targetRole.Id) ?? false) - { - return verifiedMember; - } - } - catch (Exception e) - { - command.Client.Logger.Log(LogLevel.Information, e, "Error occured trying to find a staff member in the rassign command."); - } - } - } - else // No role was specified, any active staff will be picked - { - Database.StaffMember staffEntry = Database.GetRandomActiveStaff(ticket.assignedStaffID, ticket.creatorID); - if (staffEntry == null) - { - await command.CreateResponseAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Red, - Description = "Error: There are no other staff members to choose from." - }, true); - return null; - } - - // Get the staff member from discord - try - { - return await command.Guild.GetMemberAsync(staffEntry.userID); - } - catch (NotFoundException) { } - } - - // Send a more generic error if we get to this point and still haven't found the staff member - await command.CreateResponseAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Red, - Description = "Error: Could not find an applicable staff member." - }, true); - return null; - } -} \ No newline at end of file diff --git a/Commands/RemoveCategoryCommand.cs b/Commands/RemoveCategoryCommand.cs deleted file mode 100644 index ab1120b..0000000 --- a/Commands/RemoveCategoryCommand.cs +++ /dev/null @@ -1,41 +0,0 @@ -using System.Threading.Tasks; -using DSharpPlus.Entities; -using DSharpPlus.SlashCommands; -using DSharpPlus.SlashCommands.Attributes; - -namespace SupportChild.Commands; - -public class RemoveCategoryCommand : ApplicationCommandModule -{ - [SlashRequireGuild] - [SlashCommand("removecategory", "Removes the ability for users to open tickets in a specific category.")] - public async Task OnExecute(InteractionContext command, [Option("Category", "The category to remove.")] DiscordChannel channel) - { - if (!Database.TryGetCategory(channel.Id, out Database.Category _)) - { - await command.CreateResponseAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Red, - Description = "That category is not registered." - }, true); - return; - } - - if (Database.RemoveCategory(channel.Id)) - { - await command.CreateResponseAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Green, - Description = "Category removed." - }, true); - } - else - { - await command.CreateResponseAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Red, - Description = "Error: Failed removing the category from the database." - }, true); - } - } -} \ No newline at end of file diff --git a/Commands/RemoveMessageCommand.cs b/Commands/RemoveMessageCommand.cs deleted file mode 100644 index 774d496..0000000 --- a/Commands/RemoveMessageCommand.cs +++ /dev/null @@ -1,41 +0,0 @@ -using DSharpPlus.Entities; -using System.Threading.Tasks; -using DSharpPlus.SlashCommands; -using DSharpPlus.SlashCommands.Attributes; - -namespace SupportChild.Commands; - -public class RemoveMessageCommand : ApplicationCommandModule -{ - [SlashRequireGuild] - [SlashCommand("removemessage", "Removes a message from the 'say' command.")] - public async Task OnExecute(InteractionContext command, [Option("Identifier", "The identifier word used in the /say command.")] string identifier) - { - if (!Database.TryGetMessage(identifier.ToLower(), out Database.Message _)) - { - await command.CreateResponseAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Red, - Description = "There is no message with that identifier." - }, true); - return; - } - - if (Database.RemoveMessage(identifier)) - { - await command.CreateResponseAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Green, - Description = "Message removed." - }, true); - } - else - { - await command.CreateResponseAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Red, - Description = "Error: Failed removing the message from the database." - }, true); - } - } -} \ No newline at end of file diff --git a/Commands/RemoveStaffCommand.cs b/Commands/RemoveStaffCommand.cs deleted file mode 100644 index 74d71e3..0000000 --- a/Commands/RemoveStaffCommand.cs +++ /dev/null @@ -1,49 +0,0 @@ -using System.Threading.Tasks; -using DSharpPlus.Entities; -using DSharpPlus.SlashCommands; -using DSharpPlus.SlashCommands.Attributes; -using MySqlConnector; - -namespace SupportChild.Commands; - -public class RemoveStaffCommand : ApplicationCommandModule -{ - [SlashRequireGuild] - [SlashCommand("removestaff", "Removes a staff member.")] - public async Task OnExecute(InteractionContext command, [Option("User", "User to remove from staff.")] DiscordUser user) - { - if (!Database.IsStaff(user.Id)) - { - await command.CreateResponseAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Red, - Description = "User is already not registered as staff." - }, true); - return; - } - - await using MySqlConnection c = Database.GetConnection(); - c.Open(); - MySqlCommand deletion = new MySqlCommand(@"DELETE FROM staff WHERE user_id=@user_id", c); - deletion.Parameters.AddWithValue("@user_id", user.Id); - deletion.Prepare(); - deletion.ExecuteNonQuery(); - - await command.CreateResponseAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Green, - Description = "User was removed from staff." - }, true); - - // Log it if the log channel exists - DiscordChannel logChannel = command.Guild.GetChannel(Config.logChannel); - if (logChannel != null) - { - await logChannel.SendMessageAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Green, - Description = "User was removed from staff.\n" - }); - } - } -} \ No newline at end of file diff --git a/Commands/SayCommand.cs b/Commands/SayCommand.cs deleted file mode 100644 index b60db54..0000000 --- a/Commands/SayCommand.cs +++ /dev/null @@ -1,88 +0,0 @@ -using DSharpPlus.Entities; -using System.Collections.Generic; -using System.Threading.Tasks; -using DSharpPlus.Interactivity; -using DSharpPlus.Interactivity.Extensions; -using DSharpPlus.SlashCommands; -using DSharpPlus.SlashCommands.Attributes; - -namespace SupportChild.Commands; - -public class SayCommand : ApplicationCommandModule -{ - [SlashRequireGuild] - [SlashCommand("say", "Prints a message with information from staff. Use without identifier to list all identifiers.")] - public async Task OnExecute(InteractionContext command, [Option("Identifier", "(Optional) The identifier word to summon a message.")] string identifier = null) - { - // Print list of all messages if no identifier is provided - if (identifier == null) - { - SendMessageList(command); - return; - } - - if (!Database.TryGetMessage(identifier.ToLower(), out Database.Message message)) - { - await command.CreateResponseAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Red, - Description = "There is no message with that identifier." - }, true); - return; - } - - await command.CreateResponseAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Cyan, - Description = message.message.Replace("\\n", "\n") - }); - } - - private static async void SendMessageList(InteractionContext command) - { - List messages = Database.GetAllMessages(); - if (messages.Count == 0) - { - await command.CreateResponseAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Red, - Description = "There are no messages registered." - }, true); - return; - } - - List listItems = []; - foreach (Database.Message message in messages) - { - listItems.Add("**" + message.identifier + "** Added by <@" + message.userID + ">\n"); - } - - List embeds = []; - foreach (string message in Utilities.ParseListIntoMessages(listItems)) - { - embeds.Add(new DiscordEmbedBuilder - { - Title = "Available messages:", - Color = DiscordColor.Green, - Description = message - }); - } - - // Add the footers - for (int i = 0; i < embeds.Count; i++) - { - embeds[i].Footer = new DiscordEmbedBuilder.EmbedFooter - { - Text = $"Page {i + 1} / {embeds.Count}" - }; - } - - List listPages = []; - foreach (DiscordEmbedBuilder embed in embeds) - { - listPages.Add(new Page("", embed)); - } - - await command.Interaction.SendPaginatedResponseAsync(true, command.User, listPages); - } -} \ No newline at end of file diff --git a/Commands/SetSummaryCommand.cs b/Commands/SetSummaryCommand.cs deleted file mode 100644 index d4f7526..0000000 --- a/Commands/SetSummaryCommand.cs +++ /dev/null @@ -1,42 +0,0 @@ -using System.Threading.Tasks; -using DSharpPlus.Entities; -using DSharpPlus.SlashCommands; -using DSharpPlus.SlashCommands.Attributes; -using MySqlConnector; - -namespace SupportChild.Commands; - -public class SetSummaryCommand : ApplicationCommandModule -{ - [SlashRequireGuild] - [SlashCommand("setsummary", "Sets a ticket's summary for the summary command.")] - public async Task OnExecute(InteractionContext command, [Option("Summary", "The ticket summary text.")] string summary) - { - ulong channelID = command.Channel.Id; - // Check if ticket exists in the database - if (!Database.TryGetOpenTicket(command.Channel.Id, out Database.Ticket _)) - { - await command.CreateResponseAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Red, - Description = "This channel is not a ticket." - }); - return; - } - - await using MySqlConnection c = Database.GetConnection(); - c.Open(); - MySqlCommand update = new MySqlCommand(@"UPDATE tickets SET summary = @summary WHERE channel_id = @channel_id", c); - update.Parameters.AddWithValue("@summary", summary); - update.Parameters.AddWithValue("@channel_id", channelID); - update.Prepare(); - update.ExecuteNonQuery(); - update.Dispose(); - - await command.CreateResponseAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Green, - Description = "Summary set." - }, true); - } -} \ No newline at end of file diff --git a/Commands/StatusCommand.cs b/Commands/StatusCommand.cs deleted file mode 100644 index 9089242..0000000 --- a/Commands/StatusCommand.cs +++ /dev/null @@ -1,28 +0,0 @@ -using System.Threading.Tasks; -using DSharpPlus.Entities; -using DSharpPlus.SlashCommands; -using DSharpPlus.SlashCommands.Attributes; - -namespace SupportChild.Commands; - -public class StatusCommand : ApplicationCommandModule -{ - [SlashRequireGuild] - [SlashCommand("status", "Shows bot status and information.")] - public async Task OnExecute(InteractionContext command) - { - long openTickets = Database.GetNumberOfTickets(); - long closedTickets = Database.GetNumberOfClosedTickets(); - - DiscordEmbed botInfo = new DiscordEmbedBuilder() - .WithAuthor("Emotion-stuff/supportchild @ Toastielab", "https://toastielab.dev/Emotions-stuff/SupportChild", "https://cdn.discordapp.com/attachments/765441543100170271/914327948667011132/Ellie_Concept_2_transparent_ver.png") - .WithTitle("Bot information") - .WithColor(DiscordColor.Cyan) - .AddField("Version:", SupportChild.GetVersion(), true) - .AddField("Open tickets:", openTickets + "", true) - .AddField("Closed tickets:", closedTickets + " ", true) - .AddField("Report bugs:", "[Toastielab Issues](https://toastielab.dev/Emotions-stuff/SupportChild/issues)", true) - .AddField("Commands:", "[Toastielab Repository](https://toastielab.dev/Emotions-stuff/SupportChild)", true); - await command.CreateResponseAsync(botInfo); - } -} diff --git a/Commands/SummaryCommand.cs b/Commands/SummaryCommand.cs deleted file mode 100644 index 2c69118..0000000 --- a/Commands/SummaryCommand.cs +++ /dev/null @@ -1,35 +0,0 @@ -using System.Threading.Tasks; -using DSharpPlus.Entities; -using DSharpPlus.SlashCommands; -using DSharpPlus.SlashCommands.Attributes; - -namespace SupportChild.Commands; - -public class SummaryCommand : ApplicationCommandModule -{ - [SlashRequireGuild] - [SlashCommand("summary", "Lists tickets assigned to a user.")] - public async Task OnExecute(InteractionContext command) - { - if (Database.TryGetOpenTicket(command.Channel.Id, out Database.Ticket ticket)) - { - DiscordEmbed channelInfo = new DiscordEmbedBuilder() - .WithTitle("Channel information") - .WithColor(DiscordColor.Cyan) - .AddField("Ticket number:", ticket.id.ToString("00000"), true) - .AddField("Ticket creator:", $"<@{ticket.creatorID}>", true) - .AddField("Assigned staff:", ticket.assignedStaffID == 0 ? "Unassigned." : $"<@{ticket.assignedStaffID}>", true) - .AddField("Creation time:", ticket.DiscordRelativeTime(), true) - .AddField("Summary:", string.IsNullOrEmpty(ticket.summary) ? "No summary." : ticket.summary.Replace("\\n", "\n")); - await command.CreateResponseAsync(channelInfo); - } - else - { - await command.CreateResponseAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Red, - Description = "This channel is not a ticket." - }, true); - } - } -} \ No newline at end of file diff --git a/Commands/ToggleActiveCommand.cs b/Commands/ToggleActiveCommand.cs deleted file mode 100644 index 80ef457..0000000 --- a/Commands/ToggleActiveCommand.cs +++ /dev/null @@ -1,44 +0,0 @@ -using System.Threading.Tasks; -using DSharpPlus.Entities; -using DSharpPlus.SlashCommands; -using DSharpPlus.SlashCommands.Attributes; - -namespace SupportChild.Commands; - -public class ToggleActiveCommand : ApplicationCommandModule -{ - [SlashRequireGuild] - [SlashCommand("toggleactive", "Toggles active status for a staff member.")] - public async Task OnExecute(InteractionContext command, [Option("User", "(Optional) Staff member to toggle activity for.")] DiscordUser user = null) - { - DiscordUser staffUser = user == null ? command.User : user; - - // Check if ticket exists in the database - if (!Database.TryGetStaff(staffUser.Id, out Database.StaffMember staffMember)) - { - await command.CreateResponseAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Red, - Description = user == null ? "You have not been registered as staff." : "The user is not registered as staff." - }, true); - return; - } - - if (Database.SetStaffActive(staffUser.Id, !staffMember.active)) - { - await command.CreateResponseAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Green, - Description = staffMember.active ? "Staff member is now set as inactive and will no longer be randomly assigned any support tickets." : "Staff member is now set as active and will be randomly assigned support tickets again." - }, true); - } - else - { - await command.CreateResponseAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Red, - Description = "Error: Unable to update active status in database." - }, true); - } - } -} \ No newline at end of file diff --git a/Commands/TranscriptCommand.cs b/Commands/TranscriptCommand.cs deleted file mode 100644 index ea1067f..0000000 --- a/Commands/TranscriptCommand.cs +++ /dev/null @@ -1,129 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Threading.Tasks; -using DSharpPlus.Entities; -using DSharpPlus.Exceptions; -using DSharpPlus.SlashCommands; -using DSharpPlus.SlashCommands.Attributes; - -namespace SupportChild.Commands; - -public class TranscriptCommand : ApplicationCommandModule -{ - [SlashRequireGuild] - [SlashCommand("transcript", "Creates a transcript of a ticket.")] - public async Task OnExecute(InteractionContext command, [Option("Ticket", "(Optional) Ticket number to get transcript of.")] long ticketID = 0) - { - await command.DeferAsync(true); - Database.Ticket ticket; - if (ticketID == 0) // If there are no arguments use current channel - { - if (Database.TryGetOpenTicket(command.Channel.Id, out ticket)) - { - try - { - await Transcriber.ExecuteAsync(command.Channel.Id, ticket.id); - } - catch (Exception) - { - await command.EditResponseAsync(new DiscordWebhookBuilder().AddEmbed(new DiscordEmbedBuilder - { - Color = DiscordColor.Red, - Description = "ERROR: Could not save transcript file. Aborting..." - })); - throw; - } - } - else - { - await command.EditResponseAsync(new DiscordWebhookBuilder().AddEmbed(new DiscordEmbedBuilder - { - Color = DiscordColor.Red, - Description = "This channel is not a ticket." - })); - return; - } - } - else - { - // If the ticket is still open, generate a new fresh transcript - if (Database.TryGetOpenTicketByID((uint)ticketID, out ticket) && ticket?.creatorID == command.Member.Id) - { - try - { - await Transcriber.ExecuteAsync(command.Channel.Id, ticket.id); - } - catch (Exception) - { - await command.EditResponseAsync(new DiscordWebhookBuilder().AddEmbed(new DiscordEmbedBuilder - { - Color = DiscordColor.Red, - Description = "ERROR: Could not save transcript file. Aborting..." - })); - throw; - } - - } - // If there is no open or closed ticket, send an error. If there is a closed ticket we will simply use the old transcript from when the ticket was closed. - else if (!Database.TryGetClosedTicket((uint)ticketID, out ticket) || (ticket?.creatorID != command.Member.Id && !Database.IsStaff(command.Member.Id))) - { - await command.EditResponseAsync(new DiscordWebhookBuilder().AddEmbed(new DiscordEmbedBuilder - { - Color = DiscordColor.Red, - Description = "Could not find a closed ticket with that number which you opened.\n(Use the /list command to see all your tickets)" - })); - return; - } - } - - // Log it if the log channel exists - DiscordChannel logChannel = command.Guild.GetChannel(Config.logChannel); - if (logChannel != null) - { - await using FileStream file = new FileStream(Transcriber.GetPath(ticket.id), FileMode.Open, FileAccess.Read); - - DiscordMessageBuilder message = new DiscordMessageBuilder(); - message.AddEmbed(new DiscordEmbedBuilder - { - Color = DiscordColor.Green, - Description = "Ticket " + ticket.id.ToString("00000") + " transcript generated by " + command.Member.Mention + ".\n", - Footer = new DiscordEmbedBuilder.EmbedFooter { Text = '#' + command.Channel.Name } - }); - message.AddFiles(new Dictionary { { Transcriber.GetFilename(ticket.id), file } }); - - await logChannel.SendMessageAsync(message); - } - - try - { - // Send transcript in a direct message - await using FileStream file = new FileStream(Transcriber.GetPath(ticket.id), FileMode.Open, FileAccess.Read); - - DiscordMessageBuilder directMessage = new DiscordMessageBuilder(); - directMessage.AddEmbed(new DiscordEmbedBuilder - { - Color = DiscordColor.Green, - Description = "Transcript generated!\n" - }); - directMessage.AddFiles(new Dictionary { { Transcriber.GetFilename(ticket.id), file } }); - - await command.Member.SendMessageAsync(directMessage); - } - catch (UnauthorizedException) - { - await command.EditResponseAsync(new DiscordWebhookBuilder().AddEmbed(new DiscordEmbedBuilder - { - Color = DiscordColor.Red, - Description = "Not allowed to send direct message to you, please check your privacy settings.\n" - })); - return; - } - - await command.EditResponseAsync(new DiscordWebhookBuilder().AddEmbed(new DiscordEmbedBuilder - { - Color = DiscordColor.Green, - Description = "Transcript sent!\n" - })); - } -} \ No newline at end of file diff --git a/Commands/UnassignCommand.cs b/Commands/UnassignCommand.cs deleted file mode 100644 index 4b0bfdf..0000000 --- a/Commands/UnassignCommand.cs +++ /dev/null @@ -1,52 +0,0 @@ -using System.Threading.Tasks; -using DSharpPlus.Entities; -using DSharpPlus.SlashCommands; -using DSharpPlus.SlashCommands.Attributes; - -namespace SupportChild.Commands; - -public class UnassignCommand : ApplicationCommandModule -{ - [SlashRequireGuild] - [SlashCommand("unassign", "Unassigns a staff member from a ticket.")] - public async Task OnExecute(InteractionContext command) - { - // Check if ticket exists in the database - if (!Database.TryGetOpenTicket(command.Channel.Id, out Database.Ticket ticket)) - { - await command.CreateResponseAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Red, - Description = "This channel is not a ticket." - }, true); - return; - } - - if (!Database.UnassignStaff(ticket)) - { - await command.CreateResponseAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Red, - Description = "Error: Failed to unassign staff member from ticket." - }, true); - return; - } - - await command.CreateResponseAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Green, - Description = "Unassigned staff member from ticket." - }); - - // Log it if the log channel exists - DiscordChannel logChannel = command.Guild.GetChannel(Config.logChannel); - if (logChannel != null) - { - await logChannel.SendMessageAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Green, - Description = "Staff member was unassigned from " + command.Channel.Mention + " by " + command.Member.Mention + "." - }); - } - } -} \ No newline at end of file diff --git a/Commands/UnblacklistCommand.cs b/Commands/UnblacklistCommand.cs deleted file mode 100644 index ff1681d..0000000 --- a/Commands/UnblacklistCommand.cs +++ /dev/null @@ -1,54 +0,0 @@ -using System; -using System.Threading.Tasks; -using DSharpPlus.Entities; -using DSharpPlus.SlashCommands; -using DSharpPlus.SlashCommands.Attributes; - -namespace SupportChild.Commands; - -public class UnblacklistCommand : ApplicationCommandModule -{ - [SlashRequireGuild] - [SlashCommand("unblacklist", "Unblacklists a user from opening tickets.")] - public async Task OnExecute(InteractionContext command, [Option("User", "User to remove from blacklist.")] DiscordUser user) - { - try - { - if (!Database.Unblacklist(user.Id)) - { - await command.CreateResponseAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Red, - Description = user.Mention + " is not blacklisted." - }, true); - return; - } - - await command.CreateResponseAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Green, - Description = "Removed " + user.Mention + " from blacklist." - }, true); - - // Log it if the log channel exists - DiscordChannel logChannel = command.Guild.GetChannel(Config.logChannel); - if (logChannel != null) - { - await logChannel.SendMessageAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Green, - Description = user.Mention + " was unblacklisted from opening tickets by " + command.Member.Mention + "." - }); - } - } - catch (Exception) - { - await command.CreateResponseAsync(new DiscordEmbedBuilder - { - Color = DiscordColor.Red, - Description = "Error occured while removing " + user.Mention + " from blacklist." - }, true); - throw; - } - } -} \ No newline at end of file diff --git a/Config.cs b/Config.cs deleted file mode 100644 index fd58e92..0000000 --- a/Config.cs +++ /dev/null @@ -1,102 +0,0 @@ -using System; -using System.IO; -using DSharpPlus; -using Microsoft.Extensions.Logging; -using Newtonsoft.Json.Linq; -using YamlDotNet.Serialization; - -namespace SupportChild; - -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 = ""; - - private static string configPath = "./config.yml"; - - public static void LoadConfig() - { - if (!string.IsNullOrEmpty(SupportChild.commandLineArgs.configPath)) - { - configPath = SupportChild.commandLineArgs.configPath; - } - - Logger.Log("Loading config \"" + Path.GetFullPath(configPath) + "\""); - - // Writes default config to file if it does not already exist - if (!File.Exists(configPath)) - { - File.WriteAllText(configPath, Utilities.ReadManifestData("default_config.yml")); - } - - // Reads config contents into FileStream - FileStream stream = File.OpenRead(configPath); - - // Converts the FileStream into a YAML object - IDeserializer deserializer = new DeserializerBuilder().Build(); - object yamlObject = deserializer.Deserialize(new StreamReader(stream)) ?? ""; - - // Converts the YAML object into a JSON object as the YAML ones do not support traversal or selection of nodes by name - ISerializer serializer = new SerializerBuilder().JsonCompatible().Build(); - JObject json = JObject.Parse(serializer.Serialize(yamlObject)); - - // Sets up the bot - token = json.SelectToken("bot.token")?.Value() ?? ""; - logChannel = json.SelectToken("bot.log-channel")?.Value() ?? 0; - welcomeMessage = json.SelectToken("bot.welcome-message")?.Value() ?? ""; - string stringLogLevel = json.SelectToken("bot.console-log-level")?.Value() ?? ""; - - if (!Enum.TryParse(stringLogLevel, true, out logLevel)) - { - logLevel = LogLevel.Information; - Logger.Warn("Log level '" + stringLogLevel + "' invalid, using 'Information' instead."); - } - - string stringTimestampFormat = json.SelectToken("bot.timestamp-format")?.Value() ?? "RelativeTime"; - - if (!Enum.TryParse(stringTimestampFormat, true, out timestampFormat)) - { - timestampFormat = TimestampFormat.RelativeTime; - Logger.Warn("Timestamp '" + stringTimestampFormat + "' invalid, using 'RelativeTime' instead."); - } - - randomAssignment = json.SelectToken("bot.random-assignment")?.Value() ?? false; - randomAssignRoleOverride = json.SelectToken("bot.random-assign-role-override")?.Value() ?? false; - presenceType = json.SelectToken("bot.presence-type")?.Value() ?? "Playing"; - presenceText = json.SelectToken("bot.presence-text")?.Value() ?? ""; - newCommandUsesSelector = json.SelectToken("bot.new-command-uses-selector")?.Value() ?? false; - ticketLimit = json.SelectToken("bot.ticket-limit")?.Value() ?? 5; - - ticketUpdatedNotifications = json.SelectToken("notifications.ticket-updated")?.Value() ?? false; - ticketUpdatedNotificationDelay = json.SelectToken("notifications.ticket-updated-delay")?.Value() ?? 0.0; - assignmentNotifications = json.SelectToken("notifications.assignment")?.Value() ?? false; - closingNotifications = json.SelectToken("notifications.closing")?.Value() ?? false; - - // Reads database info - hostName = json.SelectToken("database.address")?.Value() ?? ""; - port = json.SelectToken("database.port")?.Value() ?? 3306; - database = json.SelectToken("database.name")?.Value() ?? "supportchild"; - username = json.SelectToken("database.user")?.Value() ?? "supportchild"; - password = json.SelectToken("database.password")?.Value() ?? ""; - } -} \ No newline at end of file diff --git a/Jenkinsfile b/Jenkinsfile index 5dcf8ad..263f4a9 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -10,12 +10,12 @@ pipeline { parallel { stage('Linux') { steps { - sh 'dotnet publish -r linux-x64 -c Release --self-contained true --no-restore --output Linux-x64/' + sh 'dotnet publish -p:PublishSingleFile=true -p:IncludeAllContentForSelfExtract=true -p:PublishTrimmed=true -r linux-x64 -c Release --self-contained true --no-restore --output Linux-x64/' } } stage('Windows') { steps { - sh 'dotnet publish -r win-x64 -c Release --self-contained true --no-restore --output Windows-x64/' + sh 'dotnet publish -p:PublishSingleFile=true -p:IncludeAllContentForSelfExtract=true -p:PublishTrimmed=true -r win-x64 -c Release --self-contained true --no-restore --output Windows-x64/' } } } diff --git a/Logger.cs b/Logger.cs deleted file mode 100644 index 5391014..0000000 --- a/Logger.cs +++ /dev/null @@ -1,68 +0,0 @@ -using Microsoft.Extensions.Logging; -using System; -using System.Reflection; - -namespace SupportChild; - -public static class Logger -{ - public static void Debug(string message) - { - try - { - SupportChild.discordClient.Logger.Log(LogLevel.Debug, new EventId(420, Assembly.GetEntryAssembly()?.GetName().Name), message); - } - catch (NullReferenceException) - { - Console.WriteLine("[DEBUG] " + message); - } - } - - public static void Log(string message) - { - try - { - SupportChild.discordClient.Logger.Log(LogLevel.Information, new EventId(420, Assembly.GetEntryAssembly()?.GetName().Name), message); - } - catch (NullReferenceException) - { - Console.WriteLine("[INFO] " + message); - } - } - - public static void Warn(string message) - { - try - { - SupportChild.discordClient.Logger.Log(LogLevel.Warning, new EventId(420, Assembly.GetEntryAssembly()?.GetName().Name), message); - } - catch (NullReferenceException) - { - Console.WriteLine("[WARNING] " + message); - } - } - - public static void Error(string message) - { - try - { - SupportChild.discordClient.Logger.Log(LogLevel.Error, new EventId(420, Assembly.GetEntryAssembly()?.GetName().Name), message); - } - catch (NullReferenceException) - { - Console.WriteLine("[ERROR] " + message); - } - } - - public static void Fatal(string message) - { - try - { - SupportChild.discordClient.Logger.Log(LogLevel.Critical, new EventId(420, Assembly.GetEntryAssembly()?.GetName().Name), message); - } - catch (NullReferenceException) - { - Console.WriteLine("[CRITICAL] " + message); - } - } -} \ No newline at end of file diff --git a/README.md b/README.md index 99f8427..5b710e5 100644 --- a/README.md +++ b/README.md @@ -1 +1,6 @@ # SupportChild + +this is a customized version of [SupportBoi](https://github.com/KarlOfDuty/SupportBoi) it is recommended you go and check out the awesome work that is there! + +## Badges +[![.NET](https://github.com/EmotionChild/SupportChild/actions/workflows/dotnet.yml/badge.svg)](https://github.com/EmotionChild/SupportChild/actions/workflows/dotnet.yml) [![MSBuild](https://github.com/EmotionChild/SupportChild/actions/workflows/msbuild.yml/badge.svg)](https://github.com/EmotionChild/SupportChild/actions/workflows/msbuild.yml) [![Release](https://img.shields.io/github/release/EmotionChild/SupportChild.svg)](https://github.com/EmotionChild/SupportChild/releases) diff --git a/SupportChild.cs b/SupportChild.cs deleted file mode 100644 index 0f8147f..0000000 --- a/SupportChild.cs +++ /dev/null @@ -1,217 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Reflection; -using System.Threading.Tasks; -using System.Linq; -using DSharpPlus; -using DSharpPlus.Interactivity; -using DSharpPlus.Interactivity.Enums; -using DSharpPlus.Interactivity.Extensions; -using DSharpPlus.SlashCommands; -using Microsoft.Extensions.Logging; -using SupportChild.Commands; -using CommandLine; - -namespace SupportChild; - -internal static class SupportChild -{ - // Sets up a dummy client to use for logging - private static readonly DiscordConfiguration config = new() - { - Token = "DUMMY_TOKEN", - TokenType = TokenType.Bot, - MinimumLogLevel = LogLevel.Debug, - AutoReconnect = true, - Intents = DiscordIntents.All, - LogTimestampFormat = "yyyy-MM-dd HH:mm:ss", - LogUnknownEvents = false - }; - - public static DiscordClient discordClient { get; private set; } = new(config); - - private static SlashCommandsExtension commands = null; - - public class CommandLineArguments - { - [CommandLine.Option('c', - "config", - Required = false, - HelpText = "Select a config file to use.", - Default = "config.yml", - MetaValue = "PATH")] - public string configPath { get; set; } - - [CommandLine.Option('t', - "transcripts", - Required = false, - HelpText = "Select directory to store transcripts in.", - Default = "./transcripts", - MetaValue = "PATH")] - public string transcriptDir { get; set; } - - [CommandLine.Option( - "leave", - Required = false, - HelpText = "Leaves one or more Discord servers. " + - "You can check which servers your bot is in when it starts up.", - MetaValue = "ID,ID,ID...", - Separator = ',' - )] - public IEnumerable serversToLeave { get; set; } - } - - internal static CommandLineArguments commandLineArgs; - - private static void Main(string[] args) - { - StringWriter sw = new StringWriter(); - commandLineArgs = new Parser(settings => - { - settings.AutoHelp = true; - settings.HelpWriter = sw; - settings.AutoVersion = false; - }).ParseArguments(args).Value; - - // CommandLineParser has some bugs related to the built-in version option, ignore the output if it isn't found. - if (!sw.ToString().Contains("Option 'version' is unknown.")) - { - Console.Write(sw); - } - - if (args.Contains("--help")) - { - return; - } - - if (args.Contains("--version")) - { - Console.WriteLine(Assembly.GetEntryAssembly()?.GetName().Name + ' ' + GetVersion()); - Console.WriteLine("Build time: " + BuildInfo.BuildTimeUTC.ToString("yyyy-MM-dd HH:mm:ss") + " UTC"); - return; - } - - MainAsync().GetAwaiter().GetResult(); - } - - private static async Task MainAsync() - { - Logger.Log("Starting " + Assembly.GetEntryAssembly()?.GetName().Name + " version " + GetVersion() + "..."); - try - { - Reload(); - - // Block this task until the program is closed. - await Task.Delay(-1); - } - catch (Exception e) - { - 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)) - + " (" + ThisAssembly.Git.Commit + ")"; - } - - public static async void Reload() - { - if (discordClient != null) - { - await discordClient.DisconnectAsync(); - discordClient.Dispose(); - } - - Config.LoadConfig(); - - // Check if token is unset - if (Config.token is "" or "") - { - Logger.Fatal("You need to set your bot token in the config and start the bot again."); - throw new ArgumentException("Invalid Discord bot token"); - } - - // Database connection and setup - try - { - Logger.Log("Connecting to database... (" + Config.hostName + ":" + Config.port + ")"); - Database.SetConnectionString(Config.hostName, Config.port, Config.database, Config.username, Config.password); - Database.SetupTables(); - } - catch (Exception e) - { - Logger.Fatal("Could not set up database tables, please confirm connection settings, status of the server and permissions of MySQL user. Error: " + e); - throw; - } - - Logger.Log("Setting up Discord client..."); - - // Setting up client configuration - config.Token = Config.token; - config.MinimumLogLevel = Config.logLevel; - - discordClient = new DiscordClient(config); - - 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 - { - PaginationBehaviour = PaginationBehaviour.Ignore, - PaginationDeletion = PaginationDeletion.DeleteMessage, - Timeout = TimeSpan.FromMinutes(15) - }); - - Logger.Log("Registering commands..."); - commands = discordClient.UseSlashCommands(); - - commands.RegisterCommands(); - commands.RegisterCommands(); - commands.RegisterCommands(); - commands.RegisterCommands(); - commands.RegisterCommands(); - commands.RegisterCommands(); - commands.RegisterCommands(); - commands.RegisterCommands(); - commands.RegisterCommands(); - commands.RegisterCommands(); - commands.RegisterCommands(); - commands.RegisterCommands(); - commands.RegisterCommands(); - commands.RegisterCommands(); - commands.RegisterCommands(); - commands.RegisterCommands(); - commands.RegisterCommands(); - commands.RegisterCommands(); - commands.RegisterCommands(); - commands.RegisterCommands(); - commands.RegisterCommands(); - commands.RegisterCommands(); - commands.RegisterCommands(); - commands.RegisterCommands(); - commands.RegisterCommands(); - commands.RegisterCommands(); - commands.RegisterCommands(); - commands.RegisterCommands(); - - Logger.Log("Hooking command events..."); - commands.SlashCommandErrored += EventHandler.OnCommandError; - - Logger.Log("Connecting to Discord..."); - await discordClient.ConnectAsync(); - } -} \ No newline at end of file diff --git a/SupportChild.csproj b/SupportChild.csproj deleted file mode 100644 index edbd738..0000000 --- a/SupportChild.csproj +++ /dev/null @@ -1,63 +0,0 @@ - - - - Exe - 3.1.0 - ellie_icon.ico - net8.0 - SupportChild.SupportChild - win-x64;linux-x64 - true - partial - - EmotionChild - A Discord support ticket bot built for the Ellie's home server - en - Git - https://toastielab.dev/Emotions-stuff/SupportChild - - https://cdn.discordapp.com/attachments/765441543100170271/914327948667011132/Ellie_Concept_2_transparent_ver.png - LICENSE - https://toastielab.dev/Emotions-stuff/SupportChild - 3.1.0 - default - false - false - - - - full - - - - - - - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - - - - - - - - - - - - - - - lib\DiscordChatExporter.Core.dll - - - - \ No newline at end of file diff --git a/SupportChild.sln b/SupportChild.sln new file mode 100644 index 0000000..098a159 --- /dev/null +++ b/SupportChild.sln @@ -0,0 +1,16 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SupportChild", "SupportChild\SupportChild.csproj", "{B043AACB-D763-4C61-9524-C8B7C58DA3EF}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {B043AACB-D763-4C61-9524-C8B7C58DA3EF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B043AACB-D763-4C61-9524-C8B7C58DA3EF}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B043AACB-D763-4C61-9524-C8B7C58DA3EF}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B043AACB-D763-4C61-9524-C8B7C58DA3EF}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection +EndGlobal diff --git a/SupportChild.sln.DotSettings b/SupportChild.sln.DotSettings new file mode 100644 index 0000000..b960982 --- /dev/null +++ b/SupportChild.sln.DotSettings @@ -0,0 +1,6 @@ + + ERROR + True + + True + \ No newline at end of file diff --git a/SupportChild/Commands/AddCategoryCommand.cs b/SupportChild/Commands/AddCategoryCommand.cs new file mode 100644 index 0000000..3656fdb --- /dev/null +++ b/SupportChild/Commands/AddCategoryCommand.cs @@ -0,0 +1,71 @@ +using System.Threading.Tasks; +using DSharpPlus.Entities; +using DSharpPlus.SlashCommands; +using DSharpPlus.SlashCommands.Attributes; + +namespace SupportChild.Commands; + +public class AddCategoryCommand : ApplicationCommandModule +{ + [SlashRequireGuild] + [SlashCommand("addcategory", "Adds a category to the ticket bot letting users open tickets in them.")] + public async Task OnExecute(InteractionContext command, [Option("Title", "The name to display on buttons and in selection boxes.")] string title, [Option("Category", "The category to add.")] DiscordChannel category) + { + if (!category.IsCategory) + { + await command.CreateResponseAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "That channel is not a category." + }, true); + return; + } + + if (string.IsNullOrWhiteSpace(title)) + { + await command.CreateResponseAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "Invalid category title specified." + }, true); + return; + } + + if (Database.TryGetCategory(category.Id, out Database.Category _)) + { + await command.CreateResponseAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "That category is already registered." + }, true); + return; + } + + if (Database.TryGetCategory(title, out Database.Category _)) + { + await command.CreateResponseAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "There is already a category with that title." + }, true); + return; + } + + if (Database.AddCategory(title, category.Id)) + { + await command.CreateResponseAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Green, + Description = "Category added." + }, true); + } + else + { + await command.CreateResponseAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "Error: Failed adding the category to the database." + }, true); + } + } +} \ No newline at end of file diff --git a/SupportChild/Commands/AddCommand.cs b/SupportChild/Commands/AddCommand.cs new file mode 100644 index 0000000..47b92f8 --- /dev/null +++ b/SupportChild/Commands/AddCommand.cs @@ -0,0 +1,82 @@ +using System; +using System.Threading.Tasks; +using DSharpPlus; +using DSharpPlus.Entities; +using DSharpPlus.SlashCommands; +using DSharpPlus.SlashCommands.Attributes; + +namespace SupportChild.Commands; + +public class AddCommand : ApplicationCommandModule +{ + [SlashRequireGuild] + [SlashCommand("add", "Adds a user to a ticket")] + public async Task OnExecute(InteractionContext command, [Option("User", "User to add to ticket.")] DiscordUser user) + { + // Check if ticket exists in the database + if (!Database.IsOpenTicket(command.Channel.Id)) + { + await command.CreateResponseAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "This channel is not a ticket." + }, true); + return; + } + + DiscordMember member; + try + { + member = (user == null ? command.Member : await command.Guild.GetMemberAsync(user.Id)); + + if (member == null) + { + await command.CreateResponseAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "Could not find that user in this server." + }, true); + return; + } + } + catch (Exception) + { + await command.CreateResponseAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "Could not find that user in this server." + }, true); + return; + } + + try + { + await command.Channel.AddOverwriteAsync(member, Permissions.AccessChannels); + await command.CreateResponseAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Green, + Description = "Added " + member.Mention + " to ticket." + }); + + // Log it if the log channel exists + DiscordChannel logChannel = command.Guild.GetChannel(Config.logChannel); + if (logChannel != null) + { + await logChannel.SendMessageAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Green, + Description = member.Mention + " was added to " + command.Channel.Mention + + " by " + command.Member.Mention + "." + }); + } + } + catch (Exception) + { + await command.CreateResponseAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "Could not add " + member.Mention + " to ticket, unknown error occured." + }, true); + } + } +} \ No newline at end of file diff --git a/SupportChild/Commands/AddMessageCommand.cs b/SupportChild/Commands/AddMessageCommand.cs new file mode 100644 index 0000000..6ffa491 --- /dev/null +++ b/SupportChild/Commands/AddMessageCommand.cs @@ -0,0 +1,53 @@ +using DSharpPlus.Entities; +using System.Threading.Tasks; +using DSharpPlus.SlashCommands; +using DSharpPlus.SlashCommands.Attributes; + +namespace SupportChild.Commands; + +public class AddMessageCommand : ApplicationCommandModule +{ + [SlashRequireGuild] + [SlashCommand("addmessage", "Adds a new message for the 'say' command.")] + public async Task OnExecute(InteractionContext command, + [Option("Identifier", "The identifier word used in the /say command.")] string identifier, + [Option("Message", "The message the /say command will return.")] string message) + { + if (string.IsNullOrEmpty(message)) + { + await command.CreateResponseAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "No message specified." + }, true); + return; + } + + if (Database.TryGetMessage(identifier.ToLower(), out Database.Message _)) + { + await command.CreateResponseAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "There is already a message with that identifier." + }, true); + return; + } + + if (Database.AddMessage(identifier, command.Member.Id, message)) + { + await command.CreateResponseAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Green, + Description = "Message added." + }, true); + } + else + { + await command.CreateResponseAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "Error: Failed adding the message to the database." + }, true); + } + } +} \ No newline at end of file diff --git a/SupportChild/Commands/AddStaffCommand.cs b/SupportChild/Commands/AddStaffCommand.cs new file mode 100644 index 0000000..224fb1e --- /dev/null +++ b/SupportChild/Commands/AddStaffCommand.cs @@ -0,0 +1,67 @@ +using System; +using System.Threading.Tasks; +using DSharpPlus.Entities; +using DSharpPlus.SlashCommands; +using DSharpPlus.SlashCommands.Attributes; +using MySqlConnector; + +namespace SupportChild.Commands; + +public class AddStaffCommand : ApplicationCommandModule +{ + [SlashRequireGuild] + [SlashCommand("addstaff", "Adds a new staff member.")] + public async Task OnExecute(InteractionContext command, [Option("User", "User to add to staff.")] DiscordUser user) + { + DiscordMember staffMember = null; + try + { + staffMember = user == null ? command.Member : await command.Guild.GetMemberAsync(user.Id); + + if (staffMember == null) + { + await command.CreateResponseAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "Could not find that user in this server." + }, true); + return; + } + } + catch (Exception) + { + await command.CreateResponseAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "Could not find that user in this server." + }, true); + return; + } + + await using MySqlConnection c = Database.GetConnection(); + MySqlCommand cmd = Database.IsStaff(staffMember.Id) ? new MySqlCommand(@"UPDATE staff SET name = @name WHERE user_id = @user_id", c) : new MySqlCommand(@"INSERT INTO staff (user_id, name) VALUES (@user_id, @name);", c); + + c.Open(); + cmd.Parameters.AddWithValue("@user_id", staffMember.Id); + cmd.Parameters.AddWithValue("@name", staffMember.DisplayName); + cmd.ExecuteNonQuery(); + cmd.Dispose(); + + await command.CreateResponseAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Green, + Description = staffMember.Mention + " was added to staff." + }); + + // Log it if the log channel exists + DiscordChannel logChannel = command.Guild.GetChannel(Config.logChannel); + if (logChannel != null) + { + await logChannel.SendMessageAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Green, + Description = staffMember.Mention + " was added to staff.\n" + }); + } + } +} \ No newline at end of file diff --git a/SupportChild/Commands/AdminCommands.cs b/SupportChild/Commands/AdminCommands.cs new file mode 100644 index 0000000..bf90847 --- /dev/null +++ b/SupportChild/Commands/AdminCommands.cs @@ -0,0 +1,200 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using DSharpPlus.Entities; +using DSharpPlus.Interactivity; +using DSharpPlus.Interactivity.Extensions; +using DSharpPlus.SlashCommands; +using DSharpPlus.SlashCommands.Attributes; + +namespace SupportChild.Commands; + +[SlashCommandGroup("admin", "Administrative commands.")] +public class AdminCommands : ApplicationCommandModule +{ + [SlashRequireGuild] + [SlashCommand("listinvalid", "List tickets which channels have been deleted. Use /admin unsetticket to remove them.")] + public async Task ListInvalid(InteractionContext command) + { + if (!Database.TryGetOpenTickets(out List openTickets)) + { + await command.CreateResponseAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "Could not get any open tickets from database." + }, true); + } + + // Get all channels in all guilds the bot is part of + List allChannels = new List(); + foreach (KeyValuePair guild in SupportChild.discordClient.Guilds) + { + try + { + allChannels.AddRange(await guild.Value.GetChannelsAsync()); + } + catch (Exception) { /*ignored*/ } + } + + // Check which tickets channels no longer exist + List listItems = new List(); + foreach (Database.Ticket ticket in openTickets) + { + if (allChannels.All(channel => channel.Id != ticket.channelID)) + { + listItems.Add("ID: **" + ticket.id.ToString("00000") + ":** <#" + ticket.channelID + ">\n"); + } + } + + if (listItems.Count == 0) + { + await command.CreateResponseAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Green, + Description = "All tickets are valid!" + }, true); + return; + } + + List embeds = new List(); + foreach (string message in Utilities.ParseListIntoMessages(listItems)) + { + embeds.Add(new DiscordEmbedBuilder + { + Title = "Invalid tickets:", + Color = DiscordColor.Red, + Description = message + }); + } + + // Add the footers + for (int i = 0; i < embeds.Count; i++) + { + embeds[i].Footer = new DiscordEmbedBuilder.EmbedFooter + { + Text = $"Page {i + 1} / {embeds.Count}" + }; + } + + List listPages = new List(); + foreach (DiscordEmbedBuilder embed in embeds) + { + listPages.Add(new Page("", embed)); + } + + await command.Interaction.SendPaginatedResponseAsync(true, command.User, listPages); + } + + [SlashRequireGuild] + [SlashCommand("setticket", "Turns a channel into a ticket WARNING: Anyone will be able to delete the channel using /close.")] + public async Task SetTicket(InteractionContext command, [Option("User", "(Optional) The owner of the ticket.")] DiscordUser user = null) + { + // Check if ticket exists in the database + if (Database.IsOpenTicket(command.Channel.Id)) + { + await command.CreateResponseAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "This channel is already a ticket." + }, true); + return; + } + + DiscordUser ticketUser = (user == null ? command.User : user); + + long id = Database.NewTicket(ticketUser.Id, 0, command.Channel.Id); + string ticketID = id.ToString("00000"); + await command.CreateResponseAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Green, + Description = "Channel has been designated ticket " + ticketID + "." + }); + + // Log it if the log channel exists + DiscordChannel logChannel = command.Guild.GetChannel(Config.logChannel); + if (logChannel != null) + { + await logChannel.SendMessageAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Green, + Description = command.Channel.Mention + " has been designated ticket " + ticketID + " by " + command.Member.Mention + "." + }); + } + } + + [SlashRequireGuild] + [SlashCommand("unsetticket", "Deletes a ticket from the ticket system without deleting the channel.")] + public async Task UnsetTicket(InteractionContext command, [Option("TicketID", "(Optional) Ticket to unset. Uses the channel you are in by default.")] long ticketID = 0) + { + Database.Ticket ticket; + + if (ticketID == 0) + { + // Check if ticket exists in the database + if (!Database.TryGetOpenTicket(command.Channel.Id, out ticket)) + { + await command.CreateResponseAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "This channel is not a ticket!" + }, true); + return; + } + } + else + { + // Check if ticket exists in the database + if (!Database.TryGetOpenTicketByID((uint)ticketID, out ticket)) + { + await command.CreateResponseAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "There is no ticket with this ticket ID." + }, true); + return; + } + } + + + if (Database.DeleteOpenTicket(ticket.id)) + { + await command.CreateResponseAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Green, + Description = "Channel has been undesignated as a ticket." + }); + + // Log it if the log channel exists + DiscordChannel logChannel = command.Guild.GetChannel(Config.logChannel); + if (logChannel != null) + { + await logChannel.SendMessageAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Green, + Description = command.Channel.Mention + " has been undesignated as a ticket by " + command.Member.Mention + "." + }); + } + } + else + { + await command.CreateResponseAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "Error: Failed removing ticket from database." + }, true); + } + } + + [SlashCommand("reload", "Reloads the bot config.")] + public async Task Reload(InteractionContext command) + { + await command.CreateResponseAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Green, + Description = "Reloading bot application..." + }); + Logger.Log("Reloading bot..."); + SupportChild.Reload(); + } +} \ No newline at end of file diff --git a/SupportChild/Commands/AssignCommand.cs b/SupportChild/Commands/AssignCommand.cs new file mode 100644 index 0000000..171760a --- /dev/null +++ b/SupportChild/Commands/AssignCommand.cs @@ -0,0 +1,102 @@ +using System; +using System.Threading.Tasks; +using DSharpPlus.Entities; +using DSharpPlus.Exceptions; +using DSharpPlus.SlashCommands; +using DSharpPlus.SlashCommands.Attributes; + +namespace SupportChild.Commands; + +public class AssignCommand : ApplicationCommandModule +{ + [SlashRequireGuild] + [SlashCommand("assign", "Assigns a staff member to this ticket.")] + public async Task OnExecute(InteractionContext command, [Option("User", "(Optional) User to assign to this ticket.")] DiscordUser user = null) + { + DiscordMember member = null; + try + { + member = user == null ? command.Member : await command.Guild.GetMemberAsync(user.Id); + + if (member == null) + { + await command.CreateResponseAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "Could not find that user in this server." + }, true); + return; + } + } + catch (Exception) + { + await command.CreateResponseAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "Could not find that user in this server." + }, true); + return; + } + + // Check if ticket exists in the database + if (!Database.TryGetOpenTicket(command.Channel.Id, out Database.Ticket ticket)) + { + await command.CreateResponseAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "This channel is not a ticket." + }, true); + return; + } + + if (!Database.IsStaff(member.Id)) + { + await command.CreateResponseAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "Error: User is not registered as staff." + }, true); + return; + } + + if (!Database.AssignStaff(ticket, member.Id)) + { + await command.CreateResponseAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "Error: Failed to assign " + member.Mention + " to ticket." + }, true); + return; + } + + await command.CreateResponseAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Green, + Description = "Assigned " + member.Mention + " to ticket." + }); + + if (Config.assignmentNotifications) + { + try + { + await member.SendMessageAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Green, + Description = "You have been assigned to a support ticket: " + command.Channel.Mention + }); + } + catch (UnauthorizedException) { } + } + + // Log it if the log channel exists + DiscordChannel logChannel = command.Guild.GetChannel(Config.logChannel); + if (logChannel != null) + { + await logChannel.SendMessageAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Green, + Description = member.Mention + " was assigned to " + command.Channel.Mention + " by " + command.Member.Mention + "." + }); + } + } +} \ No newline at end of file diff --git a/SupportChild/Commands/BlacklistCommand.cs b/SupportChild/Commands/BlacklistCommand.cs new file mode 100644 index 0000000..33a6262 --- /dev/null +++ b/SupportChild/Commands/BlacklistCommand.cs @@ -0,0 +1,54 @@ +using System; +using System.Threading.Tasks; +using DSharpPlus.Entities; +using DSharpPlus.SlashCommands; +using DSharpPlus.SlashCommands.Attributes; + +namespace SupportChild.Commands; + +public class BlacklistCommand : ApplicationCommandModule +{ + [SlashRequireGuild] + [SlashCommand("blacklist", "Blacklists a user from opening tickets.")] + public async Task OnExecute(InteractionContext command, [Option("User", "User to blacklist.")] DiscordUser user) + { + try + { + if (!Database.Blacklist(user.Id, command.User.Id)) + { + await command.CreateResponseAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = user.Mention + " is already blacklisted." + }, true); + return; + } + + await command.CreateResponseAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Green, + Description = "Blacklisted " + user.Mention + "." + }, true); + + // Log it if the log channel exists + DiscordChannel logChannel = command.Guild.GetChannel(Config.logChannel); + if (logChannel != null) + { + await logChannel.SendMessageAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Green, + Description = user.Mention + " was blacklisted from opening tickets by " + command.Member.Mention + "." + }); + } + } + catch (Exception) + { + await command.CreateResponseAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "Error occured while blacklisting " + user.Mention + "." + }, true); + throw; + } + } +} \ No newline at end of file diff --git a/SupportChild/Commands/CloseCommand.cs b/SupportChild/Commands/CloseCommand.cs new file mode 100644 index 0000000..69a6e39 --- /dev/null +++ b/SupportChild/Commands/CloseCommand.cs @@ -0,0 +1,134 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Threading.Tasks; +using DSharpPlus; +using DSharpPlus.Entities; +using DSharpPlus.Exceptions; +using DSharpPlus.SlashCommands; +using DSharpPlus.SlashCommands.Attributes; + +namespace SupportChild.Commands; + +public class CloseCommand : ApplicationCommandModule +{ + [SlashRequireGuild] + [SlashCommand("close", "Closes a ticket.")] + public async Task OnExecute(InteractionContext command) + { + // Check if ticket exists in the database + if (!Database.TryGetOpenTicket(command.Channel.Id, out Database.Ticket _)) + { + await command.CreateResponseAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "This channel is not a ticket." + }); + return; + } + + DiscordInteractionResponseBuilder confirmation = new DiscordInteractionResponseBuilder() + .AddEmbed(new DiscordEmbedBuilder + { + Color = DiscordColor.Cyan, + Description = "Are you sure you wish to close this ticket? You cannot re-open it again later." + }) + .AddComponents(new DiscordButtonComponent(ButtonStyle.Danger, "supportchild_closeconfirm", "Confirm")); + + + await command.CreateResponseAsync(confirmation); + } + + public static async Task OnConfirmed(DiscordInteraction interaction) + { + await interaction.CreateResponseAsync(InteractionResponseType.DeferredMessageUpdate); + ulong channelID = interaction.Channel.Id; + string channelName = interaction.Channel.Name; + + // Check if ticket exists in the database + if (!Database.TryGetOpenTicket(channelID, out Database.Ticket ticket)) + { + await interaction.EditOriginalResponseAsync(new DiscordWebhookBuilder().AddEmbed(new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "This channel is not a ticket." + })); + return; + } + + // Build transcript + try + { + await Transcriber.ExecuteAsync(interaction.Channel.Id, ticket.id); + } + catch (Exception e) + { + Logger.Error("Exception occured when trying to save transcript while closing ticket: " + e); + await interaction.EditOriginalResponseAsync(new DiscordWebhookBuilder().AddEmbed(new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "ERROR: Could not save transcript file. Aborting..." + })); + return; + } + + // Log it if the log channel exists + DiscordChannel logChannel = interaction.Guild.GetChannel(Config.logChannel); + if (logChannel != null) + { + DiscordEmbed embed = new DiscordEmbedBuilder + { + Color = DiscordColor.Green, + Description = "Ticket " + ticket.id.ToString("00000") + " closed by " + interaction.User.Mention + ".\n", + Footer = new DiscordEmbedBuilder.EmbedFooter { Text = '#' + channelName } + }; + + await using FileStream file = new FileStream(Transcriber.GetPath(ticket.id), FileMode.Open, FileAccess.Read); + DiscordMessageBuilder message = new DiscordMessageBuilder(); + message.WithEmbed(embed); + message.AddFiles(new Dictionary { { Transcriber.GetFilename(ticket.id), file } }); + + await logChannel.SendMessageAsync(message); + } + + if (Config.closingNotifications) + { + DiscordEmbed embed = new DiscordEmbedBuilder + { + Color = DiscordColor.Green, + Description = "Ticket " + ticket.id.ToString("00000") + " which you opened has now been closed, check the transcript for more info.\n", + Footer = new DiscordEmbedBuilder.EmbedFooter { Text = '#' + channelName } + }; + + try + { + DiscordMember staffMember = await interaction.Guild.GetMemberAsync(ticket.creatorID); + await using FileStream file = new FileStream(Transcriber.GetPath(ticket.id), FileMode.Open, FileAccess.Read); + + DiscordMessageBuilder message = new DiscordMessageBuilder(); + message.WithEmbed(embed); + message.AddFiles(new Dictionary { { Transcriber.GetFilename(ticket.id), file } }); + + await staffMember.SendMessageAsync(message); + } + catch (NotFoundException) { } + catch (UnauthorizedException) { } + } + + Database.ArchiveTicket(ticket); + + await interaction.EditOriginalResponseAsync(new DiscordWebhookBuilder().AddEmbed(new DiscordEmbedBuilder + { + Color = DiscordColor.Green, + Description = "Channel will be deleted in 3 seconds..." + })); + + + await Task.Delay(3000); + + // Delete the channel and database entry + await interaction.Channel.DeleteAsync("Ticket closed."); + + Database.DeleteOpenTicket(ticket.id); + } +} \ No newline at end of file diff --git a/SupportChild/Commands/CreateButtonPanelCommand.cs b/SupportChild/Commands/CreateButtonPanelCommand.cs new file mode 100644 index 0000000..1224297 --- /dev/null +++ b/SupportChild/Commands/CreateButtonPanelCommand.cs @@ -0,0 +1,81 @@ +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using DSharpPlus; +using DSharpPlus.Entities; +using DSharpPlus.SlashCommands; +using DSharpPlus.SlashCommands.Attributes; + +namespace SupportChild.Commands; + +public class CreateButtonPanelCommand : ApplicationCommandModule +{ + [SlashRequireGuild] + [SlashCommand("createbuttonpanel", "Creates a series of buttons which users can use to open new tickets in specific categories.")] + public async Task OnExecute(InteractionContext command) + { + DiscordMessageBuilder builder = new DiscordMessageBuilder().WithContent(" "); + List verifiedCategories = await Utilities.GetVerifiedChannels(); + + if (verifiedCategories.Count == 0) + { + await command.CreateResponseAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "Error: No registered categories found." + }, true); + return; + } + + verifiedCategories = verifiedCategories.OrderBy(x => x.name).ToList(); + + int nrOfButtons = 0; + for (int nrOfButtonRows = 0; nrOfButtonRows < 5 && nrOfButtons < verifiedCategories.Count; nrOfButtonRows++) + { + List buttonRow = new List(); + + for (; nrOfButtons < 5 * (nrOfButtonRows + 1) && nrOfButtons < verifiedCategories.Count; nrOfButtons++) + { + buttonRow.Add(new DiscordButtonComponent(ButtonStyle.Primary, "supportchild_newticketbutton " + verifiedCategories[nrOfButtons].id, verifiedCategories[nrOfButtons].name)); + } + builder.AddComponents(buttonRow); + } + + await command.Channel.SendMessageAsync(builder); + await command.CreateResponseAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Green, + Description = "Successfully created message, make sure to run this command again if you add new categories to the bot." + }, true); + } + + public static async Task OnButtonUsed(DiscordInteraction interaction) + { + await interaction.CreateResponseAsync(InteractionResponseType.DeferredChannelMessageWithSource, new DiscordInteractionResponseBuilder().AsEphemeral()); + + if (!ulong.TryParse(interaction.Data.CustomId.Replace("supportchild_newticketbutton ", ""), out ulong categoryID) || categoryID == 0) + { + Logger.Warn("Invalid ID: " + interaction.Data.CustomId.Replace("supportchild_newticketbutton ", "")); + return; + } + + (bool success, string message) = await NewCommand.OpenNewTicket(interaction.User.Id, interaction.ChannelId, categoryID); + + if (success) + { + await interaction.CreateFollowupMessageAsync(new DiscordFollowupMessageBuilder().AddEmbed(new DiscordEmbedBuilder + { + Color = DiscordColor.Green, + Description = message + })); + } + else + { + await interaction.CreateFollowupMessageAsync(new DiscordFollowupMessageBuilder().AddEmbed(new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = message + })); + } + } +} \ No newline at end of file diff --git a/SupportChild/Commands/CreateSelectionBoxPanelCommand.cs b/SupportChild/Commands/CreateSelectionBoxPanelCommand.cs new file mode 100644 index 0000000..4442302 --- /dev/null +++ b/SupportChild/Commands/CreateSelectionBoxPanelCommand.cs @@ -0,0 +1,79 @@ +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using DSharpPlus; +using DSharpPlus.Entities; +using DSharpPlus.SlashCommands; +using DSharpPlus.SlashCommands.Attributes; + +namespace SupportChild.Commands; + +public class CreateSelectionBoxPanelCommand : ApplicationCommandModule +{ + [SlashRequireGuild] + [SlashCommand("createselectionboxpanel", "Creates a selection box which users can use to open new tickets in specific categories.")] + public async Task OnExecute(InteractionContext command, [Option("Message", "(Optional) The message to show in the selection box.")] string message = null) + { + DiscordMessageBuilder builder = new DiscordMessageBuilder() + .WithContent(" ") + .AddComponents(await GetSelectComponents(command, message ?? "Open new ticket...")); + + await command.Channel.SendMessageAsync(builder); + await command.CreateResponseAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Green, + Description = "Successfully created message, make sure to run this command again if you add new categories to the bot." + }, true); + } + + public static async Task> GetSelectComponents(InteractionContext command, string placeholder) + { + List verifiedCategories = await Utilities.GetVerifiedChannels(); + + if (verifiedCategories.Count == 0) return new List(); + + verifiedCategories = verifiedCategories.OrderBy(x => x.name).ToList(); + List selectionComponents = new List(); + int selectionOptions = 0; + for (int selectionBoxes = 0; selectionBoxes < 5 && selectionOptions < verifiedCategories.Count; selectionBoxes++) + { + List categoryOptions = new List(); + + for (; selectionOptions < 25 * (selectionBoxes + 1) && selectionOptions < verifiedCategories.Count; selectionOptions++) + { + categoryOptions.Add(new DiscordSelectComponentOption(verifiedCategories[selectionOptions].name, verifiedCategories[selectionOptions].id.ToString())); + } + selectionComponents.Add(new DiscordSelectComponent("supportchild_newticketselector" + selectionBoxes, placeholder, categoryOptions, false, 0, 1)); + } + + return selectionComponents; + } + + public static async Task OnSelectionMenuUsed(DiscordInteraction interaction) + { + if (interaction.Data.Values == null || interaction.Data.Values.Length <= 0) return; + + if (!ulong.TryParse(interaction.Data.Values[0], out ulong categoryID) || categoryID == 0) return; + + await interaction.CreateResponseAsync(InteractionResponseType.DeferredChannelMessageWithSource, new DiscordInteractionResponseBuilder().AsEphemeral()); + + (bool success, string message) = await NewCommand.OpenNewTicket(interaction.User.Id, interaction.ChannelId, categoryID); + + if (success) + { + await interaction.CreateFollowupMessageAsync(new DiscordFollowupMessageBuilder().AddEmbed(new DiscordEmbedBuilder + { + Color = DiscordColor.Green, + Description = message + }).AsEphemeral()); + } + else + { + await interaction.CreateFollowupMessageAsync(new DiscordFollowupMessageBuilder().AddEmbed(new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = message + }).AsEphemeral()); + } + } +} \ No newline at end of file diff --git a/SupportChild/Commands/ListAssignedCommand.cs b/SupportChild/Commands/ListAssignedCommand.cs new file mode 100644 index 0000000..b9ce36f --- /dev/null +++ b/SupportChild/Commands/ListAssignedCommand.cs @@ -0,0 +1,63 @@ +using System.Collections.Generic; +using System.Threading.Tasks; +using DSharpPlus.Entities; +using DSharpPlus.Interactivity; +using DSharpPlus.Interactivity.Extensions; +using DSharpPlus.SlashCommands; +using DSharpPlus.SlashCommands.Attributes; + +namespace SupportChild.Commands; + +public class ListAssignedCommand : ApplicationCommandModule +{ + [SlashRequireGuild] + [SlashCommand("listassigned", "Lists tickets assigned to a user.")] + public async Task OnExecute(InteractionContext command, [Option("User", "(Optional) User to list tickets for.")] DiscordUser user = null) + { + DiscordUser listUser = user == null ? command.User : user; + + if (!Database.TryGetAssignedTickets(listUser.Id, out List assignedTickets)) + { + await command.CreateResponseAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "User does not have any assigned tickets." + }); + return; + } + + List listItems = new List(); + foreach (Database.Ticket ticket in assignedTickets) + { + listItems.Add("**" + ticket.DiscordRelativeTime() + ":** <#" + ticket.channelID + "> by <@" + ticket.creatorID + ">\n"); + } + + List embeds = new List(); + foreach (string message in Utilities.ParseListIntoMessages(listItems)) + { + embeds.Add(new DiscordEmbedBuilder + { + Title = "Assigned tickets: ", + Color = DiscordColor.Green, + Description = message + }); + } + + // Add the footers + for (int i = 0; i < embeds.Count; i++) + { + embeds[i].Footer = new DiscordEmbedBuilder.EmbedFooter + { + Text = $"Page {i + 1} / {embeds.Count}" + }; + } + + List listPages = new List(); + foreach (DiscordEmbedBuilder embed in embeds) + { + listPages.Add(new Page("", embed)); + } + + await command.Interaction.SendPaginatedResponseAsync(true, command.User, listPages); + } +} \ No newline at end of file diff --git a/SupportChild/Commands/ListCommand.cs b/SupportChild/Commands/ListCommand.cs new file mode 100644 index 0000000..e2811b5 --- /dev/null +++ b/SupportChild/Commands/ListCommand.cs @@ -0,0 +1,99 @@ +using System.Collections.Generic; +using System.Threading.Tasks; +using DSharpPlus.Entities; +using DSharpPlus.Interactivity; +using DSharpPlus.Interactivity.Extensions; +using DSharpPlus.SlashCommands; +using DSharpPlus.SlashCommands.Attributes; + +namespace SupportChild.Commands; + +public class ListCommand : ApplicationCommandModule +{ + [SlashRequireGuild] + [SlashCommand("list", "Lists tickets opened by a user.")] + public async Task OnExecute(InteractionContext command, [Option("User", "(Optional) The user to get tickets by.")] DiscordUser user = null) + { + DiscordUser listUser = user == null ? command.User : user; + + List openEmbeds = new List(); + if (Database.TryGetOpenTickets(listUser.Id, out List openTickets)) + { + List listItems = new List(); + foreach (Database.Ticket ticket in openTickets) + { + listItems.Add("**" + ticket.DiscordRelativeTime() + ":** <#" + ticket.channelID + ">\n"); + } + + foreach (string message in Utilities.ParseListIntoMessages(listItems)) + { + openEmbeds.Add(new DiscordEmbedBuilder + { + Color = DiscordColor.Green, + Description = message + }); + } + + // Add the titles + for (int i = 0; i < openEmbeds.Count; i++) + { + openEmbeds[i].Title = $"Open tickets ({i + 1}/{openEmbeds.Count})"; + } + } + + List closedEmbeds = new List(); + if (Database.TryGetClosedTickets(listUser.Id, out List closedTickets)) + { + List listItems = new List(); + foreach (Database.Ticket ticket in closedTickets) + { + listItems.Add("**" + ticket.DiscordRelativeTime() + ":** Ticket " + ticket.id.ToString("00000") + "\n"); + } + + foreach (string message in Utilities.ParseListIntoMessages(listItems)) + { + closedEmbeds.Add(new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = message + }); + } + + // Add the titles + for (int i = 0; i < closedEmbeds.Count; i++) + { + closedEmbeds[i].Title = $"Closed tickets ({i + 1}/{closedEmbeds.Count})"; + } + } + + // Merge the embed lists and add the footers + List embeds = new List(); + embeds.AddRange(openEmbeds); + embeds.AddRange(closedEmbeds); + for (int i = 0; i < embeds.Count; i++) + { + embeds[i].Footer = new DiscordEmbedBuilder.EmbedFooter + { + Text = $"Page {i + 1} / {embeds.Count}" + }; + } + + if (embeds.Count == 0) + { + await command.CreateResponseAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Cyan, + Description = "User does not have any open or closed tickets." + }); + return; + } + + List listPages = new List(); + foreach (DiscordEmbedBuilder embed in embeds) + { + listPages.Add(new Page("", embed)); + } + + await command.Interaction.SendPaginatedResponseAsync(true, command.User, listPages); + } +} \ No newline at end of file diff --git a/SupportChild/Commands/ListOpen.cs b/SupportChild/Commands/ListOpen.cs new file mode 100644 index 0000000..7775e17 --- /dev/null +++ b/SupportChild/Commands/ListOpen.cs @@ -0,0 +1,60 @@ +using System.Collections.Generic; +using System.Threading.Tasks; +using DSharpPlus.Entities; +using DSharpPlus.Interactivity; +using DSharpPlus.Interactivity.Extensions; +using DSharpPlus.SlashCommands; +using DSharpPlus.SlashCommands.Attributes; + +namespace SupportChild.Commands; + +public class ListOpen : ApplicationCommandModule +{ + [SlashRequireGuild] + [SlashCommand("listopen", "Lists all open tickets, oldest first.")] + public async Task OnExecute(InteractionContext command) + { + if (!Database.TryGetOpenTickets(out List openTickets)) + { + await command.CreateResponseAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "Could not fetch any open tickets." + }); + return; + } + + List listItems = new List(); + foreach (Database.Ticket ticket in openTickets) + { + listItems.Add("**" + ticket.DiscordRelativeTime() + ":** <#" + ticket.channelID + "> by <@" + ticket.creatorID + ">\n"); + } + + List embeds = new List(); + foreach (string message in Utilities.ParseListIntoMessages(listItems)) + { + embeds.Add(new DiscordEmbedBuilder + { + Color = DiscordColor.Green, + Description = message + }); + } + + // Add the footers + for (int i = 0; i < embeds.Count; i++) + { + embeds[i].Footer = new DiscordEmbedBuilder.EmbedFooter + { + Text = $"Page {i + 1} / {embeds.Count}" + }; + } + + List listPages = new List(); + foreach (DiscordEmbedBuilder embed in embeds) + { + listPages.Add(new Page("", embed)); + } + + await command.Interaction.SendPaginatedResponseAsync(true, command.User, listPages); + } +} \ No newline at end of file diff --git a/SupportChild/Commands/ListUnassignedCommand.cs b/SupportChild/Commands/ListUnassignedCommand.cs new file mode 100644 index 0000000..bb0bba7 --- /dev/null +++ b/SupportChild/Commands/ListUnassignedCommand.cs @@ -0,0 +1,61 @@ +using System.Collections.Generic; +using System.Threading.Tasks; +using DSharpPlus.Entities; +using DSharpPlus.Interactivity; +using DSharpPlus.Interactivity.Extensions; +using DSharpPlus.SlashCommands; +using DSharpPlus.SlashCommands.Attributes; + +namespace SupportChild.Commands; + +public class ListUnassignedCommand : ApplicationCommandModule +{ + [SlashRequireGuild] + [SlashCommand("listunassigned", "Lists unassigned tickets.")] + public async Task OnExecute(InteractionContext command) + { + if (!Database.TryGetAssignedTickets(0, out List unassignedTickets)) + { + await command.CreateResponseAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Green, + Description = "There are no unassigned tickets." + }); + return; + } + + List listItems = new List(); + foreach (Database.Ticket ticket in unassignedTickets) + { + listItems.Add("**" + ticket.DiscordRelativeTime() + ":** <#" + ticket.channelID + "> by <@" + ticket.creatorID + ">\n"); + } + + List embeds = new List(); + foreach (string message in Utilities.ParseListIntoMessages(listItems)) + { + embeds.Add(new DiscordEmbedBuilder + { + Title = "Unassigned tickets: ", + Color = DiscordColor.Green, + Description = message + }); + } + + // Add the footers + for (int i = 0; i < embeds.Count; i++) + { + embeds[i].Footer = new DiscordEmbedBuilder.EmbedFooter + { + Text = $"Page {i + 1} / {embeds.Count}" + }; + } + + List listPages = new List(); + foreach (DiscordEmbedBuilder embed in embeds) + { + listPages.Add(new Page("", embed)); + } + + await command.Interaction.SendPaginatedResponseAsync(true, command.User, listPages); + } +} \ No newline at end of file diff --git a/SupportChild/Commands/MoveCommand.cs b/SupportChild/Commands/MoveCommand.cs new file mode 100644 index 0000000..e81cf70 --- /dev/null +++ b/SupportChild/Commands/MoveCommand.cs @@ -0,0 +1,83 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using DSharpPlus.Entities; +using DSharpPlus.Exceptions; +using DSharpPlus.SlashCommands; +using DSharpPlus.SlashCommands.Attributes; + +namespace SupportChild.Commands; + +public class MoveCommand : ApplicationCommandModule +{ + [SlashRequireGuild] + [SlashCommand("move", "Moves a ticket to another category.")] + public async Task OnExecute(InteractionContext command, [Option("Category", "The category to move the ticket to. Only has to be the beginning of the name.")] string category) + { + // Check if ticket exists in the database + if (!Database.TryGetOpenTicket(command.Channel.Id, out Database.Ticket _)) + { + await command.CreateResponseAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "This channel is not a ticket." + }, true); + return; + } + + if (string.IsNullOrEmpty(category)) + { + await command.CreateResponseAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "Error: No category provided." + }, true); + return; + } + + IReadOnlyList channels = await command.Guild.GetChannelsAsync(); + IEnumerable categories = channels.Where(x => x.IsCategory); + DiscordChannel categoryChannel = categories.FirstOrDefault(x => x.Name.StartsWith(category.Trim(), StringComparison.OrdinalIgnoreCase)); + + if (categoryChannel == null) + { + await command.CreateResponseAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "Error: Could not find a category by that name." + }, true); + return; + } + + if (command.Channel.Id == categoryChannel.Id) + { + await command.CreateResponseAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "Error: The ticket is already in that category." + }, true); + return; + } + + try + { + await command.Channel.ModifyAsync(modifiedAttributes => modifiedAttributes.Parent = categoryChannel); + } + catch (UnauthorizedException) + { + await command.CreateResponseAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "Error: Not authorized to move this ticket to that category." + }, true); + return; + } + + await command.CreateResponseAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Green, + Description = "Ticket was moved to " + categoryChannel.Mention + }); + } +} \ No newline at end of file diff --git a/SupportChild/Commands/NewCommand.cs b/SupportChild/Commands/NewCommand.cs new file mode 100644 index 0000000..2257fe9 --- /dev/null +++ b/SupportChild/Commands/NewCommand.cs @@ -0,0 +1,276 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using DSharpPlus; +using DSharpPlus.Entities; +using DSharpPlus.Exceptions; +using DSharpPlus.SlashCommands; +using DSharpPlus.SlashCommands.Attributes; + +namespace SupportChild.Commands; + +public class NewCommand : ApplicationCommandModule +{ + [SlashRequireGuild] + [SlashCommand("new", "Opens a new ticket.")] + public async Task OnExecute(InteractionContext command) + { + List verifiedCategories = await Utilities.GetVerifiedChannels(); + switch (verifiedCategories.Count) + { + case 0: + await command.CreateResponseAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "Error: No registered categories found." + }, true); + return; + case 1: + await command.DeferAsync(true); + (bool success, string message) = await OpenNewTicket(command.User.Id, command.Channel.Id, verifiedCategories[0].id); + + if (success) + { + await command.FollowUpAsync(new DiscordFollowupMessageBuilder().AddEmbed(new DiscordEmbedBuilder + { + Color = DiscordColor.Green, + Description = message + }).AsEphemeral()); + } + else + { + await command.FollowUpAsync(new DiscordFollowupMessageBuilder().AddEmbed(new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = message + }).AsEphemeral()); + } + return; + default: + if (Config.newCommandUsesSelector) + { + await CreateSelector(command, verifiedCategories); + } + else + { + await CreateButtons(command, verifiedCategories); + } + return; + } + } + + public static async Task CreateButtons(InteractionContext command, List verifiedCategories) + { + DiscordInteractionResponseBuilder builder = new DiscordInteractionResponseBuilder().WithContent(" "); + int nrOfButtons = 0; + for (int nrOfButtonRows = 0; nrOfButtonRows < 5 && nrOfButtons < verifiedCategories.Count; nrOfButtonRows++) + { + List buttonRow = new List(); + + for (; nrOfButtons < 5 * (nrOfButtonRows + 1) && nrOfButtons < verifiedCategories.Count; nrOfButtons++) + { + buttonRow.Add(new DiscordButtonComponent(ButtonStyle.Primary, "supportchild_newcommandbutton " + verifiedCategories[nrOfButtons].id, verifiedCategories[nrOfButtons].name)); + } + builder.AddComponents(buttonRow); + } + + await command.CreateResponseAsync(builder.AsEphemeral()); + } + + public static async Task CreateSelector(InteractionContext command, List verifiedCategories) + { + verifiedCategories = verifiedCategories.OrderBy(x => x.name).ToList(); + List selectionComponents = new List(); + int selectionOptions = 0; + for (int selectionBoxes = 0; selectionBoxes < 5 && selectionOptions < verifiedCategories.Count; selectionBoxes++) + { + List categoryOptions = new List(); + + for (; selectionOptions < 25 * (selectionBoxes + 1) && selectionOptions < verifiedCategories.Count; selectionOptions++) + { + categoryOptions.Add(new DiscordSelectComponentOption(verifiedCategories[selectionOptions].name, verifiedCategories[selectionOptions].id.ToString())); + } + selectionComponents.Add(new DiscordSelectComponent("supportchild_newcommandselector" + selectionBoxes, "Open new ticket...", categoryOptions, false, 0, 1)); + } + + await command.CreateResponseAsync(new DiscordInteractionResponseBuilder().AddComponents(selectionComponents).AsEphemeral()); + } + + public static async Task OnCategorySelection(DiscordInteraction interaction) + { + string stringID; + switch (interaction.Data.ComponentType) + { + case ComponentType.Button: + stringID = interaction.Data.CustomId.Replace("supportchild_newcommandbutton ", ""); + break; + case ComponentType.StringSelect: + if (interaction.Data.Values == null || interaction.Data.Values.Length <= 0) return; + stringID = interaction.Data.Values[0]; + break; + + case ComponentType.ActionRow: + case ComponentType.FormInput: + default: + return; + } + + if (!ulong.TryParse(stringID, out ulong categoryID) || categoryID == 0) return; + + await interaction.CreateResponseAsync(InteractionResponseType.DeferredMessageUpdate, new DiscordInteractionResponseBuilder().AsEphemeral()); + + (bool success, string message) = await OpenNewTicket(interaction.User.Id, interaction.ChannelId, categoryID); + + if (success) + { + await interaction.EditOriginalResponseAsync(new DiscordWebhookBuilder().AddEmbed(new DiscordEmbedBuilder + { + Color = DiscordColor.Green, + Description = message + })); + } + else + { + await interaction.EditOriginalResponseAsync(new DiscordWebhookBuilder().AddEmbed(new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = message + })); + } + } + + public static async Task<(bool, string)> OpenNewTicket(ulong userID, ulong commandChannelID, ulong categoryID) + { + // Check if user is blacklisted + if (Database.IsBlacklisted(userID)) + { + return (false, "You are banned from opening tickets."); + } + + if (Database.IsOpenTicket(commandChannelID)) + { + return (false, "You cannot use this command in a ticket channel."); + } + + if (!Database.IsStaff(userID) && Database.TryGetOpenTickets(userID, out List ownTickets) && ownTickets.Count >= Config.ticketLimit) + { + return (false, "You have reached the limit for maximum open tickets."); + } + + DiscordChannel category = null; + try + { + category = await SupportChild.discordClient.GetChannelAsync(categoryID); + } + catch (Exception) { /*ignored*/ } + + if (category == null) + { + return (false, "Error: Could not find the category to place the ticket in."); + } + + DiscordMember member = null; + try + { + member = await category.Guild.GetMemberAsync(userID); + } + catch (Exception) { /*ignored*/ } + + if (member == null) + { + return (false, "Error: Could not find you on the Discord server."); + } + + DiscordChannel ticketChannel = null; + + try + { + ticketChannel = await category.Guild.CreateChannelAsync("ticket", ChannelType.Text, category); + } + catch (Exception) { /* ignored */ } + + if (ticketChannel == null) + { + return (false, "Error occured while creating ticket, " + member.Mention + + "!\nIs the channel limit reached in the server or ticket category?"); + } + + ulong staffID = 0; + if (Config.randomAssignment) + { + staffID = Database.GetRandomActiveStaff(0)?.userID ?? 0; + } + + long id = Database.NewTicket(member.Id, staffID, ticketChannel.Id); + string ticketID = id.ToString("00000"); + + try + { + await ticketChannel.ModifyAsync(modifiedAttributes => modifiedAttributes.Name = "ticket-" + ticketID); + } + catch (DiscordException e) + { + Logger.Error("Exception occurred trying to modify channel: " + e); + Logger.Error("JsomMessage: " + e.JsonMessage); + } + + try + { + await ticketChannel.AddOverwriteAsync(member, Permissions.AccessChannels); + } + catch (DiscordException e) + { + Logger.Error("Exception occurred trying to add channel permissions: " + e); + Logger.Error("JsomMessage: " + e.JsonMessage); + } + + await ticketChannel.SendMessageAsync("Hello, " + member.Mention + "!\n" + Config.welcomeMessage); + + // Refreshes the channel as changes were made to it above + ticketChannel = await SupportChild.discordClient.GetChannelAsync(ticketChannel.Id); + + if (staffID != 0) + { + await ticketChannel.SendMessageAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Green, + Description = "Ticket was randomly assigned to <@" + staffID + ">." + }); + + if (Config.assignmentNotifications) + { + try + { + DiscordMember staffMember = await category.Guild.GetMemberAsync(staffID); + await staffMember.SendMessageAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Green, + Description = "You have been randomly assigned to a newly opened support ticket: " + + ticketChannel.Mention + }); + } + catch (DiscordException e) + { + Logger.Error("Exception occurred assign random staff member: " + e); + Logger.Error("JsomMessage: " + e.JsonMessage); + } + } + } + + // Log it if the log channel exists + DiscordChannel logChannel = category.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); + } + + return (true, "Ticket opened, " + member.Mention + "!\n" + ticketChannel.Mention); + } +} \ No newline at end of file diff --git a/SupportChild/Commands/RandomAssignCommand.cs b/SupportChild/Commands/RandomAssignCommand.cs new file mode 100644 index 0000000..36d633d --- /dev/null +++ b/SupportChild/Commands/RandomAssignCommand.cs @@ -0,0 +1,139 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using DSharpPlus.Entities; +using DSharpPlus.Exceptions; +using DSharpPlus.SlashCommands; +using DSharpPlus.SlashCommands.Attributes; +using Microsoft.Extensions.Logging; + +namespace SupportChild.Commands; + +public class RandomAssignCommand : ApplicationCommandModule +{ + [SlashRequireGuild] + [SlashCommand("rassign", "Randomly assigns a staff member to a ticket.")] + public async Task OnExecute(InteractionContext command, [Option("Role", "(Optional) Limit the random assignment to a specific role.")] DiscordRole role = null) + { + // Check if ticket exists in the database + if (!Database.TryGetOpenTicket(command.Channel.Id, out Database.Ticket ticket)) + { + await command.CreateResponseAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "Error: This channel is not a ticket." + }, true); + return; + } + + // Get a random staff member who is verified to have the correct role if applicable + DiscordMember staffMember = await GetRandomVerifiedStaffMember(command, role, ticket); + if (staffMember == null) + { + return; + } + + // Attempt to assign the staff member to the ticket + if (!Database.AssignStaff(ticket, staffMember.Id)) + { + await command.CreateResponseAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "Error: Failed to assign " + staffMember.Mention + " to ticket." + }, true); + return; + } + + // Respond that the command was successful + await command.CreateResponseAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Green, + Description = "Randomly assigned " + staffMember.Mention + " to ticket." + }); + + // Send a notification to the staff member if applicable + if (Config.assignmentNotifications) + { + try + { + await staffMember.SendMessageAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Green, + Description = "You have been randomly assigned to a support ticket: " + command.Channel.Mention + }); + } + catch (UnauthorizedException) { } + } + + // Log it if the log channel exists + DiscordChannel logChannel = command.Guild.GetChannel(Config.logChannel); + if (logChannel != null) + { + await logChannel.SendMessageAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Green, + Description = staffMember.Mention + " was randomly assigned to " + command.Channel.Mention + " by " + command.Member.Mention + "." + }); + } + } + + private static async Task GetRandomVerifiedStaffMember(InteractionContext command, DiscordRole targetRole, Database.Ticket ticket) + { + if (targetRole != null) // A role was provided + { + // Check if role rassign should override staff's active status + List staffMembers = Config.randomAssignRoleOverride + ? Database.GetAllStaff(ticket.assignedStaffID, ticket.creatorID) + : Database.GetActiveStaff(ticket.assignedStaffID, ticket.creatorID); + + // Randomize the list before checking for roles in order to reduce number of API calls + staffMembers.Shuffle(); + + // Get the first staff member that has the role + foreach (Database.StaffMember sm in staffMembers) + { + try + { + DiscordMember verifiedMember = await command.Guild.GetMemberAsync(sm.userID); + if (verifiedMember?.Roles?.Any(role => role.Id == targetRole.Id) ?? false) + { + return verifiedMember; + } + } + catch (Exception e) + { + command.Client.Logger.Log(LogLevel.Information, e, "Error occured trying to find a staff member in the rassign command."); + } + } + } + else // No role was specified, any active staff will be picked + { + Database.StaffMember staffEntry = Database.GetRandomActiveStaff(ticket.assignedStaffID, ticket.creatorID); + if (staffEntry == null) + { + await command.CreateResponseAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "Error: There are no other staff members to choose from." + }, true); + return null; + } + + // Get the staff member from discord + try + { + return await command.Guild.GetMemberAsync(staffEntry.userID); + } + catch (NotFoundException) { } + } + + // Send a more generic error if we get to this point and still haven't found the staff member + await command.CreateResponseAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "Error: Could not find an applicable staff member." + }, true); + return null; + } +} \ No newline at end of file diff --git a/SupportChild/Commands/RemoveCategoryCommand.cs b/SupportChild/Commands/RemoveCategoryCommand.cs new file mode 100644 index 0000000..0cef6a4 --- /dev/null +++ b/SupportChild/Commands/RemoveCategoryCommand.cs @@ -0,0 +1,41 @@ +using System.Threading.Tasks; +using DSharpPlus.Entities; +using DSharpPlus.SlashCommands; +using DSharpPlus.SlashCommands.Attributes; + +namespace SupportChild.Commands; + +public class RemoveCategoryCommand : ApplicationCommandModule +{ + [SlashRequireGuild] + [SlashCommand("removecategory", "Removes the ability for users to open tickets in a specific category.")] + public async Task OnExecute(InteractionContext command, [Option("Category", "The category to remove.")] DiscordChannel channel) + { + if (!Database.TryGetCategory(channel.Id, out Database.Category _)) + { + await command.CreateResponseAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "That category is not registered." + }, true); + return; + } + + if (Database.RemoveCategory(channel.Id)) + { + await command.CreateResponseAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Green, + Description = "Category removed." + }, true); + } + else + { + await command.CreateResponseAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "Error: Failed removing the category from the database." + }, true); + } + } +} \ No newline at end of file diff --git a/SupportChild/Commands/RemoveMessageCommand.cs b/SupportChild/Commands/RemoveMessageCommand.cs new file mode 100644 index 0000000..fc14a0f --- /dev/null +++ b/SupportChild/Commands/RemoveMessageCommand.cs @@ -0,0 +1,41 @@ +using DSharpPlus.Entities; +using System.Threading.Tasks; +using DSharpPlus.SlashCommands; +using DSharpPlus.SlashCommands.Attributes; + +namespace SupportChild.Commands; + +public class RemoveMessageCommand : ApplicationCommandModule +{ + [SlashRequireGuild] + [SlashCommand("removemessage", "Removes a message from the 'say' command.")] + public async Task OnExecute(InteractionContext command, [Option("Identifier", "The identifier word used in the /say command.")] string identifier) + { + if (!Database.TryGetMessage(identifier.ToLower(), out Database.Message _)) + { + await command.CreateResponseAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "There is no message with that identifier." + }, true); + return; + } + + if (Database.RemoveMessage(identifier)) + { + await command.CreateResponseAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Green, + Description = "Message removed." + }, true); + } + else + { + await command.CreateResponseAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "Error: Failed removing the message from the database." + }, true); + } + } +} \ No newline at end of file diff --git a/SupportChild/Commands/RemoveStaffCommand.cs b/SupportChild/Commands/RemoveStaffCommand.cs new file mode 100644 index 0000000..a038918 --- /dev/null +++ b/SupportChild/Commands/RemoveStaffCommand.cs @@ -0,0 +1,49 @@ +using System.Threading.Tasks; +using DSharpPlus.Entities; +using DSharpPlus.SlashCommands; +using DSharpPlus.SlashCommands.Attributes; +using MySqlConnector; + +namespace SupportChild.Commands; + +public class RemoveStaffCommand : ApplicationCommandModule +{ + [SlashRequireGuild] + [SlashCommand("removestaff", "Removes a staff member.")] + public async Task OnExecute(InteractionContext command, [Option("User", "User to remove from staff.")] DiscordUser user) + { + if (!Database.IsStaff(user.Id)) + { + await command.CreateResponseAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "User is already not registered as staff." + }, true); + return; + } + + await using MySqlConnection c = Database.GetConnection(); + c.Open(); + MySqlCommand deletion = new MySqlCommand(@"DELETE FROM staff WHERE user_id=@user_id", c); + deletion.Parameters.AddWithValue("@user_id", user.Id); + deletion.Prepare(); + deletion.ExecuteNonQuery(); + + await command.CreateResponseAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Green, + Description = "User was removed from staff." + }, true); + + // Log it if the log channel exists + DiscordChannel logChannel = command.Guild.GetChannel(Config.logChannel); + if (logChannel != null) + { + await logChannel.SendMessageAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Green, + Description = "User was removed from staff.\n" + }); + } + } +} \ No newline at end of file diff --git a/SupportChild/Commands/SayCommand.cs b/SupportChild/Commands/SayCommand.cs new file mode 100644 index 0000000..b198b9c --- /dev/null +++ b/SupportChild/Commands/SayCommand.cs @@ -0,0 +1,67 @@ +using DSharpPlus.Entities; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using DSharpPlus.SlashCommands; +using DSharpPlus.SlashCommands.Attributes; + +namespace SupportChild.Commands; + +public class SayCommand : ApplicationCommandModule +{ + [SlashRequireGuild] + [SlashCommand("say", "Prints a message with information from staff. Use without identifier to list all identifiers.")] + public async Task OnExecute(InteractionContext command, [Option("Identifier", "(Optional) The identifier word to summon a message.")] string identifier = null) + { + // Print list of all messages if no identifier is provided + if (identifier == null) + { + List messages = Database.GetAllMessages(); + if (!messages.Any()) + { + await command.CreateResponseAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "There are no messages registered." + }, true); + return; + } + + List listItems = new List(); + foreach (Database.Message message in messages) + { + listItems.Add("**" + message.identifier + "** Added by <@" + message.userID + ">\n"); + } + + LinkedList listMessages = Utilities.ParseListIntoMessages(listItems); + foreach (string listMessage in listMessages) + { + await command.CreateResponseAsync(new DiscordEmbedBuilder + { + Title = "Available messages: ", + Color = DiscordColor.Green, + Description = listMessage + }, true); + } + } + // Print specific message + else + { + if (!Database.TryGetMessage(identifier.ToLower(), out Database.Message message)) + { + await command.CreateResponseAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "There is no message with that identifier." + }, true); + return; + } + + await command.CreateResponseAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Cyan, + Description = message.message.Replace("\\n", "\n") + }); + } + } +} \ No newline at end of file diff --git a/SupportChild/Commands/SetSummaryCommand.cs b/SupportChild/Commands/SetSummaryCommand.cs new file mode 100644 index 0000000..106fd9e --- /dev/null +++ b/SupportChild/Commands/SetSummaryCommand.cs @@ -0,0 +1,42 @@ +using System.Threading.Tasks; +using DSharpPlus.Entities; +using DSharpPlus.SlashCommands; +using DSharpPlus.SlashCommands.Attributes; +using MySqlConnector; + +namespace SupportChild.Commands; + +public class SetSummaryCommand : ApplicationCommandModule +{ + [SlashRequireGuild] + [SlashCommand("setsummary", "Sets a ticket's summary for the summary command.")] + public async Task OnExecute(InteractionContext command, [Option("Summary", "The ticket summary text.")] string summary) + { + ulong channelID = command.Channel.Id; + // Check if ticket exists in the database + if (!Database.TryGetOpenTicket(command.Channel.Id, out Database.Ticket _)) + { + await command.CreateResponseAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "This channel is not a ticket." + }); + return; + } + + await using MySqlConnection c = Database.GetConnection(); + c.Open(); + MySqlCommand update = new MySqlCommand(@"UPDATE tickets SET summary = @summary WHERE channel_id = @channel_id", c); + update.Parameters.AddWithValue("@summary", summary); + update.Parameters.AddWithValue("@channel_id", channelID); + update.Prepare(); + update.ExecuteNonQuery(); + update.Dispose(); + + await command.CreateResponseAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Green, + Description = "Summary set." + }, true); + } +} \ No newline at end of file diff --git a/SupportChild/Commands/StatusCommand.cs b/SupportChild/Commands/StatusCommand.cs new file mode 100644 index 0000000..bfbbf78 --- /dev/null +++ b/SupportChild/Commands/StatusCommand.cs @@ -0,0 +1,26 @@ +using System.Threading.Tasks; +using DSharpPlus.Entities; +using DSharpPlus.SlashCommands; +using DSharpPlus.SlashCommands.Attributes; + +namespace SupportChild.Commands; + +public class StatusCommand : ApplicationCommandModule +{ + [SlashRequireGuild] + [SlashCommand("status", "Shows bot status and information.")] + public async Task OnExecute(InteractionContext command) + { + long openTickets = Database.GetNumberOfTickets(); + long closedTickets = Database.GetNumberOfClosedTickets(); + + DiscordEmbed botInfo = new DiscordEmbedBuilder() + .WithAuthor("Emotion-stuff/supportchild @ Toastielab", "https://toastielab.dev/Emotions-stuff/SupportChild", "https://cdn.discordapp.com/attachments/765441543100170271/914327948667011132/Ellie_Concept_2_transparent_ver.png") + .WithTitle("Bot information") + .WithColor(DiscordColor.Cyan) + .AddField("Version:", SupportChild.GetVersion()) + .AddField("Open tickets:", openTickets + "", true) + .AddField("Closed tickets:", closedTickets + " ", true); + await command.CreateResponseAsync(botInfo); + } +} diff --git a/SupportChild/Commands/SummaryCommand.cs b/SupportChild/Commands/SummaryCommand.cs new file mode 100644 index 0000000..69a0a3b --- /dev/null +++ b/SupportChild/Commands/SummaryCommand.cs @@ -0,0 +1,35 @@ +using System.Threading.Tasks; +using DSharpPlus.Entities; +using DSharpPlus.SlashCommands; +using DSharpPlus.SlashCommands.Attributes; + +namespace SupportChild.Commands; + +public class SummaryCommand : ApplicationCommandModule +{ + [SlashRequireGuild] + [SlashCommand("summary", "Lists tickets assigned to a user.")] + public async Task OnExecute(InteractionContext command) + { + if (Database.TryGetOpenTicket(command.Channel.Id, out Database.Ticket ticket)) + { + DiscordEmbed channelInfo = new DiscordEmbedBuilder() + .WithTitle("Channel information") + .WithColor(DiscordColor.Cyan) + .AddField("Ticket number:", ticket.id.ToString("00000"), true) + .AddField("Ticket creator:", $"<@{ticket.creatorID}>", true) + .AddField("Assigned staff:", ticket.assignedStaffID == 0 ? "Unassigned." : $"<@{ticket.assignedStaffID}>", true) + .AddField("Creation time:", ticket.DiscordRelativeTime(), true) + .AddField("Summary:", string.IsNullOrEmpty(ticket.summary) ? "No summary." : ticket.summary.Replace("\\n", "\n")); + await command.CreateResponseAsync(channelInfo); + } + else + { + await command.CreateResponseAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "This channel is not a ticket." + }, true); + } + } +} \ No newline at end of file diff --git a/SupportChild/Commands/ToggleActiveCommand.cs b/SupportChild/Commands/ToggleActiveCommand.cs new file mode 100644 index 0000000..1e07cfa --- /dev/null +++ b/SupportChild/Commands/ToggleActiveCommand.cs @@ -0,0 +1,44 @@ +using System.Threading.Tasks; +using DSharpPlus.Entities; +using DSharpPlus.SlashCommands; +using DSharpPlus.SlashCommands.Attributes; + +namespace SupportChild.Commands; + +public class ToggleActiveCommand : ApplicationCommandModule +{ + [SlashRequireGuild] + [SlashCommand("toggleactive", "Toggles active status for a staff member.")] + public async Task OnExecute(InteractionContext command, [Option("User", "(Optional) Staff member to toggle activity for.")] DiscordUser user = null) + { + DiscordUser staffUser = user == null ? command.User : user; + + // Check if ticket exists in the database + if (!Database.TryGetStaff(staffUser.Id, out Database.StaffMember staffMember)) + { + await command.CreateResponseAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = user == null ? "You have not been registered as staff." : "The user is not registered as staff." + }, true); + return; + } + + if (Database.SetStaffActive(staffUser.Id, !staffMember.active)) + { + await command.CreateResponseAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Green, + Description = staffMember.active ? "Staff member is now set as inactive and will no longer be randomly assigned any support tickets." : "Staff member is now set as active and will be randomly assigned support tickets again." + }, true); + } + else + { + await command.CreateResponseAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "Error: Unable to update active status in database." + }, true); + } + } +} \ No newline at end of file diff --git a/SupportChild/Commands/TranscriptCommand.cs b/SupportChild/Commands/TranscriptCommand.cs new file mode 100644 index 0000000..4303168 --- /dev/null +++ b/SupportChild/Commands/TranscriptCommand.cs @@ -0,0 +1,129 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Threading.Tasks; +using DSharpPlus.Entities; +using DSharpPlus.Exceptions; +using DSharpPlus.SlashCommands; +using DSharpPlus.SlashCommands.Attributes; + +namespace SupportChild.Commands; + +public class TranscriptCommand : ApplicationCommandModule +{ + [SlashRequireGuild] + [SlashCommand("transcript", "Creates a transcript of a ticket.")] + public async Task OnExecute(InteractionContext command, [Option("Ticket", "(Optional) Ticket number to get transcript of.")] long ticketID = 0) + { + await command.DeferAsync(true); + Database.Ticket ticket; + if (ticketID == 0) // If there are no arguments use current channel + { + if (Database.TryGetOpenTicket(command.Channel.Id, out ticket)) + { + try + { + await Transcriber.ExecuteAsync(command.Channel.Id, ticket.id); + } + catch (Exception) + { + await command.EditResponseAsync(new DiscordWebhookBuilder().AddEmbed(new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "ERROR: Could not save transcript file. Aborting..." + })); + throw; + } + } + else + { + await command.EditResponseAsync(new DiscordWebhookBuilder().AddEmbed(new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "This channel is not a ticket." + })); + return; + } + } + else + { + // If the ticket is still open, generate a new fresh transcript + if (Database.TryGetOpenTicketByID((uint)ticketID, out ticket) && ticket?.creatorID == command.Member.Id) + { + try + { + await Transcriber.ExecuteAsync(command.Channel.Id, ticket.id); + } + catch (Exception) + { + await command.EditResponseAsync(new DiscordWebhookBuilder().AddEmbed(new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "ERROR: Could not save transcript file. Aborting..." + })); + throw; + } + + } + // If there is no open or closed ticket, send an error. If there is a closed ticket we will simply use the old transcript from when the ticket was closed. + else if (!Database.TryGetClosedTicket((uint)ticketID, out ticket) || (ticket?.creatorID != command.Member.Id && !Database.IsStaff(command.Member.Id))) + { + await command.EditResponseAsync(new DiscordWebhookBuilder().AddEmbed(new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "Could not find a closed ticket with that number which you opened.\n(Use the /list command to see all your tickets)" + })); + return; + } + } + + // Log it if the log channel exists + DiscordChannel logChannel = command.Guild.GetChannel(Config.logChannel); + if (logChannel != null) + { + await using FileStream file = new FileStream(Transcriber.GetPath(ticket.id), FileMode.Open, FileAccess.Read); + + DiscordMessageBuilder message = new DiscordMessageBuilder(); + message.WithEmbed(new DiscordEmbedBuilder + { + Color = DiscordColor.Green, + Description = "Ticket " + ticket.id.ToString("00000") + " transcript generated by " + command.Member.Mention + ".\n", + Footer = new DiscordEmbedBuilder.EmbedFooter { Text = '#' + command.Channel.Name } + }); + message.AddFiles(new Dictionary { { Transcriber.GetFilename(ticket.id), file } }); + + await logChannel.SendMessageAsync(message); + } + + try + { + // Send transcript in a direct message + await using FileStream file = new FileStream(Transcriber.GetPath(ticket.id), FileMode.Open, FileAccess.Read); + + DiscordMessageBuilder directMessage = new DiscordMessageBuilder(); + directMessage.WithEmbed(new DiscordEmbedBuilder + { + Color = DiscordColor.Green, + Description = "Transcript generated!\n" + }); + directMessage.AddFiles(new Dictionary { { Transcriber.GetFilename(ticket.id), file } }); + + await command.Member.SendMessageAsync(directMessage); + } + catch (UnauthorizedException) + { + await command.EditResponseAsync(new DiscordWebhookBuilder().AddEmbed(new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "Not allowed to send direct message to you, please check your privacy settings.\n" + })); + return; + } + + await command.EditResponseAsync(new DiscordWebhookBuilder().AddEmbed(new DiscordEmbedBuilder + { + Color = DiscordColor.Green, + Description = "Transcript sent!\n" + })); + } +} \ No newline at end of file diff --git a/SupportChild/Commands/UnassignCommand.cs b/SupportChild/Commands/UnassignCommand.cs new file mode 100644 index 0000000..42e272c --- /dev/null +++ b/SupportChild/Commands/UnassignCommand.cs @@ -0,0 +1,52 @@ +using System.Threading.Tasks; +using DSharpPlus.Entities; +using DSharpPlus.SlashCommands; +using DSharpPlus.SlashCommands.Attributes; + +namespace SupportChild.Commands; + +public class UnassignCommand : ApplicationCommandModule +{ + [SlashRequireGuild] + [SlashCommand("unassign", "Unassigns a staff member from a ticket.")] + public async Task OnExecute(InteractionContext command) + { + // Check if ticket exists in the database + if (!Database.TryGetOpenTicket(command.Channel.Id, out Database.Ticket ticket)) + { + await command.CreateResponseAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "This channel is not a ticket." + }, true); + return; + } + + if (!Database.UnassignStaff(ticket)) + { + await command.CreateResponseAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "Error: Failed to unassign staff member from ticket." + }, true); + return; + } + + await command.CreateResponseAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Green, + Description = "Unassigned staff member from ticket." + }); + + // Log it if the log channel exists + DiscordChannel logChannel = command.Guild.GetChannel(Config.logChannel); + if (logChannel != null) + { + await logChannel.SendMessageAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Green, + Description = "Staff member was unassigned from " + command.Channel.Mention + " by " + command.Member.Mention + "." + }); + } + } +} \ No newline at end of file diff --git a/SupportChild/Commands/UnblacklistCommand.cs b/SupportChild/Commands/UnblacklistCommand.cs new file mode 100644 index 0000000..30d591a --- /dev/null +++ b/SupportChild/Commands/UnblacklistCommand.cs @@ -0,0 +1,54 @@ +using System; +using System.Threading.Tasks; +using DSharpPlus.Entities; +using DSharpPlus.SlashCommands; +using DSharpPlus.SlashCommands.Attributes; + +namespace SupportChild.Commands; + +public class UnblacklistCommand : ApplicationCommandModule +{ + [SlashRequireGuild] + [SlashCommand("unblacklist", "Unblacklists a user from opening tickets.")] + public async Task OnExecute(InteractionContext command, [Option("User", "User to remove from blacklist.")] DiscordUser user) + { + try + { + if (!Database.Unblacklist(user.Id)) + { + await command.CreateResponseAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = user.Mention + " is not blacklisted." + }, true); + return; + } + + await command.CreateResponseAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Green, + Description = "Removed " + user.Mention + " from blacklist." + }, true); + + // Log it if the log channel exists + DiscordChannel logChannel = command.Guild.GetChannel(Config.logChannel); + if (logChannel != null) + { + await logChannel.SendMessageAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Green, + Description = user.Mention + " was unblacklisted from opening tickets by " + command.Member.Mention + "." + }); + } + } + catch (Exception) + { + await command.CreateResponseAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = "Error occured while removing " + user.Mention + " from blacklist." + }, true); + throw; + } + } +} \ No newline at end of file diff --git a/SupportChild/Config.cs b/SupportChild/Config.cs new file mode 100644 index 0000000..69ad566 --- /dev/null +++ b/SupportChild/Config.cs @@ -0,0 +1,95 @@ +using System; +using System.IO; +using System.Text; +using DSharpPlus; +using Microsoft.Extensions.Logging; +using Newtonsoft.Json.Linq; +using SupportChild.Properties; +using YamlDotNet.Serialization; + +namespace SupportChild; + +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() + { + // 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() ?? ""; + logChannel = json.SelectToken("bot.log-channel")?.Value() ?? 0; + welcomeMessage = json.SelectToken("bot.welcome-message")?.Value() ?? ""; + string stringLogLevel = json.SelectToken("bot.console-log-level")?.Value() ?? ""; + + if (!Enum.TryParse(stringLogLevel, true, out logLevel)) + { + logLevel = LogLevel.Information; + Logger.Warn("Log level '" + stringLogLevel + "' invalid, using 'Information' instead."); + } + + string stringTimestampFormat = json.SelectToken("bot.timestamp-format")?.Value() ?? "RelativeTime"; + + if (!Enum.TryParse(stringTimestampFormat, true, out timestampFormat)) + { + timestampFormat = TimestampFormat.RelativeTime; + Logger.Warn("Timestamp '" + stringTimestampFormat + "' invalid, using 'RelativeTime' instead."); + } + + randomAssignment = json.SelectToken("bot.random-assignment")?.Value() ?? false; + randomAssignRoleOverride = json.SelectToken("bot.random-assign-role-override")?.Value() ?? false; + presenceType = json.SelectToken("bot.presence-type")?.Value() ?? "Playing"; + presenceText = json.SelectToken("bot.presence-text")?.Value() ?? ""; + newCommandUsesSelector = json.SelectToken("bot.new-command-uses-selector")?.Value() ?? false; + ticketLimit = json.SelectToken("bot.ticket-limit")?.Value() ?? 5; + + ticketUpdatedNotifications = json.SelectToken("notifications.ticket-updated")?.Value() ?? false; + ticketUpdatedNotificationDelay = json.SelectToken("notifications.ticket-updated-delay")?.Value() ?? 0.0; + assignmentNotifications = json.SelectToken("notifications.assignment")?.Value() ?? false; + closingNotifications = json.SelectToken("notifications.closing")?.Value() ?? false; + + // Reads database info + hostName = json.SelectToken("database.address")?.Value() ?? ""; + port = json.SelectToken("database.port")?.Value() ?? 3306; + database = json.SelectToken("database.name")?.Value() ?? "supportchild"; + username = json.SelectToken("database.user")?.Value() ?? "supportchild"; + password = json.SelectToken("database.password")?.Value() ?? ""; + } +} \ No newline at end of file diff --git a/Database.cs b/SupportChild/Database.cs similarity index 96% rename from Database.cs rename to SupportChild/Database.cs index 517da9e..f263972 100644 --- a/Database.cs +++ b/SupportChild/Database.cs @@ -1,7 +1,6 @@ using System; using System.Linq; using System.Collections.Generic; -using System.Security.Cryptography; using DSharpPlus; using MySqlConnector; @@ -11,6 +10,8 @@ public static class Database { private static string connectionString = ""; + private static readonly Random random = new Random(); + public static void SetConnectionString(string host, int port, string database, string username, string password) { connectionString = "server=" + host + @@ -454,15 +455,29 @@ public static class Database public static StaffMember GetRandomActiveStaff(params ulong[] ignoredUserIDs) { List staffMembers = GetActiveStaff(ignoredUserIDs); - return staffMembers.Any() ? staffMembers[RandomNumberGenerator.GetInt32(staffMembers.Count)] : null; + return staffMembers.Any() ? staffMembers[random.Next(staffMembers.Count)] : null; } public static List GetActiveStaff(params ulong[] ignoredUserIDs) { + bool first = true; + string filterString = ""; + foreach (ulong userID in ignoredUserIDs) + { + if (first) + { + first = false; + filterString += "AND user_id != " + userID; + } + else + { + filterString += "&& user_id != " + userID; + } + } + using MySqlConnection c = GetConnection(); c.Open(); - using MySqlCommand selection = new MySqlCommand(@"SELECT * FROM staff WHERE active = true AND user_id NOT IN (@user_ids)", c); - selection.Parameters.AddWithValue("@user_ids", string.Join(",", ignoredUserIDs)); + using MySqlCommand selection = new MySqlCommand(@"SELECT * FROM staff WHERE active = true " + filterString, c); selection.Prepare(); MySqlDataReader results = selection.ExecuteReader(); @@ -484,10 +499,26 @@ public static class Database public static List GetAllStaff(params ulong[] ignoredUserIDs) { + bool first = true; + string filterString = ""; + foreach (ulong userID in ignoredUserIDs) + { + if (first) + { + first = false; + filterString += "WHERE user_id != " + userID; + } + else + { + filterString += "&& user_id != " + userID; + } + + } + + using MySqlConnection c = GetConnection(); c.Open(); - using MySqlCommand selection = new MySqlCommand(@"SELECT * FROM staff WHERE user_id NOT IN (@user_ids)", c); - selection.Parameters.AddWithValue("@user_ids", string.Join(",", ignoredUserIDs)); + using MySqlCommand selection = new MySqlCommand(@"SELECT * FROM staff " + filterString, c); selection.Prepare(); MySqlDataReader results = selection.ExecuteReader(); diff --git a/EventHandler.cs b/SupportChild/EventHandler.cs similarity index 90% rename from EventHandler.cs rename to SupportChild/EventHandler.cs index 583787f..e1ace25 100644 --- a/EventHandler.cs +++ b/SupportChild/EventHandler.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Linq; using System.Threading.Tasks; using DSharpPlus; using DSharpPlus.Entities; @@ -30,23 +29,17 @@ internal static class EventHandler return Task.CompletedTask; } - internal static async Task OnGuildAvailable(DiscordClient discordClient, GuildCreateEventArgs e) + internal static Task OnGuildAvailable(DiscordClient _, GuildCreateEventArgs e) { - Logger.Log("Found Discord server: " + e.Guild.Name + " (" + e.Guild.Id + ")"); - - if (SupportChild.commandLineArgs.serversToLeave.Contains(e.Guild.Id)) - { - Logger.Warn("LEAVING DISCORD SERVER AS REQUESTED: " + e.Guild.Name + " (" + e.Guild.Id + ")"); - await e.Guild.LeaveAsync(); - return; - } + Logger.Log("Guild available: " + e.Guild.Name); IReadOnlyDictionary roles = e.Guild.Roles; foreach ((ulong roleID, DiscordRole role) in roles) { - Logger.Debug(role.Name.PadRight(40, '.') + roleID); + Logger.Log(role.Name.PadRight(40, '.') + roleID); } + return Task.CompletedTask; } internal static Task OnClientError(DiscordClient _, ClientErrorEventArgs e) @@ -57,8 +50,6 @@ internal static class EventHandler case BadRequestException ex: Logger.Error("JSON Message: " + ex.JsonMessage); break; - default: - break; } return Task.CompletedTask; } @@ -99,17 +90,17 @@ internal static class EventHandler switch (e.Exception) { case SlashExecutionChecksFailedException checksFailedException: - { - foreach (SlashCheckBaseAttribute attr in checksFailedException.FailedChecks) { - await e.Context.Channel.SendMessageAsync(new DiscordEmbedBuilder + foreach (SlashCheckBaseAttribute attr in checksFailedException.FailedChecks) { - Color = DiscordColor.Red, - Description = ParseFailedCheck(attr) - }); + await e.Context.Channel.SendMessageAsync(new DiscordEmbedBuilder + { + Color = DiscordColor.Red, + Description = ParseFailedCheck(attr) + }); + } + return; } - return; - } case BadRequestException ex: Logger.Error("Command exception occured:\n" + e.Exception); @@ -117,15 +108,15 @@ internal static class EventHandler 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; - } + 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; + } } } diff --git a/SupportChild/Logger.cs b/SupportChild/Logger.cs new file mode 100644 index 0000000..53d8f5e --- /dev/null +++ b/SupportChild/Logger.cs @@ -0,0 +1,68 @@ +using Microsoft.Extensions.Logging; +using System; +using System.Reflection; + +namespace SupportChild; + +public static class Logger +{ + public static void Debug(string message) + { + try + { + SupportChild.discordClient.Logger.Log(LogLevel.Debug, new EventId(420, Assembly.GetEntryAssembly()?.GetName().Name), message); + } + catch (NullReferenceException) + { + Console.WriteLine("[DEBUG] " + message); + } + } + + public static void Log(string message) + { + try + { + SupportChild.discordClient.Logger.Log(LogLevel.Information, new EventId(420, Assembly.GetEntryAssembly()?.GetName().Name), message); + } + catch (NullReferenceException) + { + Console.WriteLine("[INFO] " + message); + } + } + + public static void Warn(string message) + { + try + { + SupportChild.discordClient.Logger.Log(LogLevel.Warning, new EventId(420, Assembly.GetEntryAssembly()?.GetName().Name), message); + } + catch (NullReferenceException) + { + Console.WriteLine("[WARNING] " + message); + } + } + + public static void Error(string message) + { + try + { + SupportChild.discordClient.Logger.Log(LogLevel.Error, new EventId(420, Assembly.GetEntryAssembly()?.GetName().Name), message); + } + catch (NullReferenceException) + { + Console.WriteLine("[ERROR] " + message); + } + } + + public static void Fatal(string message) + { + try + { + SupportChild.discordClient.Logger.Log(LogLevel.Critical, new EventId(420, Assembly.GetEntryAssembly()?.GetName().Name), message); + } + catch (NullReferenceException) + { + Console.WriteLine("[CRITICAL] " + message); + } + } +} \ No newline at end of file diff --git a/SupportChild/Properties/Resources.Designer.cs b/SupportChild/Properties/Resources.Designer.cs new file mode 100644 index 0000000..8cdb657 --- /dev/null +++ b/SupportChild/Properties/Resources.Designer.cs @@ -0,0 +1,55 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace SupportChild.Properties { + using System; + + + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Resources { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Resources() { + } + + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager { + get { + if (object.ReferenceEquals(resourceMan, null)) { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("SupportChild.Properties.Resources", typeof(Resources).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture { + get { + return resourceCulture; + } + set { + resourceCulture = value; + } + } + + internal static byte[] default_config { + get { + object obj = ResourceManager.GetObject("default_config", resourceCulture); + return ((byte[])(obj)); + } + } + } +} diff --git a/SupportChild/Properties/Resources.resx b/SupportChild/Properties/Resources.resx new file mode 100644 index 0000000..8edc7ae --- /dev/null +++ b/SupportChild/Properties/Resources.resx @@ -0,0 +1,124 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + + ..\default_config.yml;System.Byte[], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/SupportChild/SupportChild.cs b/SupportChild/SupportChild.cs new file mode 100644 index 0000000..7582120 --- /dev/null +++ b/SupportChild/SupportChild.cs @@ -0,0 +1,149 @@ +using System; +using System.IO; +using System.Reflection; +using System.Threading.Tasks; +using DSharpPlus; +using DSharpPlus.Interactivity; +using DSharpPlus.Interactivity.Enums; +using DSharpPlus.Interactivity.Extensions; +using DSharpPlus.SlashCommands; +using Microsoft.Extensions.Logging; +using SupportChild.Commands; + +namespace SupportChild; + +internal static 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() + { + MainAsync().GetAwaiter().GetResult(); + } + + private static async Task MainAsync() + { + Logger.Log("Starting " + Assembly.GetEntryAssembly()?.GetName().Name + " version " + GetVersion() + "..."); + try + { + Reload(); + + // Block this task until the program is closed. + await Task.Delay(-1); + } + catch (Exception e) + { + Logger.Fatal("Fatal error:\n" + e); + Console.ReadLine(); + } + } + + public static string GetVersion() + { + Version version = Assembly.GetEntryAssembly()?.GetName().Version; + return version?.Major + "." + version?.Minor + "." + version?.Build + (version?.Revision == 0 ? "" : "-" + (char)(64 + version?.Revision ?? 0)); + } + + public static async void Reload() + { + if (discordClient != null) + { + await discordClient.DisconnectAsync(); + discordClient.Dispose(); + Logger.Log("Discord client disconnected."); + } + + Logger.Log("Loading config \"" + Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar + "config.yml\""); + Config.LoadConfig(); + + // Check if token is unset + if (Config.token is "" or "") + { + Logger.Fatal("You need to set your bot token in the config and start the bot again."); + throw new ArgumentException("Invalid Discord bot token"); + } + + // Database connection and setup + try + { + Logger.Log("Connecting to database... (" + Config.hostName + ":" + Config.port + ")"); + Database.SetConnectionString(Config.hostName, Config.port, Config.database, Config.username, Config.password); + Database.SetupTables(); + } + catch (Exception e) + { + Logger.Fatal("Could not set up database tables, please confirm connection settings, status of the server and permissions of MySQL user. Error: " + e); + throw; + } + + Logger.Log("Setting up Discord client..."); + + // Setting up client configuration + DiscordConfiguration cfg = new DiscordConfiguration + { + Token = Config.token, + TokenType = TokenType.Bot, + MinimumLogLevel = Config.logLevel, + AutoReconnect = true, + Intents = DiscordIntents.All + }; + + discordClient = new DiscordClient(cfg); + + Logger.Log("Hooking events..."); + discordClient.Ready += EventHandler.OnReady; + discordClient.GuildAvailable += EventHandler.OnGuildAvailable; + discordClient.ClientErrored += EventHandler.OnClientError; + discordClient.MessageCreated += EventHandler.OnMessageCreated; + discordClient.GuildMemberAdded += EventHandler.OnMemberAdded; + discordClient.GuildMemberRemoved += EventHandler.OnMemberRemoved; + discordClient.ComponentInteractionCreated += EventHandler.OnComponentInteractionCreated; + + discordClient.UseInteractivity(new InteractivityConfiguration + { + PaginationBehaviour = PaginationBehaviour.Ignore, + PaginationDeletion = PaginationDeletion.DeleteMessage, + Timeout = TimeSpan.FromMinutes(15) + }); + + Logger.Log("Registering commands..."); + commands = discordClient.UseSlashCommands(); + + commands.RegisterCommands(); + commands.RegisterCommands(); + commands.RegisterCommands(); + commands.RegisterCommands(); + commands.RegisterCommands(); + commands.RegisterCommands(); + commands.RegisterCommands(); + commands.RegisterCommands(); + commands.RegisterCommands(); + commands.RegisterCommands(); + commands.RegisterCommands(); + commands.RegisterCommands(); + commands.RegisterCommands(); + commands.RegisterCommands(); + commands.RegisterCommands(); + commands.RegisterCommands(); + commands.RegisterCommands(); + commands.RegisterCommands(); + commands.RegisterCommands(); + commands.RegisterCommands(); + commands.RegisterCommands(); + commands.RegisterCommands(); + commands.RegisterCommands(); + commands.RegisterCommands(); + commands.RegisterCommands(); + commands.RegisterCommands(); + commands.RegisterCommands(); + commands.RegisterCommands(); + + Logger.Log("Hooking command events..."); + commands.SlashCommandErrored += EventHandler.OnCommandError; + + Logger.Log("Connecting to Discord..."); + await discordClient.ConnectAsync(); + } +} \ No newline at end of file diff --git a/SupportChild/SupportChild.csproj b/SupportChild/SupportChild.csproj new file mode 100644 index 0000000..fcbb1f7 --- /dev/null +++ b/SupportChild/SupportChild.csproj @@ -0,0 +1,70 @@ + + + + Exe + ellie_icon.ico + net6.0 + win-x64;linux-x64 + + SupportChild.SupportChild + EmotionChild + + https://github.com/EmotionChild/SupportChild + https://github.com/EmotionChild/SupportChild + Git + LICENSE + https://cdn.discordapp.com/attachments/765441543100170271/914327948667011132/Ellie_Concept_2_transparent_ver.png + A Discord support ticket bot built for the Ellie's home server + en + 1.3.1 + 1.3.1 + 3.0.0.1 + 3.0.0.1 + + + + full + + + + + + + + + + + + + + + + + + + + + ResXFileCodeGenerator + Resources.Designer.cs + + + + + + + + + + lib\DiscordChatExporter.Core.dll + + + + + + True + True + Resources.resx + + + + \ No newline at end of file diff --git a/SupportChild/Transcriber.cs b/SupportChild/Transcriber.cs new file mode 100644 index 0000000..0fd0d5c --- /dev/null +++ b/SupportChild/Transcriber.cs @@ -0,0 +1,53 @@ +using System.IO; +using System.Threading.Tasks; + +using DiscordChatExporter.Core.Discord; +using DiscordChatExporter.Core.Discord.Data; +using DiscordChatExporter.Core.Exporting; +using DiscordChatExporter.Core.Exporting.Filtering; +using DiscordChatExporter.Core.Exporting.Partitioning; + +namespace SupportChild; + +internal static class Transcriber +{ + 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"); + } + + 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: "yyyy-MMM-dd HH:mm" + ); + + 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"; + } +} \ No newline at end of file diff --git a/SupportChild/Utilities.cs b/SupportChild/Utilities.cs new file mode 100644 index 0000000..b554cfc --- /dev/null +++ b/SupportChild/Utilities.cs @@ -0,0 +1,65 @@ +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using DSharpPlus.Entities; + +namespace SupportChild; + +public static class Utilities +{ + private static readonly Random rng = new Random(); + + public static void Shuffle(this IList list) + { + int n = list.Count; + while (n > 1) + { + n--; + int k = rng.Next(n + 1); + (list[k], list[n]) = (list[n], list[k]); + } + } + + public static LinkedList ParseListIntoMessages(List listItems) + { + LinkedList messages = new LinkedList(); + + foreach (string listItem in listItems) + { + if (messages.Last?.Value?.Length + listItem?.Length < 2048) + { + messages.Last.Value += listItem; + } + else + { + messages.AddLast(listItem); + } + } + + return messages; + } + + public static async Task> GetVerifiedChannels() + { + List verifiedCategories = new List(); + foreach (Database.Category category in Database.GetAllCategories()) + { + DiscordChannel channel = null; + try + { + channel = await SupportChild.discordClient.GetChannelAsync(category.id); + } + catch (Exception) { /*ignored*/ } + + if (channel != null) + { + verifiedCategories.Add(category); + } + else + { + Logger.Warn("Category '" + category.name + "' (" + category.id + ") no longer exists! Ignoring..."); + } + } + return verifiedCategories; + } +} \ No newline at end of file diff --git a/default_config.yml b/SupportChild/default_config.yml similarity index 97% rename from default_config.yml rename to SupportChild/default_config.yml index 51b51b5..b24019a 100644 --- a/default_config.yml +++ b/SupportChild/default_config.yml @@ -1,38 +1,28 @@ bot: # Bot token. token: "" - # Channel where ticket logs are posted (recommended) log-channel: 000000000000000000 - # Message posted when a ticket is opened. welcome-message: "Please describe your issue below, and include all information needed for us to take action." - # Decides what messages are shown in console # Possible values are: Critical, Error, Warning, Information, Debug. console-log-level: "Information" - # One of the following: LongDate, LongDateTime, LongTime, RelativeTime, ShortDate, ShortDateTime, ShortTime # More info: https://dsharpplus.github.io/api/DSharpPlus.TimestampFormat.html timestamp-format: "RelativeTime" - # Whether or not staff members should be randomly assigned tickets when they are made. Individual staff members can opt out using the toggleactive command. random-assignment: true - # If set to true the rasssign command will include staff members set as inactive if a specific role is specified in the command. # This can be useful if you have admins set as inactive to not automatically receive tickets and then have moderators elevate tickets when needed. random-assign-role-override: true - # Sets the type of activity for the bot to display in its presence status - # Possible values are: Playing, Streaming, ListeningTo, Watching, Competing, Custom + # 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 @@ -40,13 +30,10 @@ 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 @@ -54,10 +41,8 @@ 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: "" \ No newline at end of file diff --git a/ellie_icon.ico b/SupportChild/ellie_icon.ico similarity index 100% rename from ellie_icon.ico rename to SupportChild/ellie_icon.ico diff --git a/SupportChild/lib/DiscordChatExporter.Core.dll b/SupportChild/lib/DiscordChatExporter.Core.dll new file mode 100644 index 0000000..938808d Binary files /dev/null and b/SupportChild/lib/DiscordChatExporter.Core.dll differ diff --git a/Transcriber.cs b/Transcriber.cs deleted file mode 100644 index 6967545..0000000 --- a/Transcriber.cs +++ /dev/null @@ -1,63 +0,0 @@ -using System.IO; -using System.Threading.Tasks; - -using DiscordChatExporter.Core.Discord; -using DiscordChatExporter.Core.Discord.Data; -using DiscordChatExporter.Core.Exporting; -using DiscordChatExporter.Core.Exporting.Filtering; -using DiscordChatExporter.Core.Exporting.Partitioning; - -namespace SupportChild; - -internal static class Transcriber -{ - private static string transcriptDir = "./transcripts"; - - internal static async Task ExecuteAsync(ulong channelID, uint ticketID) - { - DiscordClient discordClient = new DiscordClient(Config.token); - ChannelExporter exporter = new ChannelExporter(discordClient); - - if (!string.IsNullOrEmpty(SupportChild.commandLineArgs.transcriptDir)) - { - transcriptDir = SupportChild.commandLineArgs.transcriptDir; - } - - if (!Directory.Exists(transcriptDir)) - { - Directory.CreateDirectory(transcriptDir); - } - - Channel channel = await discordClient.GetChannelAsync(new Snowflake(channelID)); - Guild guild = await discordClient.GetGuildAsync(channel.GuildId); - - ExportRequest request = new( - guild, - channel, - GetPath(ticketID), - null, - ExportFormat.HtmlDark, - null, - null, - PartitionLimit.Null, - MessageFilter.Null, - true, - false, - false, - "en-US", - true - ); - - await exporter.ExportChannelAsync(request); - } - - internal static string GetPath(uint ticketNumber) - { - return transcriptDir + "/" + GetFilename(ticketNumber); - } - - internal static string GetFilename(uint ticketNumber) - { - return "ticket-" + ticketNumber.ToString("00000") + ".html"; - } -} \ No newline at end of file diff --git a/Utilities.cs b/Utilities.cs deleted file mode 100644 index 54686cc..0000000 --- a/Utilities.cs +++ /dev/null @@ -1,84 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Reflection; -using System.Threading.Tasks; -using DSharpPlus.Entities; - -namespace SupportChild; - -public static class Utilities -{ - private static readonly Random rng = new Random(); - - public static void Shuffle(this IList list) - { - int n = list.Count; - while (n > 1) - { - n--; - int k = rng.Next(n + 1); - (list[k], list[n]) = (list[n], list[k]); - } - } - - public static LinkedList ParseListIntoMessages(List listItems) - { - LinkedList messages = new LinkedList(); - - foreach (string listItem in listItems) - { - if (messages.Last?.Value?.Length + listItem?.Length < 2048) - { - messages.Last.Value += listItem; - } - else - { - messages.AddLast(listItem); - } - } - - return messages; - } - - public static async Task> GetVerifiedChannels() - { - List verifiedCategories = new List(); - foreach (Database.Category category in Database.GetAllCategories()) - { - DiscordChannel channel = null; - try - { - channel = await SupportChild.discordClient.GetChannelAsync(category.id); - } - catch (Exception) { /*ignored*/ } - - if (channel != null) - { - verifiedCategories.Add(category); - } - else - { - Logger.Warn("Category '" + category.name + "' (" + category.id + ") no longer exists! Ignoring..."); - } - } - return verifiedCategories; - } - - - public static string ReadManifestData(string embeddedFileName) - { - Assembly assembly = Assembly.GetExecutingAssembly(); - string resourceName = assembly.GetManifestResourceNames().First(s => s.EndsWith(embeddedFileName, StringComparison.CurrentCultureIgnoreCase)); - - using Stream stream = assembly.GetManifestResourceStream(resourceName); - if (stream == null) - { - throw new InvalidOperationException("Could not load manifest resource stream."); - } - - using StreamReader reader = new StreamReader(stream); - return reader.ReadToEnd(); - } -} \ No newline at end of file diff --git a/lib/DiscordChatExporter.Core.dll b/lib/DiscordChatExporter.Core.dll deleted file mode 100644 index 0023b89..0000000 Binary files a/lib/DiscordChatExporter.Core.dll and /dev/null differ