为了账号安全,请及时绑定邮箱和手机立即绑定

无法执行命令

无法执行命令

C#
精慕HU 2021-10-09 10:24:12
我为我的不和谐机器人编写了一个简单的模块。机器人:_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 beginsint argPos = 0;// Determine if the message is a command, based on if it starts with '!' or a mention prefixif (!(message.HasCharPrefix('!', ref argPos) || message.HasMentionPrefix(_client.CurrentUser, ref argPos))) return;// Create a Command Contextvar 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不会被调用。我在这里缺少什么?
查看完整描述

1 回答

?
ITMISS

TA贡献1871条经验 获得超8个赞

你似乎没有注入MyService到你的ServiceCollection。

如果不注入服务,则永远无法创建模块,因为您将其定义为依赖项


private readonly MyService _service;

public MyModule(MyService service)

{

    _service = service;

}

要解决此问题,您可以将您MyService的添加到ServiceCollection.

为此,最好创建一个IMyService(接口)并将其添加到您的注射中


_serviceProvider = new ServiceCollection()

 .AddSingleton(_client)

 .AddSingleton(_commandService)

 .AddSingleton<IMyService, MyService>()

 .BuildServiceProvider();


查看完整回答
反对 回复 2021-10-09
  • 1 回答
  • 0 关注
  • 152 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信