使用 SlashCommandAttribute 不适用于 Discord.Net

Pau*_*ram 5 .net c# discord discord.net

斜杠命令已与交互框架一起添加到Discord.Net中。

通过查看文档,我发现我们可以在继承SlashCommandAttributeInteractionModuleBase. 更多信息可以在这里找到。

请注意,我已经让这个机器人运行了一年多,所以它完全可以使用基本命令,并且我现在正在尝试更新它以使用斜杠命令。

我尝试过的是以下步骤:

  1. 在我的主要方法中,我监听了客户端就绪事件:

    _client.Ready += _client_Ready;
    
    Run Code Online (Sandbox Code Playgroud)
  2. 在_client_Ready函数中,您可以找到以下代码:

     private async Task _client_Ready()
     {
         _interactionService = new InteractionService(_client);
         await _interactionService.AddModulesAsync(Assembly.GetEntryAssembly(), _serviceProvider);
         await _interactionService.RegisterCommandsToGuildAsync(_guildId);
     }
    
    Run Code Online (Sandbox Code Playgroud)
  3. 我创建了一个继承自 InteractionModuleBase 的模块,如下所示:

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

当我运行机器人并访问我的不和谐服务器时,我可以看到已注册的斜杠命令:

显示斜杠命令的图像

但是,当我尝试使用它时,我在 Discord 上收到错误消息,指出应用程序没有响应,并且函数内的断点Echo根本没有被命中。

我不确定这是否是斜杠命令的用途,因为显然还有另一种方法可以做到这一点,但它看起来不像具有属性的模块那么干净。

有没有人能够在模块中使用斜杠命令SlashCommandAttribute,如何使用?

Pau*_*ram 8

在文档中找到名为“执行命令”的部分后,我能够解决该问题

我必须InteractionCreated在事件_client内部添加一个事件侦听器_client_Ready

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);
    };
}
Run Code Online (Sandbox Code Playgroud)

完成此操作后,斜杠命令将在模块内执行,我可以看到结果。