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.

InteractionHandlingService.cs 1.8 kB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. using System;
  2. using System.Reflection;
  3. using System.Threading.Tasks;
  4. using Microsoft.Extensions.DependencyInjection;
  5. using Discord;
  6. using Discord.Interactions;
  7. using Discord.WebSocket;
  8. namespace ShardedClient.Services
  9. {
  10. public class CommandHandlingService
  11. {
  12. private readonly InteractionService _service;
  13. private readonly DiscordShardedClient _client;
  14. private readonly IServiceProvider _provider;
  15. public CommandHandlingService(IServiceProvider services)
  16. {
  17. _service = services.GetRequiredService<InteractionService>();
  18. _client = services.GetRequiredService<DiscordShardedClient>();
  19. _provider = services;
  20. _service.CommandExecuted += CommandExecutedAsync;
  21. _service.Log += LogAsync;
  22. _client.InteractionCreated += OnInteractionAsync;
  23. }
  24. // Register all modules, and add the commands from these modules to either guild or globally depending on the build state.
  25. public async Task InitializeAsync()
  26. {
  27. await _service.AddModulesAsync(typeof(CommandHandlingService).Assembly, _provider);
  28. #if DEBUG
  29. await _service.AddCommandsToGuildAsync(/* debug guild ID */);
  30. #else
  31. await _service.AddCommandsGloballyAsync();
  32. #endif
  33. }
  34. private async Task OnInteractionAsync(SocketInteraction interaction)
  35. {
  36. _ = Task.Run(async () =>
  37. {
  38. var context = new ShardedInteractionContext(_client, interaction);
  39. await _service.ExecuteCommandAsync(context, _provider);
  40. });
  41. await Task.CompletedTask;
  42. }
  43. private Task LogAsync(LogMessage log)
  44. {
  45. Console.WriteLine(log.ToString());
  46. return Task.CompletedTask;
  47. }
  48. }
  49. }