Utilities.cs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. using System;
  2. using System.Net;
  3. using System.Text;
  4. using System.Threading.Tasks;
  5. using System.Timers;
  6. using CardCollector.Resources;
  7. using Telegram.Bot;
  8. namespace CardCollector
  9. {
  10. public static class Utilities
  11. {
  12. public static string ToJson(object obj)
  13. {
  14. return Newtonsoft.Json.JsonConvert.SerializeObject(obj);
  15. }
  16. public static string CreateMd5(string input)
  17. {
  18. // Use input string to calculate MD5 hash
  19. using var md5 = System.Security.Cryptography.MD5.Create();
  20. var inputBytes = Encoding.ASCII.GetBytes(input);
  21. var hashBytes = md5.ComputeHash(inputBytes);
  22. // Convert the byte array to hexadecimal string
  23. var sb = new StringBuilder();
  24. foreach (var t in hashBytes)
  25. sb.Append(t.ToString("X2"));
  26. return sb.ToString();
  27. }
  28. public static async Task DownloadFile(string fileId)
  29. {
  30. await Task.Run(async () =>
  31. {
  32. /* Получаем информацию о файле */
  33. var fileInfo = await Bot.Client.GetFileAsync(fileId);
  34. /* Собираем ссылку на файл */
  35. var fileUri = $"https://api.telegram.org/file/bot{AppSettings.TOKEN}/{fileInfo.FilePath}";
  36. /* Загружаем файл */
  37. var client = new WebClient();
  38. client.DownloadFile(new Uri(fileUri), "pack.zip");
  39. });
  40. }
  41. public static void SetUpTimer(TimeSpan timeToRun, ElapsedEventHandler callback)
  42. {
  43. var elapsedInterval = timeToRun - DateTime.Now.TimeOfDay;
  44. if (elapsedInterval < TimeSpan.Zero) elapsedInterval += new TimeSpan(1, 0, 0, 0);
  45. var timer = new Timer
  46. {
  47. AutoReset = false,
  48. Enabled = true,
  49. Interval = elapsedInterval.TotalMilliseconds
  50. };
  51. timer.Elapsed += callback;
  52. timer.Elapsed += (_, _) => timer.Dispose();
  53. }
  54. }
  55. }