public void Run() { try { Timer timer = new Timer(6000); timer.AutoReset = true; bool timerFlag = false; timer.Elapsed += (x, y) => timerFlag = true; timer.Start(); Console.OutputEncoding = Encoding.UTF8; while (true) { TelegramResponse ResponseFromTelegram = telegramBot.GetUpdate(storage.GetLastUpdateTelegramFromStorage()); if (ResponseFromTelegram.result.Count > 0) { TelegramActions operation = new TelegramActions(); foreach (var result in ResponseFromTelegram.result) { loger.WriteLog($"Message from {result.message.from.username}\n" + $"Message Text {result.message.text} \n{DateTime.Now.ToShortTimeString()}"); operation.GetCommandFromMessage(result.message.text).ExecuteCommand(result, ref storage, ref telegramBot, ref viewer); } int MaxUpdate = ResponseFromTelegram.result.Max(X => X.update_id); storage.SaveTelegramUpdateToStorage((MaxUpdate + 1).ToString()); } if (timerFlag) { DevByParser parser = new DevByParser(); List <Event> currEvents = parser.GetEvents(2); storage.SaveNewEventsToStorage(currEvents); List <Event> newEvents = storage.GetNewEventsFromStorageForUser("0"); if (newEvents.Count > 0) { foreach (var @event in newEvents) { telegramBot.SendMessageMDCustom(viewer.ToMdFormat(@event), int.Parse(ConfigurationManager.AppSettings.Get("ChatGeneral ID"))); } } timerFlag = false; } } } catch (AggregateException ex) { foreach (var x in ex.InnerExceptions) { loger.WriteLog(x.ToString()); telegramBot.SendMessageMe(x.ToString()); } } }
private async Task RunUpdate() { int?offset = null; while (AnyObserver) { try { // if the token already canceled before the first request reset token if (_cancellationTokenSource.IsCancellationRequested) { _cancellationTokenSource = new CancellationTokenSource(); } var getUpdate = new GetUpdate { Offset = offset, Timeout = 60, AllowedUpdates = UpdateTypes }; var result = await _telegramBot.GetUpdate(getUpdate, _cancellationTokenSource.Token); if (!result.Any()) { await Task.Delay(1000); continue; } offset = result.Max(x => x.UpdateId) + 1; DistributeUpdates(result); } catch (TaskCanceledException) { // create new token and check observers offset = null; _cancellationTokenSource = new CancellationTokenSource(); } catch (Exception exception) { // unexpected exception report them to the observers and cancel run update OnException(exception); throw; } } }