diff --git a/CHANGELOG.md b/CHANGELOG.md
index b6430bd84..7385ab38a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,6 +1,52 @@
# Changelog
-## [3.7.1] - 2022-5-27
+## [3.8.0] - 2022-08-27
+### Added
+- #2384 Added support for the WEBHOOKS_UPDATED event (010e8e8)
+- #2370 Add async callbacks for IModuleBase (503fa75)
+- #2367 Added DeleteMessagesAsync for TIV and added remaining rate limit in client log (f178660)
+- #2379 Added Max/Min length fields for ApplicationCommandOption (e551431)
+- #2369 Added support for using `RespondWithModalAsync()` without prior IModal declaration (500e7b4)
+- #2347 Added Embed field comparison operators (89a8ea1)
+- #2359 Added support for creating lottie stickers (32b03c8)
+- #2395 Added App Command localization support and `ILocalizationManager` to IF (39bbd29)
+
+### Fixed
+- #2425 Fix missing Fact attribute in ColorTests (92215b1)
+- #2424 Fix IGuild.GetBansAsync() (b7b7964)
+- #2416 Fix role icon & emoji assignment (b6b5e95)
+- #2414 Fix NRE on RestCommandBase Data (02bc3b7)
+- #2421 Fix placeholder length being hardcoded (8dfe19f)
+- #2352 Fix issues related to the absence of bot scope (1eb42c6)
+- #2346 Fix IGuild.DisconnectAsync(IUser) not disconnecting users (ba02416)
+- #2404 Fix range of issues presented by 3rd party analyzer (902326d)
+- #2409 Removes GroupContext from requirecontext (b0b8167)
+
+### Misc
+- #2366 Fixed typo in ChannelUpdatedEvent's documentation (cfd2662)
+- #2408 Fix sharding sample throwing at appcommand registration (519deda)
+- #2420 Fix broken code snippet in dependency injection docs (ddcf68a)
+- #2430 Add a note about DontAutoRegisterAttribute (917118d)
+- #2418 Update xmldocs to reflect the ConnectedUsers split (65b98f8)
+- #2415 Adds missing DI entries in TOC (c49d483)
+- #2407 Introduces high quality dependency injection documentation (6fdcf98)
+- #2348 Added `RequiredInput` attribute to example in int.framework intro (ee6e0ad)
+- #2385 Add ServerStarter.Host to deployment.md (06ed995)
+- #2405 Add a note about `IgnoreGroupNames` to IF docs (cf25acd)
+- #2356 Makes voice section about precompiled binaries more visible (e0d68d4 )
+- #2405 IF intro docs improvements (246282d)
+- #2406 Labs deprecation & readme/docs edits (bf493ea)
+
+## [3.7.2] - 2022-06-02
+### Added
+- #2328 Add method overloads to InteractionService (0fad3e8)
+- #2336 Add support for attachments on interaction response type 7 (35db22e)
+- #2338 AddOptions no longer has an uneeded restriction, added AddOptions to SlashCommandOptionBuilder (3a37f89)
+
+### Fixed
+- #2342 Disable TIV restrictions for rollout of TIV (7adf516)
+
+## [3.7.1] - 2022-05-27
### Added
- #2325 Add missing interaction properties (d3a693a)
- #2330 Add better call control in ParseHttpInteraction (a890de9)
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 840650cf8..1455267f9 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -7,8 +7,7 @@ following guidelines when possible:
## Development Cycle
We prefer all changes to the library to be discussed beforehand,
-either in a GitHub issue, or in a discussion in our Discord channel
-with library regulars or other contributors.
+either in a GitHub issue, or in a discussion in our [Discord server](https://discord.gg/dnet)
Issues that are tagged as "up for grabs" are free to be picked up by
any member of the community.
diff --git a/Discord.Net.targets b/Discord.Net.targets
index d5c67a692..d9ec415f9 100644
--- a/Discord.Net.targets
+++ b/Discord.Net.targets
@@ -1,6 +1,6 @@
- 3.7.1
+ 3.8.0
latest
Discord.Net Contributors
discord;discordapp
diff --git a/README.md b/README.md
index e85216dbf..7b98a5f41 100644
--- a/README.md
+++ b/README.md
@@ -19,11 +19,11 @@
Discord.Net is an unofficial .NET API Wrapper for the Discord client (https://discord.com).
-## Documentation
+## 📄 Documentation
-- [Nightly](https://discordnet.dev)
+- https://discordnet.dev
-## Installation
+## 📥 Installation
### Stable (NuGet)
@@ -33,55 +33,78 @@ Our stable builds available from NuGet through the Discord.Net metapackage:
The individual components may also be installed from NuGet:
-- [Discord.Net.Commands](https://www.nuget.org/packages/Discord.Net.Commands/)
-- [Discord.Net.Rest](https://www.nuget.org/packages/Discord.Net.Rest/)
-- [Discord.Net.WebSocket](https://www.nuget.org/packages/Discord.Net.WebSocket/)
-- [Discord.Net.Webhook](https://www.nuget.org/packages/Discord.Net.Webhook/)
+- _Webhooks_
+ - [Discord.Net.Webhook](https://www.nuget.org/packages/Discord.Net.Webhook/)
-### Unstable (MyGet)
+- _Text-Command & Interaction services._
+ - [Discord.Net.Commands](https://www.nuget.org/packages/Discord.Net.Commands/)
+ - [Discord.Net.Interactions](https://www.nuget.org/packages/Discord.Net.Interactions/)
-Nightly builds are available through our MyGet feed (`https://www.myget.org/F/discord-net/api/v3/index.json`).
+- _Complete API coverage._
+ - [Discord.Net.WebSocket](https://www.nuget.org/packages/Discord.Net.WebSocket/)
+ - [Discord.Net.Rest](https://www.nuget.org/packages/Discord.Net.Rest/)
-### Unstable (Labs)
+- _The API core. Implements only entities and barebones functionality._
+ - [Discord.Net.Core](https://www.nuget.org/packages/Discord.Net.Core/)
-Labs builds are available on nuget (`https://www.nuget.org/packages/Discord.Net.Labs/`) and myget (`https://www.myget.org/F/discord-net-labs/api/v3/index.json`).
+### Unstable
-## Compiling
+Nightly builds are available through our MyGet feed (`https://www.myget.org/F/discord-net/api/v3/index.json`).
+These builds target the dev branch.
-In order to compile Discord.Net, you require the following:
+## 🛑 Known Issues
-### Using Visual Studio
+### WebSockets (Win7 and earlier)
-- [Visual Studio 2017](https://www.microsoft.com/net/core#windowsvs2017)
-- [.NET Core SDK](https://www.microsoft.com/net/download/core)
+.NET Core 1.1 does not support WebSockets on Win7 and earlier.
+This issue has been fixed since the release of .NET Core 2.1.
+It is recommended to target .NET Core 2.1 or above for your project if you wish to run your bot on legacy platforms;
+alternatively, you may choose to install the
+[Discord.Net.Providers.WS4Net](https://www.nuget.org/packages/Discord.Net.Providers.WS4Net/) package.
-The .NET Core workload must be selected during Visual Studio installation.
+### TLS on .NET Framework.
-### Using Command Line
+Discord supports only TLS1.2+ on all their websites including the API since 07/19/2022.
+.NET Framework does not support this protocol by default.
+If you depend on .NET Framework, it is suggested to upgrade your project to `net6-windows`.
+This framework supports most of the windows-only features introduced by fx, and resolves startup errors from the TLS protocol mismatch.
-- [.NET Core SDK](https://www.microsoft.com/net/download/core)
+## 🗃️ Versioning Guarantees
-## Known Issues
+This library generally abides by [Semantic Versioning](https://semver.org). Packages are published in `MAJOR.MINOR.PATCH` version format.
-### WebSockets (Win7 and earlier)
+### Patch component
-.NET Core 1.1 does not support WebSockets on Win7 and earlier. This issue has been fixed since the release of .NET Core 2.1. It is recommended to target .NET Core 2.1 or above for your project if you wish to run your bot on legacy platforms; alternatively, you may choose to install the [Discord.Net.Providers.WS4Net](https://www.nuget.org/packages/Discord.Net.Providers.WS4Net/) package.
+An increment of the **PATCH** component always indicates that an internal-only change was made, generally a bugfix. These changes will not affect the public-facing API in any way, and are always guaranteed to be forward- and backwards-compatible with your codebase, any pre-compiled dependencies of your codebase.
-## Versioning Guarantees
+### Minor component
-This library generally abides by [Semantic Versioning](https://semver.org). Packages are published in MAJOR.MINOR.PATCH version format.
+An increment of the **MINOR** component indicates that some addition was made to the library,
+and this addition is not backwards-compatible with prior versions.
+However, Discord.Net **does not guarantee forward-compatibility** on minor additions.
+In other words, we permit a limited set of breaking changes on a minor version bump.
-An increment of the PATCH component always indicates that an internal-only change was made, generally a bugfix. These changes will not affect the public-facing API in any way, and are always guaranteed to be forward- and backwards-compatible with your codebase, any pre-compiled dependencies of your codebase.
+Due to the nature of the Discord API, we will oftentimes need to add a property to an entity to support the latest API changes.
+Discord.Net provides interfaces as a method of consuming entities; and as such, introducing a new field to an entity is technically a breaking change.
+Major version bumps generally indicate some major change to the library,
+and as such we are hesitant to bump the major version for every minor addition to the library.
+To compromise, we have decided that interfaces should be treated as **consumable only**,
+and your applications should typically not be implementing interfaces.
-An increment of the MINOR component indicates that some addition was made to the library, and this addition is not backwards-compatible with prior versions. However, Discord.Net **does not guarantee forward-compatibility** on minor additions. In other words, we permit a limited set of breaking changes on a minor version bump.
+> For applications where interfaces are implemented, such as in test mocks, we apologize for this inconsistency with SemVer.
-Due to the nature of the Discord API, we will oftentimes need to add a property to an entity to support the latest API changes. Discord.Net provides interfaces as a method of consuming entities; and as such, introducing a new field to an entity is technically a breaking change. Major version bumps generally indicate some major change to the library, and as such we are hesitant to bump the major version for every minor addition to the library. To compromise, we have decided that interfaces should be treated as **consumable only**, and your applications should typically not be implementing interfaces. (For applications where interfaces are implemented, such as in test mocks, we apologize for this inconsistency with SemVer).
+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.
-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.
+### Major component
-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.
-## Branches
+## 📚 Branches
### Release/X.X
diff --git a/docs/docfx.json b/docs/docfx.json
index 5c35fcd5f..64a20ecb2 100644
--- a/docs/docfx.json
+++ b/docs/docfx.json
@@ -60,7 +60,7 @@
"overwrite": "_overwrites/**/**.md",
"globalMetadata": {
"_appTitle": "Discord.Net Documentation",
- "_appFooter": "Discord.Net (c) 2015-2022 3.7.1",
+ "_appFooter": "Discord.Net (c) 2015-2022 3.8.0",
"_enableSearch": true,
"_appLogoPath": "marketing/logo/SVG/Logomark Purple.svg",
"_appFaviconPath": "favicon.ico"
diff --git a/docs/faq/basics/client-basics.md b/docs/faq/basics/client-basics.md
index ade33c35d..3f21dd165 100644
--- a/docs/faq/basics/client-basics.md
+++ b/docs/faq/basics/client-basics.md
@@ -36,7 +36,7 @@ _client = new DiscordSocketClient(config);
This includes intents that receive messages such as: `GatewayIntents.GuildMessages, GatewayIntents.DirectMessages`
- GuildMembers: An intent disabled by default, as you need to enable it in the [developer portal].
- GuildPresences: Also disabled by default, this intent together with `GuildMembers` are the only intents not included in `AllUnprivileged`.
-- All: All intents, it is ill adviced to use this without care, as it *can* cause a memory leak from presence.
+- All: All intents, it is ill advised to use this without care, as it _can_ cause a memory leak from presence.
The library will give responsive warnings if you specify unnecessary intents.
diff --git a/docs/guides/dependency_injection/basics.md b/docs/guides/dependency_injection/basics.md
new file mode 100644
index 000000000..c553ee68c
--- /dev/null
+++ b/docs/guides/dependency_injection/basics.md
@@ -0,0 +1,69 @@
+---
+uid: Guides.DI.Intro
+title: Introduction
+---
+
+# Dependency Injection
+
+Dependency injection is a feature not required in Discord.Net, but makes it a lot easier to use.
+It can be combined with a large number of other libraries, and gives you better control over your application.
+
+> Further into the documentation, Dependency Injection will be referred to as 'DI'.
+
+## Installation
+
+DI is not native to .NET. You need to install the extension packages to your project in order to use it:
+
+- [Meta](https://www.nuget.org/packages/Microsoft.Extensions.DependencyInjection/).
+- [Abstractions](https://www.nuget.org/packages/Microsoft.Extensions.DependencyInjection.Abstractions/).
+
+> [!WARNING]
+> Downloading the abstractions package alone will not give you access to required classes to use DI properly.
+> Please install both packages, or choose to only install the meta package to implicitly install both.
+
+### Visual Package Manager:
+
+[Installing](images/manager.png)
+
+### Command Line:
+
+`PM> Install-Package Microsoft.Extensions.DependencyInjection`.
+
+> [!TIP]
+> ASP.NET already comes packed with all the necessary assemblies in its framework.
+> You do not require to install any additional NuGet packages to make full use of all features of DI in ASP.NET projects.
+
+## Getting started
+
+First of all, you will need to create an application based around dependency injection,
+which in order will be able to access and inject them across the project.
+
+[!code-csharp[Building the Program](samples/program.cs)]
+
+In order to freely pass around your dependencies in different classes,
+you will need to register them to a new `ServiceCollection` and build them into an `IServiceProvider` as seen above.
+The IServiceProvider then needs to be accessible by the startup file, so you can access your provider and manage them.
+
+[!code-csharp[Building the Collection](samples/collection.cs)]
+
+As shown above, an instance of `DiscordSocketConfig` is created, and added **before** the client itself is.
+Because the collection will prefer to create the highest populated constructor available with the services already present,
+it will prefer the constructor with the configuration, because you already added it.
+
+## Using your dependencies
+
+After building your provider in the Program class constructor, the provider is now available inside the instance you're actively using.
+Through the provider, we can ask for the DiscordSocketClient we registered earlier.
+
+[!code-csharp[Applying DI in RunAsync](samples/runasync.cs)]
+
+> [!WARNING]
+> Service constructors are not activated until the service is **first requested**.
+> An 'endpoint' service will have to be requested from the provider before it is activated.
+> If a service is requested with dependencies, its dependencies (if not already active) will be activated before the service itself is.
+
+## Injecting dependencies
+
+You can not only directly access the provider from a field or property, but you can also pass around instances to classes registered in the provider.
+There are multiple ways to do this. Please refer to the
+[Injection Documentation](Guides.DI.Injection) for further information.
diff --git a/docs/guides/dependency_injection/images/manager.png b/docs/guides/dependency_injection/images/manager.png
new file mode 100644
index 000000000..91791f7a0
Binary files /dev/null and b/docs/guides/dependency_injection/images/manager.png differ
diff --git a/docs/guides/dependency_injection/injection.md b/docs/guides/dependency_injection/injection.md
new file mode 100644
index 000000000..85a77476f
--- /dev/null
+++ b/docs/guides/dependency_injection/injection.md
@@ -0,0 +1,44 @@
+---
+uid: Guides.DI.Injection
+title: Injection
+---
+
+# Injecting instances within the provider
+
+You can inject registered services into any class that is registered to the `IServiceProvider`.
+This can be done through property or constructor.
+
+> [!NOTE]
+> As mentioned above, the dependency *and* the target class have to be registered in order for the serviceprovider to resolve it.
+
+## Injecting through a constructor
+
+Services can be injected from the constructor of the class.
+This is the preferred approach, because it automatically locks the readonly field in place with the provided service and isn't accessible outside of the class.
+
+[!code-csharp[Constructor Injection](samples/ctor-injecting.cs)]
+
+## Injecting through properties
+
+Injecting through properties is also allowed as follows.
+
+[!code-csharp[Property Injection](samples/property-injecting.cs)]
+
+> [!WARNING]
+> Dependency Injection will not resolve missing services in property injection, and it will not pick a constructor instead.
+> If a publically accessible property is attempted to be injected and its service is missing, the application will throw an error.
+
+## Using the provider itself
+
+You can also access the provider reference itself from injecting it into a class. There are multiple use cases for this:
+
+- Allowing libraries (Like Discord.Net) to access your provider internally.
+- Injecting optional dependencies.
+- Calling methods on the provider itself if necessary, this is often done for creating scopes.
+
+[!code-csharp[Provider Injection](samples/provider.cs)]
+
+> [!NOTE]
+> It is important to keep in mind that the provider will pick the 'biggest' available constructor.
+> If you choose to introduce multiple constructors,
+> keep in mind that services missing from one constructor may have the provider pick another one that *is* available instead of throwing an exception.
diff --git a/docs/guides/dependency_injection/samples/access-activator.cs b/docs/guides/dependency_injection/samples/access-activator.cs
new file mode 100644
index 000000000..29e71e894
--- /dev/null
+++ b/docs/guides/dependency_injection/samples/access-activator.cs
@@ -0,0 +1,9 @@
+async Task RunAsync()
+{
+ //...
+
+ await _serviceProvider.GetRequiredService()
+ .ActivateAsync();
+
+ //...
+}
diff --git a/docs/guides/dependency_injection/samples/collection.cs b/docs/guides/dependency_injection/samples/collection.cs
new file mode 100644
index 000000000..4d0457dc9
--- /dev/null
+++ b/docs/guides/dependency_injection/samples/collection.cs
@@ -0,0 +1,13 @@
+static IServiceProvider CreateServices()
+{
+ var config = new DiscordSocketConfig()
+ {
+ //...
+ };
+
+ var collection = new ServiceCollection()
+ .AddSingleton(config)
+ .AddSingleton();
+
+ return collection.BuildServiceProvider();
+}
diff --git a/docs/guides/dependency_injection/samples/ctor-injecting.cs b/docs/guides/dependency_injection/samples/ctor-injecting.cs
new file mode 100644
index 000000000..c412bd29c
--- /dev/null
+++ b/docs/guides/dependency_injection/samples/ctor-injecting.cs
@@ -0,0 +1,14 @@
+public class ClientHandler
+{
+ private readonly DiscordSocketClient _client;
+
+ public ClientHandler(DiscordSocketClient client)
+ {
+ _client = client;
+ }
+
+ public async Task ConfigureAsync()
+ {
+ //...
+ }
+}
diff --git a/docs/guides/dependency_injection/samples/enumeration.cs b/docs/guides/dependency_injection/samples/enumeration.cs
new file mode 100644
index 000000000..cc8c617f3
--- /dev/null
+++ b/docs/guides/dependency_injection/samples/enumeration.cs
@@ -0,0 +1,18 @@
+public class ServiceActivator
+{
+ // This contains *all* registered services of serviceType IService
+ private readonly IEnumerable _services;
+
+ public ServiceActivator(IEnumerable services)
+ {
+ _services = services;
+ }
+
+ public async Task ActivateAsync()
+ {
+ foreach(var service in _services)
+ {
+ await service.StartAsync();
+ }
+ }
+}
diff --git a/docs/guides/dependency_injection/samples/implicit-registration.cs b/docs/guides/dependency_injection/samples/implicit-registration.cs
new file mode 100644
index 000000000..52f84228b
--- /dev/null
+++ b/docs/guides/dependency_injection/samples/implicit-registration.cs
@@ -0,0 +1,12 @@
+public static ServiceCollection RegisterImplicitServices(this ServiceCollection collection, Type interfaceType, Type activatorType)
+{
+ // Get all types in the executing assembly. There are many ways to do this, but this is fastest.
+ foreach (var type in typeof(Program).Assembly.GetTypes())
+ {
+ if (interfaceType.IsAssignableFrom(type) && !type.IsAbstract)
+ collection.AddSingleton(interfaceType, type);
+ }
+
+ // Register the activator so you can activate the instances.
+ collection.AddSingleton(activatorType);
+}
diff --git a/docs/guides/dependency_injection/samples/modules.cs b/docs/guides/dependency_injection/samples/modules.cs
new file mode 100644
index 000000000..2fadc13d4
--- /dev/null
+++ b/docs/guides/dependency_injection/samples/modules.cs
@@ -0,0 +1,16 @@
+public class MyModule : InteractionModuleBase
+{
+ private readonly MyService _service;
+
+ public MyModule(MyService service)
+ {
+ _service = service;
+ }
+
+ [SlashCommand("things", "Shows things")]
+ public async Task ThingsAsync()
+ {
+ var str = string.Join("\n", _service.Things)
+ await RespondAsync(str);
+ }
+}
diff --git a/docs/guides/dependency_injection/samples/program.cs b/docs/guides/dependency_injection/samples/program.cs
new file mode 100644
index 000000000..6d985319a
--- /dev/null
+++ b/docs/guides/dependency_injection/samples/program.cs
@@ -0,0 +1,24 @@
+public class Program
+{
+ private readonly IServiceProvider _serviceProvider;
+
+ public Program()
+ {
+ _serviceProvider = CreateProvider();
+ }
+
+ static void Main(string[] args)
+ => new Program().RunAsync(args).GetAwaiter().GetResult();
+
+ static IServiceProvider CreateProvider()
+ {
+ var collection = new ServiceCollection();
+ //...
+ return collection.BuildServiceProvider();
+ }
+
+ async Task RunAsync(string[] args)
+ {
+ //...
+ }
+}
diff --git a/docs/guides/dependency_injection/samples/property-injecting.cs b/docs/guides/dependency_injection/samples/property-injecting.cs
new file mode 100644
index 000000000..c0c50e150
--- /dev/null
+++ b/docs/guides/dependency_injection/samples/property-injecting.cs
@@ -0,0 +1,9 @@
+public class ClientHandler
+{
+ public DiscordSocketClient Client { get; set; }
+
+ public async Task ConfigureAsync()
+ {
+ //...
+ }
+}
diff --git a/docs/guides/dependency_injection/samples/provider.cs b/docs/guides/dependency_injection/samples/provider.cs
new file mode 100644
index 000000000..26b600b9d
--- /dev/null
+++ b/docs/guides/dependency_injection/samples/provider.cs
@@ -0,0 +1,26 @@
+public class UtilizingProvider
+{
+ private readonly IServiceProvider _provider;
+ private readonly AnyService _service;
+
+ // This service is allowed to be null because it is only populated if the service is actually available in the provider.
+ private readonly AnyOtherService? _otherService;
+
+ // This constructor injects only the service provider,
+ // and uses it to populate the other dependencies.
+ public UtilizingProvider(IServiceProvider provider)
+ {
+ _provider = provider;
+ _service = provider.GetRequiredService();
+ _otherService = provider.GetService();
+ }
+
+ // This constructor injects the service provider, and AnyService,
+ // making sure that AnyService is not null without having to call GetRequiredService
+ public UtilizingProvider(IServiceProvider provider, AnyService service)
+ {
+ _provider = provider;
+ _service = service;
+ _otherService = provider.GetService();
+ }
+}
diff --git a/docs/guides/dependency_injection/samples/runasync.cs b/docs/guides/dependency_injection/samples/runasync.cs
new file mode 100644
index 000000000..d24efc83e
--- /dev/null
+++ b/docs/guides/dependency_injection/samples/runasync.cs
@@ -0,0 +1,17 @@
+async Task RunAsync(string[] args)
+{
+ // Request the instance from the client.
+ // Because we're requesting it here first, its targetted constructor will be called and we will receive an active instance.
+ var client = _services.GetRequiredService();
+
+ client.Log += async (msg) =>
+ {
+ await Task.CompletedTask;
+ Console.WriteLine(msg);
+ }
+
+ await client.LoginAsync(TokenType.Bot, "");
+ await client.StartAsync();
+
+ await Task.Delay(Timeout.Infinite);
+}
diff --git a/docs/guides/dependency_injection/samples/scoped.cs b/docs/guides/dependency_injection/samples/scoped.cs
new file mode 100644
index 000000000..9942f8d8e
--- /dev/null
+++ b/docs/guides/dependency_injection/samples/scoped.cs
@@ -0,0 +1,6 @@
+
+// With serviceType:
+collection.AddScoped();
+
+// Without serviceType:
+collection.AddScoped();
diff --git a/docs/guides/dependency_injection/samples/service-registration.cs b/docs/guides/dependency_injection/samples/service-registration.cs
new file mode 100644
index 000000000..f6e4d22dd
--- /dev/null
+++ b/docs/guides/dependency_injection/samples/service-registration.cs
@@ -0,0 +1,21 @@
+static IServiceProvider CreateServices()
+{
+ var config = new DiscordSocketConfig()
+ {
+ //...
+ };
+
+ // X represents either Interaction or Command, as it functions the exact same for both types.
+ var servConfig = new XServiceConfig()
+ {
+ //...
+ }
+
+ var collection = new ServiceCollection()
+ .AddSingleton(config)
+ .AddSingleton()
+ .AddSingleton(servConfig)
+ .AddSingleton();
+
+ return collection.BuildServiceProvider();
+}
diff --git a/docs/guides/dependency_injection/samples/services.cs b/docs/guides/dependency_injection/samples/services.cs
new file mode 100644
index 000000000..2e5235b69
--- /dev/null
+++ b/docs/guides/dependency_injection/samples/services.cs
@@ -0,0 +1,9 @@
+public class MyService
+{
+ public List Things { get; }
+
+ public MyService()
+ {
+ Things = new();
+ }
+}
diff --git a/docs/guides/dependency_injection/samples/singleton.cs b/docs/guides/dependency_injection/samples/singleton.cs
new file mode 100644
index 000000000..f395d743e
--- /dev/null
+++ b/docs/guides/dependency_injection/samples/singleton.cs
@@ -0,0 +1,6 @@
+
+// With serviceType:
+collection.AddSingleton();
+
+// Without serviceType:
+collection.AddSingleton();
diff --git a/docs/guides/dependency_injection/samples/transient.cs b/docs/guides/dependency_injection/samples/transient.cs
new file mode 100644
index 000000000..ae1e1a5d8
--- /dev/null
+++ b/docs/guides/dependency_injection/samples/transient.cs
@@ -0,0 +1,6 @@
+
+// With serviceType:
+collection.AddTransient();
+
+// Without serviceType:
+collection.AddTransient();
diff --git a/docs/guides/dependency_injection/scaling.md b/docs/guides/dependency_injection/scaling.md
new file mode 100644
index 000000000..356fb7c72
--- /dev/null
+++ b/docs/guides/dependency_injection/scaling.md
@@ -0,0 +1,39 @@
+---
+uid: Guides.DI.Scaling
+title: Scaling your DI
+---
+
+# Scaling your DI
+
+Dependency injection has a lot of use cases, and is very suitable for scaled applications.
+There are a few ways to make registering & using services easier in large amounts.
+
+## Using a range of services.
+
+If you have a lot of services that all have the same use such as handling an event or serving a module,
+you can register and inject them all at once by some requirements:
+
+- All classes need to inherit a single interface or abstract type.
+- While not required, it is preferred if the interface and types share a method to call on request.
+- You need to register a class that all the types can be injected into.
+
+### Registering implicitly
+
+Registering all the types is done through getting all types in the assembly and checking if they inherit the target interface.
+
+[!code-csharp[Registering](samples/implicit-registration.cs)]
+
+> [!NOTE]
+> As seen above, the interfaceType and activatorType are undefined. For our usecase below, these are `IService` and `ServiceActivator` in order.
+
+### Using implicit dependencies
+
+In order to use the implicit dependencies, you have to get access to the activator you registered earlier.
+
+[!code-csharp[Accessing the activator](samples/access-activator.cs)]
+
+When the activator is accessed and the `ActivateAsync()` method is called, the following code will be executed:
+
+[!code-csharp[Executing the activator](samples/enumeration.cs)]
+
+As a result of this, all the services that were registered with `IService` as its implementation type will execute their starting code, and start up.
diff --git a/docs/guides/dependency_injection/services.md b/docs/guides/dependency_injection/services.md
new file mode 100644
index 000000000..e021a88be
--- /dev/null
+++ b/docs/guides/dependency_injection/services.md
@@ -0,0 +1,48 @@
+---
+uid: Guides.DI.Services
+title: Using DI in Interaction & Command Frameworks
+---
+
+# DI in the Interaction- & Command Service
+
+For both the Interaction- and Command Service modules, DI is quite straight-forward to use.
+
+You can inject any service into modules without the modules having to be registered to the provider.
+Discord.Net resolves your dependencies internally.
+
+> [!WARNING]
+> The way DI is used in the Interaction- & Command Service are nearly identical, except for one detail:
+> [Resolving Module Dependencies](xref:Guides.IntFw.Intro#resolving-module-dependencies)
+
+## Registering the Service
+
+Thanks to earlier described behavior of allowing already registered members as parameters of the available ctors,
+The socket client & configuration will automatically be acknowledged and the XService(client, config) overload will be used.
+
+[!code-csharp[Service Registration](samples/service-registration.cs)]
+
+## Usage in modules
+
+In the constructor of your module, any parameters will be filled in by
+the @System.IServiceProvider that you've passed.
+
+Any publicly settable properties will also be filled in the same
+manner.
+
+[!code-csharp[Module Injection](samples/modules.cs)]
+
+If you accept `Command/InteractionService` or `IServiceProvider` as a parameter in your constructor or as an injectable property,
+these entries will be filled by the `Command/InteractionService` that the module is loaded from and the `IServiceProvider` that is passed into it respectively.
+
+> [!NOTE]
+> Annotating a property with a [DontInjectAttribute] attribute will
+> prevent the property from being injected.
+
+## Services
+
+Because modules are transient of nature and will reinstantiate on every request,
+it is suggested to create a singleton service behind it to hold values across multiple command executions.
+
+[!code-csharp[Services](samples/services.cs)]
+
+
diff --git a/docs/guides/dependency_injection/types.md b/docs/guides/dependency_injection/types.md
new file mode 100644
index 000000000..e539d0695
--- /dev/null
+++ b/docs/guides/dependency_injection/types.md
@@ -0,0 +1,52 @@
+---
+uid: Guides.DI.Dependencies
+title: Types of Dependencies
+---
+
+# Dependency Types
+
+There are 3 types of dependencies to learn to use. Several different usecases apply for each.
+
+> [!WARNING]
+> When registering types with a serviceType & implementationType,
+> only the serviceType will be available for injection, and the implementationType will be used for the underlying instance.
+
+## Singleton
+
+A singleton service creates a single instance when first requested, and maintains that instance across the lifetime of the application.
+Any values that are changed within a singleton will be changed across all instances that depend on it, as they all have the same reference to it.
+
+### Registration:
+
+[!code-csharp[Singleton Example](samples/singleton.cs)]
+
+> [!NOTE]
+> Types like the Discord client and Interaction/Command services are intended to be singleton,
+> as they should last across the entire app and share their state with all references to the object.
+
+## Scoped
+
+A scoped service creates a new instance every time a new service is requested, but is kept across the 'scope'.
+As long as the service is in view for the created scope, the same instance is used for all references to the type.
+This means that you can reuse the same instance during execution, and keep the services' state for as long as the request is active.
+
+### Registration:
+
+[!code-csharp[Scoped Example](samples/scoped.cs)]
+
+> [!NOTE]
+> Without using HTTP or libraries like EFCORE, scopes are often unused in Discord bots.
+> They are most commonly used for handling HTTP and database requests.
+
+## Transient
+
+A transient service is created every time it is requested, and does not share its state between references within the target service.
+It is intended for lightweight types that require little state, to be disposed quickly after execution.
+
+### Registration:
+
+[!code-csharp[Transient Example](samples/transient.cs)]
+
+> [!NOTE]
+> Discord.Net modules behave exactly as transient types, and are intended to only last as long as the command execution takes.
+> This is why it is suggested for apps to use singleton services to keep track of cross-execution data.
diff --git a/docs/guides/deployment/deployment.md b/docs/guides/deployment/deployment.md
index 0491e841d..4313e85b4 100644
--- a/docs/guides/deployment/deployment.md
+++ b/docs/guides/deployment/deployment.md
@@ -47,6 +47,12 @@ enough. Here is a list of recommended VPS provider.
* Location(s):
* Europe: Lithuania
* Based in: Europe
+* [ServerStarter.Host](https://serverstarter.host/clients/store/discord-bots)
+ * Description: Bot hosting with a panel for quick deployment and
+ no Linux knowledge required.
+ * Location(s):
+ * America: United States
+ * Based in: United States
## .NET Core Deployment
@@ -100,4 +106,4 @@ Windows 10 x64 based machine:
* `dotnet publish -c Release -r win10-x64`
[.NET Core application deployment]: https://docs.microsoft.com/en-us/dotnet/core/deploying/
-[Runtime ID]: https://docs.microsoft.com/en-us/dotnet/core/rid-catalog
\ No newline at end of file
+[Runtime ID]: https://docs.microsoft.com/en-us/dotnet/core/rid-catalog
diff --git a/docs/guides/getting_started/installing.md b/docs/guides/getting_started/installing.md
index 0dde72380..d07787b67 100644
--- a/docs/guides/getting_started/installing.md
+++ b/docs/guides/getting_started/installing.md
@@ -30,17 +30,25 @@ other limitations, you may also consider targeting [.NET Framework]
[.net framework]: https://docs.microsoft.com/en-us/dotnet/framework/get-started/
[additional steps]: #installing-on-net-standard-11
-## Installing with NuGet
+## Installing
Release builds of Discord.Net will be published to the
[official NuGet feed].
-Development builds of Discord.Net, as well as add-ons, will be
-published to our [MyGet feed]. See
-@Guides.GettingStarted.Installation.Nightlies to learn more.
+### Experimental/Development
-[official nuget feed]: https://nuget.org
-[myget feed]: https://www.myget.org/feed/Packages/discord-net
+Development builds of Discord.Net will be
+published to our [MyGet feed]. The MyGet feed can be used to run the latest dev branch builds.
+It is not advised to use MyGet packages in a production environment, as changes may be made that negatively affect certain library functions.
+
+### Labs
+
+This exterior branch of Discord.Net has been deprecated and is no longer supported.
+If you have used Discord.Net-Labs in the past, you are advised to update to the latest version of Discord.Net.
+All features in Labs are implemented in the main repository.
+
+[official NuGet feed]: https://nuget.org
+[MyGet feed]: https://www.myget.org/feed/Packages/discord-net
### [Using Visual Studio](#tab/vs-install)
diff --git a/docs/guides/getting_started/labs.md b/docs/guides/getting_started/labs.md
deleted file mode 100644
index e52014312..000000000
--- a/docs/guides/getting_started/labs.md
+++ /dev/null
@@ -1,30 +0,0 @@
----
-uid: Guides.GettingStarted.Installation.Labs
-title: Installing Labs builds
----
-
-# Installing Discord.NET Labs
-
-Discord.NET Labs is the experimental repository that introduces new features & chips away at all bugs until ready for merging into Discord.NET.
-Are you looking to test or play with new features?
-
-> [!IMPORTANT]
-> It is very ill advised to use Discord.NET Labs in a production environment normally,
-> considering it can include bugs that have not been discovered yet, as features are freshly added.
-> However if approached correctly, will work as a pre-release to Discord.NET.
-> Make sure to report any bugs at the Labs [repository] or on [Discord]
-
-[Discord]: https://discord.gg/dnet
-[repository]: https://github.com/Discord-Net-Labs/Discord.Net-Labs
-
-## Installation:
-
-[NuGet] - This only includes releases, on which features are ready to test.
-
-> [!NOTE]
-> Installing NuGet packages is covered fully at [Installing Discord NET](xref:Guides.GettingStarted.Installation)
-
-[MyGet] - Available for current builds and unreleased features.
-
-[NuGet]: https://www.nuget.org/packages/Discord.Net.Labs/
-[MyGet]: https://www.myget.org/feed/Packages/discord-net-labs
diff --git a/docs/guides/getting_started/terminology.md b/docs/guides/getting_started/terminology.md
index 0f24edd6f..facf1c790 100644
--- a/docs/guides/getting_started/terminology.md
+++ b/docs/guides/getting_started/terminology.md
@@ -8,18 +8,22 @@ title: Terminology
## Preface
Most terms for objects remain the same between 0.9 and 1.0 and above.
-The major difference is that the ``Server`` is now called ``Guild``
+The major difference is that the `Server` is now called `Guild`
to stay in line with Discord internally.
## Implementation Specific Entities
Discord.Net is split into a core library and two different
implementations - `Discord.Net.Core`, `Discord.Net.Rest`, and
-`Discord.Net.WebSockets`.
+`Discord.Net.WebSocket`.
-As a bot developer, you will only need to use `Discord.Net.WebSockets`,
+You will typically only need to use `Discord.Net.WebSocket`,
but you should be aware of the differences between them.
+> [!TIP]
+> If you are looking to implement Rest based interactions, or handle calls over REST in any other way,
+> `Discord.Net.Rest` is the resource most applicable to you.
+
`Discord.Net.Core` provides a set of interfaces that models Discord's
API. These interfaces are consistent throughout all implementations of
Discord.Net, and if you are writing an implementation-agnostic library
@@ -33,4 +37,4 @@ implementation are prefixed with `Rest` (e.g., `RestChannel`).
`Discord.Net.WebSocket` provides a set of concrete classes that are
used primarily with Discord's WebSocket API or entities that are kept
in cache. When developing bots, you will be using this implementation.
-All entities are prefixed with `Socket` (e.g., `SocketChannel`).
\ No newline at end of file
+All entities are prefixed with `Socket` (e.g., `SocketChannel`).
diff --git a/docs/guides/int_framework/dependency-injection.md b/docs/guides/int_framework/dependency-injection.md
deleted file mode 100644
index 31d001f4b..000000000
--- a/docs/guides/int_framework/dependency-injection.md
+++ /dev/null
@@ -1,13 +0,0 @@
----
-uid: Guides.IntFw.DI
-title: Dependency Injection
----
-
-# Dependency Injection
-
-Dependency injection in the Interaction Service is mostly based on that of the Text-based command service,
-for which further information is found [here](xref:Guides.TextCommands.DI).
-
-> [!NOTE]
-> The 2 are nearly identical, except for one detail:
-> [Resolving Module Dependencies](xref:Guides.IntFw.Intro#resolving-module-dependencies)
diff --git a/docs/guides/int_framework/intro.md b/docs/guides/int_framework/intro.md
index 54e9086a1..21ea365de 100644
--- a/docs/guides/int_framework/intro.md
+++ b/docs/guides/int_framework/intro.md
@@ -279,8 +279,8 @@ Meaning, the constructor parameters and public settable properties of a module w
For more information on dependency injection, read the [DependencyInjection] guides.
> [!NOTE]
-> On every command execution, module dependencies are resolved using a new service scope which allows you to utilize scoped service instances, just like in Asp.Net.
-> Including the precondition checks, every module method is executed using the same service scope and service scopes are disposed right after the `AfterExecute` method returns.
+> On every command execution, if the 'AutoServiceScopes' option is enabled in the config , module dependencies are resolved using a new service scope which allows you to utilize scoped service instances, just like in Asp.Net.
+> Including the precondition checks, every module method is executed using the same service scope and service scopes are disposed right after the `AfterExecute` method returns. This doesn't apply to methods other than `ExecuteAsync()`.
## Module Groups
@@ -291,6 +291,11 @@ By nesting commands inside a module that is tagged with [GroupAttribute] you can
> Although creating nested module stuctures are allowed,
> you are not permitted to use more than 2 [GroupAttribute]'s in module hierarchy.
+> [!NOTE]
+> To not use the command group's name as a prefix for component or modal interaction's custom id set `ignoreGroupNames` parameter to `true` in classes with [GroupAttribute]
+>
+> However, you have to be careful to prevent overlapping ids of buttons and modals.
+
[!code-csharp[Command Group Example](samples/intro/groupmodule.cs)]
## Executing Commands
@@ -303,8 +308,19 @@ Any of the following socket events can be used to execute commands:
- [AutocompleteExecuted]
- [UserCommandExecuted]
- [MessageCommandExecuted]
+- [ModalExecuted]
+
+These events will trigger for the specific type of interaction they inherit their name from. The [InteractionCreated] event will trigger for all.
+An example of executing a command from an event can be seen here:
+
+[!code-csharp[Command Event Example](samples/intro/event.cs)]
+
+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.
-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.
+> [!WARNING]
+> In the example above, no form of post-execution is presented.
+> Please carefully read the [Post Execution Documentation] for the best approach in resolving the result based on your `RunMode`.
You can also configure the way [InteractionService] executes the commands.
By default, commands are executed using `ConstructorInfo.Invoke()` to create module instances and
@@ -330,10 +346,13 @@ Command registration methods can only be used after the gateway client is ready
Methods like `AddModulesToGuildAsync()`, `AddCommandsToGuildAsync()`, `AddModulesGloballyAsync()` and `AddCommandsGloballyAsync()`
can be used to register cherry picked modules or commands to global/guild scopes.
+> [!NOTE]
+> [DontAutoRegisterAttribute] can be used on module classes to prevent `RegisterCommandsGloballyAsync()` and `RegisterCommandsToGuildAsync()` from registering them to the Discord.
+
> [!NOTE]
> In debug environment, since Global commands can take up to 1 hour to register/update,
> it is adviced to register your commands to a test guild for your changes to take effect immediately.
-> You can use preprocessor directives to create a simple logic for registering commands as seen above
+> You can use preprocessor directives to create a simple logic for registering commands as seen above.
## Interaction Utility
@@ -357,10 +376,52 @@ respond to the Interactions within your command modules you need to perform the
delegate can be used to create HTTP responses from a deserialized json object string.
- Use the interaction endpoints of the module base instead of the interaction object (ie. `RespondAsync()`, `FollowupAsync()`...).
+## Localization
+
+Discord Slash Commands support name/description localization. Localization is available for names and descriptions of Slash Command Groups ([GroupAttribute]), Slash Commands ([SlashCommandAttribute]), Slash Command parameters and Slash Command Parameter Choices. Interaction Service can be initialized with an `ILocalizationManager` instance in its config which is used to create the necessary localization dictionaries on command registration. Interaction Service has two built-in `ILocalizationManager` implementations: `ResxLocalizationManager` and `JsonLocalizationManager`.
+
+### ResXLocalizationManager
+
+`ResxLocalizationManager` uses `.` delimited key names to traverse the resource files and get the localized strings (`group1.group2.command.parameter.name`). A `ResxLocalizationManager` instance must be initialized with a base resource name, a target assembly and a collection of `CultureInfo`s. Every key path must end with either `.name` or `.description`, including parameter choice strings. [Discord.Tools.LocalizationTemplate.Resx](https://www.nuget.org/packages/Discord.Tools.LocalizationTemplate.Resx) dotnet tool can be used to create localization file templates.
+
+### JsonLocalizationManager
+
+`JsonLocaliationManager` uses a nested data structure similar to Discord's Application Commands schema. You can get the Json schema [here](https://gist.github.com/Cenngo/d46a881de24823302f66c3c7e2f7b254). `JsonLocalizationManager` accepts a base path and a base file name and automatically discovers every resource file ( \basePath\fileName.locale.json ). A Json resource file should have a structure similar to:
+
+```json
+{
+ "command_1":{
+ "name": "localized_name",
+ "description": "localized_description",
+ "parameter_1":{
+ "name": "localized_name",
+ "description": "localized_description"
+ }
+ },
+ "group_1":{
+ "name": "localized_name",
+ "description": "localized_description",
+ "command_1":{
+ "name": "localized_name",
+ "description": "localized_description",
+ "parameter_1":{
+ "name": "localized_name",
+ "description": "localized_description"
+ },
+ "parameter_2":{
+ "name": "localized_name",
+ "description": "localized_description"
+ }
+ }
+ }
+}
+```
+
[AutocompleteHandlers]: xref:Guides.IntFw.AutoCompletion
-[DependencyInjection]: xref:Guides.TextCommands.DI
+[DependencyInjection]: xref:Guides.DI.Intro
[GroupAttribute]: xref:Discord.Interactions.GroupAttribute
+[DontAutoRegisterAttribute]: xref:Discord.Interactions.DontAutoRegisterAttribute
[InteractionService]: xref:Discord.Interactions.InteractionService
[InteractionServiceConfig]: xref:Discord.Interactions.InteractionServiceConfig
[InteractionModuleBase]: xref:Discord.Interactions.InteractionModuleBase
@@ -371,6 +432,7 @@ delegate can be used to create HTTP responses from a deserialized json object st
[AutocompleteExecuted]: xref:Discord.WebSocket.BaseSocketClient
[UserCommandExecuted]: xref:Discord.WebSocket.BaseSocketClient
[MessageCommandExecuted]: xref:Discord.WebSocket.BaseSocketClient
+[ModalExecuted]: xref:Discord.WebSocket.BaseSocketClient
[DiscordSocketClient]: xref:Discord.WebSocket.DiscordSocketClient
[DiscordRestClient]: xref:Discord.Rest.DiscordRestClient
[SocketInteractionContext]: xref:Discord.Interactions.SocketInteractionContext
diff --git a/docs/guides/int_framework/samples/intro/event.cs b/docs/guides/int_framework/samples/intro/event.cs
new file mode 100644
index 000000000..0c9f032b9
--- /dev/null
+++ b/docs/guides/int_framework/samples/intro/event.cs
@@ -0,0 +1,14 @@
+// Theres multiple ways to subscribe to the event, depending on your application. Please use the approach fit to your type of client.
+// DiscordSocketClient:
+_socketClient.InteractionCreated += async (x) =>
+{
+ var ctx = new SocketInteractionContext(_socketClient, x);
+ await _interactionService.ExecuteCommandAsync(ctx, _serviceProvider);
+}
+
+// DiscordShardedClient:
+_shardedClient.InteractionCreated += async (x) =>
+{
+ var ctx = new ShardedInteractionContext(_shardedClient, x);
+ await _interactionService.ExecuteCommandAsync(ctx, _serviceProvider);
+}
diff --git a/docs/guides/int_framework/samples/intro/groupmodule.cs b/docs/guides/int_framework/samples/intro/groupmodule.cs
index f0d992aff..a07b2e4d8 100644
--- a/docs/guides/int_framework/samples/intro/groupmodule.cs
+++ b/docs/guides/int_framework/samples/intro/groupmodule.cs
@@ -16,6 +16,11 @@ public class CommandGroupModule : InteractionModuleBase await RespondAsync(input);
+ => await RespondAsync(input, components: new ComponentBuilder().WithButton("Echo", $"echoButton_{input}").Build());
+
+ // Component interaction with ignoreGroupNames set to true
+ [ComponentInteraction("echoButton_*", true)]
+ public async Task EchoButton(string input)
+ => await RespondAsync(input);
}
}
\ No newline at end of file
diff --git a/docs/guides/int_framework/samples/intro/modal.cs b/docs/guides/int_framework/samples/intro/modal.cs
index 65cc81abf..8a6ba9d8a 100644
--- a/docs/guides/int_framework/samples/intro/modal.cs
+++ b/docs/guides/int_framework/samples/intro/modal.cs
@@ -12,7 +12,9 @@ public class FoodModal : IModal
[ModalTextInput("food_name", placeholder: "Pizza", maxLength: 20)]
public string Food { get; set; }
- // Additional paremeters can be specified to further customize the input.
+ // Additional paremeters can be specified to further customize the input.
+ // Parameters can be optional
+ [RequiredInput(false)]
[InputLabel("Why??")]
[ModalTextInput("food_reason", TextInputStyle.Paragraph, "Kuz it's tasty", maxLength: 500)]
public string Reason { get; set; }
@@ -22,10 +24,15 @@ public class FoodModal : IModal
[ModalInteraction("food_menu")]
public async Task ModalResponse(FoodModal modal)
{
+ // Check if "Why??" field is populated
+ string reason = string.IsNullOrWhiteSpace(modal.Reason)
+ ? "."
+ : $" because {modal.Reason}";
+
// Build the message to send.
string message = "hey @everyone, I just learned " +
$"{Context.User.Mention}'s favorite food is " +
- $"{modal.Food} because {modal.Reason}.";
+ $"{modal.Food}{reason}";
// Specify the AllowedMentions so we don't actually ping everyone.
AllowedMentions mentions = new();
diff --git a/docs/guides/text_commands/dependency-injection.md b/docs/guides/text_commands/dependency-injection.md
deleted file mode 100644
index 3253643ef..000000000
--- a/docs/guides/text_commands/dependency-injection.md
+++ /dev/null
@@ -1,51 +0,0 @@
----
-uid: Guides.TextCommands.DI
-title: Dependency Injection
----
-
-# Dependency Injection
-
-The Text Command Service is bundled with a very barebone Dependency
-Injection service for your convenience. It is recommended that you use
-DI when writing your modules.
-
-> [!WARNING]
-> If you were brought here from the Interaction Service guides,
-> make sure to replace all namespaces that imply `Discord.Commands` with `Discord.Interactions`
-
-## Setup
-
-1. Create a @Microsoft.Extensions.DependencyInjection.ServiceCollection.
-2. Add the dependencies to the service collection that you wish
- to use in the modules.
-3. Build the service collection into a service provider.
-4. Pass the service collection into @Discord.Commands.CommandService.AddModulesAsync* / @Discord.Commands.CommandService.AddModuleAsync* , @Discord.Commands.CommandService.ExecuteAsync* .
-
-### Example - Setting up Injection
-
-[!code-csharp[IServiceProvider Setup](samples/dependency-injection/dependency_map_setup.cs)]
-
-## Usage in Modules
-
-In the constructor of your module, any parameters will be filled in by
-the @System.IServiceProvider that you've passed.
-
-Any publicly settable properties will also be filled in the same
-manner.
-
-> [!NOTE]
-> Annotating a property with a [DontInjectAttribute] attribute will
-> prevent the property from being injected.
-
-> [!NOTE]
-> If you accept `CommandService` or `IServiceProvider` as a parameter
-> in your constructor or as an injectable property, these entries will
-> be filled by the `CommandService` that the module is loaded from and
-> the `IServiceProvider` that is passed into it respectively.
-
-### Example - Injection in Modules
-
-[!code-csharp[Injection Modules](samples/dependency-injection/dependency_module.cs)]
-[!code-csharp[Disallow Dependency Injection](samples/dependency-injection/dependency_module_noinject.cs)]
-
-[DontInjectAttribute]: xref:Discord.Commands.DontInjectAttribute
diff --git a/docs/guides/text_commands/intro.md b/docs/guides/text_commands/intro.md
index 6632c127a..1113b0821 100644
--- a/docs/guides/text_commands/intro.md
+++ b/docs/guides/text_commands/intro.md
@@ -187,7 +187,7 @@ service provider.
### Module Constructors
-Modules are constructed using [Dependency Injection](xref:Guides.TextCommands.DI). Any parameters
+Modules are constructed using [Dependency Injection](xref:Guides.DI.Intro). Any parameters
that are placed in the Module's constructor must be injected into an
@System.IServiceProvider first.
diff --git a/docs/guides/text_commands/samples/dependency-injection/dependency_map_setup.cs b/docs/guides/text_commands/samples/dependency-injection/dependency_map_setup.cs
deleted file mode 100644
index 16ca479db..000000000
--- a/docs/guides/text_commands/samples/dependency-injection/dependency_map_setup.cs
+++ /dev/null
@@ -1,65 +0,0 @@
-public class Initialize
-{
- private readonly CommandService _commands;
- private readonly DiscordSocketClient _client;
-
- // Ask if there are existing CommandService and DiscordSocketClient
- // instance. If there are, we retrieve them and add them to the
- // DI container; if not, we create our own.
- public Initialize(CommandService commands = null, DiscordSocketClient client = null)
- {
- _commands = commands ?? new CommandService();
- _client = client ?? new DiscordSocketClient();
- }
-
- public IServiceProvider BuildServiceProvider() => new ServiceCollection()
- .AddSingleton(_client)
- .AddSingleton(_commands)
- // You can pass in an instance of the desired type
- .AddSingleton(new NotificationService())
- // ...or by using the generic method.
- //
- // The benefit of using the generic method is that
- // ASP.NET DI will attempt to inject the required
- // dependencies that are specified under the constructor
- // for us.
- .AddSingleton()
- .AddSingleton()
- .BuildServiceProvider();
-}
-public class CommandHandler
-{
- private readonly DiscordSocketClient _client;
- private readonly CommandService _commands;
- private readonly IServiceProvider _services;
-
- public CommandHandler(IServiceProvider services, CommandService commands, DiscordSocketClient client)
- {
- _commands = commands;
- _services = services;
- _client = client;
- }
-
- public async Task InitializeAsync()
- {
- // Pass the service provider to the second parameter of
- // AddModulesAsync to inject dependencies to all modules
- // that may require them.
- await _commands.AddModulesAsync(
- assembly: Assembly.GetEntryAssembly(),
- services: _services);
- _client.MessageReceived += HandleCommandAsync;
- }
-
- public async Task HandleCommandAsync(SocketMessage msg)
- {
- // ...
- // Pass the service provider to the ExecuteAsync method for
- // precondition checks.
- await _commands.ExecuteAsync(
- context: context,
- argPos: argPos,
- services: _services);
- // ...
- }
-}
diff --git a/docs/guides/text_commands/samples/dependency-injection/dependency_module.cs b/docs/guides/text_commands/samples/dependency-injection/dependency_module.cs
deleted file mode 100644
index 3e42074ca..000000000
--- a/docs/guides/text_commands/samples/dependency-injection/dependency_module.cs
+++ /dev/null
@@ -1,37 +0,0 @@
-// After setting up dependency injection, modules will need to request
-// the dependencies to let the library know to pass
-// them along during execution.
-
-// Dependency can be injected in two ways with Discord.Net.
-// You may inject any required dependencies via...
-// the module constructor
-// -or-
-// public settable properties
-
-// Injection via constructor
-public class DatabaseModule : ModuleBase
-{
- private readonly DatabaseService _database;
- public DatabaseModule(DatabaseService database)
- {
- _database = database;
- }
-
- [Command("read")]
- public async Task ReadFromDbAsync()
- {
- await ReplyAsync(_database.GetData());
- }
-}
-
-// Injection via public settable properties
-public class DatabaseModule : ModuleBase
-{
- public DatabaseService DbService { get; set; }
-
- [Command("read")]
- public async Task ReadFromDbAsync()
- {
- await ReplyAsync(DbService.GetData());
- }
-}
diff --git a/docs/guides/text_commands/samples/dependency-injection/dependency_module_noinject.cs b/docs/guides/text_commands/samples/dependency-injection/dependency_module_noinject.cs
deleted file mode 100644
index 48cd52308..000000000
--- a/docs/guides/text_commands/samples/dependency-injection/dependency_module_noinject.cs
+++ /dev/null
@@ -1,29 +0,0 @@
-// Sometimes injecting dependencies automatically with the provided
-// methods in the prior example may not be desired.
-
-// You may explicitly tell Discord.Net to **not** inject the properties
-// by either...
-// restricting the access modifier
-// -or-
-// applying DontInjectAttribute to the property
-
-// Restricting the access modifier of the property
-public class ImageModule : ModuleBase
-{
- public ImageService ImageService { get; }
- public ImageModule()
- {
- ImageService = new ImageService();
- }
-}
-
-// Applying DontInjectAttribute
-public class ImageModule : ModuleBase
-{
- [DontInject]
- public ImageService ImageService { get; set; }
- public ImageModule()
- {
- ImageService = new ImageService();
- }
-}
diff --git a/docs/guides/toc.yml b/docs/guides/toc.yml
index f122ea6ba..c892eb8c4 100644
--- a/docs/guides/toc.yml
+++ b/docs/guides/toc.yml
@@ -6,9 +6,6 @@
items:
- name: Installation
topicUid: Guides.GettingStarted.Installation
- items:
- - name: Nightly builds
- topicUid: Guides.GettingStarted.Installation.Labs
- name: Your First Bot
topicUid: Guides.GettingStarted.FirstBot
- name: Terminology
@@ -29,6 +26,18 @@
topicUid: Guides.Entities.Casting
- name: Glossary & Flowcharts
topicUid: Guides.Entities.Glossary
+- name: Dependency Injection
+ items:
+ - name: Introduction
+ topicUid: Guides.DI.Intro
+ - name: Injection
+ topicUid: Guides.DI.Injection
+ - name: Command- & Interaction Services
+ topicUid: Guides.DI.Services
+ - name: Service Types
+ topicUid: Guides.DI.Dependencies
+ - name: Scaling your Application
+ topicUid: Guides.DI.Scaling
- name: Working with Text-based Commands
items:
- name: Introduction
@@ -39,8 +48,6 @@
topicUid: Guides.TextCommands.NamedArguments
- name: Preconditions
topicUid: Guides.TextCommands.Preconditions
- - name: Dependency Injection
- topicUid: Guides.TextCommands.DI
- name: Post-execution Handling
topicUid: Guides.TextCommands.PostExecution
- name: Working with the Interaction Framework
@@ -53,8 +60,6 @@
topicUid: Guides.IntFw.TypeConverters
- name: Preconditions
topicUid: Guides.IntFw.Preconditions
- - name: Dependency Injection
- topicUid: Guides.IntFw.DI
- name: Post-execution Handling
topicUid: Guides.IntFw.PostExecution
- name: Permissions
diff --git a/docs/guides/v2_v3_guide/v2_to_v3_guide.md b/docs/guides/v2_v3_guide/v2_to_v3_guide.md
index 6b4fa5282..a837f44d2 100644
--- a/docs/guides/v2_v3_guide/v2_to_v3_guide.md
+++ b/docs/guides/v2_v3_guide/v2_to_v3_guide.md
@@ -38,7 +38,7 @@ _client = new DiscordSocketClient(config);
This includes intents that receive messages such as: `GatewayIntents.GuildMessages, GatewayIntents.DirectMessages`
- GuildMembers: An intent disabled by default, as you need to enable it in the [developer portal].
- GuildPresences: Also disabled by default, this intent together with `GuildMembers` are the only intents not included in `AllUnprivileged`.
-- All: All intents, it is ill adviced to use this without care, as it _can_ cause a memory leak from presence.
+- All: All intents, it is ill advised to use this without care, as it _can_ cause a memory leak from presence.
The library will give responsive warnings if you specify unnecessary intents.
> [!NOTE]
diff --git a/docs/guides/voice/sending-voice.md b/docs/guides/voice/sending-voice.md
index 555adbca2..36184e3a3 100644
--- a/docs/guides/voice/sending-voice.md
+++ b/docs/guides/voice/sending-voice.md
@@ -17,11 +17,9 @@ bot. (When developing on .NET Framework, this would be `bin/debug`,
when developing on .NET Core, this is where you execute `dotnet run`
from; typically the same directory as your csproj).
-For Windows Users, precompiled binaries are available for your
-convienence [here](https://github.com/discord-net/Discord.Net/tree/dev/voice-natives).
+**For Windows users, precompiled binaries are available for your convienence [here](https://github.com/discord-net/Discord.Net/tree/dev/voice-natives).**
-For Linux Users, you will need to compile [Sodium] and [Opus] from
-source, or install them from your package manager.
+**For Linux users, you will need to compile [Sodium] and [Opus] from source, or install them from your package manager.**
[Sodium]: https://download.libsodium.org/libsodium/releases/
[Opus]: http://downloads.xiph.org/releases/opus/
diff --git a/experiment/Discord.Net.BuildOverrides/BuildOverrides.cs b/experiment/Discord.Net.BuildOverrides/BuildOverrides.cs
index 54b56cc60..54bc362ec 100644
--- a/experiment/Discord.Net.BuildOverrides/BuildOverrides.cs
+++ b/experiment/Discord.Net.BuildOverrides/BuildOverrides.cs
@@ -251,7 +251,7 @@ namespace Discord
private static Assembly _overrideDomain_Resolving(AssemblyLoadContext arg1, AssemblyName arg2)
{
// resolve the override id
- var v = _loadedOverrides.FirstOrDefault(x => x.Value.Any(x => x.Assembly.FullName == arg1.Assemblies.FirstOrDefault().FullName));
+ var v = _loadedOverrides.FirstOrDefault(x => x.Value.Any(x => x.Assembly.FullName == arg1.Assemblies.First().FullName));
return GetDependencyAsync(v.Key.Id, $"{arg2}").GetAwaiter().GetResult();
}
diff --git a/samples/ShardedClient/Services/InteractionHandlingService.cs b/samples/ShardedClient/Services/InteractionHandlingService.cs
index 3c41d7f33..fc2af8150 100644
--- a/samples/ShardedClient/Services/InteractionHandlingService.cs
+++ b/samples/ShardedClient/Services/InteractionHandlingService.cs
@@ -22,6 +22,7 @@ namespace ShardedClient.Services
_service.Log += LogAsync;
_client.InteractionCreated += OnInteractionAsync;
+ _client.ShardReady += ReadyAsync;
// For examples on how to handle post execution,
// see the InteractionFramework samples.
}
@@ -30,11 +31,6 @@ namespace ShardedClient.Services
public async Task InitializeAsync()
{
await _service.AddModulesAsync(typeof(InteractionHandlingService).Assembly, _provider);
-#if DEBUG
- await _service.RegisterCommandsToGuildAsync(1 /* implement */);
-#else
- await _service.RegisterCommandsGloballyAsync();
-#endif
}
private async Task OnInteractionAsync(SocketInteraction interaction)
@@ -53,5 +49,14 @@ namespace ShardedClient.Services
return Task.CompletedTask;
}
+
+ private async Task ReadyAsync(DiscordSocketClient _)
+ {
+#if DEBUG
+ await _service.RegisterCommandsToGuildAsync(1 /* implement */);
+#else
+ await _service.RegisterCommandsGloballyAsync();
+#endif
+ }
}
}
diff --git a/src/Discord.Net.Commands/Builders/ModuleClassBuilder.cs b/src/Discord.Net.Commands/Builders/ModuleClassBuilder.cs
index 22c58f5c7..f98c81abd 100644
--- a/src/Discord.Net.Commands/Builders/ModuleClassBuilder.cs
+++ b/src/Discord.Net.Commands/Builders/ModuleClassBuilder.cs
@@ -206,6 +206,7 @@ namespace Discord.Commands
try
{
+ await instance.BeforeExecuteAsync(cmd).ConfigureAwait(false);
instance.BeforeExecute(cmd);
var task = method.Invoke(instance, args) as Task ?? Task.Delay(0);
@@ -221,6 +222,7 @@ namespace Discord.Commands
}
finally
{
+ await instance.AfterExecuteAsync(cmd).ConfigureAwait(false);
instance.AfterExecute(cmd);
(instance as IDisposable)?.Dispose();
}
diff --git a/src/Discord.Net.Commands/IModuleBase.cs b/src/Discord.Net.Commands/IModuleBase.cs
index 8b021f4de..7a953b47b 100644
--- a/src/Discord.Net.Commands/IModuleBase.cs
+++ b/src/Discord.Net.Commands/IModuleBase.cs
@@ -1,4 +1,5 @@
using Discord.Commands.Builders;
+using System.Threading.Tasks;
namespace Discord.Commands
{
@@ -13,12 +14,24 @@ namespace Discord.Commands
/// The context to set.
void SetContext(ICommandContext context);
+ ///
+ /// Executed asynchronously before a command is run in this module base.
+ ///
+ /// The command thats about to run.
+ Task BeforeExecuteAsync(CommandInfo command);
+
///
/// Executed before a command is run in this module base.
///
/// The command thats about to run.
void BeforeExecute(CommandInfo command);
+ ///
+ /// Executed asynchronously after a command is run in this module base.
+ ///
+ /// The command thats about to run.
+ Task AfterExecuteAsync(CommandInfo command);
+
///
/// Executed after a command is ran in this module base.
///
diff --git a/src/Discord.Net.Commands/ModuleBase.cs b/src/Discord.Net.Commands/ModuleBase.cs
index 5008cca35..b2d6ba119 100644
--- a/src/Discord.Net.Commands/ModuleBase.cs
+++ b/src/Discord.Net.Commands/ModuleBase.cs
@@ -46,6 +46,11 @@ namespace Discord.Commands
return await Context.Channel.SendMessageAsync(message, isTTS, embed, options, allowedMentions, messageReference, components, stickers, embeds).ConfigureAwait(false);
}
///
+ /// The method to execute asynchronously before executing the command.
+ ///
+ /// The of the command to be executed.
+ protected virtual Task BeforeExecuteAsync(CommandInfo command) => Task.CompletedTask;
+ ///
/// The method to execute before executing the command.
///
/// The of the command to be executed.
@@ -53,6 +58,11 @@ namespace Discord.Commands
{
}
///
+ /// The method to execute asynchronously after executing the command.
+ ///
+ /// The of the command to be executed.
+ protected virtual Task AfterExecuteAsync(CommandInfo command) => Task.CompletedTask;
+ ///
/// The method to execute after executing the command.
///
/// The of the command to be executed.
@@ -76,7 +86,9 @@ namespace Discord.Commands
var newValue = context as T;
Context = newValue ?? throw new InvalidOperationException($"Invalid context type. Expected {typeof(T).Name}, got {context.GetType().Name}.");
}
+ Task IModuleBase.BeforeExecuteAsync(CommandInfo command) => BeforeExecuteAsync(command);
void IModuleBase.BeforeExecute(CommandInfo command) => BeforeExecute(command);
+ Task IModuleBase.AfterExecuteAsync(CommandInfo command) => AfterExecuteAsync(command);
void IModuleBase.AfterExecute(CommandInfo command) => AfterExecute(command);
void IModuleBase.OnModuleBuilding(CommandService commandService, ModuleBuilder builder) => OnModuleBuilding(commandService, builder);
#endregion
diff --git a/src/Discord.Net.Core/Discord.Net.Core.csproj b/src/Discord.Net.Core/Discord.Net.Core.csproj
index 41d83bbc8..005280c4d 100644
--- a/src/Discord.Net.Core/Discord.Net.Core.csproj
+++ b/src/Discord.Net.Core/Discord.Net.Core.csproj
@@ -16,7 +16,6 @@
all
-
@@ -27,4 +26,7 @@
+
+
+
\ No newline at end of file
diff --git a/src/Discord.Net.Core/DiscordConfig.cs b/src/Discord.Net.Core/DiscordConfig.cs
index 2db802f1e..ebca0120c 100644
--- a/src/Discord.Net.Core/DiscordConfig.cs
+++ b/src/Discord.Net.Core/DiscordConfig.cs
@@ -18,7 +18,7 @@ namespace Discord
/// Discord API documentation
/// .
///
- public const int APIVersion = 9;
+ public const int APIVersion = 10;
///
/// Returns the Voice API version Discord.Net uses.
///
diff --git a/src/Discord.Net.Core/DiscordErrorCode.cs b/src/Discord.Net.Core/DiscordErrorCode.cs
index b444614e4..262252eab 100644
--- a/src/Discord.Net.Core/DiscordErrorCode.cs
+++ b/src/Discord.Net.Core/DiscordErrorCode.cs
@@ -66,6 +66,7 @@ namespace Discord
ActionSlowmode = 20016,
OnlyOwnerAction = 20018,
AnnouncementEditRatelimit = 20022,
+ UnderMinimumAge = 20024,
ChannelWriteRatelimit = 20028,
WriteRatelimitReached = 20029,
WordsNotAllowed = 20031,
@@ -88,7 +89,9 @@ namespace Discord
MaximumServerMembersReached = 30019,
MaximumServerCategoriesReached = 30030,
GuildTemplateAlreadyExists = 30031,
+ MaximumNumberOfApplicationCommandsReached = 30032,
MaximumThreadMembersReached = 30033,
+ MaxNumberOfDailyApplicationCommandCreatesHasBeenReached = 30034,
MaximumBansForNonGuildMembersReached = 30035,
MaximumBanFetchesReached = 30037,
MaximumUncompleteGuildScheduledEvents = 30038,
@@ -98,6 +101,7 @@ namespace Discord
#endregion
#region General Request Errors (40XXX)
+ BitrateIsTooHighForChannelOfThisType = 30052,
MaximumNumberOfEditsReached = 30046,
MaximumNumberOfPinnedThreadsInAForumChannelReached = 30047,
MaximumNumberOfTagsInAForumChannelReached = 30048,
@@ -108,12 +112,17 @@ namespace Discord
RequestEntityTooLarge = 40005,
FeatureDisabled = 40006,
UserBanned = 40007,
+ ConnectionHasBeenRevoked = 40012,
TargetUserNotInVoice = 40032,
MessageAlreadyCrossposted = 40033,
ApplicationNameAlreadyExists = 40041,
#endregion
#region Action Preconditions/Checks (50XXX)
+ ApplicationInteractionFailedToSend = 40043,
+ CannotSendAMessageInAForumChannel = 40058,
+ ThereAreNoTagsAvailableThatCanBeSetByNonModerators = 40066,
+ ATagIsRequiredToCreateAForumPostInThisChannel = 40067,
InteractionHasAlreadyBeenAcknowledged = 40060,
TagNamesMustBeUnique = 40061,
MissingPermissions = 50001,
@@ -132,6 +141,7 @@ namespace Discord
InvalidAuthenticationToken = 50014,
NoteTooLong = 50015,
ProvidedMessageDeleteCountOutOfBounds = 50016,
+ InvalidMFALevel = 50017,
InvalidPinChannel = 50019,
InvalidInvite = 50020,
CannotExecuteOnSystemMessage = 50021,
@@ -165,6 +175,9 @@ namespace Discord
#endregion
#region 2FA (60XXX)
+ OwnershipCannotBeTransferredToABotUser = 50132,
+ AssetResizeBelowTheMaximumSize= 50138,
+ UploadedFileNotFound = 50146,
MissingPermissionToSendThisSticker = 50600,
Requires2FA = 60003,
#endregion
@@ -178,6 +191,7 @@ namespace Discord
#endregion
#region API Status (130XXX)
+ ApplicationNotYetAvailable = 110001,
APIOverloaded = 130000,
#endregion
@@ -207,5 +221,15 @@ namespace Discord
CannotUpdateFinishedEvent = 180000,
FailedStageCreation = 180002,
#endregion
+
+ #region Forum & Automod
+ MessageWasBlockedByAutomaticModeration = 200000,
+ TitleWasBlockedByAutomaticModeration = 200001,
+ WebhooksPostedToForumChannelsMustHaveAThreadNameOrThreadId = 220001,
+ WebhooksPostedToForumChannelsCannotHaveBothAThreadNameAndThreadId = 220002,
+ WebhooksCanOnlyCreateThreadsInForumChannels = 220003,
+ WebhookServicesCannotBeUsedInForumChannels = 220004,
+ MessageBlockedByHarmfulLinksFilter = 240000,
+ #endregion
}
}
diff --git a/src/Discord.Net.Core/Entities/Channels/IVoiceChannel.cs b/src/Discord.Net.Core/Entities/Channels/IVoiceChannel.cs
index d921a2474..d75a4e29c 100644
--- a/src/Discord.Net.Core/Entities/Channels/IVoiceChannel.cs
+++ b/src/Discord.Net.Core/Entities/Channels/IVoiceChannel.cs
@@ -1,4 +1,5 @@
using System;
+using System.Collections.Generic;
using System.Threading.Tasks;
namespace Discord
@@ -25,6 +26,44 @@ namespace Discord
///
int? UserLimit { get; }
+ ///
+ /// Bulk-deletes multiple messages.
+ ///
+ ///
+ /// The following example gets 250 messages from the channel and deletes them.
+ ///
+ /// var messages = await voiceChannel.GetMessagesAsync(250).FlattenAsync();
+ /// await voiceChannel.DeleteMessagesAsync(messages);
+ ///
+ ///
+ ///
+ /// This method attempts to remove the messages specified in bulk.
+ ///
+ /// Due to the limitation set by Discord, this method can only remove messages that are posted within 14 days!
+ ///
+ ///
+ /// The messages to be bulk-deleted.
+ /// The options to be used when sending the request.
+ ///
+ /// A task that represents the asynchronous bulk-removal operation.
+ ///
+ Task DeleteMessagesAsync(IEnumerable messages, RequestOptions options = null);
+ ///
+ /// Bulk-deletes multiple messages.
+ ///
+ ///
+ /// This method attempts to remove the messages specified in bulk.
+ ///
+ /// Due to the limitation set by Discord, this method can only remove messages that are posted within 14 days!
+ ///
+ ///
+ /// The snowflake identifier of the messages to be bulk-deleted.
+ /// The options to be used when sending the request.
+ ///
+ /// A task that represents the asynchronous bulk-removal operation.
+ ///
+ Task DeleteMessagesAsync(IEnumerable messageIds, RequestOptions options = null);
+
///
/// Modifies this voice channel.
///
diff --git a/src/Discord.Net.Core/Entities/Guilds/GuildFeature.cs b/src/Discord.Net.Core/Entities/Guilds/GuildFeature.cs
index cb57b2726..52a70a6f5 100644
--- a/src/Discord.Net.Core/Entities/Guilds/GuildFeature.cs
+++ b/src/Discord.Net.Core/Entities/Guilds/GuildFeature.cs
@@ -12,174 +12,174 @@ namespace Discord
///
/// The guild has no features.
///
- None = 0,
+ None = 0L,
///
/// The guild has access to animated banners.
///
- AnimatedBanner = 1 << 0,
+ AnimatedBanner = 1L << 0,
///
/// The guild has access to set an animated guild icon.
///
- AnimatedIcon = 1 << 1,
+ AnimatedIcon = 1L << 1,
///
/// The guild has access to set a guild banner image.
///
- Banner = 1 << 2,
+ Banner = 1L << 2,
///
/// The guild has access to channel banners.
///
- ChannelBanner = 1 << 3,
+ ChannelBanner = 1L << 3,
///
/// The guild has access to use commerce features (i.e. create store channels).
///
- Commerce = 1 << 4,
+ Commerce = 1L << 4,
///
/// The guild can enable welcome screen, Membership Screening, stage channels and discovery, and receives community updates.
///
- Community = 1 << 5,
+ Community = 1L << 5,
///
/// The guild is able to be discovered in the directory.
///
- Discoverable = 1 << 6,
+ Discoverable = 1L << 6,
///
/// The guild has discoverable disabled.
///
- DiscoverableDisabled = 1 << 7,
+ DiscoverableDisabled = 1L << 7,
///
/// The guild has enabled discoverable before.
///
- EnabledDiscoverableBefore = 1 << 8,
+ EnabledDiscoverableBefore = 1L << 8,
///
/// The guild is able to be featured in the directory.
///
- Featureable = 1 << 9,
+ Featureable = 1L << 9,
///
/// The guild has a force relay.
///
- ForceRelay = 1 << 10,
+ ForceRelay = 1L << 10,
///
/// The guild has a directory entry.
///
- HasDirectoryEntry = 1 << 11,
+ HasDirectoryEntry = 1L << 11,
///
/// The guild is a hub.
///
- Hub = 1 << 12,
+ Hub = 1L << 12,
///
/// You shouldn't be here...
///
- InternalEmployeeOnly = 1 << 13,
+ InternalEmployeeOnly = 1L << 13,
///
/// The guild has access to set an invite splash background.
///
- InviteSplash = 1 << 14,
+ InviteSplash = 1L << 14,
///
/// The guild is linked to a hub.
///
- LinkedToHub = 1 << 15,
+ LinkedToHub = 1L << 15,
///
/// The guild has member profiles.
///
- MemberProfiles = 1 << 16,
+ MemberProfiles = 1L << 16,
///
/// The guild has enabled Membership Screening.
///
- MemberVerificationGateEnabled = 1 << 17,
+ MemberVerificationGateEnabled = 1L << 17,
///
/// The guild has enabled monetization.
///
- MonetizationEnabled = 1 << 18,
+ MonetizationEnabled = 1L << 18,
///
/// The guild has more emojis.
///
- MoreEmoji = 1 << 19,
+ MoreEmoji = 1L << 19,
///
/// The guild has increased custom sticker slots.
///
- MoreStickers = 1 << 20,
+ MoreStickers = 1L << 20,
///
/// The guild has access to create news channels.
///
- News = 1 << 21,
+ News = 1L << 21,
///
/// The guild has new thread permissions.
///
- NewThreadPermissions = 1 << 22,
+ NewThreadPermissions = 1L << 22,
///
/// The guild is partnered.
///
- Partnered = 1 << 23,
+ Partnered = 1L << 23,
///
/// The guild has a premium tier three override; guilds made by Discord usually have this.
///
- PremiumTier3Override = 1 << 24,
+ PremiumTier3Override = 1L << 24,
///
/// The guild can be previewed before joining via Membership Screening or the directory.
///
- PreviewEnabled = 1 << 25,
+ PreviewEnabled = 1L << 25,
///
/// The guild has access to create private threads.
///
- PrivateThreads = 1 << 26,
+ PrivateThreads = 1L << 26,
///
/// The guild has relay enabled.
///
- RelayEnabled = 1 << 27,
+ RelayEnabled = 1L << 27,
///
/// The guild is able to set role icons.
///
- RoleIcons = 1 << 28,
+ RoleIcons = 1L << 28,
///
/// The guild has role subscriptions available for purchase.
///
- RoleSubscriptionsAvailableForPurchase = 1 << 29,
+ RoleSubscriptionsAvailableForPurchase = 1L << 29,
///
/// The guild has role subscriptions enabled.
///
- RoleSubscriptionsEnabled = 1 << 30,
+ RoleSubscriptionsEnabled = 1L << 30,
///
/// The guild has access to the seven day archive time for threads.
///
- SevenDayThreadArchive = 1 << 31,
+ SevenDayThreadArchive = 1L << 31,
///
/// The guild has text in voice enabled.
///
- TextInVoiceEnabled = 1 << 32,
+ TextInVoiceEnabled = 1L << 32,
///
/// The guild has threads enabled.
///
- ThreadsEnabled = 1 << 33,
+ ThreadsEnabled = 1L << 33,
///
/// The guild has testing threads enabled.
///
- ThreadsEnabledTesting = 1 << 34,
+ ThreadsEnabledTesting = 1L << 34,
///
/// The guild has the default thread auto archive.
///
- ThreadsDefaultAutoArchiveDuration = 1 << 35,
+ ThreadsDefaultAutoArchiveDuration = 1L << 35,
///
/// The guild has access to the three day archive time for threads.
///
- ThreeDayThreadArchive = 1 << 36,
+ ThreeDayThreadArchive = 1L << 36,
///
/// The guild has enabled ticketed events.
///
- TicketedEventsEnabled = 1 << 37,
+ TicketedEventsEnabled = 1L << 37,
///
/// The guild has access to set a vanity URL.
///
- VanityUrl = 1 << 38,
+ VanityUrl = 1L << 38,
///
/// The guild is verified.
///
- Verified = 1 << 39,
+ Verified = 1L << 39,
///
/// The guild has access to set 384kbps bitrate in voice (previously VIP voice servers).
///
- VIPRegions = 1 << 40,
+ VIPRegions = 1L << 40,
///
/// The guild has enabled the welcome screen.
///
- WelcomeScreenEnabled = 1 << 41,
+ WelcomeScreenEnabled = 1L << 41,
}
}
diff --git a/src/Discord.Net.Core/Entities/Guilds/IGuild.cs b/src/Discord.Net.Core/Entities/Guilds/IGuild.cs
index 775ff9e65..34a08f1e7 100644
--- a/src/Discord.Net.Core/Entities/Guilds/IGuild.cs
+++ b/src/Discord.Net.Core/Entities/Guilds/IGuild.cs
@@ -1194,12 +1194,17 @@ namespace Discord
///
/// Gets this guilds application commands.
///
+ ///
+ /// Whether to include full localization dictionaries in the returned objects,
+ /// instead of the localized name and description fields.
+ ///
+ /// The target locale of the localized name and description fields. Sets the X-Discord-Locale header, which takes precedence over Accept-Language.
/// The options to be used when sending the request.
///
/// A task that represents the asynchronous get operation. The task result contains a read-only collection
/// of application commands found within the guild.
///
- Task> GetApplicationCommandsAsync(RequestOptions options = null);
+ Task> GetApplicationCommandsAsync(bool withLocalizations = false, string locale = null, RequestOptions options = null);
///
/// Gets an application command within this guild with the specified id.
diff --git a/src/Discord.Net.Core/Entities/Interactions/ApplicationCommandOption.cs b/src/Discord.Net.Core/Entities/Interactions/ApplicationCommandOption.cs
index 5857bac81..bceefda32 100644
--- a/src/Discord.Net.Core/Entities/Interactions/ApplicationCommandOption.cs
+++ b/src/Discord.Net.Core/Entities/Interactions/ApplicationCommandOption.cs
@@ -1,4 +1,5 @@
using System;
+using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
@@ -12,6 +13,8 @@ namespace Discord
{
private string _name;
private string _description;
+ private IDictionary _nameLocalizations = new Dictionary();
+ private IDictionary _descriptionLocalizations = new Dictionary();
///
/// Gets or sets the name of this option.
@@ -21,18 +24,7 @@ namespace Discord
get => _name;
set
{
- if (value == null)
- throw new ArgumentNullException(nameof(value), $"{nameof(Name)} cannot be null.");
-
- if (value.Length > 32)
- throw new ArgumentOutOfRangeException(nameof(value), "Name length must be less than or equal to 32.");
-
- if (!Regex.IsMatch(value, @"^[\w-]{1,32}$"))
- throw new FormatException($"{nameof(value)} must match the regex ^[\\w-]{{1,32}}$");
-
- if (value.Any(x => char.IsUpper(x)))
- throw new FormatException("Name cannot contain any uppercase characters.");
-
+ EnsureValidOptionName(value);
_name = value;
}
}
@@ -43,12 +35,11 @@ namespace Discord
public string Description
{
get => _description;
- set => _description = value?.Length switch
+ set
{
- > 100 => throw new ArgumentOutOfRangeException(nameof(value), "Description length must be less than or equal to 100."),
- 0 => throw new ArgumentOutOfRangeException(nameof(value), "Description length must be at least 1."),
- _ => value
- };
+ EnsureValidOptionDescription(value);
+ _description = value;
+ }
}
///
@@ -81,6 +72,16 @@ namespace Discord
///
public double? MaxValue { get; set; }
+ ///
+ /// Gets or sets the minimum allowed length for a string input.
+ ///
+ public int? MinLength { get; set; }
+
+ ///
+ /// Gets or sets the maximum allowed length for a string input.
+ ///
+ public int? MaxLength { get; set; }
+
///
/// Gets or sets the choices for string and int types for the user to pick from.
///
@@ -95,5 +96,72 @@ namespace Discord
/// Gets or sets the allowed channel types for this option.
///
public List ChannelTypes { get; set; }
+
+ ///
+ /// Gets or sets the localization dictionary for the name field of this option.
+ ///
+ /// Thrown when any of the dictionary keys is an invalid locale.
+ public IDictionary NameLocalizations
+ {
+ get => _nameLocalizations;
+ set
+ {
+ foreach (var (locale, name) in value)
+ {
+ if(!Regex.IsMatch(locale, @"^\w{2}(?:-\w{2})?$"))
+ throw new ArgumentException($"Invalid locale: {locale}", nameof(locale));
+
+ EnsureValidOptionName(name);
+ }
+ _nameLocalizations = value;
+ }
+ }
+
+ ///
+ /// Gets or sets the localization dictionary for the description field of this option.
+ ///
+ /// Thrown when any of the dictionary keys is an invalid locale.
+ public IDictionary DescriptionLocalizations
+ {
+ get => _descriptionLocalizations;
+ set
+ {
+ foreach (var (locale, description) in value)
+ {
+ if(!Regex.IsMatch(locale, @"^\w{2}(?:-\w{2})?$"))
+ throw new ArgumentException($"Invalid locale: {locale}", nameof(locale));
+
+ EnsureValidOptionDescription(description);
+ }
+ _descriptionLocalizations = value;
+ }
+ }
+
+ private static void EnsureValidOptionName(string name)
+ {
+ if (name == null)
+ throw new ArgumentNullException(nameof(name), $"{nameof(Name)} cannot be null.");
+
+ if (name.Length > 32)
+ throw new ArgumentOutOfRangeException(nameof(name), "Name length must be less than or equal to 32.");
+
+ if (!Regex.IsMatch(name, @"^[\w-]{1,32}$"))
+ throw new FormatException($"{nameof(name)} must match the regex ^[\\w-]{{1,32}}$");
+
+ if (name.Any(x => char.IsUpper(x)))
+ throw new FormatException("Name cannot contain any uppercase characters.");
+ }
+
+ private static void EnsureValidOptionDescription(string description)
+ {
+ switch (description.Length)
+ {
+ case > 100:
+ throw new ArgumentOutOfRangeException(nameof(description),
+ "Description length must be less than or equal to 100.");
+ case 0:
+ throw new ArgumentOutOfRangeException(nameof(description), "Description length must at least 1.");
+ }
+ }
}
}
diff --git a/src/Discord.Net.Core/Entities/Interactions/ApplicationCommandOptionChoice.cs b/src/Discord.Net.Core/Entities/Interactions/ApplicationCommandOptionChoice.cs
index 6a908b075..8f1ecc6d2 100644
--- a/src/Discord.Net.Core/Entities/Interactions/ApplicationCommandOptionChoice.cs
+++ b/src/Discord.Net.Core/Entities/Interactions/ApplicationCommandOptionChoice.cs
@@ -1,4 +1,8 @@
using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text.RegularExpressions;
namespace Discord
{
@@ -9,6 +13,7 @@ namespace Discord
{
private string _name;
private object _value;
+ private IDictionary _nameLocalizations = new Dictionary();
///
/// Gets or sets the name of this choice.
@@ -40,5 +45,33 @@ namespace Discord
_value = value;
}
}
+
+ ///
+ /// Gets or sets the localization dictionary for the name field of this choice.
+ ///
+ /// Thrown when any of the dictionary keys is an invalid locale.
+ public IDictionary NameLocalizations
+ {
+ get => _nameLocalizations;
+ set
+ {
+ foreach (var (locale, name) in value)
+ {
+ if (!Regex.IsMatch(locale, @"^\w{2}(?:-\w{2})?$"))
+ throw new ArgumentException("Key values of the dictionary must be valid language codes.");
+
+ switch (name.Length)
+ {
+ case > 100:
+ throw new ArgumentOutOfRangeException(nameof(value),
+ "Name length must be less than or equal to 100.");
+ case 0:
+ throw new ArgumentOutOfRangeException(nameof(value), "Name length must at least 1.");
+ }
+ }
+
+ _nameLocalizations = value;
+ }
+ }
}
}
diff --git a/src/Discord.Net.Core/Entities/Interactions/ApplicationCommandProperties.cs b/src/Discord.Net.Core/Entities/Interactions/ApplicationCommandProperties.cs
index 9b3ac8453..7ca16a27d 100644
--- a/src/Discord.Net.Core/Entities/Interactions/ApplicationCommandProperties.cs
+++ b/src/Discord.Net.Core/Entities/Interactions/ApplicationCommandProperties.cs
@@ -1,3 +1,10 @@
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Collections.Immutable;
+using System.Linq;
+using System.Text.RegularExpressions;
+
namespace Discord
{
///
@@ -5,6 +12,9 @@ namespace Discord
///
public abstract class ApplicationCommandProperties
{
+ private IReadOnlyDictionary _nameLocalizations;
+ private IReadOnlyDictionary _descriptionLocalizations;
+
internal abstract ApplicationCommandType Type { get; }
///
@@ -17,6 +27,48 @@ namespace Discord
///
public Optional IsDefaultPermission { get; set; }
+ ///
+ /// Gets or sets the localization dictionary for the name field of this command.
+ ///
+ public IReadOnlyDictionary NameLocalizations
+ {
+ get => _nameLocalizations;
+ set
+ {
+ foreach (var (locale, name) in value)
+ {
+ if(!Regex.IsMatch(locale, @"^\w{2}(?:-\w{2})?$"))
+ throw new ArgumentException($"Invalid locale: {locale}", nameof(locale));
+
+ Preconditions.AtLeast(name.Length, 1, nameof(name));
+ Preconditions.AtMost(name.Length, SlashCommandBuilder.MaxNameLength, nameof(name));
+ if (!Regex.IsMatch(name, @"^[\w-]{1,32}$"))
+ throw new ArgumentException("Option name cannot contain any special characters or whitespaces!", nameof(name));
+ }
+ _nameLocalizations = value;
+ }
+ }
+
+ ///
+ /// Gets or sets the localization dictionary for the description field of this command.
+ ///
+ public IReadOnlyDictionary DescriptionLocalizations
+ {
+ get => _descriptionLocalizations;
+ set
+ {
+ foreach (var (locale, description) in value)
+ {
+ if(!Regex.IsMatch(locale, @"^\w{2}(?:-\w{2})?$"))
+ throw new ArgumentException($"Invalid locale: {locale}", nameof(locale));
+
+ Preconditions.AtLeast(description.Length, 1, nameof(description));
+ Preconditions.AtMost(description.Length, SlashCommandBuilder.MaxDescriptionLength, nameof(description));
+ }
+ _descriptionLocalizations = value;
+ }
+ }
+
///
/// Gets or sets whether or not this command can be used in DMs.
///
diff --git a/src/Discord.Net.Core/Entities/Interactions/ContextMenus/MessageCommandBuilder.cs b/src/Discord.Net.Core/Entities/Interactions/ContextMenus/MessageCommandBuilder.cs
index 59040dd4e..ed49c685d 100644
--- a/src/Discord.Net.Core/Entities/Interactions/ContextMenus/MessageCommandBuilder.cs
+++ b/src/Discord.Net.Core/Entities/Interactions/ContextMenus/MessageCommandBuilder.cs
@@ -1,3 +1,8 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text.RegularExpressions;
+
namespace Discord
{
///
@@ -31,6 +36,11 @@ namespace Discord
///
public bool IsDefaultPermission { get; set; } = true;
+ ///
+ /// Gets the localization dictionary for the name field of this command.
+ ///
+ public IReadOnlyDictionary NameLocalizations => _nameLocalizations;
+
///
/// Gets or sets whether or not this command can be used in DMs.
///
@@ -42,6 +52,7 @@ namespace Discord
public GuildPermission? DefaultMemberPermissions { get; set; }
private string _name;
+ private Dictionary _nameLocalizations;
///
/// Build the current builder into a class.
@@ -86,6 +97,30 @@ namespace Discord
return this;
}
+ ///
+ /// Sets the collection.
+ ///
+ /// The localization dictionary to use for the name field of this command.
+ ///
+ /// Thrown if is null.
+ /// Thrown if any dictionary key is an invalid locale string.
+ public MessageCommandBuilder WithNameLocalizations(IDictionary nameLocalizations)
+ {
+ if (nameLocalizations is null)
+ throw new ArgumentNullException(nameof(nameLocalizations));
+
+ foreach (var (locale, name) in nameLocalizations)
+ {
+ if(!Regex.IsMatch(locale, @"^\w{2}(?:-\w{2})?$"))
+ throw new ArgumentException($"Invalid locale: {locale}", nameof(locale));
+
+ EnsureValidCommandName(name);
+ }
+
+ _nameLocalizations = new Dictionary(nameLocalizations);
+ return this;
+ }
+
///
/// Sets whether or not this command can be used in dms
///
@@ -97,6 +132,41 @@ namespace Discord
return this;
}
+ ///
+ /// Adds a new entry to the collection.
+ ///
+ /// Locale of the entry.
+ /// Localized string for the name field.
+ /// The current builder.
+ /// Thrown if is an invalid locale string.
+ public MessageCommandBuilder AddNameLocalization(string locale, string name)
+ {
+ if(!Regex.IsMatch(locale, @"^\w{2}(?:-\w{2})?$"))
+ throw new ArgumentException($"Invalid locale: {locale}", nameof(locale));
+
+ EnsureValidCommandName(name);
+
+ _nameLocalizations ??= new();
+ _nameLocalizations.Add(locale, name);
+
+ return this;
+ }
+
+ private static void EnsureValidCommandName(string name)
+ {
+ Preconditions.NotNullOrEmpty(name, nameof(name));
+ Preconditions.AtLeast(name.Length, 1, nameof(name));
+ Preconditions.AtMost(name.Length, MaxNameLength, nameof(name));
+
+ // Discord updated the docs, this regex prevents special characters like @!$%(... etc,
+ // https://discord.com/developers/docs/interactions/slash-commands#applicationcommand
+ if (!Regex.IsMatch(name, @"^[\w-]{1,32}$"))
+ throw new ArgumentException("Command name cannot contain any special characters or whitespaces!", nameof(name));
+
+ if (name.Any(x => char.IsUpper(x)))
+ throw new FormatException("Name cannot contain any uppercase characters.");
+ }
+
///
/// Sets the default member permissions required to use this application command.
///
diff --git a/src/Discord.Net.Core/Entities/Interactions/ContextMenus/UserCommandBuilder.cs b/src/Discord.Net.Core/Entities/Interactions/ContextMenus/UserCommandBuilder.cs
index 7c82dce55..d8bb2e056 100644
--- a/src/Discord.Net.Core/Entities/Interactions/ContextMenus/UserCommandBuilder.cs
+++ b/src/Discord.Net.Core/Entities/Interactions/ContextMenus/UserCommandBuilder.cs
@@ -1,3 +1,8 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text.RegularExpressions;
+
namespace Discord
{
///
@@ -5,7 +10,7 @@ namespace Discord
///
public class UserCommandBuilder
{
- ///
+ ///
/// Returns the maximum length a commands name allowed by Discord.
///
public const int MaxNameLength = 32;
@@ -31,6 +36,11 @@ namespace Discord
///
public bool IsDefaultPermission { get; set; } = true;
+ ///
+ /// Gets the localization dictionary for the name field of this command.
+ ///
+ public IReadOnlyDictionary NameLocalizations => _nameLocalizations;
+
///
/// Gets or sets whether or not this command can be used in DMs.
///
@@ -42,6 +52,7 @@ namespace Discord
public GuildPermission? DefaultMemberPermissions { get; set; }
private string _name;
+ private Dictionary _nameLocalizations;
///
/// Build the current builder into a class.
@@ -84,6 +95,30 @@ namespace Discord
return this;
}
+ ///
+ /// Sets the collection.
+ ///
+ /// The localization dictionary to use for the name field of this command.
+ /// The current builder.
+ /// Thrown if is null.
+ /// Thrown if any dictionary key is an invalid locale string.
+ public UserCommandBuilder WithNameLocalizations(IDictionary nameLocalizations)
+ {
+ if (nameLocalizations is null)
+ throw new ArgumentNullException(nameof(nameLocalizations));
+
+ foreach (var (locale, name) in nameLocalizations)
+ {
+ if(!Regex.IsMatch(locale, @"^\w{2}(?:-\w{2})?$"))
+ throw new ArgumentException($"Invalid locale: {locale}", nameof(locale));
+
+ EnsureValidCommandName(name);
+ }
+
+ _nameLocalizations = new Dictionary(nameLocalizations);
+ return this;
+ }
+
///
/// Sets whether or not this command can be used in dms
///
@@ -95,6 +130,41 @@ namespace Discord
return this;
}
+ ///
+ /// Adds a new entry to the collection.
+ ///
+ /// Locale of the entry.
+ /// Localized string for the name field.
+ /// The current builder.
+ /// Thrown if is an invalid locale string.
+ public UserCommandBuilder AddNameLocalization(string locale, string name)
+ {
+ if(!Regex.IsMatch(locale, @"^\w{2}(?:-\w{2})?$"))
+ throw new ArgumentException($"Invalid locale: {locale}", nameof(locale));
+
+ EnsureValidCommandName(name);
+
+ _nameLocalizations ??= new();
+ _nameLocalizations.Add(locale, name);
+
+ return this;
+ }
+
+ private static void EnsureValidCommandName(string name)
+ {
+ Preconditions.NotNullOrEmpty(name, nameof(name));
+ Preconditions.AtLeast(name.Length, 1, nameof(name));
+ Preconditions.AtMost(name.Length, MaxNameLength, nameof(name));
+
+ // Discord updated the docs, this regex prevents special characters like @!$%(... etc,
+ // https://discord.com/developers/docs/interactions/slash-commands#applicationcommand
+ if (!Regex.IsMatch(name, @"^[\w-]{1,32}$"))
+ throw new ArgumentException("Command name cannot contain any special characters or whitespaces!", nameof(name));
+
+ if (name.Any(x => char.IsUpper(x)))
+ throw new FormatException("Name cannot contain any uppercase characters.");
+ }
+
///
/// Sets the default member permissions required to use this application command.
///
diff --git a/src/Discord.Net.Core/Entities/Interactions/IApplicationCommand.cs b/src/Discord.Net.Core/Entities/Interactions/IApplicationCommand.cs
index 58a002649..6f9ce7a45 100644
--- a/src/Discord.Net.Core/Entities/Interactions/IApplicationCommand.cs
+++ b/src/Discord.Net.Core/Entities/Interactions/IApplicationCommand.cs
@@ -52,6 +52,32 @@ namespace Discord
///
IReadOnlyCollection Options { get; }
+ ///
+ /// Gets the localization dictionary for the name field of this command.
+ ///
+ IReadOnlyDictionary NameLocalizations { get; }
+
+ ///
+ /// Gets the localization dictionary for the description field of this command.
+ ///
+ IReadOnlyDictionary DescriptionLocalizations { get; }
+
+ ///
+ /// Gets the localized name of this command.
+ ///
+ ///
+ /// Only returned when the `withLocalizations` query parameter is set to when requesting the command.
+ ///
+ string NameLocalized { get; }
+
+ ///
+ /// Gets the localized description of this command.
+ ///
+ ///
+ /// Only returned when the `withLocalizations` query parameter is set to when requesting the command.
+ ///
+ string DescriptionLocalized { get; }
+
///
/// Modifies the current application command.
///
diff --git a/src/Discord.Net.Core/Entities/Interactions/IApplicationCommandOption.cs b/src/Discord.Net.Core/Entities/Interactions/IApplicationCommandOption.cs
index 72554fc98..fb179b661 100644
--- a/src/Discord.Net.Core/Entities/Interactions/IApplicationCommandOption.cs
+++ b/src/Discord.Net.Core/Entities/Interactions/IApplicationCommandOption.cs
@@ -47,6 +47,16 @@ namespace Discord
///
double? MaxValue { get; }
+ ///
+ /// Gets the minimum allowed length for a string input.
+ ///
+ int? MinLength { get; }
+
+ ///
+ /// Gets the maximum allowed length for a string input.
+ ///
+ int? MaxLength { get; }
+
///
/// Gets the choices for string and int types for the user to pick from.
///
@@ -61,5 +71,31 @@ namespace Discord
/// Gets the allowed channel types for this option.
///
IReadOnlyCollection ChannelTypes { get; }
+
+ ///
+ /// Gets the localization dictionary for the name field of this command option.
+ ///
+ IReadOnlyDictionary NameLocalizations { get; }
+
+ ///
+ /// Gets the localization dictionary for the description field of this command option.
+ ///
+ IReadOnlyDictionary DescriptionLocalizations { get; }
+
+ ///
+ /// Gets the localized name of this command option.
+ ///
+ ///
+ /// Only returned when the `withLocalizations` query parameter is set to when requesting the command.
+ ///
+ string NameLocalized { get; }
+
+ ///
+ /// Gets the localized description of this command option.
+ ///
+ ///
+ /// Only returned when the `withLocalizations` query parameter is set to true when requesting the command.
+ ///
+ string DescriptionLocalized { get; }
}
}
diff --git a/src/Discord.Net.Core/Entities/Interactions/IApplicationCommandOptionChoice.cs b/src/Discord.Net.Core/Entities/Interactions/IApplicationCommandOptionChoice.cs
index 631706c6f..3f76bae72 100644
--- a/src/Discord.Net.Core/Entities/Interactions/IApplicationCommandOptionChoice.cs
+++ b/src/Discord.Net.Core/Entities/Interactions/IApplicationCommandOptionChoice.cs
@@ -1,3 +1,5 @@
+using System.Collections.Generic;
+
namespace Discord
{
///
@@ -14,5 +16,18 @@ namespace Discord
/// Gets the value of the choice.
///
object Value { get; }
+
+ ///
+ /// Gets the localization dictionary for the name field of this command option.
+ ///
+ IReadOnlyDictionary NameLocalizations { get; }
+
+ ///
+ /// Gets the localized name of this command option.
+ ///
+ ///
+ /// Only returned when the `withLocalizations` query parameter is set to when requesting the command.
+ ///
+ string NameLocalized { get; }
}
}
diff --git a/src/Discord.Net.Core/Entities/Interactions/MessageComponents/ComponentBuilder.cs b/src/Discord.Net.Core/Entities/Interactions/MessageComponents/ComponentBuilder.cs
index 37342b039..fd8798ed3 100644
--- a/src/Discord.Net.Core/Entities/Interactions/MessageComponents/ComponentBuilder.cs
+++ b/src/Discord.Net.Core/Entities/Interactions/MessageComponents/ComponentBuilder.cs
@@ -1198,6 +1198,10 @@ namespace Discord
public class TextInputBuilder
{
+ ///
+ /// The max length of a .
+ ///
+ public const int MaxPlaceholderLength = 100;
public const int LargestMaxLength = 4000;
///
@@ -1229,13 +1233,13 @@ namespace Discord
///
/// Gets or sets the placeholder of the current text input.
///
- /// is longer than 100 characters
+ /// is longer than characters
public string Placeholder
{
get => _placeholder;
- set => _placeholder = (value?.Length ?? 0) <= 100
+ set => _placeholder = (value?.Length ?? 0) <= MaxPlaceholderLength
? value
- : throw new ArgumentException("Placeholder cannot have more than 100 characters.");
+ : throw new ArgumentException($"Placeholder cannot have more than {MaxPlaceholderLength} characters.");
}
///
diff --git a/src/Discord.Net.Core/Entities/Interactions/SlashCommands/SlashCommandBuilder.cs b/src/Discord.Net.Core/Entities/Interactions/SlashCommands/SlashCommandBuilder.cs
index bf74a160c..b443c4468 100644
--- a/src/Discord.Net.Core/Entities/Interactions/SlashCommands/SlashCommandBuilder.cs
+++ b/src/Discord.Net.Core/Entities/Interactions/SlashCommands/SlashCommandBuilder.cs
@@ -1,6 +1,9 @@
using System;
+using System.Collections;
using System.Collections.Generic;
+using System.Collections.Immutable;
using System.Linq;
+using System.Net.Sockets;
using System.Text.RegularExpressions;
namespace Discord
@@ -31,18 +34,7 @@ namespace Discord
get => _name;
set
{
- Preconditions.NotNullOrEmpty(value, nameof(value));
- Preconditions.AtLeast(value.Length, 1, nameof(value));
- Preconditions.AtMost(value.Length, MaxNameLength, nameof(value));
-
- // Discord updated the docs, this regex prevents special characters like @!$%(... etc,
- // https://discord.com/developers/docs/interactions/slash-commands#applicationcommand
- if (!Regex.IsMatch(value, @"^[\w-]{1,32}$"))
- throw new ArgumentException("Command name cannot contain any special characters or whitespaces!", nameof(value));
-
- if (value.Any(x => char.IsUpper(x)))
- throw new FormatException("Name cannot contain any uppercase characters.");
-
+ EnsureValidCommandName(value);
_name = value;
}
}
@@ -55,10 +47,7 @@ namespace Discord
get => _description;
set
{
- Preconditions.NotNullOrEmpty(value, nameof(Description));
- Preconditions.AtLeast(value.Length, 1, nameof(Description));
- Preconditions.AtMost(value.Length, MaxDescriptionLength, nameof(Description));
-
+ EnsureValidCommandDescription(value);
_description = value;
}
}
@@ -76,6 +65,16 @@ namespace Discord
}
}
+ ///
+ /// Gets the localization dictionary for the name field of this command.
+ ///
+ public IReadOnlyDictionary NameLocalizations => _nameLocalizations;
+
+ ///
+ /// Gets the localization dictionary for the description field of this command.
+ ///
+ public IReadOnlyDictionary DescriptionLocalizations => _descriptionLocalizations;
+
///
/// Gets or sets whether the command is enabled by default when the app is added to a guild
///
@@ -93,6 +92,8 @@ namespace Discord
private string _name;
private string _description;
+ private Dictionary _nameLocalizations;
+ private Dictionary _descriptionLocalizations;
private List _options;
///
@@ -106,6 +107,8 @@ namespace Discord
Name = Name,
Description = Description,
IsDefaultPermission = IsDefaultPermission,
+ NameLocalizations = _nameLocalizations,
+ DescriptionLocalizations = _descriptionLocalizations,
IsDMEnabled = IsDMEnabled,
DefaultMemberPermissions = DefaultMemberPermissions ?? Optional.Unspecified
};
@@ -190,13 +193,17 @@ namespace Discord
/// If this option is set to autocomplete.
/// The options of the option to add.
/// The allowed channel types for this option.
+ /// Localization dictionary for the name field of this command.
+ /// Localization dictionary for the description field of this command.
/// The choices of this option.
/// The smallest number value the user can input.
/// The largest number value the user can input.
/// The current builder.
public SlashCommandBuilder AddOption(string name, ApplicationCommandOptionType type,
string description, bool? isRequired = null, bool? isDefault = null, bool isAutocomplete = false, double? minValue = null, double? maxValue = null,
- List options = null, List channelTypes = null, params ApplicationCommandOptionChoiceProperties[] choices)
+ List options = null, List channelTypes = null, IDictionary nameLocalizations = null,
+ IDictionary descriptionLocalizations = null,
+ int? minLength = null, int? maxLength = null, params ApplicationCommandOptionChoiceProperties[] choices)
{
Preconditions.Options(name, description);
@@ -222,8 +229,16 @@ namespace Discord
ChannelTypes = channelTypes,
MinValue = minValue,
MaxValue = maxValue,
+ MinLength = minLength,
+ MaxLength = maxLength,
};
+ if (nameLocalizations is not null)
+ option.WithNameLocalizations(nameLocalizations);
+
+ if (descriptionLocalizations is not null)
+ option.WithDescriptionLocalizations(descriptionLocalizations);
+
return AddOption(option);
}
@@ -255,9 +270,6 @@ namespace Discord
if (options == null)
throw new ArgumentNullException(nameof(options), "Options cannot be null!");
- if (options.Length == 0)
- throw new ArgumentException("Options cannot be empty!", nameof(options));
-
Options ??= new List();
if (Options.Count + options.Length > MaxOptionsCount)
@@ -269,6 +281,116 @@ namespace Discord
Options.AddRange(options);
return this;
}
+
+ ///
+ /// Sets the collection.
+ ///
+ /// The localization dictionary to use for the name field of this command.
+ ///
+ /// Thrown if is null.
+ /// Thrown if any dictionary key is an invalid locale string.
+ public SlashCommandBuilder WithNameLocalizations(IDictionary nameLocalizations)
+ {
+ if (nameLocalizations is null)
+ throw new ArgumentNullException(nameof(nameLocalizations));
+
+ foreach (var (locale, name) in nameLocalizations)
+ {
+ if(!Regex.IsMatch(locale, @"^\w{2}(?:-\w{2})?$"))
+ throw new ArgumentException($"Invalid locale: {locale}", nameof(locale));
+
+ EnsureValidCommandName(name);
+ }
+
+ _nameLocalizations = new Dictionary(nameLocalizations);
+ return this;
+ }
+
+ ///
+ /// Sets the collection.
+ ///
+ /// The localization dictionary to use for the description field of this command.
+ ///
+ /// Thrown if is null.
+ /// Thrown if any dictionary key is an invalid locale string.
+ public SlashCommandBuilder WithDescriptionLocalizations(IDictionary descriptionLocalizations)
+ {
+ if (descriptionLocalizations is null)
+ throw new ArgumentNullException(nameof(descriptionLocalizations));
+
+ foreach (var (locale, description) in descriptionLocalizations)
+ {
+ if(!Regex.IsMatch(locale, @"^\w{2}(?:-\w{2})?$"))
+ throw new ArgumentException($"Invalid locale: {locale}", nameof(locale));
+
+ EnsureValidCommandDescription(description);
+ }
+
+ _descriptionLocalizations = new Dictionary(descriptionLocalizations);
+ return this;
+ }
+
+ ///
+ /// Adds a new entry to the collection.
+ ///
+ /// Locale of the entry.
+ /// Localized string for the name field.
+ /// The current builder.
+ /// Thrown if is an invalid locale string.
+ public SlashCommandBuilder AddNameLocalization(string locale, string name)
+ {
+ if(!Regex.IsMatch(locale, @"^\w{2}(?:-\w{2})?$"))
+ throw new ArgumentException($"Invalid locale: {locale}", nameof(locale));
+
+ EnsureValidCommandName(name);
+
+ _nameLocalizations ??= new();
+ _nameLocalizations.Add(locale, name);
+
+ return this;
+ }
+
+ ///
+ /// Adds a new entry to the collection.
+ ///
+ /// Locale of the entry.
+ /// Localized string for the description field.
+ /// The current builder.
+ /// Thrown if is an invalid locale string.
+ public SlashCommandBuilder AddDescriptionLocalization(string locale, string description)
+ {
+ if(!Regex.IsMatch(locale, @"^\w{2}(?:-\w{2})?$"))
+ throw new ArgumentException($"Invalid locale: {locale}", nameof(locale));
+
+ EnsureValidCommandDescription(description);
+
+ _descriptionLocalizations ??= new();
+ _descriptionLocalizations.Add(locale, description);
+
+ return this;
+ }
+
+ internal static void EnsureValidCommandName(string name)
+ {
+ Preconditions.NotNullOrEmpty(name, nameof(name));
+ Preconditions.AtLeast(name.Length, 1, nameof(name));
+ Preconditions.AtMost(name.Length, MaxNameLength, nameof(name));
+
+ // Discord updated the docs, this regex prevents special characters like @!$%(... etc,
+ // https://discord.com/developers/docs/interactions/slash-commands#applicationcommand
+ if (!Regex.IsMatch(name, @"^[\w-]{1,32}$"))
+ throw new ArgumentException("Command name cannot contain any special characters or whitespaces!", nameof(name));
+
+ if (name.Any(x => char.IsUpper(x)))
+ throw new FormatException("Name cannot contain any uppercase characters.");
+ }
+
+ internal static void EnsureValidCommandDescription(string description)
+ {
+ Preconditions.NotNullOrEmpty(description, nameof(description));
+ Preconditions.AtLeast(description.Length, 1, nameof(description));
+ Preconditions.AtMost(description.Length, MaxDescriptionLength, nameof(description));
+ }
}
///
@@ -288,6 +410,8 @@ namespace Discord
private string _name;
private string _description;
+ private Dictionary _nameLocalizations;
+ private Dictionary _descriptionLocalizations;
///
/// Gets or sets the name of this option.
@@ -299,10 +423,7 @@ namespace Discord
{
if (value != null)
{
- Preconditions.AtLeast(value.Length, 1, nameof(value));
- Preconditions.AtMost(value.Length, SlashCommandBuilder.MaxNameLength, nameof(value));
- if (!Regex.IsMatch(value, @"^[\w-]{1,32}$"))
- throw new ArgumentException("Option name cannot contain any special characters or whitespaces!", nameof(value));
+ EnsureValidCommandOptionName(value);
}
_name = value;
@@ -319,8 +440,7 @@ namespace Discord
{
if (value != null)
{
- Preconditions.AtLeast(value.Length, 1, nameof(value));
- Preconditions.AtMost(value.Length, SlashCommandBuilder.MaxDescriptionLength, nameof(value));
+ EnsureValidCommandOptionDescription(value);
}
_description = value;
@@ -357,6 +477,16 @@ namespace Discord
///
public double? MaxValue { get; set; }
+ ///
+ /// Gets or sets the minimum allowed length for a string input.
+ ///
+ public int? MinLength { get; set; }
+
+ ///
+ /// Gets or sets the maximum allowed length for a string input.
+ ///
+ public int? MaxLength { get; set; }
+
///
/// Gets or sets the choices for string and int types for the user to pick from.
///
@@ -372,6 +502,16 @@ namespace Discord
///
public List ChannelTypes { get; set; }
+ ///
+ /// Gets the localization dictionary for the name field of this command.
+ ///
+ public IReadOnlyDictionary NameLocalizations => _nameLocalizations;
+
+ ///
+ /// Gets the localization dictionary for the description field of this command.
+ ///
+ public IReadOnlyDictionary DescriptionLocalizations => _descriptionLocalizations;
+
///
/// Builds the current option.
///
@@ -380,6 +520,7 @@ namespace Discord
{
bool isSubType = Type == ApplicationCommandOptionType.SubCommandGroup;
bool isIntType = Type == ApplicationCommandOptionType.Integer;
+ bool isStrType = Type == ApplicationCommandOptionType.String;
if (isSubType && (Options == null || !Options.Any()))
throw new InvalidOperationException("SubCommands/SubCommandGroups must have at least one option");
@@ -393,6 +534,12 @@ namespace Discord
if (isIntType && MaxValue != null && MaxValue % 1 != 0)
throw new InvalidOperationException("MaxValue cannot have decimals on Integer command options.");
+ if(isStrType && MinLength is not null && MinLength < 0)
+ throw new InvalidOperationException("MinLength cannot be smaller than 0.");
+
+ if (isStrType && MaxLength is not null && MaxLength < 1)
+ throw new InvalidOperationException("MaxLength cannot be smaller than 1.");
+
return new ApplicationCommandOptionProperties
{
Name = Name,
@@ -407,9 +554,13 @@ namespace Discord
IsAutocomplete = IsAutocomplete,
ChannelTypes = ChannelTypes,
MinValue = MinValue,
- MaxValue = MaxValue
+ MaxValue = MaxValue,
+ NameLocalizations = _nameLocalizations,
+ DescriptionLocalizations = _descriptionLocalizations,
+ MinLength = MinLength,
+ MaxLength = MaxLength,
};
- }
+ }
///
/// Adds an option to the current slash command.
@@ -422,13 +573,17 @@ namespace Discord
/// If this option supports autocomplete.
/// The options of the option to add.
/// The allowed channel types for this option.
+ /// Localization dictionary for the description field of this command.
+ /// Localization dictionary for the description field of this command.
/// The choices of this option.
/// The smallest number value the user can input.
/// The largest number value the user can input.
/// The current builder.
public SlashCommandOptionBuilder AddOption(string name, ApplicationCommandOptionType type,
string description, bool? isRequired = null, bool isDefault = false, bool isAutocomplete = false, double? minValue = null, double? maxValue = null,
- List options = null, List channelTypes = null, params ApplicationCommandOptionChoiceProperties[] choices)
+ List options = null, List channelTypes = null, IDictionary nameLocalizations = null,
+ IDictionary descriptionLocalizations = null,
+ int? minLength = null, int? maxLength = null, params ApplicationCommandOptionChoiceProperties[] choices)
{
Preconditions.Options(name, description);
@@ -450,12 +605,20 @@ namespace Discord
IsAutocomplete = isAutocomplete,
MinValue = minValue,
MaxValue = maxValue,
+ MinLength = minLength,
+ MaxLength = maxLength,
Options = options,
Type = type,
Choices = (choices ?? Array.Empty()).ToList(),
- ChannelTypes = channelTypes
+ ChannelTypes = channelTypes,
};
+ if(nameLocalizations is not null)
+ option.WithNameLocalizations(nameLocalizations);
+
+ if(descriptionLocalizations is not null)
+ option.WithDescriptionLocalizations(descriptionLocalizations);
+
return AddOption(option);
}
///
@@ -477,15 +640,36 @@ namespace Discord
return this;
}
+ ///
+ /// Adds a collection of options to the current option.
+ ///
+ /// The collection of options to add.
+ /// The current builder.
+ public SlashCommandOptionBuilder AddOptions(params SlashCommandOptionBuilder[] options)
+ {
+ if (options == null)
+ throw new ArgumentNullException(nameof(options), "Options cannot be null!");
+
+ if ((Options?.Count ?? 0) + options.Length > SlashCommandBuilder.MaxOptionsCount)
+ throw new ArgumentOutOfRangeException(nameof(options), $"There can only be {SlashCommandBuilder.MaxOptionsCount} options per sub command group!");
+
+ foreach (var option in options)
+ Preconditions.Options(option.Name, option.Description);
+
+ Options.AddRange(options);
+ return this;
+ }
+
///
/// Adds a choice to the current option.
///
/// The name of the choice.
/// The value of the choice.
+ /// The localization dictionary for to use the name field of this command option choice.
/// The current builder.
- public SlashCommandOptionBuilder AddChoice(string name, int value)
+ public SlashCommandOptionBuilder AddChoice(string name, int value, IDictionary nameLocalizations = null)
{
- return AddChoiceInternal(name, value);
+ return AddChoiceInternal(name, value, nameLocalizations);
}
///
@@ -493,10 +677,11 @@ namespace Discord
///
/// The name of the choice.
/// The value of the choice.
+ /// The localization dictionary for to use the name field of this command option choice.
/// The current builder.
- public SlashCommandOptionBuilder AddChoice(string name, string value)
+ public SlashCommandOptionBuilder AddChoice(string name, string value, IDictionary nameLocalizations = null)
{
- return AddChoiceInternal(name, value);
+ return AddChoiceInternal(name, value, nameLocalizations);
}
///
@@ -504,10 +689,11 @@ namespace Discord
///
/// The name of the choice.
/// The value of the choice.
+ /// Localization dictionary for the description field of this command.
/// The current builder.
- public SlashCommandOptionBuilder AddChoice(string name, double value)
+ public SlashCommandOptionBuilder AddChoice(string name, double value, IDictionary nameLocalizations = null)
{
- return AddChoiceInternal(name, value);
+ return AddChoiceInternal(name, value, nameLocalizations);
}
///
@@ -515,10 +701,11 @@ namespace Discord
///
/// The name of the choice.
/// The value of the choice.
+ /// The localization dictionary to use for the name field of this command option choice.
/// The current builder.
- public SlashCommandOptionBuilder AddChoice(string name, float value)
+ public SlashCommandOptionBuilder AddChoice(string name, float value, IDictionary nameLocalizations = null)
{
- return AddChoiceInternal(name, value);
+ return AddChoiceInternal(name, value, nameLocalizations);
}
///
@@ -526,13 +713,14 @@ namespace Discord
///
/// The name of the choice.
/// The value of the choice.
+ /// The localization dictionary to use for the name field of this command option choice.
/// The current builder.
- public SlashCommandOptionBuilder AddChoice(string name, long value)
+ public SlashCommandOptionBuilder AddChoice(string name, long value, IDictionary nameLocalizations = null)
{
- return AddChoiceInternal(name, value);
+ return AddChoiceInternal(name, value, nameLocalizations);
}
- private SlashCommandOptionBuilder AddChoiceInternal(string name, object value)
+ private SlashCommandOptionBuilder AddChoiceInternal(string name, object value, IDictionary nameLocalizations = null)
{
Choices ??= new List();
@@ -554,7 +742,8 @@ namespace Discord
Choices.Add(new ApplicationCommandOptionChoiceProperties
{
Name = name,
- Value = value
+ Value = value,
+ NameLocalizations = nameLocalizations
});
return this;
@@ -640,7 +829,7 @@ namespace Discord
MinValue = value;
return this;
}
-
+
///
/// Sets the current builders max value field.
///
@@ -652,6 +841,28 @@ namespace Discord
return this;
}
+ ///
+ /// Sets the current builders min length field.
+ ///
+ /// The value to set.
+ /// The current builder.
+ public SlashCommandOptionBuilder WithMinLength(int length)
+ {
+ MinLength = length;
+ return this;
+ }
+
+ ///
+ /// Sets the current builders max length field.
+ ///
+ /// The value to set.
+ /// The current builder.
+ public SlashCommandOptionBuilder WithMaxLength(int length)
+ {
+ MaxLength = length;
+ return this;
+ }
+
///
/// Sets the current type of this builder.
///
@@ -662,5 +873,107 @@ namespace Discord
Type = type;
return this;
}
+
+ ///
+ /// Sets the collection.
+ ///
+ /// The localization dictionary to use for the name field of this command option.
+ /// The current builder.
+ /// Thrown if is null.
+ /// Thrown if any dictionary key is an invalid locale string.
+ public SlashCommandOptionBuilder WithNameLocalizations(IDictionary nameLocalizations)
+ {
+ if (nameLocalizations is null)
+ throw new ArgumentNullException(nameof(nameLocalizations));
+
+ foreach (var (locale, name) in nameLocalizations)
+ {
+ if(!Regex.IsMatch(locale, @"^\w{2}(?:-\w{2})?$"))
+ throw new ArgumentException($"Invalid locale: {locale}", nameof(locale));
+
+ EnsureValidCommandOptionName(name);
+ }
+
+ _nameLocalizations = new Dictionary(nameLocalizations);
+ return this;
+ }
+
+ ///
+ /// Sets the collection.
+ ///
+ /// The localization dictionary to use for the description field of this command option.
+ /// The current builder.
+ /// Thrown if is null.
+ /// Thrown if any dictionary key is an invalid locale string.
+ public SlashCommandOptionBuilder WithDescriptionLocalizations(IDictionary descriptionLocalizations)
+ {
+ if (descriptionLocalizations is null)
+ throw new ArgumentNullException(nameof(descriptionLocalizations));
+
+ foreach (var (locale, description) in _descriptionLocalizations)
+ {
+ if(!Regex.IsMatch(locale, @"^\w{2}(?:-\w{2})?$"))
+ throw new ArgumentException($"Invalid locale: {locale}", nameof(locale));
+
+ EnsureValidCommandOptionDescription(description);
+ }
+
+ _descriptionLocalizations = new Dictionary(descriptionLocalizations);
+ return this;
+ }
+
+ ///
+ /// Adds a new entry to the collection.
+ ///
+ /// Locale of the entry.
+ /// Localized string for the name field.
+ /// The current builder.
+ /// Thrown if is an invalid locale string.
+ public SlashCommandOptionBuilder AddNameLocalization(string locale, string name)
+ {
+ if(!Regex.IsMatch(locale, @"^\w{2}(?:-\w{2})?$"))
+ throw new ArgumentException($"Invalid locale: {locale}", nameof(locale));
+
+ EnsureValidCommandOptionName(name);
+
+ _descriptionLocalizations ??= new();
+ _nameLocalizations.Add(locale, name);
+
+ return this;
+ }
+
+ ///
+ /// Adds a new entry to the collection.
+ ///
+ /// Locale of the entry.
+ /// Localized string for the description field.
+ /// The current builder.
+ /// Thrown if is an invalid locale string.
+ public SlashCommandOptionBuilder AddDescriptionLocalization(string locale, string description)
+ {
+ if(!Regex.IsMatch(locale, @"^\w{2}(?:-\w{2})?$"))
+ throw new ArgumentException($"Invalid locale: {locale}", nameof(locale));
+
+ EnsureValidCommandOptionDescription(description);
+
+ _descriptionLocalizations ??= new();
+ _descriptionLocalizations.Add(locale, description);
+
+ return this;
+ }
+
+ private static void EnsureValidCommandOptionName(string name)
+ {
+ Preconditions.AtLeast(name.Length, 1, nameof(name));
+ Preconditions.AtMost(name.Length, SlashCommandBuilder.MaxNameLength, nameof(name));
+ if (!Regex.IsMatch(name, @"^[\w-]{1,32}$"))
+ throw new ArgumentException("Option name cannot contain any special characters or whitespaces!", nameof(name));
+ }
+
+ private static void EnsureValidCommandOptionDescription(string description)
+ {
+ Preconditions.AtLeast(description.Length, 1, nameof(description));
+ Preconditions.AtMost(description.Length, SlashCommandBuilder.MaxDescriptionLength, nameof(description));
+ }
}
}
diff --git a/src/Discord.Net.Core/Entities/Messages/Embed.cs b/src/Discord.Net.Core/Entities/Messages/Embed.cs
index 7fa6f6f36..c1478f56c 100644
--- a/src/Discord.Net.Core/Entities/Messages/Embed.cs
+++ b/src/Discord.Net.Core/Entities/Messages/Embed.cs
@@ -94,5 +94,44 @@ namespace Discord
///
public override string ToString() => Title;
private string DebuggerDisplay => $"{Title} ({Type})";
+
+ public static bool operator ==(Embed left, Embed right)
+ => left is null ? right is null
+ : left.Equals(right);
+
+ public static bool operator !=(Embed left, Embed right)
+ => !(left == right);
+
+ ///
+ /// Determines whether the specified object is equal to the current .
+ ///
+ ///
+ /// If the object passes is an , will be called to compare the 2 instances
+ ///
+ /// The object to compare with the current
+ ///
+ public override bool Equals(object obj)
+ => obj is Embed embed && Equals(embed);
+
+ ///
+ /// Determines whether the specified is equal to the current
+ ///
+ /// The to compare with the current
+ ///
+ public bool Equals(Embed embed)
+ => GetHashCode() == embed?.GetHashCode();
+
+ ///
+ public override int GetHashCode()
+ {
+ unchecked
+ {
+ var hash = 17;
+ hash = hash * 23 + (Type, Title, Description, Timestamp, Color, Image, Video, Author, Footer, Provider, Thumbnail).GetHashCode();
+ foreach(var field in Fields)
+ hash = hash * 23 + field.GetHashCode();
+ return hash;
+ }
+ }
}
}
diff --git a/src/Discord.Net.Core/Entities/Messages/EmbedAuthor.cs b/src/Discord.Net.Core/Entities/Messages/EmbedAuthor.cs
index 3b11f6a8b..fdd51e6c9 100644
--- a/src/Discord.Net.Core/Entities/Messages/EmbedAuthor.cs
+++ b/src/Discord.Net.Core/Entities/Messages/EmbedAuthor.cs
@@ -1,3 +1,4 @@
+using System;
using System.Diagnostics;
namespace Discord
@@ -41,5 +42,35 @@ namespace Discord
///
///
public override string ToString() => Name;
+
+ public static bool operator ==(EmbedAuthor? left, EmbedAuthor? right)
+ => left is null ? right is null
+ : left.Equals(right);
+
+ public static bool operator !=(EmbedAuthor? left, EmbedAuthor? right)
+ => !(left == right);
+
+ ///
+ /// Determines whether the specified object is equal to the current .
+ ///
+ ///
+ /// If the object passes is an , will be called to compare the 2 instances
+ ///
+ /// The object to compare with the current
+ ///
+ public override bool Equals(object obj)
+ => obj is EmbedAuthor embedAuthor && Equals(embedAuthor);
+
+ ///
+ /// Determines whether the specified is equal to the current
+ ///
+ /// The to compare with the current
+ ///
+ public bool Equals(EmbedAuthor? embedAuthor)
+ => GetHashCode() == embedAuthor?.GetHashCode();
+
+ ///
+ public override int GetHashCode()
+ => (Name, Url, IconUrl).GetHashCode();
}
}
diff --git a/src/Discord.Net.Core/Entities/Messages/EmbedBuilder.cs b/src/Discord.Net.Core/Entities/Messages/EmbedBuilder.cs
index 1e2a7b0d7..db38b9fb7 100644
--- a/src/Discord.Net.Core/Entities/Messages/EmbedBuilder.cs
+++ b/src/Discord.Net.Core/Entities/Messages/EmbedBuilder.cs
@@ -481,6 +481,55 @@ namespace Discord
return new Embed(EmbedType.Rich, Title, Description, Url, Timestamp, Color, _image, null, Author?.Build(), Footer?.Build(), null, _thumbnail, fields.ToImmutable());
}
+
+ public static bool operator ==(EmbedBuilder left, EmbedBuilder right)
+ => left is null ? right is null
+ : left.Equals(right);
+
+ public static bool operator !=(EmbedBuilder left, EmbedBuilder right)
+ => !(left == right);
+
+ ///
+ /// Determines whether the specified object is equal to the current .
+ ///
+ ///
+ /// If the object passes is an , will be called to compare the 2 instances
+ ///
+ /// The object to compare with the current
+ ///
+ public override bool Equals(object obj)
+ => obj is EmbedBuilder embedBuilder && Equals(embedBuilder);
+
+ ///
+ /// Determines whether the specified is equal to the current
+ ///
+ /// The to compare with the current
+ ///
+ public bool Equals(EmbedBuilder embedBuilder)
+ {
+ if (embedBuilder is null)
+ return false;
+
+ if (Fields.Count != embedBuilder.Fields.Count)
+ return false;
+
+ for (var i = 0; i < _fields.Count; i++)
+ if (_fields[i] != embedBuilder._fields[i])
+ return false;
+
+ return _title == embedBuilder?._title
+ && _description == embedBuilder?._description
+ && _image == embedBuilder?._image
+ && _thumbnail == embedBuilder?._thumbnail
+ && Timestamp == embedBuilder?.Timestamp
+ && Color == embedBuilder?.Color
+ && Author == embedBuilder?.Author
+ && Footer == embedBuilder?.Footer
+ && Url == embedBuilder?.Url;
+ }
+
+ ///
+ public override int GetHashCode() => base.GetHashCode();
}
///
@@ -597,6 +646,37 @@ namespace Discord
///
public EmbedField Build()
=> new EmbedField(Name, Value.ToString(), IsInline);
+
+ public static bool operator ==(EmbedFieldBuilder left, EmbedFieldBuilder right)
+ => left is null ? right is null
+ : left.Equals(right);
+
+ public static bool operator !=(EmbedFieldBuilder left, EmbedFieldBuilder right)
+ => !(left == right);
+
+ ///
+ /// Determines whether the specified object is equal to the current .
+ ///
+ ///
+ /// If the object passes is an , will be called to compare the 2 instances
+ ///
+ /// The object to compare with the current
+ ///
+ public override bool Equals(object obj)
+ => obj is EmbedFieldBuilder embedFieldBuilder && Equals(embedFieldBuilder);
+
+ ///
+ /// Determines whether the specified is equal to the current
+ ///
+ /// The to compare with the current
+ ///
+ public bool Equals(EmbedFieldBuilder embedFieldBuilder)
+ => _name == embedFieldBuilder?._name
+ && _value == embedFieldBuilder?._value
+ && IsInline == embedFieldBuilder?.IsInline;
+
+ ///
+ public override int GetHashCode() => base.GetHashCode();
}
///
@@ -697,6 +777,37 @@ namespace Discord
///
public EmbedAuthor Build()
=> new EmbedAuthor(Name, Url, IconUrl, null);
+
+ public static bool operator ==(EmbedAuthorBuilder left, EmbedAuthorBuilder right)
+ => left is null ? right is null
+ : left.Equals(right);
+
+ public static bool operator !=(EmbedAuthorBuilder left, EmbedAuthorBuilder right)
+ => !(left == right);
+
+ ///
+ /// Determines whether the specified object is equal to the current .
+ ///
+ ///
+ /// If the object passes is an , will be called to compare the 2 instances
+ ///
+ /// The object to compare with the current
+ ///
+ public override bool Equals(object obj)
+ => obj is EmbedAuthorBuilder embedAuthorBuilder && Equals(embedAuthorBuilder);
+
+ ///
+ /// Determines whether the specified is equals to the current
+ ///
+ /// The to compare with the current
+ ///
+ public bool Equals(EmbedAuthorBuilder embedAuthorBuilder)
+ => _name == embedAuthorBuilder?._name
+ && Url == embedAuthorBuilder?.Url
+ && IconUrl == embedAuthorBuilder?.IconUrl;
+
+ ///
+ public override int GetHashCode() => base.GetHashCode();
}
///
@@ -777,5 +888,35 @@ namespace Discord
///
public EmbedFooter Build()
=> new EmbedFooter(Text, IconUrl, null);
+
+ public static bool operator ==(EmbedFooterBuilder left, EmbedFooterBuilder right)
+ => left is null ? right is null
+ : left.Equals(right);
+
+ public static bool operator !=(EmbedFooterBuilder left, EmbedFooterBuilder right)
+ => !(left == right);
+
+ ///
+ /// Determines whether the specified object is equal to the current .
+ ///
+ ///
+ /// If the object passes is an , will be called to compare the 2 instances
+ ///
+ /// The object to compare with the current
+ ///
+ public override bool Equals(object obj)
+ => obj is EmbedFooterBuilder embedFooterBuilder && Equals(embedFooterBuilder);
+
+ ///
+ /// Determines whether the specified is equal to the current
+ ///
+ /// The to compare with the current
+ ///
+ public bool Equals(EmbedFooterBuilder embedFooterBuilder)
+ => _text == embedFooterBuilder?._text
+ && IconUrl == embedFooterBuilder?.IconUrl;
+
+ ///
+ public override int GetHashCode() => base.GetHashCode();
}
}
diff --git a/src/Discord.Net.Core/Entities/Messages/EmbedField.cs b/src/Discord.Net.Core/Entities/Messages/EmbedField.cs
index f6aa2af3b..1196869fe 100644
--- a/src/Discord.Net.Core/Entities/Messages/EmbedField.cs
+++ b/src/Discord.Net.Core/Entities/Messages/EmbedField.cs
@@ -1,3 +1,4 @@
+using System;
using System.Diagnostics;
namespace Discord
@@ -36,5 +37,35 @@ namespace Discord
/// A string that resolves to .
///
public override string ToString() => Name;
+
+ public static bool operator ==(EmbedField? left, EmbedField? right)
+ => left is null ? right is null
+ : left.Equals(right);
+
+ public static bool operator !=(EmbedField? left, EmbedField? right)
+ => !(left == right);
+
+ ///
+ /// Determines whether the specified object is equal to the current .
+ ///
+ ///
+ /// If the object passes is an , will be called to compare the 2 instances
+ ///
+ /// The object to compare with the current object
+ ///
+ public override bool Equals(object obj)
+ => obj is EmbedField embedField && Equals(embedField);
+
+ ///
+ /// Determines whether the specified is equal to the current
+ ///
+ ///
+ ///
+ public bool Equals(EmbedField? embedField)
+ => GetHashCode() == embedField?.GetHashCode();
+
+ ///
+ public override int GetHashCode()
+ => (Name, Value, Inline).GetHashCode();
}
}
diff --git a/src/Discord.Net.Core/Entities/Messages/EmbedFooter.cs b/src/Discord.Net.Core/Entities/Messages/EmbedFooter.cs
index 4c507d017..5a1f13158 100644
--- a/src/Discord.Net.Core/Entities/Messages/EmbedFooter.cs
+++ b/src/Discord.Net.Core/Entities/Messages/EmbedFooter.cs
@@ -1,3 +1,4 @@
+using System;
using System.Diagnostics;
namespace Discord
@@ -43,5 +44,35 @@ namespace Discord
/// A string that resolves to .
///
public override string ToString() => Text;
+
+ public static bool operator ==(EmbedFooter? left, EmbedFooter? right)
+ => left is null ? right is null
+ : left.Equals(right);
+
+ public static bool operator !=(EmbedFooter? left, EmbedFooter? right)
+ => !(left == right);
+
+ ///
+ /// Determines whether the specified object is equal to the current .
+ ///
+ ///
+ /// If the object passes is an , will be called to compare the 2 instances
+ ///
+ /// The object to compare with the current
+ ///
+ public override bool Equals(object obj)
+ => obj is EmbedFooter embedFooter && Equals(embedFooter);
+
+ ///
+ /// Determines whether the specified is equal to the current
+ ///
+ /// The to compare with the current
+ ///
+ public bool Equals(EmbedFooter? embedFooter)
+ => GetHashCode() == embedFooter?.GetHashCode();
+
+ ///
+ public override int GetHashCode()
+ => (Text, IconUrl, ProxyUrl).GetHashCode();
}
}
diff --git a/src/Discord.Net.Core/Entities/Messages/EmbedImage.cs b/src/Discord.Net.Core/Entities/Messages/EmbedImage.cs
index 9ce2bfe73..85a638dc8 100644
--- a/src/Discord.Net.Core/Entities/Messages/EmbedImage.cs
+++ b/src/Discord.Net.Core/Entities/Messages/EmbedImage.cs
@@ -1,3 +1,4 @@
+using System;
using System.Diagnostics;
namespace Discord
@@ -53,5 +54,35 @@ namespace Discord
/// A string that resolves to .
///
public override string ToString() => Url;
+
+ public static bool operator ==(EmbedImage? left, EmbedImage? right)
+ => left is null ? right is null
+ : left.Equals(right);
+
+ public static bool operator !=(EmbedImage? left, EmbedImage? right)
+ => !(left == right);
+
+ ///
+ /// Determines whether the specified object is equal to the current .
+ ///
+ ///
+ /// If the object passes is an , will be called to compare the 2 instances
+ ///
+ /// The object to compare with the current
+ ///
+ public override bool Equals(object obj)
+ => obj is EmbedImage embedImage && Equals(embedImage);
+
+ ///
+ /// Determines whether the specified is equal to the current
+ ///
+ /// The to compare with the current
+ ///
+ public bool Equals(EmbedImage? embedImage)
+ => GetHashCode() == embedImage?.GetHashCode();
+
+ ///
+ public override int GetHashCode()
+ => (Height, Width, Url, ProxyUrl).GetHashCode();
}
}
diff --git a/src/Discord.Net.Core/Entities/Messages/EmbedProvider.cs b/src/Discord.Net.Core/Entities/Messages/EmbedProvider.cs
index 960fb3d78..f2ee74613 100644
--- a/src/Discord.Net.Core/Entities/Messages/EmbedProvider.cs
+++ b/src/Discord.Net.Core/Entities/Messages/EmbedProvider.cs
@@ -1,3 +1,4 @@
+using System;
using System.Diagnostics;
namespace Discord
@@ -35,5 +36,35 @@ namespace Discord
/// A string that resolves to .
///
public override string ToString() => Name;
+
+ public static bool operator ==(EmbedProvider? left, EmbedProvider? right)
+ => left is null ? right is null
+ : left.Equals(right);
+
+ public static bool operator !=(EmbedProvider? left, EmbedProvider? right)
+ => !(left == right);
+
+ ///
+ /// Determines whether the specified object is equal to the current .
+ ///
+ ///
+ /// If the object passes is an , will be called to compare the 2 instances
+ ///
+ /// The object to compare with the current
+ ///
+ public override bool Equals(object obj)
+ => obj is EmbedProvider embedProvider && Equals(embedProvider);
+
+ ///
+ /// Determines whether the specified is equal to the current
+ ///
+ /// The to compare with the current
+ ///
+ public bool Equals(EmbedProvider? embedProvider)
+ => GetHashCode() == embedProvider?.GetHashCode();
+
+ ///
+ public override int GetHashCode()
+ => (Name, Url).GetHashCode();
}
}
diff --git a/src/Discord.Net.Core/Entities/Messages/EmbedThumbnail.cs b/src/Discord.Net.Core/Entities/Messages/EmbedThumbnail.cs
index 7f7b582dc..65c8139c3 100644
--- a/src/Discord.Net.Core/Entities/Messages/EmbedThumbnail.cs
+++ b/src/Discord.Net.Core/Entities/Messages/EmbedThumbnail.cs
@@ -1,3 +1,4 @@
+using System;
using System.Diagnostics;
namespace Discord
@@ -53,5 +54,35 @@ namespace Discord
/// A string that resolves to .
///
public override string ToString() => Url;
+
+ public static bool operator ==(EmbedThumbnail? left, EmbedThumbnail? right)
+ => left is null ? right is null
+ : left.Equals(right);
+
+ public static bool operator !=(EmbedThumbnail? left, EmbedThumbnail? right)
+ => !(left == right);
+
+ ///
+ /// Determines whether the specified object is equal to the current .
+ ///
+ ///
+ /// If the object passes is an , will be called to compare the 2 instances
+ ///
+ /// The object to compare with the current
+ ///
+ public override bool Equals(object obj)
+ => obj is EmbedThumbnail embedThumbnail && Equals(embedThumbnail);
+
+ ///
+ /// Determines whether the specified is equal to the current
+ ///
+ /// The to compare with the current
+ ///
+ public bool Equals(EmbedThumbnail? embedThumbnail)
+ => GetHashCode() == embedThumbnail?.GetHashCode();
+
+ ///
+ public override int GetHashCode()
+ => (Width, Height, Url, ProxyUrl).GetHashCode();
}
}
diff --git a/src/Discord.Net.Core/Entities/Messages/EmbedVideo.cs b/src/Discord.Net.Core/Entities/Messages/EmbedVideo.cs
index ca0300e80..0762ed8e7 100644
--- a/src/Discord.Net.Core/Entities/Messages/EmbedVideo.cs
+++ b/src/Discord.Net.Core/Entities/Messages/EmbedVideo.cs
@@ -1,3 +1,4 @@
+using System;
using System.Diagnostics;
namespace Discord
@@ -47,5 +48,35 @@ namespace Discord
/// A string that resolves to .
///
public override string ToString() => Url;
+
+ public static bool operator ==(EmbedVideo? left, EmbedVideo? right)
+ => left is null ? right is null
+ : left.Equals(right);
+
+ public static bool operator !=(EmbedVideo? left, EmbedVideo? right)
+ => !(left == right);
+
+ ///
+ /// Determines whether the specified object is equal to the current .
+ ///
+ ///
+ /// If the object passes is an , will be called to compare the 2 instances
+ ///
+ /// The object to compare with the current
+ ///
+ public override bool Equals(object obj)
+ => obj is EmbedVideo embedVideo && Equals(embedVideo);
+
+ ///
+ /// Determines whether the specified is equal to the current
+ ///
+ /// The to compare with the current
+ ///
+ public bool Equals(EmbedVideo? embedVideo)
+ => GetHashCode() == embedVideo?.GetHashCode();
+
+ ///
+ public override int GetHashCode()
+ => (Width, Height, Url).GetHashCode();
}
}
diff --git a/src/Discord.Net.Core/Entities/Messages/IMessage.cs b/src/Discord.Net.Core/Entities/Messages/IMessage.cs
index f5f2ca007..48db4fdf0 100644
--- a/src/Discord.Net.Core/Entities/Messages/IMessage.cs
+++ b/src/Discord.Net.Core/Entities/Messages/IMessage.cs
@@ -48,6 +48,9 @@ namespace Discord
///
/// Gets the content for this message.
///
+ ///
+ /// This will be empty if the privileged is disabled.
+ ///
///
/// A string that contains the body of the message; note that this field may be empty if there is an embed.
///
@@ -55,6 +58,9 @@ namespace Discord
///
/// Gets the clean content for this message.
///
+ ///
+ /// This will be empty if the privileged is disabled.
+ ///
///
/// A string that contains the body of the message stripped of mentions, markdown, emojis and pings; note that this field may be empty if there is an embed.
///
diff --git a/src/Discord.Net.Core/Extensions/GenericCollectionExtensions.cs b/src/Discord.Net.Core/Extensions/GenericCollectionExtensions.cs
new file mode 100644
index 000000000..75d81d292
--- /dev/null
+++ b/src/Discord.Net.Core/Extensions/GenericCollectionExtensions.cs
@@ -0,0 +1,15 @@
+using System.Linq;
+
+namespace System.Collections.Generic;
+
+internal static class GenericCollectionExtensions
+{
+ public static void Deconstruct(this KeyValuePair kvp, out T1 value1, out T2 value2)
+ {
+ value1 = kvp.Key;
+ value2 = kvp.Value;
+ }
+
+ public static Dictionary ToDictionary(this IEnumerable> kvp) =>
+ kvp.ToDictionary(x => x.Key, x => x.Value);
+}
diff --git a/src/Discord.Net.Core/GatewayIntents.cs b/src/Discord.Net.Core/GatewayIntents.cs
index f2a99e44c..e9dd8f814 100644
--- a/src/Discord.Net.Core/GatewayIntents.cs
+++ b/src/Discord.Net.Core/GatewayIntents.cs
@@ -39,7 +39,14 @@ namespace Discord
DirectMessageReactions = 1 << 13,
/// This intent includes TYPING_START
DirectMessageTyping = 1 << 14,
- /// This intent includes GUILD_SCHEDULED_EVENT_CREATE, GUILD_SCHEDULED_EVENT_UPDATE, GUILD_SCHEDULED_EVENT_DELETE, GUILD_SCHEDULED_EVENT_USER_ADD, GUILD_SCHEDULED_EVENT_USER_REMOVE
+ ///
+ /// This intent defines if the content within messages received by MESSAGE_CREATE is available or not.
+ /// This is a privileged intent and needs to be enabled in the developer portal.
+ ///
+ MessageContent = 1 << 15,
+ ///
+ /// This intent includes GUILD_SCHEDULED_EVENT_CREATE, GUILD_SCHEDULED_EVENT_UPDATE, GUILD_SCHEDULED_EVENT_DELETE, GUILD_SCHEDULED_EVENT_USER_ADD, GUILD_SCHEDULED_EVENT_USER_REMOVE
+ ///
GuildScheduledEvents = 1 << 16,
///
/// This intent includes all but and
@@ -51,6 +58,6 @@ namespace Discord
///
/// This intent includes all of them, including privileged ones.
///
- All = AllUnprivileged | GuildMembers | GuildPresences
+ All = AllUnprivileged | GuildMembers | GuildPresences | MessageContent
}
}
diff --git a/src/Discord.Net.Core/IDiscordClient.cs b/src/Discord.Net.Core/IDiscordClient.cs
index 14e156769..dd1da3ae3 100644
--- a/src/Discord.Net.Core/IDiscordClient.cs
+++ b/src/Discord.Net.Core/IDiscordClient.cs
@@ -155,12 +155,14 @@ namespace Discord
///
/// Gets a collection of all global commands.
///
+ /// Whether to include full localization dictionaries in the returned objects, instead of the name localized and description localized fields.
+ /// The target locale of the localized name and description fields. Sets X-Discord-Locale header, which takes precedence over Accept-Language.
/// The options to be used when sending the request.
///
/// A task that represents the asynchronous get operation. The task result contains a read-only collection of global
/// application commands.
///
- Task> GetGlobalApplicationCommandsAsync(RequestOptions options = null);
+ Task> GetGlobalApplicationCommandsAsync(bool withLocalizations = false, string locale = null, RequestOptions options = null);
///
/// Creates a global application command.
diff --git a/src/Discord.Net.Core/Net/Rest/IRestClient.cs b/src/Discord.Net.Core/Net/Rest/IRestClient.cs
index 71010f70d..d28fb707e 100644
--- a/src/Discord.Net.Core/Net/Rest/IRestClient.cs
+++ b/src/Discord.Net.Core/Net/Rest/IRestClient.cs
@@ -30,9 +30,13 @@ namespace Discord.Net.Rest
/// The cancellation token used to cancel the task.
/// Indicates whether to send the header only.
/// The audit log reason.
+ /// Additional headers to be sent with the request.
///
- Task SendAsync(string method, string endpoint, CancellationToken cancelToken, bool headerOnly = false, string reason = null);
- Task SendAsync(string method, string endpoint, string json, CancellationToken cancelToken, bool headerOnly = false, string reason = null);
- Task SendAsync(string method, string endpoint, IReadOnlyDictionary multipartParams, CancellationToken cancelToken, bool headerOnly = false, string reason = null);
+ Task SendAsync(string method, string endpoint, CancellationToken cancelToken, bool headerOnly = false, string reason = null,
+ IEnumerable>> requestHeaders = null);
+ Task SendAsync(string method, string endpoint, string json, CancellationToken cancelToken, bool headerOnly = false, string reason = null,
+ IEnumerable>> requestHeaders = null);
+ Task SendAsync(string method, string endpoint, IReadOnlyDictionary multipartParams, CancellationToken cancelToken, bool headerOnly = false, string reason = null,
+ IEnumerable>> requestHeaders = null);
}
}
diff --git a/src/Discord.Net.Core/RequestOptions.cs b/src/Discord.Net.Core/RequestOptions.cs
index 46aa2681f..ef8dbf756 100644
--- a/src/Discord.Net.Core/RequestOptions.cs
+++ b/src/Discord.Net.Core/RequestOptions.cs
@@ -1,5 +1,6 @@
using Discord.Net;
using System;
+using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
@@ -19,7 +20,7 @@ namespace Discord
/// Gets or sets the maximum time to wait for this request to complete.
///
///
- /// Gets or set the max time, in milliseconds, to wait for this request to complete. If
+ /// Gets or set the max time, in milliseconds, to wait for this request to complete. If
/// null, a request will not time out. If a rate limit has been triggered for this request's bucket
/// and will not be unpaused in time, this request will fail immediately.
///
@@ -53,7 +54,7 @@ namespace Discord
///
///
/// This property can also be set in .
- /// On a per-request basis, the system clock should only be disabled
+ /// On a per-request basis, the system clock should only be disabled
/// when millisecond precision is especially important, and the
/// hosting system is known to have a desynced clock.
///
@@ -70,8 +71,10 @@ namespace Discord
internal bool IsReactionBucket { get; set; }
internal bool IsGatewayBucket { get; set; }
+ internal IDictionary> RequestHeaders { get; }
+
internal static RequestOptions CreateOrClone(RequestOptions options)
- {
+ {
if (options == null)
return new RequestOptions();
else
@@ -96,8 +99,9 @@ namespace Discord
public RequestOptions()
{
Timeout = DiscordConfig.DefaultRequestTimeout;
+ RequestHeaders = new Dictionary>();
}
-
+
public RequestOptions Clone() => MemberwiseClone() as RequestOptions;
}
}
diff --git a/src/Discord.Net.Core/Utils/Preconditions.cs b/src/Discord.Net.Core/Utils/Preconditions.cs
index 2f24e660d..fb855f925 100644
--- a/src/Discord.Net.Core/Utils/Preconditions.cs
+++ b/src/Discord.Net.Core/Utils/Preconditions.cs
@@ -55,7 +55,7 @@ namespace Discord
if (obj.Value == null) throw CreateNotNullException(name, msg);
if (obj.Value.Trim().Length == 0) throw CreateNotEmptyException(name, msg);
}
- }
+ }
private static ArgumentException CreateNotEmptyException(string name, string msg)
=> new ArgumentException(message: msg ?? "Argument cannot be blank.", paramName: name);
@@ -129,7 +129,7 @@ namespace Discord
private static ArgumentException CreateNotEqualException(string name, string msg, T value)
=> new ArgumentException(message: msg ?? $"Value may not be equal to {value}.", paramName: name);
-
+
/// Value must be at least .
public static void AtLeast(sbyte obj, sbyte value, string name, string msg = null) { if (obj < value) throw CreateAtLeastException(name, msg, value); }
/// Value must be at least .
@@ -165,7 +165,7 @@ namespace Discord
private static ArgumentException CreateAtLeastException(string name, string msg, T value)
=> new ArgumentException(message: msg ?? $"Value must be at least {value}.", paramName: name);
-
+
/// Value must be greater than .
public static void GreaterThan(sbyte obj, sbyte value, string name, string msg = null) { if (obj <= value) throw CreateGreaterThanException(name, msg, value); }
/// Value must be greater than .
@@ -201,7 +201,7 @@ namespace Discord
private static ArgumentException CreateGreaterThanException(string name, string msg, T value)
=> new ArgumentException(message: msg ?? $"Value must be greater than {value}.", paramName: name);
-
+
/// Value must be at most .
public static void AtMost(sbyte obj, sbyte value, string name, string msg = null) { if (obj > value) throw CreateAtMostException(name, msg, value); }
/// Value must be at most .
@@ -237,7 +237,7 @@ namespace Discord
private static ArgumentException CreateAtMostException(string name, string msg, T value)
=> new ArgumentException(message: msg ?? $"Value must be at most {value}.", paramName: name);
-
+
/// Value must be less than .
public static void LessThan(sbyte obj, sbyte value, string name, string msg = null) { if (obj >= value) throw CreateLessThanException(name, msg, value); }
/// Value must be less than .
diff --git a/src/Discord.Net.Interactions/Attributes/MaxLengthAttribute.cs b/src/Discord.Net.Interactions/Attributes/MaxLengthAttribute.cs
new file mode 100644
index 000000000..2172886d2
--- /dev/null
+++ b/src/Discord.Net.Interactions/Attributes/MaxLengthAttribute.cs
@@ -0,0 +1,25 @@
+using System;
+
+namespace Discord.Interactions
+{
+ ///
+ /// Sets the maximum length allowed for a string type parameter.
+ ///
+ [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = true)]
+ public class MaxLengthAttribute : Attribute
+ {
+ ///
+ /// Gets the maximum length allowed for a string type parameter.
+ ///
+ public int Length { get; }
+
+ ///
+ /// Sets the maximum length allowed for a string type parameter.
+ ///
+ /// Maximum string length allowed.
+ public MaxLengthAttribute(int length)
+ {
+ Length = length;
+ }
+ }
+}
diff --git a/src/Discord.Net.Interactions/Attributes/MinLengthAttribute.cs b/src/Discord.Net.Interactions/Attributes/MinLengthAttribute.cs
new file mode 100644
index 000000000..8050f992a
--- /dev/null
+++ b/src/Discord.Net.Interactions/Attributes/MinLengthAttribute.cs
@@ -0,0 +1,25 @@
+using System;
+
+namespace Discord.Interactions
+{
+ ///
+ /// Sets the minimum length allowed for a string type parameter.
+ ///
+ [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = true)]
+ public class MinLengthAttribute : Attribute
+ {
+ ///
+ /// Gets the minimum length allowed for a string type parameter.
+ ///
+ public int Length { get; }
+
+ ///
+ /// Sets the minimum length allowed for a string type parameter.
+ ///
+ /// Minimum string length allowed.
+ public MinLengthAttribute(int length)
+ {
+ Length = length;
+ }
+ }
+}
diff --git a/src/Discord.Net.Interactions/Attributes/Preconditions/RequireContextAttribute.cs b/src/Discord.Net.Interactions/Attributes/Preconditions/RequireContextAttribute.cs
index 9d1cee8d9..057055ffc 100644
--- a/src/Discord.Net.Interactions/Attributes/Preconditions/RequireContextAttribute.cs
+++ b/src/Discord.Net.Interactions/Attributes/Preconditions/RequireContextAttribute.cs
@@ -58,7 +58,7 @@ namespace Discord.Interactions
if ((Contexts & ContextType.Guild) != 0)
isValid = !context.Interaction.IsDMInteraction;
- if ((Contexts & ContextType.DM) != 0 && (Contexts & ContextType.Group) != 0)
+ if ((Contexts & ContextType.DM) != 0)
isValid = context.Interaction.IsDMInteraction;
if (isValid)
diff --git a/src/Discord.Net.Interactions/Builders/Modals/Inputs/TextInputComponentBuilder.cs b/src/Discord.Net.Interactions/Builders/Modals/Inputs/TextInputComponentBuilder.cs
index 8dd2c4004..728b97a7a 100644
--- a/src/Discord.Net.Interactions/Builders/Modals/Inputs/TextInputComponentBuilder.cs
+++ b/src/Discord.Net.Interactions/Builders/Modals/Inputs/TextInputComponentBuilder.cs
@@ -67,26 +67,26 @@ namespace Discord.Interactions.Builders
///
/// Sets .
///
- /// New value of the .
+ /// New value of the .
///
/// The builder instance.
///
- public TextInputComponentBuilder WithMinLenght(int minLenght)
+ public TextInputComponentBuilder WithMinLength(int minLength)
{
- MinLength = minLenght;
+ MinLength = minLength;
return this;
}
///
/// Sets .
///
- /// New value of the .
+ /// New value of the .
///
/// The builder instance.
///
- public TextInputComponentBuilder WithMaxLenght(int maxLenght)
+ public TextInputComponentBuilder WithMaxLength(int maxLength)
{
- MaxLength = maxLenght;
+ MaxLength = maxLength;
return this;
}
diff --git a/src/Discord.Net.Interactions/Builders/ModuleClassBuilder.cs b/src/Discord.Net.Interactions/Builders/ModuleClassBuilder.cs
index 1bbdfcc4a..35126a674 100644
--- a/src/Discord.Net.Interactions/Builders/ModuleClassBuilder.cs
+++ b/src/Discord.Net.Interactions/Builders/ModuleClassBuilder.cs
@@ -463,6 +463,12 @@ namespace Discord.Interactions.Builders
case MinValueAttribute minValue:
builder.MinValue = minValue.Value;
break;
+ case MinLengthAttribute minLength:
+ builder.MinLength = minLength.Length;
+ break;
+ case MaxLengthAttribute maxLength:
+ builder.MaxLength = maxLength.Length;
+ break;
case ComplexParameterAttribute complexParameter:
{
builder.IsComplexParameter = true;
diff --git a/src/Discord.Net.Interactions/Builders/Parameters/SlashCommandParameterBuilder.cs b/src/Discord.Net.Interactions/Builders/Parameters/SlashCommandParameterBuilder.cs
index d600c9cc7..6f8038cef 100644
--- a/src/Discord.Net.Interactions/Builders/Parameters/SlashCommandParameterBuilder.cs
+++ b/src/Discord.Net.Interactions/Builders/Parameters/SlashCommandParameterBuilder.cs
@@ -28,6 +28,16 @@ namespace Discord.Interactions.Builders
///
public double? MinValue { get; set; }
+ ///
+ /// Gets or sets the minimum length allowed for a string type parameter.
+ ///
+ public int? MinLength { get; set; }
+
+ ///
+ /// Gets or sets the maximum length allowed for a string type parameter.
+ ///
+ public int? MaxLength { get; set; }
+
///
/// Gets a collection of the choices of this command.
///
@@ -125,6 +135,32 @@ namespace Discord.Interactions.Builders
return this;
}
+ ///
+ /// Sets .
+ ///
+ /// New value of the .
+ ///
+ /// The builder instance.
+ ///
+ public SlashCommandParameterBuilder WithMinLength(int length)
+ {
+ MinLength = length;
+ return this;
+ }
+
+ ///
+ /// Sets .
+ ///
+ /// New value of the .
+ ///
+ /// The builder instance.
+ ///
+ public SlashCommandParameterBuilder WithMaxLength(int length)
+ {
+ MaxLength = length;
+ return this;
+ }
+
///
/// Adds parameter choices to .
///
diff --git a/src/Discord.Net.Interactions/Extensions/IDiscordInteractionExtensions.cs b/src/Discord.Net.Interactions/Extensions/IDiscordInteractionExtensions.cs
index 8f0987661..d970b9930 100644
--- a/src/Discord.Net.Interactions/Extensions/IDiscordInteractionExtensions.cs
+++ b/src/Discord.Net.Interactions/Extensions/IDiscordInteractionExtensions.cs
@@ -19,9 +19,36 @@ namespace Discord.Interactions
if (!ModalUtils.TryGet(out var modalInfo))
throw new ArgumentException($"{typeof(T).FullName} isn't referenced by any registered Modal Interaction Command and doesn't have a cached {typeof(ModalInfo)}");
+ await SendModalResponseAsync(interaction, customId, modalInfo, options, modifyModal);
+ }
+
+ ///
+ /// Respond to an interaction with a .
+ ///
+ ///
+ /// This method overload uses the parameter to create a new
+ /// if there isn't a built one already in cache.
+ ///
+ /// Type of the implementation.
+ /// The interaction to respond to.
+ /// Interaction service instance that should be used to build s.
+ /// The request options for this request.
+ /// Delegate that can be used to modify the modal.
+ ///
+ public static async Task RespondWithModalAsync(this IDiscordInteraction interaction, string customId, InteractionService interactionService,
+ RequestOptions options = null, Action modifyModal = null)
+ where T : class, IModal
+ {
+ var modalInfo = ModalUtils.GetOrAdd(interactionService);
+
+ await SendModalResponseAsync(interaction, customId, modalInfo, options, modifyModal);
+ }
+
+ private static async Task SendModalResponseAsync(IDiscordInteraction interaction, string customId, ModalInfo modalInfo, RequestOptions options = null, Action modifyModal = null)
+ {
var builder = new ModalBuilder(modalInfo.Title, customId);
- foreach(var input in modalInfo.Components)
+ foreach (var input in modalInfo.Components)
switch (input)
{
case TextInputComponentInfo textComponent:
diff --git a/src/Discord.Net.Interactions/Info/Parameters/SlashCommandParameterInfo.cs b/src/Discord.Net.Interactions/Info/Parameters/SlashCommandParameterInfo.cs
index 8702d69f7..0bce42186 100644
--- a/src/Discord.Net.Interactions/Info/Parameters/SlashCommandParameterInfo.cs
+++ b/src/Discord.Net.Interactions/Info/Parameters/SlashCommandParameterInfo.cs
@@ -38,6 +38,16 @@ namespace Discord.Interactions
///
public double? MaxValue { get; }
+ ///
+ /// Gets the minimum length allowed for a string type parameter.
+ ///
+ public int? MinLength { get; }
+
+ ///
+ /// Gets the maximum length allowed for a string type parameter.
+ ///
+ public int? MaxLength { get; }
+
///
/// Gets the that will be used to convert the incoming into
/// .
@@ -86,6 +96,8 @@ namespace Discord.Interactions
Description = builder.Description;
MaxValue = builder.MaxValue;
MinValue = builder.MinValue;
+ MinLength = builder.MinLength;
+ MaxLength = builder.MaxLength;
IsComplexParameter = builder.IsComplexParameter;
IsAutocomplete = builder.Autocomplete;
Choices = builder.Choices.ToImmutableArray();
diff --git a/src/Discord.Net.Interactions/InteractionService.cs b/src/Discord.Net.Interactions/InteractionService.cs
index f57c75a31..50c1f5546 100644
--- a/src/Discord.Net.Interactions/InteractionService.cs
+++ b/src/Discord.Net.Interactions/InteractionService.cs
@@ -83,6 +83,11 @@ namespace Discord.Interactions
public event Func ModalCommandExecuted { add { _modalCommandExecutedEvent.Add(value); } remove { _modalCommandExecutedEvent.Remove(value); } }
internal readonly AsyncEvent> _modalCommandExecutedEvent = new();
+ ///
+ /// Get the used by this Interaction Service instance to localize strings.
+ ///
+ public ILocalizationManager LocalizationManager { get; set; }
+
private readonly ConcurrentDictionary _typedModuleDefs;
private readonly CommandMap _slashCommandMap;
private readonly ConcurrentDictionary> _contextCommandMaps;
@@ -203,6 +208,7 @@ namespace Discord.Interactions
_enableAutocompleteHandlers = config.EnableAutocompleteHandlers;
_autoServiceScopes = config.AutoServiceScopes;
_restResponseCallback = config.RestResponseCallback;
+ LocalizationManager = config.LocalizationManager;
_typeConverterMap = new TypeMap(this, new ConcurrentDictionary
{
@@ -426,17 +432,36 @@ namespace Discord.Interactions
/// use . Registering a commands without group names might cause the command traversal to fail.
///
/// The target guild.
+ /// If , this operation will not delete the commands that are missing from .
/// Commands to be registered to Discord.
///
/// A task representing the command registration process. The task result contains the active application commands of the target guild.
///
public async Task> AddCommandsToGuildAsync(IGuild guild, bool deleteMissing = false, params ICommandInfo[] commands)
{
- EnsureClientReady();
-
if (guild is null)
throw new ArgumentNullException(nameof(guild));
+ return await AddCommandsToGuildAsync(guild.Id, deleteMissing, commands).ConfigureAwait(false);
+ }
+
+ ///
+ /// Register Application Commands from to a guild.
+ ///
+ ///
+ /// Commands will be registered as standalone commands, if you want the to take effect,
+ /// use . Registering a commands without group names might cause the command traversal to fail.
+ ///
+ /// The target guild ID.
+ /// If , this operation will not delete the commands that are missing from .
+ /// Commands to be registered to Discord.
+ ///
+ /// A task representing the command registration process. The task result contains the active application commands of the target guild.
+ ///
+ public async Task> AddCommandsToGuildAsync(ulong guildId, bool deleteMissing = false, params ICommandInfo[] commands)
+ {
+ EnsureClientReady();
+
var props = new List();
foreach (var command in commands)
@@ -456,44 +481,60 @@ namespace Discord.Interactions
if (!deleteMissing)
{
- var existing = await RestClient.GetGuildApplicationCommands(guild.Id).ConfigureAwait(false);
+ var existing = await RestClient.GetGuildApplicationCommands(guildId).ConfigureAwait(false);
var missing = existing.Where(x => !props.Any(y => y.Name.IsSpecified && y.Name.Value == x.Name));
props.AddRange(missing.Select(x => x.ToApplicationCommandProps()));
}
- return await RestClient.BulkOverwriteGuildCommands(props.ToArray(), guild.Id).ConfigureAwait(false);
+ return await RestClient.BulkOverwriteGuildCommands(props.ToArray(), guildId).ConfigureAwait(false);
}
///
/// Register Application Commands from modules provided in to a guild.
///
/// The target guild.
+ /// If , this operation will not delete the commands that are missing from .
/// Modules to be registered to Discord.
///
/// A task representing the command registration process. The task result contains the active application commands of the target guild.
///
public async Task> AddModulesToGuildAsync(IGuild guild, bool deleteMissing = false, params ModuleInfo[] modules)
{
- EnsureClientReady();
-
if (guild is null)
throw new ArgumentNullException(nameof(guild));
+ return await AddModulesToGuildAsync(guild.Id, deleteMissing, modules).ConfigureAwait(false);
+ }
+
+ ///
+ /// Register Application Commands from modules provided in to a guild.
+ ///
+ /// The target guild ID.
+ /// If , this operation will not delete the commands that are missing from .
+ /// Modules to be registered to Discord.
+ ///
+ /// A task representing the command registration process. The task result contains the active application commands of the target guild.
+ ///
+ public async Task> AddModulesToGuildAsync(ulong guildId, bool deleteMissing = false, params ModuleInfo[] modules)
+ {
+ EnsureClientReady();
+
var props = modules.SelectMany(x => x.ToApplicationCommandProps(true)).ToList();
if (!deleteMissing)
{
- var existing = await RestClient.GetGuildApplicationCommands(guild.Id).ConfigureAwait(false);
+ var existing = await RestClient.GetGuildApplicationCommands(guildId).ConfigureAwait(false);
var missing = existing.Where(x => !props.Any(y => y.Name.IsSpecified && y.Name.Value == x.Name));
props.AddRange(missing.Select(x => x.ToApplicationCommandProps()));
}
- return await RestClient.BulkOverwriteGuildCommands(props.ToArray(), guild.Id).ConfigureAwait(false);
+ return await RestClient.BulkOverwriteGuildCommands(props.ToArray(), guildId).ConfigureAwait(false);
}
///
/// Register Application Commands from modules provided in as global commands.
///
+ /// If , this operation will not delete the commands that are missing from .
/// Modules to be registered to Discord.
///
/// A task representing the command registration process. The task result contains the active application commands of the target guild.
@@ -521,6 +562,7 @@ namespace Discord.Interactions
/// Commands will be registered as standalone commands, if you want the to take effect,
/// use . Registering a commands without group names might cause the command traversal to fail.
///
+ /// If , this operation will not delete the commands that are missing from .
/// Commands to be registered to Discord.
///
/// A task representing the command registration process. The task result contains the active application commands of the target guild.
@@ -1086,19 +1128,40 @@ namespace Discord.Interactions
///
/// The active command permissions after the modification.
///
- public async Task ModifySlashCommandPermissionsAsync (ModuleInfo module, IGuild guild,
+ public async Task ModifySlashCommandPermissionsAsync(ModuleInfo module, IGuild guild,
+ params ApplicationCommandPermission[] permissions)
+ {
+ if (module is null)
+ throw new ArgumentNullException(nameof(module));
+
+ if (guild is null)
+ throw new ArgumentNullException(nameof(guild));
+
+ return await ModifySlashCommandPermissionsAsync(module, guild.Id, permissions).ConfigureAwait(false);
+ }
+
+ ///
+ /// Modify the command permissions of the matching Discord Slash Command.
+ ///
+ /// Module representing the top level Slash Command.
+ /// Target guild ID.
+ /// New permission values.
+ ///
+ /// The active command permissions after the modification.
+ ///
+ public async Task ModifySlashCommandPermissionsAsync(ModuleInfo module, ulong guildId,
params ApplicationCommandPermission[] permissions)
{
+ if (module is null)
+ throw new ArgumentNullException(nameof(module));
+
if (!module.IsSlashGroup)
throw new InvalidOperationException($"This module does not have a {nameof(GroupAttribute)} and does not represent an Application Command");
if (!module.IsTopLevelGroup)
throw new InvalidOperationException("This module is not a top level application command. You cannot change its permissions");
- if (guild is null)
- throw new ArgumentNullException("guild");
-
- var commands = await RestClient.GetGuildApplicationCommands(guild.Id).ConfigureAwait(false);
+ var commands = await RestClient.GetGuildApplicationCommands(guildId).ConfigureAwait(false);
var appCommand = commands.First(x => x.Name == module.SlashGroupName);
return await appCommand.ModifyCommandPermissions(permissions).ConfigureAwait(false);
@@ -1113,9 +1176,29 @@ namespace Discord.Interactions
///
/// The active command permissions after the modification.
///
- public async Task ModifySlashCommandPermissionsAsync (SlashCommandInfo command, IGuild guild,
- params ApplicationCommandPermission[] permissions) =>
- await ModifyApplicationCommandPermissionsAsync(command, guild, permissions).ConfigureAwait(false);
+ public async Task ModifySlashCommandPermissionsAsync(SlashCommandInfo command, IGuild guild,
+ params ApplicationCommandPermission[] permissions)
+ {
+ if (command is null)
+ throw new ArgumentNullException(nameof(command));
+
+ if (guild is null)
+ throw new ArgumentNullException(nameof(guild));
+
+ return await ModifyApplicationCommandPermissionsAsync(command, guild.Id, permissions).ConfigureAwait(false);
+ }
+
+ ///
+ /// Modify the command permissions of the matching Discord Slash Command.
+ ///
+ /// The Slash Command.
+ /// Target guild ID.
+ /// New permission values.
+ ///
+ /// The active command permissions after the modification.
+ ///
+ public async Task ModifySlashCommandPermissionsAsync(SlashCommandInfo command, ulong guildId,
+ params ApplicationCommandPermission[] permissions) => await ModifyApplicationCommandPermissionsAsync(command, guildId, permissions).ConfigureAwait(false);
///
/// Modify the command permissions of the matching Discord Slash Command.
@@ -1126,20 +1209,40 @@ namespace Discord.Interactions
///
/// The active command permissions after the modification.
///
- public async Task ModifyContextCommandPermissionsAsync (ContextCommandInfo command, IGuild guild,
- params ApplicationCommandPermission[] permissions) =>
- await ModifyApplicationCommandPermissionsAsync(command, guild, permissions).ConfigureAwait(false);
+ public async Task ModifyContextCommandPermissionsAsync(ContextCommandInfo command, IGuild guild,
+ params ApplicationCommandPermission[] permissions)
+ {
+ if (command is null)
+ throw new ArgumentNullException(nameof(command));
+
+ if (guild is null)
+ throw new ArgumentNullException(nameof(guild));
+
+ return await ModifyApplicationCommandPermissionsAsync(command, guild.Id, permissions).ConfigureAwait(false);
+ }
- private async Task ModifyApplicationCommandPermissionsAsync (T command, IGuild guild,
+ ///
+ /// Modify the command permissions of the matching Discord Slash Command.
+ ///
+ /// The Context Command.
+ /// Target guild ID.
+ /// New permission values.
+ ///
+ /// The active command permissions after the modification.
+ ///
+ public async Task ModifyContextCommandPermissionsAsync(ContextCommandInfo command, ulong guildId,
+ params ApplicationCommandPermission[] permissions) => await ModifyApplicationCommandPermissionsAsync(command, guildId, permissions).ConfigureAwait(false);
+
+ private async Task ModifyApplicationCommandPermissionsAsync (T command, ulong guildId,
params ApplicationCommandPermission[] permissions) where T : class, IApplicationCommandInfo, ICommandInfo
{
+ if (command is null)
+ throw new ArgumentNullException(nameof(command));
+
if (!command.IsTopLevelCommand)
throw new InvalidOperationException("This command is not a top level application command. You cannot change its permissions");
- if (guild is null)
- throw new ArgumentNullException("guild");
-
- var commands = await RestClient.GetGuildApplicationCommands(guild.Id).ConfigureAwait(false);
+ var commands = await RestClient.GetGuildApplicationCommands(guildId).ConfigureAwait(false);
var appCommand = commands.First(x => x.Name == ( command as IApplicationCommandInfo ).Name);
return await appCommand.ModifyCommandPermissions(permissions).ConfigureAwait(false);
diff --git a/src/Discord.Net.Interactions/InteractionServiceConfig.cs b/src/Discord.Net.Interactions/InteractionServiceConfig.cs
index b6576a49f..b9102bc5f 100644
--- a/src/Discord.Net.Interactions/InteractionServiceConfig.cs
+++ b/src/Discord.Net.Interactions/InteractionServiceConfig.cs
@@ -64,6 +64,11 @@ namespace Discord.Interactions
/// Gets or sets whether a command execution should exit when a modal command encounters a missing modal component value.
///
public bool ExitOnMissingModalField { get; set; } = false;
+
+ ///
+ /// Localization provider to be used when registering application commands.
+ ///
+ public ILocalizationManager LocalizationManager { get; set; }
}
///
diff --git a/src/Discord.Net.Interactions/LocalizationManagers/ILocalizationManager.cs b/src/Discord.Net.Interactions/LocalizationManagers/ILocalizationManager.cs
new file mode 100644
index 000000000..13b155292
--- /dev/null
+++ b/src/Discord.Net.Interactions/LocalizationManagers/ILocalizationManager.cs
@@ -0,0 +1,32 @@
+using System;
+using System.Collections.Generic;
+using System.Threading.Tasks;
+
+namespace Discord.Interactions
+{
+ ///
+ /// Respresents a localization provider for Discord Application Commands.
+ ///
+ public interface ILocalizationManager
+ {
+ ///
+ /// Get every the resource name for every available locale.
+ ///
+ /// Location of the resource.
+ /// Type of the resource.
+ ///
+ /// A dictionary containing every available locale and the resource name.
+ ///
+ IDictionary GetAllNames(IList key, LocalizationTarget destinationType);
+
+ ///
+ /// Get every the resource description for every available locale.
+ ///
+ /// Location of the resource.
+ /// Type of the resource.
+ ///
+ /// A dictionary containing every available locale and the resource name.
+ ///
+ IDictionary GetAllDescriptions(IList key, LocalizationTarget destinationType);
+ }
+}
diff --git a/src/Discord.Net.Interactions/LocalizationManagers/JsonLocalizationManager.cs b/src/Discord.Net.Interactions/LocalizationManagers/JsonLocalizationManager.cs
new file mode 100644
index 000000000..010fb3bdd
--- /dev/null
+++ b/src/Discord.Net.Interactions/LocalizationManagers/JsonLocalizationManager.cs
@@ -0,0 +1,72 @@
+using Newtonsoft.Json;
+using Newtonsoft.Json.Linq;
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using System.Text.RegularExpressions;
+using System.Threading.Tasks;
+
+namespace Discord.Interactions
+{
+ ///
+ /// The default localization provider for Json resource files.
+ ///
+ public sealed class JsonLocalizationManager : ILocalizationManager
+ {
+ private const string NameIdentifier = "name";
+ private const string DescriptionIdentifier = "description";
+ private const string SpaceToken = "~";
+
+ private readonly string _basePath;
+ private readonly string _fileName;
+ private readonly Regex _localeParserRegex = new Regex(@"\w+.(?\w{2}(?:-\w{2})?).json", RegexOptions.Compiled | RegexOptions.Singleline);
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Base path of the Json file.
+ /// Name of the Json file.
+ public JsonLocalizationManager(string basePath, string fileName)
+ {
+ _basePath = basePath;
+ _fileName = fileName;
+ }
+
+ ///
+ public IDictionary GetAllDescriptions(IList key, LocalizationTarget destinationType) =>
+ GetValues(key, DescriptionIdentifier);
+
+ ///
+ public IDictionary GetAllNames(IList key, LocalizationTarget destinationType) =>
+ GetValues(key, NameIdentifier);
+
+ private string[] GetAllFiles() =>
+ Directory.GetFiles(_basePath, $"{_fileName}.*.json", SearchOption.TopDirectoryOnly);
+
+ private IDictionary GetValues(IList key, string identifier)
+ {
+ var result = new Dictionary();
+ var files = GetAllFiles();
+
+ foreach (var file in files)
+ {
+ var match = _localeParserRegex.Match(Path.GetFileName(file));
+ if (!match.Success)
+ continue;
+
+ var locale = match.Groups["locale"].Value;
+
+ using var sr = new StreamReader(file);
+ using var jr = new JsonTextReader(sr);
+ var obj = JObject.Load(jr);
+ var token = string.Join(".", key.Select(x => $"['{x}']")) + $".{identifier}";
+ var value = (string)obj.SelectToken(token);
+ if (value is not null)
+ result[locale] = value;
+ }
+
+ return result;
+ }
+ }
+}
diff --git a/src/Discord.Net.Interactions/LocalizationManagers/ResxLocalizationManager.cs b/src/Discord.Net.Interactions/LocalizationManagers/ResxLocalizationManager.cs
new file mode 100644
index 000000000..a110602f2
--- /dev/null
+++ b/src/Discord.Net.Interactions/LocalizationManagers/ResxLocalizationManager.cs
@@ -0,0 +1,55 @@
+using System.Collections.Generic;
+using System.Globalization;
+using System.Reflection;
+using System.Resources;
+
+namespace Discord.Interactions
+{
+ ///
+ /// The default localization provider for Resx files.
+ ///
+ public sealed class ResxLocalizationManager : ILocalizationManager
+ {
+ private const string NameIdentifier = "name";
+ private const string DescriptionIdentifier = "description";
+
+ private readonly ResourceManager _resourceManager;
+ private readonly IEnumerable _supportedLocales;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Name of the base resource.
+ /// The main assembly for the resources.
+ /// Cultures the should search for.
+ public ResxLocalizationManager(string baseResource, Assembly assembly, params CultureInfo[] supportedLocales)
+ {
+ _supportedLocales = supportedLocales;
+ _resourceManager = new ResourceManager(baseResource, assembly);
+ }
+
+ ///
+ public IDictionary GetAllDescriptions(IList key, LocalizationTarget destinationType) =>
+ GetValues(key, DescriptionIdentifier);
+
+ ///
+ public IDictionary GetAllNames(IList key, LocalizationTarget destinationType) =>
+ GetValues(key, NameIdentifier);
+
+ private IDictionary GetValues(IList key, string identifier)
+ {
+ var entryKey = (string.Join(".", key) + "." + identifier);
+
+ var result = new Dictionary();
+
+ foreach (var locale in _supportedLocales)
+ {
+ var value = _resourceManager.GetString(entryKey, locale);
+ if (value is not null)
+ result[locale.Name] = value;
+ }
+
+ return result;
+ }
+ }
+}
diff --git a/src/Discord.Net.Interactions/LocalizationTarget.cs b/src/Discord.Net.Interactions/LocalizationTarget.cs
new file mode 100644
index 000000000..cf54d3375
--- /dev/null
+++ b/src/Discord.Net.Interactions/LocalizationTarget.cs
@@ -0,0 +1,25 @@
+namespace Discord.Interactions
+{
+ ///
+ /// Resource targets for localization.
+ ///
+ public enum LocalizationTarget
+ {
+ ///
+ /// Target is a tagged with a .
+ ///
+ Group,
+ ///
+ /// Target is an application command method.
+ ///
+ Command,
+ ///
+ /// Target is a Slash Command parameter.
+ ///
+ Parameter,
+ ///
+ /// Target is a Slash Command parameter choice.
+ ///
+ Choice
+ }
+}
diff --git a/src/Discord.Net.Interactions/Map/CommandMap.cs b/src/Discord.Net.Interactions/Map/CommandMap.cs
index 2e7bf5368..336e2b1ec 100644
--- a/src/Discord.Net.Interactions/Map/CommandMap.cs
+++ b/src/Discord.Net.Interactions/Map/CommandMap.cs
@@ -42,7 +42,7 @@ namespace Discord.Interactions
public void RemoveCommand(T command)
{
- var key = ParseCommandName(command);
+ var key = CommandHierarchy.GetCommandPath(command);
_root.RemoveCommand(key, 0);
}
@@ -60,28 +60,9 @@ namespace Discord.Interactions
private void AddCommand(T command)
{
- var key = ParseCommandName(command);
+ var key = CommandHierarchy.GetCommandPath(command);
_root.AddCommand(key, 0, command);
}
-
- private IList ParseCommandName(T command)
- {
- var keywords = new List() { command.Name };
-
- var currentParent = command.Module;
-
- while (currentParent != null)
- {
- if (!string.IsNullOrEmpty(currentParent.SlashGroupName))
- keywords.Add(currentParent.SlashGroupName);
-
- currentParent = currentParent.Parent;
- }
-
- keywords.Reverse();
-
- return keywords;
- }
}
}
diff --git a/src/Discord.Net.Interactions/TypeConverters/SlashCommands/NullableConverter.cs b/src/Discord.Net.Interactions/TypeConverters/SlashCommands/NullableConverter.cs
index 874171175..d85b376d1 100644
--- a/src/Discord.Net.Interactions/TypeConverters/SlashCommands/NullableConverter.cs
+++ b/src/Discord.Net.Interactions/TypeConverters/SlashCommands/NullableConverter.cs
@@ -9,10 +9,11 @@ namespace Discord.Interactions
public NullableConverter(InteractionService interactionService, IServiceProvider services)
{
- var type = Nullable.GetUnderlyingType(typeof(T));
+ var nullableType = typeof(T);
+ var type = Nullable.GetUnderlyingType(nullableType);
if (type is null)
- throw new ArgumentException($"No type {nameof(TypeConverter)} is defined for this {type.FullName}", "type");
+ throw new ArgumentException($"No type {nameof(TypeConverter)} is defined for this {nullableType.FullName}", nameof(type));
_typeConverter = interactionService.GetTypeConverter(type, services);
}
diff --git a/src/Discord.Net.Interactions/Utilities/ApplicationCommandRestUtil.cs b/src/Discord.Net.Interactions/Utilities/ApplicationCommandRestUtil.cs
index e4b6f893c..9b507f1bb 100644
--- a/src/Discord.Net.Interactions/Utilities/ApplicationCommandRestUtil.cs
+++ b/src/Discord.Net.Interactions/Utilities/ApplicationCommandRestUtil.cs
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
+using System.Collections.Immutable;
using System.Linq;
namespace Discord.Interactions
@@ -9,6 +10,9 @@ namespace Discord.Interactions
#region Parameters
public static ApplicationCommandOptionProperties ToApplicationCommandOptionProps(this SlashCommandParameterInfo parameterInfo)
{
+ var localizationManager = parameterInfo.Command.Module.CommandService.LocalizationManager;
+ var parameterPath = parameterInfo.GetParameterPath();
+
var props = new ApplicationCommandOptionProperties
{
Name = parameterInfo.Name,
@@ -18,12 +22,17 @@ namespace Discord.Interactions
Choices = parameterInfo.Choices?.Select(x => new ApplicationCommandOptionChoiceProperties
{
Name = x.Name,
- Value = x.Value
+ Value = x.Value,
+ NameLocalizations = localizationManager?.GetAllNames(parameterInfo.GetChoicePath(x), LocalizationTarget.Choice) ?? ImmutableDictionary.Empty
})?.ToList(),
ChannelTypes = parameterInfo.ChannelTypes?.ToList(),
IsAutocomplete = parameterInfo.IsAutocomplete,
MaxValue = parameterInfo.MaxValue,
- MinValue = parameterInfo.MinValue
+ MinValue = parameterInfo.MinValue,
+ NameLocalizations = localizationManager?.GetAllNames(parameterPath, LocalizationTarget.Parameter) ?? ImmutableDictionary.Empty,
+ DescriptionLocalizations = localizationManager?.GetAllDescriptions(parameterPath, LocalizationTarget.Parameter) ?? ImmutableDictionary.Empty,
+ MinLength = parameterInfo.MinLength,
+ MaxLength = parameterInfo.MaxLength,
};
parameterInfo.TypeConverter.Write(props, parameterInfo);
@@ -36,13 +45,19 @@ namespace Discord.Interactions
public static SlashCommandProperties ToApplicationCommandProps(this SlashCommandInfo commandInfo)
{
+ var commandPath = commandInfo.GetCommandPath();
+ var localizationManager = commandInfo.Module.CommandService.LocalizationManager;
+
var props = new SlashCommandBuilder()
{
Name = commandInfo.Name,
Description = commandInfo.Description,
+ IsDefaultPermission = commandInfo.DefaultPermission,
IsDMEnabled = commandInfo.IsEnabledInDm,
DefaultMemberPermissions = ((commandInfo.DefaultMemberPermissions ?? 0) | (commandInfo.Module.DefaultMemberPermissions ?? 0)).SanitizeGuildPermissions(),
- }.Build();
+ }.WithNameLocalizations(localizationManager?.GetAllNames(commandPath, LocalizationTarget.Command) ?? ImmutableDictionary.Empty)
+ .WithDescriptionLocalizations(localizationManager?.GetAllDescriptions(commandPath, LocalizationTarget.Command) ?? ImmutableDictionary.Empty)
+ .Build();
if (commandInfo.Parameters.Count > SlashCommandBuilder.MaxOptionsCount)
throw new InvalidOperationException($"Slash Commands cannot have more than {SlashCommandBuilder.MaxOptionsCount} command parameters");
@@ -52,18 +67,30 @@ namespace Discord.Interactions
return props;
}
- public static ApplicationCommandOptionProperties ToApplicationCommandOptionProps(this SlashCommandInfo commandInfo) =>
- new ApplicationCommandOptionProperties
+ public static ApplicationCommandOptionProperties ToApplicationCommandOptionProps(this SlashCommandInfo commandInfo)
+ {
+ var localizationManager = commandInfo.Module.CommandService.LocalizationManager;
+ var commandPath = commandInfo.GetCommandPath();
+
+ return new ApplicationCommandOptionProperties
{
Name = commandInfo.Name,
Description = commandInfo.Description,
Type = ApplicationCommandOptionType.SubCommand,
IsRequired = false,
- Options = commandInfo.FlattenedParameters?.Select(x => x.ToApplicationCommandOptionProps())?.ToList()
+ Options = commandInfo.FlattenedParameters?.Select(x => x.ToApplicationCommandOptionProps())
+ ?.ToList(),
+ NameLocalizations = localizationManager?.GetAllNames(commandPath, LocalizationTarget.Command) ?? ImmutableDictionary.Empty,
+ DescriptionLocalizations = localizationManager?.GetAllDescriptions(commandPath, LocalizationTarget.Command) ?? ImmutableDictionary.Empty
};
+ }
public static ApplicationCommandProperties ToApplicationCommandProps(this ContextCommandInfo commandInfo)
- => commandInfo.CommandType switch
+ {
+ var localizationManager = commandInfo.Module.CommandService.LocalizationManager;
+ var commandPath = commandInfo.GetCommandPath();
+
+ return commandInfo.CommandType switch
{
ApplicationCommandType.Message => new MessageCommandBuilder
{
@@ -71,16 +98,21 @@ namespace Discord.Interactions
IsDefaultPermission = commandInfo.DefaultPermission,
DefaultMemberPermissions = ((commandInfo.DefaultMemberPermissions ?? 0) | (commandInfo.Module.DefaultMemberPermissions ?? 0)).SanitizeGuildPermissions(),
IsDMEnabled = commandInfo.IsEnabledInDm
- }.Build(),
+ }
+ .WithNameLocalizations(localizationManager?.GetAllNames(commandPath, LocalizationTarget.Command) ?? ImmutableDictionary.Empty)
+ .Build(),
ApplicationCommandType.User => new UserCommandBuilder
{
Name = commandInfo.Name,
IsDefaultPermission = commandInfo.DefaultPermission,
DefaultMemberPermissions = ((commandInfo.DefaultMemberPermissions ?? 0) | (commandInfo.Module.DefaultMemberPermissions ?? 0)).SanitizeGuildPermissions(),
IsDMEnabled = commandInfo.IsEnabledInDm
- }.Build(),
+ }
+ .WithNameLocalizations(localizationManager?.GetAllNames(commandPath, LocalizationTarget.Command) ?? ImmutableDictionary.Empty)
+ .Build(),
_ => throw new InvalidOperationException($"{commandInfo.CommandType} isn't a supported command type.")
};
+ }
#endregion
#region Modules
@@ -121,6 +153,9 @@ namespace Discord.Interactions
options.AddRange(moduleInfo.SubModules?.SelectMany(x => x.ParseSubModule(args, ignoreDontRegister)));
+ var localizationManager = moduleInfo.CommandService.LocalizationManager;
+ var modulePath = moduleInfo.GetModulePath();
+
var props = new SlashCommandBuilder
{
Name = moduleInfo.SlashGroupName,
@@ -128,7 +163,10 @@ namespace Discord.Interactions
IsDefaultPermission = moduleInfo.DefaultPermission,
IsDMEnabled = moduleInfo.IsEnabledInDm,
DefaultMemberPermissions = moduleInfo.DefaultMemberPermissions
- }.Build();
+ }
+ .WithNameLocalizations(localizationManager?.GetAllNames(modulePath, LocalizationTarget.Group) ?? ImmutableDictionary.Empty)
+ .WithDescriptionLocalizations(localizationManager?.GetAllDescriptions(modulePath, LocalizationTarget.Group) ?? ImmutableDictionary.Empty)
+ .Build();
if (options.Count > SlashCommandBuilder.MaxOptionsCount)
throw new InvalidOperationException($"Slash Commands cannot have more than {SlashCommandBuilder.MaxOptionsCount} command parameters");
@@ -166,7 +204,11 @@ namespace Discord.Interactions
Name = moduleInfo.SlashGroupName,
Description = moduleInfo.Description,
Type = ApplicationCommandOptionType.SubCommandGroup,
- Options = options
+ Options = options,
+ NameLocalizations = moduleInfo.CommandService.LocalizationManager?.GetAllNames(moduleInfo.GetModulePath(), LocalizationTarget.Group)
+ ?? ImmutableDictionary.Empty,
+ DescriptionLocalizations = moduleInfo.CommandService.LocalizationManager?.GetAllDescriptions(moduleInfo.GetModulePath(), LocalizationTarget.Group)
+ ?? ImmutableDictionary.Empty,
} };
}
@@ -181,17 +223,29 @@ namespace Discord.Interactions
Name = command.Name,
Description = command.Description,
IsDefaultPermission = command.IsDefaultPermission,
- Options = command.Options?.Select(x => x.ToApplicationCommandOptionProps())?.ToList() ?? Optional>.Unspecified
+ DefaultMemberPermissions = (GuildPermission)command.DefaultMemberPermissions.RawValue,
+ IsDMEnabled = command.IsEnabledInDm,
+ Options = command.Options?.Select(x => x.ToApplicationCommandOptionProps())?.ToList() ?? Optional>.Unspecified,
+ NameLocalizations = command.NameLocalizations?.ToImmutableDictionary() ?? ImmutableDictionary.Empty,
+ DescriptionLocalizations = command.DescriptionLocalizations?.ToImmutableDictionary() ?? ImmutableDictionary.Empty,
},
ApplicationCommandType.User => new UserCommandProperties
{
Name = command.Name,
- IsDefaultPermission = command.IsDefaultPermission
+ IsDefaultPermission = command.IsDefaultPermission,
+ DefaultMemberPermissions = (GuildPermission)command.DefaultMemberPermissions.RawValue,
+ IsDMEnabled = command.IsEnabledInDm,
+ NameLocalizations = command.NameLocalizations?.ToImmutableDictionary() ?? ImmutableDictionary.Empty,
+ DescriptionLocalizations = command.DescriptionLocalizations?.ToImmutableDictionary() ?? ImmutableDictionary.Empty
},
ApplicationCommandType.Message => new MessageCommandProperties
{
Name = command.Name,
- IsDefaultPermission = command.IsDefaultPermission
+ IsDefaultPermission = command.IsDefaultPermission,
+ DefaultMemberPermissions = (GuildPermission)command.DefaultMemberPermissions.RawValue,
+ IsDMEnabled = command.IsEnabledInDm,
+ NameLocalizations = command.NameLocalizations?.ToImmutableDictionary() ?? ImmutableDictionary.Empty,
+ DescriptionLocalizations = command.DescriptionLocalizations?.ToImmutableDictionary() ?? ImmutableDictionary.Empty
},
_ => throw new InvalidOperationException($"Cannot create command properties for command type {command.Type}"),
};
@@ -204,12 +258,20 @@ namespace Discord.Interactions
Description = commandOption.Description,
Type = commandOption.Type,
IsRequired = commandOption.IsRequired,
+ ChannelTypes = commandOption.ChannelTypes?.ToList(),
+ IsAutocomplete = commandOption.IsAutocomplete.GetValueOrDefault(),
+ MinValue = commandOption.MinValue,
+ MaxValue = commandOption.MaxValue,
Choices = commandOption.Choices?.Select(x => new ApplicationCommandOptionChoiceProperties
{
Name = x.Name,
Value = x.Value
}).ToList(),
- Options = commandOption.Options?.Select(x => x.ToApplicationCommandOptionProps()).ToList()
+ Options = commandOption.Options?.Select(x => x.ToApplicationCommandOptionProps()).ToList(),
+ NameLocalizations = commandOption.NameLocalizations?.ToImmutableDictionary(),
+ DescriptionLocalizations = commandOption.DescriptionLocalizations?.ToImmutableDictionary(),
+ MaxLength = commandOption.MaxLength,
+ MinLength = commandOption.MinLength,
};
public static Modal ToModal(this ModalInfo modalInfo, string customId, Action modifyModal = null)
diff --git a/src/Discord.Net.Interactions/Utilities/CommandHierarchy.cs b/src/Discord.Net.Interactions/Utilities/CommandHierarchy.cs
new file mode 100644
index 000000000..da7ef22e0
--- /dev/null
+++ b/src/Discord.Net.Interactions/Utilities/CommandHierarchy.cs
@@ -0,0 +1,53 @@
+using System;
+using System.Collections.Generic;
+
+namespace Discord.Interactions
+{
+ internal static class CommandHierarchy
+ {
+ public const char EscapeChar = '$';
+
+ public static IList GetModulePath(this ModuleInfo moduleInfo)
+ {
+ var result = new List();
+
+ var current = moduleInfo;
+ while (current is not null)
+ {
+ if (current.IsSlashGroup)
+ result.Insert(0, current.SlashGroupName);
+
+ current = current.Parent;
+ }
+
+ return result;
+ }
+
+ public static IList GetCommandPath(this ICommandInfo commandInfo)
+ {
+ if (commandInfo.IgnoreGroupNames)
+ return new List { commandInfo.Name };
+
+ var path = commandInfo.Module.GetModulePath();
+ path.Add(commandInfo.Name);
+ return path;
+ }
+
+ public static IList GetParameterPath(this IParameterInfo parameterInfo)
+ {
+ var path = parameterInfo.Command.GetCommandPath();
+ path.Add(parameterInfo.Name);
+ return path;
+ }
+
+ public static IList GetChoicePath(this IParameterInfo parameterInfo, ParameterChoice choice)
+ {
+ var path = parameterInfo.GetParameterPath();
+ path.Add(choice.Name);
+ return path;
+ }
+
+ public static IList GetTypePath(Type type) =>
+ new List { EscapeChar + type.FullName };
+ }
+}
diff --git a/src/Discord.Net.Rest/API/Common/ApplicationCommand.cs b/src/Discord.Net.Rest/API/Common/ApplicationCommand.cs
index 8b84149dd..e46369277 100644
--- a/src/Discord.Net.Rest/API/Common/ApplicationCommand.cs
+++ b/src/Discord.Net.Rest/API/Common/ApplicationCommand.cs
@@ -1,4 +1,5 @@
using Newtonsoft.Json;
+using System.Collections.Generic;
namespace Discord.API
{
@@ -25,6 +26,18 @@ namespace Discord.API
[JsonProperty("default_permission")]
public Optional DefaultPermissions { get; set; }
+ [JsonProperty("name_localizations")]
+ public Optional> NameLocalizations { get; set; }
+
+ [JsonProperty("description_localizations")]
+ public Optional> DescriptionLocalizations { get; set; }
+
+ [JsonProperty("name_localized")]
+ public Optional NameLocalized { get; set; }
+
+ [JsonProperty("description_localized")]
+ public Optional DescriptionLocalized { get; set; }
+
// V2 Permissions
[JsonProperty("dm_permission")]
public Optional DmPermission { get; set; }
diff --git a/src/Discord.Net.Rest/API/Common/ApplicationCommandOption.cs b/src/Discord.Net.Rest/API/Common/ApplicationCommandOption.cs
index d703bd46b..fb64d5ebe 100644
--- a/src/Discord.Net.Rest/API/Common/ApplicationCommandOption.cs
+++ b/src/Discord.Net.Rest/API/Common/ApplicationCommandOption.cs
@@ -1,4 +1,5 @@
using Newtonsoft.Json;
+using System.Collections.Generic;
using System.Linq;
namespace Discord.API
@@ -38,6 +39,24 @@ namespace Discord.API
[JsonProperty("channel_types")]
public Optional ChannelTypes { get; set; }
+ [JsonProperty("name_localizations")]
+ public Optional> NameLocalizations { get; set; }
+
+ [JsonProperty("description_localizations")]
+ public Optional> DescriptionLocalizations { get; set; }
+
+ [JsonProperty("name_localized")]
+ public Optional NameLocalized { get; set; }
+
+ [JsonProperty("description_localized")]
+ public Optional DescriptionLocalized { get; set; }
+
+ [JsonProperty("min_length")]
+ public Optional MinLength { get; set; }
+
+ [JsonProperty("max_length")]
+ public Optional MaxLength { get; set; }
+
public ApplicationCommandOption() { }
public ApplicationCommandOption(IApplicationCommandOption cmd)
@@ -56,11 +75,18 @@ namespace Discord.API
Default = cmd.IsDefault ?? Optional.Unspecified;
MinValue = cmd.MinValue ?? Optional.Unspecified;
MaxValue = cmd.MaxValue ?? Optional.Unspecified;
+ MinLength = cmd.MinLength ?? Optional.Unspecified;
+ MaxLength = cmd.MaxLength ?? Optional.Unspecified;
Autocomplete = cmd.IsAutocomplete ?? Optional.Unspecified;
Name = cmd.Name;
Type = cmd.Type;
Description = cmd.Description;
+
+ NameLocalizations = cmd.NameLocalizations?.ToDictionary() ?? Optional>.Unspecified;
+ DescriptionLocalizations = cmd.DescriptionLocalizations?.ToDictionary() ?? Optional>.Unspecified;
+ NameLocalized = cmd.NameLocalized;
+ DescriptionLocalized = cmd.DescriptionLocalized;
}
public ApplicationCommandOption(ApplicationCommandOptionProperties option)
{
@@ -77,6 +103,8 @@ namespace Discord.API
Default = option.IsDefault ?? Optional.Unspecified;
MinValue = option.MinValue ?? Optional.Unspecified;
MaxValue = option.MaxValue ?? Optional.Unspecified;
+ MinLength = option.MinLength ?? Optional.Unspecified;
+ MaxLength = option.MaxLength ?? Optional.Unspecified;
ChannelTypes = option.ChannelTypes?.ToArray() ?? Optional.Unspecified;
@@ -84,6 +112,9 @@ namespace Discord.API
Type = option.Type;
Description = option.Description;
Autocomplete = option.IsAutocomplete;
+
+ NameLocalizations = option.NameLocalizations?.ToDictionary() ?? Optional>.Unspecified;
+ DescriptionLocalizations = option.DescriptionLocalizations?.ToDictionary() ?? Optional>.Unspecified;
}
}
}
diff --git a/src/Discord.Net.Rest/API/Common/ApplicationCommandOptionChoice.cs b/src/Discord.Net.Rest/API/Common/ApplicationCommandOptionChoice.cs
index 6f84437f6..966405cc9 100644
--- a/src/Discord.Net.Rest/API/Common/ApplicationCommandOptionChoice.cs
+++ b/src/Discord.Net.Rest/API/Common/ApplicationCommandOptionChoice.cs
@@ -1,4 +1,5 @@
using Newtonsoft.Json;
+using System.Collections.Generic;
namespace Discord.API
{
@@ -9,5 +10,11 @@ namespace Discord.API
[JsonProperty("value")]
public object Value { get; set; }
+
+ [JsonProperty("name_localizations")]
+ public Optional> NameLocalizations { get; set; }
+
+ [JsonProperty("name_localized")]
+ public Optional NameLocalized { get; set; }
}
}
diff --git a/src/Discord.Net.Rest/API/Rest/CreateApplicationCommandParams.cs b/src/Discord.Net.Rest/API/Rest/CreateApplicationCommandParams.cs
index 7ae8718b6..2257d4b97 100644
--- a/src/Discord.Net.Rest/API/Rest/CreateApplicationCommandParams.cs
+++ b/src/Discord.Net.Rest/API/Rest/CreateApplicationCommandParams.cs
@@ -1,4 +1,8 @@
using Newtonsoft.Json;
+using System.Collections;
+using System.Collections.Generic;
+using System.Collections.Immutable;
+using System.Linq;
namespace Discord.API.Rest
{
@@ -19,6 +23,12 @@ namespace Discord.API.Rest
[JsonProperty("default_permission")]
public Optional DefaultPermission { get; set; }
+ [JsonProperty("name_localizations")]
+ public Optional> NameLocalizations { get; set; }
+
+ [JsonProperty("description_localizations")]
+ public Optional> DescriptionLocalizations { get; set; }
+
[JsonProperty("dm_permission")]
public Optional DmPermission { get; set; }
@@ -26,12 +36,15 @@ namespace Discord.API.Rest
public Optional DefaultMemberPermission { get; set; }
public CreateApplicationCommandParams() { }
- public CreateApplicationCommandParams(string name, string description, ApplicationCommandType type, ApplicationCommandOption[] options = null)
+ public CreateApplicationCommandParams(string name, string description, ApplicationCommandType type, ApplicationCommandOption[] options = null,
+ IDictionary nameLocalizations = null, IDictionary descriptionLocalizations = null)
{
Name = name;
Description = description;
Options = Optional.Create(options);
Type = type;
+ NameLocalizations = nameLocalizations?.ToDictionary(x => x.Key, x => x.Value) ?? Optional>.Unspecified;
+ DescriptionLocalizations = descriptionLocalizations?.ToDictionary(x => x.Key, x => x.Value) ?? Optional>.Unspecified;
}
}
}
diff --git a/src/Discord.Net.Rest/API/Rest/CreateStickerParams.cs b/src/Discord.Net.Rest/API/Rest/CreateStickerParams.cs
index b330a0111..a0871bc64 100644
--- a/src/Discord.Net.Rest/API/Rest/CreateStickerParams.cs
+++ b/src/Discord.Net.Rest/API/Rest/CreateStickerParams.cs
@@ -1,4 +1,5 @@
using Discord.Net.Rest;
+
using System.Collections.Generic;
using System.IO;
namespace Discord.API.Rest
@@ -20,14 +21,21 @@ namespace Discord.API.Rest
["tags"] = Tags
};
- string contentType = "image/png";
-
+ string contentType;
if (File is FileStream fileStream)
- contentType = $"image/{Path.GetExtension(fileStream.Name)}";
+ {
+ var extension = Path.GetExtension(fileStream.Name).TrimStart('.');
+ contentType = extension == "json" ? "application/json" : $"image/{extension}";
+ }
else if (FileName != null)
- contentType = $"image/{Path.GetExtension(FileName)}";
+ {
+ var extension = Path.GetExtension(FileName).TrimStart('.');
+ contentType = extension == "json" ? "application/json" : $"image/{extension}";
+ }
+ else
+ contentType = "image/png";
- d["file"] = new MultipartFile(File, FileName ?? "image", contentType.Replace(".", ""));
+ d["file"] = new MultipartFile(File, FileName ?? "image", contentType);
return d;
}
diff --git a/src/Discord.Net.Rest/API/Rest/ModifyApplicationCommandParams.cs b/src/Discord.Net.Rest/API/Rest/ModifyApplicationCommandParams.cs
index 5891c2c28..f49a3f33d 100644
--- a/src/Discord.Net.Rest/API/Rest/ModifyApplicationCommandParams.cs
+++ b/src/Discord.Net.Rest/API/Rest/ModifyApplicationCommandParams.cs
@@ -1,4 +1,5 @@
using Newtonsoft.Json;
+using System.Collections.Generic;
namespace Discord.API.Rest
{
@@ -15,5 +16,11 @@ namespace Discord.API.Rest
[JsonProperty("default_permission")]
public Optional DefaultPermission { get; set; }
+
+ [JsonProperty("name_localizations")]
+ public Optional> NameLocalizations { get; set; }
+
+ [JsonProperty("description_localizations")]
+ public Optional> DescriptionLocalizations { get; set; }
}
}
diff --git a/src/Discord.Net.Rest/BaseDiscordClient.cs b/src/Discord.Net.Rest/BaseDiscordClient.cs
index 75f477c7c..686c7b030 100644
--- a/src/Discord.Net.Rest/BaseDiscordClient.cs
+++ b/src/Discord.Net.Rest/BaseDiscordClient.cs
@@ -57,7 +57,7 @@ namespace Discord.Rest
if (info == null)
await _restLogger.VerboseAsync($"Preemptive Rate limit triggered: {endpoint} {(id.IsHashBucket ? $"(Bucket: {id.BucketHash})" : "")}").ConfigureAwait(false);
else
- await _restLogger.WarningAsync($"Rate limit triggered: {endpoint} {(id.IsHashBucket ? $"(Bucket: {id.BucketHash})" : "")}").ConfigureAwait(false);
+ await _restLogger.WarningAsync($"Rate limit triggered: {endpoint} Remaining: {info.Value.RetryAfter}s {(id.IsHashBucket ? $"(Bucket: {id.BucketHash})" : "")}").ConfigureAwait(false);
};
ApiClient.SentRequest += async (method, endpoint, millis) => await _restLogger.VerboseAsync($"{method} {endpoint}: {millis} ms").ConfigureAwait(false);
}
@@ -243,7 +243,7 @@ namespace Discord.Rest
=> Task.FromResult(null);
///
- Task> IDiscordClient.GetGlobalApplicationCommandsAsync(RequestOptions options)
+ Task> IDiscordClient.GetGlobalApplicationCommandsAsync(bool withLocalizations, string locale, RequestOptions options)
=> Task.FromResult>(ImmutableArray.Create());
Task IDiscordClient.CreateGlobalApplicationCommand(ApplicationCommandProperties properties, RequestOptions options)
=> Task.FromResult(null);
@@ -257,6 +257,6 @@ namespace Discord.Rest
///
Task IDiscordClient.StopAsync()
=> Task.Delay(0);
- #endregion
+ #endregion
}
}
diff --git a/src/Discord.Net.Rest/ClientHelper.cs b/src/Discord.Net.Rest/ClientHelper.cs
index c6ad6a9fb..0c8f8c42f 100644
--- a/src/Discord.Net.Rest/ClientHelper.cs
+++ b/src/Discord.Net.Rest/ClientHelper.cs
@@ -194,10 +194,10 @@ namespace Discord.Rest
};
}
- public static async Task> GetGlobalApplicationCommandsAsync(BaseDiscordClient client,
- RequestOptions options = null)
+ public static async Task> GetGlobalApplicationCommandsAsync(BaseDiscordClient client, bool withLocalizations = false,
+ string locale = null, RequestOptions options = null)
{
- var response = await client.ApiClient.GetGlobalApplicationCommandsAsync(options).ConfigureAwait(false);
+ var response = await client.ApiClient.GetGlobalApplicationCommandsAsync(withLocalizations, locale, options).ConfigureAwait(false);
if (!response.Any())
return Array.Empty();
@@ -212,10 +212,10 @@ namespace Discord.Rest
return model != null ? RestGlobalCommand.Create(client, model) : null;
}
- public static async Task> GetGuildApplicationCommandsAsync(BaseDiscordClient client, ulong guildId,
- RequestOptions options = null)
+ public static async Task> GetGuildApplicationCommandsAsync(BaseDiscordClient client, ulong guildId, bool withLocalizations = false,
+ string locale = null, RequestOptions options = null)
{
- var response = await client.ApiClient.GetGuildApplicationCommandsAsync(guildId, options).ConfigureAwait(false);
+ var response = await client.ApiClient.GetGuildApplicationCommandsAsync(guildId, withLocalizations, locale, options).ConfigureAwait(false);
if (!response.Any())
return ImmutableArray.Create();
diff --git a/src/Discord.Net.Rest/DiscordRestApiClient.cs b/src/Discord.Net.Rest/DiscordRestApiClient.cs
index e179675ba..615e5ac12 100644
--- a/src/Discord.Net.Rest/DiscordRestApiClient.cs
+++ b/src/Discord.Net.Rest/DiscordRestApiClient.cs
@@ -8,6 +8,7 @@ using Newtonsoft.Json;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
+using System.ComponentModel.Design;
using System.Diagnostics;
using System.Globalization;
using System.IO;
@@ -861,7 +862,7 @@ namespace Discord.API
options = RequestOptions.CreateOrClone(options);
var ids = new BucketIds(webhookId: webhookId);
- await SendJsonAsync("PATCH", () => $"webhooks/{webhookId}/{AuthToken}/messages/{messageId}${WebhookQuery(false, threadId)}", args, ids, clientBucket: ClientBucketType.SendEdit, options: options).ConfigureAwait(false);
+ await SendJsonAsync("PATCH", () => $"webhooks/{webhookId}/{AuthToken}/messages/{messageId}?{WebhookQuery(false, threadId)}", args, ids, clientBucket: ClientBucketType.SendEdit, options: options).ConfigureAwait(false);
}
/// This operation may only be called with a token.
@@ -1212,11 +1213,22 @@ namespace Discord.API
#endregion
#region Interactions
- public async Task GetGlobalApplicationCommandsAsync(RequestOptions options = null)
+ public async Task GetGlobalApplicationCommandsAsync(bool withLocalizations = false, string locale = null, RequestOptions options = null)
{
options = RequestOptions.CreateOrClone(options);
- return await SendAsync("GET", () => $"applications/{CurrentApplicationId}/commands", new BucketIds(), options: options).ConfigureAwait(false);
+ if (locale is not null)
+ {
+ if (!System.Text.RegularExpressions.Regex.IsMatch(locale, @"^\w{2}(?:-\w{2})?$"))
+ throw new ArgumentException($"{locale} is not a valid locale.", nameof(locale));
+
+ options.RequestHeaders["X-Discord-Locale"] = new[] { locale };
+ }
+
+ //with_localizations=false doesnt return localized names and descriptions
+ var query = withLocalizations ? "?with_localizations=true" : string.Empty;
+ return await SendAsync("GET", () => $"applications/{CurrentApplicationId}/commands{query}",
+ new BucketIds(), options: options).ConfigureAwait(false);
}
public async Task GetGlobalApplicationCommandAsync(ulong id, RequestOptions options = null)
@@ -1281,13 +1293,24 @@ namespace Discord.API
return await SendJsonAsync("PUT", () => $"applications/{CurrentApplicationId}/commands", commands, new BucketIds(), options: options).ConfigureAwait(false);
}
- public async Task GetGuildApplicationCommandsAsync(ulong guildId, RequestOptions options = null)
+ public async Task GetGuildApplicationCommandsAsync(ulong guildId, bool withLocalizations = false, string locale = null, RequestOptions options = null)
{
options = RequestOptions.CreateOrClone(options);
var bucket = new BucketIds(guildId: guildId);
- return await SendAsync("GET", () => $"applications/{CurrentApplicationId}/guilds/{guildId}/commands", bucket, options: options).ConfigureAwait(false);
+ if (locale is not null)
+ {
+ if (!System.Text.RegularExpressions.Regex.IsMatch(locale, @"^\w{2}(?:-\w{2})?$"))
+ throw new ArgumentException($"{locale} is not a valid locale.", nameof(locale));
+
+ options.RequestHeaders["X-Discord-Locale"] = new[] { locale };
+ }
+
+ //with_localizations=false doesnt return localized names and descriptions
+ var query = withLocalizations ? "?with_localizations=true" : string.Empty;
+ return await SendAsync("GET", () => $"applications/{CurrentApplicationId}/guilds/{guildId}/commands{query}",
+ bucket, options: options).ConfigureAwait(false);
}
public async Task GetGuildApplicationCommandAsync(ulong guildId, ulong commandId, RequestOptions options = null)
@@ -1756,7 +1779,7 @@ namespace Discord.API
if (args.TargetType.Value == TargetUserType.Stream)
Preconditions.GreaterThan(args.TargetUserId, 0, nameof(args.TargetUserId));
if (args.TargetType.Value == TargetUserType.EmbeddedApplication)
- Preconditions.GreaterThan(args.TargetApplicationId, 0, nameof(args.TargetUserId));
+ Preconditions.GreaterThan(args.TargetApplicationId, 0, nameof(args.TargetApplicationId));
}
options = RequestOptions.CreateOrClone(options);
diff --git a/src/Discord.Net.Rest/DiscordRestClient.cs b/src/Discord.Net.Rest/DiscordRestClient.cs
index daf7287c7..ddd38c5be 100644
--- a/src/Discord.Net.Rest/DiscordRestClient.cs
+++ b/src/Discord.Net.Rest/DiscordRestClient.cs
@@ -25,7 +25,7 @@ namespace Discord.Rest
/// Gets the logged-in user.
///
public new RestSelfUser CurrentUser { get => base.CurrentUser as RestSelfUser; internal set => base.CurrentUser = value; }
-
+
///
public DiscordRestClient() : this(new DiscordRestConfig()) { }
///
@@ -205,10 +205,10 @@ namespace Discord.Rest
=> ClientHelper.CreateGlobalApplicationCommandAsync(this, properties, options);
public Task CreateGuildCommand(ApplicationCommandProperties properties, ulong guildId, RequestOptions options = null)
=> ClientHelper.CreateGuildApplicationCommandAsync(this, guildId, properties, options);
- public Task> GetGlobalApplicationCommands(RequestOptions options = null)
- => ClientHelper.GetGlobalApplicationCommandsAsync(this, options);
- public Task> GetGuildApplicationCommands(ulong guildId, RequestOptions options = null)
- => ClientHelper.GetGuildApplicationCommandsAsync(this, guildId, options);
+ public Task> GetGlobalApplicationCommands(bool withLocalizations = false, string locale = null, RequestOptions options = null)
+ => ClientHelper.GetGlobalApplicationCommandsAsync(this, withLocalizations, locale, options);
+ public Task> GetGuildApplicationCommands(ulong guildId, bool withLocalizations = false, string locale = null, RequestOptions options = null)
+ => ClientHelper.GetGuildApplicationCommandsAsync(this, guildId, withLocalizations, locale, options);
public Task> BulkOverwriteGlobalCommands(ApplicationCommandProperties[] commandProperties, RequestOptions options = null)
=> ClientHelper.BulkOverwriteGlobalApplicationCommandAsync(this, commandProperties, options);
public Task> BulkOverwriteGuildCommands(ApplicationCommandProperties[] commandProperties, ulong guildId, RequestOptions options = null)
@@ -319,8 +319,8 @@ namespace Discord.Rest
=> await GetWebhookAsync(id, options).ConfigureAwait(false);
///
- async Task> IDiscordClient.GetGlobalApplicationCommandsAsync(RequestOptions options)
- => await GetGlobalApplicationCommands(options).ConfigureAwait(false);
+ async Task> IDiscordClient.GetGlobalApplicationCommandsAsync(bool withLocalizations, string locale, RequestOptions options)
+ => await GetGlobalApplicationCommands(withLocalizations, locale, options).ConfigureAwait(false);
///
async Task IDiscordClient.GetGlobalApplicationCommandAsync(ulong id, RequestOptions options)
=> await ClientHelper.GetGlobalApplicationCommandAsync(this, id, options).ConfigureAwait(false);
diff --git a/src/Discord.Net.Rest/Entities/AuditLogs/DataTypes/ThreadUpdateAuditLogData.cs b/src/Discord.Net.Rest/Entities/AuditLogs/DataTypes/ThreadUpdateAuditLogData.cs
index 2b9b95418..8eb03114d 100644
--- a/src/Discord.Net.Rest/Entities/AuditLogs/DataTypes/ThreadUpdateAuditLogData.cs
+++ b/src/Discord.Net.Rest/Entities/AuditLogs/DataTypes/ThreadUpdateAuditLogData.cs
@@ -15,7 +15,7 @@ namespace Discord.Rest
Thread = thread;
ThreadType = type;
Before = before;
- After = After;
+ After = after;
}
internal static ThreadUpdateAuditLogData Create(BaseDiscordClient discord, Model log, EntryModel entry)
diff --git a/src/Discord.Net.Rest/Entities/Guilds/GuildHelper.cs b/src/Discord.Net.Rest/Entities/Guilds/GuildHelper.cs
index 8bab35937..c4e3764d1 100644
--- a/src/Discord.Net.Rest/Entities/Guilds/GuildHelper.cs
+++ b/src/Discord.Net.Rest/Entities/Guilds/GuildHelper.cs
@@ -180,7 +180,7 @@ namespace Discord.Rest
},
nextPage: (info, lastPage) =>
{
- if (lastPage.Count != DiscordConfig.MaxMessagesPerBatch)
+ if (lastPage.Count != DiscordConfig.MaxBansPerBatch)
return false;
if (dir == Direction.Before)
info.Position = lastPage.Min(x => x.User.Id);
@@ -362,10 +362,10 @@ namespace Discord.Rest
#endregion
#region Interactions
- public static async Task> GetSlashCommandsAsync(IGuild guild, BaseDiscordClient client,
- RequestOptions options)
+ public static async Task> GetSlashCommandsAsync(IGuild guild, BaseDiscordClient client, bool withLocalizations,
+ string locale, RequestOptions options)
{
- var models = await client.ApiClient.GetGuildApplicationCommandsAsync(guild.Id, options);
+ var models = await client.ApiClient.GetGuildApplicationCommandsAsync(guild.Id, withLocalizations, locale, options);
return models.Select(x => RestGuildCommand.Create(client, x, guild.Id)).ToImmutableArray();
}
public static async Task GetSlashCommandAsync(IGuild guild, ulong id, BaseDiscordClient client,
@@ -428,7 +428,7 @@ namespace Discord.Rest
var ids = args.Roles.Value.Select(r => r.Id);
if (args.RoleIds.IsSpecified)
- args.RoleIds.Value.Concat(ids);
+ args.RoleIds = Optional.Create(args.RoleIds.Value.Concat(ids));
else
args.RoleIds = Optional.Create(ids);
}
diff --git a/src/Discord.Net.Rest/Entities/Guilds/RestGuild.cs b/src/Discord.Net.Rest/Entities/Guilds/RestGuild.cs
index 974ea69ad..eb3254619 100644
--- a/src/Discord.Net.Rest/Entities/Guilds/RestGuild.cs
+++ b/src/Discord.Net.Rest/Entities/Guilds/RestGuild.cs
@@ -311,13 +311,15 @@ namespace Discord.Rest
///
/// Gets a collection of slash commands created by the current user in this guild.
///
+ /// Whether to include full localization dictionaries in the returned objects, instead of the name localized and description localized fields.
+ /// The target locale of the localized name and description fields. Sets X-Discord-Locale header, which takes precedence over Accept-Language.
/// The options to be used when sending the request.
///
/// A task that represents the asynchronous get operation. The task result contains a read-only collection of
/// slash commands created by the current user.
///
- public Task> GetSlashCommandsAsync(RequestOptions options = null)
- => GuildHelper.GetSlashCommandsAsync(this, Discord, options);
+ public Task> GetSlashCommandsAsync(bool withLocalizations = false, string locale = null, RequestOptions options = null)
+ => GuildHelper.GetSlashCommandsAsync(this, Discord, withLocalizations, locale, options);
///
/// Gets a slash command in the current guild.
@@ -928,13 +930,15 @@ namespace Discord.Rest
///
/// Gets this guilds slash commands
///
+ /// Whether to include full localization dictionaries in the returned objects, instead of the name localized and description localized fields.
+ /// The target locale of the localized name and description fields. Sets X-Discord-Locale header, which takes precedence over Accept-Language.
/// The options to be used when sending the request.
///
/// A task that represents the asynchronous get operation. The task result contains a read-only collection
/// of application commands found within the guild.
///
- public async Task> GetApplicationCommandsAsync (RequestOptions options = null)
- => await ClientHelper.GetGuildApplicationCommandsAsync(Discord, Id, options).ConfigureAwait(false);
+ public async Task> GetApplicationCommandsAsync (bool withLocalizations = false, string locale = null, RequestOptions options = null)
+ => await ClientHelper.GetGuildApplicationCommandsAsync(Discord, Id, withLocalizations, locale, options).ConfigureAwait(false);
///
/// Gets an application command within this guild with the specified id.
///
@@ -1404,7 +1408,7 @@ namespace Discord.Rest
///
/// The user to disconnect.
/// A task that represents the asynchronous operation for disconnecting a user.
- async Task IGuild.DisconnectAsync(IGuildUser user) => await user.ModifyAsync(x => x.Channel = new Optional());
+ async Task IGuild.DisconnectAsync(IGuildUser user) => await user.ModifyAsync(x => x.Channel = null);
///
async Task IGuild.GetUserAsync(ulong id, CacheMode mode, RequestOptions options)
@@ -1467,8 +1471,8 @@ namespace Discord.Rest
async Task> IGuild.GetWebhooksAsync(RequestOptions options)
=> await GetWebhooksAsync(options).ConfigureAwait(false);
///
- async Task> IGuild.GetApplicationCommandsAsync (RequestOptions options)
- => await GetApplicationCommandsAsync(options).ConfigureAwait(false);
+ async Task> IGuild.GetApplicationCommandsAsync (bool withLocalizations, string locale, RequestOptions options)
+ => await GetApplicationCommandsAsync(withLocalizations, locale, options).ConfigureAwait(false);
///
async Task IGuild.CreateStickerAsync(string name, string description, IEnumerable tags, Image image, RequestOptions options)
=> await CreateStickerAsync(name, description, tags, image, options);
diff --git a/src/Discord.Net.Rest/Entities/Interactions/CommandBase/RestCommandBase.cs b/src/Discord.Net.Rest/Entities/Interactions/CommandBase/RestCommandBase.cs
index 22e56a733..102ede7b7 100644
--- a/src/Discord.Net.Rest/Entities/Interactions/CommandBase/RestCommandBase.cs
+++ b/src/Discord.Net.Rest/Entities/Interactions/CommandBase/RestCommandBase.cs
@@ -49,6 +49,9 @@ namespace Discord.Rest
internal override async Task UpdateAsync(DiscordRestClient client, Model model, bool doApiCall)
{
await base.UpdateAsync(client, model, doApiCall).ConfigureAwait(false);
+
+ if (model.Data.IsSpecified && model.Data.Value is RestCommandBaseData data)
+ Data = data;
}
///
diff --git a/src/Discord.Net.Rest/Entities/Interactions/InteractionHelper.cs b/src/Discord.Net.Rest/Entities/Interactions/InteractionHelper.cs
index 522c098e6..deca00b72 100644
--- a/src/Discord.Net.Rest/Entities/Interactions/InteractionHelper.cs
+++ b/src/Discord.Net.Rest/Entities/Interactions/InteractionHelper.cs
@@ -3,6 +3,7 @@ using Discord.API.Rest;
using Discord.Net;
using System;
using System.Collections.Generic;
+using System.Collections.Immutable;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
@@ -101,11 +102,12 @@ namespace Discord.Rest
DefaultPermission = arg.IsDefaultPermission.IsSpecified
? arg.IsDefaultPermission.Value
: Optional.Unspecified,
+ NameLocalizations = arg.NameLocalizations?.ToDictionary(),
+ DescriptionLocalizations = arg.DescriptionLocalizations?.ToDictionary(),
// TODO: better conversion to nullable optionals
DefaultMemberPermission = arg.DefaultMemberPermissions.ToNullable(),
DmPermission = arg.IsDMEnabled.ToNullable()
-
};
if (arg is SlashCommandProperties slashProps)
@@ -140,6 +142,8 @@ namespace Discord.Rest
DefaultPermission = arg.IsDefaultPermission.IsSpecified
? arg.IsDefaultPermission.Value
: Optional.Unspecified,
+ NameLocalizations = arg.NameLocalizations?.ToDictionary(),
+ DescriptionLocalizations = arg.DescriptionLocalizations?.ToDictionary(),
// TODO: better conversion to nullable optionals
DefaultMemberPermission = arg.DefaultMemberPermissions.ToNullable(),
@@ -181,6 +185,8 @@ namespace Discord.Rest
DefaultPermission = arg.IsDefaultPermission.IsSpecified
? arg.IsDefaultPermission.Value
: Optional.Unspecified,
+ NameLocalizations = arg.NameLocalizations?.ToDictionary(),
+ DescriptionLocalizations = arg.DescriptionLocalizations?.ToDictionary(),
// TODO: better conversion to nullable optionals
DefaultMemberPermission = arg.DefaultMemberPermissions.ToNullable(),
@@ -244,7 +250,9 @@ namespace Discord.Rest
Name = args.Name,
DefaultPermission = args.IsDefaultPermission.IsSpecified
? args.IsDefaultPermission.Value
- : Optional.Unspecified
+ : Optional.Unspecified,
+ NameLocalizations = args.NameLocalizations?.ToDictionary(),
+ DescriptionLocalizations = args.DescriptionLocalizations?.ToDictionary()
};
if (args is SlashCommandProperties slashProps)
@@ -299,6 +307,8 @@ namespace Discord.Rest
DefaultPermission = arg.IsDefaultPermission.IsSpecified
? arg.IsDefaultPermission.Value
: Optional.Unspecified,
+ NameLocalizations = arg.NameLocalizations?.ToDictionary(),
+ DescriptionLocalizations = arg.DescriptionLocalizations?.ToDictionary(),
// TODO: better conversion to nullable optionals
DefaultMemberPermission = arg.DefaultMemberPermissions.ToNullable(),
@@ -335,7 +345,9 @@ namespace Discord.Rest
Name = arg.Name,
DefaultPermission = arg.IsDefaultPermission.IsSpecified
? arg.IsDefaultPermission.Value
- : Optional.Unspecified
+ : Optional.Unspecified,
+ NameLocalizations = arg.NameLocalizations?.ToDictionary(),
+ DescriptionLocalizations = arg.DescriptionLocalizations?.ToDictionary()
};
if (arg is SlashCommandProperties slashProps)
diff --git a/src/Discord.Net.Rest/Entities/Interactions/RestApplicationCommand.cs b/src/Discord.Net.Rest/Entities/Interactions/RestApplicationCommand.cs
index 667609ef4..468d10712 100644
--- a/src/Discord.Net.Rest/Entities/Interactions/RestApplicationCommand.cs
+++ b/src/Discord.Net.Rest/Entities/Interactions/RestApplicationCommand.cs
@@ -38,6 +38,32 @@ namespace Discord.Rest
///
public IReadOnlyCollection Options { get; private set; }
+ ///
+ /// Gets the localization dictionary for the name field of this command.
+ ///
+ public IReadOnlyDictionary NameLocalizations { get; private set; }
+
+ ///
+ /// Gets the localization dictionary for the description field of this command.
+ ///
+ public IReadOnlyDictionary DescriptionLocalizations { get; private set; }
+
+ ///
+ /// Gets the localized name of this command.
+ ///
+ ///
+ /// Only returned when the `withLocalizations` query parameter is set to when requesting the command.
+ ///
+ public string NameLocalized { get; private set; }
+
+ ///
+ /// Gets the localized description of this command.
+ ///
+ ///
+ /// Only returned when the `withLocalizations` query parameter is set to when requesting the command.
+ ///
+ public string DescriptionLocalized { get; private set; }
+
///
public DateTimeOffset CreatedAt
=> SnowflakeUtils.FromSnowflake(Id);
@@ -64,6 +90,15 @@ namespace Discord.Rest
? model.Options.Value.Select(RestApplicationCommandOption.Create).ToImmutableArray()
: ImmutableArray.Create();
+ NameLocalizations = model.NameLocalizations.GetValueOrDefault(null)?.ToImmutableDictionary() ??
+ ImmutableDictionary.Empty;
+
+ DescriptionLocalizations = model.DescriptionLocalizations.GetValueOrDefault(null)?.ToImmutableDictionary() ??
+ ImmutableDictionary.Empty;
+
+ NameLocalized = model.NameLocalized.GetValueOrDefault();
+ DescriptionLocalized = model.DescriptionLocalized.GetValueOrDefault();
+
IsEnabledInDm = model.DmPermission.GetValueOrDefault(true).GetValueOrDefault(true);
DefaultMemberPermissions = new GuildPermissions((ulong)model.DefaultMemberPermission.GetValueOrDefault(0).GetValueOrDefault(0));
}
diff --git a/src/Discord.Net.Rest/Entities/Interactions/RestApplicationCommandChoice.cs b/src/Discord.Net.Rest/Entities/Interactions/RestApplicationCommandChoice.cs
index a40491a2c..b736c435d 100644
--- a/src/Discord.Net.Rest/Entities/Interactions/RestApplicationCommandChoice.cs
+++ b/src/Discord.Net.Rest/Entities/Interactions/RestApplicationCommandChoice.cs
@@ -1,3 +1,5 @@
+using System.Collections.Generic;
+using System.Collections.Immutable;
using Model = Discord.API.ApplicationCommandOptionChoice;
namespace Discord.Rest
@@ -13,10 +15,25 @@ namespace Discord.Rest
///
public object Value { get; }
+ ///
+ /// Gets the localization dictionary for the name field of this command option choice.
+ ///
+ public IReadOnlyDictionary NameLocalizations { get; }
+
+ ///
+ /// Gets the localized name of this command option choice.
+ ///
+ ///
+ /// Only returned when the `withLocalizations` query parameter is set to when requesting the command.
+ ///
+ public string NameLocalized { get; }
+
internal RestApplicationCommandChoice(Model model)
{
Name = model.Name;
Value = model.Value;
+ NameLocalizations = model.NameLocalizations.GetValueOrDefault(null)?.ToImmutableDictionary();
+ NameLocalized = model.NameLocalized.GetValueOrDefault(null);
}
}
}
diff --git a/src/Discord.Net.Rest/Entities/Interactions/RestApplicationCommandOption.cs b/src/Discord.Net.Rest/Entities/Interactions/RestApplicationCommandOption.cs
index 86c6019ed..3ac15e695 100644
--- a/src/Discord.Net.Rest/Entities/Interactions/RestApplicationCommandOption.cs
+++ b/src/Discord.Net.Rest/Entities/Interactions/RestApplicationCommandOption.cs
@@ -27,7 +27,7 @@ namespace Discord.Rest
public bool? IsRequired { get; private set; }
///
- public bool? IsAutocomplete { get; private set; }
+ public bool? IsAutocomplete { get; private set; }
///
public double? MinValue { get; private set; }
@@ -35,6 +35,12 @@ namespace Discord.Rest
///
public double? MaxValue { get; private set; }
+ ///
+ public int? MinLength { get; private set; }
+
+ ///
+ public int? MaxLength { get; private set; }
+
///
/// Gets a collection of s for this command.
///
@@ -48,6 +54,32 @@ namespace Discord.Rest
///
public IReadOnlyCollection ChannelTypes { get; private set; }
+ ///
+ /// Gets the localization dictionary for the name field of this command option.
+ ///
+ public IReadOnlyDictionary NameLocalizations { get; private set; }
+
+ ///
+ /// Gets the localization dictionary for the description field of this command option.
+ ///
+ public IReadOnlyDictionary DescriptionLocalizations { get; private set; }
+
+ ///
+ /// Gets the localized name of this command option.
+ ///
+ ///
+ /// Only returned when the `withLocalizations` query parameter is set to when requesting the command.
+ ///
+ public string NameLocalized { get; private set; }
+
+ ///
+ /// Gets the localized description of this command option.
+ ///
+ ///
+ /// Only returned when the `withLocalizations` query parameter is set to when requesting the command.
+ ///
+ public string DescriptionLocalized { get; private set; }
+
internal RestApplicationCommandOption() { }
internal static RestApplicationCommandOption Create(Model model)
@@ -78,6 +110,9 @@ namespace Discord.Rest
if (model.Autocomplete.IsSpecified)
IsAutocomplete = model.Autocomplete.Value;
+ MinLength = model.MinLength.ToNullable();
+ MaxLength = model.MaxLength.ToNullable();
+
Options = model.Options.IsSpecified
? model.Options.Value.Select(Create).ToImmutableArray()
: ImmutableArray.Create();
@@ -89,6 +124,15 @@ namespace Discord.Rest
ChannelTypes = model.ChannelTypes.IsSpecified
? model.ChannelTypes.Value.ToImmutableArray()
: ImmutableArray.Create();
+
+ NameLocalizations = model.NameLocalizations.GetValueOrDefault(null)?.ToImmutableDictionary() ??
+ ImmutableDictionary.Empty;
+
+ DescriptionLocalizations = model.DescriptionLocalizations.GetValueOrDefault(null)?.ToImmutableDictionary() ??
+ ImmutableDictionary.Empty;
+
+ NameLocalized = model.NameLocalized.GetValueOrDefault();
+ DescriptionLocalized = model.DescriptionLocalized.GetValueOrDefault();
}
#endregion
diff --git a/src/Discord.Net.Rest/Entities/Interactions/RestInteraction.cs b/src/Discord.Net.Rest/Entities/Interactions/RestInteraction.cs
index 43d13f521..ba2de12a9 100644
--- a/src/Discord.Net.Rest/Entities/Interactions/RestInteraction.cs
+++ b/src/Discord.Net.Rest/Entities/Interactions/RestInteraction.cs
@@ -426,7 +426,7 @@ namespace Discord.Rest
AllowedMentions allowedMentions, MessageComponent components, Embed embed, RequestOptions options)
=> await FollowupWithFileAsync(fileStream, fileName, text, embeds, isTTS, ephemeral, allowedMentions, components, embed, options).ConfigureAwait(false);
///
- async Task IDiscordInteraction.FollowupWithFileAsync(string filePath, string text, string fileName, Embed[] embeds, bool isTTS, bool ephemeral,
+ async Task IDiscordInteraction.FollowupWithFileAsync(string filePath, string fileName, string text, Embed[] embeds, bool isTTS, bool ephemeral,
AllowedMentions allowedMentions, MessageComponent components, Embed embed, RequestOptions options)
=> await FollowupWithFileAsync(filePath, text, fileName, embeds, isTTS, ephemeral, allowedMentions, components, embed, options).ConfigureAwait(false);
///
diff --git a/src/Discord.Net.Rest/Entities/Roles/RoleHelper.cs b/src/Discord.Net.Rest/Entities/Roles/RoleHelper.cs
index 3b2946a0d..2f6d1f062 100644
--- a/src/Discord.Net.Rest/Entities/Roles/RoleHelper.cs
+++ b/src/Discord.Net.Rest/Entities/Roles/RoleHelper.cs
@@ -23,7 +23,7 @@ namespace Discord.Rest
{
role.Guild.Features.EnsureFeature(GuildFeature.RoleIcons);
- if (args.Icon.IsSpecified && args.Emoji.IsSpecified)
+ if ((args.Icon.IsSpecified && args.Icon.Value != null) && (args.Emoji.IsSpecified && args.Emoji.Value != null))
{
throw new ArgumentException("Emoji and Icon properties cannot be present on a role at the same time.");
}
@@ -36,18 +36,18 @@ namespace Discord.Rest
Mentionable = args.Mentionable,
Name = args.Name,
Permissions = args.Permissions.IsSpecified ? args.Permissions.Value.RawValue.ToString() : Optional.Create(),
- Icon = args.Icon.IsSpecified ? args.Icon.Value.Value.ToModel() : Optional.Unspecified,
- Emoji = args.Emoji.GetValueOrDefault()?.Name ?? Optional.Unspecified
+ Icon = args.Icon.IsSpecified ? args.Icon.Value?.ToModel() ?? null : Optional.Unspecified,
+ Emoji = args.Emoji.IsSpecified ? args.Emoji.Value?.Name ?? "" : Optional.Create(),
};
- if (args.Icon.IsSpecified && role.Emoji != null)
+ if ((args.Icon.IsSpecified && args.Icon.Value != null) && role.Emoji != null)
{
- apiArgs.Emoji = null;
+ apiArgs.Emoji = "";
}
- if (args.Emoji.IsSpecified && !string.IsNullOrEmpty(role.Icon))
+ if ((args.Emoji.IsSpecified && args.Emoji.Value != null) && !string.IsNullOrEmpty(role.Icon))
{
- apiArgs.Icon = null;
+ apiArgs.Icon = Optional.Unspecified;
}
var model = await client.ApiClient.ModifyGuildRoleAsync(role.Guild.Id, role.Id, apiArgs, options).ConfigureAwait(false);
diff --git a/src/Discord.Net.Rest/Net/DefaultRestClient.cs b/src/Discord.Net.Rest/Net/DefaultRestClient.cs
index 721c7009d..97872ee6a 100644
--- a/src/Discord.Net.Rest/Net/DefaultRestClient.cs
+++ b/src/Discord.Net.Rest/Net/DefaultRestClient.cs
@@ -66,33 +66,45 @@ namespace Discord.Net.Rest
_cancelToken = cancelToken;
}
- public async Task SendAsync(string method, string endpoint, CancellationToken cancelToken, bool headerOnly, string reason = null)
+ public async Task SendAsync(string method, string endpoint, CancellationToken cancelToken, bool headerOnly, string reason = null,
+ IEnumerable>> requestHeaders = null)
{
string uri = Path.Combine(_baseUrl, endpoint);
using (var restRequest = new HttpRequestMessage(GetMethod(method), uri))
{
if (reason != null) restRequest.Headers.Add("X-Audit-Log-Reason", Uri.EscapeDataString(reason));
+ if (requestHeaders != null)
+ foreach (var header in requestHeaders)
+ restRequest.Headers.Add(header.Key, header.Value);
return await SendInternalAsync(restRequest, cancelToken, headerOnly).ConfigureAwait(false);
}
}
- public async Task SendAsync(string method, string endpoint, string json, CancellationToken cancelToken, bool headerOnly, string reason = null)
+ public async Task SendAsync(string method, string endpoint, string json, CancellationToken cancelToken, bool headerOnly, string reason = null,
+ IEnumerable>> requestHeaders = null)
{
string uri = Path.Combine(_baseUrl, endpoint);
using (var restRequest = new HttpRequestMessage(GetMethod(method), uri))
{
if (reason != null) restRequest.Headers.Add("X-Audit-Log-Reason", Uri.EscapeDataString(reason));
+ if (requestHeaders != null)
+ foreach (var header in requestHeaders)
+ restRequest.Headers.Add(header.Key, header.Value);
restRequest.Content = new StringContent(json, Encoding.UTF8, "application/json");
return await SendInternalAsync(restRequest, cancelToken, headerOnly).ConfigureAwait(false);
}
}
/// Unsupported param type.
- public async Task SendAsync(string method, string endpoint, IReadOnlyDictionary multipartParams, CancellationToken cancelToken, bool headerOnly, string reason = null)
+ public async Task SendAsync(string method, string endpoint, IReadOnlyDictionary multipartParams, CancellationToken cancelToken, bool headerOnly, string reason = null,
+ IEnumerable>> requestHeaders = null)
{
string uri = Path.Combine(_baseUrl, endpoint);
using (var restRequest = new HttpRequestMessage(GetMethod(method), uri))
{
if (reason != null) restRequest.Headers.Add("X-Audit-Log-Reason", Uri.EscapeDataString(reason));
+ if (requestHeaders != null)
+ foreach (var header in requestHeaders)
+ restRequest.Headers.Add(header.Key, header.Value);
var content = new MultipartFormDataContent("Upload----" + DateTime.Now.ToString(CultureInfo.InvariantCulture));
MemoryStream memoryStream = null;
if (multipartParams != null)
@@ -126,7 +138,7 @@ namespace Discord.Net.Rest
content.Add(streamContent, p.Key, fileValue.Filename);
#pragma warning restore IDISP004
-
+
continue;
}
default:
diff --git a/src/Discord.Net.Rest/Net/Queue/Requests/RestRequest.cs b/src/Discord.Net.Rest/Net/Queue/Requests/RestRequest.cs
index bb5840ce2..e5cab831e 100644
--- a/src/Discord.Net.Rest/Net/Queue/Requests/RestRequest.cs
+++ b/src/Discord.Net.Rest/Net/Queue/Requests/RestRequest.cs
@@ -1,5 +1,8 @@
using Discord.Net.Rest;
using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Collections.Immutable;
using System.IO;
using System.Threading.Tasks;
@@ -28,7 +31,7 @@ namespace Discord.Net.Queue
public virtual async Task SendAsync()
{
- return await Client.SendAsync(Method, Endpoint, Options.CancelToken, Options.HeaderOnly, Options.AuditLogReason).ConfigureAwait(false);
+ return await Client.SendAsync(Method, Endpoint, Options.CancelToken, Options.HeaderOnly, Options.AuditLogReason, Options.RequestHeaders).ConfigureAwait(false);
}
}
}
diff --git a/src/Discord.Net.WebSocket/API/Gateway/WebhooksUpdatedEvent.cs b/src/Discord.Net.WebSocket/API/Gateway/WebhooksUpdatedEvent.cs
new file mode 100644
index 000000000..5555dc842
--- /dev/null
+++ b/src/Discord.Net.WebSocket/API/Gateway/WebhooksUpdatedEvent.cs
@@ -0,0 +1,13 @@
+using Newtonsoft.Json;
+
+namespace Discord.API.Gateway
+{
+ internal class WebhooksUpdatedEvent
+ {
+ [JsonProperty("guild_id")]
+ public ulong GuildId { get; set; }
+
+ [JsonProperty("channel_id")]
+ public ulong ChannelId { get; set; }
+ }
+}
diff --git a/src/Discord.Net.WebSocket/BaseSocketClient.Events.cs b/src/Discord.Net.WebSocket/BaseSocketClient.Events.cs
index c47591418..fb2110399 100644
--- a/src/Discord.Net.WebSocket/BaseSocketClient.Events.cs
+++ b/src/Discord.Net.WebSocket/BaseSocketClient.Events.cs
@@ -55,7 +55,7 @@ namespace Discord.WebSocket
/// Fired when a channel is updated.
///
///
- /// This event is fired when a generic channel has been destroyed. The event handler must return a
+ /// This event is fired when a generic channel has been updated. The event handler must return a
/// and accept 2 as its parameters.
///
///
@@ -106,7 +106,7 @@ namespace Discord.WebSocket
///
///
/// This event is fired when a message is deleted. The event handler must return a
- /// and accept a and
+ /// and accept a and
/// as its parameters.
///
///
@@ -117,11 +117,11 @@ namespace Discord.WebSocket
///
/// If caching is enabled via , the
/// entity will contain the deleted message; otherwise, in event
- /// that the message cannot be retrieved, the snowflake ID of the message is preserved in the
+ /// that the message cannot be retrieved, the snowflake ID of the message is preserved in the
/// .
///
///
- /// The source channel of the removed message will be passed into the
+ /// The source channel of the removed message will be passed into the
/// parameter.
///
///
@@ -143,7 +143,7 @@ namespace Discord.WebSocket
///
///
/// This event is fired when multiple messages are bulk deleted. The event handler must return a
- /// and accept an and
+ /// and accept an and
/// as its parameters.
///
///
@@ -154,11 +154,11 @@ namespace Discord.WebSocket
///
/// If caching is enabled via , the
/// entity will contain the deleted message; otherwise, in event
- /// that the message cannot be retrieved, the snowflake ID of the message is preserved in the
+ /// that the message cannot be retrieved, the snowflake ID of the message is preserved in the
/// .
///
///
- /// The source channel of the removed message will be passed into the
+ /// The source channel of the removed message will be passed into the
/// parameter.
///
///
@@ -178,14 +178,14 @@ namespace Discord.WebSocket
///
/// If caching is enabled via , the
/// entity will contain the original message; otherwise, in event
- /// that the message cannot be retrieved, the snowflake ID of the message is preserved in the
+ /// that the message cannot be retrieved, the snowflake ID of the message is preserved in the
/// .
///
///
/// The updated message will be passed into the parameter.
///
///
- /// The source channel of the updated message will be passed into the
+ /// The source channel of the updated message will be passed into the
/// parameter.
///
///
@@ -199,24 +199,24 @@ namespace Discord.WebSocket
///
///
/// This event is fired when a reaction is added to a user message. The event handler must return a
- /// and accept a , an
+ /// and accept a , an
/// , and a as its parameter.
///
///
/// If caching is enabled via , the
/// entity will contain the original message; otherwise, in event
- /// that the message cannot be retrieved, the snowflake ID of the message is preserved in the
+ /// that the message cannot be retrieved, the snowflake ID of the message is preserved in the
/// .
///
///
- /// The source channel of the reaction addition will be passed into the
+ /// The source channel of the reaction addition will be passed into the
/// parameter.
///
///
/// The reaction that was added will be passed into the parameter.
///
///
- /// When fetching the reaction from this event, a user may not be provided under
+ /// When fetching the reaction from this event, a user may not be provided under
/// . Please see the documentation of the property for more
/// information.
///
@@ -367,7 +367,7 @@ namespace Discord.WebSocket
}
internal readonly AsyncEvent, SocketGuildEvent, Task>> _guildScheduledEventUpdated = new AsyncEvent, SocketGuildEvent, Task>>();
-
+
///
/// Fired when a guild event is cancelled.
///
@@ -877,5 +877,20 @@ namespace Discord.WebSocket
}
internal readonly AsyncEvent> _guildStickerDeleted = new AsyncEvent>();
#endregion
+
+ #region Webhooks
+
+ ///
+ /// Fired when a webhook is modified, moved, or deleted. If the webhook was
+ /// moved the channel represents the destination channel, not the source.
+ ///
+ public event Func WebhooksUpdated
+ {
+ add { _webhooksUpdated.Add(value); }
+ remove { _webhooksUpdated.Remove(value); }
+ }
+ internal readonly AsyncEvent> _webhooksUpdated = new AsyncEvent>();
+
+ #endregion
}
}
diff --git a/src/Discord.Net.WebSocket/DiscordShardedClient.cs b/src/Discord.Net.WebSocket/DiscordShardedClient.cs
index 3a14692e0..9fc717762 100644
--- a/src/Discord.Net.WebSocket/DiscordShardedClient.cs
+++ b/src/Discord.Net.WebSocket/DiscordShardedClient.cs
@@ -496,6 +496,8 @@ namespace Discord.WebSocket
client.GuildScheduledEventStarted += (arg) => _guildScheduledEventStarted.InvokeAsync(arg);
client.GuildScheduledEventUserAdd += (arg1, arg2) => _guildScheduledEventUserAdd.InvokeAsync(arg1, arg2);
client.GuildScheduledEventUserRemove += (arg1, arg2) => _guildScheduledEventUserRemove.InvokeAsync(arg1, arg2);
+
+ client.WebhooksUpdated += (arg1, arg2) => _webhooksUpdated.InvokeAsync(arg1, arg2);
}
#endregion
diff --git a/src/Discord.Net.WebSocket/DiscordSocketClient.cs b/src/Discord.Net.WebSocket/DiscordSocketClient.cs
index 5743d9abd..670ed4567 100644
--- a/src/Discord.Net.WebSocket/DiscordSocketClient.cs
+++ b/src/Discord.Net.WebSocket/DiscordSocketClient.cs
@@ -450,14 +450,16 @@ namespace Discord.WebSocket
///
/// Gets a collection of all global commands.
///
+ /// Whether to include full localization dictionaries in the returned objects, instead of the name localized and description localized fields.
+ /// The target locale of the localized name and description fields. Sets X-Discord-Locale header, which takes precedence over Accept-Language.
/// The options to be used when sending the request.
///
/// A task that represents the asynchronous get operation. The task result contains a read-only collection of global
/// application commands.
///
- public async Task> GetGlobalApplicationCommandsAsync(RequestOptions options = null)
+ public async Task> GetGlobalApplicationCommandsAsync(bool withLocalizations = false, string locale = null, RequestOptions options = null)
{
- var commands = (await ApiClient.GetGlobalApplicationCommandsAsync(options)).Select(x => SocketApplicationCommand.Create(this, x));
+ var commands = (await ApiClient.GetGlobalApplicationCommandsAsync(withLocalizations, locale, options)).Select(x => SocketApplicationCommand.Create(this, x));
foreach(var command in commands)
{
@@ -2318,7 +2320,7 @@ namespace Discord.WebSocket
case "INTERACTION_CREATE":
{
await _gatewayLogger.DebugAsync("Received Dispatch (INTERACTION_CREATE)").ConfigureAwait(false);
-
+
var data = (payload as JToken).ToObject(_serializer);
var guild = data.GuildId.IsSpecified ? GetGuild(data.GuildId.Value) : null;
@@ -2326,7 +2328,6 @@ namespace Discord.WebSocket
if (guild != null && !guild.IsSynced)
{
await UnsyncedGuildAsync(type, guild.Id).ConfigureAwait(false);
- return;
}
SocketUser user = data.User.IsSpecified
@@ -2346,15 +2347,8 @@ namespace Discord.WebSocket
{
channel = CreateDMChannel(data.ChannelId.Value, user, State);
}
- else
- {
- if (guild != null) // The guild id is set, but the guild cannot be found as the bot scope is not set.
- {
- await UnknownChannelAsync(type, data.ChannelId.Value).ConfigureAwait(false);
- return;
- }
- // The channel isnt required when responding to an interaction, so we can leave the channel null.
- }
+
+ // The channel isnt required when responding to an interaction, so we can leave the channel null.
}
}
else if (data.User.IsSpecified)
@@ -2839,6 +2833,23 @@ namespace Discord.WebSocket
#endregion
+ #region Webhooks
+
+ case "WEBHOOKS_UPDATE":
+ {
+ var data = (payload as JToken).ToObject(_serializer);
+ type = "WEBHOOKS_UPDATE";
+ await _gatewayLogger.DebugAsync("Received Dispatch (WEBHOOKS_UPDATE)").ConfigureAwait(false);
+
+ var guild = State.GetGuild(data.GuildId);
+ var channel = State.GetChannel(data.ChannelId);
+
+ await TimedInvokeAsync(_webhooksUpdated, nameof(WebhooksUpdated), guild, channel);
+ }
+ break;
+
+ #endregion
+
#region Ignored (User only)
case "CHANNEL_PINS_ACK":
await _gatewayLogger.DebugAsync("Ignored Dispatch (CHANNEL_PINS_ACK)").ConfigureAwait(false);
@@ -2858,9 +2869,6 @@ namespace Discord.WebSocket
case "USER_SETTINGS_UPDATE":
await _gatewayLogger.DebugAsync("Ignored Dispatch (USER_SETTINGS_UPDATE)").ConfigureAwait(false);
break;
- case "WEBHOOKS_UPDATE":
- await _gatewayLogger.DebugAsync("Ignored Dispatch (WEBHOOKS_UPDATE)").ConfigureAwait(false);
- break;
#endregion
#region Others
@@ -3230,8 +3238,8 @@ namespace Discord.WebSocket
async Task IDiscordClient.GetGlobalApplicationCommandAsync(ulong id, RequestOptions options)
=> await GetGlobalApplicationCommandAsync(id, options);
///
- async Task> IDiscordClient.GetGlobalApplicationCommandsAsync(RequestOptions options)
- => await GetGlobalApplicationCommandsAsync(options);
+ async Task> IDiscordClient.GetGlobalApplicationCommandsAsync(bool withLocalizations, string locale, RequestOptions options)
+ => await GetGlobalApplicationCommandsAsync(withLocalizations, locale, options);
///
async Task IDiscordClient.StartAsync()
diff --git a/src/Discord.Net.WebSocket/Entities/Channels/SocketCategoryChannel.cs b/src/Discord.Net.WebSocket/Entities/Channels/SocketCategoryChannel.cs
index 43f23de1a..42f0c76d4 100644
--- a/src/Discord.Net.WebSocket/Entities/Channels/SocketCategoryChannel.cs
+++ b/src/Discord.Net.WebSocket/Entities/Channels/SocketCategoryChannel.cs
@@ -39,7 +39,7 @@ namespace Discord.WebSocket
}
internal new static SocketCategoryChannel Create(SocketGuild guild, ClientState state, Model model)
{
- var entity = new SocketCategoryChannel(guild.Discord, model.Id, guild);
+ var entity = new SocketCategoryChannel(guild?.Discord, model.Id, guild);
entity.Update(state, model);
return entity;
}
diff --git a/src/Discord.Net.WebSocket/Entities/Channels/SocketForumChannel.cs b/src/Discord.Net.WebSocket/Entities/Channels/SocketForumChannel.cs
index bc6e28442..ea58ecdb5 100644
--- a/src/Discord.Net.WebSocket/Entities/Channels/SocketForumChannel.cs
+++ b/src/Discord.Net.WebSocket/Entities/Channels/SocketForumChannel.cs
@@ -34,7 +34,7 @@ namespace Discord.WebSocket
internal new static SocketForumChannel Create(SocketGuild guild, ClientState state, Model model)
{
- var entity = new SocketForumChannel(guild.Discord, model.Id, guild);
+ var entity = new SocketForumChannel(guild?.Discord, model.Id, guild);
entity.Update(state, model);
return entity;
}
diff --git a/src/Discord.Net.WebSocket/Entities/Channels/SocketGuildChannel.cs b/src/Discord.Net.WebSocket/Entities/Channels/SocketGuildChannel.cs
index 16ed7b32d..808982785 100644
--- a/src/Discord.Net.WebSocket/Entities/Channels/SocketGuildChannel.cs
+++ b/src/Discord.Net.WebSocket/Entities/Channels/SocketGuildChannel.cs
@@ -36,8 +36,8 @@ namespace Discord.WebSocket
/// Gets a collection of users that are able to view the channel.
///
///
- /// If this channel is a voice channel, a collection of users who are currently connected to this channel
- /// is returned.
+ /// If this channel is a voice channel, use to retrieve a
+ /// collection of users who are currently connected to this channel.
///
///
/// A read-only collection of users that can access the channel (i.e. the users seen in the user list).
diff --git a/src/Discord.Net.WebSocket/Entities/Channels/SocketNewsChannel.cs b/src/Discord.Net.WebSocket/Entities/Channels/SocketNewsChannel.cs
index eed8f9374..81e152530 100644
--- a/src/Discord.Net.WebSocket/Entities/Channels/SocketNewsChannel.cs
+++ b/src/Discord.Net.WebSocket/Entities/Channels/SocketNewsChannel.cs
@@ -23,7 +23,7 @@ namespace Discord.WebSocket
}
internal new static SocketNewsChannel Create(SocketGuild guild, ClientState state, Model model)
{
- var entity = new SocketNewsChannel(guild.Discord, model.Id, guild);
+ var entity = new SocketNewsChannel(guild?.Discord, model.Id, guild);
entity.Update(state, model);
return entity;
}
diff --git a/src/Discord.Net.WebSocket/Entities/Channels/SocketStageChannel.cs b/src/Discord.Net.WebSocket/Entities/Channels/SocketStageChannel.cs
index 56cd92185..4983bc466 100644
--- a/src/Discord.Net.WebSocket/Entities/Channels/SocketStageChannel.cs
+++ b/src/Discord.Net.WebSocket/Entities/Channels/SocketStageChannel.cs
@@ -49,7 +49,7 @@ namespace Discord.WebSocket
internal new static SocketStageChannel Create(SocketGuild guild, ClientState state, Model model)
{
- var entity = new SocketStageChannel(guild.Discord, model.Id, guild);
+ var entity = new SocketStageChannel(guild?.Discord, model.Id, guild);
entity.Update(state, model);
return entity;
}
diff --git a/src/Discord.Net.WebSocket/Entities/Channels/SocketTextChannel.cs b/src/Discord.Net.WebSocket/Entities/Channels/SocketTextChannel.cs
index 6aece7d78..2d8aeeae7 100644
--- a/src/Discord.Net.WebSocket/Entities/Channels/SocketTextChannel.cs
+++ b/src/Discord.Net.WebSocket/Entities/Channels/SocketTextChannel.cs
@@ -61,12 +61,12 @@ namespace Discord.WebSocket
internal SocketTextChannel(DiscordSocketClient discord, ulong id, SocketGuild guild)
: base(discord, id, guild)
{
- if (Discord.MessageCacheSize > 0)
+ if (Discord?.MessageCacheSize > 0)
_messages = new MessageCache(Discord);
}
internal new static SocketTextChannel Create(SocketGuild guild, ClientState state, Model model)
{
- var entity = new SocketTextChannel(guild.Discord, model.Id, guild);
+ var entity = new SocketTextChannel(guild?.Discord, model.Id, guild);
entity.Update(state, model);
return entity;
}
diff --git a/src/Discord.Net.WebSocket/Entities/Channels/SocketVoiceChannel.cs b/src/Discord.Net.WebSocket/Entities/Channels/SocketVoiceChannel.cs
index 5fc99c3f1..9036659fe 100644
--- a/src/Discord.Net.WebSocket/Entities/Channels/SocketVoiceChannel.cs
+++ b/src/Discord.Net.WebSocket/Entities/Channels/SocketVoiceChannel.cs
@@ -21,8 +21,12 @@ namespace Discord.WebSocket
///
/// Gets whether or not the guild has Text-In-Voice enabled and the voice channel is a TiV channel.
///
- public virtual bool IsTextInVoice
- => Guild.Features.HasTextInVoice;
+ ///
+ /// Discord currently doesn't have a way to disable Text-In-Voice yet so this field is always
+ /// on s and on
+ /// s.
+ ///
+ public virtual bool IsTextInVoice => true;
///
public int Bitrate { get; private set; }
@@ -46,7 +50,7 @@ namespace Discord.WebSocket
}
internal new static SocketVoiceChannel Create(SocketGuild guild, ClientState state, Model model)
{
- var entity = new SocketVoiceChannel(guild.Discord, model.Id, guild);
+ var entity = new SocketVoiceChannel(guild?.Discord, model.Id, guild);
entity.Update(state, model);
return entity;
}
@@ -54,8 +58,8 @@ namespace Discord.WebSocket
internal override void Update(ClientState state, Model model)
{
base.Update(state, model);
- Bitrate = model.Bitrate.Value;
- UserLimit = model.UserLimit.Value != 0 ? model.UserLimit.Value : (int?)null;
+ Bitrate = model.Bitrate.GetValueOrDefault(64000);
+ UserLimit = model.UserLimit.GetValueOrDefault() != 0 ? model.UserLimit.Value : (int?)null;
RTCRegion = model.RTCRegion.GetValueOrDefault(null);
}
diff --git a/src/Discord.Net.WebSocket/Entities/Guilds/SocketGuild.cs b/src/Discord.Net.WebSocket/Entities/Guilds/SocketGuild.cs
index 9ce2f507a..55f098b2f 100644
--- a/src/Discord.Net.WebSocket/Entities/Guilds/SocketGuild.cs
+++ b/src/Discord.Net.WebSocket/Entities/Guilds/SocketGuild.cs
@@ -532,13 +532,10 @@ namespace Discord.WebSocket
Features = model.Features;
var roles = new ConcurrentDictionary(ConcurrentHashSet.DefaultConcurrencyLevel, (int)(model.Roles.Length * 1.05));
- if (model.Roles != null)
+ for (int i = 0; i < model.Roles.Length; i++)
{
- for (int i = 0; i < model.Roles.Length; i++)
- {
- var role = SocketRole.Create(this, state, model.Roles[i]);
- roles.TryAdd(role.Id, role);
- }
+ var role = SocketRole.Create(this, state, model.Roles[i]);
+ roles.TryAdd(role.Id, role);
}
_roles = roles;
@@ -877,14 +874,17 @@ namespace Discord.WebSocket
///
/// Gets a collection of slash commands created by the current user in this guild.
///
+ /// Whether to include full localization dictionaries in the returned objects, instead of the name localized and description localized fields.
+ /// The target locale of the localized name and description fields. Sets X-Discord-Locale header, which takes precedence over Accept-Language.
/// The options to be used when sending the request.
///
/// A task that represents the asynchronous get operation. The task result contains a read-only collection of
/// slash commands created by the current user.
///
- public async Task> GetApplicationCommandsAsync(RequestOptions options = null)
+ public async Task> GetApplicationCommandsAsync(bool withLocalizations = false, string locale = null, RequestOptions options = null)
{
- var commands = (await Discord.ApiClient.GetGuildApplicationCommandsAsync(Id, options)).Select(x => SocketApplicationCommand.Create(Discord, x, Id));
+ var commands = (await Discord.ApiClient.GetGuildApplicationCommandsAsync(Id, withLocalizations, locale, options))
+ .Select(x => SocketApplicationCommand.Create(Discord, x, Id));
foreach (var command in commands)
{
@@ -1410,7 +1410,7 @@ namespace Discord.WebSocket
///
/// The user to disconnect.
/// A task that represents the asynchronous operation for disconnecting a user.
- async Task IGuild.DisconnectAsync(IGuildUser user) => await user.ModifyAsync(x => x.Channel = new Optional());
+ async Task IGuild.DisconnectAsync(IGuildUser user) => await user.ModifyAsync(x => x.Channel = null);
#endregion
#region Stickers
@@ -1980,8 +1980,8 @@ namespace Discord.WebSocket
async Task> IGuild.GetWebhooksAsync(RequestOptions options)
=> await GetWebhooksAsync(options).ConfigureAwait(false);
///
- async Task> IGuild.GetApplicationCommandsAsync (RequestOptions options)
- => await GetApplicationCommandsAsync(options).ConfigureAwait(false);
+ async Task> IGuild.GetApplicationCommandsAsync (bool withLocalizations, string locale, RequestOptions options)
+ => await GetApplicationCommandsAsync(withLocalizations, locale, options).ConfigureAwait(false);
///
async Task IGuild.CreateStickerAsync(string name, string description, IEnumerable tags, Image image, RequestOptions options)
=> await CreateStickerAsync(name, description, tags, image, options);
diff --git a/src/Discord.Net.WebSocket/Entities/Interaction/ContextMenuCommands/MessageCommands/SocketMessageCommand.cs b/src/Discord.Net.WebSocket/Entities/Interaction/ContextMenuCommands/MessageCommands/SocketMessageCommand.cs
index ad5575caa..0c473bcdd 100644
--- a/src/Discord.Net.WebSocket/Entities/Interaction/ContextMenuCommands/MessageCommands/SocketMessageCommand.cs
+++ b/src/Discord.Net.WebSocket/Entities/Interaction/ContextMenuCommands/MessageCommands/SocketMessageCommand.cs
@@ -20,9 +20,7 @@ namespace Discord.WebSocket
? (DataModel)model.Data.Value
: null;
- ulong? guildId = null;
- if (Channel is SocketGuildChannel guildChannel)
- guildId = guildChannel.Guild.Id;
+ ulong? guildId = model.GuildId.ToNullable();
Data = SocketMessageCommandData.Create(client, dataModel, model.Id, guildId);
}
diff --git a/src/Discord.Net.WebSocket/Entities/Interaction/ContextMenuCommands/UserCommands/SocketUserCommand.cs b/src/Discord.Net.WebSocket/Entities/Interaction/ContextMenuCommands/UserCommands/SocketUserCommand.cs
index c33c06f83..70e06f273 100644
--- a/src/Discord.Net.WebSocket/Entities/Interaction/ContextMenuCommands/UserCommands/SocketUserCommand.cs
+++ b/src/Discord.Net.WebSocket/Entities/Interaction/ContextMenuCommands/UserCommands/SocketUserCommand.cs
@@ -20,9 +20,7 @@ namespace Discord.WebSocket
? (DataModel)model.Data.Value
: null;
- ulong? guildId = null;
- if (Channel is SocketGuildChannel guildChannel)
- guildId = guildChannel.Guild.Id;
+ ulong? guildId = model.GuildId.ToNullable();
Data = SocketUserCommandData.Create(client, dataModel, model.Id, guildId);
}
diff --git a/src/Discord.Net.WebSocket/Entities/Interaction/MessageComponents/SocketMessageComponent.cs b/src/Discord.Net.WebSocket/Entities/Interaction/MessageComponents/SocketMessageComponent.cs
index aeff465bd..2a1a67d04 100644
--- a/src/Discord.Net.WebSocket/Entities/Interaction/MessageComponents/SocketMessageComponent.cs
+++ b/src/Discord.Net.WebSocket/Entities/Interaction/MessageComponents/SocketMessageComponent.cs
@@ -61,7 +61,9 @@ namespace Discord.WebSocket
author = channel.Guild.GetUser(model.Message.Value.Author.Value.Id);
}
else if (model.Message.Value.Author.IsSpecified)
- author = (Channel as SocketChannel).GetUser(model.Message.Value.Author.Value.Id);
+ author = (Channel as SocketChannel)?.GetUser(model.Message.Value.Author.Value.Id);
+
+ author ??= Discord.State.GetOrAddUser(model.Message.Value.Author.Value.Id, _ => SocketGlobalUser.Create(Discord, Discord.State, model.Message.Value.Author.Value));
Message = SocketUserMessage.Create(Discord, Discord.State, author, Channel, model.Message.Value);
}
@@ -226,8 +228,12 @@ namespace Discord.WebSocket
bool hasText = args.Content.IsSpecified ? !string.IsNullOrEmpty(args.Content.Value) : !string.IsNullOrEmpty(Message.Content);
bool hasEmbeds = embed.IsSpecified && embed.Value != null || embeds.IsSpecified && embeds.Value?.Length > 0 || Message.Embeds.Any();
+ bool hasComponents = args.Components.IsSpecified && args.Components.Value != null;
+ bool hasAttachments = args.Attachments.IsSpecified;
+ bool hasFlags = args.Flags.IsSpecified;
- if (!hasText && !hasEmbeds)
+ // No content needed if modifying flags
+ if ((!hasComponents && !hasText && !hasEmbeds && !hasAttachments) && !hasFlags)
Preconditions.NotNullOrEmpty(args.Content.IsSpecified ? args.Content.Value : string.Empty, nameof(args.Content));
var apiEmbeds = embed.IsSpecified || embeds.IsSpecified ? new List() : null;
@@ -261,20 +267,41 @@ namespace Discord.WebSocket
}
}
- var response = new API.InteractionResponse
+ if (!args.Attachments.IsSpecified)
{
- Type = InteractionResponseType.UpdateMessage,
- Data = new API.InteractionCallbackData
+ var response = new API.InteractionResponse
+ {
+ Type = InteractionResponseType.UpdateMessage,
+ Data = new API.InteractionCallbackData
+ {
+ Content = args.Content,
+ AllowedMentions = args.AllowedMentions.IsSpecified ? args.AllowedMentions.Value?.ToModel() : Optional.Unspecified,
+ Embeds = apiEmbeds?.ToArray() ?? Optional.Unspecified,
+ Components = args.Components.IsSpecified
+ ? args.Components.Value?.Components.Select(x => new API.ActionRowComponent(x)).ToArray() ?? Array.Empty()
+ : Optional.Unspecified,
+ Flags = args.Flags.IsSpecified ? args.Flags.Value ?? Optional.Unspecified : Optional.Unspecified
+ }
+ };
+
+ await InteractionHelper.SendInteractionResponseAsync(Discord, response, this, Channel, options).ConfigureAwait(false);
+ }
+ else
+ {
+ var response = new API.Rest.UploadInteractionFileParams(args.Attachments.Value.ToArray())
{
+ Type = InteractionResponseType.UpdateMessage,
Content = args.Content,
AllowedMentions = args.AllowedMentions.IsSpecified ? args.AllowedMentions.Value?.ToModel() : Optional.Unspecified,
Embeds = apiEmbeds?.ToArray() ?? Optional.Unspecified,
- Components = args.Components.IsSpecified
+ MessageComponents = args.Components.IsSpecified
? args.Components.Value?.Components.Select(x => new API.ActionRowComponent(x)).ToArray() ?? Array.Empty()
: Optional.Unspecified,
Flags = args.Flags.IsSpecified ? args.Flags.Value ?? Optional.Unspecified : Optional.Unspecified
- }
- };
+ };
+
+ await InteractionHelper.SendInteractionResponseAsync(Discord, response, this, Channel, options).ConfigureAwait(false);
+ }
lock (_lock)
{
@@ -284,7 +311,6 @@ namespace Discord.WebSocket
}
}
- await InteractionHelper.SendInteractionResponseAsync(Discord, response, this, Channel, options).ConfigureAwait(false);
HasResponded = true;
}
diff --git a/src/Discord.Net.WebSocket/Entities/Interaction/SlashCommands/SocketSlashCommand.cs b/src/Discord.Net.WebSocket/Entities/Interaction/SlashCommands/SocketSlashCommand.cs
index b3aa4a826..69f733e85 100644
--- a/src/Discord.Net.WebSocket/Entities/Interaction/SlashCommands/SocketSlashCommand.cs
+++ b/src/Discord.Net.WebSocket/Entities/Interaction/SlashCommands/SocketSlashCommand.cs
@@ -20,9 +20,7 @@ namespace Discord.WebSocket
? (DataModel)model.Data.Value
: null;
- ulong? guildId = null;
- if (Channel is SocketGuildChannel guildChannel)
- guildId = guildChannel.Guild.Id;
+ ulong? guildId = model.GuildId.ToNullable();
Data = SocketSlashCommandData.Create(client, dataModel, guildId);
}
diff --git a/src/Discord.Net.WebSocket/Entities/Interaction/SocketBaseCommand/SocketApplicationCommand.cs b/src/Discord.Net.WebSocket/Entities/Interaction/SocketBaseCommand/SocketApplicationCommand.cs
index 8f27b65f4..b0ddd0012 100644
--- a/src/Discord.Net.WebSocket/Entities/Interaction/SocketBaseCommand/SocketApplicationCommand.cs
+++ b/src/Discord.Net.WebSocket/Entities/Interaction/SocketBaseCommand/SocketApplicationCommand.cs
@@ -19,7 +19,7 @@ namespace Discord.WebSocket
/// Gets whether or not this command is a global application command.
///
public bool IsGlobalCommand
- => Guild == null;
+ => GuildId is null;
///
public ulong ApplicationId { get; private set; }
@@ -50,6 +50,32 @@ namespace Discord.WebSocket
///
public IReadOnlyCollection Options { get; private set; }
+ ///
+ /// Gets the localization dictionary for the name field of this command.
+ ///
+ public IReadOnlyDictionary NameLocalizations { get; private set; }
+
+ ///
+ /// Gets the localization dictionary for the description field of this command.
+ ///
+ public IReadOnlyDictionary DescriptionLocalizations { get; private set; }
+
+ ///
+ /// Gets the localized name of this command.
+ ///
+ ///
+ /// Only returned when the `withLocalizations` query parameter is set to when requesting the command.
+ ///
+ public string NameLocalized { get; private set; }
+
+ ///
+ /// Gets the localized description of this command.
+ ///
+ ///
+ /// Only returned when the `withLocalizations` query parameter is set to when requesting the command.
+ ///
+ public string DescriptionLocalized { get; private set; }
+
///
public DateTimeOffset CreatedAt
=> SnowflakeUtils.FromSnowflake(Id);
@@ -93,6 +119,15 @@ namespace Discord.WebSocket
? model.Options.Value.Select(SocketApplicationCommandOption.Create).ToImmutableArray()
: ImmutableArray.Create();
+ NameLocalizations = model.NameLocalizations.GetValueOrDefault(null)?.ToImmutableDictionary() ??
+ ImmutableDictionary.Empty;
+
+ DescriptionLocalizations = model.DescriptionLocalizations.GetValueOrDefault(null)?.ToImmutableDictionary() ??
+ ImmutableDictionary.Empty;
+
+ NameLocalized = model.NameLocalized.GetValueOrDefault();
+ DescriptionLocalized = model.DescriptionLocalized.GetValueOrDefault();
+
IsEnabledInDm = model.DmPermission.GetValueOrDefault(true).GetValueOrDefault(true);
DefaultMemberPermissions = new GuildPermissions((ulong)model.DefaultMemberPermission.GetValueOrDefault(0).GetValueOrDefault(0));
}
diff --git a/src/Discord.Net.WebSocket/Entities/Interaction/SocketBaseCommand/SocketApplicationCommandChoice.cs b/src/Discord.Net.WebSocket/Entities/Interaction/SocketBaseCommand/SocketApplicationCommandChoice.cs
index e70efa27b..4da1eaadb 100644
--- a/src/Discord.Net.WebSocket/Entities/Interaction/SocketBaseCommand/SocketApplicationCommandChoice.cs
+++ b/src/Discord.Net.WebSocket/Entities/Interaction/SocketBaseCommand/SocketApplicationCommandChoice.cs
@@ -1,3 +1,5 @@
+using System.Collections.Generic;
+using System.Collections.Immutable;
using Model = Discord.API.ApplicationCommandOptionChoice;
namespace Discord.WebSocket
@@ -13,6 +15,19 @@ namespace Discord.WebSocket
///
public object Value { get; private set; }
+ ///
+ /// Gets the localization dictionary for the name field of this command option choice.
+ ///
+ public IReadOnlyDictionary NameLocalizations { get; private set; }
+
+ ///
+ /// Gets the localized name of this command option choice.
+ ///
+ ///
+ /// Only returned when the `withLocalizations` query parameter is set to when requesting the command.
+ ///
+ public string NameLocalized { get; private set; }
+
internal SocketApplicationCommandChoice() { }
internal static SocketApplicationCommandChoice Create(Model model)
{
@@ -24,6 +39,8 @@ namespace Discord.WebSocket
{
Name = model.Name;
Value = model.Value;
+ NameLocalizations = model.NameLocalizations.GetValueOrDefault(null)?.ToImmutableDictionary();
+ NameLocalized = model.NameLocalized.GetValueOrDefault(null);
}
}
}
diff --git a/src/Discord.Net.WebSocket/Entities/Interaction/SocketBaseCommand/SocketApplicationCommandOption.cs b/src/Discord.Net.WebSocket/Entities/Interaction/SocketBaseCommand/SocketApplicationCommandOption.cs
index 27777749a..78bb45141 100644
--- a/src/Discord.Net.WebSocket/Entities/Interaction/SocketBaseCommand/SocketApplicationCommandOption.cs
+++ b/src/Discord.Net.WebSocket/Entities/Interaction/SocketBaseCommand/SocketApplicationCommandOption.cs
@@ -33,6 +33,12 @@ namespace Discord.WebSocket
///
public double? MaxValue { get; private set; }
+ ///
+ public int? MinLength { get; private set; }
+
+ ///
+ public int? MaxLength { get; private set; }
+
///
/// Gets a collection of choices for the user to pick from.
///
@@ -48,6 +54,32 @@ namespace Discord.WebSocket
///
public IReadOnlyCollection ChannelTypes { get; private set; }
+ ///
+ /// Gets the localization dictionary for the name field of this command option.
+ ///
+ public IReadOnlyDictionary NameLocalizations { get; private set; }
+
+ ///
+ /// Gets the localization dictionary for the description field of this command option.
+ ///
+ public IReadOnlyDictionary DescriptionLocalizations { get; private set; }
+
+ ///
+ /// Gets the localized name of this command option.
+ ///
+ ///
+ /// Only returned when the `withLocalizations` query parameter is set to when requesting the command.
+ ///
+ public string NameLocalized { get; private set; }
+
+ ///
+ /// Gets the localized description of this command option.
+ ///
+ ///
+ /// Only returned when the `withLocalizations` query parameter is set to when requesting the command.
+ ///
+ public string DescriptionLocalized { get; private set; }
+
internal SocketApplicationCommandOption() { }
internal static SocketApplicationCommandOption Create(Model model)
{
@@ -72,6 +104,9 @@ namespace Discord.WebSocket
IsAutocomplete = model.Autocomplete.ToNullable();
+ MinLength = model.MinLength.ToNullable();
+ MaxLength = model.MaxLength.ToNullable();
+
Choices = model.Choices.IsSpecified
? model.Choices.Value.Select(SocketApplicationCommandChoice.Create).ToImmutableArray()
: ImmutableArray.Create();
@@ -83,6 +118,15 @@ namespace Discord.WebSocket
ChannelTypes = model.ChannelTypes.IsSpecified
? model.ChannelTypes.Value.ToImmutableArray()
: ImmutableArray.Create();
+
+ NameLocalizations = model.NameLocalizations.GetValueOrDefault(null)?.ToImmutableDictionary() ??
+ ImmutableDictionary.Empty;
+
+ DescriptionLocalizations = model.DescriptionLocalizations.GetValueOrDefault(null)?.ToImmutableDictionary() ??
+ ImmutableDictionary.Empty;
+
+ NameLocalized = model.NameLocalized.GetValueOrDefault();
+ DescriptionLocalized = model.DescriptionLocalized.GetValueOrDefault();
}
IReadOnlyCollection IApplicationCommandOption.Choices => Choices;
diff --git a/src/Discord.Net.WebSocket/Entities/Interaction/SocketBaseCommand/SocketCommandBase.cs b/src/Discord.Net.WebSocket/Entities/Interaction/SocketBaseCommand/SocketCommandBase.cs
index 273f27c9c..bdab128f4 100644
--- a/src/Discord.Net.WebSocket/Entities/Interaction/SocketBaseCommand/SocketCommandBase.cs
+++ b/src/Discord.Net.WebSocket/Entities/Interaction/SocketBaseCommand/SocketCommandBase.cs
@@ -43,9 +43,7 @@ namespace Discord.WebSocket
? (DataModel)model.Data.Value
: null;
- ulong? guildId = null;
- if (Channel is SocketGuildChannel guildChannel)
- guildId = guildChannel.Guild.Id;
+ ulong? guildId = model.GuildId.ToNullable();
Data = SocketCommandBaseData.Create(client, dataModel, model.Id, guildId);
}
diff --git a/src/Discord.Net.WebSocket/Entities/Interaction/SocketBaseCommand/SocketResolvableData.cs b/src/Discord.Net.WebSocket/Entities/Interaction/SocketBaseCommand/SocketResolvableData.cs
index a629fd069..2167a69a1 100644
--- a/src/Discord.Net.WebSocket/Entities/Interaction/SocketBaseCommand/SocketResolvableData.cs
+++ b/src/Discord.Net.WebSocket/Entities/Interaction/SocketBaseCommand/SocketResolvableData.cs
@@ -1,3 +1,4 @@
+using Discord.Net;
using System.Collections.Generic;
namespace Discord.WebSocket
@@ -39,19 +40,30 @@ namespace Discord.WebSocket
{
foreach (var channel in resolved.Channels.Value)
{
- SocketChannel socketChannel = guild != null
+ var socketChannel = guild != null
? guild.GetChannel(channel.Value.Id)
: discord.GetChannel(channel.Value.Id);
if (socketChannel == null)
{
- var channelModel = guild != null
- ? discord.Rest.ApiClient.GetChannelAsync(guild.Id, channel.Value.Id).ConfigureAwait(false).GetAwaiter().GetResult()
- : discord.Rest.ApiClient.GetChannelAsync(channel.Value.Id).ConfigureAwait(false).GetAwaiter().GetResult();
-
- socketChannel = guild != null
- ? SocketGuildChannel.Create(guild, discord.State, channelModel)
- : (SocketChannel)SocketChannel.CreatePrivate(discord, discord.State, channelModel);
+ try
+ {
+ var channelModel = guild != null
+ ? discord.Rest.ApiClient.GetChannelAsync(guild.Id, channel.Value.Id)
+ .ConfigureAwait(false).GetAwaiter().GetResult()
+ : discord.Rest.ApiClient.GetChannelAsync(channel.Value.Id).ConfigureAwait(false)
+ .GetAwaiter().GetResult();
+
+ socketChannel = guild != null
+ ? SocketGuildChannel.Create(guild, discord.State, channelModel)
+ : (SocketChannel)SocketChannel.CreatePrivate(discord, discord.State, channelModel);
+ }
+ catch (HttpException ex) when (ex.DiscordCode == DiscordErrorCode.MissingPermissions)
+ {
+ socketChannel = guildId != null
+ ? SocketGuildChannel.Create(guild, discord.State, channel.Value)
+ : (SocketChannel)SocketChannel.CreatePrivate(discord, discord.State, channel.Value);
+ }
}
discord.State.AddChannel(socketChannel);
@@ -69,11 +81,14 @@ namespace Discord.WebSocket
}
}
- if (resolved.Roles.IsSpecified)
+ if (resolved.Roles.IsSpecified && guild != null)
{
foreach (var role in resolved.Roles.Value)
{
- var socketRole = guild.AddOrUpdateRole(role.Value);
+ var socketRole = guild is null
+ ? SocketRole.Create(null, discord.State, role.Value)
+ : guild.AddOrUpdateRole(role.Value);
+
Roles.Add(ulong.Parse(role.Key), socketRole);
}
}
@@ -93,16 +108,19 @@ namespace Discord.WebSocket
author = guild.GetUser(msg.Value.Author.Value.Id);
}
else
- author = (channel as SocketChannel).GetUser(msg.Value.Author.Value.Id);
+ author = (channel as SocketChannel)?.GetUser(msg.Value.Author.Value.Id);
if (channel == null)
{
- if (!msg.Value.GuildId.IsSpecified) // assume it is a DM
+ if (guildId is null) // assume it is a DM
{
channel = discord.CreateDMChannel(msg.Value.ChannelId, msg.Value.Author.Value, discord.State);
+ author = ((SocketDMChannel)channel).Recipient;
}
}
+ author ??= discord.State.GetOrAddUser(msg.Value.Author.Value.Id, _ => SocketGlobalUser.Create(discord, discord.State, msg.Value.Author.Value));
+
var message = SocketMessage.Create(discord, discord.State, author, channel, msg.Value);
Messages.Add(message.Id, message);
}
diff --git a/src/Discord.Net.WebSocket/Entities/Messages/SocketUserMessage.cs b/src/Discord.Net.WebSocket/Entities/Messages/SocketUserMessage.cs
index e5776a089..f5abb2c49 100644
--- a/src/Discord.Net.WebSocket/Entities/Messages/SocketUserMessage.cs
+++ b/src/Discord.Net.WebSocket/Entities/Messages/SocketUserMessage.cs
@@ -127,7 +127,7 @@ namespace Discord.WebSocket
refMsgAuthor = guild.GetUser(refMsg.Author.Value.Id);
}
else
- refMsgAuthor = (Channel as SocketChannel).GetUser(refMsg.Author.Value.Id);
+ refMsgAuthor = (Channel as SocketChannel)?.GetUser(refMsg.Author.Value.Id);
if (refMsgAuthor == null)
refMsgAuthor = SocketUnknownUser.Create(Discord, state, refMsg.Author.Value);
}
diff --git a/src/Discord.Net.WebSocket/Entities/Roles/SocketRole.cs b/src/Discord.Net.WebSocket/Entities/Roles/SocketRole.cs
index 1e90b8f5c..b6a61cfb0 100644
--- a/src/Discord.Net.WebSocket/Entities/Roles/SocketRole.cs
+++ b/src/Discord.Net.WebSocket/Entities/Roles/SocketRole.cs
@@ -63,7 +63,7 @@ namespace Discord.WebSocket
=> Guild.Users.Where(x => x.Roles.Any(r => r.Id == Id));
internal SocketRole(SocketGuild guild, ulong id)
- : base(guild.Discord, id)
+ : base(guild?.Discord, id)
{
Guild = guild;
}
diff --git a/src/Discord.Net/Discord.Net.nuspec b/src/Discord.Net/Discord.Net.nuspec
index f7a9bd467..63a288dc3 100644
--- a/src/Discord.Net/Discord.Net.nuspec
+++ b/src/Discord.Net/Discord.Net.nuspec
@@ -2,7 +2,7 @@
Discord.Net
- 3.7.1$suffix$
+ 3.8.0$suffix$
Discord.Net
Discord.Net Contributors
foxbot
@@ -14,44 +14,44 @@
https://github.com/discord-net/Discord.Net/raw/dev/docs/marketing/logo/PackageLogo.png
-
-
-
-
-
-
+
+
+
+
+
+
-
-
-
-
-
-
+
+
+
+
+
+
-
-
-
-
-
-
+
+
+
+
+
+
-
-
-
-
-
-
+
+
+
+
+
+
-
-
-
-
-
-
+
+
+
+
+
+
diff --git a/test/Discord.Net.Tests.Unit/ColorTests.cs b/test/Discord.Net.Tests.Unit/ColorTests.cs
index 46d8feabb..48a6041e5 100644
--- a/test/Discord.Net.Tests.Unit/ColorTests.cs
+++ b/test/Discord.Net.Tests.Unit/ColorTests.cs
@@ -10,6 +10,7 @@ namespace Discord
///
public class ColorTests
{
+ [Fact]
public void Color_New()
{
Assert.Equal(0u, new Color().RawValue);
diff --git a/test/Discord.Net.Tests.Unit/MockedEntities/MockedVoiceChannel.cs b/test/Discord.Net.Tests.Unit/MockedEntities/MockedVoiceChannel.cs
index fdbdeda5e..2ffc75a24 100644
--- a/test/Discord.Net.Tests.Unit/MockedEntities/MockedVoiceChannel.cs
+++ b/test/Discord.Net.Tests.Unit/MockedEntities/MockedVoiceChannel.cs
@@ -12,6 +12,9 @@ namespace Discord
public int Bitrate => throw new NotImplementedException();
public int? UserLimit => throw new NotImplementedException();
+ public Task DeleteMessagesAsync(IEnumerable messages, RequestOptions options = null) => throw new NotImplementedException();
+
+ public Task DeleteMessagesAsync(IEnumerable messageIds, RequestOptions options = null) => throw new NotImplementedException();
public ulong? CategoryId => throw new NotImplementedException();