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 kB

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