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.7 KiB

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