无法执行命令

时间:2018-07-15 13:04:32

标签: c# discord.net

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

启动:

interface Foo {
  type: string;
}
interface FooA {
  type: 'A';
}
interface FooB {
  type: 'B';
}

const handlers = {
  A: (fooA: FooA) => console.log(fooA),
  B: (fooB: FooB) => console.log(fooB),
}

// Untyped library function that we know returns some Foo-extending type
function fooFactory(type: string): any {
  return type === 'A' ? {type: 'A'} : {type: 'B'};
}

// Retrieves a Foo and calls a handler against it before doing other work
function getAndUseFoo<T extends Foo>(type: string, handler: (foo: T) => any) {
  const foo: T = fooFactory(type);
  handler(foo);
  // Do more work with foo
}

function problemFunction(type: 'A' | 'B') {
  // TypeScript thinks handlers[type] is a union type with incompatible types
  const foo = getAndUseFoo(type, handlers[type]);
}

模块:

_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方法。

我在这里想念什么?

1 个答案:

答案 0 :(得分:1)

您似乎没有将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();