0

The official discord.net API shows this only for a text-based commands but i have a problem with the SlashCommandExecuter blocking the gateway task. I initialize commands using this code:

public async Task Client_Ready()
    {
        var client = _Provider.GetRequiredService<DiscordSocketClient>();
        var ExampleCommand = new SlashCommandBuilder()
            .WithName("examplecommand")
            .WithDescription("This is a long running command");

        try
        {
            await client.CreateGlobalApplicationCommandAsync(ExampleCommand.Build());
        }
        catch (HttpException exception)
        {
            var json = JsonConvert.SerializeObject(exception.Errors, Formatting.Indented);

            Console.WriteLine(json);
        }
    }

And handle them using interaction SlashCommandExecuted in the Main Async and a separate task with command.Data.Name switch.

I searched for this parameter in the SlashCommandBuilder and also in RespondAsync. I know that i can set runmode in the CommandService config but i do not need async runmode in all of my commands. Is there any way around it? AI also doesn't give any valid answer often writing some spagetti code or showing the use of it with the ModuleBase. I found one possible option but it doesn't work either:

    private async Task SlashCommandHandler(SocketSlashCommand command)
{
    await Task.Run(async () =>
    {
        // Do some long-running task
        await Task.Delay(5000);

        // Respond to the command
        await command.RespondAsync("Command completed.");
    });
}
Stefanidze
  • 50
  • 6

1 Answers1

0

If you don't want your async code to block the Main Thread you should fire and forget it. So don't await your Task:

_ = Task.Run(async () =>
{
    // Do some long-running task
    await Task.Delay(5000);

    // Respond to the command
    await command.RespondAsync("Command completed.");
});

Nevertheless, I would recommend that you take a look at the Interaction Framework. This is very similar to the one for the TextCommands. There you can just use an Attribute like this:

[SlashCommand("test", "A sample description", runMode: RunMode.Async)]
public async Task TestCommand(string test)
{
  // do smth.
}
Julian
  • 312
  • 2
  • 14