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 1.9 kB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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. }
  21. public async Task InitializeAsync()
  22. {
  23. await _commands.AddModulesAsync(Assembly.GetEntryAssembly(), _services);
  24. _discord.MessageReceived += MessageReceivedAsync;
  25. }
  26. public async Task MessageReceivedAsync(SocketMessage rawMessage)
  27. {
  28. // Ignore system messages, or messages from other bots
  29. if (!(rawMessage is SocketUserMessage message))
  30. return;
  31. if (message.Source != MessageSource.User)
  32. return;
  33. // This value holds the offset where the prefix ends
  34. var argPos = 0;
  35. if (!message.HasMentionPrefix(_discord.CurrentUser, ref argPos))
  36. return;
  37. // A new kind of command context, ShardedCommandContext can be utilized with the commands framework
  38. var context = new ShardedCommandContext(_discord, message);
  39. var result = await _commands.ExecuteAsync(context, argPos, _services);
  40. if (result.Error.HasValue &&
  41. result.Error.Value != CommandError.UnknownCommand) // it's bad practice to send 'unknown command' errors
  42. await context.Channel.SendMessageAsync(result.ToString());
  43. }
  44. }
  45. }