public async Task StartAsync() { this.SetupLongPoll(); this.OnBotStarted?.Invoke(this, null); while (true) { try { BotsLongPollHistoryResponse longPollResponse = await Api.Groups.GetBotsLongPollHistoryAsync( new BotsLongPollHistoryParams { Key = _pollSettings.Key, Server = _pollSettings.Server, Ts = _pollSettings.Ts, Wait = this._longPollTimeoutWaitSeconds }).ContinueWith(CheckLongPollResponseForErrorsAndHandle).ConfigureAwait(false); if (longPollResponse == default(BotsLongPollHistoryResponse)) { continue; } this.ProcessLongPollEvents(longPollResponse); _pollSettings.Ts = longPollResponse.Ts; } catch (Exception ex) { this.Logger.LogError(ex.Message + "\r\n" + ex.StackTrace); throw; } } }
private async Task runPollingLoop() { while (isStarted) { BotsLongPollHistoryResponse response; try { response = BotsLongPollHistoryResponse.FromJson(await api.CallLongPollAsync(connection.Server, (VkParameters)connection)); } catch (LongPollOutdateException exception) { connection.Ts = exception.Ts; continue; } catch (Exception exception) when(exception is LongPollKeyExpiredException || exception is LongPollInfoLostException) { await connection.Create(); continue; } catch (Exception) { throw; } connection.Ts = response.Ts; foreach (var update in response.Updates) { await Handler?.Handle(update); } } }
public async Task StartAsync() { this.SetupLongPoll(); while (true) { try { BotsLongPollHistoryResponse longPollResponse = await Api.Groups.GetBotsLongPollHistoryAsync( new BotsLongPollHistoryParams { Key = PollSettings.Key, Server = PollSettings.Server, Ts = PollSettings.Ts, Wait = 1 }).ContinueWith(CheckLongPollResponseForErrorsAndHandle).ConfigureAwait(false); if (longPollResponse == default(BotsLongPollHistoryResponse)) { continue; } //Console.WriteLine(JsonConvert.SerializeObject(longPollResponse)); this.ProcessLongPollEvents(longPollResponse); PollSettings.Ts = longPollResponse.Ts; } catch (Exception ex) { Console.WriteLine(ex.Message); throw; } } }
private void MessageAllowHandler() { //Default menu KeyboardBuilder key = new KeyboardBuilder(); key.AddButton("Привязать аккаунт", null, agree); key.AddButton("Удалить привязку", null, decine); MessageKeyboard keyboard = key.Build(); try { while (true) // Бесконечный цикл, получение обновлений { api.Authorize(new ApiAuthParams() { AccessToken = userToken, }); longPoolServerResponse = new LongPollServerResponse(); longPoolServerResponse = api.Groups.GetLongPollServer(groupID); BotsLongPollHistoryResponse poll = null; try { poll = api.Groups.GetBotsLongPollHistory( new BotsLongPollHistoryParams() { Server = longPoolServerResponse.Server, Ts = longPoolServerResponse.Ts, Key = longPoolServerResponse.Key, Wait = 25 }); pts = longPoolServerResponse.Pts; if (poll?.Updates == null) { continue; // Проверка на новые события } } catch (Exception ex) { ErrorLogging(ex); ReadError(); } foreach (var a in poll.Updates) { if (a.Type == GroupUpdateType.MessageAllow) //Подписка на сообщения сообщества { long?userID = a.MessageAllow.UserId; SendMessage("😉 Спасибо за подписку!", userID, keyboard, null); } } } } catch (Exception ex) { ErrorLogging(ex); ReadError(); } }
private void GroupJoinHandler() { //Default menu KeyboardBuilder key = new KeyboardBuilder(); key.AddButton("Привязать аккаунт", null, agree); key.AddButton("Удалить привязку", null, decine); MessageKeyboard keyboard = key.Build(); try { while (true) // Бесконечный цикл, получение обновлений { api.Authorize(new ApiAuthParams() { AccessToken = userToken, }); longPoolServerResponse = new LongPollServerResponse(); longPoolServerResponse = api.Groups.GetLongPollServer(groupID); //id группы BotsLongPollHistoryResponse poll = null; try { poll = api.Groups.GetBotsLongPollHistory( new BotsLongPollHistoryParams() { Server = longPoolServerResponse.Server, Ts = longPoolServerResponse.Ts, Key = longPoolServerResponse.Key, Wait = 25 }); pts = longPoolServerResponse.Pts; if (poll?.Updates == null) { continue; // Проверка на новые события } } catch (Exception ex) { ErrorLogging(ex); ReadError(); } foreach (var a in poll.Updates) { if (a.Type == GroupUpdateType.GroupJoin) //Вступление юзера в группу { long?userID = a.GroupJoin.UserId; SendMessage("🎉 Добро пожаловать в наш игровой паблик!\nМы разработали собственную программу для синхронизации игрового чата с ВК!\nПосле привязки аккаунта, ты сможешь читать и отправлять сообщения в игровой чат! Круто же!!!", userID, keyboard, null); } } } } catch (Exception ex) { ErrorLogging(ex); ReadError(); } }
private void _processEvents(BotsLongPollHistoryResponse pollResponse) { foreach (var update in pollResponse.Updates) { OnGroupUpdateReceived?.Invoke(this, new GroupUpdateReceivedEventArgs(update)); if (update.Type == GroupUpdateType.MessageNew) { OnMessageReceived?.Invoke(this, new MessageReceivedEventArgs(update.MessageNew?.Message)); } } }
private void ProcessLongPollEvents(BotsLongPollHistoryResponse pollResponse) { foreach (GroupUpdate update in pollResponse.Updates) { OnGroupUpdateReceived?.Invoke(this, new GroupUpdateReceivedEventArgs(update)); if (update.Type == GroupUpdateType.MessageNew) { OnMessageReceived?.Invoke(this, new MessageReceivedEventArgs(update.Message)); SearchPhraseAndHandle(update.Message); } } }
void BotGetMessage(BotsLongPollHistoryResponse poll) { foreach (var a in poll.Updates) { rnd = rand.Next(1, 21474893); if (a.Type == GroupUpdateType.MessageNew) { new Thread(() => { GetAnswer(a.Message.PeerId, a.Message.Text, rnd); }).Start(); } } }
private void ProcessLongPollEvents(BotsLongPollHistoryResponse pollResponse) { foreach (GroupUpdate update in pollResponse.Updates) { OnGroupUpdateReceived?.Invoke(this, new GroupUpdateReceivedEventArgs(update, this.PeerContextManager.GlobalVars)); if (update.Type == GroupUpdateType.MessageNew) { long peerId = update.Message.PeerId.Value; PeerContext peerContext = null; if (!this.PeerContextManager.Peers.TryGetValue(peerId, out peerContext)) { peerContext = new PeerContext(this.PeerContextManager.GlobalVars); this.PeerContextManager.Peers.Add(peerId, peerContext); } OnMessageReceived?.Invoke(this, new MessageReceivedEventArgs(update.Message, peerContext)); this.SearchTemplatesMatchingMessageAndHandle(update.Message, peerContext); } } }
public static void LongPollListener() { //Default menu KeyboardBuilder key = new KeyboardBuilder(); KeyboardBuilder key_linked = new KeyboardBuilder(); KeyboardBuilder key_unlinked = new KeyboardBuilder(); KeyboardBuilder genres_menu_general = new KeyboardBuilder(); key.AddButton("Привязать аккаунт", null, agree); key.AddButton("Удалить привязку", null, decine); genres_menu_general.AddButton("House", null, def); genres_menu_general.AddButton("Vocal Deep", null, def); genres_menu_general.AddButton("Bass", null, def); genres_menu_general.AddButton("Psy-Trance", null, def); MessageKeyboard keyboard_genres_general = genres_menu_general.Build(); MessageKeyboard keyboard = key.Build(); key_linked.AddButton("Удалить привязку", null, decine); MessageKeyboard keyboard_linked = key_linked.Build(); key_unlinked.AddButton("Привязать аккаунт", null, agree); MessageKeyboard keyboard_unlinked = key_unlinked.Build(); HashSet <string> messages = new HashSet <string>(); Start: try { Restart: while (true) // Бесконечный цикл, получение обновлений { var api = new VkApi(); try { api.Authorize(new ApiAuthParams() { AccessToken = vkapiToken, }); } catch (Exception apiAuth) { Logging.ErrorLogging(apiAuth); Logging.ReadError(); goto Restart; } longPoolServerResponse = new LongPollServerResponse(); longPoolServerResponse = api.Groups.GetLongPollServer(groupID); BotsLongPollHistoryResponse poll = null; try { poll = api.Groups.GetBotsLongPollHistory( new BotsLongPollHistoryParams() { Server = longPoolServerResponse.Server, Ts = longPoolServerResponse.Ts, Key = longPoolServerResponse.Key, Wait = 25 }); pts = longPoolServerResponse.Pts; if (poll?.Updates == null) { continue; } } catch (Exception ex) { Logging.ErrorLogging(ex); Logging.ReadError(); goto Restart; } foreach (var a in poll.Updates) { PostType postType = new PostType(); postType = PostType.Post; if (a.Type == GroupUpdateType.WallPostNew) { if (a.WallPost.PostType == postType) { Uri thumbUrl = null; //Картинка для телеграма (музыки) 200 кб 90х90px string postMessage = a.WallPost.Text; //Скачать песни из вложений - отправить в телеграм var allAttachments = a.WallPost.Attachments; Console.WriteLine(string.Format("Новый пост: {0}, вложений: {1} ", postMessage, allAttachments.Count)); List <VkNet.Model.Attachments.Audio> audios = new List <VkNet.Model.Attachments.Audio>(); List <string> trackIds = new List <string>(); List <string> photoList2Load = new List <string>(); if (allAttachments.Count > 0) { foreach (var attach in allAttachments) { var attid = attach.Instance.Id; var attown = attach.Instance.OwnerId; string attachFullId = attown + "_" + attid; if (attach.Type == typeof(VkNet.Model.Attachments.Audio)) //decode - download { trackIds.Add(attachFullId); } if (attach.Type == typeof(VkNet.Model.Attachments.Photo)) { photoList2Load.Add(attachFullId); } } } List <VkNet.Model.Attachments.Photo> photoList = new List <VkNet.Model.Attachments.Photo>(); if (photoList2Load.Count > 0) { try { api = new VkApi(); //Get JPG Link api.Authorize(new ApiAuthParams() { Login = vkLogin, Password = vkPassword, ApplicationId = kateMobileAppID, Settings = Settings.All }); Console.WriteLine("VK User auth для фото!"); Thread.Sleep(1000); var photos = api.Photo.GetById(photoList2Load, null, photoSizes: true); photoList = photos.ToList(); if (photoList.Count > 0) { using (WebClient webClient = new WebClient()) { Classes.Photo photoClass2Process = GetLargePhoto.GetLargeAndThumbUrl(photoList); List <Uri> getLargePhoto = photoClass2Process.largePhotoUris; thumbUrl = photoClass2Process.smallPhotoUri; foreach (var largePhotoLink in getLargePhoto) { webClient.DownloadFile(largePhotoLink.AbsoluteUri.ToString(), Path.GetFileName(largePhotoLink.ToString())); Classes.Photo photoClass = new Classes.Photo(Path.GetFileName(largePhotoLink.ToString()), postMessage); Thread senderTGPhotoThread = new Thread(TelegramSender.SendPhoto2TG); senderTGPhotoThread.Start(photoClass); Thread.Sleep(100); } getLargePhoto.Clear(); } } } catch (Exception sendPhotoEx) { Logging.ErrorLogging(sendPhotoEx); Logging.ReadError(); goto SendMusic; } } SendMusic: if (trackIds.Count > 0) { var services = new ServiceCollection(); services.AddAudioBypass(); api = new VkApi(services); try { api.Authorize(new ApiAuthParams() { Login = vkLogin, Password = vkPassword, ApplicationId = kateMobileAppID, Settings = Settings.All }); Console.WriteLine("VK User auth для музыки!"); } catch (Exception apiEx) { Logging.ErrorLogging(apiEx); Logging.ReadError(); goto Restart; } audios = api.Audio.GetById(trackIds).ToList(); foreach (var song in audios) { Uri audioUri = song.Url; //get URI if (audioUri != null) //Если запись не по подписке или не запрещена { Uri mp3link = AudioDownloader.DecodeAudioUrl(audioUri); var uriString = mp3link.ToString(); string mp3Direct = mp3link.AbsoluteUri; int divider = mp3Direct.IndexOf('?'); string clearLink = mp3Direct.Substring(0, divider); string mp3Title = song.Title; string mp3Artist = song.Artist; string mp3name = mp3Title + " - " + mp3Artist + ".mp3"; if (song.Duration < 720) //12 минут { MP3 mP; if (thumbUrl != null) { mP = new MP3(clearLink, mp3name, mp3Title, mp3Artist, postMessage, thumbUrl); } else { mP = new MP3(clearLink, mp3name, mp3Title, mp3Artist, postMessage); } Thread senderTGThread = new Thread(TelegramSender.SendMusic2TG); senderTGThread.Start(mP); Thread.Sleep(500); } else { Console.WriteLine("Слишком длинный трек >12 минут"); } } else { continue; } } } //Clear after All try { if (trackIds.Count > 0) { trackIds.Clear(); } if (photoList.Count > 0) { photoList.Clear(); } if (photoList2Load.Count > 0) { photoList2Load.Clear(); } } catch (Exception ex) { Logging.ErrorLogging(ex); Logging.ReadError(); } } } } } } catch (Exception ex) { Logging.ErrorLogging(ex); Logging.ReadError(); goto Start; } }
//OLD Working public void LongPollListener() { //Default menu KeyboardBuilder key = new KeyboardBuilder(); //Когда привязан уже KeyboardBuilder key_linked = new KeyboardBuilder(); //Когда удалили привязку KeyboardBuilder key_unlinked = new KeyboardBuilder(); key.AddButton("Привязать аккаунт", null, agree); key.AddButton("Удалить привязку", null, decine); MessageKeyboard keyboard = key.Build(); ////Когда привязан уже //KeyboardBuilder key_linked = new KeyboardBuilder(); key_linked.AddButton("Удалить привязку", null, decine); MessageKeyboard keyboard_linked = key_linked.Build(); ////Когда удалили привязку //KeyboardBuilder key_unlinked = new KeyboardBuilder(); key_unlinked.AddButton("Привязать аккаунт", null, agree); MessageKeyboard keyboard_unlinked = key_unlinked.Build(); HashSet <string> messages = new HashSet <string>(); try { while (true) // Бесконечный цикл, получение обновлений { api.Authorize(new ApiAuthParams() { AccessToken = userToken, }); longPoolServerResponse = new LongPollServerResponse(); longPoolServerResponse = api.Groups.GetLongPollServer(groupID); //id группы BotsLongPollHistoryResponse poll = null; try { poll = api.Groups.GetBotsLongPollHistory( new BotsLongPollHistoryParams() { Server = longPoolServerResponse.Server, Ts = longPoolServerResponse.Ts, Key = longPoolServerResponse.Key, Wait = 25 }); pts = longPoolServerResponse.Pts; if (poll?.Updates == null) { continue; // Проверка на новые события } } catch (Exception ex) { ErrorLogging(ex); ReadError(); } foreach (var a in poll.Updates) { //OLD 1 Thread VERSION if (a.Type == GroupUpdateType.MessageAllow) //Подписка на сообщения сообщества { long?userID = a.MessageAllow.UserId; SendMessage("😉 Спасибо за подписку!", userID, keyboard, null); } if (a.Type == GroupUpdateType.GroupJoin) //Вступление юзера в группу { long?userID = a.GroupJoin.UserId; SendMessage("🎉 Добро пожаловать в наш игровой паблик!\nМы разработали собственную программу для синхронизации игрового чата с ВК!\nПосле привязки аккаунта, ты сможешь читать и отправлять сообщения в игровой чат! Круто же!!!", userID, keyboard, null); } if (a.Type == GroupUpdateType.GroupLeave) //Выход из группы { long?userID = a.GroupLeave.UserId; SendMessage("😔 Очень жаль(\nЗаходи к нам ещё!🔙", userID, keyboard, null); } if (a.Type == GroupUpdateType.MessageNew) { string userMessage = a.Message.Text.ToLower(); long? userID = a.Message.FromId; string payload = a.Message.Payload; long? chatID = a.Message.ChatId; long? msgID = a.Message.Id; var markAsRead = a.Message.ReadState; Console.WriteLine(userMessage); // извлекает первый при сообщении, а нужно все получить, прогнаться по всем Program P = new Program(); //Очистка списка кодов try { foreach (string code in removeMe) { otpList.Remove(code); } removeMe.Clear(); } catch (Exception ex) { ErrorLogging(ex); ReadError(); } bool isLinked = MySQLClass.IsVKLinked(userID); //Обработка входящих сообщений if (payload != null)//если пришло нажатие кнопки { //В зависимости от того какая кнопка нажата, отправляем новое меню - Если нажали првязать и успешно привязано, то удаляем кнопку"Привязать" ?! Надо ли //SendMessage("Ну на кнопки ты нажимать умеешь", userID, keyboard, null); // АНТИСПАМ: Нажали кнопку - ждем, чтобы постоянно не тыкали, сделать таймер повторной отправки для конкретного юзера switch (userMessage) { case "привязать аккаунт": //Сделать обработку если после привязать отправили сообщение а не ник if (isLinked == true) { SendMessage("‼ Вы уже привязали аккаунт!", userID, keyboard_linked, payload); //Таймер действия - если в течение 10 минут не произошло действие, сбросить меню } else { SendMessage("⌛ Зайди на сервер и напиши свой ник в игре 💬 :", userID, null, payload); } //Thread.Sleep(500); break; case "удалить привязку": //Если учетка не был привязана, проверить, если да - то проверяем if (isLinked == true) { string playerName = MySQLClass.GetNickFromID(userID); bool isSuccess2 = MySQLClass.RemoveVKID(userID); if (isSuccess2 == true) { //Успешно удалили привязку SendMessage("❌ Учетная запись отвязана", userID, keyboard_unlinked, payload); //Понижае привиллегии string unlink = "-" + playerName; TCPOtpSender.AddToOtpAndNameQueue(unlink); } else { SendMessage("‼ Ошибка удаления привязки", userID, keyboard_linked, payload); } } else { //Учетная запись не привязана - ничего не делать, отправить клавиатуру с привязкой SendMessage("⚠ Учетная запись ещё не привязана.", userID, keyboard_unlinked, null); break; } break; } } else //Если кнопку не нажимали, написали любое сообщение, отправляем клавиатуру?! { switch (userMessage) { case "начать": SendMessage("Приступим, держи меню-клавиатуру!", userID, keyboard, null); break; case "Начать": SendMessage("Приступим, держи меню-клавиатуру!", userID, keyboard, null); break; } ////Проверяем есть ли юзер в базе данных и отправляем его сообщение в чат сервера List <long?> idList = MySQLClass.GetVKID(); //СДЕЛАТЬ АНТИСПАМ, если несколько раз ввели разные ники, сделать таймер повторной отправки if (checkID(idList, userID) == true) { // Получаем ник игрока из БД и добавляем к сообщению string plName = MySQLClass.GetNickFromID(userID); if ((plName != null) && (userMessage.StartsWith('/') == false)) //Если не консоль И юзер привязан, экранируем { // Добавляем сообщение в очередь string combo = null; combo = plName + ": " + userMessage; //Сделать проверку на OTP после привязки шлет в чат код foreach (string otp in otpList) { int dividerIndex = otp.IndexOf(":"); string otpString = otp.Substring(dividerIndex + 1, otp.Length - 1 - dividerIndex); if (userMessage == otpString) { combo = plName + " только что привязал свой ВК!"; } } //Сделать проверку на привязку, если привязан - клавиатуру не слать. TCPClient.AddToUserMessageQueue(combo); //} } else if (plName == null) { SendMessage("⚠ Вы не привязали аккаунт! Игрок не найден.", userID, keyboard_unlinked, null); } } //Проверка ника (В любом случае) СПАМ или привязка не к тому аккаунту не того игрока!! (например в вк перебор ников идет, отправка кодов всем юзерам на серве) List <string> nickNameList = MySQLClass.GetNicknames(); //TODO foreach (string nick in nickNameList) { if (userMessage == nick) { //Сгенерировать временный код OTPGenerator generator = new OTPGenerator(); string otpCode = generator.GenerateOTP(); string nickNameOtp = nick + ":" + otpCode; TCPOtpSender.AddToOtpAndNameQueue(nickNameOtp); otpList.Add(nickNameOtp); Console.WriteLine(nickNameOtp); int time = 2; string sendVK = string.Format("✉ Отправь мне временный код из игры\n ⏰ (действителен в течение {0} минут):👇", time); SendMessage(sendVK, userID, null, null); // Начать отсчет таймера //Таймер действия - если в течение 10 минут не произошло действие, сбросить меню Thread otpDeleter = new Thread(OTPCleaner); otpDeleter.Start(nickNameOtp); break; } } //Проверка одноразового пароля В ЛЮБОМ СЛУЧАЕ foreach (string otp in otpList) { if (otp != null) { int dividerIndex = otp.IndexOf(":"); string playerName = otp.Substring(0, dividerIndex); string otpString = otp.Substring(dividerIndex + 1, otp.Length - 1 - dividerIndex); if (userMessage == otpString) //Временный код для авторизации юзера (получить из Майнкрафт-сервера) должен меняться, постоянно обновлять здесь { try { if (isLinked == true) { SendMessage("⚠ Учетная запись уже была привязана.", userID, keyboard_linked, null); } else { //Send userId to MYSQL bool isSuccess = MySQLClass.InsertVKID(userID, playerName); // Нужна проверка на уже привязанную (если есть VKID напротив ника) if (isSuccess == true) //Всегда успешно { //Если в базе нет привязки ника к айди ВК SendMessage("✅ Учетная запись успешно привязана!\nВы начнете получать сообщения из чата 💭 и сможете писать сразу в игру!", userID, keyboard_linked, null); string successfull = "+" + playerName; TCPOtpSender.AddToOtpAndNameQueue(successfull); //Если успешно привязали - удалить из списка юзера } else { SendMessage("⛔ Невозможно проверить по базе данных, обратитесь к админу.", userID, keyboard, null); } } } catch (Exception ex) { ErrorLogging(ex); ReadError(); } // Извлекаем из списка найденный одноразовый код finally { removeMe.Add(otp); } } } } } } } } } catch (Exception ex) { ErrorLogging(ex); ReadError(); } }
private GroupUpdate[] GetHistoryUpdates(BotsLongPollHistoryResponse history) { return(history?.Updates?.Where(x => x.Type == GroupUpdateType.MessageNew).ToArray()); }
public void Bot1() { while (true) { BotsLongPollHistoryResponse poll = new BotsLongPollHistoryResponse(); var s1 = vkapigroup.Groups.GetLongPollServer((ulong)groupid); BotsLongPollHistoryResponse poll1 = vkapigroup.Groups.GetBotsLongPollHistory(new BotsLongPollHistoryParams() { Server = s1.Server, Ts = s1.Ts, Key = s1.Key, Wait = 3 }); if (poll1?.Updates == null) { var s2 = vkapigroup.Groups.GetLongPollServer((ulong)groupid); BotsLongPollHistoryResponse poll2 = vkapigroup.Groups.GetBotsLongPollHistory(new BotsLongPollHistoryParams() { Server = s2.Server, Ts = s2.Ts, Key = s2.Key, Wait = 2 }); if (poll2?.Updates == null) { var s3 = vkapigroup.Groups.GetLongPollServer((ulong)groupid); BotsLongPollHistoryResponse poll3 = vkapigroup.Groups.GetBotsLongPollHistory(new BotsLongPollHistoryParams() { Server = s3.Server, Ts = s3.Ts, Key = s3.Key, Wait = 1 }); if (poll3?.Updates == null) { var s4 = vkapigroup.Groups.GetLongPollServer((ulong)groupid); BotsLongPollHistoryResponse poll4 = vkapigroup.Groups.GetBotsLongPollHistory(new BotsLongPollHistoryParams() { Server = s4.Server, Ts = s4.Ts, Key = s4.Key, Wait = 1 }); if (poll3?.Updates == null) { continue; } poll = poll4; BotGetMessage(poll); } else { poll = poll3; BotGetMessage(poll); } } else { poll = poll2; BotGetMessage(poll); } } else { poll = poll1; BotGetMessage(poll); } } }
private static void Main(string[] args) { Configs configs = Configs.GetConfig(); LongPollServerResponse longPollServer = Auth(configs); var botHandler = new BotHandler(_api); _currentTs = longPollServer.Ts; while (_botEnabled) { try { BotsLongPollHistoryResponse poll = _api.Groups.GetBotsLongPollHistory(new BotsLongPollHistoryParams { Server = longPollServer.Server, Ts = _currentTs, Key = longPollServer.Key, Wait = 130 }); if (poll?.Updates == null || !poll.Updates.Any()) { continue; } foreach (GroupUpdate a in poll.Updates) { _currentTs = poll.Ts; Message message; if (a.MessageNew != null) { message = a.MessageNew.Message; } else if (a.Message != null) { message = a.Message; } else { continue; } if (message.Date > _lastData || _lastData == null) { _lastData = message.Date; botHandler.MessageProcessing(message); } } } catch (LongPollException exception) { longPollServer = TryUpdateLongPollServer(exception, longPollServer, configs); } catch (Exception e) { Console.WriteLine(e.Message); } Task.Delay(100); } }