You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

CommandHandlingService.cs 2.6 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. using System;
  2. using System.Reflection;
  3. using System.Threading.Tasks;
  4. using Microsoft.Extensions.DependencyInjection;
  5. using Discord;
  6. using Discord.Commands;
  7. using Discord.WebSocket;
  8. namespace _03_sharded_client.Services
  9. {
  10. public class CommandHandlingService
  11. {
  12. private readonly CommandService _commands;
  13. private readonly DiscordShardedClient _discord;
  14. private readonly IServiceProvider _services;
  15. public CommandHandlingService(IServiceProvider services)
  16. {
  17. _commands = services.GetRequiredService<CommandService>();
  18. _discord = services.GetRequiredService<DiscordShardedClient>();
  19. _services = services;
  20. _commands.CommandExecuted += CommandExecutedAsync;
  21. _commands.Log += LogAsync;
  22. _discord.MessageReceived += MessageReceivedAsync;
  23. }
  24. public async Task InitializeAsync()
  25. {
  26. await _commands.AddModulesAsync(Assembly.GetEntryAssembly(), _services);
  27. }
  28. public async Task MessageReceivedAsync(SocketMessage rawMessage)
  29. {
  30. // Ignore system messages, or messages from other bots
  31. if (!(rawMessage is SocketUserMessage message))
  32. return;
  33. if (message.Source != MessageSource.User)
  34. return;
  35. // This value holds the offset where the prefix ends
  36. var argPos = 0;
  37. if (!message.HasMentionPrefix(_discord.CurrentUser, ref argPos))
  38. return;
  39. // A new kind of command context, ShardedCommandContext can be utilized with the commands framework
  40. var context = new ShardedCommandContext(_discord, message);
  41. await _commands.ExecuteAsync(context, argPos, _services);
  42. }
  43. public async Task CommandExecutedAsync(Optional<CommandInfo> command, ICommandContext context, IResult result)
  44. {
  45. // command is unspecified when there was a search failure (command not found); we don't care about these errors
  46. if (!command.IsSpecified)
  47. return;
  48. // the command was succesful, we don't care about this result, unless we want to log that a command succeeded.
  49. if (result.IsSuccess)
  50. return;
  51. // the command failed, let's notify the user that something happened.
  52. await context.Channel.SendMessageAsync($"error: {result.ToString()}");
  53. }
  54. private Task LogAsync(LogMessage log)
  55. {
  56. Console.WriteLine(log.ToString());
  57. return Task.CompletedTask;
  58. }
  59. }
  60. }