@@ -20,12 +20,16 @@ namespace _02_commands_framework.Services
_discord = services.GetRequiredService<DiscordSocketClient>();
_discord = services.GetRequiredService<DiscordSocketClient>();
_services = services;
_services = services;
// Hook CommandExecuted to handle post-command-execution logic.
_commands.CommandExecuted += CommandExecutedAsync;
_commands.CommandExecuted += CommandExecutedAsync;
// Hook MessageReceived so we can process each message to see
// if it qualifies as a command.
_discord.MessageReceived += MessageReceivedAsync;
_discord.MessageReceived += MessageReceivedAsync;
}
}
public async Task InitializeAsync()
public async Task InitializeAsync()
{
{
// Register modules that are public and inherit ModuleBase<T>.
await _commands.AddModulesAsync(Assembly.GetEntryAssembly(), _services);
await _commands.AddModulesAsync(Assembly.GetEntryAssembly(), _services);
}
}
@@ -37,10 +41,18 @@ namespace _02_commands_framework.Services
// This value holds the offset where the prefix ends
// This value holds the offset where the prefix ends
var argPos = 0;
var argPos = 0;
// Perform prefix check. You may want to replace this with
// (!message.HasCharPrefix('!', ref argPos))
// for a more traditional command format like !help.
if (!message.HasMentionPrefix(_discord.CurrentUser, ref argPos)) return;
if (!message.HasMentionPrefix(_discord.CurrentUser, ref argPos)) return;
var context = new SocketCommandContext(_discord, message);
var context = new SocketCommandContext(_discord, message);
await _commands.ExecuteAsync(context, argPos, _services); // we will handle the result in CommandExecutedAsync
// Perform the execution of the command. In this method,
// the command service will perform precondition and parsing check
// then execute the command if one is matched.
await _commands.ExecuteAsync(context, argPos, _services);
// Note that normally a result will be returned by this format, but here
// we will handle the result in CommandExecutedAsync,
}
}
public async Task CommandExecutedAsync(Optional<CommandInfo> command, ICommandContext context, IResult result)
public async Task CommandExecutedAsync(Optional<CommandInfo> command, ICommandContext context, IResult result)
@@ -49,12 +61,12 @@ namespace _02_commands_framework.Services
if (!command.IsSpecified)
if (!command.IsSpecified)
return;
return;
// the command was succesful, we don't care about this result, unless we want to log that a command succeeded.
// the command was success ful, we don't care about this result, unless we want to log that a command succeeded.
if (result.IsSuccess)
if (result.IsSuccess)
return;
return;
// the command failed, let's notify the user that something happened.
// the command failed, let's notify the user that something happened.
await context.Channel.SendMessageAsync($"error: {result.ToString() }");
await context.Channel.SendMessageAsync($"error: {result}");
}
}
}
}
}
}