├── .gitattributes
├── .github
├── FUNDING.yml
├── ISSUE_TEMPLATE
│ ├── bug_report.md
│ └── feature_request.md
└── workflows
│ └── nuget-publish.yml
├── .gitignore
├── .vscode
├── launch.json
├── settings.json
└── tasks.json
├── DSharpPlus.SlashCommands.sln
├── DSharpPlus.SlashCommands
├── Attributes
│ ├── DefaultParameterAttribute.cs
│ ├── SlashCommandAttribute.cs
│ ├── SlashSubcommandAttribute.cs
│ └── SlashSubcommandGroupAttribute.cs
├── DSharpPlus.SlashCommands.csproj
├── DiscordSlashClient.cs
├── DiscordSlashConfiguration.cs
├── Entities
│ ├── ApplicationCommandOptionChoice.cs
│ ├── BaseSlashCommandModule.cs
│ ├── Builders
│ │ ├── ApplicationCommandBuilder.cs
│ │ ├── ApplicationCommandOptionBuilder.cs
│ │ ├── ApplicationCommandOptionChoiceBuilder.cs
│ │ ├── IBuilder.cs
│ │ ├── InteractionApplicationCommandCallbackDataBuilder.cs
│ │ └── InteractionResponseBuilder.cs
│ ├── InteractionApplicationCommandCallbackData.cs
│ ├── InteractionContext.cs
│ ├── InteractionResponse.cs
│ ├── SlashCommand.cs
│ ├── SlashCommandConfiguration.cs
│ ├── SlashSubcommand.cs
│ └── SlashSubcommandGroup.cs
├── Enums
│ └── ApplicationCommandOptionType.cs
├── LICENSE
└── Services
│ └── SlashCommandHandlingService.cs
├── ExampleGatewayBot
├── Commands
│ └── SlashCommandTesting.cs
├── Configuration Examples
│ └── bot_config.json
├── ExampleGatewayBot.csproj
└── Program.cs
├── ExampleHTTPBot
├── Api
│ └── DiscordSlashCommandController.cs
├── Commands
│ ├── Discord
│ │ └── PingDiscordCommand.cs
│ └── Slash
│ │ ├── ArgumentExampleCommand.cs
│ │ ├── ArgumentSubcommandCommand.cs
│ │ ├── HelloWorldSlashCommand.cs
│ │ └── SubcommandExampleSlashCommand.cs
├── Configuration Examples
│ └── bot_config.json
├── ExampleHTTPBot.csproj
├── Program.cs
├── Properties
│ └── launchSettings.json
├── Startup.cs
├── Utils.cs
├── appsettings.Development.json
├── appsettings.json
└── sccfg_774671144719482881.json
├── LICENSE
├── NuGet.config
└── README.md
/.gitattributes:
--------------------------------------------------------------------------------
1 | ###############################################################################
2 | # Set default behavior to automatically normalize line endings.
3 | ###############################################################################
4 | * text=auto
5 |
6 | ###############################################################################
7 | # Set default behavior for command prompt diff.
8 | #
9 | # This is need for earlier builds of msysgit that does not have it on by
10 | # default for csharp files.
11 | # Note: This is only used by command line
12 | ###############################################################################
13 | #*.cs diff=csharp
14 |
15 | ###############################################################################
16 | # Set the merge driver for project and solution files
17 | #
18 | # Merging from the command prompt will add diff markers to the files if there
19 | # are conflicts (Merging from VS is not affected by the settings below, in VS
20 | # the diff markers are never inserted). Diff markers may cause the following
21 | # file extensions to fail to load in VS. An alternative would be to treat
22 | # these files as binary and thus will always conflict and require user
23 | # intervention with every merge. To do so, just uncomment the entries below
24 | ###############################################################################
25 | #*.sln merge=binary
26 | #*.csproj merge=binary
27 | #*.vbproj merge=binary
28 | #*.vcxproj merge=binary
29 | #*.vcproj merge=binary
30 | #*.dbproj merge=binary
31 | #*.fsproj merge=binary
32 | #*.lsproj merge=binary
33 | #*.wixproj merge=binary
34 | #*.modelproj merge=binary
35 | #*.sqlproj merge=binary
36 | #*.wwaproj merge=binary
37 |
38 | ###############################################################################
39 | # behavior for image files
40 | #
41 | # image files are treated as binary by default.
42 | ###############################################################################
43 | #*.jpg binary
44 | #*.png binary
45 | #*.gif binary
46 |
47 | ###############################################################################
48 | # diff behavior for common document formats
49 | #
50 | # Convert binary document formats to text before diffing them. This feature
51 | # is only available from the command line. Turn it on by uncommenting the
52 | # entries below.
53 | ###############################################################################
54 | #*.doc diff=astextplain
55 | #*.DOC diff=astextplain
56 | #*.docx diff=astextplain
57 | #*.DOCX diff=astextplain
58 | #*.dot diff=astextplain
59 | #*.DOT diff=astextplain
60 | #*.pdf diff=astextplain
61 | #*.PDF diff=astextplain
62 | #*.rtf diff=astextplain
63 | #*.RTF diff=astextplain
64 |
--------------------------------------------------------------------------------
/.github/FUNDING.yml:
--------------------------------------------------------------------------------
1 | # These are supported funding model platforms
2 |
3 | ko_fi: soyvolon
4 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/bug_report.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Bug report
3 | about: Create a report to help us improve the Lib
4 | title: ''
5 | labels: ''
6 | assignees: ''
7 |
8 | ---
9 |
10 | # Bug
11 | ## Description
12 | A clear and concise description of what the bug is. Please include the Lib version.
13 |
14 | ## To Reproduce
15 | Steps to reproduce the behavior:
16 | 1. Go to '...'
17 | 2. Click on '....'
18 | 3. Scroll down to '....'
19 | 4. See error
20 |
21 | ## Expected behavior
22 | A clear and concise description of what you expected to happen.
23 |
24 | ## Notes
25 | Add any other context about the problem here.
26 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/feature_request.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Feature request
3 | about: Suggest an idea for this project
4 | title: ''
5 | labels: ''
6 | assignees: ''
7 |
8 | ---
9 |
10 | # Feature
11 | A clear and concise description of what the feature is
12 |
13 | ## Potential Solution
14 | A concise idea about how this could be implemented.
15 |
16 | ## Notes
17 | Add any other context or screenshots about the feature request here.
18 |
--------------------------------------------------------------------------------
/.github/workflows/nuget-publish.yml:
--------------------------------------------------------------------------------
1 | name: Publish to Nuget
2 |
3 | on:
4 | release:
5 | types: [released]
6 | workflow_dispatch:
7 |
8 | jobs:
9 | build:
10 | runs-on: ubuntu-latest
11 |
12 | steps:
13 | - uses: actions/checkout@v2
14 | - name: Setup .NET
15 | uses: actions/setup-dotnet@v1
16 | with:
17 | dotnet-version: 5.0.100
18 | - name: Restore dependencies
19 | run: dotnet restore
20 | - name: Build
21 | run: dotnet build --no-restore
22 | - name: Test
23 | run: dotnet test --no-build --verbosity normal
24 | - name: Update Nuget Package
25 | uses: brandedoutcast/publish-nuget@v2.5.5
26 | with:
27 | PROJECT_FILE_PATH: DSharpPlus.SlashCommands/DSharpPlus.SlashCommands.csproj
28 | NUGET_KEY: ${{ secrets.NUGET_API_KEY }}
29 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 | ##
4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
5 |
6 | # Custom-Ignore
7 | *[Cc]onfig/
8 |
9 | # User-specific files
10 | *.rsuser
11 | *.suo
12 | *.user
13 | *.userosscache
14 | *.sln.docstates
15 |
16 | # User-specific files (MonoDevelop/Xamarin Studio)
17 | *.userprefs
18 |
19 | # Build results
20 | [Dd]ebug/
21 | [Dd]ebugPublic/
22 | [Rr]elease/
23 | [Rr]eleases/
24 | x64/
25 | x86/
26 | [Aa][Rr][Mm]/
27 | [Aa][Rr][Mm]64/
28 | bld/
29 | [Bb]in/
30 | [Oo]bj/
31 | [Ll]og/
32 |
33 | # Visual Studio 2015/2017 cache/options directory
34 | .vs/
35 | # Uncomment if you have tasks that create the project's static files in wwwroot
36 | #wwwroot/
37 |
38 | # Visual Studio 2017 auto generated files
39 | Generated\ Files/
40 |
41 | # MSTest test Results
42 | [Tt]est[Rr]esult*/
43 | [Bb]uild[Ll]og.*
44 |
45 | # NUNIT
46 | *.VisualState.xml
47 | TestResult.xml
48 |
49 | # Build Results of an ATL Project
50 | [Dd]ebugPS/
51 | [Rr]eleasePS/
52 | dlldata.c
53 |
54 | # Benchmark Results
55 | BenchmarkDotNet.Artifacts/
56 |
57 | # .NET Core
58 | project.lock.json
59 | project.fragment.lock.json
60 | artifacts/
61 |
62 | # StyleCop
63 | StyleCopReport.xml
64 |
65 | # Files built by Visual Studio
66 | *_i.c
67 | *_p.c
68 | *_h.h
69 | *.ilk
70 | *.meta
71 | *.obj
72 | *.iobj
73 | *.pch
74 | *.pdb
75 | *.ipdb
76 | *.pgc
77 | *.pgd
78 | *.rsp
79 | *.sbr
80 | *.tlb
81 | *.tli
82 | *.tlh
83 | *.tmp
84 | *.tmp_proj
85 | *_wpftmp.csproj
86 | *.log
87 | *.vspscc
88 | *.vssscc
89 | .builds
90 | *.pidb
91 | *.svclog
92 | *.scc
93 |
94 | # Chutzpah Test files
95 | _Chutzpah*
96 |
97 | # Visual C++ cache files
98 | ipch/
99 | *.aps
100 | *.ncb
101 | *.opendb
102 | *.opensdf
103 | *.sdf
104 | *.cachefile
105 | *.VC.db
106 | *.VC.VC.opendb
107 |
108 | # Visual Studio profiler
109 | *.psess
110 | *.vsp
111 | *.vspx
112 | *.sap
113 |
114 | # Visual Studio Trace Files
115 | *.e2e
116 |
117 | # TFS 2012 Local Workspace
118 | $tf/
119 |
120 | # Guidance Automation Toolkit
121 | *.gpState
122 |
123 | # ReSharper is a .NET coding add-in
124 | _ReSharper*/
125 | *.[Rr]e[Ss]harper
126 | *.DotSettings.user
127 |
128 | # JustCode is a .NET coding add-in
129 | .JustCode
130 |
131 | # TeamCity is a build add-in
132 | _TeamCity*
133 |
134 | # DotCover is a Code Coverage Tool
135 | *.dotCover
136 |
137 | # AxoCover is a Code Coverage Tool
138 | .axoCover/*
139 | !.axoCover/settings.json
140 |
141 | # Visual Studio code coverage results
142 | *.coverage
143 | *.coveragexml
144 |
145 | # NCrunch
146 | _NCrunch_*
147 | .*crunch*.local.xml
148 | nCrunchTemp_*
149 |
150 | # MightyMoose
151 | *.mm.*
152 | AutoTest.Net/
153 |
154 | # Web workbench (sass)
155 | .sass-cache/
156 |
157 | # Installshield output folder
158 | [Ee]xpress/
159 |
160 | # DocProject is a documentation generator add-in
161 | DocProject/buildhelp/
162 | DocProject/Help/*.HxT
163 | DocProject/Help/*.HxC
164 | DocProject/Help/*.hhc
165 | DocProject/Help/*.hhk
166 | DocProject/Help/*.hhp
167 | DocProject/Help/Html2
168 | DocProject/Help/html
169 |
170 | # Click-Once directory
171 | publish/
172 |
173 | # Publish Web Output
174 | *.[Pp]ublish.xml
175 | *.azurePubxml
176 | # Note: Comment the next line if you want to checkin your web deploy settings,
177 | # but database connection strings (with potential passwords) will be unencrypted
178 | *.pubxml
179 | *.publishproj
180 |
181 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
182 | # checkin your Azure Web App publish settings, but sensitive information contained
183 | # in these scripts will be unencrypted
184 | PublishScripts/
185 |
186 | # NuGet Packages
187 | *.nupkg
188 | # The packages folder can be ignored because of Package Restore
189 | **/[Pp]ackages/*
190 | # except build/, which is used as an MSBuild target.
191 | !**/[Pp]ackages/build/
192 | # Uncomment if necessary however generally it will be regenerated when needed
193 | #!**/[Pp]ackages/repositories.config
194 | # NuGet v3's project.json files produces more ignorable files
195 | *.nuget.props
196 | *.nuget.targets
197 |
198 | # Microsoft Azure Build Output
199 | csx/
200 | *.build.csdef
201 |
202 | # Microsoft Azure Emulator
203 | ecf/
204 | rcf/
205 |
206 | # Windows Store app package directories and files
207 | AppPackages/
208 | BundleArtifacts/
209 | Package.StoreAssociation.xml
210 | _pkginfo.txt
211 | *.appx
212 |
213 | # Visual Studio cache files
214 | # files ending in .cache can be ignored
215 | *.[Cc]ache
216 | # but keep track of directories ending in .cache
217 | !?*.[Cc]ache/
218 |
219 | # Others
220 | ClientBin/
221 | ~$*
222 | *~
223 | *.dbmdl
224 | *.dbproj.schemaview
225 | *.jfm
226 | *.pfx
227 | *.publishsettings
228 | orleans.codegen.cs
229 |
230 | # Including strong name files can present a security risk
231 | # (https://github.com/github/gitignore/pull/2483#issue-259490424)
232 | #*.snk
233 |
234 | # Since there are multiple workflows, uncomment next line to ignore bower_components
235 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
236 | #bower_components/
237 |
238 | # RIA/Silverlight projects
239 | Generated_Code/
240 |
241 | # Backup & report files from converting an old project file
242 | # to a newer Visual Studio version. Backup files are not needed,
243 | # because we have git ;-)
244 | _UpgradeReport_Files/
245 | Backup*/
246 | UpgradeLog*.XML
247 | UpgradeLog*.htm
248 | ServiceFabricBackup/
249 | *.rptproj.bak
250 |
251 | # SQL Server files
252 | *.mdf
253 | *.ldf
254 | *.ndf
255 |
256 | # Business Intelligence projects
257 | *.rdl.data
258 | *.bim.layout
259 | *.bim_*.settings
260 | *.rptproj.rsuser
261 | *- Backup*.rdl
262 |
263 | # Microsoft Fakes
264 | FakesAssemblies/
265 |
266 | # GhostDoc plugin setting file
267 | *.GhostDoc.xml
268 |
269 | # Node.js Tools for Visual Studio
270 | .ntvs_analysis.dat
271 | node_modules/
272 |
273 | # Visual Studio 6 build log
274 | *.plg
275 |
276 | # Visual Studio 6 workspace options file
277 | *.opt
278 |
279 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
280 | *.vbw
281 |
282 | # Visual Studio LightSwitch build output
283 | **/*.HTMLClient/GeneratedArtifacts
284 | **/*.DesktopClient/GeneratedArtifacts
285 | **/*.DesktopClient/ModelManifest.xml
286 | **/*.Server/GeneratedArtifacts
287 | **/*.Server/ModelManifest.xml
288 | _Pvt_Extensions
289 |
290 | # Paket dependency manager
291 | .paket/paket.exe
292 | paket-files/
293 |
294 | # FAKE - F# Make
295 | .fake/
296 |
297 | # JetBrains Rider
298 | .idea/
299 | *.sln.iml
300 |
301 | # CodeRush personal settings
302 | .cr/personal
303 |
304 | # Python Tools for Visual Studio (PTVS)
305 | __pycache__/
306 | *.pyc
307 |
308 | # Cake - Uncomment if you are using it
309 | # tools/**
310 | # !tools/packages.config
311 |
312 | # Tabs Studio
313 | *.tss
314 |
315 | # Telerik's JustMock configuration file
316 | *.jmconfig
317 |
318 | # BizTalk build output
319 | *.btp.cs
320 | *.btm.cs
321 | *.odx.cs
322 | *.xsd.cs
323 |
324 | # OpenCover UI analysis results
325 | OpenCover/
326 |
327 | # Azure Stream Analytics local run output
328 | ASALocalRun/
329 |
330 | # MSBuild Binary and Structured Log
331 | *.binlog
332 |
333 | # NVidia Nsight GPU debugger configuration file
334 | *.nvuser
335 |
336 | # MFractors (Xamarin productivity tool) working folder
337 | .mfractor/
338 |
339 | # Local History for Visual Studio
340 | .localhistory/
341 |
342 | # BeatPulse healthcheck temp database
343 | healthchecksdb
--------------------------------------------------------------------------------
/.vscode/launch.json:
--------------------------------------------------------------------------------
1 | {
2 | // Use IntelliSense to find out which attributes exist for C# debugging
3 | // Use hover for the description of the existing attributes
4 | // For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md
5 | "version": "0.2.0",
6 | "configurations": [
7 | {
8 | "name": ".NET Core Launch (web)",
9 | "type": "coreclr",
10 | "request": "launch",
11 | "preLaunchTask": "build",
12 | // If you have changed target frameworks, make sure to update the program path.
13 | "program": "${workspaceFolder}/ExampleBot/bin/Debug/net5.0/ExampleBot.dll",
14 | "args": [],
15 | "cwd": "${workspaceFolder}/ExampleBot",
16 | "stopAtEntry": false,
17 | // Enable launching a web browser when ASP.NET Core starts. For more information: https://aka.ms/VSCode-CS-LaunchJson-WebBrowser
18 | "serverReadyAction": {
19 | "action": "openExternally",
20 | "pattern": "\\bNow listening on:\\s+(https?://\\S+)"
21 | },
22 | "env": {
23 | "ASPNETCORE_ENVIRONMENT": "Development"
24 | },
25 | "sourceFileMap": {
26 | "/Views": "${workspaceFolder}/Views"
27 | }
28 | },
29 | {
30 | "name": ".NET Core Attach",
31 | "type": "coreclr",
32 | "request": "attach",
33 | "processId": "${command:pickProcess}"
34 | }
35 | ]
36 | }
--------------------------------------------------------------------------------
/.vscode/settings.json:
--------------------------------------------------------------------------------
1 | {
2 | "cSpell.words": [
3 | "Linq",
4 | "Moinvaziri",
5 | "Newtonsoft",
6 | "Subcommand",
7 | "discordslash",
8 | "sccfg",
9 | "subcommands"
10 | ]
11 | }
--------------------------------------------------------------------------------
/.vscode/tasks.json:
--------------------------------------------------------------------------------
1 | {
2 | "version": "2.0.0",
3 | "tasks": [
4 | {
5 | "label": "build",
6 | "command": "dotnet",
7 | "type": "process",
8 | "args": [
9 | "build",
10 | "${workspaceFolder}/ExampleBot/ExampleBot.csproj",
11 | "/property:GenerateFullPaths=true",
12 | "/consoleloggerparameters:NoSummary"
13 | ],
14 | "problemMatcher": "$msCompile"
15 | },
16 | {
17 | "label": "publish",
18 | "command": "dotnet",
19 | "type": "process",
20 | "args": [
21 | "publish",
22 | "${workspaceFolder}/ExampleBot/ExampleBot.csproj",
23 | "/property:GenerateFullPaths=true",
24 | "/consoleloggerparameters:NoSummary"
25 | ],
26 | "problemMatcher": "$msCompile"
27 | },
28 | {
29 | "label": "watch",
30 | "command": "dotnet",
31 | "type": "process",
32 | "args": [
33 | "watch",
34 | "run",
35 | "${workspaceFolder}/ExampleBot/ExampleBot.csproj",
36 | "/property:GenerateFullPaths=true",
37 | "/consoleloggerparameters:NoSummary"
38 | ],
39 | "problemMatcher": "$msCompile"
40 | }
41 | ]
42 | }
--------------------------------------------------------------------------------
/DSharpPlus.SlashCommands.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio Version 16
4 | VisualStudioVersion = 16.0.30711.63
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DSharpPlus.SlashCommands", "DSharpPlus.SlashCommands\DSharpPlus.SlashCommands.csproj", "{30FF64B3-45E2-4776-A822-94073D4F92D9}"
7 | EndProject
8 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "1. sln", "1. sln", "{BB481774-975C-4AE6-B39D-CEF4030848B1}"
9 | ProjectSection(SolutionItems) = preProject
10 | .gitignore = .gitignore
11 | LICENSE = LICENSE
12 | NuGet.config = NuGet.config
13 | README.md = README.md
14 | EndProjectSection
15 | EndProject
16 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ExampleGatewayBot", "ExampleGatewayBot\ExampleGatewayBot.csproj", "{D11DEA0A-E20E-4CA9-B7CD-98AE6E46D58A}"
17 | EndProject
18 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ExampleHTTPBot", "ExampleHTTPBot\ExampleHTTPBot.csproj", "{7D2C3FE2-CCE6-47F7-BE02-F1FE0D61F1A5}"
19 | EndProject
20 | Global
21 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
22 | Debug|Any CPU = Debug|Any CPU
23 | Release|Any CPU = Release|Any CPU
24 | EndGlobalSection
25 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
26 | {30FF64B3-45E2-4776-A822-94073D4F92D9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
27 | {30FF64B3-45E2-4776-A822-94073D4F92D9}.Debug|Any CPU.Build.0 = Debug|Any CPU
28 | {30FF64B3-45E2-4776-A822-94073D4F92D9}.Release|Any CPU.ActiveCfg = Release|Any CPU
29 | {30FF64B3-45E2-4776-A822-94073D4F92D9}.Release|Any CPU.Build.0 = Release|Any CPU
30 | {D11DEA0A-E20E-4CA9-B7CD-98AE6E46D58A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
31 | {D11DEA0A-E20E-4CA9-B7CD-98AE6E46D58A}.Debug|Any CPU.Build.0 = Debug|Any CPU
32 | {D11DEA0A-E20E-4CA9-B7CD-98AE6E46D58A}.Release|Any CPU.ActiveCfg = Release|Any CPU
33 | {D11DEA0A-E20E-4CA9-B7CD-98AE6E46D58A}.Release|Any CPU.Build.0 = Release|Any CPU
34 | {7D2C3FE2-CCE6-47F7-BE02-F1FE0D61F1A5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
35 | {7D2C3FE2-CCE6-47F7-BE02-F1FE0D61F1A5}.Debug|Any CPU.Build.0 = Debug|Any CPU
36 | {7D2C3FE2-CCE6-47F7-BE02-F1FE0D61F1A5}.Release|Any CPU.ActiveCfg = Release|Any CPU
37 | {7D2C3FE2-CCE6-47F7-BE02-F1FE0D61F1A5}.Release|Any CPU.Build.0 = Release|Any CPU
38 | EndGlobalSection
39 | GlobalSection(SolutionProperties) = preSolution
40 | HideSolutionNode = FALSE
41 | EndGlobalSection
42 | GlobalSection(ExtensibilityGlobals) = postSolution
43 | SolutionGuid = {E978CC3F-A9D6-4EDF-AEBA-5F96A68F30BE}
44 | EndGlobalSection
45 | EndGlobal
46 |
--------------------------------------------------------------------------------
/DSharpPlus.SlashCommands/Attributes/DefaultParameterAttribute.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace DSharpPlus.SlashCommands.Attributes
4 | {
5 | [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false)]
6 | public class DefaultParameterAttribute : Attribute
7 | {
8 | }
9 | }
10 |
--------------------------------------------------------------------------------
/DSharpPlus.SlashCommands/Attributes/SlashCommandAttribute.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace DSharpPlus.SlashCommands.Attributes
4 | {
5 | ///
6 | /// Used to designate a class as a slash command.
7 | ///
8 | [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
9 | public class SlashCommandAttribute : Attribute
10 | {
11 | public string Name { get; init; }
12 | public ulong? GuildId { get; init; }
13 |
14 | public SlashCommandAttribute(string name, ulong guildId = 0)
15 | {
16 | Name = name;
17 | GuildId = guildId == 0 ? null : guildId;
18 | }
19 | }
20 | }
--------------------------------------------------------------------------------
/DSharpPlus.SlashCommands/Attributes/SlashSubcommandAttribute.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace DSharpPlus.SlashCommands.Attributes
4 | {
5 | ///
6 | /// Defines a method as the default command for a command grouping.
7 | ///
8 | [AttributeUsage(AttributeTargets.Method)]
9 | public class SlashSubcommandAttribute : Attribute
10 | {
11 | public string Name { get; init; }
12 |
13 | public SlashSubcommandAttribute(string name)
14 | {
15 | Name = name;
16 | }
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/DSharpPlus.SlashCommands/Attributes/SlashSubcommandGroupAttribute.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace DSharpPlus.SlashCommands.Attributes
4 | {
5 | [AttributeUsage(AttributeTargets.Class)]
6 | public class SlashSubcommandGroupAttribute : Attribute
7 | {
8 | public string Name { get; set; }
9 | public SlashSubcommandGroupAttribute(string name)
10 | {
11 | Name = name;
12 | }
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/DSharpPlus.SlashCommands/DSharpPlus.SlashCommands.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | net5.0
5 | enable
6 | Soyvolon.DSharpPlus.SlashCommands
7 | 0.5.0
8 | Soyvolon
9 | LICENSE
10 |
11 | DSharpPlus based SlashCommnads
12 | >A SlashCommnad library that uses DSharpPlus to encoperate SlashCommands for Discord
13 | https://github.com/Soyvolon/DSharpPlus.SlashCommands
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
--------------------------------------------------------------------------------
/DSharpPlus.SlashCommands/DiscordSlashClient.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Net.Http;
3 | using System.Reflection;
4 | using System.Threading.Tasks;
5 |
6 | using DSharpPlus.Entities;
7 | using DSharpPlus.EventArgs;
8 | using DSharpPlus.SlashCommands.Entities;
9 | using DSharpPlus.SlashCommands.Entities.Builders;
10 | using DSharpPlus.SlashCommands.Services;
11 |
12 | using Microsoft.AspNetCore.Http;
13 | using Microsoft.Extensions.DependencyInjection;
14 | using Microsoft.Extensions.Logging;
15 |
16 | using Newtonsoft.Json;
17 | using Newtonsoft.Json.Linq;
18 |
19 | namespace DSharpPlus.SlashCommands
20 | {
21 | public class DiscordSlashClient
22 | {
23 | private const string api = "https://discord.com/api/v8";
24 |
25 | private ulong ApplicationId
26 | {
27 | get
28 | {
29 | if (this._discord is not null)
30 | return this._discord.CurrentApplication.Id;
31 | else if (this._sharded is not null)
32 | return this._sharded.CurrentApplication.Id;
33 | else return 0;
34 | }
35 | }
36 |
37 | private readonly IServiceProvider _services;
38 | private readonly IServiceProvider _internalServices;
39 | private readonly SlashCommandHandlingService _slash;
40 | private readonly DiscordSlashConfiguration _config;
41 | private readonly BaseDiscordClient? _discord;
42 | private readonly DiscordShardedClient? _sharded;
43 | private readonly HttpClient _http;
44 | private readonly ILogger _logger;
45 | private readonly JsonSerializerSettings _jsonSettings = new JsonSerializerSettings
46 | {
47 | NullValueHandling = NullValueHandling.Ignore,
48 | DefaultValueHandling = DefaultValueHandling.Ignore
49 | };
50 | private const string _contentType = "application/json";
51 |
52 | public DiscordSlashClient(DiscordSlashConfiguration config)
53 | {
54 | IServiceCollection internalServices = new ServiceCollection();
55 | internalServices.AddSingleton()
56 | .AddSingleton();
57 |
58 | this._config = config;
59 | this._discord = this._config.Client;
60 | this._sharded = this._config.ShardedClient;
61 |
62 | if (config.Logger is not null)
63 | {
64 | internalServices.AddSingleton(config.Logger);
65 | }
66 | else
67 | {
68 | if (_discord is not null)
69 | {
70 | internalServices.AddSingleton(_discord.Logger);
71 | }
72 | else if (_sharded is not null)
73 | {
74 | internalServices.AddSingleton(_sharded!.Logger);
75 | }
76 | }
77 |
78 | this._services = config.Services ?? new ServiceCollection().BuildServiceProvider();
79 | this._internalServices = internalServices.BuildServiceProvider();
80 | this._logger = this._internalServices.GetRequiredService();
81 | this._http = this._internalServices.GetRequiredService();
82 | this._slash = new SlashCommandHandlingService(this._services, this._http, this._logger);
83 | this._http.DefaultRequestHeaders.Authorization = new("Bot", this._config.Token);
84 |
85 | if (this._discord is null && this._sharded is null)
86 | throw new Exception("A Discord Client or Sharded Client is required.");
87 | }
88 |
89 | ///
90 | /// Add an assembly to register commands from.
91 | ///
92 | /// Assembly to register
93 | public void RegisterCommands(Assembly assembly)
94 | {
95 | _slash.WithCommandAssembly(assembly);
96 | }
97 |
98 | ///
99 | /// Starts the slash command client.
100 | ///
101 | /// Start operation
102 | public async Task StartAsync()
103 | {
104 | // Set this restriction to ensure proper response for async command handling.
105 | if ((_config.DefaultResponseType == InteractionResponseType.ChannelMessageWithSource)
106 | && _config.DefaultResponseData is null)
107 | throw new Exception("DeafultResponseData must not be null if not using ResponseType of ChannelMessageWithSource.");
108 |
109 |
110 | // Initialize the command handling service (and therefor updating command on discord).
111 | await _slash.StartAsync(_config.Token, ApplicationId);
112 | }
113 |
114 | public async Task HandleGatewayEvent(DiscordClient client, InteractionCreateEventArgs args)
115 | {
116 | await _slash.HandleInteraction(client, args.Interaction, this);
117 |
118 | var data = GetDeafultResponse().Build();
119 |
120 | var msg = new HttpRequestMessage()
121 | {
122 | Method = HttpMethod.Post,
123 | RequestUri = GetGatewayFollowupUri(args.Interaction.Id.ToString(), args.Interaction.Token),
124 | Content = new StringContent(JsonConvert.SerializeObject(data, _jsonSettings))
125 | };
126 |
127 | msg.Content.Headers.ContentType = new(_contentType);
128 |
129 | var res = await _http.SendAsync(msg);
130 |
131 | return res.IsSuccessStatusCode;
132 | }
133 |
134 | ///
135 | /// Handle an incoming webhook request and return the default data to send back to Discord.
136 | ///
137 | /// HttpRequest for the interaction POST
138 | /// Handle Webhook operation
139 | public async Task HandleWebhookPost(string requestBody)
140 | {
141 | try
142 | {// Attempt to get the Interact object from the JSON ...
143 | var i = JsonConvert.DeserializeObject(requestBody);
144 | // ... and tell the handler to run the command ...
145 |
146 | //var jobj = JObject.Parse(requestBody);
147 | //DiscordUser? user = jobj["member"]?["user"]?.ToObject();
148 | //// ... because we cant serialize direct to a DiscordMember, we are working around this
149 | //// and using a DiscordUser instead. I would have to set the Lib as upstream to this before I
150 | //// would be able to change this.
151 | //i.User = user;
152 |
153 | var client = GetBaseClientForRequest(i.GuildId);
154 |
155 | await _slash.HandleInteraction(client, i, this);
156 | }
157 | catch (Exception ex)
158 | { // ... if it errors, log and return null.
159 | _logger.LogError(ex, "Webhook Handler failed.");
160 | return null;
161 | }
162 |
163 | return GetDeafultResponse().Build();
164 | }
165 |
166 | private BaseDiscordClient GetBaseClientForRequest(ulong? guildId = null)
167 | {
168 | BaseDiscordClient? client = null;
169 | if (_discord is not null)
170 | client = _discord;
171 |
172 | if (client is null)
173 | {
174 | if (guildId is null)
175 | {
176 | if(_sharded is not null && _sharded.ShardClients.Count > 0)
177 | {
178 | client = _sharded.ShardClients[0];
179 | }
180 | }
181 | else
182 | {
183 | if (_sharded is not null)
184 | {
185 | foreach (var shard in _sharded.ShardClients)
186 | if (shard.Value.Guilds.ContainsKey(guildId.Value))
187 | client = shard.Value;
188 | }
189 | }
190 | }
191 |
192 | if (client is null)
193 | throw new Exception("Failed to get a proper cleint for this request.");
194 |
195 | return client;
196 | }
197 |
198 | private InteractionResponseBuilder GetDeafultResponse()
199 | {
200 | // createa new response object ....
201 | var response = new InteractionResponseBuilder()
202 | .WithType(_config.DefaultResponseType);
203 | // ... add the optional configs ...
204 | if (_config.DefaultResponseType == InteractionResponseType.ChannelMessageWithSource)
205 | {
206 | response.Data = _config.DefaultResponseData;
207 | }
208 | // ... and return the builder object.
209 | return response;
210 | }
211 |
212 | ///
213 | /// Updates the original interaction response.
214 | ///
215 | /// New version of the response
216 | /// Update task
217 | internal async Task UpdateAsync(InteractionResponse edit, string token)
218 | {
219 | if(_config.DefaultResponseType == InteractionResponseType.ChannelMessageWithSource)
220 | throw new Exception("Can't edit default response when using Acknowledge or ACKWithSource.");
221 |
222 | var request = new HttpRequestMessage()
223 | {
224 | Method = HttpMethod.Patch,
225 | RequestUri = GetEditOrDeleteInitialUri(token),
226 | Content = new StringContent(edit.BuildWebhookEditBody(_jsonSettings)),
227 | };
228 | request.Content.Headers.ContentType = new(_contentType);
229 |
230 | var res = await _http.SendAsync(request);
231 |
232 | if (res.IsSuccessStatusCode)
233 | {
234 | return await GetResponseBody(res);
235 | }
236 | else return null;
237 | }
238 |
239 | ///
240 | /// Deletes the original response
241 | ///
242 | /// Token for the default interaction to be delete.
243 | /// Delete task
244 | internal async Task DeleteAsync(string token)
245 | {
246 | if(_config.DefaultResponseType == InteractionResponseType.ChannelMessageWithSource)
247 | throw new Exception("Can't delete default response when using Acknowledge or ACKWithSource.");
248 |
249 | var request = new HttpRequestMessage()
250 | {
251 | Method = HttpMethod.Delete,
252 | RequestUri = GetEditOrDeleteInitialUri(token),
253 | };
254 |
255 | var res = await _http.SendAsync(request);
256 |
257 | if (res.IsSuccessStatusCode)
258 | {
259 | return await GetResponseBody(res);
260 | }
261 | else return null;
262 | }
263 |
264 | ///
265 | /// Follow up the interaction response with a new response.
266 | ///
267 | /// New response to send.
268 | /// Original response token.
269 | /// The DiscordMessage that was created.
270 | internal async Task FollowupWithAsync(InteractionResponse followup, string token)
271 | {
272 | var request = new HttpRequestMessage
273 | {
274 | Method = HttpMethod.Post,
275 | RequestUri = GetPostFollowupUri(token),
276 | Content = new StringContent(followup.BuildWebhookBody(_jsonSettings))
277 | };
278 | request.Content.Headers.ContentType = new(_contentType);
279 |
280 | var res = await _http.SendAsync(request);
281 |
282 | if (res.IsSuccessStatusCode)
283 | {
284 | return await GetResponseBody(res);
285 | }
286 | else return null;
287 | }
288 |
289 | ///
290 | /// Edits a followup message from a response.
291 | ///
292 | /// New message to replace the old one with.
293 | /// Original response token.
294 | /// Id of the followup message that you want to edit.
295 | /// Edit task
296 | internal async Task EditAsync(InteractionResponse edit, string token, ulong id)
297 | {
298 | var request = new HttpRequestMessage()
299 | {
300 | Method = HttpMethod.Patch,
301 | RequestUri = GetEditFollowupUri(token, id),
302 | Content = new StringContent(edit.BuildWebhookEditBody(_jsonSettings)),
303 | };
304 | request.Content.Headers.ContentType = new(_contentType);
305 |
306 | var res = await _http.SendAsync(request);
307 |
308 | if (res.IsSuccessStatusCode)
309 | {
310 | return await GetResponseBody(res);
311 | }
312 | else return null;
313 | }
314 |
315 | private async Task GetResponseBody(HttpResponseMessage res)
316 | {
317 | try
318 | {
319 | var resJson = await res.Content.ReadAsStringAsync();
320 | var msg = JsonConvert.DeserializeObject(resJson);
321 | return msg;
322 | }
323 | catch (Exception ex)
324 | {
325 | _logger.LogError(ex, "Update Original Async Failed");
326 | return null;
327 | }
328 | }
329 |
330 | protected Uri GetEditOrDeleteInitialUri(string token)
331 | {
332 | return new Uri($"{api}/webhooks/{ApplicationId}/{token}/messages/@original");
333 | }
334 |
335 | protected Uri GetPostFollowupUri(string token)
336 | {
337 | return new Uri($"{api}/webhooks/{ApplicationId}/{token}");
338 | }
339 |
340 | protected Uri GetEditFollowupUri(string token, ulong messageId)
341 | {
342 | return new Uri($"{api}/webhooks/{ApplicationId}/{token}/messages/{messageId}");
343 | }
344 |
345 | protected Uri GetGatewayFollowupUri(string interactId, string token)
346 | {
347 | return new Uri($"{api}/interactions/{interactId}/{token}/callback");
348 | }
349 | }
350 | }
351 |
--------------------------------------------------------------------------------
/DSharpPlus.SlashCommands/DiscordSlashConfiguration.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | using DSharpPlus.SlashCommands.Entities;
4 | using DSharpPlus.SlashCommands.Entities.Builders;
5 | using DSharpPlus.SlashCommands.Enums;
6 | using Microsoft.Extensions.Logging;
7 |
8 | namespace DSharpPlus.SlashCommands
9 | {
10 | public class DiscordSlashConfiguration
11 | {
12 | ///
13 | /// Token used for the Discrod Bot user that your application has.
14 | ///
15 | public string Token { get; set; }
16 | ///
17 | /// Base client used for parsing DSharpPlus arguments. Can be a Rest or Regular client. This or a ShardedClient is required.
18 | ///
19 | public BaseDiscordClient? Client { get; set; }
20 | ///
21 | /// Base sharded client used for parsing DSharpPLus arguments. This or a Rest or Regular client is required.
22 | ///
23 | public DiscordShardedClient? ShardedClient { get; set; }
24 | ///
25 | /// The Default Response type that is sent to Discord upon receiving a request.
26 | ///
27 | public InteractionResponseType DefaultResponseType { get; set; } = InteractionResponseType.DeferredChannelMessageWithSource;
28 | ///
29 | /// The default data to be used when the DefaultResponseType is ChannelMessage or ChannelMessageWithSource.
30 | ///
31 | public InteractionApplicationCommandCallbackDataBuilder? DefaultResponseData { get; set; } = null;
32 | ///
33 | /// Supply a logger to override the DSharpPlus logger.
34 | ///
35 | public ILogger? Logger { get; set; } = null;
36 | ///
37 | /// Services for dependency injection for slash commands.
38 | ///
39 | public IServiceProvider? Services { get; set; } = null;
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/DSharpPlus.SlashCommands/Entities/ApplicationCommandOptionChoice.cs:
--------------------------------------------------------------------------------
1 |
2 | using Newtonsoft.Json;
3 |
4 | namespace DSharpPlus.SlashCommands.Entities
5 | {
6 | public class ApplicationCommandOptionChoice
7 | {
8 | [JsonProperty("name")]
9 | public string Name { get; internal set; }
10 |
11 | ///
12 | /// Must be string or int
13 | ///
14 | [JsonProperty("value")]
15 | public object Value { get; internal set; }
16 |
17 | internal ApplicationCommandOptionChoice() : this("", 0) { }
18 |
19 | public ApplicationCommandOptionChoice(string n, int v)
20 | {
21 | Name = n;
22 | Value = v;
23 | }
24 |
25 | public ApplicationCommandOptionChoice(string n, string v)
26 | {
27 | Name = n;
28 | Value = v;
29 | }
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/DSharpPlus.SlashCommands/Entities/BaseSlashCommandModule.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace DSharpPlus.SlashCommands.Entities
4 | {
5 | public class BaseSlashCommandModule
6 | {
7 | protected readonly IServiceProvider _services;
8 |
9 | public BaseSlashCommandModule(IServiceProvider services)
10 | {
11 | _services = services;
12 | }
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/DSharpPlus.SlashCommands/Entities/Builders/ApplicationCommandBuilder.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 |
4 | using DSharpPlus.Entities;
5 |
6 | namespace DSharpPlus.SlashCommands.Entities.Builders
7 | {
8 | public class ApplicationCommandBuilder : IBuilder
9 | {
10 | public string Name { get; set; }
11 | public string Description { get; set; }
12 |
13 | ///
14 | /// Options/Subcommands - Max of 10.
15 | ///
16 | public List Options { get; set; }
17 |
18 | public ApplicationCommandBuilder()
19 | {
20 | Name = "";
21 | Description = "";
22 | Options = new();
23 | }
24 |
25 | public ApplicationCommandBuilder WithName(string name)
26 | {
27 | if (name is null || name == "")
28 | throw new Exception("Name cannot be null");
29 |
30 | if (name.Length < 3 || name.Length > 32)
31 | throw new Exception("Name must be between 3 and 32 characters.");
32 |
33 | Name = name;
34 | return this;
35 | }
36 |
37 | public ApplicationCommandBuilder WithDescription(string description)
38 | {
39 | if (description.Length < 1 || description.Length > 100)
40 | throw new Exception("Description must be between 1 and 100 characters.");
41 |
42 | Description = description;
43 | return this;
44 | }
45 |
46 | public ApplicationCommandBuilder AddOption(ApplicationCommandOptionBuilder options)
47 | {
48 | Options.Add(options);
49 | return this;
50 | }
51 |
52 | public DiscordApplicationCommand Build()
53 | {
54 | List options = new();
55 | foreach (var op in Options)
56 | options.Add(op.Build());
57 |
58 | if (Description is null || Description == "")
59 | Description = "none provided";
60 |
61 | return new DiscordApplicationCommand(Name, Description, options);
62 | }
63 | }
64 | }
65 |
--------------------------------------------------------------------------------
/DSharpPlus.SlashCommands/Entities/Builders/ApplicationCommandOptionBuilder.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 |
4 | using DSharpPlus.Entities;
5 | using DSharpPlus.SlashCommands.Enums;
6 |
7 | namespace DSharpPlus.SlashCommands.Entities.Builders
8 | {
9 | public class ApplicationCommandOptionBuilder : IBuilder
10 | {
11 | public ApplicationCommandOptionType Type { get; set; }
12 | public string Name { get; set; }
13 | public string Description { get; set; }
14 | public bool? Default { get; set; }
15 | public bool? Required { get; set; }
16 | public List Choices { get; set; }
17 | public List Options { get; set; }
18 |
19 | public ApplicationCommandOptionBuilder()
20 | {
21 | Name = "";
22 | Description = "";
23 | Choices = new();
24 | Options = new();
25 | }
26 |
27 | public ApplicationCommandOptionBuilder WithType(ApplicationCommandOptionType type)
28 | {
29 | Type = type;
30 | return this;
31 | }
32 |
33 | public ApplicationCommandOptionBuilder WithName(string name)
34 | {
35 | if (name is null || name == "")
36 | throw new Exception("Name can not be null");
37 |
38 | if (name.Length < 1 || name.Length > 32)
39 | throw new Exception("Name must be between 1 and 32 characters.");
40 |
41 | Name = name;
42 | return this;
43 | }
44 |
45 | public ApplicationCommandOptionBuilder WithDescription(string description)
46 | {
47 | Description = description;
48 | return this;
49 | }
50 |
51 | public ApplicationCommandOptionBuilder IsDefault(bool? defaultCmd)
52 | {
53 | Default = defaultCmd;
54 | return this;
55 | }
56 |
57 | public ApplicationCommandOptionBuilder IsRequired(bool? required)
58 | {
59 | Required = required;
60 | return this;
61 | }
62 |
63 | public ApplicationCommandOptionBuilder AddChoice(ApplicationCommandOptionChoiceBuilder choices)
64 | {
65 | // I think. Not completely sure.
66 | if (Options.Count >= 10)
67 | throw new Exception("Cant have more than 10 choices.");
68 |
69 | Choices.Add(choices);
70 | return this;
71 | }
72 | ///
73 | /// Adds an Enum as the avalible choices. This overrides all other choices added with AddChoice.
74 | ///
75 | /// Enum to generate choices from.
76 | /// This builder
77 | public ApplicationCommandOptionBuilder WithChoices(Type enumType)
78 | {
79 | if (!enumType.IsEnum)
80 | throw new Exception("Type is not an enum");
81 |
82 | var names = enumType.GetEnumNames();
83 | var values = enumType.GetEnumValues();
84 |
85 | List choices = new();
86 |
87 | for(int i = 0; i < names.Length; i++)
88 | {
89 | var part = new ApplicationCommandOptionChoiceBuilder()
90 | .WithName(names[i]);
91 | var val = values.GetValue(i);
92 |
93 | part.WithValue((int)val!);
94 |
95 | choices.Add(part);
96 | }
97 |
98 | Choices = choices;
99 |
100 | return this;
101 | }
102 |
103 | public ApplicationCommandOptionBuilder AddOption(ApplicationCommandOptionBuilder options)
104 | {
105 | if (Options.Count >= 10)
106 | throw new Exception("Cant have more than 10 options.");
107 |
108 | Options.Add(options);
109 | return this;
110 | }
111 |
112 | public DiscordApplicationCommandOption Build()
113 | {
114 | List choices = new();
115 | foreach (var ch in Choices)
116 | choices.Add(ch.Build());
117 |
118 | List options = new();
119 | foreach (var op in Options)
120 | options.Add(op.Build());
121 |
122 | return new DiscordApplicationCommandOption(Name, Description, Type, Required, choices, options);
123 | }
124 | }
125 | }
126 |
--------------------------------------------------------------------------------
/DSharpPlus.SlashCommands/Entities/Builders/ApplicationCommandOptionChoiceBuilder.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | using DSharpPlus.Entities;
4 |
5 | namespace DSharpPlus.SlashCommands.Entities.Builders
6 | {
7 | public class ApplicationCommandOptionChoiceBuilder : IBuilder
8 | {
9 | public string Name { get; set; }
10 |
11 | ///
12 | /// Must be string or int
13 | ///
14 | public object Value { get; set; }
15 |
16 | public ApplicationCommandOptionChoiceBuilder()
17 | {
18 | Name = "";
19 | Value = 0;
20 | }
21 |
22 | public ApplicationCommandOptionChoiceBuilder WithName(string name)
23 | {
24 | if (name is null || name == "")
25 | throw new Exception("Name can not be null");
26 |
27 | if (name.Length < 1 || name.Length > 100)
28 | throw new Exception("Name must be between 1 and 100 characters.");
29 |
30 | Name = name;
31 | return this;
32 | }
33 |
34 | public ApplicationCommandOptionChoiceBuilder WithValue(int value)
35 | {
36 | Value = value;
37 | return this;
38 | }
39 |
40 | public ApplicationCommandOptionChoiceBuilder WithValue(string value)
41 | {
42 | Value = value;
43 | return this;
44 | }
45 |
46 | public DiscordApplicationCommandOptionChoice Build()
47 | {
48 | return new DiscordApplicationCommandOptionChoice(Name, Value);
49 | }
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/DSharpPlus.SlashCommands/Entities/Builders/IBuilder.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace DSharpPlus.SlashCommands.Entities.Builders
8 | {
9 | public interface IBuilder
10 | {
11 | public T Build();
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/DSharpPlus.SlashCommands/Entities/Builders/InteractionApplicationCommandCallbackDataBuilder.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | using DSharpPlus.Entities;
8 |
9 | namespace DSharpPlus.SlashCommands.Entities.Builders
10 | {
11 | public class InteractionApplicationCommandCallbackDataBuilder : IBuilder
12 | {
13 | public bool? TextToSpeech { get; set; }
14 | public string? Content { get; set; }
15 | public List Embeds { get; set; } = new();
16 | public List AllowedMentions { get; set; } = new();
17 |
18 | public InteractionApplicationCommandCallbackDataBuilder()
19 | {
20 |
21 | }
22 |
23 | public InteractionApplicationCommandCallbackDataBuilder WithTTS()
24 | {
25 | TextToSpeech = true;
26 | return this;
27 | }
28 |
29 | public InteractionApplicationCommandCallbackDataBuilder WithContent(string content)
30 | {
31 | Content = content;
32 | return this;
33 | }
34 |
35 | public InteractionApplicationCommandCallbackDataBuilder WithEmbed(DiscordEmbed embed)
36 | {
37 | Embeds.Add(embed);
38 | return this;
39 | }
40 |
41 | public InteractionApplicationCommandCallbackDataBuilder WithAllowedMention(IMention mention)
42 | {
43 | AllowedMentions.Add(mention);
44 | return this;
45 | }
46 |
47 | public InteractionApplicationCommandCallbackData Build()
48 | {
49 | if (Embeds.Count <= 0 && (Content is null || Content == ""))
50 | throw new Exception("Either an embed or content is required.");
51 |
52 | return new InteractionApplicationCommandCallbackData()
53 | {
54 | AllowedMentions = AllowedMentions.Count > 0 ? AllowedMentions : null,
55 | Embeds = Embeds.Count > 0 ? Embeds.ToArray() : null,
56 | Content = Content,
57 | TextToSpeech = TextToSpeech
58 | };
59 | }
60 | }
61 | }
62 |
--------------------------------------------------------------------------------
/DSharpPlus.SlashCommands/Entities/Builders/InteractionResponseBuilder.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | using DSharpPlus.SlashCommands.Enums;
8 |
9 | namespace DSharpPlus.SlashCommands.Entities.Builders
10 | {
11 | public class InteractionResponseBuilder : IBuilder
12 | {
13 | public InteractionResponseType Type { get; set; }
14 | public InteractionApplicationCommandCallbackDataBuilder? Data { get; set; }
15 |
16 | public InteractionResponseBuilder WithType(InteractionResponseType type)
17 | {
18 | Type = type;
19 | return this;
20 | }
21 |
22 | public InteractionResponseBuilder WithData(InteractionApplicationCommandCallbackDataBuilder data)
23 | {
24 | Data = data;
25 | return this;
26 | }
27 |
28 | public InteractionResponse Build()
29 | {
30 | return new InteractionResponse()
31 | {
32 | Type = Type,
33 | Data = Data?.Build()
34 | };
35 | }
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/DSharpPlus.SlashCommands/Entities/InteractionApplicationCommandCallbackData.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 |
3 | using DSharpPlus.Entities;
4 |
5 | using Newtonsoft.Json;
6 |
7 | namespace DSharpPlus.SlashCommands.Entities
8 | {
9 | public class InteractionApplicationCommandCallbackData
10 | {
11 | [JsonProperty("tts")]
12 | public bool? TextToSpeech { get; internal set; }
13 | [JsonProperty("content")]
14 | public string Content { get; internal set; }
15 | [JsonProperty("embeds")]
16 | public DiscordEmbed[]? Embeds { get; internal set; }
17 | [JsonProperty("allowed_mentions")]
18 | public IEnumerable? AllowedMentions { get; internal set; }
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/DSharpPlus.SlashCommands/Entities/InteractionContext.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Concurrent;
3 | using System.Collections.Generic;
4 | using System.Linq;
5 | using System.Text;
6 | using System.Threading.Tasks;
7 |
8 | using DSharpPlus.Entities;
9 | using DSharpPlus.SlashCommands.Enums;
10 |
11 | using Microsoft.AspNetCore.Http;
12 |
13 | namespace DSharpPlus.SlashCommands.Entities
14 | {
15 | public class InteractionContext
16 | {
17 | private readonly DiscordSlashClient _client;
18 |
19 | public DiscordInteraction Interaction { get; internal set; }
20 |
21 | public InteractionContext(DiscordSlashClient c, DiscordInteraction i)
22 | {
23 | _client = c;
24 | Interaction = i;
25 | }
26 | #region Followup
27 | ///
28 | /// Reply to the interaction by sending a followup message.
29 | ///
30 | /// Text content to send back
31 | /// Embeds to send back
32 | /// Is this message a text to speech message?
33 | /// The allowed mentions of the message
34 | /// The response object form discord
35 | public async Task ReplyAsync(string message = "", DiscordEmbed[]? embeds = null, bool? tts = null, IMention[]? allowedMentions = null, bool showSource = false)
36 | {
37 | if (embeds is not null && embeds.Length > 10)
38 | throw new Exception("Too many embeds");
39 |
40 | return await ReplyAsync(new InteractionResponse()
41 | {
42 | Type = showSource ? InteractionResponseType.ChannelMessageWithSource : InteractionResponseType.DeferredChannelMessageWithSource,
43 | Data = new InteractionApplicationCommandCallbackData()
44 | {
45 | Content = message,
46 | Embeds = embeds,
47 | TextToSpeech = tts,
48 | AllowedMentions = allowedMentions
49 | }
50 | });
51 | }
52 |
53 | ///
54 | /// Reply to the interaction by sending a followup message.
55 | ///
56 | /// An InteractionResponse object to send to the user.
57 | /// The response object form discord
58 | public async Task ReplyAsync(InteractionResponse response)
59 | {
60 | var msg = await _client.FollowupWithAsync(response, Interaction.Token);
61 |
62 | if (msg is null)
63 | throw new Exception("Failed to reterive message object from Discord.");
64 |
65 | return msg;
66 | }
67 | #endregion
68 | #region Edit
69 | // Edit for both initial response and other responses.
70 | ///
71 | /// Edits an already sent message.
72 | ///
73 | /// Text content to send
74 | /// Message to edit by ID of the order it was sent. Defaults to the initial response
75 | /// Embeds to send.
76 | /// Is this Text To Speech?
77 | /// Allowed mentions list
78 | /// The edited response
79 | public async Task EditResponseAsync(string message = "", ulong toEdit = 0, DiscordEmbed[]? embeds = null, bool? tts = null, IMention[]? allowedMentions = null)
80 | {
81 | if (embeds is not null && embeds.Length > 10)
82 | throw new Exception("Too many embeds");
83 |
84 | return await EditResponseAsync(new InteractionResponse()
85 | {
86 | Type = InteractionResponseType.ChannelMessageWithSource,
87 | Data = new InteractionApplicationCommandCallbackData()
88 | {
89 | Content = message,
90 | Embeds = embeds,
91 | TextToSpeech = tts,
92 | AllowedMentions = allowedMentions
93 | }
94 | },
95 | toEdit);
96 | }
97 |
98 | ///
99 | /// Edits an already sent message
100 | ///
101 | /// InteractionResponse to send to the user
102 | /// Message to edit by ID of the order it was sent. Defaults to the initial response
103 | /// The edited response
104 | public async Task EditResponseAsync(InteractionResponse response, ulong toEdit = 0)
105 | {
106 | DiscordMessage? msg;
107 | if(toEdit == 0)
108 | {
109 | msg = await _client.UpdateAsync(response, Interaction.Token);
110 | }
111 | else
112 | {
113 | msg = await _client.EditAsync(response, Interaction.Token, toEdit);
114 | }
115 |
116 | if (msg is null)
117 | throw new Exception("Failed to edit the message");
118 |
119 | return msg;
120 | }
121 | #endregion
122 | #region Delete
123 | ///
124 | /// Deletes the initial response for this interaction.
125 | ///
126 | /// The deleted interaction
127 | public async Task DeleteInitalAsync()
128 | {
129 | var msg = await _client.DeleteAsync(Interaction.Token);
130 |
131 | if (msg is null)
132 | throw new Exception("Failed to delete original message");
133 |
134 | return msg;
135 | }
136 | #endregion
137 | }
138 | }
139 |
--------------------------------------------------------------------------------
/DSharpPlus.SlashCommands/Entities/InteractionResponse.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | using DSharpPlus.SlashCommands.Enums;
4 |
5 | using Newtonsoft.Json;
6 | using Newtonsoft.Json.Linq;
7 |
8 | namespace DSharpPlus.SlashCommands.Entities
9 | {
10 | public class InteractionResponse
11 | {
12 | [JsonProperty("type")]
13 | public InteractionResponseType Type { get; internal set; }
14 | [JsonProperty("data")]
15 | public InteractionApplicationCommandCallbackData? Data { get; internal set; }
16 |
17 | ///
18 | /// Builds the webhook body for sending a new message.
19 | ///
20 | /// Raw JSON body for a webhook POST operation.
21 | public string BuildWebhookBody(JsonSerializerSettings settings)
22 | {
23 | if (Data is null)
24 | throw new Exception("Data can not be null.");
25 |
26 | return JsonConvert.SerializeObject(Data, settings);
27 | }
28 |
29 | ///
30 | /// Builds the webhook edit body for editing a previous message.
31 | ///
32 | /// Raw JSON body for a webhook PATCH operation.
33 | public string BuildWebhookEditBody(JsonSerializerSettings settings)
34 | {
35 | if (Data is null)
36 | throw new Exception("Data can not be null.");
37 |
38 | var d = JObject.Parse(JsonConvert.SerializeObject(Data, settings));
39 |
40 | if (d.ContainsKey("tts"))
41 | d.Remove("tts");
42 |
43 | return d.ToString();
44 | }
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/DSharpPlus.SlashCommands/Entities/SlashCommand.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Threading.Tasks;
5 |
6 | namespace DSharpPlus.SlashCommands.Entities
7 | {
8 | public class SlashCommand
9 | {
10 | public string Name { get; set; }
11 | public string Description { get; set; }
12 | public ulong? GuildId { get; set; }
13 | public ulong? CommandId { get; set; }
14 | public ulong? ApplicationId { get; set; }
15 | public SlashSubcommand? Command { get; init; }
16 |
17 | public Dictionary? Subcommands { get; init; }
18 |
19 | public SlashCommand(string name, SlashSubcommand command, ulong? gid)
20 | {
21 | Name = name;
22 | Description = command.Description;
23 | GuildId = gid;
24 | Command = command;
25 | Subcommands = null;
26 | }
27 |
28 | public SlashCommand(string name, SlashSubcommandGroup[] subcommands, ulong? gid, string desc = "n/a")
29 | {
30 | Name = name;
31 | Description = desc;
32 | Subcommands = subcommands.ToDictionary(x => x.Name);
33 | GuildId = gid;
34 | Command = null;
35 | }
36 |
37 | ///
38 | /// Attempts to execute a command from a command with no subcommands.
39 | ///
40 | /// Command arguments
41 | /// True if the command was attempted, false if there was no command to attempt.
42 | public bool ExecuteCommand(BaseDiscordClient c, InteractionContext ctx, params object[] args)
43 | {
44 | List