Compare commits
153 commits
Author | SHA1 | Date | |
---|---|---|---|
c9ba8b4952 | |||
5aec1b7e7b | |||
66d67257be | |||
c6579beba2 | |||
dac221246c | |||
12337101b7 | |||
e3984ab968 | |||
0304744d9d | |||
2b73548b7a | |||
a9c28a04b6 | |||
f5d044512a | |||
0ee12cb1ec | |||
586f9c8f07 | |||
c6c7379f20 | |||
8e7a21c81a | |||
ad940c6167 | |||
a88997e8e5 | |||
384f046915 | |||
bb9ef65e42 | |||
c12c17de41 | |||
bfd3196374 | |||
56d3c6b089 | |||
7b64129cc1 | |||
316e814248 | |||
8820549927 | |||
23d6209ffc | |||
580597afae | |||
7d70cde3b4 | |||
84ad8cbca4 | |||
7dfa3ad5e4 | |||
3a57fa1e02 | |||
556f082aa2 | |||
47ff409902 | |||
d4be9cb849 | |||
22dc2255bc | |||
9641cdb0f1 | |||
3ed8dfc06b | |||
055fd5a940 | |||
75ee39f63c | |||
c2c305317c | |||
b80733cf83 | |||
be04edff3f | |||
76462b97fb | |||
a254bc5697 | |||
87e5957ae9 | |||
78994a6263 | |||
e51afd0b47 | |||
2ee77c89af | |||
e8bf4d3004 | |||
851a3c949c | |||
414dbae62f | |||
24defe0128 | |||
2db90a44c7 | |||
769643a292 | |||
f0e48cc2ab | |||
3feaf50b59 | |||
8bf14fcd05 | |||
f5852dae29 | |||
b2c6478458 | |||
e7547b749d | |||
a534ceac69 | |||
93446ca30d | |||
4f265f44e2 | |||
6ec63eb7a7 | |||
3d2d987dfe | |||
b02aacadd6 | |||
729e84fdce | |||
b2113695f8 | |||
14724c054e | |||
414ace3dcc | |||
2553ad5c69 | |||
f03473ba14 | |||
f1ce93ae86 | |||
e2494c73d4 | |||
d9fcef449a | |||
1ced350789 | |||
a8d7440a7a | |||
91991c10f2 | |||
ebd279da45 | |||
839ec527df | |||
f9fbc5990c | |||
280d18c80b | |||
32776826ba | |||
327f4d6de6 | |||
d212f13b12 | |||
e87208d8bd | |||
233fd3278b | |||
9ef4364a13 | |||
4f716dbbc9 | |||
03497a28f8 | |||
d70c2ae0d2 | |||
5c75e1fa7d | |||
f89d50c982 | |||
ce836a465f | |||
c34a396c78 | |||
3a94de9f23 | |||
7f13161853 | |||
32f5518891 | |||
3296fa98d1 | |||
8af3e0a2f4 | |||
3e66a5659d | |||
55029de233 | |||
9c25573e98 | |||
e3137eaa1f | |||
9f15236878 | |||
0dd6913dd8 | |||
4bac506bfc | |||
ea1516e5db | |||
493cfd3436 | |||
c084cbe368 | |||
dc072d2d58 | |||
c77e7c003a | |||
e5d0b40d09 | |||
cb166ec963 | |||
57a1a90747 | |||
851e26f530 | |||
fd74cc14f5 | |||
d8da5084e4 | |||
dd944fb6c8 | |||
b86f613610 | |||
|
aefe977193 | ||
|
bc383e3456 | ||
|
9d890484b9 | ||
|
acf63a745b | ||
|
b4e833404c | ||
|
186587fa0d | ||
|
1f7dd735f2 | ||
|
c6a5b7b656 | ||
|
e638630d30 | ||
|
31bc48d161 | ||
|
d0ad7980d3 | ||
|
dae587e4fd | ||
|
9e8140d0dd | ||
|
e3494c9af0 | ||
|
f99f0e4d09 | ||
|
79d5497b2e | ||
|
f6067f38c3 | ||
|
cfacbfe8e6 | ||
|
ba97c93651 | ||
|
90fced65aa | ||
|
426f190f81 | ||
|
26c6107b81 | ||
|
58ebb0b959 | ||
|
ccc8cd2d15 | ||
|
51d4f07fb5 | ||
|
7d82285e1b | ||
|
b1cfafda4a | ||
|
cf658bf5ca | ||
|
3d8709eb25 | ||
|
f0011a857d | ||
|
6c105ea695 | ||
|
f98c881364 | ||
|
d2ebd118b2 |
99 changed files with 6950 additions and 5311 deletions
63
.gitattributes
vendored
63
.gitattributes
vendored
|
@ -1,63 +0,0 @@
|
|||
###############################################################################
|
||||
# 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
|
18
.github/dependabot.yml
vendored
18
.github/dependabot.yml
vendored
|
@ -1,18 +0,0 @@
|
|||
# To get started with Dependabot version updates, you'll need to specify which
|
||||
# package ecosystems to update and where the package manifests are located.
|
||||
# Please see the documentation for all configuration options:
|
||||
# https://help.github.com/github/administering-a-repository/configuration-options-for-dependency-updates
|
||||
|
||||
version: 2
|
||||
updates:
|
||||
- package-ecosystem: "nuget" # See documentation for possible values
|
||||
directory: "/" # Location of package manifests
|
||||
schedule:
|
||||
interval: "daily"
|
||||
open-pull-requests-limit: 5
|
||||
reviewers:
|
||||
- EmotionChild
|
||||
target-branch: "development"
|
||||
labels:
|
||||
- "nuget"
|
||||
- "dependencies"
|
26
.github/workflows/auto-approve.yml
vendored
26
.github/workflows/auto-approve.yml
vendored
|
@ -1,26 +0,0 @@
|
|||
name: Auto approve
|
||||
|
||||
on: pull_request
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
auto-approve:
|
||||
|
||||
name: Auto approve Pull Request
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
# for hmarr/auto-approve-action to approve PRs
|
||||
permissions:
|
||||
pull-requests: write
|
||||
|
||||
# Only run this on the main repo
|
||||
if: github.event.pull_request.head.repo.full_name == 'EmotionChild/SupportChild'
|
||||
|
||||
steps:
|
||||
- name: Approve via actions
|
||||
uses: hmarr/auto-approve-action@v2.2.1
|
||||
if: github.actor == 'EmotionChild' || github.actor == 'dependabot[bot]'
|
||||
with:
|
||||
github-token: "${{ secrets.GITHUB_TOKEN }}"
|
25
.github/workflows/dotnet.yml
vendored
25
.github/workflows/dotnet.yml
vendored
|
@ -1,25 +0,0 @@
|
|||
name: .NET
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ main ]
|
||||
pull_request:
|
||||
branches: [ main ]
|
||||
|
||||
jobs:
|
||||
build:
|
||||
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- name: Setup .NET
|
||||
uses: actions/setup-dotnet@v2
|
||||
with:
|
||||
dotnet-version: 6.0.x
|
||||
- name: Restore dependencies
|
||||
run: dotnet restore
|
||||
- name: Build
|
||||
run: dotnet build --no-restore
|
||||
- name: Test
|
||||
run: dotnet test --no-build --verbosity normal
|
39
.github/workflows/msbuild.yml
vendored
39
.github/workflows/msbuild.yml
vendored
|
@ -1,39 +0,0 @@
|
|||
name: MSBuild
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ "main" ]
|
||||
pull_request:
|
||||
branches: [ "main" ]
|
||||
|
||||
env:
|
||||
# Path to the solution file relative to the root of the project.
|
||||
SOLUTION_FILE_PATH: .
|
||||
|
||||
# Configuration type to build.
|
||||
# You can convert this to a build matrix if you need coverage of multiple configuration types.
|
||||
# https://docs.github.com/actions/learn-github-actions/managing-complex-workflows#using-a-build-matrix
|
||||
BUILD_CONFIGURATION: Release
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: windows-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
|
||||
- name: Add MSBuild to PATH
|
||||
uses: microsoft/setup-msbuild@v1.0.2
|
||||
|
||||
- name: Restore NuGet packages
|
||||
working-directory: ${{env.GITHUB_WORKSPACE}}
|
||||
run: nuget restore ${{env.SOLUTION_FILE_PATH}}
|
||||
|
||||
- name: Build
|
||||
working-directory: ${{env.GITHUB_WORKSPACE}}
|
||||
# Add additional options to the MSBuild command line here (like platform or verbosity level).
|
||||
# See https://docs.microsoft.com/visualstudio/msbuild/msbuild-command-line-reference
|
||||
run: msbuild /m /p:Configuration=${{env.BUILD_CONFIGURATION}} ${{env.SOLUTION_FILE_PATH}}
|
375
.gitignore
vendored
375
.gitignore
vendored
|
@ -1,369 +1,10 @@
|
|||
## 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
|
||||
*.rsuser
|
||||
*.suo
|
||||
*.user
|
||||
*.userosscache
|
||||
*.sln.docstates
|
||||
/.idea
|
||||
/.vs
|
||||
/bin
|
||||
/obj
|
||||
|
||||
# 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
|
||||
/config.yml
|
||||
/transcripts
|
||||
/Linux-x64
|
||||
/Windows-x64
|
79
Commands/AddCategoryCommand.cs
Normal file
79
Commands/AddCategoryCommand.cs
Normal file
|
@ -0,0 +1,79 @@
|
|||
using System.ComponentModel;
|
||||
using System.Threading.Tasks;
|
||||
using DSharpPlus.Commands;
|
||||
using DSharpPlus.Commands.ContextChecks;
|
||||
using DSharpPlus.Commands.Processors.SlashCommands;
|
||||
using DSharpPlus.Entities;
|
||||
using DSharpPlus.Exceptions;
|
||||
|
||||
namespace SupportChild.Commands;
|
||||
|
||||
public class AddCategoryCommand
|
||||
{
|
||||
[RequireGuild]
|
||||
[Command("addcategory")]
|
||||
[Description("Adds a category to the ticket bot letting users open tickets in them.")]
|
||||
public async Task OnExecute(SlashCommandContext command,
|
||||
[Parameter("title")][Description("The name to display on buttons and in selection boxes.")] string title,
|
||||
[Parameter("category")][Description("The category to add.")] DiscordChannel category)
|
||||
{
|
||||
if (!category.IsCategory)
|
||||
{
|
||||
await command.RespondAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Red,
|
||||
Description = "That channel is not a category."
|
||||
}, true);
|
||||
return;
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(title))
|
||||
{
|
||||
await command.RespondAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Red,
|
||||
Description = "Invalid category title specified."
|
||||
}, true);
|
||||
return;
|
||||
}
|
||||
|
||||
if (Database.TryGetCategory(category.Id, out Database.Category _))
|
||||
{
|
||||
await command.RespondAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Red,
|
||||
Description = "That category is already registered."
|
||||
}, true);
|
||||
return;
|
||||
}
|
||||
|
||||
if (Database.TryGetCategory(title, out Database.Category _))
|
||||
{
|
||||
await command.RespondAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Red,
|
||||
Description = "There is already a category with that title."
|
||||
}, true);
|
||||
return;
|
||||
}
|
||||
|
||||
if (Database.AddCategory(title, category.Id))
|
||||
{
|
||||
await command.RespondAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Green,
|
||||
Description = "Category added."
|
||||
}, true);
|
||||
}
|
||||
else
|
||||
{
|
||||
await command.RespondAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Red,
|
||||
Description = "Error: Failed adding the category to the database."
|
||||
}, true);
|
||||
}
|
||||
|
||||
await LogChannel.Success(command.User.Mention + " added `" + category.Name + "` as `" + title + "` to the category list.");
|
||||
}
|
||||
}
|
76
Commands/AddCommand.cs
Normal file
76
Commands/AddCommand.cs
Normal file
|
@ -0,0 +1,76 @@
|
|||
using System;
|
||||
using System.ComponentModel;
|
||||
using System.Threading.Tasks;
|
||||
using DSharpPlus.Commands;
|
||||
using DSharpPlus.Commands.ContextChecks;
|
||||
using DSharpPlus.Commands.Processors.SlashCommands;
|
||||
using DSharpPlus.Entities;
|
||||
using DSharpPlus.Exceptions;
|
||||
|
||||
namespace SupportChild.Commands;
|
||||
|
||||
public class AddCommand
|
||||
{
|
||||
[RequireGuild]
|
||||
[Command("add")]
|
||||
[Description("Adds a user to this ticket.")]
|
||||
public async Task OnExecute(SlashCommandContext command,
|
||||
[Parameter("user")][Description("User to add to ticket.")] DiscordUser user)
|
||||
{
|
||||
// Check if ticket exists in the database
|
||||
if (!Database.TryGetOpenTicket(command.Channel.Id, out Database.Ticket ticket))
|
||||
{
|
||||
await command.RespondAsync(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.RespondAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Red,
|
||||
Description = "Could not find that user in this server."
|
||||
}, true);
|
||||
return;
|
||||
}
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
await command.RespondAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Red,
|
||||
Description = "Could not find that user in this server."
|
||||
}, true);
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
await command.Channel.AddOverwriteAsync(member, DiscordPermissions.AccessChannels);
|
||||
await command.RespondAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Green,
|
||||
Description = "Added " + member.Mention + " to ticket."
|
||||
});
|
||||
|
||||
await LogChannel.Success(member.Mention + " was added to " + command.Channel.Mention + " by " + command.User.Mention + ".", ticket.id);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
await command.RespondAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Red,
|
||||
Description = "Could not add " + member.Mention + " to ticket, unknown error occured."
|
||||
}, true);
|
||||
}
|
||||
}
|
||||
}
|
60
Commands/AddMessageCommand.cs
Normal file
60
Commands/AddMessageCommand.cs
Normal file
|
@ -0,0 +1,60 @@
|
|||
using System.ComponentModel;
|
||||
using System.Globalization;
|
||||
using DSharpPlus.Entities;
|
||||
using System.Threading.Tasks;
|
||||
using DSharpPlus.Commands;
|
||||
using DSharpPlus.Commands.ContextChecks;
|
||||
using DSharpPlus.Commands.Processors.SlashCommands;
|
||||
using DSharpPlus.Exceptions;
|
||||
|
||||
namespace SupportChild.Commands;
|
||||
|
||||
public class AddMessageCommand
|
||||
{
|
||||
[RequireGuild]
|
||||
[Command("addmessage")]
|
||||
[Description("Adds a new message for the 'say' command.")]
|
||||
public async Task OnExecute(SlashCommandContext command,
|
||||
[Parameter("identifier")][Description("The identifier word used in the /say command.")] string identifier,
|
||||
[Parameter("message")][Description("The message the /say command will return.")] string message)
|
||||
{
|
||||
if (string.IsNullOrEmpty(message))
|
||||
{
|
||||
await command.RespondAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Red,
|
||||
Description = "No message specified."
|
||||
}, true);
|
||||
return;
|
||||
}
|
||||
|
||||
if (Database.TryGetMessage(identifier.ToLower(CultureInfo.InvariantCulture), out Database.Message _))
|
||||
{
|
||||
await command.RespondAsync(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.RespondAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Green,
|
||||
Description = "Message added."
|
||||
}, true);
|
||||
}
|
||||
else
|
||||
{
|
||||
await command.RespondAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Red,
|
||||
Description = "Error: Failed adding the message to the database."
|
||||
}, true);
|
||||
}
|
||||
|
||||
await LogChannel.Success(command.User.Mention + " added or updated `" + identifier + "` in the /say command.\n\nContent:\n\n" + message);
|
||||
}
|
||||
}
|
76
Commands/AddStaffCommand.cs
Normal file
76
Commands/AddStaffCommand.cs
Normal file
|
@ -0,0 +1,76 @@
|
|||
using System;
|
||||
using System.ComponentModel;
|
||||
using System.Threading.Tasks;
|
||||
using DSharpPlus.Commands;
|
||||
using DSharpPlus.Commands.ContextChecks;
|
||||
using DSharpPlus.Commands.Processors.SlashCommands;
|
||||
using DSharpPlus.Entities;
|
||||
using DSharpPlus.Exceptions;
|
||||
using MySqlConnector;
|
||||
|
||||
namespace SupportChild.Commands;
|
||||
|
||||
public class AddStaffCommand
|
||||
{
|
||||
[RequireGuild]
|
||||
[Command("addstaff")]
|
||||
[Description("Adds a new staff member.")]
|
||||
public async Task OnExecute(SlashCommandContext command,
|
||||
[Parameter("user")][Description("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.RespondAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Red,
|
||||
Description = "Could not find that user in this server."
|
||||
}, true);
|
||||
return;
|
||||
}
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
await command.RespondAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Red,
|
||||
Description = "Could not find that user in this server."
|
||||
}, true);
|
||||
return;
|
||||
}
|
||||
|
||||
bool alreadyStaff = Database.IsStaff(staffMember.Id);
|
||||
|
||||
await using MySqlConnection c = Database.GetConnection();
|
||||
MySqlCommand cmd = alreadyStaff ? 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();
|
||||
|
||||
if (alreadyStaff)
|
||||
{
|
||||
await command.RespondAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Green,
|
||||
Description = staffMember.Mention + " is already a staff member, refreshed username in database."
|
||||
}, true);
|
||||
}
|
||||
else
|
||||
{
|
||||
await command.RespondAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Green,
|
||||
Description = staffMember.Mention + " was added to staff."
|
||||
}, true);
|
||||
|
||||
await LogChannel.Success(staffMember.Mention + " was added to staff by " + command.User.Mention + ".");
|
||||
}
|
||||
}
|
||||
}
|
135
Commands/AdminCommands.cs
Normal file
135
Commands/AdminCommands.cs
Normal file
|
@ -0,0 +1,135 @@
|
|||
using System;
|
||||
using System.ComponentModel;
|
||||
using System.Threading.Tasks;
|
||||
using DSharpPlus.Commands;
|
||||
using DSharpPlus.Commands.ContextChecks;
|
||||
using DSharpPlus.Commands.Processors.SlashCommands;
|
||||
using DSharpPlus.Entities;
|
||||
using DSharpPlus.Exceptions;
|
||||
using SupportChild.Interviews;
|
||||
|
||||
namespace SupportChild.Commands;
|
||||
|
||||
[Command("admin")]
|
||||
[Description("Administrative commands.")]
|
||||
public class AdminCommands
|
||||
{
|
||||
[RequireGuild]
|
||||
[Command("setticket")]
|
||||
[Description("Turns a channel into a ticket. WARNING: Anyone will be able to delete the channel using /close.")]
|
||||
public async Task SetTicket(SlashCommandContext command,
|
||||
[Parameter("user")][Description("(Optional) The owner of the ticket.")] DiscordUser user = null)
|
||||
{
|
||||
// Check if ticket exists in the database
|
||||
if (Database.IsOpenTicket(command.Channel.Id))
|
||||
{
|
||||
await command.RespondAsync(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);
|
||||
await command.RespondAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Green,
|
||||
Description = "Channel has been designated ticket " + id.ToString("00000") + "."
|
||||
});
|
||||
|
||||
await LogChannel.Success(command.Channel.Mention + " has been designated ticket " + id.ToString("00000") + " by " + command.Member?.Mention + ".", (uint)id);
|
||||
}
|
||||
|
||||
[RequireGuild]
|
||||
[Command("unsetticket")]
|
||||
[Description("Deletes a ticket from the ticket system without deleting the channel.")]
|
||||
public async Task UnsetTicket(SlashCommandContext command,
|
||||
[Parameter("ticket-id")][Description("(Optional) Ticket to unset. Uses the channel you are in by default. Use ticket ID, not channel ID!")] long ticketID = 0)
|
||||
{
|
||||
Database.Ticket ticket;
|
||||
DiscordChannel channel = null;
|
||||
|
||||
await command.DeferResponseAsync(true);
|
||||
|
||||
if (ticketID == 0)
|
||||
{
|
||||
// Check if ticket exists in the database
|
||||
if (!Database.TryGetOpenTicket(command.Channel.Id, out ticket))
|
||||
{
|
||||
await command.RespondAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Red,
|
||||
Description = "This channel is not a ticket!"
|
||||
}, true);
|
||||
return;
|
||||
}
|
||||
channel = command.Channel;
|
||||
}
|
||||
else
|
||||
{
|
||||
// Check if ticket exists in the database
|
||||
if (!Database.TryGetOpenTicketByID((uint)ticketID, out ticket))
|
||||
{
|
||||
await command.RespondAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Red,
|
||||
Description = "There is no ticket with this ticket ID."
|
||||
}, true);
|
||||
return;
|
||||
}
|
||||
|
||||
// Find the channel if it still exists
|
||||
try
|
||||
{
|
||||
channel = await command.Guild.GetChannelAsync(ticket.channelID);
|
||||
}
|
||||
catch (Exception) { /*ignored*/ }
|
||||
}
|
||||
|
||||
// If the channel exists, stop any ongoing interview
|
||||
if (channel != null)
|
||||
{
|
||||
await Interviewer.StopInterview(channel);
|
||||
}
|
||||
|
||||
// Delete the ticket from the database and respond to command
|
||||
if (Database.DeleteOpenTicket(ticket.id))
|
||||
{
|
||||
await command.RespondAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Green,
|
||||
Description = "Channel has been undesignated as a ticket."
|
||||
});
|
||||
|
||||
await LogChannel.Success(command.Channel.Mention + " has been undesignated as a ticket by " + command.User.Mention + ".", ticket.id);
|
||||
}
|
||||
else
|
||||
{
|
||||
await command.RespondAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Red,
|
||||
Description = "Error: Failed removing ticket from database."
|
||||
}, true);
|
||||
}
|
||||
}
|
||||
|
||||
[RequireGuild]
|
||||
[Command("reload")]
|
||||
[Description("Reloads the bot config.")]
|
||||
public async Task Reload(SlashCommandContext command)
|
||||
{
|
||||
await command.RespondAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Green,
|
||||
Description = "Reloading bot application..."
|
||||
}, true);
|
||||
|
||||
await LogChannel.Success(command.Channel.Mention + " reloaded the bot.");
|
||||
|
||||
Logger.Log("Reloading bot...");
|
||||
await SupportChild.Reload();
|
||||
}
|
||||
}
|
97
Commands/AssignCommand.cs
Normal file
97
Commands/AssignCommand.cs
Normal file
|
@ -0,0 +1,97 @@
|
|||
using System;
|
||||
using System.ComponentModel;
|
||||
using System.Threading.Tasks;
|
||||
using DSharpPlus.Commands;
|
||||
using DSharpPlus.Commands.ContextChecks;
|
||||
using DSharpPlus.Commands.Processors.SlashCommands;
|
||||
using DSharpPlus.Entities;
|
||||
using DSharpPlus.Exceptions;
|
||||
|
||||
namespace SupportChild.Commands;
|
||||
|
||||
public class AssignCommand
|
||||
{
|
||||
[RequireGuild]
|
||||
[Command("assign")]
|
||||
[Description("Assigns a staff member to this ticket.")]
|
||||
public async Task OnExecute(SlashCommandContext command,
|
||||
[Parameter("user")][Description("(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.RespondAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Red,
|
||||
Description = "Could not find that user in this server."
|
||||
}, true);
|
||||
return;
|
||||
}
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
await command.RespondAsync(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.RespondAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Red,
|
||||
Description = "This channel is not a ticket."
|
||||
}, true);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!Database.IsStaff(member.Id))
|
||||
{
|
||||
await command.RespondAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Red,
|
||||
Description = "Error: User is not registered as staff."
|
||||
}, true);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!Database.AssignStaff(ticket, member.Id))
|
||||
{
|
||||
await command.RespondAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Red,
|
||||
Description = "Error: Failed to assign " + member.Mention + " to ticket."
|
||||
}, true);
|
||||
return;
|
||||
}
|
||||
|
||||
await command.RespondAsync(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) { /* ignore */ }
|
||||
}
|
||||
|
||||
await LogChannel.Success(member.Mention + " was assigned to " + command.Channel.Mention + " by " + command.User.Mention + ".", ticket.id);
|
||||
}
|
||||
}
|
50
Commands/BlacklistCommand.cs
Normal file
50
Commands/BlacklistCommand.cs
Normal file
|
@ -0,0 +1,50 @@
|
|||
using System;
|
||||
using System.ComponentModel;
|
||||
using System.Threading.Tasks;
|
||||
using DSharpPlus.Commands;
|
||||
using DSharpPlus.Commands.ContextChecks;
|
||||
using DSharpPlus.Commands.Processors.SlashCommands;
|
||||
using DSharpPlus.Entities;
|
||||
using DSharpPlus.Exceptions;
|
||||
|
||||
namespace SupportChild.Commands;
|
||||
|
||||
public class BlacklistCommand
|
||||
{
|
||||
[RequireGuild]
|
||||
[Command("blacklist")]
|
||||
[Description("Blacklists a user from opening tickets.")]
|
||||
public async Task OnExecute(SlashCommandContext command,
|
||||
[Parameter("user")][Description("User to blacklist.")] DiscordUser user)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!Database.Blacklist(user.Id, command.User.Id))
|
||||
{
|
||||
await command.RespondAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Red,
|
||||
Description = user.Mention + " is already blacklisted."
|
||||
}, true);
|
||||
return;
|
||||
}
|
||||
|
||||
await command.RespondAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Green,
|
||||
Description = "Blocked " + user.Mention + " from opening new tickets."
|
||||
}, true);
|
||||
|
||||
await LogChannel.Success(user.Mention + " was blocked from opening tickets by " + command.User.Mention + ".");
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
await command.RespondAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Red,
|
||||
Description = "Error occured while blacklisting " + user.Mention + "."
|
||||
}, true);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
225
Commands/CloseCommand.cs
Normal file
225
Commands/CloseCommand.cs
Normal file
|
@ -0,0 +1,225 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.IO;
|
||||
using System.Threading.Tasks;
|
||||
using DSharpPlus.Commands;
|
||||
using DSharpPlus.Commands.ContextChecks;
|
||||
using DSharpPlus.Commands.Processors.SlashCommands;
|
||||
using DSharpPlus.Entities;
|
||||
using DSharpPlus.Exceptions;
|
||||
|
||||
namespace SupportChild.Commands;
|
||||
|
||||
public class CloseCommand
|
||||
{
|
||||
// TODO: Refactor this class a whole lot
|
||||
private static Dictionary<ulong, string> closeReasons = new Dictionary<ulong, string>();
|
||||
private static List<ulong> currentlyClosingTickets = new List<ulong>();
|
||||
|
||||
[RequireGuild]
|
||||
[Command("close")]
|
||||
[Description("Closes this ticket.")]
|
||||
public async Task OnExecute(SlashCommandContext command,
|
||||
[Parameter("reason")][Description("(Optional) The reason for closing this ticket.")] string reason = "")
|
||||
{
|
||||
// Check if ticket exists in the database
|
||||
if (!Database.TryGetOpenTicket(command.Channel.Id, out Database.Ticket _))
|
||||
{
|
||||
await command.RespondAsync(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(DiscordButtonStyle.Danger, "supportchild_closeconfirm", "Confirm"));
|
||||
|
||||
await command.RespondAsync(confirmation);
|
||||
closeReasons.Add(command.Channel.Id, reason);
|
||||
}
|
||||
|
||||
public static async Task OnConfirmed(DiscordInteraction interaction)
|
||||
{
|
||||
if (currentlyClosingTickets.Contains(interaction.Channel.Id))
|
||||
{
|
||||
await interaction.CreateResponseAsync(DiscordInteractionResponseType.ChannelMessageWithSource,
|
||||
new DiscordInteractionResponseBuilder().AddEmbed(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Red,
|
||||
Description = "This ticket is already closing."
|
||||
}).AsEphemeral());
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
currentlyClosingTickets.Add(interaction.Channel.Id);
|
||||
await interaction.CreateResponseAsync(DiscordInteractionResponseType.DeferredMessageUpdate);
|
||||
|
||||
// Check if ticket exists in the database
|
||||
if (!Database.TryGetOpenTicket(interaction.Channel.Id, out Database.Ticket ticket))
|
||||
{
|
||||
currentlyClosingTickets.Remove(interaction.Channel.Id);
|
||||
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)
|
||||
{
|
||||
currentlyClosingTickets.Remove(interaction.Channel.Id);
|
||||
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(interaction.Channel.Id, out string cachedReason))
|
||||
{
|
||||
closeReason = "\nReason: " + cachedReason + "\n";
|
||||
}
|
||||
|
||||
string fileName = Transcriber.GetZipFilename(ticket.id);
|
||||
string filePath = Transcriber.GetZipPath(ticket.id);
|
||||
long zipSize = 0;
|
||||
|
||||
// If the zip transcript doesn't exist, use the html file.
|
||||
try
|
||||
{
|
||||
FileInfo fileInfo = new FileInfo(filePath);
|
||||
if (!fileInfo.Exists || fileInfo.Length >= 26214400)
|
||||
{
|
||||
fileName = Transcriber.GetHTMLFilename(ticket.id);
|
||||
filePath = Transcriber.GetHtmlPath(ticket.id);
|
||||
}
|
||||
zipSize = fileInfo.Length;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
currentlyClosingTickets.Remove(interaction.Channel.Id);
|
||||
await interaction.EditOriginalResponseAsync(new DiscordWebhookBuilder().AddEmbed(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Red,
|
||||
Description = "ERROR: Could not find transcript file. Aborting..."
|
||||
}));
|
||||
Logger.Error("Failed to access transcript file:", e);
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if the chosen file path works.
|
||||
if (!File.Exists(filePath))
|
||||
{
|
||||
currentlyClosingTickets.Remove(interaction.Channel.Id);
|
||||
await interaction.EditOriginalResponseAsync(new DiscordWebhookBuilder().AddEmbed(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Red,
|
||||
Description = "ERROR: Could not find transcript file. Aborting..."
|
||||
}));
|
||||
Logger.Error("Transcript file does not exist: \"" + filePath + "\"");
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
await using FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read);
|
||||
await LogChannel.Success("Ticket " + ticket.id.ToString("00000") + " closed by " + interaction.User.Mention + ".\n" + closeReason, ticket.id, new Utilities.File(fileName, file));
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Logger.Error("Error occurred sending transcript log message. ", e);
|
||||
}
|
||||
|
||||
if (Config.closingNotifications)
|
||||
{
|
||||
try
|
||||
{
|
||||
DiscordUser staffMember = await SupportChild.client.GetUserAsync(ticket.creatorID);
|
||||
await using FileStream file = new(filePath, FileMode.Open, FileAccess.Read);
|
||||
|
||||
DiscordMessageBuilder message = new();
|
||||
|
||||
if (zipSize >= 26214400)
|
||||
{
|
||||
message.AddEmbed(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Orange,
|
||||
Description = "Ticket " + ticket.id.ToString("00000") + " which you opened has now been closed, check the transcript for more info.\n\n" +
|
||||
"The zip file is too large, sending only the HTML file. Ask an administrator for the zip if you need it.\"\n" + closeReason,
|
||||
Footer = new DiscordEmbedBuilder.EmbedFooter
|
||||
{
|
||||
Text = "Ticket: " + ticket.id.ToString("00000")
|
||||
}
|
||||
});
|
||||
}
|
||||
else
|
||||
{
|
||||
message.AddEmbed(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 = "Ticket: " + ticket.id.ToString("00000")
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
message.AddFiles(new Dictionary<string, Stream> { { fileName, file } });
|
||||
|
||||
await staffMember.SendMessageAsync(message);
|
||||
}
|
||||
catch (NotFoundException) { /* ignore */ }
|
||||
catch (UnauthorizedException) { /* ignore */ }
|
||||
}
|
||||
|
||||
Database.ArchiveTicket(ticket);
|
||||
Database.TryDeleteInterview(interaction.Channel.Id);
|
||||
|
||||
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(interaction.Channel.Id);
|
||||
currentlyClosingTickets.Remove(interaction.Channel.Id);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
currentlyClosingTickets.Remove(interaction.Channel.Id);
|
||||
await interaction.EditOriginalResponseAsync(new DiscordWebhookBuilder().AddEmbed(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Red,
|
||||
Description = "An unexpected error occurred when trying to close ticket. Aborting..."
|
||||
}));
|
||||
Logger.Error("An unexpected error occurred when trying to close ticket:", e);
|
||||
}
|
||||
}
|
||||
}
|
56
Commands/CreateButtonPanelCommand.cs
Normal file
56
Commands/CreateButtonPanelCommand.cs
Normal file
|
@ -0,0 +1,56 @@
|
|||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using DSharpPlus.Commands;
|
||||
using DSharpPlus.Commands.ContextChecks;
|
||||
using DSharpPlus.Commands.Processors.SlashCommands;
|
||||
using DSharpPlus.Entities;
|
||||
using DSharpPlus.Exceptions;
|
||||
|
||||
namespace SupportChild.Commands;
|
||||
|
||||
public class CreateButtonPanelCommand
|
||||
{
|
||||
[RequireGuild]
|
||||
[Command("createbuttonpanel")]
|
||||
[Description("Creates a series of buttons which users can use to open new tickets in specific categories.")]
|
||||
public async Task OnExecute(SlashCommandContext command)
|
||||
{
|
||||
DiscordMessageBuilder builder = new DiscordMessageBuilder().WithContent(" ");
|
||||
List<Database.Category> verifiedCategories = await Utilities.GetVerifiedCategories();
|
||||
|
||||
if (verifiedCategories.Count == 0)
|
||||
{
|
||||
await command.RespondAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Red,
|
||||
Description = "Error: No registered categories found. You have to use /addcategory first."
|
||||
}, true);
|
||||
return;
|
||||
}
|
||||
|
||||
verifiedCategories = verifiedCategories.OrderBy(x => x.name).ToList();
|
||||
|
||||
int nrOfButtons = 0;
|
||||
for (int nrOfButtonRows = 0; nrOfButtonRows < 5 && nrOfButtons < verifiedCategories.Count; nrOfButtonRows++)
|
||||
{
|
||||
List<DiscordButtonComponent> buttonRow = new List<DiscordButtonComponent>();
|
||||
|
||||
for (; nrOfButtons < 5 * (nrOfButtonRows + 1) && nrOfButtons < verifiedCategories.Count; nrOfButtons++)
|
||||
{
|
||||
buttonRow.Add(new DiscordButtonComponent(DiscordButtonStyle.Primary, "supportchild_newticketbutton " + verifiedCategories[nrOfButtons].id, verifiedCategories[nrOfButtons].name));
|
||||
}
|
||||
builder.AddComponents(buttonRow);
|
||||
}
|
||||
|
||||
await command.Channel.SendMessageAsync(builder);
|
||||
await command.RespondAsync(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);
|
||||
|
||||
await LogChannel.Success(command.User.Mention + " created a new button panel in " + command.Channel.Mention + ".");
|
||||
}
|
||||
}
|
95
Commands/CreateSelectionBoxPanelCommand.cs
Normal file
95
Commands/CreateSelectionBoxPanelCommand.cs
Normal file
|
@ -0,0 +1,95 @@
|
|||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using DSharpPlus.Commands;
|
||||
using DSharpPlus.Commands.ContextChecks;
|
||||
using DSharpPlus.Commands.Processors.SlashCommands;
|
||||
using DSharpPlus.Entities;
|
||||
using DSharpPlus.Exceptions;
|
||||
|
||||
namespace SupportChild.Commands;
|
||||
|
||||
public class CreateSelectionBoxPanelCommand
|
||||
{
|
||||
[RequireGuild]
|
||||
[Command("createselectionboxpanel")]
|
||||
[Description("Creates a selection box which users can use to open new tickets in specific categories.")]
|
||||
public async Task OnExecute(SlashCommandContext command,
|
||||
[Parameter("placeholder")][Description("(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.RespondAsync(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);
|
||||
|
||||
await LogChannel.Success(command.User.Mention + " created a new selector panel in " + command.Channel.Mention + ".");
|
||||
}
|
||||
|
||||
public static async Task<List<DiscordSelectComponent>> GetSelectComponents(SlashCommandContext command, string placeholder)
|
||||
{
|
||||
List<Database.Category> verifiedCategories = await Utilities.GetVerifiedCategories();
|
||||
|
||||
if (verifiedCategories.Count == 0)
|
||||
{
|
||||
return new List<DiscordSelectComponent>();
|
||||
}
|
||||
|
||||
verifiedCategories = verifiedCategories.OrderBy(x => x.name).ToList();
|
||||
List<DiscordSelectComponent> selectionComponents = new List<DiscordSelectComponent>();
|
||||
|
||||
int selectionOptions = 0;
|
||||
for (int selectionBoxes = 0; selectionBoxes < 5 && selectionOptions < verifiedCategories.Count; selectionBoxes++)
|
||||
{
|
||||
List<DiscordSelectComponentOption> categoryOptions = new List<DiscordSelectComponentOption>();
|
||||
|
||||
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(DiscordInteractionResponseType.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());
|
||||
}
|
||||
}
|
||||
}
|
96
Commands/InterviewCommands.cs
Normal file
96
Commands/InterviewCommands.cs
Normal file
|
@ -0,0 +1,96 @@
|
|||
using System.ComponentModel;
|
||||
using System.Threading.Tasks;
|
||||
using DSharpPlus.Commands;
|
||||
using DSharpPlus.Commands.Processors.SlashCommands;
|
||||
using DSharpPlus.Entities;
|
||||
using DSharpPlus.Exceptions;
|
||||
using SupportChild.Interviews;
|
||||
|
||||
namespace SupportChild.Commands;
|
||||
|
||||
[Command("interview")]
|
||||
[Description("Interview management.")]
|
||||
public class InterviewCommands
|
||||
{
|
||||
[Command("restart")]
|
||||
[Description("Restarts the interview in this ticket, using an updated template if available.")]
|
||||
public async Task Restart(SlashCommandContext command)
|
||||
{
|
||||
if (!Database.TryGetOpenTicket(command.Channel.Id, out Database.Ticket ticket))
|
||||
{
|
||||
await command.RespondAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Red,
|
||||
Description = "This channel is not a ticket."
|
||||
}, true);
|
||||
return;
|
||||
}
|
||||
|
||||
await command.DeferResponseAsync(true);
|
||||
|
||||
if (await Interviewer.RestartInterview(command.Channel))
|
||||
{
|
||||
await command.RespondAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Green,
|
||||
Description = "Interview restarted."
|
||||
}, true);
|
||||
}
|
||||
else
|
||||
{
|
||||
await command.RespondAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Red,
|
||||
Description = "An error occured when trying to restart the interview."
|
||||
}, true);
|
||||
}
|
||||
|
||||
await LogChannel.Success(command.User.Mention + " restarted interview in " + command.Channel.Mention + ".", ticket.id);
|
||||
}
|
||||
|
||||
[Command("stop")]
|
||||
[Description("Stops the interview in this ticket.")]
|
||||
public async Task Stop(SlashCommandContext command)
|
||||
{
|
||||
if (!Database.TryGetOpenTicket(command.Channel.Id, out Database.Ticket ticket))
|
||||
{
|
||||
await command.RespondAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Red,
|
||||
Description = "This channel is not a ticket."
|
||||
}, true);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!Database.TryGetInterview(command.Channel.Id, out InterviewStep interviewRoot))
|
||||
{
|
||||
await command.RespondAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Red,
|
||||
Description = "There is no interview open in this ticket.."
|
||||
}, true);
|
||||
return;
|
||||
}
|
||||
|
||||
await command.DeferResponseAsync(true);
|
||||
|
||||
if (await Interviewer.StopInterview(command.Channel))
|
||||
{
|
||||
await command.RespondAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Green,
|
||||
Description = "Interview stopped."
|
||||
}, true);
|
||||
}
|
||||
else
|
||||
{
|
||||
await command.RespondAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Red,
|
||||
Description = "An error occured when trying to stop the interview."
|
||||
}, true);
|
||||
}
|
||||
|
||||
await LogChannel.Success(command.User.Mention + " stopped the interview in " + command.Channel.Mention + ".", ticket.id);
|
||||
}
|
||||
}
|
241
Commands/InterviewTemplateCommands.cs
Normal file
241
Commands/InterviewTemplateCommands.cs
Normal file
|
@ -0,0 +1,241 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.IO;
|
||||
using System.Net.Http;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using DSharpPlus.Commands;
|
||||
using DSharpPlus.Commands.ContextChecks;
|
||||
using DSharpPlus.Commands.Processors.SlashCommands;
|
||||
using DSharpPlus.Entities;
|
||||
using DSharpPlus.Exceptions;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Schema;
|
||||
using SupportChild.Interviews;
|
||||
|
||||
namespace SupportChild.Commands;
|
||||
|
||||
[Command("interviewtemplate")]
|
||||
[Description("Interview template management.")]
|
||||
public class InterviewTemplateCommands
|
||||
{
|
||||
private static readonly string jsonSchema = Utilities.ReadManifestData("Interviews.interview_template.schema.json");
|
||||
|
||||
[RequireGuild]
|
||||
[Command("get")]
|
||||
[Description("Provides a copy of the interview template for a category which you can edit and then reupload.")]
|
||||
public async Task Get(SlashCommandContext command,
|
||||
[Parameter("category")][Description("The category to get the template for.")] DiscordChannel category)
|
||||
{
|
||||
if (!category?.IsCategory ?? true)
|
||||
{
|
||||
await command.RespondAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Red,
|
||||
Description = "That channel is not a category."
|
||||
}, true);
|
||||
return;
|
||||
}
|
||||
|
||||
string interviewTemplateJSON = Database.GetInterviewTemplateJSON(category.Id);
|
||||
if (interviewTemplateJSON == null)
|
||||
{
|
||||
string defaultTemplate =
|
||||
"{\n" +
|
||||
" \"category-id\": " + category.Id + ",\n" +
|
||||
" \"interview\":\n" +
|
||||
" {\n" +
|
||||
" \"message\": \"\",\n" +
|
||||
" \"message-type\": \"\",\n" +
|
||||
" \"color\": \"\",\n" +
|
||||
" \"steps\":\n" +
|
||||
" {\n" +
|
||||
" \n" +
|
||||
" }\n" +
|
||||
" }\n" +
|
||||
"}";
|
||||
MemoryStream stream = new(Encoding.UTF8.GetBytes(defaultTemplate));
|
||||
|
||||
DiscordInteractionResponseBuilder response = new DiscordInteractionResponseBuilder().AddEmbed(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Green,
|
||||
Description = "No interview template found for this category. A default template has been generated."
|
||||
}).AddFile("interview-template-" + category.Id + ".json", stream).AsEphemeral();
|
||||
await command.RespondAsync(response);
|
||||
}
|
||||
else
|
||||
{
|
||||
MemoryStream stream = new(Encoding.UTF8.GetBytes(interviewTemplateJSON));
|
||||
await command.RespondAsync(new DiscordInteractionResponseBuilder().AddFile("interview-template-" + category.Id + ".json", stream).AsEphemeral());
|
||||
}
|
||||
}
|
||||
|
||||
[RequireGuild]
|
||||
[Command("set")]
|
||||
[Description("Uploads an interview template file.")]
|
||||
public async Task Set(SlashCommandContext command,
|
||||
[Parameter("file")][Description("The file containing the template.")] DiscordAttachment file)
|
||||
{
|
||||
await command.DeferResponseAsync(true);
|
||||
|
||||
if (!file.MediaType?.Contains("application/json") ?? false)
|
||||
{
|
||||
await command.RespondAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Red,
|
||||
Description = "The uploaded file is not a JSON file according to Discord."
|
||||
}, true);
|
||||
return;
|
||||
}
|
||||
|
||||
Stream stream = await new HttpClient().GetStreamAsync(file.Url);
|
||||
try
|
||||
{
|
||||
JSchemaValidatingReader validatingReader = new(new JsonTextReader(new StreamReader(stream)));
|
||||
validatingReader.Schema = JSchema.Parse(jsonSchema);
|
||||
|
||||
// The schema seems to throw an additional error with incorrect information if an invalid parameter is included
|
||||
// in the template. Throw here in order to only show the first correct error to the user, also skips unnecessary validation further down.
|
||||
validatingReader.ValidationEventHandler += (_, a) => throw new JsonException(a.Message);
|
||||
|
||||
JsonSerializer serializer = new();
|
||||
Template template = serializer.Deserialize<Template>(validatingReader);
|
||||
|
||||
DiscordChannel category = await SupportChild.client.GetChannelAsync(template.categoryID);
|
||||
if (!category.IsCategory)
|
||||
{
|
||||
await command.RespondAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Red,
|
||||
Description = "The category ID in the uploaded JSON structure is not a valid category."
|
||||
}, true);
|
||||
return;
|
||||
}
|
||||
|
||||
List<string> errors = [];
|
||||
List<string> warnings = [];
|
||||
template.interview.Validate(ref errors, ref warnings, "interview", 0, 0);
|
||||
if (errors.Count != 0)
|
||||
{
|
||||
string errorString = string.Join("```\n```", errors);
|
||||
if (errorString.Length > 4000)
|
||||
{
|
||||
errorString = errorString.Substring(0, 4000);
|
||||
}
|
||||
|
||||
await command.RespondAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Red,
|
||||
Description = "The uploaded JSON structure could not be parsed as an interview template.\n\nErrors:\n```\n" + errorString + "\n```"
|
||||
}, true);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!Database.SetInterviewTemplate(template))
|
||||
{
|
||||
await command.RespondAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Red,
|
||||
Description = "An error occured trying to write the new template to database."
|
||||
}, true);
|
||||
return;
|
||||
}
|
||||
|
||||
if (warnings.Count == 0)
|
||||
{
|
||||
await command.RespondAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Green,
|
||||
Description = "Uploaded interview template for `" + category.Name + "`."
|
||||
}, true);
|
||||
}
|
||||
else
|
||||
{
|
||||
string warningString = string.Join("```\n```", warnings);
|
||||
if (warningString.Length > 4000)
|
||||
{
|
||||
warningString = warningString.Substring(0, 4000);
|
||||
}
|
||||
|
||||
await command.RespondAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Orange,
|
||||
Description = "Uploaded interview template.\n\n**Warnings:**\n```\n" + warningString + "\n```"
|
||||
}, true);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
MemoryStream memStream = new(Encoding.UTF8.GetBytes(Database.GetInterviewTemplateJSON(template.categoryID)));
|
||||
await LogChannel.Success(command.User.Mention + " uploaded a new interview template for the `" + category.Name + "` category.", 0,
|
||||
new Utilities.File("interview-template-" + template.categoryID + ".json", memStream));
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Logger.Error("Unable to log interview template upload.", e);
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Logger.Debug("Exception occured when trying to upload interview template:\n", e);
|
||||
await command.RespondAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Red,
|
||||
Description = "The uploaded JSON structure could not be parsed as an interview template.\n\nError message:\n```\n" + e.Message + "\n```",
|
||||
Footer = new DiscordEmbedBuilder.EmbedFooter
|
||||
{
|
||||
Text = "More detailed information may be available as debug messages in the bot logs."
|
||||
}
|
||||
}, true);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
[RequireGuild]
|
||||
[Command("delete")]
|
||||
[Description("Deletes the interview template for a category.")]
|
||||
public async Task Delete(SlashCommandContext command,
|
||||
[Parameter("category")][Description("The category to delete the template for.")] DiscordChannel category)
|
||||
{
|
||||
if (!category?.IsCategory ?? true)
|
||||
{
|
||||
await command.RespondAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Red,
|
||||
Description = "That channel is not a category."
|
||||
}, true);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!Database.TryGetInterviewTemplate(category.Id, out InterviewStep _))
|
||||
{
|
||||
await command.RespondAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Red,
|
||||
Description = "That category does not have an interview template."
|
||||
}, true);
|
||||
return;
|
||||
}
|
||||
|
||||
MemoryStream memStream = new(Encoding.UTF8.GetBytes(Database.GetInterviewTemplateJSON(category.Id)));
|
||||
if (!Database.TryDeleteInterviewTemplate(category.Id))
|
||||
{
|
||||
await command.RespondAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Red,
|
||||
Description = "A database error occured trying to delete the interview template."
|
||||
}, true);
|
||||
return;
|
||||
}
|
||||
|
||||
await command.RespondAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Green,
|
||||
Description = "Deleted interview template."
|
||||
}, true);
|
||||
|
||||
await LogChannel.Success(command.User.Mention + " deleted the interview template for the `" + category.Name + "` category.", 0,
|
||||
new Utilities.File("interview-template-" + category.Id + ".json", memStream));
|
||||
}
|
||||
}
|
67
Commands/ListAssignedCommand.cs
Normal file
67
Commands/ListAssignedCommand.cs
Normal file
|
@ -0,0 +1,67 @@
|
|||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.Threading.Tasks;
|
||||
using DSharpPlus.Commands;
|
||||
using DSharpPlus.Commands.ContextChecks;
|
||||
using DSharpPlus.Commands.Processors.SlashCommands;
|
||||
using DSharpPlus.Entities;
|
||||
using DSharpPlus.Interactivity;
|
||||
using DSharpPlus.Interactivity.Extensions;
|
||||
|
||||
namespace SupportChild.Commands;
|
||||
|
||||
public class ListAssignedCommand
|
||||
{
|
||||
[RequireGuild]
|
||||
[Command("listassigned")]
|
||||
[Description("Lists tickets assigned to a user.")]
|
||||
public async Task OnExecute(SlashCommandContext command,
|
||||
[Parameter("user")][Description("(Optional) User to list tickets for.")] DiscordUser user = null)
|
||||
{
|
||||
DiscordUser listUser = user == null ? command.User : user;
|
||||
|
||||
if (!Database.TryGetAssignedTickets(listUser.Id, out List<Database.Ticket> assignedTickets))
|
||||
{
|
||||
await command.RespondAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Red,
|
||||
Description = "User does not have any assigned tickets."
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
List<string> listItems = new List<string>();
|
||||
foreach (Database.Ticket ticket in assignedTickets)
|
||||
{
|
||||
listItems.Add("**" + ticket.DiscordRelativeTime() + ":** <#" + ticket.channelID + "> by <@" + ticket.creatorID + ">\n");
|
||||
}
|
||||
|
||||
List<DiscordEmbedBuilder> embeds = new List<DiscordEmbedBuilder>();
|
||||
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<Page> listPages = new List<Page>();
|
||||
foreach (DiscordEmbedBuilder embed in embeds)
|
||||
{
|
||||
listPages.Add(new Page("", embed));
|
||||
}
|
||||
|
||||
await command.Interaction.SendPaginatedResponseAsync(true, command.User, listPages);
|
||||
}
|
||||
}
|
103
Commands/ListCommand.cs
Normal file
103
Commands/ListCommand.cs
Normal file
|
@ -0,0 +1,103 @@
|
|||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.Threading.Tasks;
|
||||
using DSharpPlus.Commands;
|
||||
using DSharpPlus.Commands.ContextChecks;
|
||||
using DSharpPlus.Commands.Processors.SlashCommands;
|
||||
using DSharpPlus.Entities;
|
||||
using DSharpPlus.Interactivity;
|
||||
using DSharpPlus.Interactivity.Extensions;
|
||||
|
||||
namespace SupportChild.Commands;
|
||||
|
||||
public class ListCommand
|
||||
{
|
||||
[RequireGuild]
|
||||
[Command("list")]
|
||||
[Description("Lists tickets opened by a user.")]
|
||||
public async Task OnExecute(SlashCommandContext command,
|
||||
[Parameter("user")][Description("(Optional) The user whose tickets to get, yourself by default.")] DiscordUser user = null)
|
||||
{
|
||||
DiscordUser listUser = user == null ? command.User : user;
|
||||
|
||||
List<DiscordEmbedBuilder> openEmbeds = new List<DiscordEmbedBuilder>();
|
||||
if (Database.TryGetOpenTickets(listUser.Id, out List<Database.Ticket> openTickets))
|
||||
{
|
||||
List<string> listItems = new List<string>();
|
||||
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<DiscordEmbedBuilder> closedEmbeds = new List<DiscordEmbedBuilder>();
|
||||
if (Database.TryGetClosedTickets(listUser.Id, out List<Database.Ticket> closedTickets))
|
||||
{
|
||||
List<string> listItems = new List<string>();
|
||||
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<DiscordEmbedBuilder> embeds = new List<DiscordEmbedBuilder>();
|
||||
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.RespondAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Cyan,
|
||||
Description = "User does not have any open or closed tickets."
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
List<Page> listPages = new List<Page>();
|
||||
foreach (DiscordEmbedBuilder embed in embeds)
|
||||
{
|
||||
listPages.Add(new Page("", embed));
|
||||
}
|
||||
|
||||
await command.Interaction.SendPaginatedResponseAsync(true, command.User, listPages);
|
||||
}
|
||||
}
|
102
Commands/ListInvalidCommand.cs
Normal file
102
Commands/ListInvalidCommand.cs
Normal file
|
@ -0,0 +1,102 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using DSharpPlus.Commands;
|
||||
using DSharpPlus.Commands.ContextChecks;
|
||||
using DSharpPlus.Commands.Processors.SlashCommands;
|
||||
using DSharpPlus.Entities;
|
||||
using DSharpPlus.Exceptions;
|
||||
using DSharpPlus.Interactivity;
|
||||
using DSharpPlus.Interactivity.Extensions;
|
||||
|
||||
namespace SupportChild.Commands;
|
||||
|
||||
public class ListInvalidCommand
|
||||
{
|
||||
[RequireGuild]
|
||||
[Command("listinvalid")]
|
||||
[Description("List tickets which channels have been deleted. Use /admin unsetticket <id> to remove them.")]
|
||||
public async Task ListInvalid(SlashCommandContext command)
|
||||
{
|
||||
if (!Database.TryGetOpenTickets(out List<Database.Ticket> openTickets))
|
||||
{
|
||||
await command.RespondAsync(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<DiscordChannel> allChannels = new List<DiscordChannel>();
|
||||
foreach (KeyValuePair<ulong, DiscordGuild> guild in SupportChild.client.Guilds)
|
||||
{
|
||||
try
|
||||
{
|
||||
allChannels.AddRange(await guild.Value.GetChannelsAsync());
|
||||
}
|
||||
catch (Exception) { /*ignored*/ }
|
||||
}
|
||||
|
||||
// Check which tickets channels no longer exist
|
||||
List<string> invalidTickets = new List<string>();
|
||||
foreach (Database.Ticket ticket in openTickets)
|
||||
{
|
||||
DiscordChannel channel = allChannels.FirstOrDefault(c => c.Id == ticket.channelID);
|
||||
if (channel == null)
|
||||
{
|
||||
invalidTickets.Add("**`ticket-" + ticket.id.ToString("00000") + ":`** Channel no longer exists (<#" + ticket.channelID + ">)\n");
|
||||
continue;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
await channel.Guild.GetMemberAsync(ticket.creatorID);
|
||||
}
|
||||
catch (NotFoundException)
|
||||
{
|
||||
invalidTickets.Add("**`ticket-" + ticket.id.ToString("00000") + ":`** Creator has left (<#" + ticket.channelID + ">)\n");
|
||||
}
|
||||
}
|
||||
|
||||
if (invalidTickets.Count == 0)
|
||||
{
|
||||
await command.RespondAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Green,
|
||||
Description = "All tickets are valid!"
|
||||
}, true);
|
||||
return;
|
||||
}
|
||||
|
||||
List<DiscordEmbedBuilder> embeds = new List<DiscordEmbedBuilder>();
|
||||
foreach (string message in Utilities.ParseListIntoMessages(invalidTickets))
|
||||
{
|
||||
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<Page> listPages = new List<Page>();
|
||||
foreach (DiscordEmbedBuilder embed in embeds)
|
||||
{
|
||||
listPages.Add(new Page("", embed));
|
||||
}
|
||||
|
||||
await command.Interaction.SendPaginatedResponseAsync(true, command.User, listPages);
|
||||
}
|
||||
}
|
88
Commands/ListOpen.cs
Normal file
88
Commands/ListOpen.cs
Normal file
|
@ -0,0 +1,88 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using DSharpPlus.Commands;
|
||||
using DSharpPlus.Commands.ContextChecks;
|
||||
using DSharpPlus.Commands.Processors.SlashCommands;
|
||||
using DSharpPlus.Entities;
|
||||
using DSharpPlus.Exceptions;
|
||||
using DSharpPlus.Interactivity;
|
||||
using DSharpPlus.Interactivity.Extensions;
|
||||
|
||||
namespace SupportChild.Commands;
|
||||
|
||||
public class ListOpen
|
||||
{
|
||||
[RequireGuild]
|
||||
[Command("listopen")]
|
||||
[Description("Lists all open tickets, oldest first.")]
|
||||
public async Task OnExecute(SlashCommandContext command)
|
||||
{
|
||||
if (!Database.TryGetOpenTickets(out List<Database.Ticket> openTickets))
|
||||
{
|
||||
await command.RespondAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Red,
|
||||
Description = "Could not fetch any open tickets."
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// Get all channels in all guilds the bot is part of
|
||||
List<DiscordChannel> allChannels = new List<DiscordChannel>();
|
||||
foreach (KeyValuePair<ulong, DiscordGuild> guild in SupportChild.client.Guilds)
|
||||
{
|
||||
try
|
||||
{
|
||||
allChannels.AddRange(await guild.Value.GetChannelsAsync());
|
||||
}
|
||||
catch (Exception) { /*ignored*/ }
|
||||
}
|
||||
|
||||
List<string> listItems = new List<string>();
|
||||
foreach (Database.Ticket ticket in openTickets)
|
||||
{
|
||||
try
|
||||
{
|
||||
DiscordChannel channel = allChannels.FirstOrDefault(c => c.Id == ticket.channelID);
|
||||
if (channel != null)
|
||||
{
|
||||
if (command.Member!.PermissionsIn(channel).HasPermission(DiscordPermissions.AccessChannels))
|
||||
{
|
||||
listItems.Add("**" + ticket.DiscordRelativeTime() + ":** <#" + ticket.channelID + "> by <@" + ticket.creatorID + ">\n");
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (NotFoundException) { /*ignored*/ }
|
||||
}
|
||||
|
||||
List<DiscordEmbedBuilder> embeds = new List<DiscordEmbedBuilder>();
|
||||
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<Page> listPages = new List<Page>();
|
||||
foreach (DiscordEmbedBuilder embed in embeds)
|
||||
{
|
||||
listPages.Add(new Page("", embed));
|
||||
}
|
||||
|
||||
await command.Interaction.SendPaginatedResponseAsync(true, command.User, listPages);
|
||||
}
|
||||
}
|
89
Commands/ListUnassignedCommand.cs
Normal file
89
Commands/ListUnassignedCommand.cs
Normal file
|
@ -0,0 +1,89 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using DSharpPlus.Commands;
|
||||
using DSharpPlus.Commands.ContextChecks;
|
||||
using DSharpPlus.Commands.Processors.SlashCommands;
|
||||
using DSharpPlus.Entities;
|
||||
using DSharpPlus.Exceptions;
|
||||
using DSharpPlus.Interactivity;
|
||||
using DSharpPlus.Interactivity.Extensions;
|
||||
|
||||
namespace SupportChild.Commands;
|
||||
|
||||
public class ListUnassignedCommand
|
||||
{
|
||||
[RequireGuild]
|
||||
[Command("listunassigned")]
|
||||
[Description("Lists unassigned tickets.")]
|
||||
public async Task OnExecute(SlashCommandContext command)
|
||||
{
|
||||
if (!Database.TryGetAssignedTickets(0, out List<Database.Ticket> unassignedTickets))
|
||||
{
|
||||
await command.RespondAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Green,
|
||||
Description = "There are no unassigned tickets."
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// Get all channels in all guilds the bot is part of
|
||||
List<DiscordChannel> allChannels = new List<DiscordChannel>();
|
||||
foreach (KeyValuePair<ulong, DiscordGuild> guild in SupportChild.client.Guilds)
|
||||
{
|
||||
try
|
||||
{
|
||||
allChannels.AddRange(await guild.Value.GetChannelsAsync());
|
||||
}
|
||||
catch (Exception) { /*ignored*/ }
|
||||
}
|
||||
|
||||
List<string> listItems = new List<string>();
|
||||
foreach (Database.Ticket ticket in unassignedTickets)
|
||||
{
|
||||
try
|
||||
{
|
||||
DiscordChannel channel = allChannels.FirstOrDefault(c => c.Id == ticket.channelID);
|
||||
if (channel != null)
|
||||
{
|
||||
if (command.Member!.PermissionsIn(channel).HasPermission(DiscordPermissions.AccessChannels))
|
||||
{
|
||||
listItems.Add("**" + ticket.DiscordRelativeTime() + ":** <#" + ticket.channelID + "> by <@" + ticket.creatorID + ">\n");
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (NotFoundException) { /*ignored*/ }
|
||||
}
|
||||
|
||||
List<DiscordEmbedBuilder> embeds = new List<DiscordEmbedBuilder>();
|
||||
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<Page> listPages = new List<Page>();
|
||||
foreach (DiscordEmbedBuilder embed in embeds)
|
||||
{
|
||||
listPages.Add(new Page("", embed));
|
||||
}
|
||||
|
||||
await command.Interaction.SendPaginatedResponseAsync(true, command.User, listPages);
|
||||
}
|
||||
}
|
110
Commands/MoveCommand.cs
Normal file
110
Commands/MoveCommand.cs
Normal file
|
@ -0,0 +1,110 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using DSharpPlus.Commands;
|
||||
using DSharpPlus.Commands.ContextChecks;
|
||||
using DSharpPlus.Commands.Processors.SlashCommands;
|
||||
using DSharpPlus.Entities;
|
||||
using DSharpPlus.Exceptions;
|
||||
|
||||
namespace SupportChild.Commands;
|
||||
|
||||
public class MoveCommand
|
||||
{
|
||||
[RequireGuild]
|
||||
[Command("move")]
|
||||
[Description("Moves a ticket to another category.")]
|
||||
public async Task OnExecute(SlashCommandContext command,
|
||||
[Parameter("category")][Description("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 ticket))
|
||||
{
|
||||
await command.RespondAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Red,
|
||||
Description = "This channel is not a ticket."
|
||||
}, true);
|
||||
return;
|
||||
}
|
||||
|
||||
if (string.IsNullOrEmpty(category))
|
||||
{
|
||||
await command.RespondAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Red,
|
||||
Description = "Error: No category provided."
|
||||
}, true);
|
||||
return;
|
||||
}
|
||||
|
||||
IReadOnlyList<DiscordChannel> channels = await command.Guild.GetChannelsAsync();
|
||||
IEnumerable<DiscordChannel> categories = channels.Where(x => x.IsCategory);
|
||||
DiscordChannel categoryChannel = categories.FirstOrDefault(x => x.Name.StartsWith(category.Trim(), StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
if (categoryChannel == null)
|
||||
{
|
||||
await command.RespondAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Red,
|
||||
Description = "Error: Could not find a category by that name."
|
||||
}, true);
|
||||
return;
|
||||
}
|
||||
|
||||
if (command.Channel.Parent.Id == categoryChannel.Id)
|
||||
{
|
||||
await command.RespondAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Red,
|
||||
Description = "Error: The ticket is already in that category."
|
||||
}, true);
|
||||
return;
|
||||
}
|
||||
|
||||
if (categoryChannel.Children.Count == 50)
|
||||
{
|
||||
Logger.Warn("Could not move ticket " + ticket.id.ToString("00000") + " to the category '" + categoryChannel.Name + "', likely because it is full.");
|
||||
await command.RespondAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Red,
|
||||
Description = "Error: Unable to move ticket to that category, is it full?"
|
||||
}, true);
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
await command.Channel.ModifyAsync(modifiedAttributes => modifiedAttributes.Parent = categoryChannel);
|
||||
}
|
||||
catch (UnauthorizedException)
|
||||
{
|
||||
await command.RespondAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Red,
|
||||
Description = "Error: Not authorized to move this ticket to that category."
|
||||
}, true);
|
||||
return;
|
||||
}
|
||||
catch (BadRequestException)
|
||||
{
|
||||
Logger.Warn("Could not move ticket " + ticket.id.ToString("00000") + " to the category '" + categoryChannel.Name + "', likely because it is full.");
|
||||
await command.RespondAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Red,
|
||||
Description = "Error: Unable to move ticket to that category, is it full?"
|
||||
}, true);
|
||||
return;
|
||||
}
|
||||
|
||||
await command.RespondAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Green,
|
||||
Description = "Ticket was moved to `" + categoryChannel.Name + "`."
|
||||
});
|
||||
|
||||
await LogChannel.Success(command.User.Mention + " moved " + command.Channel.Mention + " to `" + categoryChannel.Name + "`.", ticket.id);
|
||||
}
|
||||
}
|
249
Commands/NewCommand.cs
Normal file
249
Commands/NewCommand.cs
Normal file
|
@ -0,0 +1,249 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using DSharpPlus.Commands;
|
||||
using DSharpPlus.Commands.ContextChecks;
|
||||
using DSharpPlus.Commands.Processors.SlashCommands;
|
||||
using DSharpPlus.Entities;
|
||||
using DSharpPlus.Exceptions;
|
||||
using SupportChild.Interviews;
|
||||
|
||||
namespace SupportChild.Commands;
|
||||
public class NewCommand
|
||||
{
|
||||
[RequireGuild]
|
||||
[Command("new")]
|
||||
[Description("Opens a new ticket.")]
|
||||
public async Task OnExecute(SlashCommandContext command)
|
||||
{
|
||||
List<Database.Category> verifiedCategories = await Utilities.GetVerifiedCategories();
|
||||
switch (verifiedCategories.Count)
|
||||
{
|
||||
case 0:
|
||||
await command.RespondAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Red,
|
||||
Description = "Error: No registered categories found."
|
||||
}, true);
|
||||
return;
|
||||
case 1:
|
||||
await command.DeferResponseAsync(true);
|
||||
(bool success, string message) = await OpenNewTicket(command.User.Id, command.Channel.Id, verifiedCategories[0].id);
|
||||
|
||||
if (success)
|
||||
{
|
||||
await command.FollowupAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Green,
|
||||
Description = message
|
||||
}, true);
|
||||
}
|
||||
else
|
||||
{
|
||||
await command.FollowupAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Red,
|
||||
Description = message
|
||||
}, true);
|
||||
}
|
||||
return;
|
||||
default:
|
||||
if (Config.newCommandUsesSelector)
|
||||
{
|
||||
await CreateSelector(command, verifiedCategories);
|
||||
}
|
||||
else
|
||||
{
|
||||
await CreateButtons(command, verifiedCategories);
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
public static async Task CreateButtons(SlashCommandContext command, List<Database.Category> verifiedCategories)
|
||||
{
|
||||
DiscordInteractionResponseBuilder builder = new DiscordInteractionResponseBuilder().WithContent(" ");
|
||||
|
||||
int nrOfButtons = 0;
|
||||
for (int nrOfButtonRows = 0; nrOfButtonRows < 5 && nrOfButtons < verifiedCategories.Count; nrOfButtonRows++)
|
||||
{
|
||||
List<DiscordButtonComponent> buttonRow = new List<DiscordButtonComponent>();
|
||||
|
||||
for (; nrOfButtons < 5 * (nrOfButtonRows + 1) && nrOfButtons < verifiedCategories.Count; nrOfButtons++)
|
||||
{
|
||||
buttonRow.Add(new DiscordButtonComponent(DiscordButtonStyle.Primary, "supportchild_newcommandbutton " + verifiedCategories[nrOfButtons].id, verifiedCategories[nrOfButtons].name));
|
||||
}
|
||||
builder.AddComponents(buttonRow);
|
||||
}
|
||||
|
||||
await command.RespondAsync(builder.AsEphemeral());
|
||||
}
|
||||
|
||||
public static async Task CreateSelector(SlashCommandContext command, List<Database.Category> verifiedCategories)
|
||||
{
|
||||
verifiedCategories = verifiedCategories.OrderBy(x => x.name).ToList();
|
||||
List<DiscordSelectComponent> selectionComponents = new List<DiscordSelectComponent>();
|
||||
|
||||
int selectionOptions = 0;
|
||||
for (int selectionBoxes = 0; selectionBoxes < 5 && selectionOptions < verifiedCategories.Count; selectionBoxes++)
|
||||
{
|
||||
List<DiscordSelectComponentOption> categoryOptions = new List<DiscordSelectComponentOption>();
|
||||
|
||||
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.RespondAsync(new DiscordInteractionResponseBuilder().AddComponents(selectionComponents).AsEphemeral());
|
||||
}
|
||||
|
||||
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<Database.Ticket> ownTickets)
|
||||
&& (ownTickets.Count >= Config.ticketLimit && Config.ticketLimit != 0))
|
||||
{
|
||||
return (false, "You have reached the limit for maximum open tickets.");
|
||||
}
|
||||
|
||||
DiscordChannel category = null;
|
||||
try
|
||||
{
|
||||
category = await SupportChild.client.GetChannelAsync(categoryID);
|
||||
}
|
||||
catch (Exception) { /*ignored*/ }
|
||||
|
||||
if (category == null)
|
||||
{
|
||||
return (false, "Error: Could not find the category to place the ticket in.");
|
||||
}
|
||||
|
||||
if (category.Children.Count == 50)
|
||||
{
|
||||
return (false, "This ticket category is full, can not create ticket channel.");
|
||||
}
|
||||
|
||||
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", DiscordChannelType.Text, category);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Logger.Error("Error occured while creating ticket.", e);
|
||||
}
|
||||
|
||||
if (ticketChannel == null)
|
||||
{
|
||||
return (false, "Error occured while creating ticket, " + member.Mention +
|
||||
"!\nIs the channel limit reached in the server or ticket category?");
|
||||
}
|
||||
|
||||
DiscordMember assignedStaff = null;
|
||||
if (Config.randomAssignment)
|
||||
{
|
||||
assignedStaff = await RandomAssignCommand.GetRandomVerifiedStaffMember(ticketChannel, userID, 0, null);
|
||||
}
|
||||
|
||||
long id = Database.NewTicket(member.Id, assignedStaff?.Id ?? 0, ticketChannel.Id);
|
||||
try
|
||||
{
|
||||
await ticketChannel.ModifyAsync(modifiedAttributes => modifiedAttributes.Name = "ticket-" + id.ToString("00000"));
|
||||
}
|
||||
catch (DiscordException e)
|
||||
{
|
||||
Logger.Error("Exception occurred trying to modify channel: " + e);
|
||||
Logger.Error("JsonMessage: " + e.JsonMessage);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
await ticketChannel.AddOverwriteAsync(member, DiscordPermissions.AccessChannels);
|
||||
}
|
||||
catch (DiscordException e)
|
||||
{
|
||||
Logger.Error("Exception occurred trying to add channel permissions: " + e);
|
||||
Logger.Error("JsonMessage: " + e.JsonMessage);
|
||||
}
|
||||
|
||||
DiscordMessage message = await ticketChannel.SendMessageAsync("Hello, " + member.Mention + "!\n" + Config.welcomeMessage);
|
||||
|
||||
if (Config.pinFirstMessage)
|
||||
{
|
||||
try
|
||||
{
|
||||
await message.PinAsync();
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Logger.Error("Exception occurred trying to pin message: ", e);
|
||||
}
|
||||
}
|
||||
|
||||
// Refreshes the channel as changes were made to it above
|
||||
ticketChannel = await SupportChild.client.GetChannelAsync(ticketChannel.Id);
|
||||
|
||||
if (Config.interviewsEnabled)
|
||||
{
|
||||
await Interviewer.StartInterview(ticketChannel);
|
||||
}
|
||||
|
||||
if (assignedStaff != null)
|
||||
{
|
||||
await ticketChannel.SendMessageAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Green,
|
||||
Description = "Ticket was randomly assigned to " + assignedStaff.Mention + "."
|
||||
});
|
||||
|
||||
if (Config.assignmentNotifications)
|
||||
{
|
||||
try
|
||||
{
|
||||
await assignedStaff.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("JsonMessage: " + e.JsonMessage);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
await LogChannel.Success("Ticket " + ticketChannel.Mention + " opened by " + member.Mention + ".", (uint)id);
|
||||
return (true, "Ticket opened, " + member.Mention + "!\n" + ticketChannel.Mention);
|
||||
}
|
||||
}
|
126
Commands/RandomAssignCommand.cs
Normal file
126
Commands/RandomAssignCommand.cs
Normal file
|
@ -0,0 +1,126 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using DSharpPlus.Commands;
|
||||
using DSharpPlus.Commands.ContextChecks;
|
||||
using DSharpPlus.Commands.Processors.SlashCommands;
|
||||
using DSharpPlus.Entities;
|
||||
using DSharpPlus.Exceptions;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace SupportChild.Commands;
|
||||
|
||||
public class RandomAssignCommand
|
||||
{
|
||||
[RequireGuild]
|
||||
[Command("rassign")]
|
||||
[Description("Randomly assigns a staff member to a ticket.")]
|
||||
public async Task OnExecute(SlashCommandContext command, [Parameter("role")][Description("(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.RespondAsync(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.Channel, ticket.creatorID, ticket.assignedStaffID, role);
|
||||
if (staffMember == null)
|
||||
{
|
||||
await command.RespondAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Red,
|
||||
Description = "Error: Could not find an applicable staff member with access to this channel."
|
||||
}, true);
|
||||
return;
|
||||
}
|
||||
|
||||
// Attempt to assign the staff member to the ticket
|
||||
if (!Database.AssignStaff(ticket, staffMember.Id))
|
||||
{
|
||||
await command.RespondAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Red,
|
||||
Description = "Error: Failed to assign " + staffMember.Mention + " to ticket."
|
||||
}, true);
|
||||
return;
|
||||
}
|
||||
|
||||
// Respond that the command was successful
|
||||
await command.RespondAsync(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) { /* ignore */ }
|
||||
}
|
||||
|
||||
await LogChannel.Success(staffMember.Mention + " was randomly assigned to " + command.Channel.Mention + " by " + command.User.Mention + ".", ticket.id);
|
||||
}
|
||||
|
||||
internal static async Task<DiscordMember> GetRandomVerifiedStaffMember(DiscordChannel channel, ulong creatorID, ulong currentStaffID, DiscordRole targetRole)
|
||||
{
|
||||
List<Database.StaffMember> staffMembers;
|
||||
ulong[] ignoredUserIDs = [creatorID, currentStaffID];
|
||||
|
||||
if (targetRole == null)
|
||||
{
|
||||
// No role was specified, any active staff will be picked
|
||||
staffMembers = Database.GetActiveStaff(ignoredUserIDs);
|
||||
}
|
||||
else
|
||||
{
|
||||
// Check if role rassign should override staff's active status
|
||||
staffMembers = Config.randomAssignRoleOverride
|
||||
? Database.GetAllStaff(ignoredUserIDs)
|
||||
: Database.GetActiveStaff(ignoredUserIDs);
|
||||
}
|
||||
|
||||
// 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 staffMember in staffMembers)
|
||||
{
|
||||
try
|
||||
{
|
||||
DiscordMember verifiedMember = await channel.Guild.GetMemberAsync(staffMember.userID);
|
||||
|
||||
// If a role is set filter to only members with that role
|
||||
if (targetRole == null || verifiedMember.Roles.Any(role => role.Id == targetRole.Id))
|
||||
{
|
||||
// Only assign staff members with access to this channel
|
||||
if (verifiedMember.PermissionsIn(channel).HasFlag(DiscordPermissions.AccessChannels))
|
||||
{
|
||||
return verifiedMember;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Logger.Error("Error occured trying to find a staff member for random assignment. User ID: " + staffMember.userID, e);
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
48
Commands/RemoveCategoryCommand.cs
Normal file
48
Commands/RemoveCategoryCommand.cs
Normal file
|
@ -0,0 +1,48 @@
|
|||
using System.ComponentModel;
|
||||
using System.Threading.Tasks;
|
||||
using DSharpPlus.Commands;
|
||||
using DSharpPlus.Commands.ContextChecks;
|
||||
using DSharpPlus.Commands.Processors.SlashCommands;
|
||||
using DSharpPlus.Entities;
|
||||
using DSharpPlus.Exceptions;
|
||||
|
||||
namespace SupportChild.Commands;
|
||||
|
||||
public class RemoveCategoryCommand
|
||||
{
|
||||
[RequireGuild]
|
||||
[Command("removecategory")]
|
||||
[Description("Removes the ability for users to open tickets in a specific category.")]
|
||||
public async Task OnExecute(SlashCommandContext command,
|
||||
[Parameter("category")][Description("The category to remove.")] DiscordChannel category)
|
||||
{
|
||||
if (!Database.TryGetCategory(category.Id, out Database.Category _))
|
||||
{
|
||||
await command.RespondAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Red,
|
||||
Description = "That category is not registered."
|
||||
}, true);
|
||||
return;
|
||||
}
|
||||
|
||||
if (Database.RemoveCategory(category.Id))
|
||||
{
|
||||
await command.RespondAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Green,
|
||||
Description = "Category removed."
|
||||
}, true);
|
||||
}
|
||||
else
|
||||
{
|
||||
await command.RespondAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Red,
|
||||
Description = "Error: Failed removing the category from the database."
|
||||
}, true);
|
||||
}
|
||||
|
||||
await LogChannel.Success("`" + category.Name + "` was removed by " + command.User.Mention + ".");
|
||||
}
|
||||
}
|
49
Commands/RemoveMessageCommand.cs
Normal file
49
Commands/RemoveMessageCommand.cs
Normal file
|
@ -0,0 +1,49 @@
|
|||
using System.ComponentModel;
|
||||
using System.Globalization;
|
||||
using DSharpPlus.Entities;
|
||||
using System.Threading.Tasks;
|
||||
using DSharpPlus.Commands;
|
||||
using DSharpPlus.Commands.ContextChecks;
|
||||
using DSharpPlus.Commands.Processors.SlashCommands;
|
||||
using DSharpPlus.Exceptions;
|
||||
|
||||
namespace SupportChild.Commands;
|
||||
|
||||
public class RemoveMessageCommand
|
||||
{
|
||||
[RequireGuild]
|
||||
[Command("removemessage")]
|
||||
[Description("Removes a message from the 'say' command.")]
|
||||
public async Task OnExecute(SlashCommandContext command,
|
||||
[Parameter("identifier")][Description("The identifier word used in the /say command.")] string identifier)
|
||||
{
|
||||
if (!Database.TryGetMessage(identifier.ToLower(CultureInfo.InvariantCulture), out Database.Message _))
|
||||
{
|
||||
await command.RespondAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Red,
|
||||
Description = "There is no message with that identifier."
|
||||
}, true);
|
||||
return;
|
||||
}
|
||||
|
||||
if (Database.RemoveMessage(identifier))
|
||||
{
|
||||
await command.RespondAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Green,
|
||||
Description = "Message removed."
|
||||
}, true);
|
||||
}
|
||||
else
|
||||
{
|
||||
await command.RespondAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Red,
|
||||
Description = "Error: Failed removing the message from the database."
|
||||
}, true);
|
||||
}
|
||||
|
||||
await LogChannel.Success("`" + identifier + "` was removed from the /say command by " + command.User.Mention + ".");
|
||||
}
|
||||
}
|
71
Commands/RemoveStaffCommand.cs
Normal file
71
Commands/RemoveStaffCommand.cs
Normal file
|
@ -0,0 +1,71 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.Threading.Tasks;
|
||||
using DSharpPlus.Commands;
|
||||
using DSharpPlus.Commands.ContextChecks;
|
||||
using DSharpPlus.Commands.Processors.SlashCommands;
|
||||
using DSharpPlus.Entities;
|
||||
using MySqlConnector;
|
||||
|
||||
namespace SupportChild.Commands;
|
||||
|
||||
public class RemoveStaffCommand
|
||||
{
|
||||
[RequireGuild]
|
||||
[Command("removestaff")]
|
||||
[Description("Removes a staff member.")]
|
||||
public async Task OnExecute(SlashCommandContext command,
|
||||
[Parameter("user")][Description("User to remove from staff.")] DiscordUser user)
|
||||
{
|
||||
if (!Database.IsStaff(user.Id))
|
||||
{
|
||||
await command.RespondAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Red,
|
||||
Description = "User is already not registered as staff."
|
||||
}, true);
|
||||
return;
|
||||
}
|
||||
|
||||
await command.DeferResponseAsync(true);
|
||||
|
||||
if (Database.TryGetAssignedTickets(user.Id, out List<Database.Ticket> assignedTickets))
|
||||
{
|
||||
foreach (Database.Ticket assignedTicket in assignedTickets)
|
||||
{
|
||||
Database.UnassignStaff(assignedTicket);
|
||||
try
|
||||
{
|
||||
DiscordChannel ticketChannel = await SupportChild.client.GetChannelAsync(assignedTicket.channelID);
|
||||
await ticketChannel.SendMessageAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Green,
|
||||
Description = "Unassigned <@" + assignedTicket.assignedStaffID + "> from ticket."
|
||||
});
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Logger.Error("Error when trying to send message about unassigning staff member from ticket-" + assignedTicket.id.ToString("00000"), e);
|
||||
}
|
||||
|
||||
await LogChannel.Success("<@" + assignedTicket.assignedStaffID + "> was unassigned from <#" + assignedTicket.channelID + "> by " + command.User.Mention + ".", assignedTicket.id);
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
await deletion.PrepareAsync();
|
||||
deletion.ExecuteNonQuery();
|
||||
|
||||
await command.RespondAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Green,
|
||||
Description = "User was removed from staff."
|
||||
}, true);
|
||||
|
||||
await LogChannel.Success(user.Mention + " was removed from staff by " + command.User.Mention + ".");
|
||||
}
|
||||
}
|
97
Commands/SayCommand.cs
Normal file
97
Commands/SayCommand.cs
Normal file
|
@ -0,0 +1,97 @@
|
|||
using DSharpPlus.Entities;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.Globalization;
|
||||
using System.Threading.Tasks;
|
||||
using DSharpPlus.Commands;
|
||||
using DSharpPlus.Commands.ContextChecks;
|
||||
using DSharpPlus.Commands.Processors.SlashCommands;
|
||||
using DSharpPlus.Exceptions;
|
||||
using DSharpPlus.Interactivity;
|
||||
using DSharpPlus.Interactivity.Extensions;
|
||||
|
||||
namespace SupportChild.Commands;
|
||||
|
||||
public class SayCommand
|
||||
{
|
||||
[RequireGuild]
|
||||
[Command("say")]
|
||||
[Description("Prints a message with information from staff. Use without identifier to list all identifiers.")]
|
||||
public async Task OnExecute(SlashCommandContext command,
|
||||
[Parameter("Identifier")][Description("(Optional) The identifier word to summon a message.")] string identifier = null)
|
||||
{
|
||||
// Print list of all messages if no identifier is provided
|
||||
if (identifier == null)
|
||||
{
|
||||
await SendMessageList(command);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!Database.TryGetMessage(identifier.ToLower(CultureInfo.InvariantCulture),
|
||||
out Database.Message message))
|
||||
{
|
||||
await command.RespondAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Red,
|
||||
Description = "There is no message with that identifier."
|
||||
}, true);
|
||||
return;
|
||||
}
|
||||
|
||||
await command.RespondAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Cyan,
|
||||
Description = message.message.Replace("\\n", "\n")
|
||||
});
|
||||
|
||||
await LogChannel.Success(command.User.Mention + " posted the " + message.identifier + " message in " + command.Channel.Mention + ".");
|
||||
}
|
||||
|
||||
private static async Task SendMessageList(SlashCommandContext command)
|
||||
{
|
||||
List<Database.Message> messages = Database.GetAllMessages();
|
||||
if (messages.Count == 0)
|
||||
{
|
||||
await command.RespondAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Red,
|
||||
Description = "There are no messages registered."
|
||||
}, true);
|
||||
return;
|
||||
}
|
||||
|
||||
List<string> listItems = [];
|
||||
foreach (Database.Message message in messages)
|
||||
{
|
||||
listItems.Add("**" + message.identifier + "** Added by <@" + message.userID + ">\n");
|
||||
}
|
||||
|
||||
List<DiscordEmbedBuilder> 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<Page> listPages = [];
|
||||
foreach (DiscordEmbedBuilder embed in embeds)
|
||||
{
|
||||
listPages.Add(new Page("", embed));
|
||||
}
|
||||
|
||||
await command.Interaction.SendPaginatedResponseAsync(true, command.User, listPages);
|
||||
}
|
||||
}
|
48
Commands/SetSummaryCommand.cs
Normal file
48
Commands/SetSummaryCommand.cs
Normal file
|
@ -0,0 +1,48 @@
|
|||
using System.ComponentModel;
|
||||
using System.Threading.Tasks;
|
||||
using DSharpPlus.Commands;
|
||||
using DSharpPlus.Commands.ContextChecks;
|
||||
using DSharpPlus.Commands.Processors.SlashCommands;
|
||||
using DSharpPlus.Entities;
|
||||
using DSharpPlus.Exceptions;
|
||||
using MySqlConnector;
|
||||
|
||||
namespace SupportChild.Commands;
|
||||
|
||||
public class SetSummaryCommand
|
||||
{
|
||||
[RequireGuild]
|
||||
[Command("setsummary")]
|
||||
[Description("Sets a ticket's summary for the summary command.")]
|
||||
public async Task OnExecute(SlashCommandContext command, [Parameter("Summary")][Description("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 ticket))
|
||||
{
|
||||
await command.RespondAsync(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);
|
||||
await update.PrepareAsync();
|
||||
update.ExecuteNonQuery();
|
||||
update.Dispose();
|
||||
|
||||
await command.RespondAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Green,
|
||||
Description = "Summary set."
|
||||
}, true);
|
||||
|
||||
await LogChannel.Success(command.User.Mention + " set the summary for " + command.Channel.Mention + " to:\n\n" + summary, ticket.id);
|
||||
}
|
||||
}
|
31
Commands/StatusCommand.cs
Normal file
31
Commands/StatusCommand.cs
Normal file
|
@ -0,0 +1,31 @@
|
|||
using System.ComponentModel;
|
||||
using System.Threading.Tasks;
|
||||
using DSharpPlus.Commands;
|
||||
using DSharpPlus.Commands.ContextChecks;
|
||||
using DSharpPlus.Commands.Processors.SlashCommands;
|
||||
using DSharpPlus.Entities;
|
||||
|
||||
namespace SupportChild.Commands;
|
||||
|
||||
public class StatusCommand
|
||||
{
|
||||
[RequireGuild]
|
||||
[Command("status")]
|
||||
[Description("Shows bot status and information.")]
|
||||
public async Task OnExecute(SlashCommandContext 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/src/branch/main/docs/Commands.md)", true);
|
||||
await command.RespondAsync(botInfo);
|
||||
}
|
||||
}
|
37
Commands/SummaryCommand.cs
Normal file
37
Commands/SummaryCommand.cs
Normal file
|
@ -0,0 +1,37 @@
|
|||
using System.ComponentModel;
|
||||
using System.Threading.Tasks;
|
||||
using DSharpPlus.Commands;
|
||||
using DSharpPlus.Commands.ContextChecks;
|
||||
using DSharpPlus.Commands.Processors.SlashCommands;
|
||||
using DSharpPlus.Entities;
|
||||
|
||||
namespace SupportChild.Commands;
|
||||
|
||||
public class SummaryCommand
|
||||
{
|
||||
[RequireGuild]
|
||||
[Command("summary")]
|
||||
[Description("Shows ticket information and summary if there is one.")]
|
||||
public async Task OnExecute(SlashCommandContext command)
|
||||
{
|
||||
if (!Database.TryGetOpenTicket(command.Channel.Id, out Database.Ticket ticket))
|
||||
{
|
||||
await command.RespondAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Red,
|
||||
Description = "This channel is not a ticket."
|
||||
}, true);
|
||||
return;
|
||||
}
|
||||
|
||||
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.RespondAsync(channelInfo);
|
||||
}
|
||||
}
|
70
Commands/ToggleActiveCommand.cs
Normal file
70
Commands/ToggleActiveCommand.cs
Normal file
|
@ -0,0 +1,70 @@
|
|||
using System.ComponentModel;
|
||||
using System.Threading.Tasks;
|
||||
using DSharpPlus.Commands;
|
||||
using DSharpPlus.Commands.ContextChecks;
|
||||
using DSharpPlus.Commands.Processors.SlashCommands;
|
||||
using DSharpPlus.Entities;
|
||||
using DSharpPlus.Exceptions;
|
||||
|
||||
namespace SupportChild.Commands;
|
||||
|
||||
public class ToggleActiveCommand
|
||||
{
|
||||
[RequireGuild]
|
||||
[Command("toggleactive")]
|
||||
[Description("Toggles active status for a staff member.")]
|
||||
public async Task OnExecute(SlashCommandContext command, [Parameter("user")][Description("(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.RespondAsync(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))
|
||||
{
|
||||
if (user != null && user.Id != command.User.Id)
|
||||
{
|
||||
await command.RespondAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Green,
|
||||
Description = staffUser.Mention + (staffMember.active ? " is now set as inactive and will no longer be randomly assigned any support tickets."
|
||||
: " is now set as active and will be randomly assigned support tickets again.")
|
||||
}, true);
|
||||
}
|
||||
else
|
||||
{
|
||||
await command.RespondAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Green,
|
||||
Description = staffMember.active ? "You are now set as inactive and will no longer be randomly assigned any support tickets."
|
||||
: "You are now set as active and will be randomly assigned support tickets again."
|
||||
}, true);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
await command.RespondAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Red,
|
||||
Description = "Error: Unable to update active status in database."
|
||||
}, true);
|
||||
}
|
||||
|
||||
if (user != null && user.Id != command.User.Id)
|
||||
{
|
||||
await LogChannel.Success(staffUser.Mention + " set " + command.Channel.Mention + "'s status to " + (staffMember.active ? "active" : "inactive"));
|
||||
}
|
||||
else
|
||||
{
|
||||
await LogChannel.Success(staffUser.Mention + " set their own status to " + (staffMember.active ? "active" : "inactive"));
|
||||
}
|
||||
}
|
||||
}
|
191
Commands/TranscriptCommand.cs
Normal file
191
Commands/TranscriptCommand.cs
Normal file
|
@ -0,0 +1,191 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.IO;
|
||||
using System.Threading.Tasks;
|
||||
using DSharpPlus.Commands;
|
||||
using DSharpPlus.Commands.ContextChecks;
|
||||
using DSharpPlus.Commands.Processors.SlashCommands;
|
||||
using DSharpPlus.Entities;
|
||||
using DSharpPlus.Exceptions;
|
||||
|
||||
namespace SupportChild.Commands;
|
||||
|
||||
public class TranscriptCommand
|
||||
{
|
||||
// TODO: Refactor the hell out of this
|
||||
[RequireGuild]
|
||||
[Command("transcript")]
|
||||
[Description("Creates a transcript of a ticket.")]
|
||||
public async Task OnExecute(SlashCommandContext command, [Parameter("ticket-id")][Description("(Optional) Ticket number to get transcript of.")] long ticketID = 0)
|
||||
{
|
||||
await command.DeferResponseAsync(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;
|
||||
}
|
||||
}
|
||||
|
||||
string fileName = Transcriber.GetZipFilename(ticket.id);
|
||||
string filePath = Transcriber.GetZipPath(ticket.id);
|
||||
long zipSize = 0;
|
||||
|
||||
// If the zip transcript doesn't exist, use the html file.
|
||||
try
|
||||
{
|
||||
FileInfo fileInfo = new FileInfo(filePath);
|
||||
if (!fileInfo.Exists || fileInfo.Length >= 26214400)
|
||||
{
|
||||
fileName = Transcriber.GetHTMLFilename(ticket.id);
|
||||
filePath = Transcriber.GetHtmlPath(ticket.id);
|
||||
}
|
||||
zipSize = fileInfo.Length;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
await command.EditResponseAsync(new DiscordWebhookBuilder().AddEmbed(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Red,
|
||||
Description = "ERROR: Could not find transcript file. Aborting..."
|
||||
}));
|
||||
Logger.Error("Failed to access transcript file:", e);
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if the chosen file path works.
|
||||
if (!File.Exists(filePath))
|
||||
{
|
||||
await command.EditResponseAsync(new DiscordWebhookBuilder().AddEmbed(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Red,
|
||||
Description = "ERROR: Could not find transcript file. Aborting..."
|
||||
}));
|
||||
Logger.Error("Transcript file does not exist: \"" + filePath + "\"");
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
await using FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read);
|
||||
await LogChannel.Success("Transcript generated by " + command.User.Mention + ".", ticket.id, new Utilities.File(fileName, file));
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Logger.Error("Failed to log transcript generation.", e);
|
||||
}
|
||||
|
||||
if (await SendDirectMessage(command, fileName, filePath, zipSize, ticket.id))
|
||||
{
|
||||
await command.EditResponseAsync(new DiscordWebhookBuilder().AddEmbed(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Green,
|
||||
Description = "Transcript sent!\n"
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task<bool> SendDirectMessage(SlashCommandContext command, string fileName, string filePath, long zipSize, uint ticketID)
|
||||
{
|
||||
try
|
||||
{
|
||||
// Send transcript in a direct message
|
||||
await using FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read);
|
||||
|
||||
DiscordMessageBuilder directMessage = new DiscordMessageBuilder();
|
||||
|
||||
if (zipSize >= 26214400)
|
||||
{
|
||||
directMessage.AddEmbed(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Orange,
|
||||
Description = "Transcript generated.\n\nThe zip file is too large, sending only the HTML file. Ask an administrator for the zip if you need it.",
|
||||
Footer = new DiscordEmbedBuilder.EmbedFooter
|
||||
{
|
||||
Text = "Ticket: " + ticketID.ToString("00000")
|
||||
}
|
||||
});
|
||||
}
|
||||
else
|
||||
{
|
||||
directMessage.AddEmbed(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Green,
|
||||
Description = "Transcript generated!\n",
|
||||
Footer = new DiscordEmbedBuilder.EmbedFooter
|
||||
{
|
||||
Text = "Ticket: " + ticketID.ToString("00000")
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
directMessage.AddFiles(new Dictionary<string, Stream> { { fileName, file } });
|
||||
|
||||
await command.Member.SendMessageAsync(directMessage);
|
||||
return true;
|
||||
}
|
||||
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 false;
|
||||
}
|
||||
}
|
||||
}
|
47
Commands/UnassignCommand.cs
Normal file
47
Commands/UnassignCommand.cs
Normal file
|
@ -0,0 +1,47 @@
|
|||
using System.ComponentModel;
|
||||
using System.Threading.Tasks;
|
||||
using DSharpPlus.Commands;
|
||||
using DSharpPlus.Commands.ContextChecks;
|
||||
using DSharpPlus.Commands.Processors.SlashCommands;
|
||||
using DSharpPlus.Entities;
|
||||
using DSharpPlus.Exceptions;
|
||||
|
||||
namespace SupportChild.Commands;
|
||||
|
||||
public class UnassignCommand
|
||||
{
|
||||
[RequireGuild]
|
||||
[Command("unassign")]
|
||||
[Description("Unassigns a staff member from a ticket.")]
|
||||
public async Task OnExecute(SlashCommandContext command)
|
||||
{
|
||||
// Check if ticket exists in the database
|
||||
if (!Database.TryGetOpenTicket(command.Channel.Id, out Database.Ticket ticket))
|
||||
{
|
||||
await command.RespondAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Red,
|
||||
Description = "This channel is not a ticket."
|
||||
}, true);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!Database.UnassignStaff(ticket))
|
||||
{
|
||||
await command.RespondAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Red,
|
||||
Description = "Error: Failed to unassign staff member from ticket."
|
||||
}, true);
|
||||
return;
|
||||
}
|
||||
|
||||
await command.RespondAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Green,
|
||||
Description = "Unassigned <@" + ticket.assignedStaffID + "> from ticket."
|
||||
});
|
||||
|
||||
await LogChannel.Success("<@" + ticket.assignedStaffID + "> was unassigned from <#" + ticket.channelID + "> by " + command.User.Mention + ".", ticket.id);
|
||||
}
|
||||
}
|
49
Commands/UnblacklistCommand.cs
Normal file
49
Commands/UnblacklistCommand.cs
Normal file
|
@ -0,0 +1,49 @@
|
|||
using System;
|
||||
using System.ComponentModel;
|
||||
using System.Threading.Tasks;
|
||||
using DSharpPlus.Commands;
|
||||
using DSharpPlus.Commands.ContextChecks;
|
||||
using DSharpPlus.Commands.Processors.SlashCommands;
|
||||
using DSharpPlus.Entities;
|
||||
using DSharpPlus.Exceptions;
|
||||
|
||||
namespace SupportChild.Commands;
|
||||
|
||||
public class UnblacklistCommand
|
||||
{
|
||||
[RequireGuild]
|
||||
[Command("unblacklist")]
|
||||
[Description("Unblacklists a user from opening tickets.")]
|
||||
public async Task OnExecute(SlashCommandContext command, [Parameter("user")][Description("User to remove from blacklist.")] DiscordUser user)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!Database.Unblacklist(user.Id))
|
||||
{
|
||||
await command.RespondAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Red,
|
||||
Description = user.Mention + " is not blacklisted."
|
||||
}, true);
|
||||
return;
|
||||
}
|
||||
|
||||
await command.RespondAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Green,
|
||||
Description = "Unblocked " + user.Mention + " from opening new tickets."
|
||||
}, true);
|
||||
|
||||
await LogChannel.Success(user.Mention + " was unblocked from opening tickets by " + command.User.Mention + ".");
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
await command.RespondAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Red,
|
||||
Description = "Error occured while removing " + user.Mention + " from blacklist."
|
||||
}, true);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
113
Config.cs
Normal file
113
Config.cs
Normal file
|
@ -0,0 +1,113 @@
|
|||
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 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 pinFirstMessage = false;
|
||||
internal static string transcriptDir = "";
|
||||
|
||||
internal static bool ticketUpdatedNotifications = false;
|
||||
internal static double ticketUpdatedNotificationDelay = 0.0;
|
||||
internal static bool assignmentNotifications = false;
|
||||
internal static bool closingNotifications = false;
|
||||
|
||||
internal static bool interviewsEnabled = false;
|
||||
internal static bool deleteMessagesAfterSummary = false;
|
||||
internal static bool deleteMessagesAfterNoSummary = 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<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 = LogLevel.Information;
|
||||
Logger.Warn("Log level '" + stringLogLevel + "' is invalid, using 'Information' instead.");
|
||||
}
|
||||
Logger.SetLogLevel(logLevel);
|
||||
|
||||
string stringTimestampFormat = json.SelectToken("bot.timestamp-format")?.Value<string>() ?? "RelativeTime";
|
||||
if (!Enum.TryParse(stringTimestampFormat, true, out timestampFormat))
|
||||
{
|
||||
timestampFormat = TimestampFormat.RelativeTime;
|
||||
Logger.Warn("Timestamp '" + stringTimestampFormat + "' is 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;
|
||||
pinFirstMessage = json.SelectToken("bot.pin-first-message")?.Value<bool>() ?? false;
|
||||
transcriptDir = json.SelectToken("bot.transcript-dir")?.Value<string>() ?? "";
|
||||
|
||||
ticketUpdatedNotifications = json.SelectToken("notifications.ticket-updated")?.Value<bool>() ?? false;
|
||||
ticketUpdatedNotificationDelay = json.SelectToken("notifications.ticket-updated-delay")?.Value<double>() ?? 0.0;
|
||||
assignmentNotifications = json.SelectToken("notifications.assignment")?.Value<bool>() ?? false;
|
||||
closingNotifications = json.SelectToken("notifications.closing")?.Value<bool>() ?? false;
|
||||
|
||||
interviewsEnabled = json.SelectToken("interviews.enabled")?.Value<bool>() ?? false;
|
||||
deleteMessagesAfterSummary = json.SelectToken("interviews.delete-messages-after-summary")?.Value<bool>() ?? false;
|
||||
deleteMessagesAfterNoSummary = json.SelectToken("interviews.delete-messages-after-no-summary")?.Value<bool>() ?? false;
|
||||
|
||||
// Reads database info
|
||||
hostName = json.SelectToken("database.address")?.Value<string>() ?? "";
|
||||
port = json.SelectToken("database.port")?.Value<int>() ?? 3306;
|
||||
database = json.SelectToken("database.name")?.Value<string>() ?? "supportchild";
|
||||
username = json.SelectToken("database.user")?.Value<string>() ?? "supportchild";
|
||||
password = json.SelectToken("database.password")?.Value<string>() ?? "";
|
||||
}
|
||||
}
|
974
Database.cs
Normal file
974
Database.cs
Normal file
|
@ -0,0 +1,974 @@
|
|||
using System;
|
||||
using System.Linq;
|
||||
using System.Collections.Generic;
|
||||
using System.Security.Cryptography;
|
||||
using DSharpPlus;
|
||||
using MySqlConnector;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Serialization;
|
||||
using SupportChild.Interviews;
|
||||
|
||||
namespace SupportChild;
|
||||
|
||||
public static class Database
|
||||
{
|
||||
private static string connectionString = "";
|
||||
|
||||
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);
|
||||
using MySqlCommand createInterviews = new MySqlCommand(
|
||||
"CREATE TABLE IF NOT EXISTS interviews(" +
|
||||
"channel_id BIGINT UNSIGNED NOT NULL PRIMARY KEY," +
|
||||
"interview JSON NOT NULL)",
|
||||
c);
|
||||
using MySqlCommand createInterviewTemplates = new MySqlCommand(
|
||||
"CREATE TABLE IF NOT EXISTS interview_templates(" +
|
||||
"category_id BIGINT UNSIGNED NOT NULL PRIMARY KEY," +
|
||||
"template JSON NOT NULL)",
|
||||
c);
|
||||
c.Open();
|
||||
createTickets.ExecuteNonQuery();
|
||||
createBlacklisted.ExecuteNonQuery();
|
||||
createTicketHistory.ExecuteNonQuery();
|
||||
createStaffList.ExecuteNonQuery();
|
||||
createMessages.ExecuteNonQuery();
|
||||
createCategories.ExecuteNonQuery();
|
||||
createInterviews.ExecuteNonQuery();
|
||||
createInterviewTemplates.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 List<StaffMember> GetActiveStaff(params ulong[] ignoredUserIDs)
|
||||
{
|
||||
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));
|
||||
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)
|
||||
{
|
||||
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));
|
||||
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 static string GetInterviewTemplateJSON(ulong categoryID)
|
||||
{
|
||||
using MySqlConnection c = GetConnection();
|
||||
c.Open();
|
||||
using MySqlCommand selection = new MySqlCommand("SELECT * FROM interview_templates WHERE category_id=@category_id", c);
|
||||
selection.Parameters.AddWithValue("@category_id", categoryID);
|
||||
selection.Prepare();
|
||||
MySqlDataReader results = selection.ExecuteReader();
|
||||
|
||||
// Return a default template if it doesn't exist.
|
||||
if (!results.Read())
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
string templates = results.GetString("template");
|
||||
results.Close();
|
||||
return templates;
|
||||
}
|
||||
|
||||
public static bool TryGetInterviewTemplate(ulong categoryID, out Interviews.InterviewStep template)
|
||||
{
|
||||
using MySqlConnection c = GetConnection();
|
||||
c.Open();
|
||||
using MySqlCommand selection = new MySqlCommand("SELECT * FROM interview_templates WHERE category_id=@category_id", c);
|
||||
selection.Parameters.AddWithValue("@category_id", categoryID);
|
||||
selection.Prepare();
|
||||
MySqlDataReader results = selection.ExecuteReader();
|
||||
|
||||
// Check if messages exist in the database
|
||||
if (!results.Read())
|
||||
{
|
||||
template = null;
|
||||
return false;
|
||||
}
|
||||
|
||||
string templateString = results.GetString("template");
|
||||
results.Close();
|
||||
|
||||
try
|
||||
{
|
||||
template = JsonConvert.DeserializeObject<Interviews.Template>(templateString, new JsonSerializerSettings
|
||||
{
|
||||
Error = delegate (object sender, ErrorEventArgs args)
|
||||
{
|
||||
Logger.Error("Error occured when trying to read interview template '" + categoryID + "' from database: " + args.ErrorContext.Error.Message);
|
||||
Logger.Debug("Detailed exception:", args.ErrorContext.Error);
|
||||
args.ErrorContext.Handled = false;
|
||||
}
|
||||
}).interview;
|
||||
return true;
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
template = null;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static bool SetInterviewTemplate(Interviews.Template template)
|
||||
{
|
||||
try
|
||||
{
|
||||
string templateString = JsonConvert.SerializeObject(template, new JsonSerializerSettings()
|
||||
{
|
||||
NullValueHandling = NullValueHandling.Ignore,
|
||||
MissingMemberHandling = MissingMemberHandling.Error,
|
||||
Formatting = Formatting.Indented,
|
||||
ContractResolver = new InterviewStep.StripInternalPropertiesResolver()
|
||||
});
|
||||
|
||||
string query;
|
||||
if (TryGetInterviewTemplate(template.categoryID, out _))
|
||||
{
|
||||
query = "UPDATE interview_templates SET template = @template WHERE category_id=@category_id";
|
||||
}
|
||||
else
|
||||
{
|
||||
query = "INSERT INTO interview_templates (category_id,template) VALUES (@category_id, @template)";
|
||||
}
|
||||
|
||||
using MySqlConnection c = GetConnection();
|
||||
c.Open();
|
||||
using MySqlCommand cmd = new MySqlCommand(query, c);
|
||||
cmd.Parameters.AddWithValue("@category_id", template.categoryID);
|
||||
cmd.Parameters.AddWithValue("@template", templateString);
|
||||
cmd.Prepare();
|
||||
return cmd.ExecuteNonQuery() > 0;
|
||||
}
|
||||
catch (MySqlException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static bool TryDeleteInterviewTemplate(ulong categoryID)
|
||||
{
|
||||
try
|
||||
{
|
||||
using MySqlConnection c = GetConnection();
|
||||
c.Open();
|
||||
using MySqlCommand deletion = new MySqlCommand(@"DELETE FROM interview_templates WHERE category_id=@category_id", c);
|
||||
deletion.Parameters.AddWithValue("@category_id", categoryID);
|
||||
deletion.Prepare();
|
||||
return deletion.ExecuteNonQuery() > 0;
|
||||
}
|
||||
catch (MySqlException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static bool SaveInterview(ulong channelID, Interviews.InterviewStep interview)
|
||||
{
|
||||
try
|
||||
{
|
||||
string query;
|
||||
if (TryGetInterview(channelID, out _))
|
||||
{
|
||||
query = "UPDATE interviews SET interview = @interview WHERE channel_id = @channel_id";
|
||||
}
|
||||
else
|
||||
{
|
||||
query = "INSERT INTO interviews (channel_id,interview) VALUES (@channel_id, @interview)";
|
||||
}
|
||||
|
||||
using MySqlConnection c = GetConnection();
|
||||
c.Open();
|
||||
using MySqlCommand cmd = new MySqlCommand(query, c);
|
||||
cmd.Parameters.AddWithValue("@channel_id", channelID);
|
||||
cmd.Parameters.AddWithValue("@interview", JsonConvert.SerializeObject(interview, Formatting.Indented));
|
||||
cmd.Prepare();
|
||||
return cmd.ExecuteNonQuery() > 0;
|
||||
}
|
||||
catch (MySqlException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static bool TryGetInterview(ulong channelID, out Interviews.InterviewStep interview)
|
||||
{
|
||||
using MySqlConnection c = GetConnection();
|
||||
c.Open();
|
||||
using MySqlCommand selection = new MySqlCommand(@"SELECT * FROM interviews 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())
|
||||
{
|
||||
interview = null;
|
||||
return false;
|
||||
}
|
||||
interview = JsonConvert.DeserializeObject<Interviews.InterviewStep>(results.GetString("interview"));
|
||||
results.Close();
|
||||
return true;
|
||||
}
|
||||
|
||||
public static bool TryDeleteInterview(ulong channelID)
|
||||
{
|
||||
try
|
||||
{
|
||||
using MySqlConnection c = GetConnection();
|
||||
c.Open();
|
||||
using MySqlCommand deletion = new MySqlCommand(@"DELETE FROM interviews WHERE channel_id=@channel_id", c);
|
||||
deletion.Parameters.AddWithValue("@channel_id", channelID);
|
||||
deletion.Prepare();
|
||||
return deletion.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");
|
||||
}
|
||||
}
|
||||
}
|
413
EventHandler.cs
Normal file
413
EventHandler.cs
Normal file
|
@ -0,0 +1,413 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using DiscordChatExporter.Core.Utils.Extensions;
|
||||
using DSharpPlus;
|
||||
using DSharpPlus.Commands;
|
||||
using DSharpPlus.Commands.ContextChecks;
|
||||
using DSharpPlus.Commands.EventArgs;
|
||||
using DSharpPlus.Commands.Exceptions;
|
||||
using DSharpPlus.Entities;
|
||||
using DSharpPlus.EventArgs;
|
||||
using DSharpPlus.Exceptions;
|
||||
using SupportChild.Commands;
|
||||
using SupportChild.Interviews;
|
||||
|
||||
namespace SupportChild;
|
||||
|
||||
public static class EventHandler
|
||||
{
|
||||
internal static bool hasLoggedGuilds = false;
|
||||
|
||||
public static Task OnReady(DiscordClient client, GuildDownloadCompletedEventArgs e)
|
||||
{
|
||||
Logger.Log("Connected to Discord.");
|
||||
|
||||
// Checking activity type
|
||||
if (!Enum.TryParse(Config.presenceType, true, out DiscordActivityType activityType))
|
||||
{
|
||||
Logger.Log("Presence type '" + Config.presenceType + "' invalid, using 'Playing' instead.");
|
||||
activityType = DiscordActivityType.Playing;
|
||||
}
|
||||
|
||||
client.UpdateStatusAsync(new DiscordActivity(Config.presenceText, activityType), DiscordUserStatus.Online);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public static async Task OnGuildAvailable(DiscordClient discordClient, GuildAvailableEventArgs e)
|
||||
{
|
||||
if (hasLoggedGuilds)
|
||||
{
|
||||
return;
|
||||
}
|
||||
hasLoggedGuilds = true;
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
IReadOnlyDictionary<ulong, DiscordRole> roles = e.Guild.Roles;
|
||||
|
||||
foreach ((ulong roleID, DiscordRole role) in roles)
|
||||
{
|
||||
Logger.Debug(role.Name.PadRight(40, '.') + roleID);
|
||||
}
|
||||
}
|
||||
|
||||
public static async Task OnMessageCreated(DiscordClient client, MessageCreatedEventArgs e)
|
||||
{
|
||||
if (e.Author.IsCurrent && e.Message.MessageType == DiscordMessageType.ChannelPinnedMessage)
|
||||
{
|
||||
await e.Message.DeleteAsync();
|
||||
}
|
||||
|
||||
if (e.Author.IsBot)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Ignore messages outside of tickets.
|
||||
if (!Database.TryGetOpenTicket(e.Channel.Id, out Database.Ticket ticket))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Send staff notification if applicable.
|
||||
if (Config.ticketUpdatedNotifications)
|
||||
{
|
||||
await SendTicketUpdatedMessage(e, ticket);
|
||||
}
|
||||
|
||||
// Try to process the message as an interview response if the ticket owner replied to this bot.
|
||||
if (ticket.creatorID == e.Author.Id && e.Message.ReferencedMessage?.Author == client.CurrentUser)
|
||||
{
|
||||
await Interviewer.ProcessResponseMessage(e.Message);
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task SendTicketUpdatedMessage(MessageCreatedEventArgs e, Database.Ticket ticket)
|
||||
{
|
||||
// Ignore staff messages
|
||||
if (Database.IsStaff(e.Author.Id))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Sends a DM to the assigned staff member if at least a day has gone by since the last message
|
||||
IReadOnlyList<DiscordMessage> messages = await e.Channel.GetMessagesAsync(2);
|
||||
if (messages.Count > 1 && messages[1].Timestamp < DateTimeOffset.UtcNow.AddDays(Config.ticketUpdatedNotificationDelay * -1))
|
||||
{
|
||||
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) { /* ignored */ }
|
||||
catch (UnauthorizedException) { /* ignored */ }
|
||||
}
|
||||
}
|
||||
|
||||
public static async Task OnMemberAdded(DiscordClient client, GuildMemberAddedEventArgs 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, DiscordPermissions.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("JsonMessage: " + ex.JsonMessage);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
catch (Exception) { /* ignored */ }
|
||||
}
|
||||
}
|
||||
|
||||
public static async Task OnMemberRemoved(DiscordClient client, GuildMemberRemovedEventArgs 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 (LogChannel.IsEnabled && Database.TryGetAssignedTickets(e.Member.Id, out List<Database.Ticket> assignedTickets))
|
||||
{
|
||||
foreach (Database.Ticket ticket in assignedTickets)
|
||||
{
|
||||
try
|
||||
{
|
||||
DiscordChannel channel = await client.GetChannelAsync(ticket.channelID);
|
||||
if (channel?.GuildId == e.Guild.Id)
|
||||
{
|
||||
await LogChannel.Warn("Assigned staff member '" + e.Member.Username + "#" + e.Member.Discriminator + "' has left the server: <#" + channel.Id + ">");
|
||||
}
|
||||
}
|
||||
catch (Exception) { /* ignored */ }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static async Task OnComponentInteractionCreated(DiscordClient client, ComponentInteractionCreatedEventArgs e)
|
||||
{
|
||||
try
|
||||
{
|
||||
switch (e.Interaction.Data.ComponentType)
|
||||
{
|
||||
case DiscordComponentType.Button:
|
||||
switch (e.Id)
|
||||
{
|
||||
case "supportchild_closeconfirm":
|
||||
await CloseCommand.OnConfirmed(e.Interaction);
|
||||
return;
|
||||
case not null when e.Id.StartsWith("supportchild_newcommandbutton"):
|
||||
await OnNewTicketSelectorUsed(e.Interaction);
|
||||
return;
|
||||
case not null when e.Id.StartsWith("supportchild_newticketbutton"):
|
||||
await OnNewTicketButtonUsed(e.Interaction);
|
||||
return;
|
||||
case not null when e.Id.StartsWith("supportchild_interviewbutton"):
|
||||
await Interviewer.ProcessButtonOrSelectorResponse(e.Interaction);
|
||||
return;
|
||||
case "right":
|
||||
case "left":
|
||||
case "rightskip":
|
||||
case "leftskip":
|
||||
case "stop":
|
||||
return;
|
||||
default:
|
||||
Logger.Warn("Unknown button press received! '" + e.Id + "'");
|
||||
return;
|
||||
}
|
||||
case DiscordComponentType.StringSelect:
|
||||
switch (e.Id)
|
||||
{
|
||||
case not null when e.Id.StartsWith("supportchild_newcommandselector"):
|
||||
await OnNewTicketSelectorUsed(e.Interaction);
|
||||
return;
|
||||
case not null when e.Id.StartsWith("supportchild_newticketselector"):
|
||||
await CreateSelectionBoxPanelCommand.OnSelectionMenuUsed(e.Interaction);
|
||||
return;
|
||||
case not null when e.Id.StartsWith("supportchild_interviewselector"):
|
||||
await Interviewer.ProcessButtonOrSelectorResponse(e.Interaction);
|
||||
return;
|
||||
default:
|
||||
Logger.Warn("Unknown selection box option received! '" + e.Id + "'");
|
||||
return;
|
||||
}
|
||||
case DiscordComponentType.ActionRow:
|
||||
Logger.Warn("Unknown action row received! '" + e.Id + "'");
|
||||
return;
|
||||
case DiscordComponentType.FormInput:
|
||||
Logger.Warn("Unknown form input received! '" + e.Id + "'");
|
||||
return;
|
||||
case DiscordComponentType.UserSelect:
|
||||
if (e.Id.StartsWith("supportchild_interviewuserselector"))
|
||||
{
|
||||
await Interviewer.ProcessButtonOrSelectorResponse(e.Interaction);
|
||||
return;
|
||||
}
|
||||
|
||||
Logger.Warn("Unknown selection box option received! '" + e.Id + "'");
|
||||
return;
|
||||
case DiscordComponentType.RoleSelect:
|
||||
if (e.Id.StartsWith("supportchild_interviewroleselector"))
|
||||
{
|
||||
await Interviewer.ProcessButtonOrSelectorResponse(e.Interaction);
|
||||
return;
|
||||
}
|
||||
|
||||
Logger.Warn("Unknown selection box option received! '" + e.Id + "'");
|
||||
return;
|
||||
case DiscordComponentType.MentionableSelect:
|
||||
if (e.Id.StartsWith("supportchild_interviewmentionableselector"))
|
||||
{
|
||||
await Interviewer.ProcessButtonOrSelectorResponse(e.Interaction);
|
||||
return;
|
||||
}
|
||||
|
||||
Logger.Warn("Unknown selection box option received! '" + e.Id + "'");
|
||||
return;
|
||||
case DiscordComponentType.ChannelSelect:
|
||||
if (e.Id.StartsWith("supportchild_interviewchannelselector"))
|
||||
{
|
||||
await Interviewer.ProcessButtonOrSelectorResponse(e.Interaction);
|
||||
return;
|
||||
}
|
||||
|
||||
Logger.Warn("Unknown selection box option 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("JsonMessage: " + ex.JsonMessage);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.Error("Interaction Exception occured: " + ex.GetType() + ": " + ex);
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task OnNewTicketButtonUsed(DiscordInteraction interaction)
|
||||
{
|
||||
await interaction.CreateResponseAsync(DiscordInteractionResponseType.DeferredChannelMessageWithSource, new DiscordInteractionResponseBuilder().AsEphemeral());
|
||||
|
||||
if (!ulong.TryParse(interaction.Data.CustomId.Replace("supportchild_newticketbutton ", ""), out ulong categoryID) || categoryID == 0)
|
||||
{
|
||||
Logger.Warn("Invalid ticket button 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
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task OnNewTicketSelectorUsed(DiscordInteraction interaction)
|
||||
{
|
||||
string stringID;
|
||||
switch (interaction.Data.ComponentType)
|
||||
{
|
||||
case DiscordComponentType.Button:
|
||||
stringID = interaction.Data.CustomId.Replace("supportchild_newcommandbutton ", "");
|
||||
break;
|
||||
case DiscordComponentType.StringSelect:
|
||||
if (interaction.Data.Values == null || interaction.Data.Values.Length <= 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
stringID = interaction.Data.Values[0];
|
||||
break;
|
||||
|
||||
case DiscordComponentType.ActionRow:
|
||||
case DiscordComponentType.FormInput:
|
||||
default:
|
||||
return;
|
||||
}
|
||||
|
||||
if (!ulong.TryParse(stringID, out ulong categoryID) || categoryID == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
await interaction.CreateResponseAsync(DiscordInteractionResponseType.DeferredMessageUpdate, new DiscordInteractionResponseBuilder().AsEphemeral());
|
||||
|
||||
(bool success, string message) = await NewCommand.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 OnCommandError(CommandsExtension commandSystem, CommandErroredEventArgs e)
|
||||
{
|
||||
switch (e.Exception)
|
||||
{
|
||||
case ChecksFailedException checksFailedException:
|
||||
{
|
||||
foreach (ContextCheckFailedData error in checksFailedException.Errors)
|
||||
{
|
||||
await e.Context.Channel.SendMessageAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Red,
|
||||
Description = error.ErrorMessage
|
||||
});
|
||||
}
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
336
Interviews/Interview.cs
Normal file
336
Interviews/Interview.cs
Normal file
|
@ -0,0 +1,336 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Specialized;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using DSharpPlus.Entities;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Converters;
|
||||
using Newtonsoft.Json.Serialization;
|
||||
|
||||
namespace SupportChild.Interviews;
|
||||
|
||||
public enum MessageType
|
||||
{
|
||||
// TODO: Support multiselector as separate type
|
||||
ERROR,
|
||||
END_WITH_SUMMARY,
|
||||
END_WITHOUT_SUMMARY,
|
||||
BUTTONS,
|
||||
TEXT_SELECTOR,
|
||||
USER_SELECTOR,
|
||||
ROLE_SELECTOR,
|
||||
MENTIONABLE_SELECTOR, // User or role
|
||||
CHANNEL_SELECTOR,
|
||||
TEXT_INPUT
|
||||
}
|
||||
|
||||
public enum ButtonType
|
||||
{
|
||||
PRIMARY,
|
||||
SECONDARY,
|
||||
SUCCESS,
|
||||
DANGER
|
||||
}
|
||||
|
||||
// A tree of steps representing an interview.
|
||||
// The tree is generated by the config file when a new ticket is opened or the restart interview command is used.
|
||||
// Additional components not specified in the config file are populated as the interview progresses.
|
||||
// The entire interview tree is serialized and stored in the database to record responses as they are made.
|
||||
public class InterviewStep
|
||||
{
|
||||
// Title of the message embed.
|
||||
[JsonProperty("heading")]
|
||||
public string heading;
|
||||
|
||||
// Message contents sent to the user.
|
||||
[JsonProperty("message")]
|
||||
public string message;
|
||||
|
||||
// The type of message.
|
||||
[JsonConverter(typeof(StringEnumConverter))]
|
||||
[JsonProperty("message-type")]
|
||||
public MessageType messageType;
|
||||
|
||||
// Colour of the message embed.
|
||||
[JsonProperty("color")]
|
||||
public string color;
|
||||
|
||||
// Used as label for this answer in the post-interview summary.
|
||||
[JsonProperty("summary-field")]
|
||||
public string summaryField;
|
||||
|
||||
// If this step is on a button, give it this style.
|
||||
[JsonConverter(typeof(StringEnumConverter))]
|
||||
[JsonProperty("button-style")]
|
||||
public ButtonType? buttonStyle;
|
||||
|
||||
// If this step is on a selector, give it this placeholder.
|
||||
[JsonProperty("selector-placeholder")]
|
||||
public string selectorPlaceholder;
|
||||
|
||||
// If this step is on a selector, give it this description.
|
||||
[JsonProperty("selector-description")]
|
||||
public string selectorDescription;
|
||||
|
||||
// The maximum length of a text input.
|
||||
[JsonProperty("max-length")]
|
||||
public int? maxLength;
|
||||
|
||||
// The minimum length of a text input.
|
||||
[JsonProperty("min-length")]
|
||||
public int? minLength;
|
||||
|
||||
// Possible questions to ask next, an error message, or the end of the interview.
|
||||
[JsonProperty("steps")]
|
||||
public Dictionary<string, InterviewStep> steps = new();
|
||||
|
||||
// ////////////////////////////////////////////////////////////////////////////
|
||||
// The following parameters are populated by the bot, not the json template. //
|
||||
// ////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
// The ID of this message where the bot asked this question.
|
||||
[JsonProperty("message-id")]
|
||||
public ulong messageID;
|
||||
|
||||
// The contents of the user's answer.
|
||||
[JsonProperty("answer")]
|
||||
public string answer;
|
||||
|
||||
// The ID of the user's answer message if this is a TEXT_INPUT type.
|
||||
[JsonProperty("answer-id")]
|
||||
public ulong answerID;
|
||||
|
||||
// Any extra messages generated by the bot that should be removed when the interview ends.
|
||||
[JsonProperty("related-message-ids")]
|
||||
public List<ulong> relatedMessageIDs;
|
||||
|
||||
public bool TryGetCurrentStep(out InterviewStep step)
|
||||
{
|
||||
// This object has not been initialized, we have checked too deep.
|
||||
if (messageID == 0)
|
||||
{
|
||||
step = null;
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check children.
|
||||
foreach (KeyValuePair<string, InterviewStep> childStep in steps)
|
||||
{
|
||||
// This child either is the one we are looking for or contains the one we are looking for.
|
||||
if (childStep.Value.TryGetCurrentStep(out step))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// This object is the deepest object with a message ID set, meaning it is the latest asked question.
|
||||
step = this;
|
||||
return true;
|
||||
}
|
||||
|
||||
public void GetSummary(ref OrderedDictionary summary)
|
||||
{
|
||||
if (messageID == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(summaryField))
|
||||
{
|
||||
summary.Add(summaryField, answer);
|
||||
}
|
||||
|
||||
// This will always contain exactly one or zero children.
|
||||
foreach (KeyValuePair<string, InterviewStep> step in steps)
|
||||
{
|
||||
step.Value.GetSummary(ref summary);
|
||||
}
|
||||
}
|
||||
|
||||
public void GetMessageIDs(ref List<ulong> messageIDs)
|
||||
{
|
||||
if (messageID != 0)
|
||||
{
|
||||
messageIDs.Add(messageID);
|
||||
}
|
||||
|
||||
if (answerID != 0)
|
||||
{
|
||||
messageIDs.Add(answerID);
|
||||
}
|
||||
|
||||
if (relatedMessageIDs != null)
|
||||
{
|
||||
messageIDs.AddRange(relatedMessageIDs);
|
||||
}
|
||||
|
||||
// This will always contain exactly one or zero children.
|
||||
foreach (KeyValuePair<string, InterviewStep> step in steps)
|
||||
{
|
||||
step.Value.GetMessageIDs(ref messageIDs);
|
||||
}
|
||||
}
|
||||
|
||||
public void AddRelatedMessageIDs(params ulong[] messageIDs)
|
||||
{
|
||||
if (relatedMessageIDs == null)
|
||||
{
|
||||
relatedMessageIDs = messageIDs.ToList();
|
||||
}
|
||||
else
|
||||
{
|
||||
relatedMessageIDs.AddRange(messageIDs);
|
||||
}
|
||||
}
|
||||
|
||||
public DiscordButtonStyle GetButtonStyle()
|
||||
{
|
||||
return buttonStyle switch
|
||||
{
|
||||
ButtonType.PRIMARY => DiscordButtonStyle.Primary,
|
||||
ButtonType.SECONDARY => DiscordButtonStyle.Secondary,
|
||||
ButtonType.SUCCESS => DiscordButtonStyle.Success,
|
||||
ButtonType.DANGER => DiscordButtonStyle.Danger,
|
||||
_ => DiscordButtonStyle.Secondary
|
||||
};
|
||||
}
|
||||
|
||||
public void Validate(ref List<string> errors,
|
||||
ref List<string> warnings,
|
||||
string stepID,
|
||||
int summaryFieldCount = 0,
|
||||
int summaryMaxLength = 0,
|
||||
InterviewStep parent = null)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(summaryField))
|
||||
{
|
||||
++summaryFieldCount;
|
||||
summaryMaxLength += summaryField.Length;
|
||||
switch (messageType)
|
||||
{
|
||||
case MessageType.BUTTONS:
|
||||
case MessageType.TEXT_SELECTOR:
|
||||
// Get the longest button/selector text
|
||||
if (steps.Count > 0)
|
||||
{
|
||||
summaryMaxLength += steps.Max(kv => kv.Key.Length);
|
||||
}
|
||||
break;
|
||||
case MessageType.USER_SELECTOR:
|
||||
case MessageType.ROLE_SELECTOR:
|
||||
case MessageType.MENTIONABLE_SELECTOR:
|
||||
case MessageType.CHANNEL_SELECTOR:
|
||||
// Approximate length of a mention
|
||||
summaryMaxLength += 23;
|
||||
break;
|
||||
case MessageType.TEXT_INPUT:
|
||||
summaryMaxLength += Math.Min(maxLength ?? 1024, 1024);
|
||||
break;
|
||||
case MessageType.END_WITH_SUMMARY:
|
||||
case MessageType.END_WITHOUT_SUMMARY:
|
||||
case MessageType.ERROR:
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (messageType is MessageType.ERROR or MessageType.END_WITH_SUMMARY or MessageType.END_WITHOUT_SUMMARY)
|
||||
{
|
||||
if (steps.Count > 0)
|
||||
{
|
||||
warnings.Add("Steps of the type '" + messageType + "' cannot have child steps.\n\n" + stepID + ".message-type");
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(summaryField))
|
||||
{
|
||||
warnings.Add("Steps of the type '" + messageType + "' cannot have summary field names.\n\n" + stepID + ".summary-field");
|
||||
}
|
||||
}
|
||||
else if (steps.Count == 0)
|
||||
{
|
||||
errors.Add("Steps of the type '" + messageType + "' must have at least one child step.\n\n" + stepID + ".message-type");
|
||||
}
|
||||
|
||||
if (messageType is MessageType.END_WITH_SUMMARY)
|
||||
{
|
||||
summaryMaxLength += message?.Length ?? 0;
|
||||
summaryMaxLength += heading?.Length ?? 0;
|
||||
if (summaryFieldCount > 25)
|
||||
{
|
||||
errors.Add("A summary cannot contain more than 25 fields, but you have " + summaryFieldCount + " fields in this branch.\n\n" + stepID);
|
||||
}
|
||||
else if (summaryMaxLength >= 6000)
|
||||
{
|
||||
warnings.Add("A summary cannot contain more than 6000 characters, but this branch may reach " + summaryMaxLength + " characters.\n" +
|
||||
"Use the \"max-length\" parameter to limit text input field lengths, or shorten other parts of the summary message.\n\n" + stepID);
|
||||
}
|
||||
}
|
||||
|
||||
if (parent?.messageType is not MessageType.BUTTONS && buttonStyle != null)
|
||||
{
|
||||
warnings.Add("Button styles have no effect on child steps of a '" + parent?.messageType + "' step.\n\n" + stepID + ".button-style");
|
||||
}
|
||||
|
||||
if (parent?.messageType is not MessageType.TEXT_SELECTOR && selectorDescription != null)
|
||||
{
|
||||
warnings.Add("Selector descriptions have no effect on child steps of a '" + parent?.messageType + "' step.\n\n" + stepID + ".selector-description");
|
||||
}
|
||||
|
||||
if (messageType is not MessageType.TEXT_SELECTOR && selectorPlaceholder != null)
|
||||
{
|
||||
warnings.Add("Selector placeholders have no effect on steps of the type '" + messageType + "'.\n\n" + stepID + ".selector-placeholder");
|
||||
}
|
||||
|
||||
if (messageType is not MessageType.TEXT_INPUT && maxLength != null)
|
||||
{
|
||||
warnings.Add("Max length has no effect on steps of the type '" + messageType + "'.\n\n" + stepID + ".max-length");
|
||||
}
|
||||
|
||||
if (messageType is not MessageType.TEXT_INPUT && minLength != null)
|
||||
{
|
||||
warnings.Add("Min length has no effect on steps of the type '" + messageType + "'.\n\n" + stepID + ".min-length");
|
||||
}
|
||||
|
||||
foreach (KeyValuePair<string, InterviewStep> step in steps)
|
||||
{
|
||||
// The JSON schema error messages use this format for the JSON path, so we use it here too.
|
||||
string nextStepID = stepID;
|
||||
nextStepID += step.Key.ContainsAny('.', ' ', '[', ']', '(', ')', '/', '\\')
|
||||
? ".steps['" + step.Key + "']"
|
||||
: ".steps." + step.Key;
|
||||
|
||||
step.Value.Validate(ref errors, ref warnings, nextStepID, summaryFieldCount, summaryMaxLength, this);
|
||||
}
|
||||
}
|
||||
|
||||
public class StripInternalPropertiesResolver : DefaultContractResolver
|
||||
{
|
||||
private static readonly HashSet<string> ignoreProps =
|
||||
[
|
||||
"message-id",
|
||||
"answer",
|
||||
"answer-id",
|
||||
"related-message-ids"
|
||||
];
|
||||
|
||||
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
|
||||
{
|
||||
JsonProperty property = base.CreateProperty(member, memberSerialization);
|
||||
if (ignoreProps.Contains(property.PropertyName))
|
||||
{
|
||||
property.ShouldSerialize = _ => false;
|
||||
}
|
||||
return property;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public class Template(ulong categoryID, InterviewStep interview)
|
||||
{
|
||||
[JsonProperty("category-id", Required = Required.Always)]
|
||||
public ulong categoryID = categoryID;
|
||||
|
||||
[JsonProperty("interview", Required = Required.Always)]
|
||||
public InterviewStep interview = interview;
|
||||
}
|
477
Interviews/Interviewer.cs
Normal file
477
Interviews/Interviewer.cs
Normal file
|
@ -0,0 +1,477 @@
|
|||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Specialized;
|
||||
using System.Linq;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Threading.Tasks;
|
||||
using DSharpPlus.Commands.Processors.SlashCommands;
|
||||
using DSharpPlus.Entities;
|
||||
|
||||
namespace SupportChild.Interviews;
|
||||
|
||||
public static class Interviewer
|
||||
{
|
||||
public static async Task<bool> StartInterview(DiscordChannel channel)
|
||||
{
|
||||
if (!Database.TryGetInterviewTemplate(channel.Parent.Id, out InterviewStep template))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
await SendNextMessage(channel, template);
|
||||
return Database.SaveInterview(channel.Id, template);
|
||||
}
|
||||
|
||||
public static async Task<bool> RestartInterview(DiscordChannel channel)
|
||||
{
|
||||
if (Database.TryGetInterview(channel.Id, out InterviewStep interviewRoot))
|
||||
{
|
||||
if (Config.deleteMessagesAfterNoSummary)
|
||||
{
|
||||
await DeletePreviousMessages(interviewRoot, channel);
|
||||
}
|
||||
|
||||
if (!Database.TryDeleteInterview(channel.Id))
|
||||
{
|
||||
Logger.Warn("Could not delete interview from database. Channel ID: " + channel.Id);
|
||||
}
|
||||
}
|
||||
|
||||
return await StartInterview(channel);
|
||||
}
|
||||
|
||||
public static async Task<bool> StopInterview(DiscordChannel channel)
|
||||
{
|
||||
if (Database.TryGetInterview(channel.Id, out InterviewStep interviewRoot))
|
||||
{
|
||||
if (Config.deleteMessagesAfterNoSummary)
|
||||
{
|
||||
await DeletePreviousMessages(interviewRoot, channel);
|
||||
}
|
||||
|
||||
if (!Database.TryDeleteInterview(channel.Id))
|
||||
{
|
||||
Logger.Warn("Could not delete interview from database. Channel ID: " + channel.Id);
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public static async Task ProcessButtonOrSelectorResponse(DiscordInteraction interaction)
|
||||
{
|
||||
if (interaction?.Channel == null || interaction?.Message == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Ignore if option was deselected.
|
||||
if (interaction.Data.ComponentType is not DiscordComponentType.Button && interaction.Data.Values.Length == 0)
|
||||
{
|
||||
await interaction.CreateResponseAsync(DiscordInteractionResponseType.UpdateMessage);
|
||||
return;
|
||||
}
|
||||
|
||||
// Return if there is no active interview in this channel
|
||||
if (!Database.TryGetInterview(interaction.Channel.Id, out InterviewStep interviewRoot))
|
||||
{
|
||||
await interaction.CreateResponseAsync(DiscordInteractionResponseType.ChannelMessageWithSource, new DiscordInteractionResponseBuilder()
|
||||
.AddEmbed(new DiscordEmbedBuilder()
|
||||
.WithColor(DiscordColor.Red)
|
||||
.WithDescription("Error: There is no active interview in this ticket, ask an admin to check the bot logs if this seems incorrect."))
|
||||
.AsEphemeral());
|
||||
return;
|
||||
}
|
||||
|
||||
// Return if the current question cannot be found in the interview.
|
||||
if (!interviewRoot.TryGetCurrentStep(out InterviewStep currentStep))
|
||||
{
|
||||
await interaction.CreateResponseAsync(DiscordInteractionResponseType.ChannelMessageWithSource, new DiscordInteractionResponseBuilder()
|
||||
.AddEmbed(new DiscordEmbedBuilder()
|
||||
.WithColor(DiscordColor.Red)
|
||||
.WithDescription("Error: Something seems to have broken in this interview, you may want to restart it."))
|
||||
.AsEphemeral());
|
||||
Logger.Error("The interview for channel " + interaction.Channel.Id + " exists but does not have a message ID set for it's root interview step");
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if this button/selector is for an older question.
|
||||
if (interaction.Message.Id != currentStep.messageID)
|
||||
{
|
||||
await interaction.CreateResponseAsync(DiscordInteractionResponseType.ChannelMessageWithSource, new DiscordInteractionResponseBuilder()
|
||||
.AddEmbed(new DiscordEmbedBuilder()
|
||||
.WithColor(DiscordColor.Red)
|
||||
.WithDescription("Error: You have already replied to this question, you have to reply to the latest one."))
|
||||
.AsEphemeral());
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
await interaction.CreateResponseAsync(DiscordInteractionResponseType.UpdateMessage);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Logger.Error("Could not update original message:", e);
|
||||
}
|
||||
|
||||
// Parse the response index from the button/selector.
|
||||
string componentID = "";
|
||||
string answer = "";
|
||||
|
||||
switch (interaction.Data.ComponentType)
|
||||
{
|
||||
case DiscordComponentType.UserSelect:
|
||||
case DiscordComponentType.RoleSelect:
|
||||
case DiscordComponentType.ChannelSelect:
|
||||
case DiscordComponentType.MentionableSelect:
|
||||
if (interaction.Data.Resolved?.Roles?.Any() ?? false)
|
||||
{
|
||||
answer = interaction.Data.Resolved.Roles.First().Value.Mention;
|
||||
}
|
||||
else if (interaction.Data.Resolved?.Users?.Any() ?? false)
|
||||
{
|
||||
answer = interaction.Data.Resolved.Users.First().Value.Mention;
|
||||
}
|
||||
else if (interaction.Data.Resolved?.Channels?.Any() ?? false)
|
||||
{
|
||||
answer = interaction.Data.Resolved.Channels.First().Value.Mention;
|
||||
}
|
||||
else if (interaction.Data.Resolved?.Messages?.Any() ?? false)
|
||||
{
|
||||
answer = interaction.Data.Resolved.Messages.First().Value.Id.ToString();
|
||||
}
|
||||
break;
|
||||
case DiscordComponentType.StringSelect:
|
||||
componentID = interaction.Data.Values[0];
|
||||
break;
|
||||
case DiscordComponentType.Button:
|
||||
componentID = interaction.Data.CustomId.Replace("supportchild_interviewbutton ", "");
|
||||
break;
|
||||
case DiscordComponentType.ActionRow:
|
||||
case DiscordComponentType.FormInput:
|
||||
default:
|
||||
throw new ArgumentOutOfRangeException("Tried to process an invalid component type: " + interaction.Data.ComponentType);
|
||||
}
|
||||
|
||||
// The different mentionable selectors provide the actual answer, while the others just return the ID.
|
||||
if (componentID == "")
|
||||
{
|
||||
foreach (KeyValuePair<string, InterviewStep> step in currentStep.steps)
|
||||
{
|
||||
// Skip to the first matching step.
|
||||
if (Regex.IsMatch(answer, step.Key))
|
||||
{
|
||||
await HandleAnswer(answer, step.Value, interviewRoot, currentStep, interaction.Channel);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
Logger.Error("The interview for channel " + interaction.Channel.Id + " reached a step of type " + currentStep.messageType + " which has no valid next step. Their selection was:\n" + answer);
|
||||
DiscordMessage followupMessage = await interaction.CreateFollowupMessageAsync(new DiscordFollowupMessageBuilder().AddEmbed(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Red,
|
||||
Description = "Error: Could not determine the next question based on your answer. Check your response and ask an admin to check the bot logs if this seems incorrect."
|
||||
}).AsEphemeral());
|
||||
currentStep.AddRelatedMessageIDs(followupMessage.Id);
|
||||
Database.SaveInterview(interaction.Channel.Id, interviewRoot);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (!int.TryParse(componentID, out int stepIndex))
|
||||
{
|
||||
Logger.Error("Invalid interview button/selector index: " + componentID);
|
||||
return;
|
||||
}
|
||||
|
||||
if (stepIndex >= currentStep.steps.Count || stepIndex < 0)
|
||||
{
|
||||
Logger.Error("Invalid interview button/selector index: " + stepIndex);
|
||||
return;
|
||||
}
|
||||
|
||||
(string stepString, InterviewStep nextStep) = currentStep.steps.ElementAt(stepIndex);
|
||||
await HandleAnswer(stepString, nextStep, interviewRoot, currentStep, interaction.Channel);
|
||||
}
|
||||
}
|
||||
|
||||
public static async Task ProcessResponseMessage(DiscordMessage answerMessage)
|
||||
{
|
||||
// Either the message or the referenced message is null.
|
||||
if (answerMessage.Channel == null || answerMessage.ReferencedMessage?.Channel == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// The channel does not have an active interview.
|
||||
if (!Database.TryGetInterview(answerMessage.ReferencedMessage.Channel.Id, out InterviewStep interviewRoot))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (!interviewRoot.TryGetCurrentStep(out InterviewStep currentStep))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// The user responded to something other than the latest interview question.
|
||||
if (answerMessage.ReferencedMessage.Id != currentStep.messageID)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// The user responded to a question which does not take a text response.
|
||||
if (currentStep.messageType != MessageType.TEXT_INPUT)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// The length requirement is less than 1024 characters, and must be less than the configurable limit if it is set.
|
||||
int maxLength = Math.Min(currentStep.maxLength ?? 1024, 1024);
|
||||
|
||||
if (answerMessage.Content.Length > maxLength)
|
||||
{
|
||||
DiscordMessage lengthMessage = await answerMessage.RespondAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Description = "Error: Your answer cannot be more than " + maxLength + " characters (" + answerMessage.Content.Length + "/" + maxLength + ").",
|
||||
Color = DiscordColor.Red
|
||||
});
|
||||
currentStep.AddRelatedMessageIDs(answerMessage.Id, lengthMessage.Id);
|
||||
Database.SaveInterview(answerMessage.Channel.Id, interviewRoot);
|
||||
return;
|
||||
}
|
||||
|
||||
if (answerMessage.Content.Length < (currentStep.minLength ?? 0))
|
||||
{
|
||||
DiscordMessage lengthMessage = await answerMessage.RespondAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Description = "Error: Your answer must be at least " + currentStep.minLength + " characters (" + answerMessage.Content.Length + "/" + currentStep.minLength + ").",
|
||||
Color = DiscordColor.Red
|
||||
});
|
||||
currentStep.AddRelatedMessageIDs(answerMessage.Id, lengthMessage.Id);
|
||||
Database.SaveInterview(answerMessage.Channel.Id, interviewRoot);
|
||||
return;
|
||||
}
|
||||
|
||||
foreach ((string stepPattern, InterviewStep nextStep) in currentStep.steps)
|
||||
{
|
||||
// Skip to the first matching step.
|
||||
if (!Regex.IsMatch(answerMessage.Content, stepPattern))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
await HandleAnswer(answerMessage.Content, nextStep, interviewRoot, currentStep, answerMessage.Channel, answerMessage);
|
||||
return;
|
||||
}
|
||||
|
||||
Logger.Error("The interview for channel " + answerMessage.Channel.Id + " reached a step of type " + currentStep.messageType + " which has no valid next step. Their message was:\n" + answerMessage.Content);
|
||||
DiscordMessage errorMessage = await answerMessage.RespondAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Description = "Error: Could not determine the next question based on your answer. Check your response and ask an admin to check the bot logs if this seems incorrect.",
|
||||
Color = DiscordColor.Red
|
||||
});
|
||||
currentStep.AddRelatedMessageIDs(answerMessage.Id, errorMessage.Id);
|
||||
Database.SaveInterview(answerMessage.Channel.Id, interviewRoot);
|
||||
}
|
||||
|
||||
private static async Task HandleAnswer(string answer,
|
||||
InterviewStep nextStep,
|
||||
InterviewStep interviewRoot,
|
||||
InterviewStep previousStep,
|
||||
DiscordChannel channel,
|
||||
DiscordMessage answerMessage = null)
|
||||
{
|
||||
// The error message type should not alter anything about the interview.
|
||||
if (nextStep.messageType != MessageType.ERROR)
|
||||
{
|
||||
previousStep.answer = answer;
|
||||
|
||||
// There is no message ID if the step is not a text input.
|
||||
previousStep.answerID = answerMessage == null ? 0 : answerMessage.Id;
|
||||
}
|
||||
|
||||
// Create next step, or finish the interview.
|
||||
switch (nextStep.messageType)
|
||||
{
|
||||
case MessageType.TEXT_INPUT:
|
||||
case MessageType.BUTTONS:
|
||||
case MessageType.TEXT_SELECTOR:
|
||||
case MessageType.ROLE_SELECTOR:
|
||||
case MessageType.USER_SELECTOR:
|
||||
case MessageType.CHANNEL_SELECTOR:
|
||||
case MessageType.MENTIONABLE_SELECTOR:
|
||||
await SendNextMessage(channel, nextStep);
|
||||
Database.SaveInterview(channel.Id, interviewRoot);
|
||||
break;
|
||||
case MessageType.END_WITH_SUMMARY:
|
||||
OrderedDictionary summaryFields = new OrderedDictionary();
|
||||
interviewRoot.GetSummary(ref summaryFields);
|
||||
|
||||
DiscordEmbedBuilder embed = new DiscordEmbedBuilder()
|
||||
{
|
||||
Color = Utilities.StringToColor(nextStep.color),
|
||||
Title = nextStep.heading,
|
||||
Description = nextStep.message,
|
||||
};
|
||||
|
||||
foreach (DictionaryEntry entry in summaryFields)
|
||||
{
|
||||
embed.AddField((string)entry.Key, (string)entry.Value);
|
||||
}
|
||||
|
||||
await channel.SendMessageAsync(embed);
|
||||
|
||||
if (Config.deleteMessagesAfterSummary)
|
||||
{
|
||||
await DeletePreviousMessages(interviewRoot, channel);
|
||||
}
|
||||
|
||||
if (!Database.TryDeleteInterview(channel.Id))
|
||||
{
|
||||
Logger.Error("Could not delete interview from database. Channel ID: " + channel.Id);
|
||||
}
|
||||
return;
|
||||
case MessageType.END_WITHOUT_SUMMARY:
|
||||
await channel.SendMessageAsync(new DiscordEmbedBuilder()
|
||||
{
|
||||
Color = Utilities.StringToColor(nextStep.color),
|
||||
Title = nextStep.heading,
|
||||
Description = nextStep.message
|
||||
});
|
||||
|
||||
if (Config.deleteMessagesAfterNoSummary)
|
||||
{
|
||||
await DeletePreviousMessages(interviewRoot, channel);
|
||||
}
|
||||
|
||||
if (!Database.TryDeleteInterview(channel.Id))
|
||||
{
|
||||
Logger.Error("Could not delete interview from database. Channel ID: " + channel.Id);
|
||||
}
|
||||
break;
|
||||
case MessageType.ERROR:
|
||||
default:
|
||||
if (answerMessage == null)
|
||||
{
|
||||
DiscordMessage errorMessage = await channel.SendMessageAsync(new DiscordEmbedBuilder()
|
||||
{
|
||||
Color = Utilities.StringToColor(nextStep.color),
|
||||
Title = nextStep.heading,
|
||||
Description = nextStep.message
|
||||
});
|
||||
previousStep.AddRelatedMessageIDs(errorMessage.Id);
|
||||
}
|
||||
else
|
||||
{
|
||||
DiscordMessageBuilder errorMessageBuilder = new DiscordMessageBuilder()
|
||||
.AddEmbed(new DiscordEmbedBuilder()
|
||||
{
|
||||
Color = Utilities.StringToColor(nextStep.color),
|
||||
Title = nextStep.heading,
|
||||
Description = nextStep.message
|
||||
}).WithReply(answerMessage.Id);
|
||||
DiscordMessage errorMessage = await answerMessage.RespondAsync(errorMessageBuilder);
|
||||
previousStep.AddRelatedMessageIDs(errorMessage.Id, answerMessage.Id);
|
||||
}
|
||||
|
||||
Database.SaveInterview(channel.Id, interviewRoot);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task DeletePreviousMessages(InterviewStep interviewRoot, DiscordChannel channel)
|
||||
{
|
||||
List<ulong> previousMessages = [];
|
||||
interviewRoot.GetMessageIDs(ref previousMessages);
|
||||
|
||||
foreach (ulong previousMessageID in previousMessages)
|
||||
{
|
||||
try
|
||||
{
|
||||
DiscordMessage previousMessage = await channel.GetMessageAsync(previousMessageID);
|
||||
await channel.DeleteMessageAsync(previousMessage, "Deleting old interview message.");
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Logger.Warn("Failed to delete old interview message: ", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task SendNextMessage(DiscordChannel channel, InterviewStep step)
|
||||
{
|
||||
DiscordMessageBuilder msgBuilder = new();
|
||||
DiscordEmbedBuilder embed = new()
|
||||
{
|
||||
Color = Utilities.StringToColor(step.color),
|
||||
Title = step.heading,
|
||||
Description = step.message
|
||||
};
|
||||
|
||||
switch (step.messageType)
|
||||
{
|
||||
case MessageType.BUTTONS:
|
||||
int nrOfButtons = 0;
|
||||
for (int nrOfButtonRows = 0; nrOfButtonRows < 5 && nrOfButtons < step.steps.Count; nrOfButtonRows++)
|
||||
{
|
||||
List<DiscordButtonComponent> buttonRow = [];
|
||||
for (; nrOfButtons < 5 * (nrOfButtonRows + 1) && nrOfButtons < step.steps.Count; nrOfButtons++)
|
||||
{
|
||||
(string stepPattern, InterviewStep nextStep) = step.steps.ToArray()[nrOfButtons];
|
||||
buttonRow.Add(new DiscordButtonComponent(nextStep.GetButtonStyle(), "supportchild_interviewbutton " + nrOfButtons, stepPattern));
|
||||
}
|
||||
msgBuilder.AddComponents(buttonRow);
|
||||
}
|
||||
break;
|
||||
case MessageType.TEXT_SELECTOR:
|
||||
List<DiscordSelectComponent> selectionComponents = [];
|
||||
|
||||
int selectionOptions = 0;
|
||||
for (int selectionBoxes = 0; selectionBoxes < 5 && selectionOptions < step.steps.Count; selectionBoxes++)
|
||||
{
|
||||
List<DiscordSelectComponentOption> categoryOptions = [];
|
||||
for (; selectionOptions < 25 * (selectionBoxes + 1) && selectionOptions < step.steps.Count; selectionOptions++)
|
||||
{
|
||||
(string stepPattern, InterviewStep nextStep) = step.steps.ToArray()[selectionOptions];
|
||||
categoryOptions.Add(new DiscordSelectComponentOption(stepPattern, selectionOptions.ToString(), nextStep.selectorDescription));
|
||||
}
|
||||
|
||||
selectionComponents.Add(new DiscordSelectComponent("supportchild_interviewselector " + selectionBoxes, string.IsNullOrWhiteSpace(step.selectorPlaceholder)
|
||||
? "Select an option..." : step.selectorPlaceholder, categoryOptions));
|
||||
}
|
||||
|
||||
msgBuilder.AddComponents(selectionComponents);
|
||||
break;
|
||||
case MessageType.ROLE_SELECTOR:
|
||||
msgBuilder.AddComponents(new DiscordRoleSelectComponent("supportchild_interviewroleselector", string.IsNullOrWhiteSpace(step.selectorPlaceholder)
|
||||
? "Select a role..." : step.selectorPlaceholder));
|
||||
break;
|
||||
case MessageType.USER_SELECTOR:
|
||||
msgBuilder.AddComponents(new DiscordUserSelectComponent("supportchild_interviewuserselector", string.IsNullOrWhiteSpace(step.selectorPlaceholder)
|
||||
? "Select a user..." : step.selectorPlaceholder));
|
||||
break;
|
||||
case MessageType.CHANNEL_SELECTOR:
|
||||
msgBuilder.AddComponents(new DiscordChannelSelectComponent("supportchild_interviewchannelselector", string.IsNullOrWhiteSpace(step.selectorPlaceholder)
|
||||
? "Select a channel..." : step.selectorPlaceholder));
|
||||
break;
|
||||
case MessageType.MENTIONABLE_SELECTOR:
|
||||
msgBuilder.AddComponents(new DiscordMentionableSelectComponent("supportchild_interviewmentionableselector", string.IsNullOrWhiteSpace(step.selectorPlaceholder)
|
||||
? "Select a user or role..." : step.selectorPlaceholder));
|
||||
break;
|
||||
case MessageType.TEXT_INPUT:
|
||||
embed.WithFooter("Reply to this message with your answer. You cannot include images or files.");
|
||||
break;
|
||||
case MessageType.END_WITH_SUMMARY:
|
||||
case MessageType.END_WITHOUT_SUMMARY:
|
||||
case MessageType.ERROR:
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
msgBuilder.AddEmbed(embed);
|
||||
DiscordMessage message = await channel.SendMessageAsync(msgBuilder);
|
||||
step.messageID = message.Id;
|
||||
}
|
||||
}
|
182
Interviews/interview_template.schema.json
Normal file
182
Interviews/interview_template.schema.json
Normal file
|
@ -0,0 +1,182 @@
|
|||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"id": "https://toastielab.dev/Emotions-stuff/SupportChild/raw/branch/main/Interviews/interview_template.schema.json",
|
||||
"title": "Interview Template",
|
||||
"description": "An interview dialog tree template for SupportBoi",
|
||||
"definitions":
|
||||
{
|
||||
"step":
|
||||
{
|
||||
"type": "object",
|
||||
"title": "Interview Step",
|
||||
"description": "Contains a question, error message or end of an interview.",
|
||||
"properties":
|
||||
{
|
||||
"heading":
|
||||
{
|
||||
"type": "string",
|
||||
"title": "Heading",
|
||||
"description": "The title of the message.",
|
||||
"minLength": 1
|
||||
},
|
||||
"message":
|
||||
{
|
||||
"type": "string",
|
||||
"title": "Message",
|
||||
"description": "The text in the embed message that will be sent to the user when they reach this step.",
|
||||
"minLength": 1
|
||||
},
|
||||
"message-type":
|
||||
{
|
||||
"type": "string",
|
||||
"title": "Message Type",
|
||||
"description": "The type of message, decides what the bot will do when the user gets to this step.",
|
||||
"enum":
|
||||
[
|
||||
"ERROR",
|
||||
"END_WITH_SUMMARY",
|
||||
"END_WITHOUT_SUMMARY",
|
||||
"BUTTONS",
|
||||
"TEXT_SELECTOR",
|
||||
"USER_SELECTOR",
|
||||
"ROLE_SELECTOR",
|
||||
"MENTIONABLE_SELECTOR",
|
||||
"CHANNEL_SELECTOR",
|
||||
"TEXT_INPUT"
|
||||
]
|
||||
},
|
||||
"color":
|
||||
{
|
||||
"type": "string",
|
||||
"title": "Color",
|
||||
"description": "Colour of the message embed. You can either enter a colour name or a hexadecimal RGB value.",
|
||||
"examples":
|
||||
[
|
||||
"BLACK",
|
||||
"WHITE",
|
||||
"GRAY",
|
||||
"DARKGRAY",
|
||||
"LIGHTGRAY",
|
||||
"VERYDARKGRAY",
|
||||
"BLURPLE",
|
||||
"GRAYPLE",
|
||||
"DARKBUTNOTBLACK",
|
||||
"NOTQUITEBLACK",
|
||||
"RED",
|
||||
"DARKRED",
|
||||
"GREEN",
|
||||
"DARKGREEN",
|
||||
"BLUE",
|
||||
"DARKBLUE",
|
||||
"YELLOW",
|
||||
"CYAN",
|
||||
"MAGENTA",
|
||||
"TEAL",
|
||||
"AQUAMARINE",
|
||||
"GOLD",
|
||||
"GOLDENROD",
|
||||
"AZURE",
|
||||
"ROSE",
|
||||
"SPRINGGREEN",
|
||||
"CHARTREUSE",
|
||||
"ORANGE",
|
||||
"PURPLE",
|
||||
"VIOLET",
|
||||
"BROWN",
|
||||
"HOTPINK",
|
||||
"LILAC",
|
||||
"CORNFLOWERBLUE",
|
||||
"MIDNIGHTBLUE",
|
||||
"WHEAT",
|
||||
"INDIANRED",
|
||||
"TURQUOISE",
|
||||
"SAPGREEN",
|
||||
"PHTHALOBLUE",
|
||||
"PHTHALOGREEN",
|
||||
"SIENNA"
|
||||
],
|
||||
"minLength": 1
|
||||
},
|
||||
"steps":
|
||||
{
|
||||
"type": "object",
|
||||
"title": "Steps",
|
||||
"description": "One or more interview steps. The name of the step is used as a regex match against the user's answer, except for selection boxes and buttons where each step becomes a button or selection option.",
|
||||
"patternProperties":
|
||||
{
|
||||
".*":
|
||||
{
|
||||
"$ref": "#/definitions/step"
|
||||
}
|
||||
}
|
||||
},
|
||||
"summary-field":
|
||||
{
|
||||
"type": "string",
|
||||
"title": "Summary Field",
|
||||
"description": "When an interview ends all previous answers with this property will be put in a summary. If this property is not specified the answer will not be shown in the summary. The value of this property is the name which will be displayed next to the answer in the summary.",
|
||||
"minLength": 1
|
||||
},
|
||||
"button-style":
|
||||
{
|
||||
"type": "string",
|
||||
"title": "Button Style",
|
||||
"description": "The style of the button that leads to this step. Requires that the parent step is a 'BUTTONS' step.",
|
||||
"enum":
|
||||
[
|
||||
"PRIMARY",
|
||||
"SECONDARY",
|
||||
"SUCCESS",
|
||||
"DANGER"
|
||||
]
|
||||
},
|
||||
"selector-description":
|
||||
{
|
||||
"type": "string",
|
||||
"title": "Selector Description",
|
||||
"description": "Description for this option in the parent step's selection box. Requires that the parent step is a 'TEXT_SELECTOR'.",
|
||||
"minLength": 1
|
||||
},
|
||||
"selector-placeholder":
|
||||
{
|
||||
"type": "string",
|
||||
"title": "Selector Placeholder",
|
||||
"description": "The placeholder text shown before a value is selected in the selection box. Requires that this step is a TEXT_SELECTOR.",
|
||||
"minLength": 1
|
||||
},
|
||||
"max-length":
|
||||
{
|
||||
"type": "number",
|
||||
"title": "Max Length",
|
||||
"description": "The maximum length of the user's response message. Requires that this step is a 'TEXT_INPUT'.",
|
||||
"maximum": 1024
|
||||
},
|
||||
"min-length":
|
||||
{
|
||||
"type": "number",
|
||||
"title": "Min Length",
|
||||
"description": "The minimum length of the user's response message. Requires that this step is a 'TEXT_INPUT'.",
|
||||
"minimum": 0
|
||||
}
|
||||
},
|
||||
"required": [ "message", "message-type", "color" ],
|
||||
"unevaluatedProperties": false
|
||||
}
|
||||
},
|
||||
"type": "object",
|
||||
"properties":
|
||||
{
|
||||
"category-id":
|
||||
{
|
||||
"type": "number",
|
||||
"title": "Category ID",
|
||||
"description": "The id of the category this template applies to. You can change this and re-upload the template to apply it to a different category."
|
||||
},
|
||||
"interview":
|
||||
{
|
||||
"$ref": "#/definitions/step"
|
||||
}
|
||||
},
|
||||
"required": [ "category-id", "interview" ],
|
||||
"unevaluatedProperties": false
|
||||
}
|
10
Jenkinsfile
vendored
10
Jenkinsfile
vendored
|
@ -10,12 +10,16 @@ pipeline {
|
|||
parallel {
|
||||
stage('Linux') {
|
||||
steps {
|
||||
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/'
|
||||
sh 'dotnet publish -r linux-x64 -c Release -p:PublishTrimmed=true --self-contained true --no-restore --output Linux-x64/'
|
||||
sh 'mv Linux-x64/SupportChild Linux-x64/SupportChild-SC'
|
||||
sh 'dotnet publish -r linux-x64 -c Release --self-contained false --no-restore --output Linux-x64/'
|
||||
}
|
||||
}
|
||||
stage('Windows') {
|
||||
steps {
|
||||
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/'
|
||||
sh 'dotnet publish -r win-x64 -c Release -p:PublishTrimmed=true --self-contained true --no-restore --output Windows-x64/'
|
||||
sh 'mv Windows-x64/SupportChild.exe Windows-x64/SupportChild-SC.exe'
|
||||
sh 'dotnet publish -r win-x64 -c Release --self-contained false --no-restore --output Windows-x64/'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -25,11 +29,13 @@ pipeline {
|
|||
stage('Linux') {
|
||||
steps {
|
||||
archiveArtifacts(artifacts: 'Linux-x64/SupportChild', caseSensitive: true)
|
||||
archiveArtifacts(artifacts: 'Linux-x64/SupportChild-SC', caseSensitive: true)
|
||||
}
|
||||
}
|
||||
stage('Windows') {
|
||||
steps {
|
||||
archiveArtifacts(artifacts: 'Windows-x64/SupportChild.exe', caseSensitive: true)
|
||||
archiveArtifacts(artifacts: 'Windows-x64/SupportChild-SC.exe', caseSensitive: true)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
876
LICENSE
876
LICENSE
|
@ -1,674 +1,202 @@
|
|||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright 2024 toastie_t0ast
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
74
LogChannel.cs
Normal file
74
LogChannel.cs
Normal file
|
@ -0,0 +1,74 @@
|
|||
using System;
|
||||
using System.Threading.Tasks;
|
||||
using DSharpPlus.Entities;
|
||||
using DSharpPlus.Exceptions;
|
||||
|
||||
namespace SupportChild;
|
||||
|
||||
public static class LogChannel
|
||||
{
|
||||
public static bool IsEnabled => Config.logChannel != 0;
|
||||
|
||||
public static async Task Log(string message, uint ticketID = 0, Utilities.File file = null)
|
||||
{
|
||||
await Log(DiscordColor.Cyan, message, ticketID, file);
|
||||
}
|
||||
|
||||
public static async Task Success(string message, uint ticketID = 0, Utilities.File file = null)
|
||||
{
|
||||
await Log(DiscordColor.Green, message, ticketID, file);
|
||||
}
|
||||
|
||||
public static async Task Warn(string message, uint ticketID = 0, Utilities.File file = null)
|
||||
{
|
||||
await Log(DiscordColor.Orange, message, ticketID, file);
|
||||
}
|
||||
|
||||
public static async Task Error(string message, uint ticketID = 0, Utilities.File file = null)
|
||||
{
|
||||
await Log(DiscordColor.Red, message, ticketID, file);
|
||||
}
|
||||
|
||||
private static async Task Log(DiscordColor color, string message, uint ticketID = 0, Utilities.File file = null)
|
||||
{
|
||||
if (!IsEnabled)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
DiscordEmbedBuilder embedBuilder = new()
|
||||
{
|
||||
Color = color,
|
||||
Description = message
|
||||
};
|
||||
if (ticketID != 0)
|
||||
{
|
||||
embedBuilder.WithFooter("Ticket: " + ticketID.ToString("00000"));
|
||||
}
|
||||
|
||||
DiscordMessageBuilder messageBuilder = new();
|
||||
messageBuilder.AddEmbed(embedBuilder);
|
||||
if (file != null)
|
||||
{
|
||||
messageBuilder.AddFile(file.fileName, file.contents);
|
||||
}
|
||||
|
||||
DiscordChannel logChannel = await SupportChild.client.GetChannelAsync(Config.logChannel);
|
||||
await logChannel.SendMessageAsync(messageBuilder);
|
||||
}
|
||||
catch (NotFoundException)
|
||||
{
|
||||
Logger.Error("Log channel does not exist. Channel ID: " + Config.logChannel);
|
||||
}
|
||||
catch (UnauthorizedException)
|
||||
{
|
||||
Logger.Error("No permissions to send message in log channel. Channel ID: " + Config.logChannel);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Logger.Error("Error occured trying to send message in log channel. Channel ID: " + Config.logChannel, e);
|
||||
}
|
||||
}
|
||||
}
|
160
Logger.cs
Normal file
160
Logger.cs
Normal file
|
@ -0,0 +1,160 @@
|
|||
using Microsoft.Extensions.Logging;
|
||||
using System;
|
||||
using DSharpPlus;
|
||||
using DSharpPlus.Exceptions;
|
||||
|
||||
namespace SupportChild;
|
||||
|
||||
internal class LogTestFactory : ILoggerProvider
|
||||
{
|
||||
public void Dispose() { }
|
||||
|
||||
public ILogger CreateLogger(string categoryName)
|
||||
{
|
||||
return Logger.instance;
|
||||
}
|
||||
}
|
||||
|
||||
public class Logger : ILogger
|
||||
{
|
||||
public static Logger instance { get; } = new Logger();
|
||||
|
||||
private static LogLevel minimumLogLevel = LogLevel.Trace;
|
||||
private readonly object @lock = new();
|
||||
|
||||
internal static void SetLogLevel(LogLevel level)
|
||||
{
|
||||
minimumLogLevel = level;
|
||||
}
|
||||
|
||||
internal static void Debug(string message, Exception exception = null)
|
||||
{
|
||||
instance.Log(LogLevel.Debug, new EventId(420, "BOT"), exception, message);
|
||||
}
|
||||
|
||||
internal static void Log(string message, Exception exception = null)
|
||||
{
|
||||
instance.Log(LogLevel.Information, new EventId(420, "BOT"), exception, message);
|
||||
}
|
||||
|
||||
internal static void Warn(string message, Exception exception = null)
|
||||
{
|
||||
instance.Log(LogLevel.Warning, new EventId(420, "BOT"), exception, message);
|
||||
}
|
||||
|
||||
internal static void Error(string message, Exception exception = null)
|
||||
{
|
||||
instance.Log(LogLevel.Error, new EventId(420, "BOT"), exception, message);
|
||||
}
|
||||
|
||||
internal static void Fatal(string message, Exception exception = null)
|
||||
{
|
||||
instance.Log(LogLevel.Critical, new EventId(420, "BOT"), exception, message);
|
||||
}
|
||||
|
||||
public bool IsEnabled(LogLevel logLevel)
|
||||
{
|
||||
return logLevel >= minimumLogLevel && logLevel != LogLevel.None;
|
||||
}
|
||||
|
||||
public IDisposable BeginScope<TState>(TState state) where TState : notnull => default;
|
||||
|
||||
private static ConsoleColor GetLogLevelColour(LogLevel logLevel)
|
||||
{
|
||||
return logLevel switch
|
||||
{
|
||||
LogLevel.Trace => ConsoleColor.White,
|
||||
LogLevel.Debug => ConsoleColor.DarkGray,
|
||||
LogLevel.Information => ConsoleColor.DarkBlue,
|
||||
LogLevel.Warning => ConsoleColor.Yellow,
|
||||
LogLevel.Error => ConsoleColor.Red,
|
||||
_ => ConsoleColor.White
|
||||
};
|
||||
}
|
||||
|
||||
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
|
||||
{
|
||||
if (!IsEnabled(logLevel))
|
||||
return;
|
||||
|
||||
// Ratelimit messages are usually warnings, but they are unimportant in this case so downgrade them to debug.
|
||||
if (formatter(state, exception).StartsWith("Hit Discord ratelimit on route ") && logLevel == LogLevel.Warning)
|
||||
{
|
||||
logLevel = LogLevel.Debug;
|
||||
}
|
||||
// The bot will handle NotFoundExceptions on its own, downgrade to debug
|
||||
else if (exception is NotFoundException && eventId == LoggerEvents.RestError)
|
||||
{
|
||||
logLevel = LogLevel.Debug;
|
||||
}
|
||||
|
||||
string[] logLevelParts = logLevel switch
|
||||
{
|
||||
LogLevel.Trace => ["[", "Trace", "] "],
|
||||
LogLevel.Debug => ["[", "Debug", "] "],
|
||||
LogLevel.Information => [" [", "Info", "] "],
|
||||
LogLevel.Warning => [" [", "Warn", "] "],
|
||||
LogLevel.Error => ["[", "Error", "] "],
|
||||
LogLevel.Critical => [" [", "\u001b[1mCrit\u001b[0m", "] "],
|
||||
_ => [" [", "None", "] "],
|
||||
};
|
||||
|
||||
lock (@lock)
|
||||
{
|
||||
Console.ForegroundColor = ConsoleColor.Gray;
|
||||
Console.Write("[");
|
||||
|
||||
Console.ResetColor();
|
||||
Console.ForegroundColor = GetLogLevelColour(logLevel);
|
||||
if (logLevel == LogLevel.Critical)
|
||||
{
|
||||
Console.BackgroundColor = ConsoleColor.DarkRed;
|
||||
}
|
||||
Console.Write($"{DateTimeOffset.UtcNow.ToString("yyyy-MM-dd HH:mm:ss")}");
|
||||
Console.ResetColor();
|
||||
|
||||
Console.ForegroundColor = ConsoleColor.Gray;
|
||||
Console.Write("] ");
|
||||
|
||||
Console.ForegroundColor = ConsoleColor.Gray;
|
||||
Console.Write("[");
|
||||
|
||||
Console.ForegroundColor = eventId == 420 ? ConsoleColor.Green : ConsoleColor.DarkGreen;
|
||||
Console.Write(eventId == 420 ? "BOT" : "API");
|
||||
|
||||
Console.ForegroundColor = ConsoleColor.Gray;
|
||||
Console.Write("] ");
|
||||
Console.Write(logLevelParts[0]);
|
||||
|
||||
Console.ForegroundColor = GetLogLevelColour(logLevel);
|
||||
if (logLevel == LogLevel.Critical)
|
||||
{
|
||||
Console.BackgroundColor = ConsoleColor.DarkRed;
|
||||
}
|
||||
Console.Write(logLevelParts[1]);
|
||||
|
||||
Console.ResetColor();
|
||||
Console.ForegroundColor = ConsoleColor.Gray;
|
||||
Console.Write(logLevelParts[2]);
|
||||
|
||||
Console.ResetColor();
|
||||
if (logLevel is LogLevel.Trace or LogLevel.Debug)
|
||||
{
|
||||
Console.ForegroundColor = ConsoleColor.Gray;
|
||||
}
|
||||
else if (logLevel is LogLevel.Critical or LogLevel.Error)
|
||||
{
|
||||
Console.ForegroundColor = ConsoleColor.Red;
|
||||
}
|
||||
Console.WriteLine(formatter(state, exception));
|
||||
|
||||
if (exception != null)
|
||||
{
|
||||
Console.ForegroundColor = ConsoleColor.Gray;
|
||||
Console.WriteLine($"{exception} : {exception.Message}\n{exception.StackTrace}");
|
||||
}
|
||||
|
||||
Console.ResetColor();
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,3 +1,3 @@
|
|||
# SupportChild
|
||||
[![Build Status](https://ci.toastielab.dev/buildStatus/icon?job=Toastie-stuff%2FSupportChild%2Fmain)](https://ci.toastielab.dev/job/Toastie-stuff/job/SupportChild/job/main/)
|
||||
|
||||
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!
|
||||
# SupportChild
|
||||
|
|
254
SupportChild.cs
Normal file
254
SupportChild.cs
Normal file
|
@ -0,0 +1,254 @@
|
|||
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.Commands;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using SupportChild.Commands;
|
||||
using CommandLine;
|
||||
using DSharpPlus.Commands.Processors.SlashCommands;
|
||||
using DSharpPlus.Exceptions;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace SupportChild;
|
||||
|
||||
internal static class SupportChild
|
||||
{
|
||||
internal static DiscordClient client = null;
|
||||
public class CommandLineArguments
|
||||
{
|
||||
[Option('c',
|
||||
"config",
|
||||
Required = false,
|
||||
HelpText = "Select a config file to use.",
|
||||
MetaValue = "PATH")]
|
||||
public string configPath { get; set; }
|
||||
|
||||
[Option('t',
|
||||
"transcripts",
|
||||
Required = false,
|
||||
HelpText = "Select directory to store transcripts in.",
|
||||
MetaValue = "PATH")]
|
||||
public string transcriptDir { get; set; }
|
||||
|
||||
[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<ulong> 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<CommandLineArguments>(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
|
||||
{
|
||||
if (!await Reload())
|
||||
{
|
||||
Logger.Fatal("Aborting startup due to a fatal error...");
|
||||
return;
|
||||
}
|
||||
|
||||
// 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 Task<bool> Reload()
|
||||
{
|
||||
if (client != null)
|
||||
{
|
||||
await client.DisconnectAsync();
|
||||
client.Dispose();
|
||||
}
|
||||
|
||||
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);
|
||||
return false;
|
||||
}
|
||||
|
||||
Logger.Log("Setting up Discord client...");
|
||||
DiscordClientBuilder clientBuilder = DiscordClientBuilder.CreateDefault(Config.token, DiscordIntents.All).SetReconnectOnFatalGatewayErrors();
|
||||
|
||||
clientBuilder.ConfigureServices(configure =>
|
||||
{
|
||||
configure.AddSingleton<IClientErrorHandler>(new ErrorHandler());
|
||||
});
|
||||
|
||||
clientBuilder.ConfigureEventHandlers(builder =>
|
||||
{
|
||||
builder.HandleGuildDownloadCompleted(EventHandler.OnReady);
|
||||
builder.HandleGuildAvailable(EventHandler.OnGuildAvailable);
|
||||
builder.HandleMessageCreated(EventHandler.OnMessageCreated);
|
||||
builder.HandleGuildMemberAdded(EventHandler.OnMemberAdded);
|
||||
builder.HandleGuildMemberRemoved(EventHandler.OnMemberRemoved);
|
||||
builder.HandleComponentInteractionCreated(EventHandler.OnComponentInteractionCreated);
|
||||
});
|
||||
|
||||
clientBuilder.UseInteractivity(new InteractivityConfiguration
|
||||
{
|
||||
PaginationBehaviour = PaginationBehaviour.Ignore,
|
||||
PaginationDeletion = PaginationDeletion.DeleteMessage,
|
||||
Timeout = TimeSpan.FromMinutes(15)
|
||||
});
|
||||
|
||||
clientBuilder.UseCommands((_, extension) =>
|
||||
{
|
||||
extension.AddCommands(
|
||||
[
|
||||
typeof(AddCategoryCommand),
|
||||
typeof(AddCommand),
|
||||
typeof(AddMessageCommand),
|
||||
typeof(AddStaffCommand),
|
||||
typeof(AdminCommands),
|
||||
typeof(AssignCommand),
|
||||
typeof(BlacklistCommand),
|
||||
typeof(CloseCommand),
|
||||
typeof(CreateButtonPanelCommand),
|
||||
typeof(CreateSelectionBoxPanelCommand),
|
||||
typeof(InterviewTemplateCommands),
|
||||
typeof(ListAssignedCommand),
|
||||
typeof(ListCommand),
|
||||
typeof(ListInvalidCommand),
|
||||
typeof(ListOpen),
|
||||
typeof(ListUnassignedCommand),
|
||||
typeof(MoveCommand),
|
||||
typeof(NewCommand),
|
||||
typeof(RandomAssignCommand),
|
||||
typeof(RemoveCategoryCommand),
|
||||
typeof(RemoveMessageCommand),
|
||||
typeof(RemoveStaffCommand),
|
||||
typeof(InterviewCommands),
|
||||
typeof(SayCommand),
|
||||
typeof(SetSummaryCommand),
|
||||
typeof(StatusCommand),
|
||||
typeof(SummaryCommand),
|
||||
typeof(ToggleActiveCommand),
|
||||
typeof(TranscriptCommand),
|
||||
typeof(UnassignCommand),
|
||||
typeof(UnblacklistCommand),
|
||||
]);
|
||||
extension.AddProcessor(new SlashCommandProcessor());
|
||||
extension.CommandErrored += EventHandler.OnCommandError;
|
||||
}, new CommandsConfiguration()
|
||||
{
|
||||
RegisterDefaultCommandProcessors = false,
|
||||
UseDefaultCommandErrorHandler = false
|
||||
});
|
||||
|
||||
clientBuilder.ConfigureExtraFeatures(clientConfig =>
|
||||
{
|
||||
clientConfig.LogUnknownEvents = false;
|
||||
clientConfig.LogUnknownAuditlogs = false;
|
||||
});
|
||||
|
||||
clientBuilder.ConfigureLogging(config =>
|
||||
{
|
||||
config.AddProvider(new LogTestFactory());
|
||||
});
|
||||
|
||||
client = clientBuilder.Build();
|
||||
|
||||
Logger.Log("Connecting to Discord...");
|
||||
EventHandler.hasLoggedGuilds = false;
|
||||
await client.ConnectAsync();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
internal class ErrorHandler : IClientErrorHandler
|
||||
{
|
||||
public ValueTask HandleEventHandlerError(string name, Exception exception, Delegate invokedDelegate, object sender, object args)
|
||||
{
|
||||
Logger.Error("Client exception occured:\n" + exception);
|
||||
switch (exception)
|
||||
{
|
||||
case BadRequestException ex:
|
||||
Logger.Error("JSON Message: " + ex.JsonMessage);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
return ValueTask.FromException(exception);
|
||||
}
|
||||
|
||||
public ValueTask HandleGatewayError(Exception exception)
|
||||
{
|
||||
Logger.Error("A gateway error occured:\n" + exception);
|
||||
return ValueTask.FromException(exception);
|
||||
}
|
||||
}
|
66
SupportChild.csproj
Normal file
66
SupportChild.csproj
Normal file
|
@ -0,0 +1,66 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<Version>4.0.0</Version>
|
||||
<ApplicationIcon>ellie_icon.ico</ApplicationIcon>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<StartupObject>SupportChild.SupportChild</StartupObject>
|
||||
<RuntimeIdentifiers>win-x64;linux-x64</RuntimeIdentifiers>
|
||||
<PublishSingleFile>true</PublishSingleFile>
|
||||
<TrimMode>partial</TrimMode>
|
||||
|
||||
<Authors>Toastie_t0ast</Authors>
|
||||
<Description>A Discord support ticket bot built for the Ellie's home server</Description>
|
||||
<NeutralLanguage>en</NeutralLanguage>
|
||||
<RepositoryType>Git</RepositoryType>
|
||||
<RepositoryUrl>https://toastielab.dev/Emotions-stuff/SupportChild</RepositoryUrl>
|
||||
|
||||
<PackageIconUrl>https://cdn.discordapp.com/attachments/765441543100170271/914327948667011132/Ellie_Concept_2_transparent_ver.png</PackageIconUrl>
|
||||
<PackageLicenseFile>LICENSE</PackageLicenseFile>
|
||||
<PackageProjectUrl>https://toastielab.dev/Emotions-stuff/SupportChild</PackageProjectUrl>
|
||||
<PackageVersion>4.0.0</PackageVersion>
|
||||
<LangVersion>default</LangVersion>
|
||||
<IncludeSourceRevisionInInformationalVersion>false</IncludeSourceRevisionInInformationalVersion>
|
||||
<GitVersion>false</GitVersion>
|
||||
</PropertyGroup>
|
||||
|
||||
<PropertyGroup Condition=" '$(Configuration)' == 'Debug' ">
|
||||
<DebugType>full</DebugType>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="AsyncKeyedLock" Version="7.1.4" />
|
||||
<PackageReference Include="CommandLineParser" Version="2.9.1" />
|
||||
<PackageReference Include="DSharpPlus" Version="5.0.0-nightly-02405" />
|
||||
<PackageReference Include="DSharpPlus.Commands" Version="5.0.0-nightly-02405" />
|
||||
<PackageReference Include="DSharpPlus.Interactivity" Version="5.0.0-nightly-02405" />
|
||||
<PackageReference Include="EmbeddedBuildTime" Version="1.0.3" />
|
||||
<PackageReference Include="GitInfo" Version="3.3.5">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="JsonExtensions" Version="1.2.0" />
|
||||
<PackageReference Include="MySqlConnector" Version="2.4.0" />
|
||||
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
|
||||
<PackageReference Include="Newtonsoft.Json.Schema" Version="4.0.1" />
|
||||
<PackageReference Include="Polly" Version="8.4.2" />
|
||||
<PackageReference Include="RazorBlade" Version="0.6.0" />
|
||||
<PackageReference Include="Superpower" Version="3.0.0" />
|
||||
<PackageReference Include="WebMarkupMin.Core" Version="2.17.0" />
|
||||
<PackageReference Include="YamlDotNet" Version="16.2.0" />
|
||||
<PackageReference Include="YoutubeExplode" Version="6.4.3" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Reference Include="DiscordChatExporter.Core">
|
||||
<HintPath>lib/DiscordChatExporter.Core.dll</HintPath>
|
||||
</Reference>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<EmbeddedResource Include="default_config.yml" />
|
||||
<EmbeddedResource Include="Interviews/interview_template.schema.json" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
|
@ -1,16 +0,0 @@
|
|||
|
||||
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
|
|
@ -1,6 +0,0 @@
|
|||
<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
|
||||
<s:String x:Key="/Default/CodeInspection/PencilsConfiguration/ActualSeverity/@EntryValue">ERROR</s:String>
|
||||
<s:Boolean x:Key="/Default/ResxEditorPersonal/CheckedGroups/=SupportChild_002FProperties_002FResources/@EntryIndexedValue">True</s:Boolean>
|
||||
|
||||
<s:Boolean x:Key="/Default/ResxEditorPersonal/Initialized/@EntryValue">True</s:Boolean>
|
||||
</wpf:ResourceDictionary>
|
|
@ -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);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -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);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -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);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,67 +0,0 @@
|
|||
using System;
|
||||
using System.Threading.Tasks;
|
||||
using DSharpPlus.Entities;
|
||||
using DSharpPlus.SlashCommands;
|
||||
using DSharpPlus.SlashCommands.Attributes;
|
||||
using MySql.Data.MySqlClient;
|
||||
|
||||
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"
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
|
@ -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 <id> to remove them.")]
|
||||
public async Task ListInvalid(InteractionContext command)
|
||||
{
|
||||
if (!Database.TryGetOpenTickets(out List<Database.Ticket> 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<DiscordChannel> allChannels = new List<DiscordChannel>();
|
||||
foreach (KeyValuePair<ulong, DiscordGuild> guild in SupportChild.discordClient.Guilds)
|
||||
{
|
||||
try
|
||||
{
|
||||
allChannels.AddRange(await guild.Value.GetChannelsAsync());
|
||||
}
|
||||
catch (Exception) { /*ignored*/ }
|
||||
}
|
||||
|
||||
// Check which tickets channels no longer exist
|
||||
List<string> listItems = new List<string>();
|
||||
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<DiscordEmbedBuilder> embeds = new List<DiscordEmbedBuilder>();
|
||||
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<Page> listPages = new List<Page>();
|
||||
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();
|
||||
}
|
||||
}
|
|
@ -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 + "."
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
|
@ -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;
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,134 +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
|
||||
{
|
||||
[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.WithFiles(new Dictionary<string, Stream> { { 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.WithFiles(new Dictionary<string, Stream> { { 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);
|
||||
}
|
||||
}
|
|
@ -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<Database.Category> 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<DiscordButtonComponent> buttonRow = new List<DiscordButtonComponent>();
|
||||
|
||||
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
|
||||
}));
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,79 +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<List<DiscordSelectComponent>> GetSelectComponents(InteractionContext command, string placeholder)
|
||||
{
|
||||
List<Database.Category> verifiedCategories = await Utilities.GetVerifiedChannels();
|
||||
|
||||
if (verifiedCategories.Count == 0) return new List<DiscordSelectComponent>();
|
||||
|
||||
verifiedCategories = verifiedCategories.OrderBy(x => x.name).ToList();
|
||||
List<DiscordSelectComponent> selectionComponents = new List<DiscordSelectComponent>();
|
||||
int selectionOptions = 0;
|
||||
for (int selectionBoxes = 0; selectionBoxes < 5 && selectionOptions < verifiedCategories.Count; selectionBoxes++)
|
||||
{
|
||||
List<DiscordSelectComponentOption> categoryOptions = new List<DiscordSelectComponentOption>();
|
||||
|
||||
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());
|
||||
}
|
||||
}
|
||||
}
|
|
@ -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<Database.Ticket> assignedTickets))
|
||||
{
|
||||
await command.CreateResponseAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Red,
|
||||
Description = "User does not have any assigned tickets."
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
List<string> listItems = new List<string>();
|
||||
foreach (Database.Ticket ticket in assignedTickets)
|
||||
{
|
||||
listItems.Add("**" + ticket.DiscordRelativeTime() + ":** <#" + ticket.channelID + "> by <@" + ticket.creatorID + ">\n");
|
||||
}
|
||||
|
||||
List<DiscordEmbedBuilder> embeds = new List<DiscordEmbedBuilder>();
|
||||
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<Page> listPages = new List<Page>();
|
||||
foreach (DiscordEmbedBuilder embed in embeds)
|
||||
{
|
||||
listPages.Add(new Page("", embed));
|
||||
}
|
||||
|
||||
await command.Interaction.SendPaginatedResponseAsync(true, command.User, listPages);
|
||||
}
|
||||
}
|
|
@ -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<DiscordEmbedBuilder> openEmbeds = new List<DiscordEmbedBuilder>();
|
||||
if (Database.TryGetOpenTickets(listUser.Id, out List<Database.Ticket> openTickets))
|
||||
{
|
||||
List<string> listItems = new List<string>();
|
||||
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<DiscordEmbedBuilder> closedEmbeds = new List<DiscordEmbedBuilder>();
|
||||
if (Database.TryGetClosedTickets(listUser.Id, out List<Database.Ticket> closedTickets))
|
||||
{
|
||||
List<string> listItems = new List<string>();
|
||||
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<DiscordEmbedBuilder> embeds = new List<DiscordEmbedBuilder>();
|
||||
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<Page> listPages = new List<Page>();
|
||||
foreach (DiscordEmbedBuilder embed in embeds)
|
||||
{
|
||||
listPages.Add(new Page("", embed));
|
||||
}
|
||||
|
||||
await command.Interaction.SendPaginatedResponseAsync(true, command.User, listPages);
|
||||
}
|
||||
}
|
|
@ -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<Database.Ticket> openTickets))
|
||||
{
|
||||
await command.CreateResponseAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Red,
|
||||
Description = "Could not fetch any open tickets."
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
List<string> listItems = new List<string>();
|
||||
foreach (Database.Ticket ticket in openTickets)
|
||||
{
|
||||
listItems.Add("**" + ticket.DiscordRelativeTime() + ":** <#" + ticket.channelID + "> by <@" + ticket.creatorID + ">\n");
|
||||
}
|
||||
|
||||
List<DiscordEmbedBuilder> embeds = new List<DiscordEmbedBuilder>();
|
||||
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<Page> listPages = new List<Page>();
|
||||
foreach (DiscordEmbedBuilder embed in embeds)
|
||||
{
|
||||
listPages.Add(new Page("", embed));
|
||||
}
|
||||
|
||||
await command.Interaction.SendPaginatedResponseAsync(true, command.User, listPages);
|
||||
}
|
||||
}
|
|
@ -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<Database.Ticket> unassignedTickets))
|
||||
{
|
||||
await command.CreateResponseAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Green,
|
||||
Description = "There are no unassigned tickets."
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
List<string> listItems = new List<string>();
|
||||
foreach (Database.Ticket ticket in unassignedTickets)
|
||||
{
|
||||
listItems.Add("**" + ticket.DiscordRelativeTime() + ":** <#" + ticket.channelID + "> by <@" + ticket.creatorID + ">\n");
|
||||
}
|
||||
|
||||
List<DiscordEmbedBuilder> embeds = new List<DiscordEmbedBuilder>();
|
||||
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<Page> listPages = new List<Page>();
|
||||
foreach (DiscordEmbedBuilder embed in embeds)
|
||||
{
|
||||
listPages.Add(new Page("", embed));
|
||||
}
|
||||
|
||||
await command.Interaction.SendPaginatedResponseAsync(true, command.User, listPages);
|
||||
}
|
||||
}
|
|
@ -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<DiscordChannel> channels = await command.Guild.GetChannelsAsync();
|
||||
IEnumerable<DiscordChannel> 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
|
||||
});
|
||||
}
|
||||
}
|
|
@ -1,276 +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<Database.Category> 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<Database.Category> verifiedCategories)
|
||||
{
|
||||
DiscordInteractionResponseBuilder builder = new DiscordInteractionResponseBuilder().WithContent(" ");
|
||||
int nrOfButtons = 0;
|
||||
for (int nrOfButtonRows = 0; nrOfButtonRows < 5 && nrOfButtons < verifiedCategories.Count; nrOfButtonRows++)
|
||||
{
|
||||
List<DiscordButtonComponent> buttonRow = new List<DiscordButtonComponent>();
|
||||
|
||||
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<Database.Category> verifiedCategories)
|
||||
{
|
||||
verifiedCategories = verifiedCategories.OrderBy(x => x.name).ToList();
|
||||
List<DiscordSelectComponent> selectionComponents = new List<DiscordSelectComponent>();
|
||||
int selectionOptions = 0;
|
||||
for (int selectionBoxes = 0; selectionBoxes < 5 && selectionOptions < verifiedCategories.Count; selectionBoxes++)
|
||||
{
|
||||
List<DiscordSelectComponentOption> categoryOptions = new List<DiscordSelectComponentOption>();
|
||||
|
||||
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.Select:
|
||||
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<Database.Ticket> 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);
|
||||
}
|
||||
}
|
|
@ -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<DiscordMember> 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<Database.StaffMember> 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;
|
||||
}
|
||||
}
|
|
@ -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);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -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);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,49 +0,0 @@
|
|||
using System.Threading.Tasks;
|
||||
using DSharpPlus.Entities;
|
||||
using DSharpPlus.SlashCommands;
|
||||
using DSharpPlus.SlashCommands.Attributes;
|
||||
using MySql.Data.MySqlClient;
|
||||
|
||||
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"
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,67 +0,0 @@
|
|||
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<Database.Message> messages = Database.GetAllMessages();
|
||||
if (!messages.Any())
|
||||
{
|
||||
await command.CreateResponseAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Red,
|
||||
Description = "There are no messages registered."
|
||||
}, true);
|
||||
return;
|
||||
}
|
||||
|
||||
List<string> listItems = new List<string>();
|
||||
foreach (Database.Message message in messages)
|
||||
{
|
||||
listItems.Add("**" + message.identifier + "** Added by <@" + message.userID + ">\n");
|
||||
}
|
||||
|
||||
LinkedList<string> 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")
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,42 +0,0 @@
|
|||
using System.Threading.Tasks;
|
||||
using DSharpPlus.Entities;
|
||||
using DSharpPlus.SlashCommands;
|
||||
using DSharpPlus.SlashCommands.Attributes;
|
||||
using MySql.Data.MySqlClient;
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
|
@ -1,26 +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("KarlofDuty/supportchild @ GitHub", "https://github.com/EmotionChild/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);
|
||||
}
|
||||
}
|
|
@ -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);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -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);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -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.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.WithFiles(new Dictionary<string, Stream> { { 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.WithFiles(new Dictionary<string, Stream> { { 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"
|
||||
}));
|
||||
}
|
||||
}
|
|
@ -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 + "."
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
|
@ -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;
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,95 +0,0 @@
|
|||
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<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>() ?? "supportchild";
|
||||
username = json.SelectToken("database.user")?.Value<string>() ?? "supportchild";
|
||||
password = json.SelectToken("database.password")?.Value<string>() ?? "";
|
||||
}
|
||||
}
|
|
@ -1,818 +0,0 @@
|
|||
using System;
|
||||
using System.Linq;
|
||||
using System.Collections.Generic;
|
||||
using DSharpPlus;
|
||||
using MySql.Data.MySqlClient;
|
||||
|
||||
namespace SupportChild;
|
||||
|
||||
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 +
|
||||
";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())
|
||||
{
|
||||
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");
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,275 +0,0 @@
|
|||
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 SupportChild.Commands;
|
||||
|
||||
namespace SupportChild;
|
||||
|
||||
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 ticket exists in the database and ticket notifications are enabled
|
||||
if (!Database.TryGetOpenTicket(e.Channel.Id, out Database.Ticket ticket) || !Config.ticketUpdatedNotifications)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Sends a DM to the assigned staff member if at least a day has gone by since the last message and the user sending the message isn't staff
|
||||
IReadOnlyList<DiscordMessage> messages = await e.Channel.GetMessagesAsync(2);
|
||||
if (messages.Count > 1 && messages[1].Timestamp < DateTimeOffset.UtcNow.AddDays(Config.ticketUpdatedNotificationDelay * -1) && !Database.IsStaff(e.Author.Id))
|
||||
{
|
||||
try
|
||||
{
|
||||
DiscordMember staffMember = await e.Guild.GetMemberAsync(ticket.assignedStaffID);
|
||||
await staffMember.SendMessageAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
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)
|
||||
{
|
||||
await channel.SendMessageAsync(new DiscordEmbedBuilder
|
||||
{
|
||||
Color = DiscordColor.Green,
|
||||
Description = "User '" + e.Member.Username + "#" + e.Member.Discriminator + "' has rejoined the server, and has been re-added to the ticket."
|
||||
});
|
||||
}
|
||||
}
|
||||
catch (Exception) { /* 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 "supportchild_closeconfirm":
|
||||
await CloseCommand.OnConfirmed(e.Interaction);
|
||||
return;
|
||||
case { } when e.Id.StartsWith("supportchild_newcommandbutton"):
|
||||
await NewCommand.OnCategorySelection(e.Interaction);
|
||||
return;
|
||||
case { } when e.Id.StartsWith("supportchild_newticketbutton"):
|
||||
await CreateButtonPanelCommand.OnButtonUsed(e.Interaction);
|
||||
return;
|
||||
case "right":
|
||||
return;
|
||||
case "left":
|
||||
return;
|
||||
case "rightskip":
|
||||
return;
|
||||
case "leftskip":
|
||||
return;
|
||||
case "stop":
|
||||
return;
|
||||
default:
|
||||
Logger.Warn("Unknown button press received! '" + e.Id + "'");
|
||||
return;
|
||||
}
|
||||
case ComponentType.Select:
|
||||
switch (e.Id)
|
||||
{
|
||||
case { } when e.Id.StartsWith("supportchild_newcommandselector"):
|
||||
await NewCommand.OnCategorySelection(e.Interaction);
|
||||
return;
|
||||
case { } when e.Id.StartsWith("supportchild_newticketselector"):
|
||||
await CreateSelectionBoxPanelCommand.OnSelectionMenuUsed(e.Interaction);
|
||||
return;
|
||||
default:
|
||||
Logger.Warn("Unknown selection box option received! '" + e.Id + "'");
|
||||
return;
|
||||
}
|
||||
case ComponentType.ActionRow:
|
||||
Logger.Warn("Unknown action row received! '" + e.Id + "'");
|
||||
return;
|
||||
case ComponentType.FormInput:
|
||||
Logger.Warn("Unknown form input received! '" + e.Id + "'");
|
||||
return;
|
||||
default:
|
||||
Logger.Warn("Unknown interaction type received! '" + e.Interaction.Data.ComponentType + "'");
|
||||
break;
|
||||
}
|
||||
}
|
||||
catch (DiscordException ex)
|
||||
{
|
||||
Logger.Error("Interaction Exception occurred: " + ex);
|
||||
Logger.Error("JsomMessage: " + ex.JsonMessage);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.Error("Interaction Exception occured: " + ex.GetType() + ": " + ex);
|
||||
}
|
||||
}
|
||||
|
||||
private static string ParseFailedCheck(SlashCheckBaseAttribute attr)
|
||||
{
|
||||
return attr switch
|
||||
{
|
||||
SlashRequireDirectMessageAttribute => "This command can only be used in direct messages!",
|
||||
SlashRequireOwnerAttribute => "Only the server owner can use that command!",
|
||||
SlashRequirePermissionsAttribute => "You don't have permission to do that!",
|
||||
SlashRequireBotPermissionsAttribute => "The bot doesn't have the required permissions to do that!",
|
||||
SlashRequireUserPermissionsAttribute => "You don't have permission to do that!",
|
||||
SlashRequireGuildAttribute => "This command has to be used in a Discord server!",
|
||||
_ => "Unknown Discord API error occured, please try again later."
|
||||
};
|
||||
}
|
||||
}
|
|
@ -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);
|
||||
}
|
||||
}
|
||||
}
|
55
SupportChild/Properties/Resources.Designer.cs
generated
55
SupportChild/Properties/Resources.Designer.cs
generated
|
@ -1,55 +0,0 @@
|
|||
//------------------------------------------------------------------------------
|
||||
// <auto-generated>
|
||||
// This code was generated by a tool.
|
||||
//
|
||||
// Changes to this file may cause incorrect behavior and will be lost if
|
||||
// the code is regenerated.
|
||||
// </auto-generated>
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
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));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,124 +0,0 @@
|
|||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<root>
|
||||
<!--
|
||||
Microsoft ResX Schema
|
||||
|
||||
Version 2.0
|
||||
|
||||
The primary goals of this format is to allow a simple XML format
|
||||
that is mostly human readable. The generation and parsing of the
|
||||
various data types are done through the TypeConverter classes
|
||||
associated with the data types.
|
||||
|
||||
Example:
|
||||
|
||||
... ado.net/XML headers & schema ...
|
||||
<resheader name="resmimetype">text/microsoft-resx</resheader>
|
||||
<resheader name="version">2.0</resheader>
|
||||
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
|
||||
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
|
||||
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
|
||||
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
|
||||
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
|
||||
<value>[base64 mime encoded serialized .NET Framework object]</value>
|
||||
</data>
|
||||
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
|
||||
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
|
||||
<comment>This is a comment</comment>
|
||||
</data>
|
||||
|
||||
There are any number of "resheader" rows that contain simple
|
||||
name/value pairs.
|
||||
|
||||
Each data row contains a name, and value. The row also contains a
|
||||
type or mimetype. Type corresponds to a .NET class that support
|
||||
text/value conversion through the TypeConverter architecture.
|
||||
Classes that don't support this are serialized and stored with the
|
||||
mimetype set.
|
||||
|
||||
The mimetype is used for serialized objects, and tells the
|
||||
ResXResourceReader how to depersist the object. This is currently not
|
||||
extensible. For a given mimetype the value must be set accordingly:
|
||||
|
||||
Note - application/x-microsoft.net.object.binary.base64 is the format
|
||||
that the ResXResourceWriter will generate, however the reader can
|
||||
read any of the formats listed below.
|
||||
|
||||
mimetype: application/x-microsoft.net.object.binary.base64
|
||||
value : The object must be serialized with
|
||||
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
|
||||
: and then encoded with base64 encoding.
|
||||
|
||||
mimetype: application/x-microsoft.net.object.soap.base64
|
||||
value : The object must be serialized with
|
||||
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
|
||||
: and then encoded with base64 encoding.
|
||||
|
||||
mimetype: application/x-microsoft.net.object.bytearray.base64
|
||||
value : The object must be serialized into a byte array
|
||||
: using a System.ComponentModel.TypeConverter
|
||||
: and then encoded with base64 encoding.
|
||||
-->
|
||||
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
|
||||
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
|
||||
<xsd:element name="root" msdata:IsDataSet="true">
|
||||
<xsd:complexType>
|
||||
<xsd:choice maxOccurs="unbounded">
|
||||
<xsd:element name="metadata">
|
||||
<xsd:complexType>
|
||||
<xsd:sequence>
|
||||
<xsd:element name="value" type="xsd:string" minOccurs="0" />
|
||||
</xsd:sequence>
|
||||
<xsd:attribute name="name" use="required" type="xsd:string" />
|
||||
<xsd:attribute name="type" type="xsd:string" />
|
||||
<xsd:attribute name="mimetype" type="xsd:string" />
|
||||
<xsd:attribute ref="xml:space" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
<xsd:element name="assembly">
|
||||
<xsd:complexType>
|
||||
<xsd:attribute name="alias" type="xsd:string" />
|
||||
<xsd:attribute name="name" type="xsd:string" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
<xsd:element name="data">
|
||||
<xsd:complexType>
|
||||
<xsd:sequence>
|
||||
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
|
||||
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
|
||||
</xsd:sequence>
|
||||
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
|
||||
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
|
||||
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
|
||||
<xsd:attribute ref="xml:space" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
<xsd:element name="resheader">
|
||||
<xsd:complexType>
|
||||
<xsd:sequence>
|
||||
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
|
||||
</xsd:sequence>
|
||||
<xsd:attribute name="name" type="xsd:string" use="required" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
</xsd:choice>
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
</xsd:schema>
|
||||
<resheader name="resmimetype">
|
||||
<value>text/microsoft-resx</value>
|
||||
</resheader>
|
||||
<resheader name="version">
|
||||
<value>2.0</value>
|
||||
</resheader>
|
||||
<resheader name="reader">
|
||||
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
</resheader>
|
||||
<resheader name="writer">
|
||||
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
</resheader>
|
||||
<assembly alias="System.Windows.Forms" name="System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
|
||||
<data name="default_config" type="System.Resources.ResXFileRef, System.Windows.Forms">
|
||||
<value>..\default_config.yml;System.Byte[], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
</data>
|
||||
</root>
|
|
@ -1,150 +0,0 @@
|
|||
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 "<add-token-here>" or "")
|
||||
{
|
||||
Logger.Fatal("You need to set your bot token in the config and start the bot again.");
|
||||
throw new ArgumentException("Invalid Discord bot token");
|
||||
}
|
||||
|
||||
// Database connection and setup
|
||||
try
|
||||
{
|
||||
Logger.Log("Connecting to database... (" + Config.hostName + ":" + Config.port + ")");
|
||||
Database.SetConnectionString(Config.hostName, Config.port, Config.database, Config.username, Config.password);
|
||||
Database.SetupTables();
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Logger.Fatal("Could not set up database tables, please confirm connection settings, status of the server and permissions of MySQL user. Error: " + e);
|
||||
throw;
|
||||
}
|
||||
|
||||
Logger.Log("Setting up Discord client...");
|
||||
|
||||
// Setting up client configuration
|
||||
DiscordConfiguration cfg = new DiscordConfiguration
|
||||
{
|
||||
Token = Config.token,
|
||||
TokenType = TokenType.Bot,
|
||||
MinimumLogLevel = Config.logLevel,
|
||||
AutoReconnect = true,
|
||||
Intents = DiscordIntents.All
|
||||
};
|
||||
|
||||
discordClient = new DiscordClient(cfg);
|
||||
|
||||
Logger.Log("Hooking events...");
|
||||
discordClient.Ready += EventHandler.OnReady;
|
||||
discordClient.GuildAvailable += EventHandler.OnGuildAvailable;
|
||||
discordClient.ClientErrored += EventHandler.OnClientError;
|
||||
discordClient.MessageCreated += EventHandler.OnMessageCreated;
|
||||
discordClient.GuildMemberAdded += EventHandler.OnMemberAdded;
|
||||
discordClient.GuildMemberRemoved += EventHandler.OnMemberRemoved;
|
||||
discordClient.ComponentInteractionCreated += EventHandler.OnComponentInteractionCreated;
|
||||
|
||||
discordClient.UseInteractivity(new InteractivityConfiguration
|
||||
{
|
||||
AckPaginationButtons = true,
|
||||
PaginationBehaviour = PaginationBehaviour.Ignore,
|
||||
PaginationDeletion = PaginationDeletion.DeleteMessage,
|
||||
Timeout = TimeSpan.FromMinutes(15)
|
||||
});
|
||||
|
||||
Logger.Log("Registering commands...");
|
||||
commands = discordClient.UseSlashCommands();
|
||||
|
||||
commands.RegisterCommands<AddCategoryCommand>();
|
||||
commands.RegisterCommands<AddCommand>();
|
||||
commands.RegisterCommands<AddMessageCommand>();
|
||||
commands.RegisterCommands<AddStaffCommand>();
|
||||
commands.RegisterCommands<AssignCommand>();
|
||||
commands.RegisterCommands<BlacklistCommand>();
|
||||
commands.RegisterCommands<CloseCommand>();
|
||||
commands.RegisterCommands<CreateButtonPanelCommand>();
|
||||
commands.RegisterCommands<CreateSelectionBoxPanelCommand>();
|
||||
commands.RegisterCommands<ListAssignedCommand>();
|
||||
commands.RegisterCommands<ListCommand>();
|
||||
commands.RegisterCommands<ListOpen>();
|
||||
commands.RegisterCommands<ListUnassignedCommand>();
|
||||
commands.RegisterCommands<MoveCommand>();
|
||||
commands.RegisterCommands<NewCommand>();
|
||||
commands.RegisterCommands<RandomAssignCommand>();
|
||||
commands.RegisterCommands<RemoveCategoryCommand>();
|
||||
commands.RegisterCommands<RemoveMessageCommand>();
|
||||
commands.RegisterCommands<RemoveStaffCommand>();
|
||||
commands.RegisterCommands<SayCommand>();
|
||||
commands.RegisterCommands<SetSummaryCommand>();
|
||||
commands.RegisterCommands<StatusCommand>();
|
||||
commands.RegisterCommands<SummaryCommand>();
|
||||
commands.RegisterCommands<ToggleActiveCommand>();
|
||||
commands.RegisterCommands<TranscriptCommand>();
|
||||
commands.RegisterCommands<UnassignCommand>();
|
||||
commands.RegisterCommands<UnblacklistCommand>();
|
||||
commands.RegisterCommands<AdminCommands>();
|
||||
|
||||
Logger.Log("Hooking command events...");
|
||||
commands.SlashCommandErrored += EventHandler.OnCommandError;
|
||||
|
||||
Logger.Log("Connecting to Discord...");
|
||||
await discordClient.ConnectAsync();
|
||||
}
|
||||
}
|
|
@ -1,70 +0,0 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<ApplicationIcon>ellie_icon.ico</ApplicationIcon>
|
||||
<TargetFramework>net6.0</TargetFramework>
|
||||
<RuntimeIdentifiers>win-x64;linux-x64</RuntimeIdentifiers>
|
||||
|
||||
<StartupObject>SupportChild.SupportChild</StartupObject>
|
||||
<Authors>EmotionChild</Authors>
|
||||
<Product />
|
||||
<PackageProjectUrl>https://github.com/EmotionChild/SupportChild</PackageProjectUrl>
|
||||
<RepositoryUrl>https://github.com/EmotionChild/SupportChild</RepositoryUrl>
|
||||
<RepositoryType>Git</RepositoryType>
|
||||
<PackageLicenseFile>LICENSE</PackageLicenseFile>
|
||||
<PackageIconUrl>https://cdn.discordapp.com/attachments/765441543100170271/914327948667011132/Ellie_Concept_2_transparent_ver.png</PackageIconUrl>
|
||||
<Description>A Discord support ticket bot built for the Ellie's home server</Description>
|
||||
<NeutralLanguage>en</NeutralLanguage>
|
||||
<Version>1.3.0</Version>
|
||||
<PackageVersion>1.3.0</PackageVersion>
|
||||
<AssemblyVersion>3.0.0.1</AssemblyVersion>
|
||||
<FileVersion>3.0.0.1</FileVersion>
|
||||
</PropertyGroup>
|
||||
|
||||
<PropertyGroup Condition=" '$(Configuration)' == 'Debug' ">
|
||||
<DebugType>full</DebugType>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="DSharpPlus" Version="4.2.0" />
|
||||
<PackageReference Include="DSharpPlus.Interactivity" Version="4.2.0" />
|
||||
<PackageReference Include="DSharpPlus.SlashCommands" Version="4.2.0" />
|
||||
<PackageReference Include="Gress" Version="2.0.1" />
|
||||
<PackageReference Include="JsonExtensions" Version="1.2.0" />
|
||||
<PackageReference Include="MiniRazor.CodeGen" Version="2.2.1" />
|
||||
<PackageReference Include="MySql.Data" Version="8.0.30" />
|
||||
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
|
||||
<PackageReference Include="Polly" Version="7.2.3" />
|
||||
<PackageReference Include="Superpower" Version="3.0.0" />
|
||||
<PackageReference Include="Tyrrrz.Extensions" Version="1.6.5" />
|
||||
<PackageReference Include="WebMarkupMin.Core" Version="2.9.0" />
|
||||
<PackageReference Include="YamlDotNet" Version="12.0.0" />
|
||||
</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>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Update="Properties\Resources.Designer.cs">
|
||||
<DesignTime>True</DesignTime>
|
||||
<AutoGen>True</AutoGen>
|
||||
<DependentUpon>Resources.resx</DependentUpon>
|
||||
</Compile>
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
|
@ -1,53 +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
|
||||
{
|
||||
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";
|
||||
}
|
||||
}
|
|
@ -1,65 +0,0 @@
|
|||
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<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 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;
|
||||
}
|
||||
}
|
Binary file not shown.
139
Transcriber.cs
Normal file
139
Transcriber.cs
Normal file
|
@ -0,0 +1,139 @@
|
|||
using System;
|
||||
using System.IO;
|
||||
using System.IO.Compression;
|
||||
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);
|
||||
|
||||
string htmlPath = GetHtmlPath(ticketID);
|
||||
string zipPath = GetZipPath(ticketID);
|
||||
string assetDirPath = GetAssetDirPath(ticketID);
|
||||
|
||||
string assetDirName = GetAssetDirName(ticketID);
|
||||
string htmlFilename = GetHTMLFilename(ticketID);
|
||||
|
||||
if (File.Exists(htmlPath))
|
||||
{
|
||||
File.Delete(htmlPath);
|
||||
}
|
||||
|
||||
if (File.Exists(zipPath))
|
||||
{
|
||||
File.Delete(zipPath);
|
||||
}
|
||||
|
||||
if (Directory.Exists(assetDirPath))
|
||||
{
|
||||
Directory.Delete(assetDirPath, true);
|
||||
}
|
||||
|
||||
Channel channel = await discordClient.GetChannelAsync(new Snowflake(channelID));
|
||||
Guild guild = await discordClient.GetGuildAsync(channel.GuildId);
|
||||
|
||||
ExportRequest request = new(
|
||||
guild,
|
||||
channel,
|
||||
htmlPath,
|
||||
assetDirPath,
|
||||
ExportFormat.HtmlDark,
|
||||
null,
|
||||
null,
|
||||
PartitionLimit.Null,
|
||||
MessageFilter.Null,
|
||||
true,
|
||||
true,
|
||||
true,
|
||||
"en-SE",
|
||||
true
|
||||
);
|
||||
|
||||
await exporter.ExportChannelAsync(request);
|
||||
|
||||
string[] assetFiles;
|
||||
try
|
||||
{
|
||||
assetFiles = Directory.GetFiles(assetDirPath);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
assetFiles = [];
|
||||
}
|
||||
|
||||
if (assetFiles.Length > 0)
|
||||
{
|
||||
using (ZipArchive zip = ZipFile.Open(zipPath, ZipArchiveMode.Create))
|
||||
{
|
||||
zip.CreateEntryFromFile(htmlPath, htmlFilename, CompressionLevel.SmallestSize);
|
||||
foreach (string assetFile in assetFiles)
|
||||
{
|
||||
zip.CreateEntryFromFile(assetFile, assetDirName + "/" + Path.GetFileName(assetFile), CompressionLevel.SmallestSize);
|
||||
}
|
||||
}
|
||||
|
||||
Directory.Delete(assetDirPath, true);
|
||||
}
|
||||
}
|
||||
|
||||
private static string GetTranscriptDir()
|
||||
{
|
||||
string transcriptDir = "./transcripts";
|
||||
if (!string.IsNullOrEmpty(SupportChild.commandLineArgs.transcriptDir))
|
||||
{
|
||||
transcriptDir = SupportChild.commandLineArgs.transcriptDir;
|
||||
}
|
||||
else if (!string.IsNullOrEmpty(Config.transcriptDir))
|
||||
{
|
||||
transcriptDir = Config.transcriptDir;
|
||||
}
|
||||
|
||||
if (!Directory.Exists(transcriptDir))
|
||||
{
|
||||
Directory.CreateDirectory(transcriptDir);
|
||||
}
|
||||
|
||||
return transcriptDir;
|
||||
}
|
||||
|
||||
internal static string GetHtmlPath(uint ticketNumber)
|
||||
{
|
||||
return GetTranscriptDir() + "/" + GetHTMLFilename(ticketNumber);
|
||||
}
|
||||
|
||||
internal static string GetZipPath(uint ticketNumber)
|
||||
{
|
||||
return GetTranscriptDir() + "/" + GetZipFilename(ticketNumber);
|
||||
}
|
||||
|
||||
internal static string GetAssetDirPath(uint ticketNumber)
|
||||
{
|
||||
return GetTranscriptDir() + "/" + GetAssetDirName(ticketNumber);
|
||||
}
|
||||
|
||||
internal static string GetAssetDirName(uint ticketNumber)
|
||||
{
|
||||
return "ticket-" + ticketNumber.ToString("00000") + "-assets";
|
||||
}
|
||||
|
||||
internal static string GetHTMLFilename(uint ticketNumber)
|
||||
{
|
||||
return "ticket-" + ticketNumber.ToString("00000") + ".html";
|
||||
}
|
||||
|
||||
internal static string GetZipFilename(uint ticketNumber)
|
||||
{
|
||||
return "ticket-" + ticketNumber.ToString("00000") + ".zip";
|
||||
}
|
||||
}
|
203
Utilities.cs
Normal file
203
Utilities.cs
Normal file
|
@ -0,0 +1,203 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Threading.Tasks;
|
||||
using DSharpPlus.Entities;
|
||||
|
||||
namespace SupportChild;
|
||||
|
||||
public static class Extensions
|
||||
{
|
||||
public static bool ContainsAny(this string haystack, params string[] needles)
|
||||
{
|
||||
return needles.Any(haystack.Contains);
|
||||
}
|
||||
|
||||
public static bool ContainsAny(this string haystack, params char[] needles)
|
||||
{
|
||||
return needles.Any(haystack.Contains);
|
||||
}
|
||||
}
|
||||
|
||||
public static class Utilities
|
||||
{
|
||||
private static readonly Random rng = new Random();
|
||||
|
||||
public class File(string fileName, Stream contents)
|
||||
{
|
||||
public string fileName = fileName;
|
||||
public Stream contents = contents;
|
||||
}
|
||||
|
||||
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>> GetVerifiedCategories()
|
||||
{
|
||||
List<Database.Category> verifiedCategories = new List<Database.Category>();
|
||||
foreach (Database.Category category in Database.GetAllCategories())
|
||||
{
|
||||
DiscordChannel channel = null;
|
||||
try
|
||||
{
|
||||
channel = await SupportChild.client.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();
|
||||
}
|
||||
|
||||
public static DiscordColor StringToColor(string color)
|
||||
{
|
||||
switch (color.ToLower(CultureInfo.InvariantCulture))
|
||||
{
|
||||
case "black":
|
||||
return DiscordColor.Black;
|
||||
case "white":
|
||||
return DiscordColor.White;
|
||||
case "gray":
|
||||
return DiscordColor.Gray;
|
||||
case "darkgray":
|
||||
return DiscordColor.DarkGray;
|
||||
case "lightgray":
|
||||
return DiscordColor.LightGray;
|
||||
case "verydarkgray":
|
||||
return DiscordColor.VeryDarkGray;
|
||||
case "blurple":
|
||||
return DiscordColor.Blurple;
|
||||
case "grayple":
|
||||
return DiscordColor.Grayple;
|
||||
case "darkbutnotblack":
|
||||
return DiscordColor.DarkButNotBlack;
|
||||
case "notquiteblack":
|
||||
return DiscordColor.NotQuiteBlack;
|
||||
case "red":
|
||||
return DiscordColor.Red;
|
||||
case "darkred":
|
||||
return DiscordColor.DarkRed;
|
||||
case "green":
|
||||
return DiscordColor.Green;
|
||||
case "darkgreen":
|
||||
return DiscordColor.DarkGreen;
|
||||
case "blue":
|
||||
return DiscordColor.Blue;
|
||||
case "darkblue":
|
||||
return DiscordColor.DarkBlue;
|
||||
case "yellow":
|
||||
return DiscordColor.Yellow;
|
||||
case "cyan":
|
||||
return DiscordColor.Cyan;
|
||||
case "magenta":
|
||||
return DiscordColor.Magenta;
|
||||
case "teal":
|
||||
return DiscordColor.Teal;
|
||||
case "aquamarine":
|
||||
return DiscordColor.Aquamarine;
|
||||
case "gold":
|
||||
return DiscordColor.Gold;
|
||||
case "goldenrod":
|
||||
return DiscordColor.Goldenrod;
|
||||
case "azure":
|
||||
return DiscordColor.Azure;
|
||||
case "rose":
|
||||
return DiscordColor.Rose;
|
||||
case "springgreen":
|
||||
return DiscordColor.SpringGreen;
|
||||
case "chartreuse":
|
||||
return DiscordColor.Chartreuse;
|
||||
case "orange":
|
||||
return DiscordColor.Orange;
|
||||
case "purple":
|
||||
return DiscordColor.Purple;
|
||||
case "violet":
|
||||
return DiscordColor.Violet;
|
||||
case "brown":
|
||||
return DiscordColor.Brown;
|
||||
case "hotpink":
|
||||
return DiscordColor.HotPink;
|
||||
case "lilac":
|
||||
return DiscordColor.Lilac;
|
||||
case "cornflowerblue":
|
||||
return DiscordColor.CornflowerBlue;
|
||||
case "midnightblue":
|
||||
return DiscordColor.MidnightBlue;
|
||||
case "wheat":
|
||||
return DiscordColor.Wheat;
|
||||
case "indianred":
|
||||
return DiscordColor.IndianRed;
|
||||
case "turquoise":
|
||||
return DiscordColor.Turquoise;
|
||||
case "sapgreen":
|
||||
return DiscordColor.SapGreen;
|
||||
case "phthaloblue":
|
||||
return DiscordColor.PhthaloBlue;
|
||||
case "phthalogreen":
|
||||
return DiscordColor.PhthaloGreen;
|
||||
case "sienna":
|
||||
return DiscordColor.Sienna;
|
||||
default:
|
||||
try
|
||||
{
|
||||
return new DiscordColor(color);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return DiscordColor.None;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,48 +1,80 @@
|
|||
bot:
|
||||
# Bot token.
|
||||
token: "<add-token-here>"
|
||||
# Channel where ticket logs are posted (recommended)
|
||||
|
||||
# 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
|
||||
|
||||
# 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
|
||||
|
||||
# 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.
|
||||
|
||||
# Whether 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.
|
||||
|
||||
# If set to true the rassign 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
|
||||
|
||||
# Sets the type of activity for the bot to display in its presence status.
|
||||
# Possible values are: Playing, Streaming, ListeningTo, Watching, Competing, Custom.
|
||||
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
|
||||
|
||||
# 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
|
||||
|
||||
# Number of tickets a single user can have open at a time, staff members are excluded from this.
|
||||
ticket-limit: 5
|
||||
|
||||
# Pins the first message in a ticket to allow for quick navigation to the top in large tickets.
|
||||
pin-first-message: true
|
||||
|
||||
# Ticket transcript location, can be overridden using command line arguments.
|
||||
transcript-dir: "./transcripts"
|
||||
|
||||
notifications:
|
||||
# Notifies the assigned staff member when a new message is posted in a ticket if the ticket has been silent for a configurable amount of time
|
||||
# Notifies the assigned staff member when a new message is posted in a ticket if the ticket has been silent for a configurable amount of time.
|
||||
# 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
|
||||
|
||||
# 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
|
||||
|
||||
# Notifies the user opening the ticket that their ticket was closed and includes the transcript.
|
||||
closing: true
|
||||
|
||||
interviews:
|
||||
# Enable the interview system. You must set up interview templates before you can start using it.
|
||||
# Any existing interviews can still be completed while interviews are disabled, but new ones will not be created.
|
||||
enabled: true
|
||||
|
||||
# Whether to delete the interview question and answer messages after an interview summary is posted.
|
||||
delete-messages-after-summary: true
|
||||
|
||||
# Whether to delete the interview question and answer messages after an interview ends without a summary.
|
||||
delete-messages-after-no-summary: true
|
||||
|
||||
database:
|
||||
# Address and port of the mysql server
|
||||
# Address and port of the mysql server.
|
||||
address: "127.0.0.1"
|
||||
port: 3306
|
||||
# Name of the database to use
|
||||
|
||||
# Name of the database to use.
|
||||
name: "supportchild"
|
||||
# Username and password for authentication
|
||||
|
||||
# Username and password for authentication.
|
||||
user: ""
|
||||
password: ""
|
41
docs/Commands.md
Normal file
41
docs/Commands.md
Normal file
|
@ -0,0 +1,41 @@
|
|||
# Commands
|
||||
These are all the commands you can use with the bot. Remember to set up your command permissions after you start the bot up, otherwise everyone will be able to use all commands.
|
||||
|
||||
| Command | Description |
|
||||
|----------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------|
|
||||
| `/add <user>` | Add a user to the ticket. |
|
||||
| `/addcategory <title> <category>` | Adds a category for users to open tickets in. The title is what will be used on buttons and in selection menus. |
|
||||
| `/addmessage <identifier> <message>` | Adds a new message for the `/say` command. The identifier is the word used in the say command and the message is what the bot prints. |
|
||||
| `/addstaff <user>` | Registers a user as a staff member for ticket assignment. |
|
||||
| `/assign (user)` | Assigns a ticket to a staff member. Assigns to self if no mention or id is provided. |
|
||||
| `/blacklist <user>` | Blocks a user from opening tickets. |
|
||||
| `/close` | Closes a ticket channel. The ticket transcript is optionally sent to the ticket creator. |
|
||||
| `/createbuttonpanel` | Creates a panel of buttons for users to open tickets with, one for each saved category. |
|
||||
| `/createselectionbox (placeholder)` | Creates a selection menu for users to open tickets with. Placeholder is the text shown on the selection menu before anything is selected. |
|
||||
| `/interview restart` | Restarts the interview in the current channel. It will use a new template if one is available. |
|
||||
| `/interview stop` | Stops the ongoing interview in this channel. |
|
||||
| `/interviewtemplate get <category>` | Get the json interview template for a specific category. A basic one will be returned if one doesn't exist. |
|
||||
| `/interviewtemplate set <template>` | Set the interview template for a category. The category is specified by the ID in the template file. |
|
||||
| `/interviewtemplate delete <category>` | Deletes the interview template for a category. |
|
||||
| `/list (user)` | Lists a user's open and closed tickets. |
|
||||
| `/listassigned (user)` | Lists all of a staff member's assigned tickets. |
|
||||
| `/listinvalid` | Lists tickets which channels have been deleted or the creator has left the server. |
|
||||
| `/listopen` | Lists a number of the oldest still open tickets, default is 20. Only shows tickets the user has access to read. |
|
||||
| `/listunassigned` | Lists all unassigned tickets. Only shows tickets the user has access to read. |
|
||||
| `/move <category>` | Moves a ticket to a specific category by partial name. |
|
||||
| `/new` | Opens a new ticket channel. |
|
||||
| `/rassign (role)` | Randomly assigns a ticket to an active staff member. If a role is provided only staff members with that role are considered. |
|
||||
| `/removecategory <category>` | Removes a category from the bot. |
|
||||
| `/removemessage <identifier>` | Removes message from the database. |
|
||||
| `/removestaff <user>` | Removes a user from staff. |
|
||||
| `/say (identifier)` | Prints a message with information from staff. Use with no arguments to list identifiers. |
|
||||
| `/setsummary <summary>` | Sets a summary for a ticket which can be viewed using the `/summary` command. |
|
||||
| `/status` | Shows a status message about the bot with info such as number of tickets and which version is running. |
|
||||
| `/summary` | Shows some information about a ticket and its summary if set. |
|
||||
| `/toggleactive (user)` | Toggles whether a staff member counts as active or not when automatic assigning occurs. |
|
||||
| `/transcript (ticket id)` | Generates a ticket transcript as an html file. |
|
||||
| `/unassign` | Unassigns a ticket from the currently assigned staff member. |
|
||||
| `/unblacklist <user>` | Un-blacklists users from opening tickets. |
|
||||
| `/admin reload` | Reloads the config. |
|
||||
| `/admin setticket (channel)` | Makes the current channel a ticket. WARNING: Anyone will be able to delete the channel using /close. |
|
||||
| `/admin unsetticket (ticket id)` | Deletes a ticket from the ticket system without deleting the Discord channel. |
|
292
docs/InterviewTemplates.md
Normal file
292
docs/InterviewTemplates.md
Normal file
|
@ -0,0 +1,292 @@
|
|||
# Writing Interview Templates
|
||||
|
||||
The bot can automatically interview users when they open a ticket. These interviews are defined in interview templates.
|
||||
The templates each apply to a single ticket category so you can have different interviews depending on the type of ticket.
|
||||
|
||||
## Interview Template Commands
|
||||
|
||||
Whether you already have a template or not the first step is always to use the `/interviewtemplate get <category>` command on the
|
||||
ticket category you want to edit. If you haven't yet, use the `/addcategory` command on the category to register it with the bot.
|
||||
|
||||
The bot will reply with a JSON template file which you can edit and upload using the `/interviewtemplate set` command.
|
||||
|
||||
You can also delete an interview template using the `/interviewtemplate delete` command.
|
||||
|
||||
## Writing Your First Interview Template
|
||||
|
||||
Use the get command to get a default template for the ticket category you want to edit:
|
||||
```
|
||||
/interviewtemplate get <category>
|
||||
```
|
||||
|
||||
The bot will reply with a JSON template file for you to edit using your preferred text editor.
|
||||
|
||||
**Note:** It is highly recommended to use integrated template validation in your text editor, see below.
|
||||
|
||||
When you are done editing it you can upload it to the bot using the set command:
|
||||
```
|
||||
/interviewtemplate set <category>
|
||||
```
|
||||
|
||||
The bot will check that your template is correctly formatted and provide feedback if it is not.
|
||||
|
||||
## Automatic Template Validation and Suggestions in Text Editors
|
||||
|
||||
It is highly recommended to use the interview template JSON schema to get live validation of your template while you write it:
|
||||
|
||||
### Guides for Different Editors:
|
||||
|
||||
<details>
|
||||
|
||||
<summary>VS Code</summary>
|
||||
|
||||
1. Go to `File->Preferences->Settings`.
|
||||
2. Search for `json schema`.
|
||||
3. Click `Edit in settings.json` on the schema setting.
|
||||
4. Set the `json.schemas` property to the following to automatically validate template files:
|
||||
```json
|
||||
{
|
||||
"json.schemas":
|
||||
[
|
||||
{
|
||||
"fileMatch":
|
||||
[
|
||||
"interview-template*.json"
|
||||
],
|
||||
"url": "https://toastielab.dev/Emotions-stuff/SupportChild/raw/branch/main/Interviews/interview_template.schema.json"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
5. Open an interview template, you should now get suggestions for things like message types and color names, and error highlighting for any invalid sections.
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
|
||||
<summary>Jetbrains Editors</summary>
|
||||
|
||||
1. Go to `File->Settings->Languages & Frameworks->Schemas->JSON Schema Mapping`.
|
||||
2. Add a new schema with the following URL: `https://toastielab.dev/Emotions-stuff/SupportChild/raw/branch/main/Interviews/interview_template.schema.json`.
|
||||
3. Restart your editor and all interview templates should now automatically be set to the correct schema in the bottom right of the window.
|
||||
|
||||
</details>
|
||||
|
||||
## Interview Template Format
|
||||
|
||||
This section lists all the properties that can be used in an interview template.
|
||||
If you have set up your editor as suggested above it will handle a lot of this for you automatically.
|
||||
|
||||
Here is a simple example of an interview asking a user for their favourite colour out of the different button colours:
|
||||
```json
|
||||
{
|
||||
"category-id": "1006863882301755503",
|
||||
"interview":
|
||||
{
|
||||
"message": "What is your favourite colour?",
|
||||
"message-type": "BUTTONS",
|
||||
"color": "BLUE",
|
||||
"summary-field": "Favourite colour",
|
||||
"steps":
|
||||
{
|
||||
"Blue":
|
||||
{
|
||||
"message": "Summary",
|
||||
"message-type": "END_WITH_SUMMARY",
|
||||
"color": "BLUE",
|
||||
"button-style": "PRIMARY",
|
||||
"steps": {}
|
||||
},
|
||||
"Gray":
|
||||
{
|
||||
"message": "Summary",
|
||||
"message-type": "END_WITH_SUMMARY",
|
||||
"color": "GRAY",
|
||||
"button-style": "SECONDARY",
|
||||
"steps": {}
|
||||
},
|
||||
"Green":
|
||||
{
|
||||
"message": "Summary",
|
||||
"message-type": "END_WITH_SUMMARY",
|
||||
"color": "GREEN",
|
||||
"button-style": "SUCCESS",
|
||||
"steps": {}
|
||||
},
|
||||
"Red":
|
||||
{
|
||||
"message": "Summary",
|
||||
"message-type": "END_WITH_SUMMARY",
|
||||
"color": "RED",
|
||||
"button-style": "DANGER",
|
||||
"steps": {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Template Root
|
||||
|
||||
| Property | Required | Description |
|
||||
|----------------------------------------------------------------------------|----------|--------------------------------------------------------------------------------------------------------------------------------------|
|
||||
| `category-id` | Yes | The id of the category this template applies to. You can change this and re-upload the template to apply it to a different category. |
|
||||
| `interview` | Yes | Contains the interview conversation tree, starting with one interview step which branches into many. |
|
||||
|
||||
### Interview Paths
|
||||
|
||||
<!-- This is an HTML table to allow for markdown formatting inside -->
|
||||
<table>
|
||||
<tbody>
|
||||
<tr>
|
||||
<th>Property </th>
|
||||
<th>Required</th>
|
||||
<th>Type</th>
|
||||
<th>Description</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
<!-- For whatever reason there must be an empty row here -->
|
||||
|
||||
`message`
|
||||
</td>
|
||||
<td>Yes</td>
|
||||
<td>String</td>
|
||||
<td>
|
||||
The text in the embed message that will be sent to the user when they reach this step.
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
`message-type`
|
||||
</td>
|
||||
<td>Yes</td>
|
||||
<td>String</td>
|
||||
<td>
|
||||
The type of message, decides what the bot will do when the user gets to this step. See the list of message types below for more info.
|
||||
|
||||
<!-- For whatever reason this tag cannot be indented -->
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
<!-- For whatever reason there must be an empty row here -->
|
||||
|
||||
`color`
|
||||
</td>
|
||||
<td>Yes</td>
|
||||
<td>String</td>
|
||||
<td>
|
||||
|
||||
Colour of the message embed. You can either enter a colour name or a hexadecimal RGB value.
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
`steps`
|
||||
</td>
|
||||
<td>No</td>
|
||||
<td>Steps</td>
|
||||
<td>
|
||||
One or more interview steps. The name of the step is used as a regex match against the user's answer,
|
||||
except for selection boxes and buttons where each step becomes a button or selection option.
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
`heading`
|
||||
</td>
|
||||
<td>No</td>
|
||||
<td>String</td>
|
||||
<td>
|
||||
The title of the embed message.
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
`summary-field`
|
||||
</td>
|
||||
<td>No</td>
|
||||
<td>String</td>
|
||||
<td>
|
||||
When an interview ends all previous answers with this property will be put in a summary.
|
||||
If this property is not specified the answer will not be shown in the summary.
|
||||
The value of this property is the name which will be displayed next to the answer in the summary.
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
`button-style`
|
||||
</td>
|
||||
<td>No</td>
|
||||
<td>String</td>
|
||||
<td>
|
||||
The style of this step's button. Requires that the parent step is a `BUTTONS` step.
|
||||
Must be one of the following:
|
||||
- `PRIMARY`
|
||||
- `SECONDARY`
|
||||
- `SUCCESS`
|
||||
- `DANGER`
|
||||
|
||||
Default style is `SECONDARY`.
|
||||
|
||||
![Button Example](./img/buttonExample.png)
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
`selector-description`
|
||||
</td>
|
||||
<td>No</td>
|
||||
<td>String</td>
|
||||
<td>
|
||||
Description for this option in the parent step's selection box. Requires that the parent step is a `TEXT_SELECTOR`.
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
`selector-placeholder`
|
||||
</td>
|
||||
<td>No</td>
|
||||
<td>String</td>
|
||||
<td>
|
||||
The placeholder text shown before a value is selected in the selection box. Requires that this step is a `TEXT_SELECTOR`.
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
`max-length`
|
||||
</td>
|
||||
<td>No</td>
|
||||
<td>Number</td>
|
||||
<td>
|
||||
The maximum length of the user's response message. Requires that this step is a `TEXT_INPUT`.
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
`min-length`
|
||||
</td>
|
||||
<td>No</td>
|
||||
<td>Number</td>
|
||||
<td>
|
||||
The minimum length of the user's response message. Requires that this step is a `TEXT_INPUT`.
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
### Message Types
|
||||
|
||||
| Message Type | Description |
|
||||
|------------------------|------------------------------------------------------------------------------------------------------------------------------------------|
|
||||
| `ERROR` | Sends an error message but does not stop the interview. The interview remains on the same step as before allowing the user to try again. |
|
||||
| `END_WITH_SUMMARY` | End the interview and create a summary of the answers. |
|
||||
| `END_WITHOUT_SUMMARY` | End the interview with a simple message without a summary. |
|
||||
| `BUTTONS` | Creates a message with one button per child step where the button text is the name of the child step. |
|
||||
| `TEXT_SELECTOR` | Creates a selection box with one option per child step where the option text is the name of the child step. |
|
||||
| `USER_SELECTOR` | Creates a selection box where the user can select a user from the Discord server. The value used for the summary is the user's mention. |
|
||||
| `ROLE_SELECTOR` | Same as above but for a role. |
|
||||
| `MENTIONABLE_SELECTOR` | Same as above but works for both roles and users. |
|
||||
| `CHANNEL_SELECTOR` | Same as above but for channels and categories. |
|
||||
| `TEXT_INPUT` | Lets the user reply to the bot message with their own text. |
|
BIN
docs/img/buttonExample.png
Normal file
BIN
docs/img/buttonExample.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 6.1 KiB |
Before Width: | Height: | Size: 4.2 KiB After Width: | Height: | Size: 4.2 KiB |
BIN
lib/DiscordChatExporter.Core.dll
Normal file
BIN
lib/DiscordChatExporter.Core.dll
Normal file
Binary file not shown.
Loading…
Reference in a new issue