Browse Source

Merge branch 'dev' into v3-final

pull/1966/head
quin lynch 3 years ago
parent
commit
1cd60ab8b5
10 changed files with 637 additions and 5 deletions
  1. +1
    -1
      README.md
  2. +27
    -0
      docs/guides/interactions_framework/autocompleters.md
  3. +27
    -0
      docs/guides/interactions_framework/dependency-injection.md
  4. +360
    -0
      docs/guides/interactions_framework/intro.md
  5. +73
    -0
      docs/guides/interactions_framework/post_execution.md
  6. +8
    -0
      docs/guides/interactions_framework/preconditions.md
  7. +130
    -0
      docs/guides/interactions_framework/typeconverters.md
  8. +9
    -1
      src/Discord.Net.Commands/Builders/ModuleBuilder.cs
  9. +0
    -1
      src/Discord.Net.Commands/Builders/ModuleClassBuilder.cs
  10. +2
    -2
      src/Discord.Net.Core/Entities/Interactions/SlashCommands/SlashCommandBuilder.cs

+ 1
- 1
README.md View File

@@ -68,4 +68,4 @@ Due to the nature of the Discord API, we will oftentimes need to add a property

Furthermore, while we will never break the API (outside of interface changes) on minor builds, we will occasionally need to break the ABI, by introducing parameters to a method to match changes upstream with Discord. As such, a minor version increment may require you to recompile your code, and dependencies, such as addons, may also need to be recompiled and republished on the newer version. When a binary breaking change is made, the change will be noted in the release notes.

An increment of the MAJOR component indicates that breaking changes have been made to the library; consumers should check the release notes to determine what changes need to be made.
An increment of the MAJOR component indicates that breaking changes have been made to the library; consumers should check the release notes to determine what changes need to be made.

+ 27
- 0
docs/guides/interactions_framework/autocompleters.md View File

@@ -0,0 +1,27 @@
---
uid: Guides.InteractionsFramework.Autocompleters
title: Autocompleters
---

# Autocompleters

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.

+ 27
- 0
docs/guides/interactions_framework/dependency-injection.md View File

@@ -0,0 +1,27 @@
---
uid: Guides.InteractionsFramework.DependencyInjection
title: Dependency Injection
---

# Dependency Injection

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).

+ 360
- 0
docs/guides/interactions_framework/intro.md View File

@@ -0,0 +1,360 @@
---
uid: Guides.InteractionsFramework.Intro
title: Introduction to the Interaction Framework
---

# Getting Started

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 |
|-------------------------------|------------------------------|---------------------|-------------------------------|--------------------------|
|[Slash Command](#slash-commands)| `Task`/`Task<RuntimeResult>` | 25 | any* | `[SlashCommand]` |
|[User Command](#user-commands) | `Task`/`Task<RuntimeResult>` | 1 | Implementations of `IUser` | `[UserCommand]` |
|[Message Command](#message-commands)| `Task`/`Task<RuntimeResult>` | 1 | Implementations of `IMessage` | `[MessageCommand]` |
|[Component Interaction Command](#component-interaction-commands)| `Task`/`Task<RuntimeResult>` | inf | `string` or `string[]` | `[ComponentInteraction]` |
|[Autocomplete Command](#autocomplete-commands)| `Task`/`Task<RuntimeResult>` | - | - | `[AutocompleteCommand]`|

> [!NOTE]
> 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.*
| interface | Channel Type |
|---------------------|-------------------------------|
| `IStageChannel` | Stage Channels |
| `IVoiceChannel` | Voice Channels |
| `IDMChannel` | DM Channels |
| `IGroupChannel` | Group Channels |
| `ICategory Channel` | Category Channels |
| `INewsChannel` | News Channels |
| `IThreadChannel` | Public, Private, News Threads |
| `ITextChannel` | Text Channels |

---

##### Optional Parameters

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:

```csharp
[AutocompleteCommand("command_name", "parameter_name")]
public async Task Autocomplete()
{
IEnumerable<AutocompleteResult> results;

...

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`.

```csharp
discordClient.ButtonExecuted += async (interaction) =>
{
var ctx = new SocketInteractionContext<SocketMessageComponent>(discordClient, interaction);
await interactionService.ExecuteAsync(ctx, serviceProvider);
};

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:

| Method | Mean | Error | StdDev |
|----------------- |----------:|---------:|---------:|
| ReflectionInvoke | 225.93 ns | 4.522 ns | 7.040 ns |
| CompiledLambda | 48.79 ns | 0.981 ns | 1.276 ns |

## Registering Commands to Discord

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:

```csharp
#if DEBUG
await interactionService.RegisterCommandsToGuildAsync(<test_guild_id>);
#else
await interactionService.RegisterCommandsGloballyAsync();
#endif
```

+ 73
- 0
docs/guides/interactions_framework/post_execution.md View File

@@ -0,0 +1,73 @@
---
uid: Guides.InteractionsFramework.PostEx
title: Post-Execution
---

# Post-Execution Logic

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.

```csharp
interactionService.SlashCommandExecuted += SlashCommandExecuted;

async Task SlashCommandExecuted (SlashCommandInfo arg1, Discord.IInteractionContext arg2, IResult arg3)
{
if (!arg3.IsSuccess)
{
switch (arg3.Error)
{
case InteractionCommandError.UnmetPrecondition:
await arg2.Interaction.RespondAsync($"Unmet Precondition: {arg3.ErrorReason}");
break;
case InteractionCommandError.UnknownCommand:
await arg2.Interaction.RespondAsync("Unknown command");
break;
case InteractionCommandError.BadArgs:
await arg2.Interaction.RespondAsync("Invalid number or arguments");
break;
case InteractionCommandError.Exception:
await arg2.Interaction.RespondAsync($"Command exception:{arg3.ErrorReason}");
break;
case InteractionCommandError.Unsuccessful:
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.

+ 8
- 0
docs/guides/interactions_framework/preconditions.md View File

@@ -0,0 +1,8 @@
---
uid: Guides.InteractionsFramework.Preconditions
title: Preconditions
---

# Preconditions

Preconditions in Interaction Service work exactly the same as they do in ***Discord.Net.Commands***. For more information, check out [Preconditions](../commands/preconditions.md)

+ 130
- 0
docs/guides/interactions_framework/typeconverters.md View File

@@ -0,0 +1,130 @@
---
uid: Guides.InteractionsFramework.TypeConverters
title: Type Converters
---

# TypeConverters

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.FromSuccess(result));
else
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>();

foreach (var name in names)
choices.Add(new ApplicationCommandOptionChoiceProperties
{
Name = name,
Value = name
});

properties.Choices = choices;
}
}
}
```

---

## Registering TypeConverters

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

```csharp
interactionService.AddTypeConverter<string[]>(new StringArrayConverter());
```

### Generic TypeConverters

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:

```csharp
interactionService.AddGenericTypeConverter<Enum>(typeof(EnumConverter<>));
```

Interaction service checks if the target base type satisfies the type constraints of the Generic TypeConverter class.

> Dependencies of Generic TypeConverters are also resolved using the Dependency Injection pattern.

+ 9
- 1
src/Discord.Net.Commands/Builders/ModuleBuilder.cs View File

@@ -8,6 +8,7 @@ namespace Discord.Commands.Builders
public class ModuleBuilder
{
#region ModuleBuilder
private string _group;
private readonly List<CommandBuilder> _commands;
private readonly List<ModuleBuilder> _submodules;
private readonly List<PreconditionAttribute> _preconditions;
@@ -19,7 +20,14 @@ namespace Discord.Commands.Builders
public string Name { get; set; }
public string Summary { get; set; }
public string Remarks { get; set; }
public string Group { get; set; }
public string Group { get => _group;
set
{
_aliases.Remove(_group);
_group = value;
AddAliases(value);
}
}

public IReadOnlyList<CommandBuilder> Commands => _commands;
public IReadOnlyList<ModuleBuilder> Modules => _submodules;


+ 0
- 1
src/Discord.Net.Commands/Builders/ModuleClassBuilder.cs View File

@@ -118,7 +118,6 @@ namespace Discord.Commands
case GroupAttribute group:
builder.Name ??= group.Prefix;
builder.Group = group.Prefix;
builder.AddAliases(group.Prefix);
break;
case PreconditionAttribute precondition:
builder.AddPrecondition(precondition);


+ 2
- 2
src/Discord.Net.Core/Entities/Interactions/SlashCommands/SlashCommandBuilder.cs View File

@@ -397,7 +397,7 @@ namespace Discord
/// <param name="maxValue">The largest number value the user can input.</param>
/// <returns>The current builder.</returns>
public SlashCommandOptionBuilder AddOption(string name, ApplicationCommandOptionType type,
string description, bool? required = null, bool isDefault = false, bool isAutocomplete = false, double? minValue = null, double? maxValue = null,
string description, bool? isRequired = null, bool isDefault = false, bool isAutocomplete = false, double? minValue = null, double? maxValue = null,
List<SlashCommandOptionBuilder> options = null, List<ChannelType> channelTypes = null, params ApplicationCommandOptionChoiceProperties[] choices)
{
// Make sure the name matches the requirements from discord
@@ -423,7 +423,7 @@ namespace Discord
{
Name = name,
Description = description,
IsRequired = required,
IsRequired = isRequired,
IsDefault = isDefault,
IsAutocomplete = isAutocomplete,
MinValue = minValue,


Loading…
Cancel
Save