Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Clarify command samples #1257

Merged
merged 4 commits into from
Mar 16, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions samples/02_commands_framework/Modules/PublicModule.cs
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ public Task EchoAsync([Remainder] string text)
public Task ListAsync(params string[] objects)
=> ReplyAsync("You listed: " + string.Join("; ", objects));

// Setting a custom ErrorMessage property will help clarify the precondition error
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This comment could be moved one line down so that it's more obvious what it's referring to.

[Command("guild_only")]
[RequireContext(ContextType.Guild, ErrorMessage = "Sorry, this command must be ran from within a server, not a DM!")]
public Task GuildOnlyCommand()
Expand Down
4 changes: 3 additions & 1 deletion samples/02_commands_framework/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,10 +37,12 @@ public async Task MainAsync()
client.Log += LogAsync;
services.GetRequiredService<CommandService>().Log += LogAsync;

// Tokens should be considered secret data, and never hard-coded.
// Tokens should be considered secret data and never hard-coded.
// We can read from the environment variable to avoid hardcoding.
await client.LoginAsync(TokenType.Bot, Environment.GetEnvironmentVariable("token"));
await client.StartAsync();

// Here we initialize the logic required to register our commands.
await services.GetRequiredService<CommandHandlingService>().InitializeAsync();

await Task.Delay(-1);
Expand Down
18 changes: 15 additions & 3 deletions samples/02_commands_framework/Services/CommandHandlingService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,16 @@ public CommandHandlingService(IServiceProvider services)
_discord = services.GetRequiredService<DiscordSocketClient>();
_services = services;

// Hook CommandExecuted to handle post-command-execution logic.
_commands.CommandExecuted += CommandExecutedAsync;
// Hook MessageReceived so we can process each message to see
// if it qualifies as a command.
_discord.MessageReceived += MessageReceivedAsync;
}

public async Task InitializeAsync()
{
// Register modules that are public and inherit ModuleBase<T>.
await _commands.AddModulesAsync(Assembly.GetEntryAssembly(), _services);
}

Expand All @@ -37,10 +41,18 @@ public async Task MessageReceivedAsync(SocketMessage rawMessage)

// This value holds the offset where the prefix ends
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;

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)
Expand All @@ -49,12 +61,12 @@ public async Task CommandExecutedAsync(Optional<CommandInfo> command, ICommandCo
if (!command.IsSpecified)
return;

// the command was succesful, we don't care about this result, unless we want to log that a command succeeded.
// the command was successful, we don't care about this result, unless we want to log that a command succeeded.
if (result.IsSuccess)
return;

// the command failed, let's notify the user that something happened.
await context.Channel.SendMessageAsync($"error: {result.ToString()}");
await context.Channel.SendMessageAsync($"error: {result}");
}
}
}