如何在discord.net中设置斜杠命令的运行模式?



官方discord.net API显示这仅用于基于文本的命令,但我有一个问题与slashcommandexexecuter阻塞网关任务。我使用以下代码初始化命令:

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);
}
}

和处理他们使用交互SlashCommandExecuted在主异步和一个单独的任务与command.Data.Name开关。

我在SlashCommandBuilder和RespondAsync中搜索了这个参数。我知道我可以在CommandService配置中设置运行模式,但我不需要在我的所有命令中异步运行模式。还有别的办法吗?AI也没有给出任何有效的答案,经常写一些意大利面代码或显示它与ModuleBase的使用。我找到了一个可能的选择,但它也不起作用:

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.");
});
}

如果你不想让你的异步代码阻塞主线程,你应该触发并忘记它。所以不要等待你的任务:

_ = Task.Run(async () =>
{
// Do some long-running task
await Task.Delay(5000);
// Respond to the command
await command.RespondAsync("Command completed.");
});

尽管如此,我还是建议您看一下交互框架。这与TextCommands非常相似。你可以使用这样的属性:

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

最新更新