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 KiB

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