无法执行命令

我为我的不和谐机器人编写了一个简单的模块。


机器人:


_client = new DiscordSocketClient();

_commandService = new CommandService();


_serviceProvider = new ServiceCollection()

     .AddSingleton(_client)

     .AddSingleton(_commandService)

     .BuildServiceProvider();

模块:


public class MyModule: ModuleBase<ICommandContext>

{

    private readonly MyService _service;


    public MyModule(MyService service)

    {

        _service = service;

    }


    [Command("DoStuff", RunMode = RunMode.Async)]

    public async Task DoStuffCmd()

    {

        await _service.DoStuff(Context.Guild, (Context.User as IVoiceState).VoiceChannel);

    }

}

模块添加如下:


await _commandService.AddModulesAsync(Assembly.GetEntryAssembly());

添加模块显式将导致该模块已经添加的异常,所以我假设它有效。


我像这样处理命令。


// Create a number to track where the prefix ends and the command begins

int argPos = 0;

// Determine if the message is a command, based on if it starts with '!' or a mention prefix

if (!(message.HasCharPrefix('!', ref argPos) || message.HasMentionPrefix(_client.CurrentUser, ref argPos))) return;

// Create a Command Context

var context = new CommandContext(_client, message);

// Execute the command. (result does not indicate a return value, 

// rather an object stating if the command executed successfully)

var result = await _commandService.ExecuteAsync(context, argPos, _serviceProvider);

该result变量总是返回Success,但DoStuffCmd在方法MyModule不会被调用。


我在这里缺少什么?


精慕HU
浏览 153回答 1
1回答

ITMISS

你似乎没有注入MyService到你的ServiceCollection。如果不注入服务,则永远无法创建模块,因为您将其定义为依赖项private readonly MyService _service;public MyModule(MyService service){&nbsp; &nbsp; _service = service;}要解决此问题,您可以将您MyService的添加到ServiceCollection.为此,最好创建一个IMyService(接口)并将其添加到您的注射中_serviceProvider = new ServiceCollection()&nbsp;.AddSingleton(_client)&nbsp;.AddSingleton(_commandService)&nbsp;.AddSingleton<IMyService, MyService>()&nbsp;.BuildServiceProvider();
打开App,查看更多内容
随时随地看视频慕课网APP