- #1923 Added helpers to `Emoji` for parsing (933ea42).
- #1923 Added banner and accent color to guild users (933ea42).
- #1923 Added `RatelimitCallback` to `RequestOptions` (933ea42).
- #1923 Added `Emoji` to roles (933ea42).
- #1923 Added `UseInteractionSnowflakeDate` to config (933ea42).
- #1923 Added checks for gateway intent in some methods. DownloadUsersAsync will throw an exception if you don't have the gateway intent enabled locally now, this will help with the vauge error that was given before (933ea42).
- #1923 Added SendFilesAsync to channels (933ea42).
- #1923 Added Attachments property to MessageProperties (933ea42).
- #1958 Added NET5.0 and NET6.0 builds (aa6bb5e).
- #1958 Added `Discord.Interactions` (aa6bb5e).
### Fixed
- #1832 Grab correct Uses value for vanity urls (8ed8714)
- #1849 Remove obsolete methods and properties (70aab6c)
- #1850 Create DM channel with id and author alone (95bae78)
- #1853 Fire GuildMemberUpdated without cached user (d176fef)
- #1854 Gateway events for DMs (a7ff6ce)
- #1858 MessageUpdated without author (8b29e0f)
- #1859 Add missing AddRef and related (de7f9b5)
- #1862 Message update without author (fabe034)
- #1864 ApiClient.CurrentUser being null (08507c0)
- #1871 Add empty role list if not present (f47001a)
- #1872 Connection deadlock when trying to Send and Disconnect (97d90b9)
- #1873 Remove OperationCanceledException handling in connecting logic (7cf8499)
- #1876 Message type (ac52a11)
- #1877 Rest message type (22bb1b0)
- #1886 Change embed description max length to 4096 (8349cd7)
- #1890 Add default avatar to WithAuthor extension (c200861)
### Misc
- #20 Update EmbedBuilder.Overwrites.md (76a878a)
- #21 Fix line about PriorityAttribute (75b74e1)
- #1152 Add characters commonly use in links to Sanitize (b9274d1)
- #1852 Internal change to GetOrCreateUser (dfaaa21)
- #1861 Add MaxBitrate to the interface (e0dbe7c)
- #1865 Add null check to AllowedMentions.ToModel() (3cb662f)
- #1923 Merge Labs 3.X into dev (933ea42)
- #1941 Fix emoto try parse (900c1f4)
- #1942 Implement multi-file upload to webhooks (bc440ab)
- #1944 Add Voice binaries (b5c150d)
- #1945 Update socket presence and add new presence event (9d6dc62)
- #1946 fix NRE when adding parameters thru builders (143ca6d)
- #1947 fix sharded client current user (d5f5ae1)
- #1950 Add custom setter to Group property of ModuleBuilder to automatically invoke AddAliases (ba656e9)
- #1958 Update from Discord .Net Labs 3.4.8 (aa6bb5e)
- #1959 Update isRequired (98b03be)
- Add `MatchResult` (d1b31c8)
- Add requested changes (a92ec56)
- Fix incorrect casing on `HandleCommandPipeline` (adf3a9c)
- Merge branch 'commands/validate-get-best-match' of https://github.com/siscodeorg/Discord.Net into siscodeorg-commands/validate-get-best-match (3cd9f39)
- Merge branch 'siscodeorg-commands/validate-get-best-match' into dev (4f1fe2b)
- Remove docs build from azure pipelines (2336b98)
- use async main (125f6c7)
- #1923 Made `Hierarchy` a `IGuildUser` property.
- #1923 Changed embed discription length to 4096 (933ea42).
- #1923 Fixed gateway serialization to include nulls for API v9 (933ea42).
- #1923 Removed error log for gateway reconnects (933ea42).
Autocompleters provide a similar pattern to TypeConverters. Autocompleters are cached, singleton services and they are used by the Interaction Service to handle Autocomplete Interations targeted to a specific Slash Command parameter.
To start using Autocompleters, use the `[AutocompleteAttribute(Type autocompleterType)]` overload of the `[AutocompleteAttribute]`. This will dynamically link the parameter to the Autocompleter type.
## Creating Autocompleters
A valid Autocompleter must inherit `AutocompleteHandler` base type and implement all of its abstract methods.
### GenerateSuggestionsAsync()
Interactions Service uses this method to generate a response to a Autocomplete Interaction. This method should return `AutocompletionResult.FromSuccess(IEnumerable<AutocompleteResult>)` to display parameter sugesstions to the user. If there are no suggestions to be presented to the user, you have two options:
1. Returning the parameterless `AutocompletionResult.FromSuccess()` will display "No options match your search." message to the user.
2. Returning `AutocompleteResult.FromError()` will make the Interaction Service not respond to the interation, consequently displaying the user "Loading options failed." message.
## Resolving Autocompleter Dependencies
Autocompleter dependencies are resolved using the same dependency injection pattern as the Interaction Modules. Property injection and constructor injection are both valid ways to get service dependencies.
Because Autocompleters are constructed at service startup, class dependencies are resolved only once. If you need to access per-request dependencies you can use the IServiceProvider parameter of the `GenerateSuggestionsAsync()` method.
Interaction Service uses dependency injection to perform most of its operations. This way, you can access service dependencies throughout the framework.
## Setup
1. Create a `Microsoft.Extensions.DependencyInjection.ServiceCollection`.
2. Add the dependencies you wish to use in the modules.
3. Build a `IServiceProvider` using the `BuildServiceProvider()` method of the `ServiceCollection`.
4. Pass the `IServiceProvider` to `AddModulesAsync()`, `AddModuleAsync()` and `ExecuteAsync()` methods.
## Accessing the Dependencies
Services of a `IServiceProvider` can be accessed using *Contructor Injection* and *Property Injection*.
Interaction Service will populate the constructor parameters using the provided `IServiceProvider`. Any public settable class Property will also be populated in the same manner.
## Service Scopes
Interaction Service has built-in support for scoped service types. Scoped lifetime services are instantiated once per command execution. Including the Preconditon checks, every module operation is executed within a single service scope (which is sepearate from the global service scope).
> For more in-depth information about service lifetimes check out [Microsoft Docs](https://docs.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-5.0#service-lifetimes-1).
Interaction Service provides an attribute based framework for creating Discord Interaction handlers.
To start using the Interaction Service, you need to create a service instance. Optionally you can provide the `InterctionService` constructor with a `InteractionServiceConfig` to change the services behaviour to suit your needs.
```csharp
...
var commands = new InteractionService(discord);
...
```
## Modules
Attribute based Interaction handlers must be defined within a command module class. Command modules are responsible for executing the Interaction handlers and providing them with the necessary execution info and helper functions.
Command modules are transient objects. A new module instance is created before a command execution starts then it will be disposed right after the method returns.
Every module class must:
- be public
- inherit `InteractionModuleBase`
Optionally you can override the included :
- OnModuleBuilding (executed after the module is built)
- BeforeExecute (executed before a command execution starts)
- AfterExecute (executed after a command execution concludes)
methods to configure the modules behaviour.
Every command module exposes a set of helper methods, namely:
- `RespondAsync()` => Respond to the interaction
- `FollowupAsync()` => Create a followup message for an interaction
- `ReplyAsync()` => Send a message to the origin channel of the interaction
- `DeleteOriginalResponseAsync()` => Delete the original interaction response
## Commands
Valid **Interaction Commands** must comply with the following requirements:
| | return type | max parameter count | allowed parameter types | attribute |
> a `TypeConverter` that is capable of parsing type in question must be registered to the `InteractionService` instance.
You should avoid using long running code in your command module. Depending on your setup, long running code may block the Gateway thread of your bot, interrupting its connection to Discord.
### Slash Commands
Slash Commands are created using the `[SlashCommandAttribute]`. Every Slash Command must declare a name and a description. You can check Discords **Application Command Naming Guidelines** [here](https://discord.com/developers/docs/interactions/application-commands#application-command-object-application-command-naming).
```csharp
[SlashCommand("echo", "Echo an input")]
public async Task Echo(string input)
{
await RespondAsync(input);
}
```
#### Parameters
Slash Commands can have up to 25 method parameters. You must name your parameters in accordance with [Discords Naming Guidelines](https://discord.com/developers/docs/interactions/application-commands#application-command-object-application-command-naming). Interaction Service also features a pascal casing seperator for formatting parameter names with pascal casing into Discord compliant parameter names('parameterName' => 'parameter-name'). By default, your methods can feature the following parameter types:
- Implementations of `IUser`
- Implementations of `IChannel`*
- Implementations of `IRole`
- Implementations of `IMentionable`
- `string`
- `float`, `double`, `decimal`
- `bool`
- `char`
- `sbyte`, `byte`
- `int16`, `int32`, `int64`
- `uint16`, `uint32`, `uint64`
- `enum` (Values are registered as multiple choice options and are enforced by Discord. Use `[HideAttribute]' on enum values to prevent them from getting registered.)
- `DateTime`
- `TimeSpan`
---
**You can use more specialized implementations of `IChannel` to restrict the allowed channel types for a channel type option.*
Parameters with default values (ie. `int count = 0`) will be displayed as optional parameters on Discord Client.
##### Parameter Summary
By using the `[SummaryAttribute]` you can customize the displayed name and description of a parameter
```csharp
[Summary(description: "this is a parameter description")] string input
```
##### Parameter Choices
`[ChoiceAttribute]` can be used to add choices to a parameter.
```csharp
[SlashCommand("blep", "Send a random adorable animal photo")]
public async Task Blep([Choice("Dog","dog"), Choice("Cat", "cat"), Choice("Penguin", "penguin")] string animal)
{
...
}
```
In most cases, instead of relying on this attribute, you should use an `Enum` to create multiple choice parameters. Ex.
```csharp
public enum Animal
{
Cat,
Dog,
Penguin
}
[SlashCommand("blep", "Send a random adorable animal photo")]
public async Task Blep(Animal animal)
{
...
}
```
This Slash Command will be displayed exactly the same as the previous example.
##### Channel Types
Channel types for an `IChannel` parameter can also be restricted using the `[ChannelTypesAttribute]`.
```csharp
[SlashCommand("name", "Description")]
public async Task Command([ChannelTypes(ChannelType.Stage, ChannelType.Text)]IChannel channel)
{
...
}
```
In this case, user can only input Stage Channels and Text Channels to this parameter.
##### Autocomplete
You can enable Autocomple Interactions for a Slash Command parameter using the `[AutocompleteAttribute]`. To handle the Autocomplete Interactions raised by this parameter you can either create [Autocomplete Commands](#autocomplete-commands) or you can opt to use the [Autocompleters Pattern](./autocompleters)
##### Min/Max Value
You can specify the permitted max/min value for a number type parameter using the `[MaxValueAttribute]` and `[MinValueAttribute]`.
### User Commands
A valid User Command must have the following structure:
```csharp
[UserCommand("Say Hello")]
public async Task SayHello(IUser user)
{
...
}
```
User commands can only have one parameter and its type must be an implementation of `IUser`.
### Message Commands
A valid Message Command must have the following structure:
```csharp
[MessageCommand("Bookmark")]
public async Task Bookmark(IMessage user)
{
...
}
```
Message commands can only have one parameter and its type must be an implementation of `IMessage`.
### Component Interaction Commands
Component Interaction Commands are used to handle interactions that originate from **Discord Message Component**s. This pattern is particularly useful if you will be reusing a set a **Custom ID**s.
```csharp
[ComponentInteraction("custom_id")]
public async Task RoleSelection()
{
...
}
```
Component Interaction Commands support wild card matching, by default `*` character can be used to create a wild card pattern. Interaction Service will use lazy matching to capture the words corresponding to the wild card character. And the captured words will be passed on to the command method in the same order they were captured.
*Ex.*
If Interaction Service recieves a component interaction with **player:play,rickroll** custom id, `op` will be *play* and `name` will be *rickroll*
```csharp
[ComponentInteraction("player:*,*")]
public async Task Play(string op, string name)
{
...
}
```
You may use as many wild card characters as you want.
#### Select Menus
Unlike button interactions, select menu interactions also contain the values of the selected menu items. In this case, you should structure your method to accept a string array.
```csharp
[ComponentInteraction("role_selection")]
public async Task RoleSelection(string[] selectedRoles)
{
...
}
```
Wild card pattern can also be used to match select menu custom ids but remember that the array containing the select menu values should be the last parameter.
```csharp
[ComponentInteraction("role_selection_*")]
public async Task RoleSelection(string id, string[] selectedRoles)
{
...
}
```
### Autocomplete Commands
Autocomplete commands must be parameterless methods. A valid Autocomplete command must have the following structure:
await (Context.Interaction as SocketAutocompleteInteraction).RespondAsync(results);
}
```
Alternatively, you can use the *Autocompleters* to simplify this workflow.
## Interaction Context
Every command module provides its commands with an execution context. This context property includes general information about the underlying interaction that triggered the command execution. The base command context.
You can design your modules to work with different implementation types of `IInteractionContext`. To achieve this, make sure your module classes inherit from the generic variant of the `InteractionModuleBase`.
> Context type must be consistent throughout the project, or you will run into issues during runtime.
Interaction Service ships with 4 different kinds of `InteractionContext`s:
1. InteractionContext: A bare-bones execution context consisting of only implementation netural interfaces
2. SocketInteractionContext: An execution context for use with `DiscordSocketClient`. Socket entities are exposed in this context without the need of casting them.
3. ShardedInteractionContext: `DiscordShardedClient` variant of the `SocketInteractionContext`
4. RestInteractionContext: An execution context designed to be used with a `DiscordRestClient` and webhook based interactions pattern
You can create custom Interaction Contexts by implementing the `IInteracitonContext` interface.
One problem with using the concrete type InteractionContexts is that you cannot access the information that is specific to different interaction types without casting. Concrete type interaction contexts are great for creating shared interaction modules but you can also use the generic variants of the built-in interaction contexts to create interaction specific interaction modules.
Ex.
Message component interactions have access to a special method called `UpdateAsync()` to update the body of the method the interaction originated from. Normally this wouldn't be accessable without casting the `Context.Interaction`.
public class MessageComponentModule : InteractionModuleBase<SocketInteractionContext<SocketMessageComponent>>
{
[ComponentInteraction("custom_id")]
public async Command()
{
Context.Interaction.UpdateAsync(...);
}
}
```
## Loading Modules
Interaction Service can automatically discover and load modules that inherit `InteractionModuleBase` from an `Assembly`. Call `InteractionService.AddModulesAsync()` to use this functionality.
You can also manually add Interaction modules using the `InteractionService.AddModuleAsync()` method by providing the module type you want to load.
## Resolving Module Dependencies
Module dependencies are resolved using the Constructor Injection and Property Injection patterns. Meaning, the constructor parameters and public settable properties of a module will be assigned using the `IServiceProvider`. For more information on dependency injection, check out [Dependency Injection](./dependency-injection.md)
## Module Groups
Module groups allow you to create sub-commands and sub-commands groups. By nesting commands inside a module that is tagged with `[GroupAttribute]` you can create prefixed commands.
Although creating nested module stuctures are allowed, you are not permitted to use more than 2 `[GroupAttribute]`s in module hierarchy.
## Executing Commands
Any of the following socket events can be used to execute commands:
- InteractionCreated
- ButtonExecuted
- SelectMenuExecuted
- AutocompleteExecuted
- UserCommandExecuted
- MessageCommandExecuted
Commands can be either executed on the gateway thread or on a seperate thread from the thread pool. This behaviour can be configured by changing the *RunMode* property of `InteractionServiceConfig` or by setting the *runMode* parameter of a command attribute.
You can also configure the way `InteractionService` executes the commands. By default, commands are executed using `ConstructorInfo.Invoke()` to create module instances and `MethodInfo.Invoke()` method for executing the method bodies. By setting, `InteractionServiceConfig.UseCompiledLambda` to `true`, you can make `InteractionService` create module instances and execute commands using *Compiled Lambda* expressions. This cuts down on command execution time but it might add some memory overhead.
Time it takes to create a module instance and execute a `Task.Delay(0)` method using the Reflection methods compared to Compiled Lambda expressions:
Application commands loaded to the Interaction Service can be registered to Discord using a number of different methods. In most cases `RegisterCommandsGloballyAsync()` and `RegisterCommandsToGuildAsync()` are the methods to use. Command registration methods can only be used after the gateway client is ready or the rest client is logged in.
In debug environment, since Global commands can take up to 1 hour to register/update, you should register your commands to a test guild for your changes to take effect immediately. You can use the preprocessor directives to create a simple logic for registering commands:
Interaction Service uses `IResult`s to provide information about the state of command execution. These can be used to log internal exceptions or provide some insight to the command user.
If you are running your commands using `RunMode.Sync` these command results can be retrieved from the return value of `InteractionService.ExecuteCommandAsync()` method or by registering delegates to Interaction Service events.
If you are using the `RunMode.Async` to run your commands, you must use the Interaction Service events to get the execution results. When using `RunMode.Async`, `InteractionService.ExecuteCommandAsync()` will always return a successful result.
## Results
Interaction Result come in a handful of different flavours:
1. `AutocompletionResult`: returned by Autocompleters
2. `ExecuteResult`: contains the result of method body execution process
3. `PreconditionGroupResult`: returned by Precondition groups
4. `PreconditionResult`: returned by preconditions
5. `RuntimeResult`: a user implementable result for returning user defined results
6. `SearchResult`: returned by command lookup map
7. `TypeConverterResult`: returned by TypeConverters
You can either use the `IResult.Error` property of an Interaction result or create type check for the afformentioned result types to branch out your post-execution logic to handle different situations.
## CommandExecuted Events
Every time a command gets executed, Interaction Service raises a *CommandExecuted event. These events can be used to create a post-execution pipeline.
await arg2.Interaction.RespondAsync("Command could not be executed");
break;
default:
break;
}
}
}
```
## Log Event
InteractionService regularly outputs information about the occuring events to keep the developer informed.
## Runtime Result
Interaction commands allow you to return `Task<RuntimeResult>` to pass on additional information about the command execution process back to your post-execution logic.
Custom `RuntimeResult` classes can be created by inheriting the base `RuntimeResult` class.
If command execution process reaches the method body of the command and no exceptions are thrown during the execution of the method body, `RuntimeResult` returned by your command will be accessible by casting/type-checking the `IResult` parameter of the *CommandExecuted event delegate.
Preconditions in Interaction Service work exactly the same as they do in ***Discord.Net.Commands***. For more information, check out [Preconditions](../commands/preconditions.md)
TypeConverters are responsible for registering command parameters to Discord and parsing the user inputs into method parameters.
By default, TypeConverters for the following types are provided with `Discord.Net.Interactions` library.
- Implementations of `IUser`
- Implementations of `IChannel`
- Implementations of `IRole`
- Implementations of `IMentionable`
- `string`
- `float`, `double`, `decimal`
- `bool`
- `char`
- `sbyte`, `byte`
- `int16`, `int32`, `int64`
- `uint16`, `uint32`, `uint64`
- `enum`
- `DateTime`
- `TimeSpan`
## Creating TypeConverters
Depending on your needs, there are two types of `TypeConverter`s you can create:
- Concrete type
- Generic type
A valid converter must inherit `TypeConverter` base type. And override the abstract base methods.
### CanConvertTo() Method
This method is used by Interaction Service to search for alternative Type Converters.
Interaction Services determines the most suitable `TypeConverter` for a parameter type in the following order:
1. It searches for a `TypeConverter` that is registered to specifically target that parameter type
2. It searches for a generic `TypeConverter` with a matching type constraint. If there are more multiple matches, the one whose type constraint is the most specialized will be chosen.
3. It searches for a `TypeConverter` that returns `true` when its `CanConvertTo()` method is invoked for thaty parameter type.
> Alternatively, you can use the generic variant (`TypeConverter<T>`) of the `TypeConverter` base class which implements the following method body for `CanConvertTo()` method
```csharp
public sealed override bool CanConvertTo (Type type) =>
typeof(T).IsAssignableFrom(type);
```
### GetDiscordType() Method
This method is used by Interaction Service to determine the [Discord Application Command Option type](https://discord.com/developers/docs/interactions/application-commands#application-command-object-application-command-option-type) of a parameter type.
### ReadAsync() Method
This method is used by Interaction Service to parse the user input. This method should return `TypeConverterResult.FromSuccess` if the parsing operation is successful, otherwise it should return `TypeConverterResult.FromError`. The inner logic of this method is totally up to you, however you should avoid using long running code.
### Write() Method
This method is used to configure the **Discord Application Command Option** before it gets registered to Discord. Command Option is configured by modifying the `ApplicationCommandOptionProperties` instance.
The default parameter building pipeline is isolated and will not be disturbed by the `TypeConverter` workflow. But changes made in this method will override the values generated by the Interaction Service for a **Discord Application Command Option**.
---
### Example Enum TypeConverter
```csharp
internal sealed class EnumConverter<T> : TypeConverter<T> where T : struct, Enum
{
public override ApplicationCommandOptionType GetDiscordType ( ) => ApplicationCommandOptionType.String;
public override Task<TypeConverterResult> ReadAsync (IInteractionCommandContext context, SocketSlashCommandDataOption option, IServiceProvider services)
{
if (Enum.TryParse<T>((string)option.Value, out var result))
return Task.FromResult(TypeConverterResult.FromError(InteractionCommandError.ConvertFailed, $"Value {option.Value} cannot be converted to {nameof(T)}"));
}
public override void Write (ApplicationCommandOptionProperties properties, IParameterInfo parameterInfo)
{
var names = Enum.GetNames(typeof(T));
if (names.Length <= 25)
{
var choices = new List<ApplicationCommandOptionChoiceProperties>();
> TypeConverters must be registered prior to module discovery. If Interaction Service encounters a parameter type that doesn't belong to any of the registered `TypeConverter`s during this phase, it will throw an exception.
### Concrete TypeConverters
Registering Concrete TypeConverters are as simple as creating an instance of your custom converter and invoking `AddTypeConverter()` method.
To register a generic TypeConverter, you need to invoke the `AddGenericTypeConverter()` method of the Interaction Service class. You need to pass the type of your `TypeConverter` and a target base type to this method.
For instance, to register the previously mentioned [Example Enum Converter](#example-enum-converter) the following can be used:
Thank you for your continuous support to the Openl Qizhi Community AI Collaboration Platform. In order to protect your usage rights and ensure network security, we updated the Openl Qizhi Community AI Collaboration Platform Usage Agreement in January 2024. The updated agreement specifies that users are prohibited from using intranet penetration tools. After you click "Agree and continue", you can continue to use our services. Thank you for your cooperation and understanding.