From 02d3ce6e0158e5d4fce145d2ec46741fa8d1ac1f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gediminas=20Mila=C5=A1ius?= <8672277+GedasFX@users.noreply.github.com> Date: Sat, 21 Jan 2023 12:48:36 +0200 Subject: [PATCH] Fix NullReferenceException caused by Options being undefined. (#2549) --- .../SlashCommands/SlashCommandBuilder.cs | 4 +++- .../CommandBuilderTests.cs | 20 ++++++++++++++++++- 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/src/Discord.Net.Core/Entities/Interactions/SlashCommands/SlashCommandBuilder.cs b/src/Discord.Net.Core/Entities/Interactions/SlashCommands/SlashCommandBuilder.cs index b0b8e9600..295986bb5 100644 --- a/src/Discord.Net.Core/Entities/Interactions/SlashCommands/SlashCommandBuilder.cs +++ b/src/Discord.Net.Core/Entities/Interactions/SlashCommands/SlashCommandBuilder.cs @@ -664,7 +664,9 @@ namespace Discord if (options == null) throw new ArgumentNullException(nameof(options), "Options cannot be null!"); - if ((Options?.Count ?? 0) + options.Length > SlashCommandBuilder.MaxOptionsCount) + Options ??= new List(); + + if (Options.Count + 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) diff --git a/test/Discord.Net.Tests.Unit/CommandBuilderTests.cs b/test/Discord.Net.Tests.Unit/CommandBuilderTests.cs index e122f9cdd..c804f21db 100644 --- a/test/Discord.Net.Tests.Unit/CommandBuilderTests.cs +++ b/test/Discord.Net.Tests.Unit/CommandBuilderTests.cs @@ -17,7 +17,7 @@ public class CommandBuilderTests ApplicationCommandOptionType.String, "option1 description", isRequired: true, - choices: new [] + choices: new [] { new ApplicationCommandOptionChoiceProperties() { @@ -34,4 +34,22 @@ public class CommandBuilderTests .AddChoice("choice2", "2")); command.Build(); } + + [Fact] + public void BuildSubSlashCommand() + { + var command = new SlashCommandBuilder() + .WithName("command").WithDescription("Command desc.") + .AddOptions(new SlashCommandOptionBuilder() + .WithType(ApplicationCommandOptionType.SubCommand) + .WithName("subcommand").WithDescription("Subcommand desc.") + .AddOptions( + new SlashCommandOptionBuilder() + .WithType(ApplicationCommandOptionType.String) + .WithName("name1").WithDescription("desc1"), + new SlashCommandOptionBuilder() + .WithType(ApplicationCommandOptionType.String) + .WithName("name2").WithDescription("desc2"))); + command.Build(); + } }