Reputation:
I wrote a simple module for my discord bot.
Bot:
_client = new DiscordSocketClient();
_commandService = new CommandService();
_serviceProvider = new ServiceCollection()
.AddSingleton(_client)
.AddSingleton(_commandService)
.BuildServiceProvider();
Module:
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);
}
}
Modules get added like this:
await _commandService.AddModulesAsync(Assembly.GetEntryAssembly());
Adding the Module explicit will result in the exception that this modlue has already been added, so i assume it worked.
I handle the Command like this.
// 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);
The result
variable always returns Success
but DoStuffCmd
Method in MyModule
never gets called.
What am I missing here?
Upvotes: 0
Views: 133
Reputation: 2485
You don't seem to inject the MyService
into your ServiceCollection
.
If you do not inject the service, your module can never be created, as you defined it as a dependency
private readonly MyService _service;
public MyModule(MyService service)
{
_service = service;
}
To fix this you can add your MyService
to the ServiceCollection
.
To do this, it would be best to Create a IMyService
(interface) and add this to your injections as such
_serviceProvider = new ServiceCollection()
.AddSingleton(_client)
.AddSingleton(_commandService)
.AddSingleton<IMyService, MyService>()
.BuildServiceProvider();
Upvotes: 1