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.

Program.cs 2.8 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. using System;
  2. using System.Threading;
  3. using System.Threading.Tasks;
  4. using _03_sharded_client.Services;
  5. using Discord;
  6. using Discord.Commands;
  7. using Discord.WebSocket;
  8. using Microsoft.Extensions.DependencyInjection;
  9. namespace _03_sharded_client
  10. {
  11. // This is a minimal example of using Discord.Net's Sharded Client
  12. // The provided DiscordShardedClient class simplifies having multiple
  13. // DiscordSocketClient instances (or shards) to serve a large number of guilds.
  14. class Program
  15. {
  16. static void Main(string[] args)
  17. => new Program().MainAsync().GetAwaiter().GetResult();
  18. public async Task MainAsync()
  19. {
  20. // You specify the amount of shards you'd like to have with the
  21. // DiscordSocketConfig. Generally, it's recommended to
  22. // have 1 shard per 1500-2000 guilds your bot is in.
  23. var config = new DiscordSocketConfig
  24. {
  25. TotalShards = 2
  26. };
  27. // You should dispose a service provider created using ASP.NET
  28. // when you are finished using it, at the end of your app's lifetime.
  29. // If you use another dependency injection framework, you should inspect
  30. // its documentation for the best way to do this.
  31. using (var services = ConfigureServices(config))
  32. {
  33. var client = services.GetRequiredService<DiscordShardedClient>();
  34. // The Sharded Client does not have a Ready event.
  35. // The ShardReady event is used instead, allowing for individual
  36. // control per shard.
  37. client.ShardReady += ReadyAsync;
  38. client.Log += LogAsync;
  39. await services.GetRequiredService<CommandHandlingService>().InitializeAsync();
  40. // Tokens should be considered secret data, and never hard-coded.
  41. await client.LoginAsync(TokenType.Bot, Environment.GetEnvironmentVariable("token"));
  42. await client.StartAsync();
  43. await Task.Delay(Timeout.Infinite);
  44. }
  45. }
  46. private ServiceProvider ConfigureServices(DiscordSocketConfig config)
  47. {
  48. return new ServiceCollection()
  49. .AddSingleton(new DiscordShardedClient(config))
  50. .AddSingleton<CommandService>()
  51. .AddSingleton<CommandHandlingService>()
  52. .BuildServiceProvider();
  53. }
  54. private Task ReadyAsync(DiscordSocketClient shard)
  55. {
  56. Console.WriteLine($"Shard Number {shard.ShardId} is connected and ready!");
  57. return Task.CompletedTask;
  58. }
  59. private Task LogAsync(LogMessage log)
  60. {
  61. Console.WriteLine(log.ToString());
  62. return Task.CompletedTask;
  63. }
  64. }
  65. }