亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

無法執行命令

無法執行命令

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 關注
  • 176 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號