Compare commits

...

188 commits
v1.1.0 ... main

Author SHA1 Message Date
c9ba8b4952 Update README.md
All checks were successful
Toastie-stuff/SupportChild/pipeline/head This commit looks good
2025-01-04 14:34:51 +00:00
5aec1b7e7b Update README.md
All checks were successful
Toastie-stuff/SupportChild/pipeline/head This commit looks good
2025-01-04 14:32:55 +00:00
66d67257be
Fix logging issues
All checks were successful
Toastie-stuff/SupportChild/pipeline/head This commit looks good
2024-12-27 20:22:00 +13:00
c6579beba2
Refactored log channel handling 2024-12-27 20:17:14 +13:00
dac221246c
Refactor random assignment and make it only assign staff with read access 2024-12-27 19:43:06 +13:00
12337101b7
Only log guilds and roles once after connecting 2024-12-27 19:39:52 +13:00
e3984ab968
Added transcript dir to config 2024-12-27 19:36:02 +13:00
0304744d9d
Improved unassign log messages 2024-12-27 19:30:30 +13:00
2b73548b7a
Remove unnecessary parameter 2024-12-27 19:27:51 +13:00
a9c28a04b6
Add non-selfcontained build to jenkins 2024-12-27 19:26:24 +13:00
f5d044512a
Unassign staff member from tickets when they are removed from staff 2024-12-27 19:23:54 +13:00
0ee12cb1ec
Downgrade GitInfo due to some new license issue 2024-12-27 19:18:16 +13:00
586f9c8f07
Improved feedback message for /addstaff when user is already staff 2024-12-27 18:18:23 +13:00
c6c7379f20
Make some messages ephemeral 2024-12-27 18:15:54 +13:00
8e7a21c81a
Fix interview category id type in schema 2024-12-27 18:14:20 +13:00
ad940c6167
Set the compression method to prioritize file size 2024-12-27 18:09:50 +13:00
a88997e8e5
Update InterviewTemplates.md 2024-12-27 18:08:34 +13:00
384f046915
Update command documentation 2024-12-27 18:06:25 +13:00
bb9ef65e42
Update interview set feedback message 2024-12-27 18:01:19 +13:00
c12c17de41
Updated author with my new username 2024-12-27 17:49:47 +13:00
bfd3196374
Updated formatting. 2024-12-27 17:46:22 +13:00
56d3c6b089
Delete the notification when the bot pins a message 2024-12-27 17:30:05 +13:00
7b64129cc1
Updated descriptions in schema 2024-12-27 17:29:06 +13:00
316e814248
More path -> step 2024-12-27 17:26:31 +13:00
8820549927
Normalised interview terminology for "question", "path", "step" to use "step" everywhere 2024-12-27 17:23:03 +13:00
23d6209ffc
Update dependencies 2024-12-27 17:06:06 +13:00
580597afae
Remove todo 2024-12-27 17:02:10 +13:00
7d70cde3b4
Add some janky handling of users clicking the close button several times 2024-12-27 17:00:24 +13:00
84ad8cbca4
Tickets with assets smaller than 25MiB include them in the transcript 2024-12-27 16:58:26 +13:00
7dfa3ad5e4
Fuck it, we're going for a major release 2024-12-27 16:54:53 +13:00
3a57fa1e02
Updated log error message 2024-12-27 16:53:40 +13:00
556f082aa2
Added command and functionality to stop interviews 2024-12-27 16:43:55 +13:00
47ff409902
Made paths no longer required 2024-12-27 16:34:28 +13:00
d4be9cb849
Made registering a category no longer be a requirement for uploading a template for it 2024-12-27 16:28:27 +13:00
22dc2255bc
Delete interview if channel is no longer a ticket 2024-12-27 16:22:30 +13:00
9641cdb0f1
I put the wrong link 2024-12-27 03:52:56 +13:00
3ed8dfc06b
Finished template documentation for now 2024-12-27 03:48:56 +13:00
055fd5a940
Improved error handling during template validation 2024-12-27 03:39:00 +13:00
75ee39f63c
Fixed old property in default template 2024-12-27 03:27:37 +13:00
c2c305317c
Added some docs 2024-12-27 03:22:28 +13:00
b80733cf83
Add JSON schema for interview templates, switched so using it internally for validation too 2024-12-27 03:21:59 +13:00
be04edff3f
Updated some comments. 2024-12-27 02:58:17 +13:00
76462b97fb
Add JSON schema for interview templates, switched so using it internally for validation too 2024-12-27 02:47:04 +13:00
a254bc5697
Fix delete command description 2024-12-27 02:28:09 +13:00
87e5957ae9
Split interview template commands from admin and added delete command 2024-12-27 02:24:48 +13:00
78994a6263
Hide forbidden channels in /listopen and /listunassigned 2024-12-27 02:16:27 +13:00
e51afd0b47
I forgot something in the last commit 2024-12-27 02:09:08 +13:00
2ee77c89af
Promoted listinvalid to a top level command 2024-12-27 02:07:42 +13:00
e8bf4d3004
Added tickets where the user has left to /admin listinvalid 2024-12-27 02:01:09 +13:00
851a3c949c
Fix summary command description 2024-12-27 01:57:41 +13:00
414dbae62f
Moved interview templates to own table
This splits them into different entries making it possible to separately edit different ones at the same time.
2024-12-27 01:54:28 +13:00
24defe0128
Remove some unnecessary variables 2024-12-27 01:39:46 +13:00
2db90a44c7
Made log level tags right-aligned 2024-12-27 01:35:11 +13:00
769643a292
Fixed check for if ticket is already in destination category 2024-12-27 01:31:19 +13:00
f0e48cc2ab
Improved error detection when moving a ticket to a different category 2024-12-27 01:29:32 +13:00
3feaf50b59
Move ratelimit warning log to debug 2024-12-27 01:26:48 +13:00
8bf14fcd05
Fix interview errors not getting removed when interview is finished 2024-12-27 01:24:42 +13:00
f5852dae29
Added more detailed logging to log channel 2024-12-27 01:21:37 +13:00
b2c6478458
More cleanup 2024-12-27 01:04:20 +13:00
e7547b749d
Update dependencies 2024-12-27 01:00:09 +13:00
a534ceac69
Minor cleanup 2024-12-27 00:50:33 +13:00
93446ca30d
Slight update 2024-12-27 00:47:23 +13:00
4f265f44e2
Minor cleanup 2024-12-27 00:38:35 +13:00
6ec63eb7a7
Remove todos 2024-12-27 00:32:34 +13:00
3d2d987dfe
Add config entries for interviews 2024-12-26 23:47:55 +13:00
b02aacadd6
Small refactoring 2024-12-26 23:38:59 +13:00
729e84fdce
Switch to always reading interviews directly from database 2024-12-26 23:33:32 +13:00
b2113695f8
Added support for multiple paths in mention selectors
Not sure how this could actually be useful but no reason to lock it down really.
2024-12-26 23:27:36 +13:00
14724c054e
Add selector descriptions 2024-12-26 23:25:11 +13:00
414ace3dcc
Added extra validation for templates 2024-12-26 23:23:25 +13:00
2553ad5c69
Added selector placeholders to template 2024-12-26 22:24:42 +13:00
f03473ba14
Add all other discord selector types 2024-12-26 20:51:41 +13:00
f1ce93ae86
Fixed restart interview command not being ephemeral 2024-12-26 20:48:50 +13:00
e2494c73d4
Add command to restart interviews 2024-12-26 20:47:07 +13:00
d9fcef449a
Get templates from database every time a new interview is started to avoid issues with the templates being passed by reference and then modified accidentally 2024-12-26 20:38:17 +13:00
1ced350789
Added optional properties to interview questions 2024-12-26 20:32:34 +13:00
a8d7440a7a
Add error handling for buttons and selectors 2024-12-26 20:30:56 +13:00
91991c10f2
Added support for END_WITHOUT_SUMMARY and ERROR question types 2024-12-26 20:28:39 +13:00
ebd279da45
Improved error handling in interview database functions 2024-12-26 20:24:32 +13:00
839ec527df
Made interview command responses ephemeral 2024-12-26 20:22:05 +13:00
f9fbc5990c
Some cleanup 2024-12-26 20:18:07 +13:00
280d18c80b
Added selection box support 2024-12-26 20:16:18 +13:00
32776826ba
Created functioning interview system PoC 2024-12-26 20:12:50 +13:00
327f4d6de6
Moved button and selector logic for new tickets to event handler 2024-12-26 20:04:47 +13:00
d212f13b12
Add commands to update interview templates 2024-12-26 19:50:47 +13:00
e87208d8bd
Slight update 2024-12-26 19:37:56 +13:00
233fd3278b
Some updated logging colours 2024-12-26 19:26:54 +13:00
9ef4364a13
Added option to pin the first ticket message 2024-12-26 19:25:08 +13:00
4f716dbbc9
Switched from mention to category name in move command 2024-12-26 19:01:20 +13:00
03497a28f8
Catch not found exceptions 2024-12-26 18:57:41 +13:00
d70c2ae0d2
Added custom logger 2024-12-26 18:41:36 +13:00
5c75e1fa7d
Updated to latest 5.0.0 nightly build of DSharpPlus
Still needs a new logger implementation and some new exception handling.
2024-12-26 18:36:20 +13:00
f89d50c982
Remove custom status, not supported in this version of D#+ 2024-12-26 18:09:13 +13:00
ce836a465f
Added database functions for interviews 2024-12-26 18:07:36 +13:00
c34a396c78
Split if statement for more clarity 2024-12-26 18:01:10 +13:00
3a94de9f23
Fix disabling ticket limit using 0 2024-12-26 17:57:58 +13:00
7f13161853
Started interview system PoC 2024-12-26 17:55:00 +13:00
32f5518891
Added utility function to get DiscordColor from string 2024-12-26 17:46:21 +13:00
3296fa98d1
Added pagination to say list 2024-10-29 23:17:44 +13:00
8af3e0a2f4
Added reason to close command 2024-10-29 23:14:47 +13:00
3e66a5659d
Switched RNG 2024-10-29 23:12:51 +13:00
55029de233
Added more info to status command 2024-10-29 23:11:05 +13:00
9c25573e98
Formatting changes in default config 2024-10-29 23:07:47 +13:00
e3137eaa1f
Added command line arguments: --config, --transcript, --leave, --help, --version 2024-10-29 23:05:16 +13:00
9f15236878
Updated transcription library 2024-10-29 22:52:02 +13:00
0dd6913dd8
Bump nuget dependencies 2024-10-29 22:40:46 +13:00
4bac506bfc
Codacy refactoring 2024-10-29 22:34:41 +13:00
ea1516e5db
Cleaned up README.md 2024-10-29 22:27:04 +13:00
493cfd3436
Switched to modern resources, some refactor of project and jenkins files 2024-10-29 22:25:03 +13:00
c084cbe368
Fixed project being indented by tabs instead of spaces 2024-10-29 22:10:37 +13:00
dc072d2d58
Deleted solution, moved project up. 2024-10-29 21:43:04 +13:00
c77e7c003a Merge pull request 'Removed .github files' (#2) from staging into main
Reviewed-on: Emotions-stuff/SupportChild#2
2024-06-23 05:18:59 -07:00
e5d0b40d09 Merge branch 'main' into staging 2024-06-23 05:18:44 -07:00
cb166ec963 Delete .github/dependabot.yml 2024-06-23 05:18:14 -07:00
57a1a90747 Delete .github/workflows/dotnet.yml 2024-06-23 05:18:07 -07:00
851e26f530 Delete .github/workflows/msbuild.yml 2024-06-23 05:17:59 -07:00
fd74cc14f5 Delete .github/workflows/auto-approve.yml 2024-06-23 05:17:53 -07:00
d8da5084e4 Merge pull request 'Update .github/workflows/dotnet.yml' (#1) from staging into main
Reviewed-on: Emotions-stuff/SupportChild#1
2024-06-23 05:15:02 -07:00
dd944fb6c8 Update .github/workflows/dotnet.yml 2024-06-23 05:12:35 -07:00
b86f613610 Update LICENSE 2024-05-28 05:37:45 -07:00
Emotion
aefe977193
Small update 2023-07-10 15:48:29 +12:00
Emotion
bc383e3456
Update dependabot.yml (#48) 2023-03-24 01:26:56 +13:00
Emotion
9d890484b9
Update dependabot.yml 2023-03-24 01:23:44 +13:00
Emotion
acf63a745b
Fixed some stuff
Signed-off-by: Emotion <emotion@elliebot.net>
2023-03-24 01:21:20 +13:00
Emotion
b4e833404c
Quick hotfix 2022-12-26 00:21:51 +13:00
Emotion
186587fa0d
Bump YamlDotNet to 12.2.1 (#32) 2022-12-18 14:20:58 +13:00
Emotion
1f7dd735f2
Bump YamlDotNet from 12.1.0 to 12.2.1 (#31) 2022-12-18 14:12:34 +13:00
dependabot[bot]
c6a5b7b656
Bump YamlDotNet from 12.1.0 to 12.2.1
Bumps [YamlDotNet](https://github.com/aaubry/YamlDotNet) from 12.1.0 to 12.2.1.
- [Release notes](https://github.com/aaubry/YamlDotNet/releases)
- [Commits](https://github.com/aaubry/YamlDotNet/compare/v12.1.0...v12.2.1)

---
updated-dependencies:
- dependency-name: YamlDotNet
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2022-12-14 19:06:05 +00:00
Emotion
e638630d30
Bump YamlDotNet to 12.1.0 (#29) 2022-12-06 19:45:46 +13:00
Emotion
31bc48d161
Bump YamlDotNet from 12.0.2 to 12.1.0 (#28) 2022-12-06 19:41:08 +13:00
dependabot[bot]
d0ad7980d3
Bump YamlDotNet from 12.0.2 to 12.1.0
Bumps [YamlDotNet](https://github.com/aaubry/YamlDotNet) from 12.0.2 to 12.1.0.
- [Release notes](https://github.com/aaubry/YamlDotNet/releases)
- [Commits](https://github.com/aaubry/YamlDotNet/compare/v12.0.2...v12.1.0)

---
updated-dependencies:
- dependency-name: YamlDotNet
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2022-12-05 19:08:02 +00:00
Emotion
dae587e4fd
Bump Newtonsoft.Json to 13.0.2 (#27) 2022-12-01 09:43:09 +13:00
Emotion
9e8140d0dd
Bump Newtonsoft.Json from 13.0.1 to 13.0.2 (#26) 2022-12-01 09:38:36 +13:00
dependabot[bot]
e3494c9af0
Bump Newtonsoft.Json from 13.0.1 to 13.0.2
Bumps [Newtonsoft.Json](https://github.com/JamesNK/Newtonsoft.Json) from 13.0.1 to 13.0.2.
- [Release notes](https://github.com/JamesNK/Newtonsoft.Json/releases)
- [Commits](https://github.com/JamesNK/Newtonsoft.Json/compare/13.0.1...13.0.2)

---
updated-dependencies:
- dependency-name: Newtonsoft.Json
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2022-11-24 19:06:36 +00:00
Emotion
f99f0e4d09
Update README.md 2022-11-12 00:46:30 +13:00
Emotion
79d5497b2e
Update README.md 2022-11-12 00:41:09 +13:00
Emotion
f6067f38c3
Update README.md 2022-11-12 00:40:31 +13:00
Emotion
cfacbfe8e6
Update msbuild.yml 2022-11-11 15:34:04 +13:00
Emotion
ba97c93651
Bump WebMarkupMin.Core to 2.13.0 (#25) 2022-11-11 15:32:16 +13:00
Emotion
90fced65aa
Update msbuild.yml 2022-11-11 15:07:56 +13:00
Emotion
426f190f81
Bump WebMarkupMin.Core from 2.12.0 to 2.13.0 (#24) 2022-11-11 14:31:45 +13:00
dependabot[bot]
26c6107b81
Bump WebMarkupMin.Core from 2.12.0 to 2.13.0
Bumps [WebMarkupMin.Core](https://github.com/Taritsyn/WebMarkupMin) from 2.12.0 to 2.13.0.
- [Release notes](https://github.com/Taritsyn/WebMarkupMin/releases)
- [Changelog](https://github.com/Taritsyn/WebMarkupMin/blob/master/CHANGELOG.md)
- [Commits](https://github.com/Taritsyn/WebMarkupMin/compare/v2.12.0...v2.13.0)

---
updated-dependencies:
- dependency-name: WebMarkupMin.Core
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2022-11-08 19:05:31 +00:00
Emotion
58ebb0b959
Merge pull request #22 from EmotionChild/development
Development
2022-10-08 18:46:03 +13:00
Emotion
ccc8cd2d15
Merge pull request #21 from EmotionChild/dependabot/nuget/development/YamlDotNet-12.0.2
Bump YamlDotNet from 12.0.1 to 12.0.2
2022-10-08 18:43:13 +13:00
dependabot[bot]
51d4f07fb5
Bump YamlDotNet from 12.0.1 to 12.0.2
Bumps [YamlDotNet](https://github.com/aaubry/YamlDotNet) from 12.0.1 to 12.0.2.
- [Release notes](https://github.com/aaubry/YamlDotNet/releases)
- [Commits](https://github.com/aaubry/YamlDotNet/compare/v12.0.1...v12.0.2)

---
updated-dependencies:
- dependency-name: YamlDotNet
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2022-10-07 19:47:46 +00:00
Emotion
7d82285e1b
Merge pull request #20 from EmotionChild/development
Development
2022-09-26 20:48:36 +13:00
Emotion
b1cfafda4a
Merge pull request #18 from EmotionChild/dependabot/nuget/development/MiniRazor.CodeGen-2.2.2
Bump MiniRazor.CodeGen from 2.2.1 to 2.2.2
2022-09-26 20:29:12 +13:00
Emotion
cf658bf5ca
Merge pull request #19 from EmotionChild/dependabot/nuget/development/YamlDotNet-12.0.1
Bump YamlDotNet from 12.0.0 to 12.0.1
2022-09-26 20:28:51 +13:00
dependabot[bot]
3d8709eb25
Bump YamlDotNet from 12.0.0 to 12.0.1
Bumps [YamlDotNet](https://github.com/aaubry/YamlDotNet) from 12.0.0 to 12.0.1.
- [Release notes](https://github.com/aaubry/YamlDotNet/releases)
- [Commits](https://github.com/aaubry/YamlDotNet/compare/v12.0.0...v12.0.1)

---
updated-dependencies:
- dependency-name: YamlDotNet
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2022-09-20 19:38:54 +00:00
dependabot[bot]
f0011a857d
Bump MiniRazor.CodeGen from 2.2.1 to 2.2.2
Bumps [MiniRazor.CodeGen](https://github.com/Tyrrrz/MiniRazor) from 2.2.1 to 2.2.2.
- [Release notes](https://github.com/Tyrrrz/MiniRazor/releases)
- [Changelog](https://github.com/Tyrrrz/MiniRazor/blob/master/Changelog.md)
- [Commits](https://github.com/Tyrrrz/MiniRazor/compare/2.2.1...2.2.2)

---
updated-dependencies:
- dependency-name: MiniRazor.CodeGen
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2022-09-14 19:42:42 +00:00
Emotion
6c105ea695
Merge pull request #17 from EmotionChild/development
Development
2022-09-13 14:06:18 +12:00
Emotion
f98c881364
Merge pull request #16 from EmotionChild/dependabot/nuget/development/WebMarkupMin.Core-2.12.0
Bump WebMarkupMin.Core from 2.9.0 to 2.12.0
2022-09-05 22:06:57 +12:00
dependabot[bot]
d2ebd118b2
Bump WebMarkupMin.Core from 2.9.0 to 2.12.0
Bumps [WebMarkupMin.Core](https://github.com/Taritsyn/WebMarkupMin) from 2.9.0 to 2.12.0.
- [Release notes](https://github.com/Taritsyn/WebMarkupMin/releases)
- [Changelog](https://github.com/Taritsyn/WebMarkupMin/blob/master/CHANGELOG.md)
- [Commits](https://github.com/Taritsyn/WebMarkupMin/compare/v2.9.0...v2.12.0)

---
updated-dependencies:
- dependency-name: WebMarkupMin.Core
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2022-08-22 19:48:33 +00:00
Emotion
28700fb27b
Merge pull request #15 from EmotionChild/development
Create msbuild.yml
2022-08-21 21:59:35 +12:00
Emotion
b1ccca64d3
Create msbuild.yml 2022-08-21 21:55:09 +12:00
Emotion
6fbd971318
Merge pull request #13 from EmotionChild/development
Development
2022-08-21 20:44:55 +12:00
EmotionChild
1d9ca5d004
Updated some more files 2022-08-21 20:43:28 +12:00
EmotionChild
2187fdc8fc
Merge branch 'development' of https://github.com/EmotionChild/SupportChild into development 2022-08-21 20:13:55 +12:00
EmotionChild
c4a0879d9b
Updated SupportChild.csproj 2022-08-21 20:13:34 +12:00
Emotion
afbb5cdfba
version 1.3.0
Development
2022-08-21 19:37:53 +12:00
Emotion
df1e669aa4
Create auto-approve.yml 2022-08-21 19:36:29 +12:00
EmotionChild
94df384934
Updated commands 2022-08-21 19:34:11 +12:00
EmotionChild
0e5a93a6a6
Updated general files 2022-08-21 19:33:27 +12:00
EmotionChild
d4651ee055
Updated Resources.Designer.cs 2022-08-21 19:32:26 +12:00
EmotionChild
248e638e6e
Merge branch 'development' of https://github.com/EmotionChild/SupportChild into development 2022-08-21 19:30:43 +12:00
EmotionChild
affe8955e1
Updated transcript lib 2022-08-21 19:21:53 +12:00
Emotion
e072c0fd60
Delete dotnet-desktop.yml 2022-05-21 02:24:28 +12:00
Emotion
201193af11
Merge pull request #8 from EmotionChild/EmotionChild-patch-1
Create dotnet-desktop.yml
2022-05-21 01:40:09 +12:00
Emotion
c75fb7dd78
Create dotnet-desktop.yml 2022-05-21 01:39:59 +12:00
Emotion
1e80bb8f95
Merge pull request #7 from EmotionChild/development
Create Jenkinsfile
2022-05-20 02:09:46 +12:00
Emotion
f4cb10f027
Create Jenkinsfile 2022-05-20 02:08:22 +12:00
Emotion
8f2f03a99b
1.2.0 update
Updated and fixed some stuff
2022-05-20 02:06:32 +12:00
Emotion
f918dd5df8
Update README.md 2022-05-20 02:05:13 +12:00
EmotionChild
b565047517 working? 2022-05-19 23:38:59 +12:00
EmotionChild
c9180130f9 More stuff updated 2022-05-18 01:11:57 +12:00
EmotionChild
8365b7c5aa More stuff updated 2022-05-18 01:10:49 +12:00
EmotionChild
ad0916477b updated some stuff 2022-05-18 01:09:25 +12:00
EmotionChild
94324f4d4a
Updated a file 2022-04-18 22:59:52 +12:00
EmotionChild
8408ddce01
Updated a file 2022-04-18 22:58:25 +12:00
EmotionChild
f3782e68f3
Updated a file 2022-04-18 22:55:48 +12:00
EmotionChild
6a39ece053
Update time! 2022-04-18 22:52:03 +12:00
EmotionChild
58a9c0f842
Added/updated files 2022-04-13 00:29:57 +12:00
EmotionChild
b38bc2e183
Added/updated files 2022-04-13 00:23:38 +12:00
EmotionChild
cec0680842
Updated stuff 2022-04-12 23:42:42 +12:00
Emotion
66429e8378
Merge pull request #1 from EmotionChild/dependabot/nuget/main/MiniRazor.CodeGen-2.2.1
Bump MiniRazor.CodeGen from 2.2.0 to 2.2.1
2022-03-30 14:53:55 +13:00
dependabot[bot]
c0c38c52a0
Bump MiniRazor.CodeGen from 2.2.0 to 2.2.1
Bumps [MiniRazor.CodeGen](https://github.com/Tyrrrz/MiniRazor) from 2.2.0 to 2.2.1.
- [Release notes](https://github.com/Tyrrrz/MiniRazor/releases)
- [Changelog](https://github.com/Tyrrrz/MiniRazor/blob/master/Changelog.md)
- [Commits](https://github.com/Tyrrrz/MiniRazor/compare/2.2...2.2.1)

---
updated-dependencies:
- dependency-name: MiniRazor.CodeGen
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2022-03-30 01:52:27 +00:00
Emotion
c66a58cae0
Create dependabot.yml 2022-03-30 14:51:12 +13:00
Emotion
c8221e021f
Create dotnet.yml 2022-03-30 13:59:18 +13:00
92 changed files with 7018 additions and 5320 deletions

63
.gitattributes vendored
View file

@ -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

372
.gitignore vendored
View file

@ -1,366 +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
/warp-packer.exe
/SupportChild.exe
/config.yml
/transcripts
/Linux-x64
/Windows-x64

View 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
View 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);
}
}
}

View 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);
}
}

View 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
View 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
View 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);
}
}

View 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
View 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);
}
}
}

View 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 + ".");
}
}

View 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());
}
}
}

View 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);
}
}

View 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));
}
}

View 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
View 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);
}
}

View 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
View 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);
}
}

View 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
View 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
View 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);
}
}

View 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;
}
}

View 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 + ".");
}
}

View 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 + ".");
}
}

View 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
View 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);
}
}

View 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
View 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);
}
}

View 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);
}
}

View 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"));
}
}
}

View 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;
}
}
}

View 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);
}
}

View 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
View 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
View 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
View 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
View 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
View 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;
}
}

View 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
}

44
Jenkinsfile vendored Normal file
View file

@ -0,0 +1,44 @@
pipeline {
agent any
stages {
stage('Setup Dependencies') {
steps {
sh 'dotnet restore'
}
}
stage('Build') {
parallel {
stage('Linux') {
steps {
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 -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/'
}
}
}
}
stage('Archive') {
parallel {
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)
}
}
}
}
}
}

858
LICENSE
View file

@ -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.
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
How to Apply These Terms to Your New Programs
APPENDIX: How to apply the Apache License to your work.
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 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.
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.
Copyright 2024 toastie_t0ast
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
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
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.
http://www.apache.org/licenses/LICENSE-2.0
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>.
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
View 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
View 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();
}
}
}

View file

@ -1 +1,3 @@
[![Build Status](https://ci.toastielab.dev/buildStatus/icon?job=Toastie-stuff%2FSupportChild%2Fmain)](https://ci.toastielab.dev/job/Toastie-stuff/job/SupportChild/job/main/)
# SupportChild

254
SupportChild.cs Normal file
View 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
View 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>

View file

@ -1,25 +0,0 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.0.32126.317
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SupportChild", "SupportChild\SupportChild.csproj", "{9124DF58-D261-4906-8ECA-D853DEBE07D4}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{9124DF58-D261-4906-8ECA-D853DEBE07D4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{9124DF58-D261-4906-8ECA-D853DEBE07D4}.Debug|Any CPU.Build.0 = Debug|Any CPU
{9124DF58-D261-4906-8ECA-D853DEBE07D4}.Release|Any CPU.ActiveCfg = Release|Any CPU
{9124DF58-D261-4906-8ECA-D853DEBE07D4}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {B2CD3447-A8BA-4B02-9E08-A75CBBD2BDCB}
EndGlobalSection
EndGlobal

View file

@ -1,107 +0,0 @@
using System;
using System.Threading.Tasks;
using DSharpPlus;
using DSharpPlus.CommandsNext;
using DSharpPlus.CommandsNext.Attributes;
using DSharpPlus.Entities;
using Microsoft.Extensions.Logging;
namespace SupportChild.Commands
{
public class AddCommand : BaseCommandModule
{
[Command("add")]
[Description("Adds a user to a ticket.")]
public async Task OnExecute(CommandContext command, [RemainingText] string commandArgs)
{
// Check if the user has permission to use this command.
if (!Config.HasPermission(command.Member, "add"))
{
DiscordEmbed error = new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = "You do not have permission to use this command."
};
await command.RespondAsync(error);
command.Client.Logger.Log(LogLevel.Information, "User tried to use the add command but did not have permission.");
return;
}
// Check if ticket exists in the database
if (!Database.IsOpenTicket(command.Channel.Id))
{
DiscordEmbed error = new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = "This channel is not a ticket."
};
await command.RespondAsync(error);
return;
}
string[] parsedArgs = Utilities.ParseIDs(command.RawArgumentString);
foreach (string parsedArg in parsedArgs)
{
if (!ulong.TryParse(parsedArg, out ulong userID))
{
DiscordEmbed error = new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = "Invalid ID/Mention. (Could not convert to numerical)"
};
await command.RespondAsync(error);
continue;
}
DiscordMember mentionedMember;
try
{
mentionedMember = await command.Guild.GetMemberAsync(userID);
}
catch (Exception)
{
DiscordEmbed error = new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = "Invalid ID/Mention. (Could not find user on this server)"
};
await command.RespondAsync(error);
continue;
}
try
{
await command.Channel.AddOverwriteAsync(mentionedMember, Permissions.AccessChannels, Permissions.None);
DiscordEmbed message = new DiscordEmbedBuilder
{
Color = DiscordColor.Green,
Description = "Added " + mentionedMember.Mention + " to ticket."
};
await command.RespondAsync(message);
// Log it if the log channel exists
DiscordChannel logChannel = command.Guild.GetChannel(Config.logChannel);
if (logChannel != null)
{
DiscordEmbed logMessage = new DiscordEmbedBuilder
{
Color = DiscordColor.Green,
Description = mentionedMember.Mention + " was added to " + command.Channel.Mention +
" by " + command.Member.Mention + "."
};
await logChannel.SendMessageAsync(logMessage);
}
}
catch (Exception)
{
DiscordEmbed message = new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = "Could not add <@" + parsedArg + "> to ticket, unknown error occured."
};
await command.RespondAsync(message);
}
}
}
}
}

View file

@ -1,77 +0,0 @@
using DSharpPlus.CommandsNext;
using DSharpPlus.CommandsNext.Attributes;
using DSharpPlus.Entities;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SupportChild.Commands
{
public class AddMessageCommand : BaseCommandModule
{
[Command("addmessage")]
[Description("Adds a new message for the 'say' command.")]
public async Task OnExecute(CommandContext command, string identifier, [RemainingText] string message)
{
// Check if the user has permission to use this command.
if (!Config.HasPermission(command.Member, "addmessage"))
{
DiscordEmbed error = new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = "You do not have permission to use this command."
};
await command.RespondAsync(error);
command.Client.Logger.Log(LogLevel.Information, "User tried to use the addmessage command but did not have permission.");
return;
}
if (string.IsNullOrEmpty(message))
{
DiscordEmbed error = new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = "No message specified."
};
await command.RespondAsync(error);
return;
}
if (Database.TryGetMessage(identifier.ToLower(), out Database.Message _))
{
DiscordEmbed error = new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = "There is already a message with that identifier."
};
await command.RespondAsync(error);
return;
}
if (Database.AddMessage(identifier, command.Member.Id, message))
{
DiscordEmbed error = new DiscordEmbedBuilder
{
Color = DiscordColor.Green,
Description = "Message added."
};
await command.RespondAsync(error);
return;
}
else
{
DiscordEmbed error = new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = "Error: Failed adding the message to the database."
};
await command.RespondAsync(error);
return;
}
}
}
}

View file

@ -1,96 +0,0 @@
using System;
using System.Linq;
using System.Threading.Tasks;
using DSharpPlus.CommandsNext;
using DSharpPlus.CommandsNext.Attributes;
using DSharpPlus.Entities;
using Microsoft.Extensions.Logging;
using MySql.Data.MySqlClient;
namespace SupportChild.Commands
{
public class AddStaffCommand : BaseCommandModule
{
[Command("addstaff")]
[Cooldown(1, 5, CooldownBucketType.User)]
public async Task OnExecute(CommandContext command, [RemainingText] string commandArgs)
{
// Check if the user has permission to use this command.
if (!Config.HasPermission(command.Member, "addstaff"))
{
DiscordEmbed error = new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = "You do not have permission to use this command."
};
await command.RespondAsync(error);
command.Client.Logger.Log(LogLevel.Information, "User tried to use the addstaff command but did not have permission.");
return;
}
ulong userID;
string[] parsedArgs = Utilities.ParseIDs(commandArgs);
if (!parsedArgs.Any())
{
userID = command.Member.Id;
}
else if (!ulong.TryParse(parsedArgs[0], out userID))
{
DiscordEmbed error = new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = "Invalid ID/Mention. (Could not convert to numerical)"
};
await command.RespondAsync(error);
return;
}
DiscordMember member;
try
{
member = await command.Guild.GetMemberAsync(userID);
}
catch (Exception)
{
DiscordEmbed error = new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = "Invalid ID/Mention. (Could not find user on this server)"
};
await command.RespondAsync(error);
return;
}
using (MySqlConnection c = Database.GetConnection())
{
MySqlCommand cmd = Database.IsStaff(userID) ? 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", userID);
cmd.Parameters.AddWithValue("@name", member.DisplayName);
cmd.ExecuteNonQuery();
cmd.Dispose();
DiscordEmbed message = new DiscordEmbedBuilder
{
Color = DiscordColor.Green,
Description = member.Mention + " was added to staff."
};
await command.RespondAsync(message);
// Log it if the log channel exists
DiscordChannel logChannel = command.Guild.GetChannel(Config.logChannel);
if (logChannel != null)
{
DiscordEmbed logMessage = new DiscordEmbedBuilder
{
Color = DiscordColor.Green,
Description = member.Mention + " was added to staff.\n",
};
await logChannel.SendMessageAsync(logMessage);
}
}
}
}
}

View file

@ -1,135 +0,0 @@
using System.Linq;
using System.Threading.Tasks;
using DSharpPlus.CommandsNext;
using DSharpPlus.CommandsNext.Attributes;
using DSharpPlus.Entities;
using DSharpPlus.Exceptions;
using Microsoft.Extensions.Logging;
namespace SupportChild.Commands
{
public class AssignCommand : BaseCommandModule
{
[Command("assign")]
[Description("Assigns a staff member to a ticket.")]
public async Task OnExecute(CommandContext command, [RemainingText] string commandArgs)
{
// Check if the user has permission to use this command.
if (!Config.HasPermission(command.Member, "assign"))
{
DiscordEmbed error = new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = "You do not have permission to use this command."
};
await command.RespondAsync(error);
command.Client.Logger.Log(LogLevel.Information, "User tried to use the assign command but did not have permission.");
return;
}
// Check if ticket exists in the database
if (!Database.TryGetOpenTicket(command.Channel.Id, out Database.Ticket ticket))
{
DiscordEmbed error = new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = "This channel is not a ticket."
};
await command.RespondAsync(error);
return;
}
ulong staffID;
string[] parsedMessage = Utilities.ParseIDs(command.RawArgumentString);
if (!parsedMessage.Any())
{
staffID = command.Member.Id;
}
else if (!ulong.TryParse(parsedMessage[0], out staffID))
{
DiscordEmbed error = new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = "Invalid ID/Mention. (Could not convert to numerical)"
};
await command.RespondAsync(error);
return;
}
DiscordMember staffMember = null;
try
{
staffMember = await command.Guild.GetMemberAsync(staffID);
}
catch (NotFoundException) { }
if (staffMember == null)
{
DiscordEmbed error = new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = "Error: Could not find user."
};
await command.RespondAsync(error);
return;
}
if (!Database.IsStaff(staffMember.Id))
{
DiscordEmbed error = new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = "Error: User is not registered as staff."
};
await command.RespondAsync(error);
return;
}
if (!Database.AssignStaff(ticket, staffID))
{
DiscordEmbed error = new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = "Error: Failed to assign " + staffMember.Mention + " to ticket."
};
await command.RespondAsync(error);
return;
}
DiscordEmbed feedback = new DiscordEmbedBuilder
{
Color = DiscordColor.Green,
Description = "Assigned " + staffMember.Mention + " to ticket."
};
await command.RespondAsync(feedback);
if (Config.assignmentNotifications)
{
try
{
DiscordEmbed message = new DiscordEmbedBuilder
{
Color = DiscordColor.Green,
Description = "You have been assigned to a support ticket: " + command.Channel.Mention
};
await staffMember.SendMessageAsync(message);
}
catch (UnauthorizedException) { }
}
// Log it if the log channel exists
DiscordChannel logChannel = command.Guild.GetChannel(Config.logChannel);
if (logChannel != null)
{
DiscordEmbed logMessage = new DiscordEmbedBuilder
{
Color = DiscordColor.Green,
Description = staffMember.Mention + " was was assigned to " + command.Channel.Mention + " by " + command.Member.Mention + "."
};
await logChannel.SendMessageAsync(logMessage);
}
}
}
}

View file

@ -1,98 +0,0 @@
using System;
using System.Threading.Tasks;
using DSharpPlus.CommandsNext;
using DSharpPlus.CommandsNext.Attributes;
using DSharpPlus.Entities;
using DSharpPlus.Exceptions;
using Microsoft.Extensions.Logging;
namespace SupportChild.Commands
{
public class BlacklistCommand : BaseCommandModule
{
[Command("balcklist")]
[Description("Blacklists a user from opening tickets.")]
public async Task OnExecute(CommandContext command, [RemainingText] string commandArgs)
{
// Check is the user has permission to use this command.
if (!Config.HasPermission(command.Member, "blacklist"))
{
DiscordEmbed error = new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = "You do not have permission to use this command."
};
await command.RespondAsync(error);
command.Client.Logger.Log(LogLevel.Information, "User tried to use the blacklist command but did not have permission.");
return;
}
string[] parsedArgs = Utilities.ParseIDs(command.RawArgumentString);
foreach (string parsedArg in parsedArgs)
{
if (ulong.TryParse(parsedArg, out ulong userId))
{
DiscordUser blacklistedUser = null;
try
{
blacklistedUser = await command.Client.GetUserAsync(userId);
}
catch (NotFoundException) { }
if (blacklistedUser == null)
{
DiscordEmbed message = new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = "Error: Could not find user."
};
await command.RespondAsync(message);
continue;
}
try
{
if (!Database.Blacklist(blacklistedUser.Id, command.User.Id))
{
DiscordEmbed error = new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = blacklistedUser.Mention + " is already blacklisted."
};
await command.RespondAsync(error);
continue;
}
DiscordEmbed message = new DiscordEmbedBuilder
{
Color = DiscordColor.Green,
Description = "Blacklisted " + blacklistedUser.Mention + "."
};
await command.RespondAsync(message);
// Log it if the log channel exists
DiscordChannel logChannel = command.Guild.GetChannel(Config.logChannel);
if (logChannel != null)
{
DiscordEmbed logMessage = new DiscordEmbedBuilder
{
Color = DiscordColor.Green,
Description = blacklistedUser.Mention + " was blacklisted from opening tickets by " + command.Member.Mention + "."
};
}
}
catch (Exception)
{
DiscordEmbed message = new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = "Error occured while blacklisting " + blacklistedUser.Mention + "."
};
await command.RespondAsync(message);
throw;
}
}
}
}
}
}

View file

@ -1,118 +0,0 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using DSharpPlus.CommandsNext;
using DSharpPlus.CommandsNext.Attributes;
using DSharpPlus.Entities;
using DSharpPlus.Exceptions;
using Microsoft.Extensions.Logging;
namespace SupportChild.Commands
{
public class CloseCommand : BaseCommandModule
{
[Command("close")]
[Cooldown(1, 5, CooldownBucketType.User)]
public async Task OnExecute(CommandContext command, [RemainingText] string commandArgs)
{
// Check if the user has permission to use this command.
if (!Config.HasPermission(command.Member, "close"))
{
DiscordEmbed error = new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = "You do not have permission to use this command."
};
await command.RespondAsync(error);
command.Client.Logger.Log(LogLevel.Information, "User tried to use the close command but did not have permission.");
return;
}
ulong channelID = command.Channel.Id;
string channelName = command.Channel.Name;
// Check if ticket exists in the database
if (!Database.TryGetOpenTicket(channelID, out Database.Ticket ticket))
{
DiscordEmbed error = new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = "This channel is not a ticket."
};
await command.RespondAsync(error);
return;
}
// Build transcript
try
{
await Transcriber.ExecuteAsync(command.Channel.Id, ticket.id);
}
catch (Exception)
{
DiscordEmbed error = new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = "ERROR: Could not save transcript file. Aborting..."
};
await command.RespondAsync(error);
throw;
}
// Log it if the log channel exists
DiscordChannel logChannel = command.Guild.GetChannel(Config.logChannel);
if (logChannel != null)
{
DiscordEmbed embed = new DiscordEmbedBuilder
{
Color = DiscordColor.Green,
Description = "Ticket " + ticket.id.ToString("00000") + " closed by " + command.Member.Mention + ".\n",
Footer = new DiscordEmbedBuilder.EmbedFooter { Text = '#' + channelName }
};
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 command.Guild.GetMemberAsync(ticket.creatorID);
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);
// Delete the channel and database entry
await command.Channel.DeleteAsync("Ticket closed.");
Database.DeleteOpenTicket(ticket.id);
}
}
}

View file

@ -1,76 +0,0 @@
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using DSharpPlus.CommandsNext;
using DSharpPlus.CommandsNext.Attributes;
using DSharpPlus.Entities;
using Microsoft.Extensions.Logging;
namespace SupportChild.Commands
{
public class ListAssignedCommand : BaseCommandModule
{
[Command("listassigned")]
[Aliases("la")]
[Cooldown(1, 5, CooldownBucketType.User)]
public async Task OnExecute(CommandContext command, [RemainingText] string commandArgs)
{
// Check if the user has permission to use this command.
if (!Config.HasPermission(command.Member, "listassigned"))
{
DiscordEmbed error = new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = "You do not have permission to use this command."
};
await command.RespondAsync(error);
command.Client.Logger.Log(LogLevel.Information, "User tried to use the listassigned command but did not have permission.");
return;
}
ulong staffID;
string[] parsedIDs = Utilities.ParseIDs(command.RawArgumentString);
if (!parsedIDs.Any())
{
staffID = command.Member.Id;
}
else if (!ulong.TryParse(parsedIDs[0], out staffID))
{
DiscordEmbed error = new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = "Invalid ID/Mention. (Could not convert to numerical)"
};
await command.RespondAsync(error);
return;
}
if (!Database.TryGetAssignedTickets(staffID, out List<Database.Ticket> assignedTickets))
{
DiscordEmbed error = new DiscordEmbedBuilder()
.WithColor(DiscordColor.Red)
.WithDescription("User does not have any assigned tickets.");
await command.RespondAsync(error);
return;
}
List<string> listItems = new List<string>();
foreach (Database.Ticket ticket in assignedTickets)
{
listItems.Add("**" + ticket.FormattedCreatedTime() + ":** <#" + ticket.channelID + "> by <@" + ticket.creatorID + ">\n");
}
LinkedList<string> messages = Utilities.ParseListIntoMessages(listItems);
foreach (string message in messages)
{
DiscordEmbed channelInfo = new DiscordEmbedBuilder()
.WithTitle("Assigned tickets: ")
.WithColor(DiscordColor.Green)
.WithDescription(message);
await command.RespondAsync(channelInfo);
}
}
}
}

View file

@ -1,101 +0,0 @@
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using DSharpPlus.CommandsNext;
using DSharpPlus.CommandsNext.Attributes;
using DSharpPlus.Entities;
using Microsoft.Extensions.Logging;
namespace SupportChild.Commands
{
public class ListCommand : BaseCommandModule
{
[Command("list")]
[Cooldown(1, 5, CooldownBucketType.User)]
public async Task OnExecute(CommandContext command, [RemainingText] string commandArgs)
{
// Check if the user has permission to use this command.
if (!Config.HasPermission(command.Member, "list"))
{
DiscordEmbed error = new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = "You do not have permission to use this command."
};
await command.RespondAsync(error);
command.Client.Logger.Log(LogLevel.Information, "User tried to use the list command but did not have permission.");
return;
}
ulong userID;
string[] parsedMessage = Utilities.ParseIDs(command.RawArgumentString);
if (!parsedMessage.Any())
{
userID = command.Member.Id;
}
else if (!ulong.TryParse(parsedMessage[0], out userID))
{
DiscordEmbed error = new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = "Invalid ID/Mention. (Could not convert to numerical)"
};
await command.RespondAsync(error);
return;
}
if (Database.TryGetOpenTickets(userID, out List<Database.Ticket> openTickets))
{
List<string> listItems = new List<string>();
foreach (Database.Ticket ticket in openTickets)
{
listItems.Add("**" + ticket.FormattedCreatedTime() + ":** <#" + ticket.channelID + ">\n");
}
LinkedList<string> messages = Utilities.ParseListIntoMessages(listItems);
foreach (string message in messages)
{
DiscordEmbed channelInfo = new DiscordEmbedBuilder()
.WithTitle("Open tickets: ")
.WithColor(DiscordColor.Green)
.WithDescription(message);
await command.RespondAsync(channelInfo);
}
}
else
{
DiscordEmbed channelInfo = new DiscordEmbedBuilder()
.WithColor(DiscordColor.Green)
.WithDescription("User does not have any open tickets.");
await command.RespondAsync(channelInfo);
}
if (Database.TryGetClosedTickets(userID, out List<Database.Ticket> closedTickets))
{
List<string> listItems = new List<string>();
foreach (Database.Ticket ticket in closedTickets)
{
listItems.Add("**" + ticket.FormattedCreatedTime() + ":** Ticket " + ticket.id.ToString("00000") + "\n");
}
LinkedList<string> messages = Utilities.ParseListIntoMessages(listItems);
foreach (string message in messages)
{
DiscordEmbed channelInfo = new DiscordEmbedBuilder()
.WithTitle("Closed tickets: ")
.WithColor(DiscordColor.Red)
.WithDescription(message);
await command.RespondAsync(channelInfo);
}
}
else
{
DiscordEmbed channelInfo = new DiscordEmbedBuilder()
.WithColor(DiscordColor.Red)
.WithDescription("User does not have any closed tickets.");
await command.RespondAsync(channelInfo);
}
}
}
}

View file

@ -1,71 +0,0 @@
using System.Collections.Generic;
using System.Threading.Tasks;
using DSharpPlus.CommandsNext;
using DSharpPlus.CommandsNext.Attributes;
using DSharpPlus.Entities;
using Microsoft.Extensions.Logging;
namespace SupportChild.Commands
{
public class ListOldestCommand : BaseCommandModule
{
[Command("listoldest")]
[Aliases("lo")]
[Cooldown(1, 5, CooldownBucketType.User)]
public async Task OnExecute(CommandContext command, [RemainingText] string commandArgs)
{
// Check if the user has permission to use this command.
if (!Config.HasPermission(command.Member, "listoldest"))
{
DiscordEmbed error = new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = "You do not have permission to use this command."
};
await command.RespondAsync(error);
command.Client.Logger.Log(LogLevel.Information, "User tried to use the listoldest command but did not have permission.");
return;
}
int listLimit = 20;
if (!string.IsNullOrEmpty(command.RawArgumentString?.Trim() ?? ""))
{
if (!int.TryParse(command.RawArgumentString?.Trim(), out listLimit) || listLimit < 5 || listLimit > 100)
{
DiscordEmbed error = new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = "Invalid list amount. (Must be an integer between 5 and 100)"
};
await command.RespondAsync(error);
return;
}
}
if (!Database.TryGetOldestTickets(command.Member.Id, out List<Database.Ticket> openTickets, listLimit))
{
DiscordEmbed channelInfo = new DiscordEmbedBuilder()
.WithColor(DiscordColor.Red)
.WithDescription("Could not fetch any open tickets.");
await command.RespondAsync(channelInfo);
return;
}
List<string> listItems = new List<string>();
foreach (Database.Ticket ticket in openTickets)
{
listItems.Add("**" + ticket.FormattedCreatedTime() + ":** <#" + ticket.channelID + "> by <@" + ticket.creatorID + ">\n");
}
LinkedList<string> messages = Utilities.ParseListIntoMessages(listItems);
foreach (string message in messages)
{
DiscordEmbed channelInfo = new DiscordEmbedBuilder()
.WithTitle("The " + openTickets.Count + " oldest open tickets: ")
.WithColor(DiscordColor.Green)
.WithDescription(message?.Trim());
await command.RespondAsync(channelInfo);
}
}
}
}

View file

@ -1,55 +0,0 @@
using System.Collections.Generic;
using System.Threading.Tasks;
using DSharpPlus.CommandsNext;
using DSharpPlus.CommandsNext.Attributes;
using DSharpPlus.Entities;
using Microsoft.Extensions.Logging;
namespace SupportChild.Commands
{
public class ListUnassignedCommand : BaseCommandModule
{
[Command("listunassigned")]
[Aliases("lu")]
[Cooldown(1, 5, CooldownBucketType.User)]
public async Task OnExecute(CommandContext command, [RemainingText] string commandArgs)
{
// Check if the user has permission to use this command.
if (!Config.HasPermission(command.Member, "listunassigned"))
{
DiscordEmbed error = new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = "You do not have permission to use this command."
};
await command.RespondAsync(error);
command.Client.Logger.Log(LogLevel.Information, "User tried to use the listunassigned command but did not have permission.");
return;
}
if (!Database.TryGetAssignedTickets(0, out List<Database.Ticket> unassignedTickets))
{
DiscordEmbed response = new DiscordEmbedBuilder()
.WithColor(DiscordColor.Green)
.WithDescription("There are no unassigned tickets.");
await command.RespondAsync(response);
}
List<string> listItems = new List<string>();
foreach (Database.Ticket ticket in unassignedTickets)
{
listItems.Add("**" + ticket.FormattedCreatedTime() + ":** <#" + ticket.channelID + "> by <@" + ticket.creatorID + ">\n");
}
LinkedList<string> messages = Utilities.ParseListIntoMessages(listItems);
foreach (string message in messages)
{
DiscordEmbed channelInfo = new DiscordEmbedBuilder()
.WithTitle("Unassigned tickets: ")
.WithColor(DiscordColor.Green)
.WithDescription(message?.Trim());
await command.RespondAsync(channelInfo);
}
}
}
}

View file

@ -1,104 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using DSharpPlus.CommandsNext;
using DSharpPlus.CommandsNext.Attributes;
using DSharpPlus.Entities;
using DSharpPlus.Exceptions;
using Microsoft.Extensions.Logging;
namespace SupportChild.Commands
{
public class MoveCommand : BaseCommandModule
{
[Command("move")]
[Description("Move a ticket to another category.")]
public async Task OnExecute(CommandContext command, [RemainingText] string commandArgs)
{
// Check if the user has permission to use this command.
if (!Config.HasPermission(command.Member, "move"))
{
DiscordEmbed error = new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = "You do not have permission to use this command."
};
await command.RespondAsync(error);
command.Client.Logger.Log(LogLevel.Information, "User tried to use the move command but did not have permission.");
return;
}
// Check if ticket exists in the database
if (!Database.TryGetOpenTicket(command.Channel.Id, out Database.Ticket ticket))
{
DiscordEmbed error = new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = "This channel is not a ticket."
};
await command.RespondAsync(error);
return;
}
if (string.IsNullOrEmpty(command.RawArgumentString))
{
DiscordEmbed error = new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = "Error: No category provided."
};
await command.RespondAsync(error);
return;
}
IReadOnlyList<DiscordChannel> channels = await command.Guild.GetChannelsAsync();
IEnumerable<DiscordChannel> categories = channels.Where(x => x.IsCategory);
DiscordChannel category = categories.FirstOrDefault(x => x.Name.StartsWith(command.RawArgumentString.Trim(), StringComparison.OrdinalIgnoreCase));
if (category == null)
{
DiscordEmbed error = new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = "Error: Could not find a category by that name."
};
await command.RespondAsync(error);
return;
}
if (command.Channel.Id == category.Id)
{
DiscordEmbed error = new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = "Error: The ticket is already in that category."
};
await command.RespondAsync(error);
return;
}
try
{
await command.Channel.ModifyAsync(modifiedAttributes => modifiedAttributes.Parent = category);
}
catch (UnauthorizedException)
{
DiscordEmbed error = new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = "Error: Not authorized to move this ticket to that category."
};
await command.RespondAsync(error);
return;
}
DiscordEmbed feedback = new DiscordEmbedBuilder
{
Color = DiscordColor.Green,
Description = "Ticket was moved to " + category.Mention
};
await command.RespondAsync(feedback);
}
}
}

View file

@ -1,150 +0,0 @@
using System;
using System.Threading.Tasks;
using DSharpPlus;
using DSharpPlus.CommandsNext;
using DSharpPlus.CommandsNext.Attributes;
using DSharpPlus.Entities;
using DSharpPlus.Exceptions;
using Microsoft.Extensions.Logging;
namespace SupportChild.Commands
{
public class NewCommand : BaseCommandModule
{
[Command("new")]
[Cooldown(1, 5, CooldownBucketType.User)]
public async Task OnExecute(CommandContext command, [RemainingText] string commandArgs)
{
// Check if the user has permission to use this command.
if (!Config.HasPermission(command.Member, "new"))
{
DiscordEmbed error = new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = "You do not have permission to use this command."
};
await command.RespondAsync(error);
command.Client.Logger.Log(LogLevel.Information, "User tried to use the new command but did not have permission.");
return;
}
// Check if user is blacklisted
if (Database.IsBlacklisted(command.User.Id))
{
DiscordEmbed error = new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = "You are banned from opening tickets."
};
await command.RespondAsync(error);
return;
}
if (Database.IsOpenTicket(command.Channel.Id))
{
DiscordEmbed error = new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = "You cannot use this command in a ticket channel."
};
await command.RespondAsync(error);
return;
}
DiscordChannel category = command.Guild.GetChannel(Config.ticketCategory);
DiscordChannel ticketChannel;
try
{
ticketChannel = await command.Guild.CreateChannelAsync("ticket", ChannelType.Text, category);
}
catch (Exception)
{
DiscordEmbed error = new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = "Error occured while creating ticket, " + command.Member.Mention +
"!\nIs the channel limit reached in the server or ticket category?"
};
await command.RespondAsync(error);
return;
}
if (ticketChannel == null)
{
DiscordEmbed error = new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = "Error occured while creating ticket, " + command.Member.Mention +
"!\nIs the channel limit reached in the server or ticket category?"
};
await command.RespondAsync(error);
return;
}
ulong staffID = 0;
if (Config.randomAssignment)
{
staffID = Database.GetRandomActiveStaff(0)?.userID ?? 0;
}
long id = Database.NewTicket(command.Member.Id, staffID, ticketChannel.Id);
string ticketID = id.ToString("00000");
await ticketChannel.ModifyAsync(modifiedAttributes => modifiedAttributes.Name = "ticket-" + ticketID);
await ticketChannel.AddOverwriteAsync(command.Member, Permissions.AccessChannels, Permissions.None);
await ticketChannel.SendMessageAsync("Hello, " + command.Member.Mention + "!\n" + Config.welcomeMessage);
// Refreshes the channel as changes were made to it above
ticketChannel = command.Guild.GetChannel(ticketChannel.Id);
if (staffID != 0)
{
DiscordEmbed assignmentMessage = new DiscordEmbedBuilder
{
Color = DiscordColor.Green,
Description = "Ticket was randomly assigned to <@" + staffID + ">."
};
await ticketChannel.SendMessageAsync(assignmentMessage);
if (Config.assignmentNotifications)
{
DiscordEmbed message = new DiscordEmbedBuilder
{
Color = DiscordColor.Green,
Description = "You have been randomly assigned to a newly opened support ticket: " +
ticketChannel.Mention
};
try
{
DiscordMember staffMember = await command.Guild.GetMemberAsync(staffID);
await staffMember.SendMessageAsync(message);
}
catch (NotFoundException) { }
catch (UnauthorizedException) { }
}
}
DiscordEmbed response = new DiscordEmbedBuilder
{
Color = DiscordColor.Green,
Description = "Ticket opened, " + command.Member.Mention + "!\n" + ticketChannel.Mention
};
await command.RespondAsync(response);
// Log it if the log channel exists
DiscordChannel logChannel = command.Guild.GetChannel(Config.logChannel);
if (logChannel != null)
{
DiscordEmbed logMessage = new DiscordEmbedBuilder
{
Color = DiscordColor.Green,
Description = "Ticket " + ticketChannel.Mention + " opened by " + command.Member.Mention + ".\n",
Footer = new DiscordEmbedBuilder.EmbedFooter { Text = "Ticket " + ticketID }
};
await logChannel.SendMessageAsync(logMessage);
}
}
}
}

View file

@ -1,182 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using DSharpPlus.CommandsNext;
using DSharpPlus.CommandsNext.Attributes;
using DSharpPlus.Entities;
using DSharpPlus.Exceptions;
using Microsoft.Extensions.Logging;
namespace SupportChild.Commands
{
public class RandomAssignCommand : BaseCommandModule
{
[Command("rassign")]
[Description("Randomly assigns a staff member to a ticket.")]
public async Task OnExecute(CommandContext command, [RemainingText] string commandArguments)
{
// Check if the user has permission to use this command.
if (!Config.HasPermission(command.Member, "rassign"))
{
DiscordEmbed error = new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = "You do not have permission to use this command."
};
await command.RespondAsync(error);
command.Client.Logger.Log(LogLevel.Information, "User tried to use the rassign command but did not have permission.");
return;
}
// Check if ticket exists in the database
if (!Database.TryGetOpenTicket(command.Channel.Id, out Database.Ticket ticket))
{
DiscordEmbed error = new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = "This channel is not a ticket."
};
await command.RespondAsync(error);
return;
}
// Get a random staff member who is verified to have the correct role if applicable
DiscordMember staffMember = await GetRandomVerifiedStaffMember(command, ticket);
if (staffMember == null)
{
return;
}
// Attempt to assign the staff member to the ticket
if (!Database.AssignStaff(ticket, staffMember.Id))
{
DiscordEmbed error = new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = "Error: Failed to assign " + staffMember.Mention + " to ticket."
};
await command.RespondAsync(error);
return;
}
// Respond that the command was successful
DiscordEmbed feedback = new DiscordEmbedBuilder
{
Color = DiscordColor.Green,
Description = "Randomly assigned " + staffMember.Mention + " to ticket."
};
await command.RespondAsync(feedback);
// Send a notification to the staff member if applicable
if (Config.assignmentNotifications)
{
try
{
DiscordEmbed message = new DiscordEmbedBuilder
{
Color = DiscordColor.Green,
Description = "You have been randomly assigned to a support ticket: " + command.Channel.Mention
};
await staffMember.SendMessageAsync(message);
}
catch (UnauthorizedException) { }
}
// Log it if the log channel exists
DiscordChannel logChannel = command.Guild.GetChannel(Config.logChannel);
if (logChannel != null)
{
DiscordEmbed logMessage = new DiscordEmbedBuilder
{
Color = DiscordColor.Green,
Description = staffMember.Mention + " was was assigned to " + command.Channel.Mention + " by " + command.Member.Mention + "."
};
await logChannel.SendMessageAsync(logMessage);
}
}
private async Task<DiscordMember> GetRandomVerifiedStaffMember(CommandContext command, Database.Ticket ticket)
{
if (command.RawArguments.Any()) // An argument was provided, check if this can be parsed into a role
{
ulong roleID = 0;
// Try to parse either discord mention or ID
string[] parsedMessage = Utilities.ParseIDs(command.RawArgumentString);
if (!ulong.TryParse(parsedMessage[0], out roleID))
{
// Try to find role by name
roleID = Utilities.GetRoleByName(command.Guild, command.RawArgumentString)?.Id ?? 0;
}
// Check if a role was found
if (roleID == 0)
{
DiscordEmbed error = new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = "Could not find a role by that name/ID."
};
await command.RespondAsync(error);
return null;
}
// Check if role rassign should override staff's active status
List<Database.StaffMember> staffMembers = Config.randomAssignRoleOverride
? Database.GetAllStaff(ticket.assignedStaffID)
: Database.GetActiveStaff(ticket.assignedStaffID);
// Randomize the list before checking for roles in order to reduce number of API calls
staffMembers = Utilities.RandomizeList(staffMembers);
// 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 == roleID) ?? 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);
if (staffEntry == null)
{
DiscordEmbed error = new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = "Error: There are no other staff members to choose from."
};
await command.RespondAsync(error);
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
DiscordEmbed err = new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = "Error: Could not find an applicable staff member."
};
await command.RespondAsync(err);
return null;
}
}
}

View file

@ -1,38 +0,0 @@
using System;
using System.Threading.Tasks;
using DSharpPlus.CommandsNext;
using DSharpPlus.CommandsNext.Attributes;
using DSharpPlus.Entities;
using Microsoft.Extensions.Logging;
namespace SupportChild.Commands
{
public class ReloadCommand : BaseCommandModule
{
[Command("reload")]
public async Task OnExecute(CommandContext command, [RemainingText] string commandArgs)
{
// Check if the user has permission to use this command.
if (!Config.HasPermission(command.Member, "reload"))
{
DiscordEmbed error = new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = "You do not have permission to use this command."
};
await command.RespondAsync(error);
command.Client.Logger.Log(LogLevel.Information, "User tried to use the reload command but did not have permission.");
return;
}
DiscordEmbed message = new DiscordEmbedBuilder
{
Color = DiscordColor.Green,
Description = "Reloading bot application..."
};
await command.RespondAsync(message);
Console.WriteLine("Reloading bot...");
SupportChild.instance.Reload();
}
}
}

View file

@ -1,66 +0,0 @@
using DSharpPlus.CommandsNext;
using DSharpPlus.CommandsNext.Attributes;
using DSharpPlus.Entities;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SupportChild.Commands
{
public class RemoveMessageCommand : BaseCommandModule
{
[Command("removemessage")]
[Description("Removes a message from the 'say' command.")]
public async Task OnExecute(CommandContext command, string identifier)
{
// Check if the user has permission to use this command.
if (!Config.HasPermission(command.Member, "removemessage"))
{
DiscordEmbed error = new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = "You do not have permission to use this command."
};
await command.RespondAsync(error);
command.Client.Logger.Log(LogLevel.Information, "User tried to use the removemessage command but did not have permission.");
return;
}
if (!Database.TryGetMessage(identifier.ToLower(), out Database.Message _))
{
DiscordEmbed error = new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = "There is no message with that identifier."
};
await command.RespondAsync(error);
return;
}
if (Database.RemoveMessage(identifier))
{
DiscordEmbed error = new DiscordEmbedBuilder
{
Color = DiscordColor.Green,
Description = "Message removed."
};
await command.RespondAsync(error);
return;
}
else
{
DiscordEmbed error = new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = "Error: Failed removing the message from the database."
};
await command.RespondAsync(error);
return;
}
}
}
}

View file

@ -1,104 +0,0 @@
using System;
using System.Linq;
using System.Threading.Tasks;
using DSharpPlus.CommandsNext;
using DSharpPlus.CommandsNext.Attributes;
using DSharpPlus.Entities;
using Microsoft.Extensions.Logging;
using MySql.Data.MySqlClient;
namespace SupportChild.Commands
{
public class RemoveStaffCommand : BaseCommandModule
{
[Command("removestaff")]
[Cooldown(1, 5, CooldownBucketType.User)]
public async Task OnExecute(CommandContext command, [RemainingText] string commandArgs)
{
// Check if the user has permission to use this command.
if (!Config.HasPermission(command.Member, "removestaff"))
{
DiscordEmbed error = new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = "You do not have permission to use this command."
};
await command.RespondAsync(error);
command.Client.Logger.Log(LogLevel.Information, "User tried to use the removestaff command but did not have permission.");
return;
}
ulong userID;
string[] parsedMessage = Utilities.ParseIDs(command.RawArgumentString);
if (!parsedMessage.Any())
{
userID = command.Member.Id;
}
else if (!ulong.TryParse(parsedMessage[0], out userID))
{
DiscordEmbed error = new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = "Invalid ID/Mention. (Could not convert to numerical)"
};
await command.RespondAsync(error);
return;
}
try
{
await command.Client.GetUserAsync(userID);
}
catch (Exception)
{
DiscordEmbed error = new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = "Invalid ID/Mention. (Could not find user on Discord)"
};
await command.RespondAsync(error);
return;
}
if (!Database.IsStaff(userID))
{
DiscordEmbed error = new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = "User is already not registered as staff."
};
await command.RespondAsync(error);
return;
}
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", userID);
deletion.Prepare();
deletion.ExecuteNonQuery();
DiscordEmbed message = new DiscordEmbedBuilder
{
Color = DiscordColor.Green,
Description = "User was removed from staff."
};
await command.RespondAsync(message);
// Log it if the log channel exists
DiscordChannel logChannel = command.Guild.GetChannel(Config.logChannel);
if (logChannel != null)
{
DiscordEmbed logMessage = new DiscordEmbedBuilder
{
Color = DiscordColor.Green,
Description = "User was removed from staff.\n",
};
await logChannel.SendMessageAsync(logMessage);
}
}
}
}
}

View file

@ -1,96 +0,0 @@
using DSharpPlus.CommandsNext;
using DSharpPlus.CommandsNext.Attributes;
using DSharpPlus.Entities;
using Microsoft.Extensions.Logging;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace SupportChild.Commands
{
public class SayCommand : BaseCommandModule
{
[Command("say")]
[Cooldown(1, 2, CooldownBucketType.User)]
[Description("Prints a message with information from staff.")]
public async Task OnExecute(CommandContext command, string identifier)
{
// Check if the user has permission to use this command.
if (!Config.HasPermission(command.Member, "say"))
{
DiscordEmbed error = new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = "You do not have permission to use this command."
};
await command.RespondAsync(error);
command.Client.Logger.Log(LogLevel.Information, "User tried to use the say command but did not have permission.");
return;
}
if (!Database.TryGetMessage(identifier.ToLower(), out Database.Message message))
{
DiscordEmbed error = new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = "There is no message with that identifier."
};
await command.RespondAsync(error);
return;
}
DiscordEmbed reply = new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = message.message
};
await command.RespondAsync(reply);
}
[Command("say")]
[Cooldown(1, 2.0, CooldownBucketType.Channel)]
[Description("Prints a list of staff messages.")]
public async Task OnExecute(CommandContext command)
{
// Check if the user has permission to use this command.
if (!Config.HasPermission(command.Member, "say"))
{
DiscordEmbed error = new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = "You do not have permission to use this command."
};
await command.RespondAsync(error);
command.Client.Logger.Log(LogLevel.Information, "User tried to use the say command but did not have permission.");
return;
}
List<Database.Message> messages = Database.GetAllMessages();
if (!messages.Any())
{
DiscordEmbed error = new DiscordEmbedBuilder()
.WithColor(DiscordColor.Red)
.WithDescription("There are no messages registered.");
await command.RespondAsync(error);
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)
{
DiscordEmbed channelInfo = new DiscordEmbedBuilder()
.WithTitle("Available messages: ")
.WithColor(DiscordColor.Green)
.WithDescription(listMessage);
await command.RespondAsync(channelInfo);
}
}
}
}

View file

@ -1,63 +0,0 @@
using System.Threading.Tasks;
using DSharpPlus.CommandsNext;
using DSharpPlus.CommandsNext.Attributes;
using DSharpPlus.Entities;
using Microsoft.Extensions.Logging;
using MySql.Data.MySqlClient;
namespace SupportChild.Commands
{
public class SetSummaryCommand : BaseCommandModule
{
[Command("setsummary")]
[Cooldown(1, 5, CooldownBucketType.User)]
public async Task OnExecute(CommandContext command, [RemainingText] string commandArgs)
{
// Check if the user has permission to use this command.
if (!Config.HasPermission(command.Member, "setsummary"))
{
DiscordEmbed error = new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = "You do not have permission to use this command."
};
await command.RespondAsync(error);
command.Client.Logger.Log(LogLevel.Information, "User tried to use the setsummary command but did not have permission.");
return;
}
ulong channelID = command.Channel.Id;
// Check if ticket exists in the database
if (!Database.TryGetOpenTicket(command.Channel.Id, out Database.Ticket ticket))
{
DiscordEmbed error = new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = "This channel is not a ticket."
};
await command.RespondAsync(error);
return;
}
string sumarry = command.Message.Content.Replace(Config.prefix + "setsummary", "").Trim();
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", sumarry);
update.Parameters.AddWithValue("@channel_id", channelID);
update.Prepare();
update.ExecuteNonQuery();
update.Dispose();
DiscordEmbed message = new DiscordEmbedBuilder
{
Color = DiscordColor.Green,
Description = "Summary set."
};
await command.RespondAsync(message);
}
}
}
}

View file

@ -1,98 +0,0 @@
using System.Linq;
using System.Threading.Tasks;
using DSharpPlus.CommandsNext;
using DSharpPlus.CommandsNext.Attributes;
using DSharpPlus.Entities;
using Microsoft.Extensions.Logging;
using MySql.Data.MySqlClient;
namespace SupportChild.Commands
{
public class SetTicketCommand : BaseCommandModule
{
[Command("setticket")]
[Description("Turns a channel into a ticket, warning: this will let anyone with write access delete the channel using the close command.")]
public async Task OnExecute(CommandContext command, [RemainingText] string commandArgs)
{
using (MySqlConnection c = Database.GetConnection())
{
// Check if the user has permission to use this command.
if (!Config.HasPermission(command.Member, "setticket"))
{
DiscordEmbed error = new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = "You do not have permission to use this command."
};
await command.RespondAsync(error);
command.Client.Logger.Log(LogLevel.Information, "User tried to use the setticket command but did not have permission.");
return;
}
// Check if ticket exists in the database
if (Database.IsOpenTicket(command.Channel.Id))
{
DiscordEmbed error = new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = "This channel is already a ticket."
};
await command.RespondAsync(error);
return;
}
ulong userID;
string[] parsedMessage = Utilities.ParseIDs(command.RawArgumentString);
if (!parsedMessage.Any())
{
userID = command.Member.Id;
}
else if (!ulong.TryParse(parsedMessage[0], out userID))
{
DiscordEmbed error = new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = "Invalid ID/Mention. (Could not convert to numerical)"
};
await command.RespondAsync(error);
return;
}
DiscordUser user = await command.Client.GetUserAsync(userID);
if (user == null)
{
DiscordEmbed error = new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = "Invalid ID/Mention."
};
await command.RespondAsync(error);
return;
}
long id = Database.NewTicket(userID, 0, command.Channel.Id);
string ticketID = id.ToString("00000");
DiscordEmbed message = new DiscordEmbedBuilder
{
Color = DiscordColor.Green,
Description = "Channel has been designated ticket " + ticketID + "."
};
await command.RespondAsync(message);
// Log it if the log channel exists
DiscordChannel logChannel = command.Guild.GetChannel(Config.logChannel);
if (logChannel != null)
{
DiscordEmbed logMessage = new DiscordEmbedBuilder
{
Color = DiscordColor.Green,
Description = command.Channel.Mention + " has been designated ticket " + ticketID + " by " + command.Member.Mention + "."
};
await logChannel.SendMessageAsync(logMessage);
}
}
}
}
}

View file

@ -1,41 +0,0 @@
using System.Threading.Tasks;
using DSharpPlus.CommandsNext;
using DSharpPlus.CommandsNext.Attributes;
using DSharpPlus.Entities;
using Microsoft.Extensions.Logging;
namespace SupportChild.Commands
{
public class StatusCommand : BaseCommandModule
{
[Command("status")]
[Cooldown(1, 5, CooldownBucketType.User)]
public async Task OnExecute(CommandContext command, [RemainingText] string commandArgs)
{
// Check if the user has permission to use this command.
if (!Config.HasPermission(command.Member, "status"))
{
DiscordEmbed error = new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = "You do not have permission to use this command."
};
await command.RespondAsync(error);
command.Client.Logger.Log(LogLevel.Information, "User tried to use the status command but did not have permission.");
return;
}
long openTickets = Database.GetNumberOfTickets();
long closedTickets = Database.GetNumberOfClosedTickets();
DiscordEmbed botInfo = new DiscordEmbedBuilder()
.WithAuthor("EmotionChild/SupportChild @ GitHub", "https://github.com/EmotionChild/SupportChild", "https://cdn.discordapp.com/attachments/765441543100170271/919729931922051072/Ellise_Concept_2.png")
.WithTitle("Bot information")
.WithColor(DiscordColor.Cyan)
.AddField("Version:", SupportChild.GetVersion(), false)
.AddField("Open tickets:", openTickets + "", true)
.AddField("Closed tickets (1.1.0+ tickets only):", closedTickets + " ", true);
await command.RespondAsync(botInfo);
}
}
}

View file

@ -1,51 +0,0 @@
using System.Threading.Tasks;
using DSharpPlus.CommandsNext;
using DSharpPlus.CommandsNext.Attributes;
using DSharpPlus.Entities;
using Microsoft.Extensions.Logging;
namespace SupportChild.Commands
{
public class SummaryCommand : BaseCommandModule
{
[Command("summary")]
[Cooldown(1, 5, CooldownBucketType.User)]
public async Task OnExecute(CommandContext command, [RemainingText] string commandArgs)
{
// Check if the user has permission to use this command.
if (!Config.HasPermission(command.Member, "summary"))
{
DiscordEmbed error = new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = "You do not have permission to use this command."
};
await command.RespondAsync(error);
command.Client.Logger.Log(LogLevel.Information, "User tried to use the summary command but did not have permission.");
return;
}
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(), true)
.AddField("Ticket creator:", $"<@{ticket.creatorID}>", true)
.AddField("Assigned staff:", ticket.assignedStaffID == 0 ? "Unassigned." : $"<@{ticket.assignedStaffID}>", true)
.AddField("Creation time:", ticket.createdTime.ToString(Config.timestampFormat), true)
.AddField("Summary:", string.IsNullOrEmpty(ticket.summary) ? "No summary." : ticket.summary, false);
await command.RespondAsync(channelInfo);
}
else
{
DiscordEmbed error = new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = "This channel is not a ticket."
};
await command.RespondAsync(error);
}
}
}
}

View file

@ -1,78 +0,0 @@
using System.Linq;
using System.Threading.Tasks;
using DSharpPlus.CommandsNext;
using DSharpPlus.CommandsNext.Attributes;
using DSharpPlus.Entities;
using Microsoft.Extensions.Logging;
using MySql.Data.MySqlClient;
namespace SupportChild.Commands
{
public class ToggleActiveCommand : BaseCommandModule
{
[Command("toggleactive")]
[Aliases("ta")]
public async Task OnExecute(CommandContext command, [RemainingText] string commandArgs)
{
using (MySqlConnection c = Database.GetConnection())
{
// Check if the user has permission to use this command.
if (!Config.HasPermission(command.Member, "toggleactive"))
{
DiscordEmbed error = new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = "You do not have permission to use this command."
};
await command.RespondAsync(error);
command.Client.Logger.Log(LogLevel.Information, "User tried to use the toggleactive command but did not have permission.");
return;
}
ulong staffID;
string[] parsedMessage = Utilities.ParseIDs(command.RawArgumentString);
if (!parsedMessage.Any())
{
staffID = command.Member.Id;
}
else if (!ulong.TryParse(parsedMessage[0], out staffID))
{
DiscordEmbed error = new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = "Invalid ID/Mention. (Could not convert to numerical)"
};
await command.RespondAsync(error);
return;
}
// Check if ticket exists in the database
if (!Database.TryGetStaff(staffID, out Database.StaffMember staffMember))
{
DiscordEmbed error = new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = "You have not been registered as staff."
};
await command.RespondAsync(error);
return;
}
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", !staffMember.active);
update.Prepare();
update.ExecuteNonQuery();
DiscordEmbed message = new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
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."
};
await command.RespondAsync(message);
}
}
}
}

View file

@ -1,172 +0,0 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using DSharpPlus.CommandsNext;
using DSharpPlus.CommandsNext.Attributes;
using DSharpPlus.Entities;
using DSharpPlus.Exceptions;
using Microsoft.Extensions.Logging;
namespace SupportChild.Commands
{
public class TranscriptCommand : BaseCommandModule
{
[Command("transcript")]
[Cooldown(1, 5, CooldownBucketType.User)]
public async Task OnExecute(CommandContext command, [RemainingText] string commandArgs)
{
// Check if the user has permission to use this command.
if (!Config.HasPermission(command.Member, "transcript"))
{
DiscordEmbed error = new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = "You do not have permission to use this command."
};
await command.RespondAsync(error);
command.Client.Logger.Log(LogLevel.Information, "User tried to use the transcript but did not have permission.");
return;
}
Database.Ticket ticket;
string strippedMessage = command.Message.Content.Replace(Config.prefix, "");
string[] parsedMessage = strippedMessage.Replace("<@!", "").Replace("<@", "").Replace(">", "").Split();
// If there are no arguments use current channel
if (parsedMessage.Length < 2)
{
if (Database.TryGetOpenTicket(command.Channel.Id, out ticket))
{
try
{
await Transcriber.ExecuteAsync(command.Channel.Id, ticket.id);
}
catch (Exception)
{
DiscordEmbed error = new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = "ERROR: Could not save transcript file. Aborting..."
};
await command.RespondAsync(error);
throw;
}
}
else
{
DiscordEmbed error = new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = "This channel is not a ticket."
};
await command.RespondAsync(error);
return;
}
}
else
{
// Check if argument is numerical, if not abort
if (!uint.TryParse(parsedMessage[1], out uint ticketID))
{
DiscordEmbed error = new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = "Argument must be a number."
};
await command.RespondAsync(error);
return;
}
// If the ticket is still open, generate a new fresh transcript
if (Database.TryGetOpenTicketByID(ticketID, out ticket) && ticket?.creatorID == command.Member.Id)
{
try
{
await Transcriber.ExecuteAsync(command.Channel.Id, ticket.id);
}
catch (Exception)
{
DiscordEmbed error = new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = "ERROR: Could not save transcript file. Aborting..."
};
await command.RespondAsync(error);
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(ticketID, out ticket) || (ticket?.creatorID != command.Member.Id && !Database.IsStaff(command.Member.Id)))
{
DiscordEmbed error = new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = "Could not find a closed ticket with that number which you opened." + (Config.HasPermission(command.Member, "list") ? "\n(Use the " + Config.prefix + "list command to see all your tickets)" : "")
};
await command.RespondAsync(error);
return;
}
}
// Log it if the log channel exists
DiscordChannel logChannel = command.Guild.GetChannel(Config.logChannel);
if (logChannel != null)
{
DiscordEmbed embed = 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 }
};
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);
}
}
try
{
// Send transcript privately
DiscordEmbed directMessageEmbed = new DiscordEmbedBuilder
{
Color = DiscordColor.Green,
Description = "Transcript generated, " + command.Member.Mention + "!\n"
};
using (FileStream file = new FileStream(Transcriber.GetPath(ticket.id), FileMode.Open, FileAccess.Read))
{
DiscordMessageBuilder directMessage = new DiscordMessageBuilder();
directMessage.WithEmbed(directMessageEmbed);
directMessage.WithFiles(new Dictionary<string, Stream>() { { Transcriber.GetFilename(ticket.id), file } });
await command.Member.SendMessageAsync(directMessage);
}
// Respond to message directly
DiscordEmbed response = new DiscordEmbedBuilder
{
Color = DiscordColor.Green,
Description = "Transcript sent, " + command.Member.Mention + "!\n"
};
await command.RespondAsync(response);
}
catch (UnauthorizedException)
{
// Send transcript privately
DiscordEmbed error = new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = "Not allowed to send direct message to you, " + command.Member.Mention + ", please check your privacy settings.\n"
};
await command.RespondAsync(error);
}
}
}
}

View file

@ -1,71 +0,0 @@
using System.Threading.Tasks;
using DSharpPlus.CommandsNext;
using DSharpPlus.CommandsNext.Attributes;
using DSharpPlus.Entities;
using Microsoft.Extensions.Logging;
namespace SupportChild.Commands
{
public class UnassignCommand : BaseCommandModule
{
[Command("unassign")]
[Description("Unassigns a staff member from a ticket.")]
public async Task OnExecute(CommandContext command, [RemainingText] string commandArgs)
{
// Check if the user has permission to use this command.
if (!Config.HasPermission(command.Member, "unassign"))
{
DiscordEmbed error = new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = "You do not have permission to use this command."
};
await command.RespondAsync(error);
command.Client.Logger.Log(LogLevel.Information, "User tried to use the unassign command but did not have permission.");
return;
}
// Check if ticket exists in the database
if (!Database.TryGetOpenTicket(command.Channel.Id, out Database.Ticket ticket))
{
DiscordEmbed error = new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = "This channel is not a ticket."
};
await command.RespondAsync(error);
return;
}
if (!Database.UnassignStaff(ticket))
{
DiscordEmbed error = new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = "Error: Failed to unassign staff from ticket."
};
await command.RespondAsync(error);
return;
}
DiscordEmbed message = new DiscordEmbedBuilder
{
Color = DiscordColor.Green,
Description = "Unassigned staff from ticket."
};
await command.RespondAsync(message);
// Log it if the log channel exists
DiscordChannel logChannel = command.Guild.GetChannel(Config.logChannel);
if (logChannel != null)
{
DiscordEmbed logMessage = new DiscordEmbedBuilder
{
Color = DiscordColor.Green,
Description = "Staff was unassigned from " + command.Channel.Mention + " by " + command.Member.Mention + "."
};
await logChannel.SendMessageAsync(logMessage);
}
}
}
}

View file

@ -1,99 +0,0 @@
using System;
using System.Threading.Tasks;
using DSharpPlus.CommandsNext;
using DSharpPlus.CommandsNext.Attributes;
using DSharpPlus.Entities;
using DSharpPlus.Exceptions;
using Microsoft.Extensions.Logging;
namespace SupportChild.Commands
{
public class UnblacklistCommand : BaseCommandModule
{
[Command("unblacklist")]
[Description("Un-blacklists a user from from opening tickets.")]
public async Task OnExecute(CommandContext command, [RemainingText] string commandArgs)
{
// Check if the user has permission to use this command.
if (!Config.HasPermission(command.Member, "unblacklist"))
{
DiscordEmbed error = new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = "You do not have permission to use this command."
};
await command.RespondAsync(error);
command.Client.Logger.Log(LogLevel.Information, "User tried to use the unblacklist command but did not have permission.");
return;
}
string[] words = Utilities.ParseIDs(command.RawArgumentString);
foreach (string word in words)
{
if (ulong.TryParse(word, out ulong userId))
{
DiscordUser blacklistedUser = null;
try
{
blacklistedUser = await command.Client.GetUserAsync(userId);
}
catch (NotFoundException) { }
if (blacklistedUser == null)
{
DiscordEmbed message = new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = "Error: Could not find user."
};
await command.RespondAsync(message);
continue;
}
try
{
if (!Database.Unblacklist(blacklistedUser.Id))
{
DiscordEmbed error = new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = blacklistedUser.Mention + " is not blacklisted."
};
await command.RespondAsync(error);
continue;
}
DiscordEmbed message = new DiscordEmbedBuilder
{
Color = DiscordColor.Green,
Description = "Removed " + blacklistedUser.Mention + " from blacklist."
};
await command.RespondAsync(message);
// Log it if the log channel exists
DiscordChannel logChannel = command.Guild.GetChannel(Config.logChannel);
if (logChannel != null)
{
DiscordEmbed logMessage = new DiscordEmbedBuilder
{
Color = DiscordColor.Green,
Description = blacklistedUser.Mention + " was unblacklisted from opening tickets by " + command.Member.Mention + "."
};
await logChannel.SendMessageAsync(logMessage);
}
}
catch (Exception)
{
DiscordEmbed message = new DiscordEmbedBuilder()
{
Color = DiscordColor.Red,
Description = "Error occured while removing " + blacklistedUser.Mention + " from blacklist."
};
await command.RespondAsync(message);
throw;
}
}
}
}
}
}

View file

@ -1,70 +0,0 @@
using System.Threading.Tasks;
using DSharpPlus.CommandsNext;
using DSharpPlus.CommandsNext.Attributes;
using DSharpPlus.Entities;
using Microsoft.Extensions.Logging;
using MySql.Data.MySqlClient;
namespace SupportChild.Commands
{
public class UnsetTicketCommand : BaseCommandModule
{
[Command("unsetticket")]
[Description(
"Deletes a channel from the ticket system without deleting the channel.")]
public async Task OnExecute(CommandContext command, [RemainingText] string commandArgs)
{
using (MySqlConnection c = Database.GetConnection())
{
// Check if the user has permission to use this command.
if (!Config.HasPermission(command.Member, "unsetticket"))
{
DiscordEmbed error = new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = "You do not have permission to use this command."
};
await command.RespondAsync(error);
command.Client.Logger.Log(LogLevel.Information, "User tried to use the unsetticket command but did not have permission.");
return;
}
// Check if ticket exists in the database
if (!Database.TryGetOpenTicket(command.Channel.Id, out Database.Ticket ticket))
{
DiscordEmbed error = new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = "This channel is not a ticket."
};
await command.RespondAsync(error);
return;
}
c.Open();
MySqlCommand deletion = new MySqlCommand(@"DELETE FROM tickets WHERE channel_id=@channel_id", c);
deletion.Parameters.AddWithValue("@channel_id", command.Channel.Id);
deletion.Prepare();
deletion.ExecuteNonQuery();
DiscordEmbed message = new DiscordEmbedBuilder
{
Color = DiscordColor.Green,
Description = "Channel has been undesignated as a ticket."
};
await command.RespondAsync(message);
// Log it if the log channel exists
DiscordChannel logChannel = command.Guild.GetChannel(Config.logChannel);
if (logChannel != null)
{
DiscordEmbed logMessage = new DiscordEmbedBuilder
{
Color = DiscordColor.Green,
Description = command.Channel.Mention + " has been undesignated as a ticket by " + command.Member.Mention + "."
};
await logChannel.SendMessageAsync(logMessage);
}
}
}
}
}

View file

@ -1,143 +0,0 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using DSharpPlus.Entities;
using Newtonsoft.Json.Linq;
using SupportChild.Properties;
using YamlDotNet.Serialization;
namespace SupportChild
{
internal static class Config
{
internal static string token = "";
internal static string prefix = "";
internal static ulong logChannel;
internal static ulong ticketCategory;
internal static ulong reactionMessage;
internal static string welcomeMessage = "";
internal static string logLevel = "Information";
internal static string timestampFormat = "yyyy-MMM-dd HH:mm";
internal static bool randomAssignment = false;
internal static bool randomAssignRoleOverride = false; // TODO: Implement
internal static string presenceType = "Playing";
internal static string presenceText = "";
internal static bool ticketUpdatedNotifications = false;
internal static double ticketUpdatedNotificationDelay = 0.0;
internal static bool assignmentNotifications = false;
internal static bool closingNotifications = false;
internal static string hostName = "127.0.0.1";
internal static int port = 3306;
internal static string database = "supportbot";
internal static string username = "supportbot";
internal static string password = "";
private static readonly Dictionary<string, ulong[]> permissions = new Dictionary<string, ulong[]>
{
// Public commands
{ "close", new ulong[]{ } },
{ "list", new ulong[]{ } },
{ "new", new ulong[]{ } },
{ "say", new ulong[]{ } },
{ "status", new ulong[]{ } },
{ "summary", new ulong[]{ } },
{ "transcript", new ulong[]{ } },
// Moderator commands
{ "add", new ulong[]{ } },
{ "addmessage", new ulong[]{ } },
{ "assign", new ulong[]{ } },
{ "blacklist", new ulong[]{ } },
{ "listassigned", new ulong[]{ } },
{ "listoldest", new ulong[]{ } },
{ "listunassigned", new ulong[]{ } },
{ "move", new ulong[]{ } },
{ "rassign", new ulong[]{ } },
{ "removemessage", new ulong[]{ } },
{ "setsummary", new ulong[]{ } },
{ "toggleactive", new ulong[]{ } },
{ "unassign", new ulong[]{ } },
{ "unblacklist", new ulong[]{ } },
// Admin commands
{ "addstaff", new ulong[]{ } },
{ "reload", new ulong[]{ } },
{ "removestaff", new ulong[]{ } },
{ "setticket", new ulong[]{ } },
{ "unsetticket", new ulong[]{ } },
};
public static void LoadConfig()
{
// Writes default config to file if it does not already exist
if (!File.Exists("./config.yml"))
{
File.WriteAllText("./config.yml", Encoding.UTF8.GetString(Resources.default_config));
}
// Reads config contents into FileStream
FileStream stream = File.OpenRead("./config.yml");
// Converts the FileStream into a YAML object
IDeserializer deserializer = new DeserializerBuilder().Build();
object yamlObject = deserializer.Deserialize(new StreamReader(stream));
// Converts the YAML object into a JSON object as the YAML ones do not support traversal or selection of nodes by name
ISerializer serializer = new SerializerBuilder().JsonCompatible().Build();
JObject json = JObject.Parse(serializer.Serialize(yamlObject));
// Sets up the bot
token = json.SelectToken("bot.token").Value<string>() ?? "";
prefix = json.SelectToken("bot.prefix").Value<string>() ?? "";
logChannel = json.SelectToken("bot.log-channel").Value<ulong>();
ticketCategory = json.SelectToken("bot.ticket-category")?.Value<ulong>() ?? 0;
reactionMessage = json.SelectToken("bot.reaction-message")?.Value<ulong>() ?? 0;
welcomeMessage = json.SelectToken("bot.welcome-message").Value<string>() ?? "";
logLevel = json.SelectToken("bot.console-log-level").Value<string>() ?? "";
timestampFormat = json.SelectToken("bot.timestamp-format").Value<string>() ?? "yyyy-MM-dd HH:mm";
randomAssignment = json.SelectToken("bot.random-assignment")?.Value<bool>() ?? false;
randomAssignRoleOverride = json.SelectToken("bot.random-assign-role-override")?.Value<bool>() ?? false;
presenceType = json.SelectToken("bot.presence-type")?.Value<string>() ?? "Playing";
presenceText = json.SelectToken("bot.presence-text")?.Value<string>() ?? "";
ticketUpdatedNotifications = json.SelectToken("notifications.ticket-updated")?.Value<bool>() ?? false;
ticketUpdatedNotificationDelay = json.SelectToken("notifications.ticket-updated-delay")?.Value<double>() ?? 0.0;
assignmentNotifications = json.SelectToken("notifications.assignment")?.Value<bool>() ?? false;
closingNotifications = json.SelectToken("notifications.closing")?.Value<bool>() ?? false;
// Reads database info
hostName = json.SelectToken("database.address")?.Value<string>() ?? "";
port = json.SelectToken("database.port")?.Value<int>() ?? 3306;
database = json.SelectToken("database.name")?.Value<string>() ?? "supportbot";
username = json.SelectToken("database.user")?.Value<string>() ?? "supportbot";
password = json.SelectToken("database.password")?.Value<string>() ?? "";
timestampFormat = timestampFormat.Trim();
foreach (KeyValuePair<string, ulong[]> node in permissions.ToList())
{
try
{
permissions[node.Key] = json.SelectToken("permissions." + node.Key).Value<JArray>().Values<ulong>().ToArray();
}
catch (ArgumentNullException)
{
Console.WriteLine("Permission node '" + node.Key + "' was not found in the config, using default value: []");
}
}
}
/// <summary>
/// Checks whether a user has a specific permission.
/// </summary>
/// <param name="member">The Discord user to check.</param>
/// <param name="permission">The permission name to check.</param>
/// <returns></returns>
public static bool HasPermission(DiscordMember member, string permission)
{
return member.Roles.Any(role => permissions[permission].Contains(role.Id)) || permissions[permission].Contains(member.Guild.Id);
}
}
}

View file

@ -1,691 +0,0 @@
using System;
using System.Linq;
using System.Collections.Generic;
using MySql.Data.MySqlClient;
namespace SupportChild
{
public static class Database
{
private static string connectionString = "";
private static 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())
{
MySqlCommand countTickets = new MySqlCommand("SELECT COUNT(*) FROM tickets", c);
c.Open();
return (long)countTickets.ExecuteScalar();
}
}
catch (Exception e)
{
Console.WriteLine("Error occured when attempting to count number of open tickets: " + e);
}
return -1;
}
public static long GetNumberOfClosedTickets()
{
try
{
using (MySqlConnection c = GetConnection())
{
MySqlCommand countTickets = new MySqlCommand("SELECT COUNT(*) FROM ticket_history", c);
c.Open();
return (long)countTickets.ExecuteScalar();
}
}
catch (Exception e)
{
Console.WriteLine("Error occured when attempting to count number of open tickets: " + e);
}
return -1;
}
public static void SetupTables()
{
using (MySqlConnection c = GetConnection())
{
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);
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);
MySqlCommand createBlacklisted = new MySqlCommand(
"CREATE TABLE IF NOT EXISTS blacklisted_users(" +
"user_id BIGINT UNSIGNED NOT NULL PRIMARY KEY," +
"time DATETIME NOT NULL," +
"moderator_id BIGINT UNSIGNED NOT NULL," +
"INDEX(user_id, time))",
c);
MySqlCommand createStaffList = new MySqlCommand(
"CREATE TABLE IF NOT EXISTS staff(" +
"user_id BIGINT UNSIGNED NOT NULL PRIMARY KEY," +
"name VARCHAR(256) NOT NULL," +
"active BOOLEAN NOT NULL DEFAULT true)",
c);
MySqlCommand createMessages = new MySqlCommand(
"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);
c.Open();
createTickets.ExecuteNonQuery();
createBlacklisted.ExecuteNonQuery();
createTicketHistory.ExecuteNonQuery();
createStaffList.ExecuteNonQuery();
createMessages.ExecuteNonQuery();
}
}
public static bool IsOpenTicket(ulong channelID)
{
using (MySqlConnection c = GetConnection())
{
c.Open();
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();
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();
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);
return true;
}
ticket = null;
return false;
}
}
public static bool TryGetClosedTicket(uint id, out Ticket ticket)
{
using (MySqlConnection c = GetConnection())
{
c.Open();
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);
return true;
}
ticket = null;
return false;
}
}
public static bool TryGetOpenTickets(ulong userID, out List<Ticket> tickets)
{
tickets = null;
using (MySqlConnection c = GetConnection())
{
c.Open();
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 TryGetOldestTickets(ulong userID, out List<Ticket> tickets, int listLimit)
{
tickets = null;
using (MySqlConnection c = GetConnection())
{
c.Open();
MySqlCommand selection = new MySqlCommand(@"SELECT * FROM tickets ORDER BY created_time ASC LIMIT @limit", c);
selection.Parameters.AddWithValue("@creator_id", userID);
selection.Parameters.AddWithValue("@limit", listLimit);
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();
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();
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();
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())
{
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();
}
}
using (MySqlConnection c = GetConnection())
{
// Create an entry in the ticket history database
MySqlCommand archiveTicket = new MySqlCommand(@"INSERT INTO ticket_history (id, created_time, closed_time, creator_id, assigned_staff_id, summary, channel_id) VALUES (@id, @created_time, UTC_TIMESTAMP(), @creator_id, @assigned_staff_id, @summary, @channel_id);", c);
archiveTicket.Parameters.AddWithValue("@id", ticket.id);
archiveTicket.Parameters.AddWithValue("@created_time", ticket.createdTime);
archiveTicket.Parameters.AddWithValue("@creator_id", ticket.creatorID);
archiveTicket.Parameters.AddWithValue("@assigned_staff_id", ticket.assignedStaffID);
archiveTicket.Parameters.AddWithValue("@summary", ticket.summary);
archiveTicket.Parameters.AddWithValue("@channel_id", ticket.channelID);
c.Open();
archiveTicket.Prepare();
archiveTicket.ExecuteNonQuery();
}
}
public static void DeleteOpenTicket(uint ticketID)
{
using (MySqlConnection c = GetConnection())
{
MySqlCommand deletion = new MySqlCommand(@"DELETE FROM tickets WHERE id=@id", c);
deletion.Parameters.AddWithValue("@id", ticketID);
c.Open();
deletion.Prepare();
deletion.ExecuteNonQuery();
}
}
public static bool IsBlacklisted(ulong userID)
{
using (MySqlConnection c = GetConnection())
{
c.Open();
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)
{
using (MySqlConnection c = GetConnection())
{
try
{
c.Open();
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)
{
using (MySqlConnection c = GetConnection())
{
try
{
c.Open();
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)
{
using (MySqlConnection c = GetConnection())
{
try
{
c.Open();
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 StaffMember GetRandomActiveStaff(ulong currentStaffID)
{
List<StaffMember> staffMembers = GetActiveStaff(currentStaffID);
if (!staffMembers.Any())
{
return null;
}
return staffMembers[random.Next(staffMembers.Count)];
}
public static List<StaffMember> GetActiveStaff(ulong currentStaffID = 0)
{
using (MySqlConnection c = GetConnection())
{
c.Open();
MySqlCommand selection = new MySqlCommand(@"SELECT * FROM staff WHERE active = true AND user_id != @user_id", c);
selection.Parameters.AddWithValue("@user_id", currentStaffID);
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(ulong currentStaffID = 0)
{
using (MySqlConnection c = GetConnection())
{
c.Open();
MySqlCommand selection = new MySqlCommand(@"SELECT * FROM staff WHERE user_id != @user_id", c);
selection.Parameters.AddWithValue("@user_id", currentStaffID);
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();
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();
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();
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();
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)
{
using (MySqlConnection c = GetConnection())
{
try
{
c.Open();
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)
{
using (MySqlConnection c = GetConnection())
{
try
{
c.Open();
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 class Ticket
{
public uint id;
public DateTime createdTime;
public ulong creatorID;
public ulong assignedStaffID;
public string summary;
public ulong channelID;
public Ticket(MySqlDataReader reader)
{
this.id = reader.GetUInt32("id");
this.createdTime = reader.GetDateTime("created_time");
this.creatorID = reader.GetUInt64("creator_id");
this.assignedStaffID = reader.GetUInt64("assigned_staff_id");
this.summary = reader.GetString("summary");
this.channelID = reader.GetUInt64("channel_id");
}
public string FormattedCreatedTime()
{
return this.createdTime.ToString(Config.timestampFormat);
}
}
public class StaffMember
{
public ulong userID;
public string name;
public bool active;
public StaffMember(MySqlDataReader reader)
{
this.userID = reader.GetUInt64("user_id");
this.name = reader.GetString("name");
this.active = reader.GetBoolean("active");
}
}
public class Message
{
public string identifier;
public ulong userID;
public string message;
public Message(MySqlDataReader reader)
{
this.identifier = reader.GetString("identifier");
this.userID = reader.GetUInt64("user_id");
this.message = reader.GetString("message");
}
}
}
}

View file

@ -1,307 +0,0 @@
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using DSharpPlus;
using DSharpPlus.CommandsNext;
using DSharpPlus.CommandsNext.Attributes;
using DSharpPlus.CommandsNext.Exceptions;
using DSharpPlus.Entities;
using DSharpPlus.EventArgs;
using DSharpPlus.Exceptions;
using Microsoft.Extensions.Logging;
namespace SupportChild
{
internal class EventHandler
{
private DiscordClient discordClient;
//DateTime for the end of the cooldown
private static Dictionary<ulong, DateTime> reactionTicketCooldowns = new Dictionary<ulong, DateTime>();
public EventHandler(DiscordClient client)
{
this.discordClient = client;
}
internal Task OnReady(DiscordClient client, ReadyEventArgs e)
{
discordClient.Logger.Log(LogLevel.Information, "Client is ready to process events.");
// Checking activity type
if (!Enum.TryParse(Config.presenceType, true, out ActivityType activityType))
{
Console.WriteLine("Presence type '" + Config.presenceType + "' invalid, using 'Playing' instead.");
activityType = ActivityType.Playing;
}
this.discordClient.UpdateStatusAsync(new DiscordActivity(Config.presenceText, activityType), UserStatus.Online);
return Task.CompletedTask;
}
internal Task OnGuildAvailable(DiscordClient client, GuildCreateEventArgs e)
{
discordClient.Logger.Log(LogLevel.Information, $"Guild available: {e.Guild.Name}");
IReadOnlyDictionary<ulong, DiscordRole> roles = e.Guild.Roles;
foreach ((ulong roleID, DiscordRole role) in roles)
{
discordClient.Logger.Log(LogLevel.Information, role.Name.PadRight(40, '.') + roleID);
}
return Task.CompletedTask;
}
internal Task OnClientError(DiscordClient client, ClientErrorEventArgs e)
{
discordClient.Logger.Log(LogLevel.Error, $"Exception occured: {e.Exception.GetType()}: {e.Exception}");
return Task.CompletedTask;
}
internal async Task OnMessageCreated(DiscordClient client, MessageCreateEventArgs e)
{
if (e.Author.IsBot)
{
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
{
DiscordEmbed message = new DiscordEmbedBuilder
{
Color = DiscordColor.Green,
Description = "A ticket you are assigned to has been updated: " + e.Channel.Mention
};
DiscordMember staffMember = await e.Guild.GetMemberAsync(ticket.assignedStaffID);
await staffMember.SendMessageAsync(message);
}
catch (NotFoundException) { }
catch (UnauthorizedException) { }
}
}
internal Task OnCommandError(CommandsNextExtension commandSystem, CommandErrorEventArgs e)
{
switch (e.Exception)
{
case CommandNotFoundException _:
return Task.CompletedTask;
case ChecksFailedException _:
{
foreach (CheckBaseAttribute attr in ((ChecksFailedException)e.Exception).FailedChecks)
{
DiscordEmbed error = new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = this.ParseFailedCheck(attr)
};
e.Context?.Channel?.SendMessageAsync(error);
}
return Task.CompletedTask;
}
default:
{
discordClient.Logger.Log(LogLevel.Error, $"Exception occured: {e.Exception.GetType()}: {e.Exception}");
DiscordEmbed error = new DiscordEmbedBuilder
{
Color = DiscordColor.Red,
Description = "Internal error occured, please report this to the developer."
};
e.Context?.Channel?.SendMessageAsync(error);
return Task.CompletedTask;
}
}
}
internal async Task OnReactionAdded(DiscordClient client, MessageReactionAddEventArgs e)
{
if (e.Message.Id != Config.reactionMessage) return;
DiscordGuild guild = e.Message.Channel.Guild;
DiscordMember member = await guild.GetMemberAsync(e.User.Id);
if (!Config.HasPermission(member, "new") || Database.IsBlacklisted(member.Id)) return;
if (reactionTicketCooldowns.ContainsKey(member.Id))
{
if (reactionTicketCooldowns[member.Id] > DateTime.Now) return; // cooldown has not expired
else reactionTicketCooldowns.Remove(member.Id); // cooldown exists but has expired, delete it
}
DiscordChannel category = guild.GetChannel(Config.ticketCategory);
DiscordChannel ticketChannel = await guild.CreateChannelAsync("ticket", ChannelType.Text, category);
if (ticketChannel == null) return;
ulong staffID = 0;
if (Config.randomAssignment)
{
staffID = Database.GetRandomActiveStaff(0)?.userID ?? 0;
}
long id = Database.NewTicket(member.Id, staffID, ticketChannel.Id);
reactionTicketCooldowns.Add(member.Id, DateTime.Now.AddSeconds(10)); // add a cooldown which expires in 10 seconds
string ticketID = id.ToString("00000");
await ticketChannel.ModifyAsync(model => model.Name = "ticket-" + ticketID);
await ticketChannel.AddOverwriteAsync(member, Permissions.AccessChannels, Permissions.None);
await ticketChannel.SendMessageAsync("Hello, " + member.Mention + "!\n" + Config.welcomeMessage);
// Remove user's reaction
await e.Message.DeleteReactionAsync(e.Emoji, e.User);
// Refreshes the channel as changes were made to it above
ticketChannel = await SupportChild.GetClient().GetChannelAsync(ticketChannel.Id);
if (staffID != 0)
{
DiscordEmbed assignmentMessage = new DiscordEmbedBuilder
{
Color = DiscordColor.Green,
Description = "Ticket was randomly assigned to <@" + staffID + ">."
};
await ticketChannel.SendMessageAsync(assignmentMessage);
if (Config.assignmentNotifications)
{
DiscordEmbed message = new DiscordEmbedBuilder
{
Color = DiscordColor.Green,
Description = "You have been randomly assigned to a newly opened support ticket: " +
ticketChannel.Mention
};
try
{
DiscordMember staffMember = await guild.GetMemberAsync(staffID);
await staffMember.SendMessageAsync(message);
}
catch (NotFoundException)
{
}
catch (UnauthorizedException)
{
}
}
}
// Log it if the log channel exists
DiscordChannel logChannel = guild.GetChannel(Config.logChannel);
if (logChannel != null)
{
DiscordEmbed logMessage = new DiscordEmbedBuilder
{
Color = DiscordColor.Green,
Description = "Ticket " + ticketChannel.Mention + " opened by " + member.Mention + ".\n",
Footer = new DiscordEmbedBuilder.EmbedFooter { Text = "Ticket " + ticketID }
};
await logChannel.SendMessageAsync(logMessage);
}
}
internal async Task OnMemberAdded(DiscordClient client, GuildMemberAddEventArgs e)
{
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.AddOverwriteAsync(e.Member, Permissions.AccessChannels, Permissions.None);
DiscordEmbed message = new DiscordEmbedBuilder()
.WithColor(DiscordColor.Green)
.WithDescription("User '" + e.Member.Username + "#" + e.Member.Discriminator + "' has rejoined the server, and has been re-added to the ticket.");
await channel.SendMessageAsync(message);
}
}
catch (Exception) { }
}
}
internal 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)
{
DiscordEmbed message = new DiscordEmbedBuilder()
.WithColor(DiscordColor.Red)
.WithDescription("User '" + e.Member.Username + "#" + e.Member.Discriminator + "' has left the server.");
await channel.SendMessageAsync(message);
}
}
catch (Exception) { }
}
}
if (Database.TryGetAssignedTickets(e.Member.Id, out List<Database.Ticket> assignedTickets) && Config.logChannel != 0)
{
DiscordChannel logChannel = await client.GetChannelAsync(Config.logChannel);
if (logChannel != null)
{
foreach (Database.Ticket ticket in assignedTickets)
{
try
{
DiscordChannel channel = await client.GetChannelAsync(ticket.channelID);
if (channel?.GuildId == e.Guild.Id)
{
DiscordEmbed message = new DiscordEmbedBuilder()
.WithColor(DiscordColor.Red)
.WithDescription("Assigned staff member '" + e.Member.Username + "#" + e.Member.Discriminator + "' has left the server: <#" + channel.Id + ">");
await logChannel.SendMessageAsync(message);
}
}
catch (Exception) { }
}
}
}
}
private string ParseFailedCheck(CheckBaseAttribute attr)
{
switch (attr)
{
case CooldownAttribute _:
return "You cannot use do that so often!";
case RequireOwnerAttribute _:
return "Only the server owner can use that command!";
case RequirePermissionsAttribute _:
return "You don't have permission to do that!";
case RequireRolesAttribute _:
return "You do not have a required role!";
case RequireUserPermissionsAttribute _:
return "You don't have permission to do that!";
case RequireNsfwAttribute _:
return "This command can only be used in an NSFW channel!";
default:
return "Unknown Discord API error occured, please try again later.";
}
}
}
}

View file

@ -1,73 +0,0 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace SupportChild.Properties {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[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() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[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;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized resource of type System.Byte[].
/// </summary>
internal static byte[] default_config {
get {
object obj = ResourceManager.GetObject("default_config", resourceCulture);
return ((byte[])(obj));
}
}
}
}

View file

@ -1,123 +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>

View file

@ -1,163 +0,0 @@
using System;
using System.IO;
using System.Reflection;
using System.Threading.Tasks;
using DSharpPlus;
using DSharpPlus.CommandsNext;
using Microsoft.Extensions.Logging;
using SupportChild.Commands;
namespace SupportChild
{
internal class SupportChild
{
internal static SupportChild instance;
private DiscordClient discordClient = null;
private CommandsNextExtension commands = null;
private EventHandler eventHandler;
static void Main(string[] args)
{
new SupportChild().MainAsync().GetAwaiter().GetResult();
}
private async Task MainAsync()
{
instance = this;
Console.WriteLine("Starting SupportChild version " + GetVersion() + "...");
try
{
this.Reload();
// Block this task until the program is closed.
await Task.Delay(-1);
}
catch (Exception e)
{
Console.WriteLine("Fatal error:");
Console.WriteLine(e);
Console.ReadLine();
}
}
public static DiscordClient GetClient()
{
return instance.discordClient;
}
public static string GetVersion()
{
Version version = Assembly.GetEntryAssembly()?.GetName().Version;
return version?.Major + "." + version?.Minor + "." + version?.Build + (version?.Revision == 0 ? "" : "-" + (char)(64 + version?.Revision ?? 0));
}
public async void Reload()
{
if (this.discordClient != null)
{
await this.discordClient.DisconnectAsync();
this.discordClient.Dispose();
Console.WriteLine("Discord client disconnected.");
}
Console.WriteLine("Loading config \"" + Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar + "config.yml\"");
Config.LoadConfig();
// Check if token is unset
if (Config.token == "<add-token-here>" || Config.token == "")
{
Console.WriteLine("You need to set your bot token in the config and start the bot again.");
throw new ArgumentException("Invalid Discord bot token");
}
// Database connection and setup
try
{
Console.WriteLine("Connecting to database... (" + Config.hostName + ":" + Config.port + ")");
Database.SetConnectionString(Config.hostName, Config.port, Config.database, Config.username, Config.password);
Database.SetupTables();
}
catch (Exception e)
{
Console.WriteLine("Could not set up database tables, please confirm connection settings, status of the server and permissions of MySQL user. Error: " + e);
throw;
}
Console.WriteLine("Setting up Discord client...");
// Checking log level
if (!Enum.TryParse(Config.logLevel, true, out LogLevel logLevel))
{
Console.WriteLine("Log level '" + Config.logLevel + "' invalid, using 'Information' instead.");
logLevel = LogLevel.Information;
}
// Setting up client configuration
DiscordConfiguration cfg = new DiscordConfiguration
{
Token = Config.token,
TokenType = TokenType.Bot,
MinimumLogLevel = logLevel,
AutoReconnect = true,
Intents = DiscordIntents.All
};
this.discordClient = new DiscordClient(cfg);
this.eventHandler = new EventHandler(this.discordClient);
Console.WriteLine("Hooking events...");
this.discordClient.Ready += this.eventHandler.OnReady;
this.discordClient.GuildAvailable += this.eventHandler.OnGuildAvailable;
this.discordClient.ClientErrored += this.eventHandler.OnClientError;
this.discordClient.MessageCreated += this.eventHandler.OnMessageCreated;
this.discordClient.GuildMemberAdded += this.eventHandler.OnMemberAdded;
this.discordClient.GuildMemberRemoved += this.eventHandler.OnMemberRemoved;
if (Config.reactionMessage != 0)
{
this.discordClient.MessageReactionAdded += this.eventHandler.OnReactionAdded;
}
Console.WriteLine("Registering commands...");
commands = discordClient.UseCommandsNext(new CommandsNextConfiguration
{
StringPrefixes = new[] { Config.prefix }
});
this.commands.RegisterCommands<AddCommand>();
this.commands.RegisterCommands<AddMessageCommand>();
this.commands.RegisterCommands<AddStaffCommand>();
this.commands.RegisterCommands<AssignCommand>();
this.commands.RegisterCommands<BlacklistCommand>();
this.commands.RegisterCommands<CloseCommand>();
this.commands.RegisterCommands<ListAssignedCommand>();
this.commands.RegisterCommands<ListCommand>();
this.commands.RegisterCommands<ListOldestCommand>();
this.commands.RegisterCommands<ListUnassignedCommand>();
this.commands.RegisterCommands<MoveCommand>();
this.commands.RegisterCommands<NewCommand>();
this.commands.RegisterCommands<RandomAssignCommand>();
this.commands.RegisterCommands<ReloadCommand>();
this.commands.RegisterCommands<RemoveMessageCommand>();
this.commands.RegisterCommands<RemoveStaffCommand>();
this.commands.RegisterCommands<SayCommand>();
this.commands.RegisterCommands<SetSummaryCommand>();
this.commands.RegisterCommands<SetTicketCommand>();
this.commands.RegisterCommands<StatusCommand>();
this.commands.RegisterCommands<SummaryCommand>();
this.commands.RegisterCommands<ToggleActiveCommand>();
this.commands.RegisterCommands<TranscriptCommand>();
this.commands.RegisterCommands<UnassignCommand>();
this.commands.RegisterCommands<UnblacklistCommand>();
this.commands.RegisterCommands<UnsetTicketCommand>();
Console.WriteLine("Hooking command events...");
this.commands.CommandErrored += this.eventHandler.OnCommandError;
Console.WriteLine("Connecting to Discord...");
await this.discordClient.ConnectAsync();
}
}
}

View file

@ -1,60 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net5.0</TargetFramework>
<Version>1.1.0</Version>
<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></PackageIconUrl>
<Description>A Discord support bot build for the Ellie's Home Discord server</Description>
<AssemblyVersion>2.5.0.0</AssemblyVersion>
<FileVersion>2.5.0.0</FileVersion>
<NeutralLanguage>en</NeutralLanguage>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="DSharpPlus" Version="4.1.0" />
<PackageReference Include="DSharpPlus.CommandsNext" Version="4.1.0" />
<PackageReference Include="DSharpPlus.Interactivity" Version="4.1.0" />
<PackageReference Include="JsonExtensions" Version="1.2.0" />
<PackageReference Include="MiniRazor.CodeGen" Version="2.2.0" />
<PackageReference Include="MySql.Data" Version="8.0.28" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
<PackageReference Include="Polly" Version="7.2.3" />
<PackageReference Include="Superpower" Version="3.0.0" />
<PackageReference Include="Tyrrrz.Extensions" Version="1.6.5" />
<PackageReference Include="YamlDotNet" Version="11.2.1" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<Folder Include="lib\" />
</ItemGroup>
<ItemGroup>
<Reference Include="DiscordChatExporter.Core">
<HintPath>lib\DiscordChatExporter.Core.dll</HintPath>
</Reference>
</ItemGroup>
</Project>

View file

@ -1,62 +0,0 @@
using System.IO;
using System.Threading.Tasks;
using DiscordChatExporter.Core.Discord;
using DiscordChatExporter.Core.Discord.Data;
using DiscordChatExporter.Core.Exceptions;
using DiscordChatExporter.Core.Exporting;
using DiscordChatExporter.Core.Exporting.Filtering;
using DiscordChatExporter.Core.Exporting.Partitioning;
using DiscordChatExporter.Core.Utils.Extensions;
namespace SupportChild
{
internal static class Transcriber
{
internal static async Task ExecuteAsync(ulong channelID, uint ticketID)
{
DiscordClient discordClient = new DiscordClient(new AuthToken(AuthTokenKind.Bot, Config.token));
ChannelExporter Exporter = new ChannelExporter(discordClient);
if (!Directory.Exists("./transcripts"))
{
Directory.CreateDirectory("./transcripts");
}
string dateFormat = "yyyy-MMM-dd HH:mm";
// Configure settings
if (Config.timestampFormat != "")
dateFormat = Config.timestampFormat;
Channel channel = await discordClient.GetChannelAsync(new Snowflake(channelID));
Guild guild = await discordClient.GetGuildAsync(channel.GuildId);
ExportRequest request = new ExportRequest(
guild: guild,
channel: channel,
outputPath: GetPath(ticketID),
format: ExportFormat.HtmlDark,
after: null,
before: null,
partitionLimit: PartitionLimit.Null,
messageFilter: MessageFilter.Null,
shouldDownloadMedia: false,
shouldReuseMedia: false,
dateFormat: dateFormat
);
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";
}
}
}

View file

@ -1,71 +0,0 @@
using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using DSharpPlus.Entities;
namespace SupportChild
{
public static class Utilities
{
public static List<T> RandomizeList<T>(List<T> list)
{
RNGCryptoServiceProvider provider = new RNGCryptoServiceProvider();
int n = list.Count;
while (n > 1)
{
byte[] box = new byte[1];
do provider.GetBytes(box);
while (!(box[0] < n * (Byte.MaxValue / n)));
int k = (box[0] % n);
n--;
T value = list[k];
list[k] = list[n];
list[n] = value;
}
return list;
}
public static string[] ParseIDs(string args)
{
if (string.IsNullOrEmpty(args))
{
return new string[0];
}
return args.Trim().Replace("<@!", "").Replace("<@", "").Replace(">", "").Split();
}
public static LinkedList<string> ParseListIntoMessages(List<string> listItems)
{
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 DiscordRole GetRoleByName(DiscordGuild guild, string Name)
{
Name = Name.Trim().ToLower();
foreach (DiscordRole role in guild.Roles.Values)
{
if (role.Name.ToLower().StartsWith(Name))
{
return role;
}
}
return null;
}
}
}

View file

@ -1,84 +0,0 @@
bot:
# Bot token.
token: "<add-token-here>"
# Command prefix.
prefix: "+"
# Channel where ticket logs are posted (recommended)
log-channel: 000000000000000000
# Category where the ticket will be created, it will have the same permissions of that ticket plus read permissions for the user opening the ticket (recommended)
ticket-category: 000000000000000000
# A message which will open new tickets when users react to it (optional)
reaction-message: 000000000000000000
# Message posted when a ticket is opened.
welcome-message: "Please describe your issue below, and include all information needed for us to help you."
# Decides what messages are shown in console
# Possible values are: Critical, Error, Warning, Information, Debug.
console-log-level: "Information"
# Format for timestamps in transcripts and google sheets if used
timestamp-format: "yyyy-MM-dd HH:mm"
# Whether or not staff members should be randomly assigned tickets when they are made. Individual staff members can opt out using the toggleactive command.
random-assignment: true
# If set to true the rasssign command will include staff members set as inactive if a specific role is specified in the command.
# This can be useful if you have admins set as inactive to not automatically recieve tickets and then have moderators elevate tickets when needed.
random-assign-role-override: true
# Sets the type of activity for the bot to display in its presence status
# Possible values are: Playing, Streaming, ListeningTo, Watching, Competing
presence-type: "ListeningTo"
# Sets the activity text shown in the bot's status
presence-text: "+new"
notifications:
# Notifies the assigned staff member when a new message is posted in a ticket if the ticket has been silent for a configurable amount of time
# Other staff members and bots do not trigger this.
ticket-updated: true
# The above notification will only be sent if the ticket has been silent for more than this amount of days. Default is 0.5 days.
ticket-updated-delay: 0.5
# Notifies staff when they are assigned to tickets
assignment: true
# Notifies the user opening the ticket that their ticket was closed and includes the transcript
closing: true
database:
# Address and port of the mysql server
address: "127.0.0.1"
port: 3306
# Name of the database to use
name: "supportbot"
# Username and password for authentication
user: ""
password: ""
# Set up which roles are allowed to use different commands.
# Example:
# new: [ 000000000000000000, 111111111111111111 ]
# They are grouped into suggested command groups below for first time setup.
permissions:
# Public commands
close: []
list: []
new: []
say: []
status: []
summary: []
transcript: []
# Moderator commands
add: []
addmessage: []
assign: []
blacklist: []
listassigned: []
listoldest: []
listunassigned: []
move: []
rassign: []
removemessage: []
setsummary: []
toggleactive: []
unassign: []
unblacklist: []
# Admin commands
addstaff: []
reload: []
removestaff: []
setticket: []
unsetticket: []

139
Transcriber.cs Normal file
View 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
View 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;
}
}
}
}

80
default_config.yml Normal file
View file

@ -0,0 +1,80 @@
bot:
# Bot token.
token: "<add-token-here>"
# Channel where ticket logs are posted (recommended).
log-channel: 000000000000000000
# Message posted when a ticket is opened.
welcome-message: "Please describe your issue below, and include all information needed for us to take action."
# Decides what messages are shown in console.
# Possible values are: Critical, Error, Warning, Information, Debug.
console-log-level: "Information"
# One of the following: LongDate, LongDateTime, LongTime, RelativeTime, ShortDate, ShortDateTime, ShortTime.
# More info: https://dsharpplus.github.io/api/DSharpPlus.TimestampFormat.html
timestamp-format: "RelativeTime"
# Whether 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 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, 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.
new-command-uses-selector: false
# Number of tickets a single user can have open at a time, staff members are excluded from this.
ticket-limit: 5
# 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.
# Other staff members and bots do not trigger this.
ticket-updated: true
# The above notification will only be sent if the ticket has been silent for more than this amount of days. Default is 0.5 days.
ticket-updated-delay: 0.5
# Notifies staff when they are assigned to tickets.
assignment: true
# Notifies the user opening the ticket that their ticket was closed and includes the transcript.
closing: true
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: "127.0.0.1"
port: 3306
# Name of the database to use.
name: "supportchild"
# Username and password for authentication.
user: ""
password: ""

41
docs/Commands.md Normal file
View 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
View 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&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; | 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&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</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

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.1 KiB

BIN
ellie_icon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

Binary file not shown.