Using SlashCommandAttribute not working with Discord.Net

Slash commands have been added to Discord.Net along side the Interaction Framework.

By going through the documentation, I found out that we can use the SlashCommandAttribute inside a module that inherits from InteractionModuleBase. More info can be found here.

Please note that I've already had this bot running for over a year now, so it's fully working with basic commands, and I am trying to update it to work with slash commands now.

What I have tried is the following steps:

  1. Inside my main method, I listened to client ready event:

    _client.Ready += _client_Ready;
    
  2. Inside the _client_Ready function, you can find the following code:

     private async Task _client_Ready()
     {
         _interactionService = new InteractionService(_client);
         await _interactionService.AddModulesAsync(Assembly.GetEntryAssembly(), _serviceProvider);
         await _interactionService.RegisterCommandsToGuildAsync(_guildId);
     }
    
  3. I created a module that inherits from InteractionModuleBase as following:

    public class TestingSlashCommandModule : InteractionModuleBase<SocketInteractionContext>
    {
        [SlashCommand("test-slash", "Echo an input")]
        public async Task Echo(string input)
        {
            await RespondAsync(input);
        }
    }
    

When I run the bot and go to my discord server, I can see the slash command registered:

Image showing the slash command

However, when I try to use it, I get an error on Discord saying that the application did not respond, and the breakpoint inside the Echo function isn't being hit at all.

I am not sure if this is how slash commands are intended to be used because there's another way to do it, apparently, but it doesn't look as clean as the modules with the attributes.

Has anyone been able to use slash commands within the modules using the SlashCommandAttribute, and how so?


I was able to fix that after I found a section in the documentation called Executing Commands

I had to add an event listener to InteractionCreated on _client inside the _client_Ready event:

private async Task _client_Ready()
{
    _interactionService = new InteractionService(_client);
    await _interactionService.AddModulesAsync(Assembly.GetEntryAssembly(), _serviceProvider);
    await _interactionService.RegisterCommandsToGuildAsync(_guildId);

    _client.InteractionCreated += async interaction =>
    {
        var scope = _serviceProvider.CreateScope();
        var ctx = new SocketInteractionContext(_client, interaction);
        await _interactionService.ExecuteCommandAsync(ctx, scope.ServiceProvider);
    };
}

After doing this, the slash commands are being executed within the modules and I can see the result.