Bot.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Threading;
  4. using System.Timers;
  5. using CardCollector.DataBase;
  6. using CardCollector.DataBase.EntityDao;
  7. using CardCollector.Resources;
  8. using Telegram.Bot;
  9. using Telegram.Bot.Types;
  10. using CancellationTokenSource = System.Threading.CancellationTokenSource;
  11. using Timer = System.Timers.Timer;
  12. namespace CardCollector
  13. {
  14. using static Controllers.MessageController;
  15. public static class Bot
  16. {
  17. private static TelegramBotClient _client;
  18. public static TelegramBotClient Client => _client ??= new TelegramBotClient(AppSettings.TOKEN);
  19. private static readonly ManualResetEvent _end = new(false);
  20. private static readonly Timer _timer = new () {
  21. AutoReset = true,
  22. Enabled = true,
  23. Interval = Constants.SAVING_CHANGES_INTERVAL
  24. };
  25. private static readonly IEnumerable<BotCommand> _commands = new[]
  26. {
  27. new BotCommand {Command = "/menu", Description = "Показать меню"},
  28. new BotCommand {Command = "/help", Description = "Показать информацию"},
  29. new BotCommand {Command = "/error", Description = "Сообщить об ошибке"},
  30. };
  31. public static void Main(string[] args)
  32. {
  33. var cts = new CancellationTokenSource();
  34. Client.StartReceiving(HandleUpdateAsync, HandleErrorAsync, cancellationToken: cts.Token);
  35. Client.SetMyCommandsAsync(_commands, BotCommandScope.AllPrivateChats(), cancellationToken: cts.Token);
  36. _timer.Elapsed += SavingChanges;
  37. _timer.Elapsed += UserDao.ClearMemory;
  38. _end.WaitOne();
  39. Logs.LogOut("Stopping program");
  40. cts.Cancel();
  41. }
  42. public static void StopProgram()
  43. {
  44. _timer.Elapsed += (_, _) =>
  45. {
  46. _timer.Stop();
  47. UserDao.ClearMemory();
  48. _end.Set();
  49. };
  50. }
  51. private static async void SavingChanges(object o, ElapsedEventArgs e)
  52. {
  53. try {
  54. await CardCollectorDatabase.SaveAllChangesAsync();
  55. } catch (Exception) { /*ignored*/ }
  56. }
  57. }
  58. }