Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings
This repository was archived by the owner on Apr 30, 2024. It is now read-only.

Commit a5122d8

Browse files
Update README.md (#35)
1 parent ed5311f commit a5122d8

File tree

1 file changed

+1
-323
lines changed

1 file changed

+1
-323
lines changed

‎README.md‎

Lines changed: 1 addition & 323 deletions
Original file line numberDiff line numberDiff line change
@@ -11,326 +11,4 @@ Join the [Discord server](https://discord.gg/2ZhXXVJYhU) for any questions, help
1111

1212
# Documentation
1313

14-
DSharpPlus doesn't currently have a slash command framework. You can use this library to implement slash commands and context menus into your bot.
15-
16-
I have done my best to make this as similar to CommandsNext as possible to make it a smooth experience. However, the library does not support registering or editing commands at runtime. While you can make commands at runtime using the methods on the client, if you have a command class registered for that guild/globally if you're making global commands, it will be overwritten (therefore probably deleted) on the next startup due to the limitations of the bulk overwrite endpoint.
17-
18-
Now, on to the actual guide:
19-
## Installing
20-
Simply search for `IDoEverything.DSharpPlus.SlashCommands` and install the latest version. If you're using command line:
21-
22-
Package-Manager: `Install-Package IDoEverything.DSharpPlus.SlashCommands`
23-
24-
.NET CLI: `dotnet add package IDoEverything.DSharpPlus.SlashCommands`
25-
26-
The current version of the library depends on the DSharpPlus nightly version. If you're using the stable nuget version, [update to the nightly version](https://dsharpplus.github.io/articles/misc/nightly_builds.html).
27-
# Important: Authorizing your bot
28-
29-
For a bot to make slash commands in a server, it must be authorized with the applications.commands scope as well. In the OAuth2 section of the developer portal, you can check the applications.commands box to generate an invite link. You can check the bot box as well to generate a link that authorizes both. If a bot is already authorized with the bot scope, you can still authorize with just the applications.commands scope without having to kick out the bot.
30-
31-
If your bot isn't properly authorized, a 403 exception will be thrown on startup.
32-
33-
# Setup
34-
35-
Add the using reference to your bot class:
36-
```cs
37-
using DSharpPlus.SlashCommands;
38-
```
39-
40-
You can then register a `SlashCommandsExtension` on your `DiscordClient`, similar to how you register a `CommandsNextExtension`
41-
42-
```cs
43-
var slash = discord.UseSlashCommands();
44-
```
45-
46-
## Making a command class
47-
Similar to CommandsNext, you can make a module for slash commands and make it inherit from `ApplicationCommandModule`
48-
```cs
49-
public class SlashCommands : ApplicationCommandModule
50-
{
51-
//commands
52-
}
53-
```
54-
You have to then register it with your `SlashCommandsExtension`.
55-
56-
Slash commands can be registered either globally or for a certain guild. However, if you try to register them globally, they can take up to an hour to cache across all guilds. So, it is recommended that you only register them for a certain guild for testing, and only register them globally once they're ready to be used.
57-
58-
To register your command class,
59-
```cs
60-
//To register them for a single server, recommended for testing
61-
slash.RegisterCommands<SlashCommands>(guild_id);
62-
63-
//To register them globally, once you're confident that they're ready to be used by everyone
64-
slash.RegisterCommands<SlashCommands>();
65-
```
66-
*Make sure that you register them before your `ConnectAsync`*
67-
68-
## Making Slash Commands!
69-
On to the exciting part.
70-
71-
Slash command methods must be `Task`s and have the `SlashCommand` attribute. The first argument for the method must be an `InteractionContext`. Let's make a simple slash command:
72-
```cs
73-
public class SlashCommands : ApplicationCommandModule
74-
{
75-
[SlashCommand("test", "A slash command made to test the DSharpPlusSlashCommands library!")]
76-
public async Task TestCommand(InteractionContext ctx) { }
77-
}
78-
```
79-
80-
To make a response, you must run `CreateResponseAsync` on your `InteractionContext`. `CreateResponseAsync` takes two arguments. The first is a [`InteractionResponseType`](https://dsharpplus.github.io/api/DSharpPlus.InteractionResponseType.html):
81-
* `DeferredChannelMessageWithSource` - Acknowledges the interaction, doesn't require any content.
82-
* `ChannelMessageWithSource` - Sends a message to the channel, requires you to specify some data to send.
83-
84-
An interaction expires in 3 seconds unless you make a response. If the code you execute before making a response has the potential to take more than 3 seconds, you should first create a `DeferredChannelMessageWithSource` response, and then edit it after your code executes.
85-
86-
The second argument is a type of [`DiscordInteractionResponseBuilder`](https://dsharpplus.github.io/api/DSharpPlus.Entities.DiscordInteractionResponseBuilder.html). It functions similarly to the DiscordMessageBuilder, except you cannot send files, and you can have multiple embeds.
87-
88-
If you want to send a file, you'll have to edit the response.
89-
90-
A simple response would be like:
91-
```cs
92-
[SlashCommand("test", "A slash command made to test the DSharpPlusSlashCommands library!")]
93-
public async Task TestCommand(InteractionContext ctx)
94-
{
95-
await ctx.CreateResponseAsync(InteractionResponseType.ChannelMessageWithSource, new DiscordInteractionResponseBuilder().WithContent("Success!"));
96-
}
97-
```
98-
If your code will take some time to execute:
99-
```cs
100-
[SlashCommand("delaytest", "A slash command made to test the DSharpPlusSlashCommands library!")]
101-
public async Task DelayTestCommand(InteractionContext ctx)
102-
{
103-
await ctx.CreateResponseAsync(InteractionResponseType.DeferredChannelMessageWithSource);
104-
105-
//Some time consuming task like a database call or a complex operation
106-
107-
await ctx.EditResponseAsync(new DiscordWebhookBuilder().WithContent("Thanks for waiting!"));
108-
}
109-
```
110-
You can also override `BeforeExecutionAsync` and `AfterExecutionAsync` to run code before and after all the commands in a module. This does not apply to groups, you have the override them individually for the group's class.
111-
`BeforeExecutionAsync` can also be used to prevent the command from running.
112-
113-
### Arguments
114-
If you want the user to be able to give more data to the command, you can add some arguments.
115-
116-
Arguments must have the `Option` attribute, and can be of type:
117-
* `string`
118-
* `long` or `long?`
119-
* `bool` or `bool?`
120-
* `double` or `double?`
121-
* `DiscordUser` - This can be cast to `DiscordMember` if the command is run in a guild
122-
* `DiscordChannel`
123-
* `DiscordRole`
124-
* `SnowflakeObject` - This can accept both a user and a role; you can cast it `DiscordUser`, `DiscordMember` or `DiscordRole` to get the actual object
125-
* `Enum` - This can used for choices through an enum; read further
126-
127-
If you want to make them optional, you can assign a default value.
128-
129-
You can also predefine some choices for the option. Choices only work for `string`, `long` or `double` arguments. THere are several ways to use them:
130-
1. Using the `Choice` attribute. You can add multiple attributes to add multiple choices.
131-
2. You can define choices using enums. See the example below.
132-
3. You can use a `ChoiceProvider` to run code to get the choices from a database or similar. See the example below.
133-
134-
(second and third method contributed by @Epictek)
135-
136-
Some examples:
137-
```cs
138-
//Attribute choices
139-
[SlashCommand("ban", "Bans a user")]
140-
public async Task Ban(InteractionContext ctx, [Option("user", "User to ban")] DiscordUser user,
141-
[Choice("None", 0)]
142-
[Choice("1 Day", 1)]
143-
[Choice("1 Week", 7)]
144-
[Option("deletedays", "Number of days of message history to delete")] long deleteDays = 0)
145-
{
146-
await ctx.Guild.BanMemberAsync(user.Id, (int)deleteDays);
147-
await ctx.CreateResponseAsync(InteractionResponseType.ChannelMessageWithSource, new DiscordInteractionResponseBuilder().WithContent($"Banned {user.Username}"));
148-
}
149-
150-
//Enum choices
151-
public enum MyEnum
152-
{
153-
[ChoiceName("Option 1")]
154-
option1,
155-
[ChoiceName("Option 2")]
156-
option2,
157-
[ChoiceName("Option 3")]
158-
option3
159-
}
160-
161-
[SlashCommand("enum", "Test enum")]
162-
public async Task EnumCommand(InteractionContext ctx, [Option("enum", "enum option")]MyEnum myEnum = MyEnum.option1)
163-
{
164-
await ctx.CreateResponseAsync(InteractionResponseType.ChannelMessageWithSource, new DiscordInteractionResponseBuilder().WithContent(myEnum.GetName()));
165-
}
166-
167-
//ChoiceProvider choices
168-
public class TestChoiceProvider : IChoiceProvider
169-
{
170-
public async Task<IEnumerable<DiscordApplicationCommandOptionChoice>> Provider()
171-
{
172-
return new DiscordApplicationCommandOptionChoice[]
173-
{
174-
//You would normally use a database call here
175-
new DiscordApplicationCommandOptionChoice("testing", "testing"),
176-
new DiscordApplicationCommandOptionChoice("testing2", "test option 2")
177-
};
178-
}
179-
}
180-
181-
[SlashCommand("choiceprovider", "test")]
182-
public async Task ChoiceProviderCommand(InteractionContext ctx,
183-
[ChoiceProvider(typeof(TestChoiceProvider))]
184-
[Option("option", "option")] string option)
185-
{
186-
await ctx.CreateResponseAsync(InteractionResponseType.ChannelMessageWithSource, new DiscordInteractionResponseBuilder().WithContent(option));
187-
}
188-
```
189-
190-
### Groups
191-
You can have slash commands in groups. Their structure is explained [here](https://discord.com/developers/docs/interactions/slash-commands#nested-subcommands-and-groups). You can simply mark your command class with the `[SlashCommandGroup]` attribute.
192-
```cs
193-
//for regular groups
194-
[SlashCommandGroup("group", "description")]
195-
public class GroupContainer : ApplicationCommandModule
196-
{
197-
[SlashCommand("command", "description")]
198-
public async Task Command(InteractionContext ctx) {}
199-
200-
[SlashCommand("command2", "description")]
201-
public async Task Command2(InteractionContext ctx) {}
202-
}
203-
204-
//For subgroups inside groups
205-
[SlashCommandGroup("group", "description")]
206-
public class SubGroupContainer : ApplicationCommandModule
207-
{
208-
[SlashCommandGroup("subgroup", "description")]
209-
public class SubGroup : ApplicationCommandModule
210-
{
211-
[SlashCommand("command", "description")]
212-
public async Task Command(InteractionContext ctx) {}
213-
214-
[SlashCommand("command2", "description")]
215-
public async Task Command2(InteractionContext ctx) {}
216-
}
217-
218-
[SlashCommandGroup("subgroup2", "description")]
219-
public class SubGroup2 : ApplicationCommandModule
220-
{
221-
[SlashCommand("command", "description")]
222-
public async Task Command(InteractionContext ctx) {}
223-
224-
[SlashCommand("command2", "description")]
225-
public async Task Command2(InteractionContext ctx) {}
226-
}
227-
}
228-
```
229-
230-
## Context Menus
231-
Context menus are commands that show up when you right click on a user or a message. Their implementation is fairly similar to slash commands.
232-
```cs
233-
//For user commands
234-
[ContextMenu(ApplicationCommandType.UserContextMenu, "User Menu")]
235-
public async Task UserMenu(ContextMenuContext ctx) { }
236-
237-
//For message commands
238-
[ContextMenu(ApplicationCommandType.MessageContextMenu, "Message Menu")]
239-
public async Task MessageMenu(ContextMenuContext ctx) { }
240-
```
241-
Responding works exactly the same as slash commands. You cannot define any arguments.
242-
243-
### Pre-execution checks
244-
You can define some custom attributes that function as pre-execution checks, working very similarly to `CommandsNext`. Simply create an attribute that inherits `SlashCheckBaseAttribute` for slash commands, and `ContextMenuCheckBaseAttribute` for context menus and override the methods.
245-
246-
There are also some built in ones for slash commands, the same ones as on `CommandsNext` but prefix with `Slash` - for example the `SlashRequirePermissionsAttribute`
247-
```cs
248-
public class RequireUserIdAttribute : SlashCheckBaseAttribute
249-
{
250-
public ulong UserId;
251-
252-
public RequireUserIdAttribute(ulong userId)
253-
{
254-
this.UserId = userId;
255-
}
256-
257-
public override async Task<bool> ExecuteChecksAsync(InteractionContext ctx)
258-
{
259-
if (ctx.User.Id == UserId)
260-
return true;
261-
else
262-
return false;
263-
}
264-
}
265-
266-
```
267-
Then just apply it to your command
268-
```cs
269-
[SlashCommand("admin", "runs sneaky admin things")]
270-
[RequireUserId(0000000000000)]
271-
public async Task Admin(InteractionContext ctx) { //secrets }
272-
```
273-
To provide a custom error message when an execution check fails, hook the `SlashCommandErrored` event for slash commands, and `ContextMenuErrored` event for context menus on your `SlashCommandsExtension`
274-
```cs
275-
SlashCommandsExtension slash = //assigned;
276-
slash.SlashCommandErrored += async (s, e) =>
277-
{
278-
if(e.Exception is SlashExecutionChecksFailedException slex)
279-
{
280-
foreach (var check in slex.FailedChecks)
281-
if (check is RequireUserIdAttribute att)
282-
await e.Context.CreateResponseAsync(InteractionResponseType.ChannelMessageWithSource, new DiscordInteractionResponseBuilder().WithContent($"Only <@{att.Id}> can run this command!"));
283-
}
284-
};
285-
```
286-
Context menus throw `ContextMenuExecutionChecksFailedException`.
287-
288-
To use a built in one:
289-
```cs
290-
[SlashCommand("ban", "Bans a user")]
291-
[SlashRequirePermissions(Permissions.BanMembers)]
292-
public async Task Ban(InteractionContext ctx, [Option("user", "User to ban")] DiscordUser user,
293-
[Choice("None", 0)]
294-
[Choice("1 Day", 1)]
295-
[Choice("1 Week", 7)]
296-
[Option("deletedays", "Number of days of message history to delete")] long deleteDays = 0)
297-
{
298-
await ctx.Guild.BanMemberAsync(user.Id, (int)deleteDays);
299-
await ctx.CreateResponseAsync(InteractionResponseType.ChannelMessageWithSource, new DiscordInteractionResponseBuilder().WithContent($"Banned {user.Username}"));
300-
}
301-
```
302-
303-
### Dependency Injection
304-
To pass in a service collection, provide a `SlashCommandsConfiguration` in `UseSlashCommands`.
305-
```cs
306-
var slash = discord.UseSlashCommands(new SlashCommandsConfiguration
307-
{
308-
Services = new ServiceCollection().AddSingleton<Random>().BuildServiceProvider()
309-
});
310-
```
311-
Property injection is implemented, however static properties will not be replaced. If you wish for a non-static property to be left alone, assign it the `DontInject` attribute. Property Injection can be used like so:
312-
```cs
313-
public class Commands : ApplicationCommandModule
314-
{
315-
public Database Database { private get; set; } // The get accessor is optionally public, but the set accessor must be public.
316-
317-
[SlashCommand("ping", "Checks the latency between the bot and it's database. Best used to see if the bot is lagging.")]
318-
public async Task Ping(InteractionContext context) => await context.CreateResponseAsync(InteractionResponseType.ChannelMessageWithSource, new()
319-
{
320-
Content = $"Pong! Database latency is {Database.GetPing()}ms."
321-
});
322-
}
323-
```
324-
### Sharding
325-
`UseSlashCommands` -> `UseSlashCommmandsAsync` which returns a dictionary.
326-
327-
You'll have to foreach over it to register events.
328-
329-
### Module Lifespans
330-
You can specify a module's lifespan by applying the `SlashModuleLifespan` attribute on it. Modules are transient by default.
331-
332-
# Issues and contributing
333-
If you find any issues or bugs, you should join the discord server and discuss it. If it's an actual bug, you can create an [issue](https://github.com/IDoEverything/DSharpPlus.SlashCommands/issues). If you would like to contribute or make changes, feel free to open a [pull request](https://github.com/IDoEverything/DSharpPlus.SlashCommands/pulls).
334-
335-
# Questions?
336-
Join the [discord server](https://discord.gg/2ZhXXVJYhU)!
14+
Documentation and further maintenance has moved over to https://github.com/DSharpPlus/DSharpPlus/tree/master/DSharpPlus.SlashCommands

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /