Files have been added

This commit is contained in:
Emotion 2023-07-08 20:03:19 +12:00
parent 3d548c96e8
commit 3185bb33aa
No known key found for this signature in database
GPG key ID: D7D3E4C27A98C37B
12 changed files with 2015 additions and 0 deletions

338
.gitignore vendored Normal file
View file

@ -0,0 +1,338 @@
## 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
# User-specific files
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
# 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
# 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/
**/Properties/launchSettings.json
# StyleCop
StyleCopReport.xml
# Files built by Visual Studio
*_i.c
*_p.c
*_i.h
*.ilk
*.meta
*.obj
*.iobj
*.pch
*.pdb
*.ipdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*.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
# JustCode is a .NET coding add-in
.JustCode
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# AxoCover is a Code Coverage Tool
.axoCover/*
!.axoCover/settings.json
# 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
# 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
# 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
# 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/
# JetBrains Rider
.idea/
*.sln.iml
# CodeRush
.cr/
# 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/
Akheemah/transcripts/
Akheemah/config\.yml
Akheemah/credentials.json
Akheemah/token.json/

25
Akheemah.sln Normal file
View file

@ -0,0 +1,25 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.6.33815.320
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Akheemah", "Akheemah\Akheemah.csproj", "{669016B1-8F32-4C9A-A7D9-1E96934858E9}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{669016B1-8F32-4C9A-A7D9-1E96934858E9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{669016B1-8F32-4C9A-A7D9-1E96934858E9}.Debug|Any CPU.Build.0 = Debug|Any CPU
{669016B1-8F32-4C9A-A7D9-1E96934858E9}.Release|Any CPU.ActiveCfg = Release|Any CPU
{669016B1-8F32-4C9A-A7D9-1E96934858E9}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {9089ED64-EA0D-40BD-AD54-67097A076A48}
EndGlobalSection
EndGlobal

149
Akheemah/Akheemah.cs Normal file
View file

@ -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 Akheemah.Commands;
namespace Akheemah;
internal static class Akheemah
{
// 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 "<add-token-here>" or "")
{
Logger.Fatal("You need to set your bot token in the config and start the bot again.");
throw new ArgumentException("Invalid Discord bot token");
}
// Database connection and setup
try
{
Logger.Log("Connecting to database... (" + Config.hostName + ":" + Config.port + ")");
Database.SetConnectionString(Config.hostName, Config.port, Config.database, Config.username, Config.password);
Database.SetupTables();
}
catch (Exception e)
{
Logger.Fatal("Could not set up database tables, please confirm connection settings, status of the server and permissions of MySQL user. Error: " + e);
throw;
}
Logger.Log("Setting up Discord client...");
// Setting up client configuration
DiscordConfiguration cfg = new DiscordConfiguration
{
Token = Config.token,
TokenType = TokenType.Bot,
MinimumLogLevel = Config.logLevel,
AutoReconnect = true,
Intents = DiscordIntents.All
};
discordClient = new DiscordClient(cfg);
Logger.Log("Hooking events...");
discordClient.Ready += EventHandler.OnReady;
discordClient.GuildAvailable += EventHandler.OnGuildAvailable;
discordClient.ClientErrored += EventHandler.OnClientError;
discordClient.MessageCreated += EventHandler.OnMessageCreated;
discordClient.GuildMemberAdded += EventHandler.OnMemberAdded;
discordClient.GuildMemberRemoved += EventHandler.OnMemberRemoved;
discordClient.ComponentInteractionCreated += EventHandler.OnComponentInteractionCreated;
discordClient.UseInteractivity(new InteractivityConfiguration
{
PaginationBehaviour = PaginationBehaviour.Ignore,
PaginationDeletion = PaginationDeletion.DeleteMessage,
Timeout = TimeSpan.FromMinutes(15)
});
Logger.Log("Registering commands...");
commands = discordClient.UseSlashCommands();
commands.RegisterCommands<AddCategoryCommand>();
commands.RegisterCommands<AddCommand>();
commands.RegisterCommands<AddMessageCommand>();
commands.RegisterCommands<AddStaffCommand>();
commands.RegisterCommands<AssignCommand>();
commands.RegisterCommands<BlacklistCommand>();
commands.RegisterCommands<CloseCommand>();
commands.RegisterCommands<CreateButtonPanelCommand>();
commands.RegisterCommands<CreateSelectionBoxPanelCommand>();
commands.RegisterCommands<ListAssignedCommand>();
commands.RegisterCommands<ListCommand>();
commands.RegisterCommands<ListOpen>();
commands.RegisterCommands<ListUnassignedCommand>();
commands.RegisterCommands<MoveCommand>();
commands.RegisterCommands<NewCommand>();
commands.RegisterCommands<RandomAssignCommand>();
commands.RegisterCommands<RemoveCategoryCommand>();
commands.RegisterCommands<RemoveMessageCommand>();
commands.RegisterCommands<RemoveStaffCommand>();
commands.RegisterCommands<SayCommand>();
commands.RegisterCommands<SetSummaryCommand>();
commands.RegisterCommands<StatusCommand>();
commands.RegisterCommands<SummaryCommand>();
commands.RegisterCommands<ToggleActiveCommand>();
commands.RegisterCommands<TranscriptCommand>();
commands.RegisterCommands<UnassignCommand>();
commands.RegisterCommands<UnblacklistCommand>();
commands.RegisterCommands<AdminCommands>();
Logger.Log("Hooking command events...");
commands.SlashCommandErrored += EventHandler.OnCommandError;
Logger.Log("Connecting to Discord...");
await discordClient.ConnectAsync();
}
}

70
Akheemah/Akheemah.csproj Normal file
View file

@ -0,0 +1,70 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<ApplicationIcon>akheemah.ico</ApplicationIcon>
<TargetFramework>net6.0</TargetFramework>
<RuntimeIdentifiers>win-x64;linux-x64</RuntimeIdentifiers>
<StartupObject>Akheemah.Akheemah</StartupObject>
<Authors>taostie_t0ast</Authors>
<Product />
<PackageProjectUrl>https://toastielab.dev/Dragonschildstudios/Akheemah</PackageProjectUrl>
<RepositoryUrl>https://toastielab.dev/Dragonschildstudios/Akheemah</RepositoryUrl>
<RepositoryType>Git</RepositoryType>
<PackageLicenseFile>LICENSE</PackageLicenseFile>
<PackageIconUrl>https://karlofduty.com/img/tardisIcon.jpg</PackageIconUrl>
<Description>A Discord support ticket bot to help out in the Dragon's child studios server.</Description>
<NeutralLanguage>en</NeutralLanguage>
<Version>1.3.1</Version>
<PackageVersion>3.0.1</PackageVersion>
<AssemblyVersion>1.3.1</AssemblyVersion>
<FileVersion>1.3.1</FileVersion>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Debug' ">
<DebugType>full</DebugType>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="DSharpPlus" Version="4.4.1" />
<PackageReference Include="DSharpPlus.Interactivity" Version="4.4.1" />
<PackageReference Include="DSharpPlus.SlashCommands" Version="4.4.1" />
<PackageReference Include="Gress" Version="2.1.1" />
<PackageReference Include="JsonExtensions" Version="1.2.0" />
<PackageReference Include="MiniRazor.CodeGen" Version="2.2.1" />
<PackageReference Include="MySqlConnector" Version="2.2.6" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="Polly" Version="7.2.3" />
<PackageReference Include="Superpower" Version="3.0.0" />
<PackageReference Include="Tyrrrz.Extensions" Version="1.6.5" />
<PackageReference Include="WebMarkupMin.Core" Version="2.14.0" />
<PackageReference Include="YamlDotNet" Version="13.1.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<Folder Include="lib\" />
</ItemGroup>
<ItemGroup>
<Reference Include="DiscordChatExporter.Core">
<HintPath>lib\DiscordChatExporter.Core.dll</HintPath>
</Reference>
</ItemGroup>
</Project>

95
Akheemah/Config.cs Normal file
View file

@ -0,0 +1,95 @@
using System;
using System.IO;
using System.Text;
using DSharpPlus;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Linq;
using Akheemah.Properties;
using YamlDotNet.Serialization;
namespace Akheemah;
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 = "akheemah";
internal static string username = "akheemah";
internal static string password = "";
public static void LoadConfig()
{
// Write 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 of nodes by name
ISerializer serializer = new SerializerBuilder().JsonCompatible().Build();
JObject json = JObject.Parse(serializer.Serialize(yamlObject));
// Sets up the bot
token = json.SelectToken("bot.token")?.Value<string>() ?? "";
logChannel = json.SelectToken("bot.log-channel")?.Value<ulong>() ?? 0;
welcomeMessage = json.SelectToken("bot.welcome-message")?.Value<string>() ?? "";
string stringLogLevel = json.SelectToken("bot.console-log-level")?.Value<string>() ?? "";
if (!Enum.TryParse(stringLogLevel, true, out logLevel))
{
logLevel = LogLevel.Information;
Logger.Warn("Log level '" + stringLogLevel + "' invalid, using 'Information' instead.");
}
string stringTimestampFormat = json.SelectToken("bot.timestamp-format")?.Value<string>() ?? "RelativeTime";
if (!Enum.TryParse(stringTimestampFormat, true, out timestampFormat))
{
timestampFormat = TimestampFormat.RelativeTime;
Logger.Warn("Timestamp '" + stringTimestampFormat + "' invalid, using 'RelativeTime' instead.");
}
randomAssignment = json.SelectToken("bot.random-assignment")?.Value<bool>() ?? false;
randomAssignRoleOverride = json.SelectToken("bot.random-assign-role-override")?.Value<bool>() ?? false;
presenceType = json.SelectToken("bot.presence-type")?.Value<string>() ?? "Playing";
presenceText = json.SelectToken("bot.presence-text")?.Value<string>() ?? "";
newCommandUsesSelector = json.SelectToken("bot.new-command-uses-selector")?.Value<bool>() ?? false;
ticketLimit = json.SelectToken("bot.ticket-limit")?.Value<int>() ?? 5;
ticketUpdatedNotifications = json.SelectToken("notifications.ticket-updated")?.Value<bool>() ?? false;
ticketUpdatedNotificationDelay = json.SelectToken("notifications.ticket-updated-delay")?.Value<double>() ?? 0.0;
assignmentNotifications = json.SelectToken("notifications.assignment")?.Value<bool>() ?? false;
closingNotifications = json.SelectToken("notifications.closing")?.Value<bool>() ?? false;
// Reads database info
hostName = json.SelectToken("database.address")?.Value<string>() ?? "";
port = json.SelectToken("database.port")?.Value<int>() ?? 3306;
database = json.SelectToken("database.name")?.Value<string>() ?? "akheemah";
username = json.SelectToken("database.user")?.Value<string>() ?? "akheemah";
password = json.SelectToken("database.password")?.Value<string>() ?? "";
}
}

819
Akheemah/Database.cs Normal file
View file

@ -0,0 +1,819 @@
using System;
using System.Linq;
using System.Collections.Generic;
using DSharpPlus;
using MySqlConnector;
namespace Akheemah;
public static class Database
{
public 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 +
";database=" + database +
";port=" + port +
";userid=" + username +
";password=" + password;
}
public static MySqlConnection GetConnection()
{
return new MySqlConnection(connectionString);
}
public static long GetNumberOfTickets()
{
try
{
using MySqlConnection c = GetConnection();
using MySqlCommand countTickets = new MySqlCommand("SELECT COUNT(*) FROM tickets", c);
c.Open();
return (long)countTickets.ExecuteScalar();
}
catch (Exception e)
{
Logger.Error("Error occured when attempting to count number of open tickets: " + e);
}
return -1;
}
public static long GetNumberOfClosedTickets()
{
try
{
using MySqlConnection c = GetConnection();
using MySqlCommand countTickets = new MySqlCommand("SELECT COUNT(*) FROM ticket_history", c);
c.Open();
return (long)countTickets.ExecuteScalar();
}
catch (Exception e)
{
Logger.Error("Error occured when attempting to count number of open tickets: " + e);
}
return -1;
}
public static void SetupTables()
{
using MySqlConnection c = GetConnection();
using MySqlCommand createTickets = new MySqlCommand(
"CREATE TABLE IF NOT EXISTS tickets(" +
"id INT UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT," +
"created_time DATETIME NOT NULL," +
"creator_id BIGINT UNSIGNED NOT NULL," +
"assigned_staff_id BIGINT UNSIGNED NOT NULL DEFAULT 0," +
"summary VARCHAR(5000) NOT NULL," +
"channel_id BIGINT UNSIGNED NOT NULL UNIQUE," +
"INDEX(created_time, assigned_staff_id, channel_id))",
c);
using MySqlCommand createTicketHistory = new MySqlCommand(
"CREATE TABLE IF NOT EXISTS ticket_history(" +
"id INT UNSIGNED NOT NULL PRIMARY KEY," +
"created_time DATETIME NOT NULL," +
"closed_time DATETIME NOT NULL," +
"creator_id BIGINT UNSIGNED NOT NULL," +
"assigned_staff_id BIGINT UNSIGNED NOT NULL DEFAULT 0," +
"summary VARCHAR(5000) NOT NULL," +
"channel_id BIGINT UNSIGNED NOT NULL UNIQUE," +
"INDEX(created_time, closed_time, channel_id))",
c);
using MySqlCommand createBlacklisted = new MySqlCommand(
"CREATE TABLE IF NOT EXISTS blacklisted_users(" +
"user_id BIGINT UNSIGNED NOT NULL PRIMARY KEY," +
"time DATETIME NOT NULL," +
"moderator_id BIGINT UNSIGNED NOT NULL," +
"INDEX(user_id, time))",
c);
using MySqlCommand createStaffList = new MySqlCommand(
"CREATE TABLE IF NOT EXISTS staff(" +
"user_id BIGINT UNSIGNED NOT NULL PRIMARY KEY," +
"name VARCHAR(256) NOT NULL," +
"active BOOLEAN NOT NULL DEFAULT true)",
c);
using MySqlCommand createMessages = new MySqlCommand(
"CREATE TABLE IF NOT EXISTS messages(" +
"identifier VARCHAR(256) NOT NULL PRIMARY KEY," +
"user_id BIGINT UNSIGNED NOT NULL," +
"message VARCHAR(5000) NOT NULL)",
c);
using MySqlCommand createCategories = new MySqlCommand(
"CREATE TABLE IF NOT EXISTS categories(" +
"name VARCHAR(256) NOT NULL UNIQUE," +
"category_id BIGINT UNSIGNED NOT NULL PRIMARY KEY)",
c);
c.Open();
createTickets.ExecuteNonQuery();
createBlacklisted.ExecuteNonQuery();
createTicketHistory.ExecuteNonQuery();
createStaffList.ExecuteNonQuery();
createMessages.ExecuteNonQuery();
createCategories.ExecuteNonQuery();
}
public static bool IsOpenTicket(ulong channelID)
{
using MySqlConnection c = GetConnection();
c.Open();
using MySqlCommand selection = new MySqlCommand(@"SELECT * FROM tickets WHERE channel_id=@channel_id", c);
selection.Parameters.AddWithValue("@channel_id", channelID);
selection.Prepare();
MySqlDataReader results = selection.ExecuteReader();
// Check if ticket exists in the database
if (!results.Read())
{
return false;
}
results.Close();
return true;
}
public static bool TryGetOpenTicket(ulong channelID, out Ticket ticket)
{
using MySqlConnection c = GetConnection();
c.Open();
using MySqlCommand selection = new MySqlCommand(@"SELECT * FROM tickets WHERE channel_id=@channel_id", c);
selection.Parameters.AddWithValue("@channel_id", channelID);
selection.Prepare();
MySqlDataReader results = selection.ExecuteReader();
// Check if ticket exists in the database
if (!results.Read())
{
ticket = null;
return false;
}
ticket = new Ticket(results);
results.Close();
return true;
}
public static bool TryGetOpenTicketByID(uint id, out Ticket ticket)
{
using MySqlConnection c = GetConnection();
c.Open();
using MySqlCommand selection = new MySqlCommand(@"SELECT * FROM tickets WHERE id=@id", c);
selection.Parameters.AddWithValue("@id", id);
selection.Prepare();
MySqlDataReader results = selection.ExecuteReader();
// Check if open ticket exists in the database
if (results.Read())
{
ticket = new Ticket(results);
results.Close();
return true;
}
results.Close();
ticket = null;
return false;
}
public static bool TryGetClosedTicket(uint id, out Ticket ticket)
{
using MySqlConnection c = GetConnection();
c.Open();
using MySqlCommand selection = new MySqlCommand(@"SELECT * FROM ticket_history WHERE id=@id", c);
selection.Parameters.AddWithValue("@id", id);
selection.Prepare();
MySqlDataReader results = selection.ExecuteReader();
// Check if closed ticket exists in the database
if (results.Read())
{
ticket = new Ticket(results);
results.Close();
return true;
}
ticket = null;
results.Close();
return false;
}
public static bool TryGetOpenTickets(ulong userID, out List<Ticket> tickets)
{
tickets = null;
using MySqlConnection c = GetConnection();
c.Open();
using MySqlCommand selection = new MySqlCommand(@"SELECT * FROM tickets WHERE creator_id=@creator_id", c);
selection.Parameters.AddWithValue("@creator_id", userID);
selection.Prepare();
MySqlDataReader results = selection.ExecuteReader();
if (!results.Read())
{
return false;
}
tickets = new List<Ticket> { new Ticket(results) };
while (results.Read())
{
tickets.Add(new Ticket(results));
}
results.Close();
return true;
}
public static bool TryGetOpenTickets(out List<Ticket> tickets)
{
tickets = null;
using MySqlConnection c = GetConnection();
c.Open();
using MySqlCommand selection = new MySqlCommand(@"SELECT * FROM tickets ORDER BY channel_id ASC", c);
selection.Prepare();
MySqlDataReader results = selection.ExecuteReader();
if (!results.Read())
{
return false;
}
tickets = new List<Ticket> { new Ticket(results) };
while (results.Read())
{
tickets.Add(new Ticket(results));
}
results.Close();
return true;
}
public static bool TryGetClosedTickets(ulong userID, out List<Ticket> tickets)
{
tickets = null;
using MySqlConnection c = GetConnection();
c.Open();
using MySqlCommand selection = new MySqlCommand(@"SELECT * FROM ticket_history WHERE creator_id=@creator_id", c);
selection.Parameters.AddWithValue("@creator_id", userID);
selection.Prepare();
MySqlDataReader results = selection.ExecuteReader();
if (!results.Read())
{
return false;
}
tickets = new List<Ticket> { new Ticket(results) };
while (results.Read())
{
tickets.Add(new Ticket(results));
}
results.Close();
return true;
}
public static bool TryGetAssignedTickets(ulong staffID, out List<Ticket> tickets)
{
tickets = null;
using MySqlConnection c = GetConnection();
c.Open();
using MySqlCommand selection = new MySqlCommand(@"SELECT * FROM tickets WHERE assigned_staff_id=@assigned_staff_id", c);
selection.Parameters.AddWithValue("@assigned_staff_id", staffID);
selection.Prepare();
MySqlDataReader results = selection.ExecuteReader();
if (!results.Read())
{
return false;
}
tickets = new List<Ticket> { new Ticket(results) };
while (results.Read())
{
tickets.Add(new Ticket(results));
}
results.Close();
return true;
}
public static long NewTicket(ulong memberID, ulong staffID, ulong ticketID)
{
using MySqlConnection c = GetConnection();
c.Open();
using MySqlCommand cmd = new MySqlCommand(@"INSERT INTO tickets (created_time, creator_id, assigned_staff_id, summary, channel_id) VALUES (UTC_TIMESTAMP(), @creator_id, @assigned_staff_id, @summary, @channel_id);", c);
cmd.Parameters.AddWithValue("@creator_id", memberID);
cmd.Parameters.AddWithValue("@assigned_staff_id", staffID);
cmd.Parameters.AddWithValue("@summary", "");
cmd.Parameters.AddWithValue("@channel_id", ticketID);
cmd.ExecuteNonQuery();
return cmd.LastInsertedId;
}
public static void ArchiveTicket(Ticket ticket)
{
// Check if ticket already exists in the archive
if (TryGetClosedTicket(ticket.id, out Ticket _))
{
using MySqlConnection c = GetConnection();
using MySqlCommand deleteTicket = new MySqlCommand(@"DELETE FROM ticket_history WHERE id=@id OR channel_id=@channel_id", c);
deleteTicket.Parameters.AddWithValue("@id", ticket.id);
deleteTicket.Parameters.AddWithValue("@channel_id", ticket.channelID);
c.Open();
deleteTicket.Prepare();
deleteTicket.ExecuteNonQuery();
}
// Create an entry in the ticket history database
using MySqlConnection conn = GetConnection();
using MySqlCommand archiveTicket = new MySqlCommand(@"INSERT INTO ticket_history (id, created_time, closed_time, creator_id, assigned_staff_id, summary, channel_id) VALUES (@id, @created_time, UTC_TIMESTAMP(), @creator_id, @assigned_staff_id, @summary, @channel_id);", conn);
archiveTicket.Parameters.AddWithValue("@id", ticket.id);
archiveTicket.Parameters.AddWithValue("@created_time", ticket.channelID.GetSnowflakeTime());
archiveTicket.Parameters.AddWithValue("@creator_id", ticket.creatorID);
archiveTicket.Parameters.AddWithValue("@assigned_staff_id", ticket.assignedStaffID);
archiveTicket.Parameters.AddWithValue("@summary", ticket.summary);
archiveTicket.Parameters.AddWithValue("@channel_id", ticket.channelID);
conn.Open();
archiveTicket.Prepare();
archiveTicket.ExecuteNonQuery();
}
public static bool DeleteOpenTicket(uint ticketID)
{
try
{
using MySqlConnection c = GetConnection();
using MySqlCommand deletion = new MySqlCommand(@"DELETE FROM tickets WHERE id=@id", c);
deletion.Parameters.AddWithValue("@id", ticketID);
c.Open();
deletion.Prepare();
return deletion.ExecuteNonQuery() > 0;
}
catch (MySqlException)
{
return false;
}
}
public static bool IsBlacklisted(ulong userID)
{
using MySqlConnection c = GetConnection();
c.Open();
using MySqlCommand selection = new MySqlCommand(@"SELECT * FROM blacklisted_users WHERE user_id=@user_id", c);
selection.Parameters.AddWithValue("@user_id", userID);
selection.Prepare();
MySqlDataReader results = selection.ExecuteReader();
// Check if user is blacklisted
if (results.Read())
{
results.Close();
return true;
}
results.Close();
return false;
}
public static bool Blacklist(ulong blacklistedID, ulong staffID)
{
try
{
using MySqlConnection c = GetConnection();
c.Open();
using MySqlCommand cmd = new MySqlCommand(@"INSERT INTO blacklisted_users (user_id,time,moderator_id) VALUES (@user_id, UTC_TIMESTAMP(), @moderator_id);", c);
cmd.Parameters.AddWithValue("@user_id", blacklistedID);
cmd.Parameters.AddWithValue("@moderator_id", staffID);
cmd.Prepare();
return cmd.ExecuteNonQuery() > 0;
}
catch (MySqlException)
{
return false;
}
}
public static bool Unblacklist(ulong blacklistedID)
{
try
{
using MySqlConnection c = GetConnection();
c.Open();
using MySqlCommand cmd = new MySqlCommand(@"DELETE FROM blacklisted_users WHERE user_id=@user_id", c);
cmd.Parameters.AddWithValue("@user_id", blacklistedID);
cmd.Prepare();
return cmd.ExecuteNonQuery() > 0;
}
catch (MySqlException)
{
return false;
}
}
public static bool AssignStaff(Ticket ticket, ulong staffID)
{
try
{
using MySqlConnection c = GetConnection();
c.Open();
using MySqlCommand update = new MySqlCommand(@"UPDATE tickets SET assigned_staff_id = @assigned_staff_id WHERE id = @id", c);
update.Parameters.AddWithValue("@assigned_staff_id", staffID);
update.Parameters.AddWithValue("@id", ticket.id);
update.Prepare();
return update.ExecuteNonQuery() > 0;
}
catch (MySqlException)
{
return false;
}
}
public static bool UnassignStaff(Ticket ticket)
{
return AssignStaff(ticket, 0);
}
public static bool SetStaffActive(ulong staffID, bool active)
{
try
{
using MySqlConnection c = GetConnection();
c.Open();
MySqlCommand update = new MySqlCommand(@"UPDATE staff SET active = @active WHERE user_id = @user_id", c);
update.Parameters.AddWithValue("@user_id", staffID);
update.Parameters.AddWithValue("@active", active);
update.Prepare();
return update.ExecuteNonQuery() > 0;
}
catch (MySqlException)
{
return false;
}
}
public static StaffMember GetRandomActiveStaff(params ulong[] ignoredUserIDs)
{
List<StaffMember> staffMembers = GetActiveStaff(ignoredUserIDs);
return staffMembers.Any() ? staffMembers[random.Next(staffMembers.Count)] : null;
}
public static List<StaffMember> GetActiveStaff(params ulong[] ignoredUserIDs)
{
bool first = true;
string filterString = "";
foreach (ulong userID in ignoredUserIDs)
{
if (first)
{
first = false;
filterString += "AND user_id != " + userID;
}
else
{
filterString += "&& user_id != " + userID;
}
}
using MySqlConnection c = GetConnection();
c.Open();
using MySqlCommand selection = new MySqlCommand(@"SELECT * FROM staff WHERE active = true " + filterString, c);
selection.Prepare();
MySqlDataReader results = selection.ExecuteReader();
// Check if staff exists in the database
if (!results.Read())
{
return new List<StaffMember>();
}
List<StaffMember> staffMembers = new List<StaffMember> { new StaffMember(results) };
while (results.Read())
{
staffMembers.Add(new StaffMember(results));
}
results.Close();
return staffMembers;
}
public static List<StaffMember> GetAllStaff(params ulong[] ignoredUserIDs)
{
bool first = true;
string filterString = "";
foreach (ulong userID in ignoredUserIDs)
{
if (first)
{
first = false;
filterString += "WHERE user_id != " + userID;
}
else
{
filterString += "&& user_id != " + userID;
}
}
using MySqlConnection c = GetConnection();
c.Open();
using MySqlCommand selection = new MySqlCommand(@"SELECT * FROM staff " + filterString, c);
selection.Prepare();
MySqlDataReader results = selection.ExecuteReader();
// Check if staff exist in the database
if (!results.Read())
{
return new List<StaffMember>();
}
List<StaffMember> staffMembers = new List<StaffMember> { new StaffMember(results) };
while (results.Read())
{
staffMembers.Add(new StaffMember(results));
}
results.Close();
return staffMembers;
}
public static bool IsStaff(ulong staffID)
{
using MySqlConnection c = GetConnection();
c.Open();
using MySqlCommand selection = new MySqlCommand(@"SELECT * FROM staff WHERE user_id=@user_id", c);
selection.Parameters.AddWithValue("@user_id", staffID);
selection.Prepare();
MySqlDataReader results = selection.ExecuteReader();
// Check if ticket exists in the database
if (!results.Read())
{
return false;
}
results.Close();
return true;
}
public static bool TryGetStaff(ulong staffID, out StaffMember staffMember)
{
using MySqlConnection c = GetConnection();
c.Open();
using MySqlCommand selection = new MySqlCommand(@"SELECT * FROM staff WHERE user_id=@user_id", c);
selection.Parameters.AddWithValue("@user_id", staffID);
selection.Prepare();
MySqlDataReader results = selection.ExecuteReader();
// Check if ticket exists in the database
if (!results.Read())
{
staffMember = null;
return false;
}
staffMember = new StaffMember(results);
results.Close();
return true;
}
public static List<Message> GetAllMessages()
{
using MySqlConnection c = GetConnection();
c.Open();
using MySqlCommand selection = new MySqlCommand(@"SELECT * FROM messages", c);
selection.Prepare();
MySqlDataReader results = selection.ExecuteReader();
// Check if messages exist in the database
if (!results.Read())
{
return new List<Message>();
}
List<Message> messages = new List<Message> { new Message(results) };
while (results.Read())
{
messages.Add(new Message(results));
}
results.Close();
return messages;
}
public static bool TryGetMessage(string identifier, out Message message)
{
using MySqlConnection c = GetConnection();
c.Open();
using MySqlCommand selection = new MySqlCommand(@"SELECT * FROM messages WHERE identifier=@identifier", c);
selection.Parameters.AddWithValue("@identifier", identifier);
selection.Prepare();
MySqlDataReader results = selection.ExecuteReader();
// Check if ticket exists in the database
if (!results.Read())
{
message = null;
return false;
}
message = new Message(results);
results.Close();
return true;
}
public static bool AddMessage(string identifier, ulong userID, string message)
{
try
{
using MySqlConnection c = GetConnection();
c.Open();
using MySqlCommand cmd = new MySqlCommand(@"INSERT INTO messages (identifier,user_id,message) VALUES (@identifier, @user_id, @message);", c);
cmd.Parameters.AddWithValue("@identifier", identifier);
cmd.Parameters.AddWithValue("@user_id", userID);
cmd.Parameters.AddWithValue("@message", message);
cmd.Prepare();
return cmd.ExecuteNonQuery() > 0;
}
catch (MySqlException)
{
return false;
}
}
public static bool RemoveMessage(string identifier)
{
try
{
using MySqlConnection c = GetConnection();
c.Open();
using MySqlCommand cmd = new MySqlCommand(@"DELETE FROM messages WHERE identifier=@identifier", c);
cmd.Parameters.AddWithValue("@identifier", identifier);
cmd.Prepare();
return cmd.ExecuteNonQuery() > 0;
}
catch (MySqlException)
{
return false;
}
}
public static List<Category> GetAllCategories()
{
using MySqlConnection c = GetConnection();
c.Open();
using MySqlCommand selection = new MySqlCommand(@"SELECT * FROM categories", c);
selection.Prepare();
MySqlDataReader results = selection.ExecuteReader();
// Check if messages exist in the database
if (!results.Read())
{
return new List<Category>();
}
List<Category> categories = new List<Category> { new Category(results) };
while (results.Read())
{
categories.Add(new Category(results));
}
results.Close();
return categories;
}
public static bool TryGetCategory(ulong categoryID, out Category message)
{
using MySqlConnection c = GetConnection();
c.Open();
using MySqlCommand selection = new MySqlCommand(@"SELECT * FROM categories WHERE category_id=@category_id", c);
selection.Parameters.AddWithValue("@category_id", categoryID);
selection.Prepare();
MySqlDataReader results = selection.ExecuteReader();
// Check if ticket exists in the database
if (!results.Read())
{
message = null;
return false;
}
message = new Category(results);
results.Close();
return true;
}
public static bool TryGetCategory(string name, out Category message)
{
using MySqlConnection c = GetConnection();
c.Open();
using MySqlCommand selection = new MySqlCommand(@"SELECT * FROM categories WHERE name=@name", c);
selection.Parameters.AddWithValue("@name", name);
selection.Prepare();
MySqlDataReader results = selection.ExecuteReader();
// Check if ticket exists in the database
if (!results.Read())
{
message = null;
return false;
}
message = new Category(results);
results.Close();
return true;
}
public static bool AddCategory(string name, ulong categoryID)
{
try
{
using MySqlConnection c = GetConnection();
c.Open();
using MySqlCommand cmd = new MySqlCommand(@"INSERT INTO categories (name,category_id) VALUES (@name, @category_id);", c);
cmd.Parameters.AddWithValue("@name", name);
cmd.Parameters.AddWithValue("@category_id", categoryID);
cmd.Prepare();
return cmd.ExecuteNonQuery() > 0;
}
catch (MySqlException)
{
return false;
}
}
public static bool RemoveCategory(ulong categoryID)
{
try
{
using MySqlConnection c = GetConnection();
c.Open();
using MySqlCommand cmd = new MySqlCommand(@"DELETE FROM categories WHERE category_id=@category_id", c);
cmd.Parameters.AddWithValue("@category_id", categoryID);
cmd.Prepare();
return cmd.ExecuteNonQuery() > 0;
}
catch (MySqlException)
{
return false;
}
}
public class Ticket
{
public uint id;
public ulong creatorID;
public ulong assignedStaffID;
public string summary;
public ulong channelID;
public Ticket(MySqlDataReader reader)
{
id = reader.GetUInt32("id");
creatorID = reader.GetUInt64("creator_id");
assignedStaffID = reader.GetUInt64("assigned_staff_id");
summary = reader.GetString("summary");
channelID = reader.GetUInt64("channel_id");
}
public string DiscordRelativeTime()
{
return Formatter.Timestamp(channelID.GetSnowflakeTime(), Config.timestampFormat);
}
}
public class StaffMember
{
public ulong userID;
public string name;
public bool active;
public StaffMember(MySqlDataReader reader)
{
userID = reader.GetUInt64("user_id");
name = reader.GetString("name");
active = reader.GetBoolean("active");
}
}
public class Message
{
public string identifier;
public ulong userID;
public string message;
public Message(MySqlDataReader reader)
{
identifier = reader.GetString("identifier");
userID = reader.GetUInt64("user_id");
message = reader.GetString("message");
}
}
public class Category
{
public string name;
public ulong id;
public Category(MySqlDataReader reader)
{
name = reader.GetString("name");
id = reader.GetUInt64("category_id");
}
}
}

285
Akheemah/EventHandler.cs Normal file
View file

@ -0,0 +1,285 @@
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using DSharpPlus;
using DSharpPlus.Entities;
using DSharpPlus.EventArgs;
using DSharpPlus.Exceptions;
using DSharpPlus.SlashCommands;
using DSharpPlus.SlashCommands.Attributes;
using DSharpPlus.SlashCommands.EventArgs;
using Akheemah.Commands;
namespace Akheemah;
internal static class EventHandler
{
internal static Task OnReady(DiscordClient client, ReadyEventArgs e)
{
Logger.Log("Client is ready to process events.");
// Checking activity type
if (!Enum.TryParse(Config.presenceType, true, out ActivityType activityType))
{
Logger.Log("Presence type '" + Config.presenceType + "' invalid, using 'Playing' instead.");
activityType = ActivityType.Playing;
}
client.UpdateStatusAsync(new DiscordActivity(Config.presenceText, activityType), UserStatus.Online);
return Task.CompletedTask;
}
internal static Task OnGuildAvailable(DiscordClient _, GuildCreateEventArgs e)
{
Logger.Log("Guild available: " + e.Guild.Name);
IReadOnlyDictionary<ulong, DiscordRole> roles = e.Guild.Roles;
foreach ((ulong roleID, DiscordRole role) in roles)
{
Logger.Log(role.Name.PadRight(40, '.') + roleID);
}
return Task.CompletedTask;
}
internal static Task OnClientError(DiscordClient _, ClientErrorEventArgs e)
{
Logger.Error("Client exception occured:\n" + e.Exception);
switch (e.Exception)
{
case BadRequestException ex:
Logger.Error("JSON Message: " + ex.JsonMessage);
break;
}
return Task.CompletedTask;
}
internal static async Task OnMessageCreated(DiscordClient client, MessageCreateEventArgs e)
{
if (e.Author.IsBot)
{
return;
}
// Check if ticker exists in the database and ticket notifications are enabled
if (!Database.TryGetOpenTicket(e.Channel.Id, out Database.Ticket ticket) || !Config.ticketUpdatedNotifications)
{
return;
}
// Sends a DM to the assigned staff member if at least a day has gone by since the last message and the user sending the message isn't staff
IReadOnlyList<DiscordMessage> messages = await e.Channel.GetMessagesAsync(2);
if (messages.Count > 1 && messages[1].Timestamp < DateTimeOffset.UtcNow.AddDays(Config.ticketUpdatedNotificationDelay * -1) && !Database.IsStaff(e.Author.Id))
{
try
{
DiscordMember staffMember = await e.Guild.GetMemberAsync(ticket.assignedStaffID);
await staffMember.SendMessageAsync(new DiscordEmbedBuilder
{
Color = DiscordColor.Green,
Description = "A ticket you are assigned to has been updated: " + e.Channel.Mention
});
}
catch (NotFoundException) { }
catch (UnauthorizedException) { }
}
}
internal static async Task OnCommandError(SlashCommandsExtension commandSystem, SlashCommandErrorEventArgs e)
{
switch (e.Exception)
{
case SlashExecutionChecksFailedException checksFailedException:
{
foreach (SlashCheckBaseAttribute attr in checksFailedException.FailedChecks)
{
await e.Context.Channel.SendMessageAsync(new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = ParseFailedCheck(attr)
});
}
return;
}
case BadRequestException ex:
Logger.Error("Command exception occured:\n" + e.Exception);
Logger.Error("JSON Message: " + ex.JsonMessage);
return;
default:
{
Logger.Error("Exception occured: " + e.Exception.GetType() + ": " + e.Exception);
await e.Context.Channel.SendMessageAsync(new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = "Internal error occured, please report this to the developer."
});
return;
}
}
}
internal static async Task OnMemberAdded(DiscordClient client, GuildMemberAddEventArgs e)
{
if (!Database.TryGetOpenTickets(e.Member.Id, out List<Database.Ticket> ownTickets))
{
return;
}
foreach (Database.Ticket ticket in ownTickets)
{
try
{
DiscordChannel channel = await client.GetChannelAsync(ticket.channelID);
if (channel?.GuildId == e.Guild.Id)
{
try
{
await channel.AddOverwriteAsync(e.Member, Permissions.AccessChannels);
await channel.SendMessageAsync(new DiscordEmbedBuilder
{
Color = DiscordColor.Green,
Description = "User '" + e.Member.Username + "#" + e.Member.Discriminator + "' has rejoined the server, and has been re-added to the ticket."
});
}
catch (DiscordException ex)
{
Logger.Error("Exception occurred trying to add channel permissions: " + ex);
Logger.Error("JsomMessage: " + ex.JsonMessage);
}
}
}
catch (Exception) { /* ignored */ }
}
}
internal static async Task OnMemberRemoved(DiscordClient client, GuildMemberRemoveEventArgs e)
{
if (Database.TryGetOpenTickets(e.Member.Id, out List<Database.Ticket> ownTickets))
{
foreach (Database.Ticket ticket in ownTickets)
{
try
{
DiscordChannel channel = await client.GetChannelAsync(ticket.channelID);
if (channel?.GuildId == e.Guild.Id)
{
await channel.SendMessageAsync(new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = "User '" + e.Member.Username + "#" + e.Member.Discriminator + "' has left the server."
});
}
}
catch (Exception) { /* ignored */ }
}
}
if (Database.TryGetAssignedTickets(e.Member.Id, out List<Database.Ticket> assignedTickets) && Config.logChannel != 0)
{
DiscordChannel logChannel = await client.GetChannelAsync(Config.logChannel);
if (logChannel != null)
{
foreach (Database.Ticket ticket in assignedTickets)
{
try
{
DiscordChannel channel = await client.GetChannelAsync(ticket.channelID);
if (channel?.GuildId == e.Guild.Id)
{
await logChannel.SendMessageAsync(new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = "Assigned staff member '" + e.Member.Username + "#" + e.Member.Discriminator + "' has left the server: <#" + channel.Id + ">"
});
}
}
catch (Exception) { /* ignored */ }
}
}
}
}
internal static async Task OnComponentInteractionCreated(DiscordClient client, ComponentInteractionCreateEventArgs e)
{
try
{
switch (e.Interaction.Data.ComponentType)
{
case ComponentType.Button:
switch (e.Id)
{
case "supportboi_closeconfirm":
await CloseCommand.OnConfirmed(e.Interaction);
return;
case { } when e.Id.StartsWith("supportboi_newcommandbutton"):
await NewCommand.OnCategorySelection(e.Interaction);
return;
case { } when e.Id.StartsWith("supportboi_newticketbutton"):
await CreateButtonPanelCommand.OnButtonUsed(e.Interaction);
return;
case "right":
return;
case "left":
return;
case "rightskip":
return;
case "leftskip":
return;
case "stop":
return;
default:
Logger.Warn("Unknown button press received! '" + e.Id + "'");
return;
}
case ComponentType.StringSelect:
switch (e.Id)
{
case { } when e.Id.StartsWith("supportboi_newcommandselector"):
await NewCommand.OnCategorySelection(e.Interaction);
return;
case { } when e.Id.StartsWith("supportboi_newticketselector"):
await CreateSelectionBoxPanelCommand.OnSelectionMenuUsed(e.Interaction);
return;
default:
Logger.Warn("Unknown selection box option received! '" + e.Id + "'");
return;
}
case ComponentType.ActionRow:
Logger.Warn("Unknown action row received! '" + e.Id + "'");
return;
case ComponentType.FormInput:
Logger.Warn("Unknown form input received! '" + e.Id + "'");
return;
default:
Logger.Warn("Unknown interaction type received! '" + e.Interaction.Data.ComponentType + "'");
break;
}
}
catch (DiscordException ex)
{
Logger.Error("Interaction Exception occurred: " + ex);
Logger.Error("JsomMessage: " + ex.JsonMessage);
}
catch (Exception ex)
{
Logger.Error("Interaction Exception occured: " + ex.GetType() + ": " + ex);
}
}
private static string ParseFailedCheck(SlashCheckBaseAttribute attr)
{
return attr switch
{
SlashRequireDirectMessageAttribute => "This command can only be used in direct messages!",
SlashRequireOwnerAttribute => "Only the server owner can use that command!",
SlashRequirePermissionsAttribute => "You don't have permission to do that!",
SlashRequireBotPermissionsAttribute => "The bot doesn't have the required permissions to do that!",
SlashRequireUserPermissionsAttribute => "You don't have permission to do that!",
SlashRequireGuildAttribute => "This command has to be used in a Discord server!",
_ => "Unknown Discord API error occured, please try again later."
};
}
}

68
Akheemah/Logger.cs Normal file
View file

@ -0,0 +1,68 @@
using Microsoft.Extensions.Logging;
using System;
using System.Reflection;
namespace Akheemah;
public static class Logger
{
public static void Debug(string message)
{
try
{
Akheemah.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
{
Akheemah.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
{
Akheemah.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
{
Akheemah.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
{
Akheemah.discordClient.Logger.Log(LogLevel.Critical, new EventId(420, Assembly.GetEntryAssembly()?.GetName().Name), message);
}
catch (NullReferenceException)
{
Console.WriteLine("[CRITICAL] " + message);
}
}
}

53
Akheemah/Transcriber.cs Normal file
View file

@ -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 Akheemah;
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";
}
}

65
Akheemah/Utilities.cs Normal file
View file

@ -0,0 +1,65 @@
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using DSharpPlus.Entities;
namespace Akheemah;
public static class Utilities
{
private static readonly Random rng = new Random();
public static void Shuffle<T>(this IList<T> list)
{
int n = list.Count;
while (n > 1)
{
n--;
int k = rng.Next(n + 1);
(list[k], list[n]) = (list[n], list[k]);
}
}
public static LinkedList<string> ParseListIntoMessages(List<string> listItems)
{
LinkedList<string> messages = new LinkedList<string>();
foreach (string listItem in listItems)
{
if (messages.Last?.Value?.Length + listItem?.Length < 2048)
{
messages.Last.Value += listItem;
}
else
{
messages.AddLast(listItem);
}
}
return messages;
}
public static async Task<List<Database.Category>> GetVerifiedChannels()
{
List<Database.Category> verifiedCategories = new List<Database.Category>();
foreach (Database.Category category in Database.GetAllCategories())
{
DiscordChannel channel = null;
try
{
channel = await Akheemah.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;
}
}

BIN
Akheemah/akheemah.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 422 KiB

View file

@ -0,0 +1,48 @@
bot:
# Bot token.
token: "<add-token-here>"
# Channel where ticket logs are posted (recommended)
log-channel: 000000000000000000
# Message posted when a ticket is opened.
welcome-message: "Please describe your issue below, and include all information needed for us to help you."
# Decides what messages are shown in console
# Possible values are: Critical, Error, Warning, Information, Debug.
console-log-level: "Information"
# One of the following: LongDate, LongDateTime, LongTime, RelativeTime, ShortDate, ShortDateTime, ShortTime
# More info: https://dsharpplus.github.io/api/DSharpPlus.TimestampFormat.html
timestamp-format: "RelativeTime"
# Whether or not staff members should be randomly assigned tickets when they are made. Individual staff members can opt out using the toggleactive command.
random-assignment: true
# If set to true the rasssign command will include staff members set as inactive if a specific role is specified in the command.
# This can be useful if you have admins set as inactive to not automatically receive tickets and then have moderators elevate tickets when needed.
random-assign-role-override: true
# Sets the type of activity for the bot to display in its presence status
# Possible values are: Playing, Streaming, ListeningTo, Watching, Competing
presence-type: "ListeningTo"
# Sets the activity text shown in the bot's status
presence-text: "/new"
# Set to true if you want the /new command to show a selection box instead of a series of buttons
new-command-uses-selector: false
# Number of tickets a single user can have open at a time, staff members are excluded from this
ticket-limit: 5
notifications:
# Notifies the assigned staff member when a new message is posted in a ticket if the ticket has been silent for a configurable amount of time
# Other staff members and bots do not trigger this.
ticket-updated: true
# The above notification will only be sent if the ticket has been silent for more than this amount of days. Default is 0.5 days.
ticket-updated-delay: 0.5
# Notifies staff when they are assigned to tickets
assignment: true
# Notifies the user opening the ticket that their ticket was closed and includes the transcript
closing: true
database:
# Address and port of the mysql server
address: "127.0.0.1"
port: 3306
# Name of the database to use
name: "akheemah"
# Username and password for authentication
user: ""
password: ""