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.

DiscordClient.cs 2.8 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. using Discord;
  2. using Discord.Commands;
  3. using Discord.SlashCommands;
  4. using Discord.WebSocket;
  5. using Microsoft.Extensions.DependencyInjection;
  6. using System;
  7. using System.Reflection;
  8. using System.Threading.Tasks;
  9. namespace SlashCommandsExample
  10. {
  11. class DiscordClient
  12. {
  13. public static DiscordSocketClient socketClient { get; set; } = new DiscordSocketClient();
  14. public static SlashCommandService _commands { get; set; }
  15. public static IServiceProvider _services { get; set; }
  16. private string botToken = "<YOUR TOKEN HERE>";
  17. public DiscordClient()
  18. {
  19. _commands = new SlashCommandService();
  20. _services = new ServiceCollection()
  21. .AddSingleton(socketClient)
  22. .AddSingleton(_commands)
  23. .BuildServiceProvider();
  24. socketClient.Log += SocketClient_Log;
  25. _commands.Log += SocketClient_Log;
  26. socketClient.InteractionCreated += InteractionHandler;
  27. // This is for dev purposes.
  28. // To avoid the situation in which you accidentally push your bot token to upstream, you can use
  29. // EnviromentVariables to store your key.
  30. botToken = Environment.GetEnvironmentVariable("DiscordSlashCommandsBotToken", EnvironmentVariableTarget.User);
  31. // Uncomment the next line of code to set the environment variable.
  32. // ------------------------------------------------------------------
  33. // | WARNING! |
  34. // | |
  35. // | MAKE SURE TO DELETE YOUR TOKEN AFTER YOU HAVE SET THE VARIABLE |
  36. // | |
  37. // ------------------------------------------------------------------
  38. //Environment.SetEnvironmentVariable("DiscordSlashCommandsBotToken",
  39. // "[YOUR TOKEN GOES HERE DELETE & COMMENT AFTER USE]",
  40. // EnvironmentVariableTarget.User);
  41. }
  42. public async Task RunAsync()
  43. {
  44. await socketClient.LoginAsync(TokenType.Bot, botToken);
  45. await socketClient.StartAsync();
  46. await _commands.AddModulesAsync(Assembly.GetEntryAssembly(), _services);
  47. await Task.Delay(-1);
  48. }
  49. private async Task InteractionHandler(SocketInteraction arg)
  50. {
  51. if(arg.Type == InteractionType.ApplicationCommand)
  52. {
  53. await _commands.ExecuteAsync(arg);
  54. }
  55. }
  56. private Task SocketClient_Log(LogMessage arg)
  57. {
  58. Console.WriteLine("[Discord] " + arg.ToString());
  59. return Task.CompletedTask;
  60. }
  61. }
  62. }