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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. using System;
  2. using System.Threading.Tasks;
  3. using Discord;
  4. using Discord.WebSocket;
  5. namespace _01_basic_ping_bot
  6. {
  7. // This is a minimal, barebones example of using Discord.Net
  8. //
  9. // If writing a bot with commands, we recommend using the Discord.Net.Commands
  10. // framework, rather than handling commands yourself, like we do in this sample.
  11. //
  12. // You can find samples of using the command framework:
  13. // - Here, under the 02_commands_framework sample
  14. // - https://github.com/foxbot/DiscordBotBase - a barebones bot template
  15. // - https://github.com/foxbot/patek - a more feature-filled bot, utilizing more aspects of the library
  16. class Program
  17. {
  18. private DiscordSocketClient _client;
  19. // Discord.Net heavily utilizes TAP for async, so we create
  20. // an asynchronous context from the beginning.
  21. static void Main(string[] args)
  22. => new Program().MainAsync().GetAwaiter().GetResult();
  23. public async Task MainAsync()
  24. {
  25. _client = new DiscordSocketClient();
  26. _client.Log += LogAsync;
  27. _client.Ready += ReadyAsync;
  28. _client.MessageReceived += MessageReceivedAsync;
  29. // Tokens should be considered secret data, and never hard-coded.
  30. await _client.LoginAsync(TokenType.Bot, Environment.GetEnvironmentVariable("token"));
  31. await _client.StartAsync();
  32. // Block the program until it is closed.
  33. await Task.Delay(-1);
  34. }
  35. private Task LogAsync(LogMessage log)
  36. {
  37. Console.WriteLine(log.ToString());
  38. return Task.CompletedTask;
  39. }
  40. // The Ready event indicates that the client has opened a
  41. // connection and it is now safe to access the cache.
  42. private Task ReadyAsync()
  43. {
  44. Console.WriteLine($"{_client.CurrentUser} is connected!");
  45. return Task.CompletedTask;
  46. }
  47. // This is not the recommmended way to write a bot - consider
  48. // reading over the Commands Framework sample.
  49. private async Task MessageReceivedAsync(SocketMessage message)
  50. {
  51. // The bot should never respond to itself.
  52. if (message.Author.Id == _client.CurrentUser.Id)
  53. return;
  54. if (message.Content == "!ping")
  55. await message.Channel.SendMessageAsync("pong!");
  56. }
  57. }
  58. }