Bot.cs 1.9 KB

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