Add DiscordShardedClient sample project & Client FAQ entry. (#1177)
* Add DiscordShardedClient sample project & Client FAQ entry. * Revise language, fix typo, add xrefs * Adjust placement of message handler. * Resolve DI issue with initialized client; properly initialize command handling service.
This commit is contained in:
committed by
Christopher F
parent
fb8dbcae4b
commit
00097d3c27
52
samples/03_sharded_client/Services/CommandHandlingService.cs
Normal file
52
samples/03_sharded_client/Services/CommandHandlingService.cs
Normal file
@@ -0,0 +1,52 @@
|
||||
using System;
|
||||
using System.Reflection;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Discord;
|
||||
using Discord.Commands;
|
||||
using Discord.WebSocket;
|
||||
|
||||
namespace _03_sharded_client.Services
|
||||
{
|
||||
public class CommandHandlingService
|
||||
{
|
||||
private readonly CommandService _commands;
|
||||
private readonly DiscordShardedClient _discord;
|
||||
private readonly IServiceProvider _services;
|
||||
|
||||
public CommandHandlingService(IServiceProvider services)
|
||||
{
|
||||
_commands = services.GetRequiredService<CommandService>();
|
||||
_discord = services.GetRequiredService<DiscordShardedClient>();
|
||||
_services = services;
|
||||
}
|
||||
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
await _commands.AddModulesAsync(Assembly.GetEntryAssembly(), _services);
|
||||
_discord.MessageReceived += MessageReceivedAsync;
|
||||
}
|
||||
|
||||
public async Task MessageReceivedAsync(SocketMessage rawMessage)
|
||||
{
|
||||
// Ignore system messages, or messages from other bots
|
||||
if (!(rawMessage is SocketUserMessage message))
|
||||
return;
|
||||
if (message.Source != MessageSource.User)
|
||||
return;
|
||||
|
||||
// This value holds the offset where the prefix ends
|
||||
var argPos = 0;
|
||||
if (!message.HasMentionPrefix(_discord.CurrentUser, ref argPos))
|
||||
return;
|
||||
|
||||
// A new kind of command context, ShardedCommandContext can be utilized with the commands framework
|
||||
var context = new ShardedCommandContext(_discord, message);
|
||||
var result = await _commands.ExecuteAsync(context, argPos, _services);
|
||||
|
||||
if (result.Error.HasValue &&
|
||||
result.Error.Value != CommandError.UnknownCommand) // it's bad practice to send 'unknown command' errors
|
||||
await context.Channel.SendMessageAsync(result.ToString());
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user