public async Task ReceiveAsync(RequestDelegate rootHandler, CancellationToken cancellationToken = default) { if (rootHandler is null) { throw new ArgumentNullException(nameof(rootHandler)); } var messageOffset = 0; while (!cancellationToken.IsCancellationRequested) { var updates = Array.Empty <Update>(); try { updates = await _client.GetUpdatesAsync ( offset : messageOffset, timeout : (int)_client.Timeout.TotalSeconds, cancellationToken : cancellationToken ); } catch (OperationCanceledException) { // Ignore... } finally { foreach (var update in updates) { _logger?.LogInformation($"Update received with type: {update.Type}"); if (update.Message is Message message) { _callbackQueryListener.UnregisterRequest(message.Chat.Id); } var callbackQuery = update.CallbackQuery; if (callbackQuery is not null && _callbackQueryListener.GetRequestInfo(callbackQuery.Message.Chat.Id, callbackQuery.Message.MessageId) is CallbackQueryRequestInfo requestInfo) { _callbackQueryListener.UnregisterRequest(requestInfo.Message.Chat.Id); await requestInfo.Callback ( request : requestInfo.Message, response : callbackQuery, payload : requestInfo.Payload ); }
public async Task <UserRequestBatch> GetUserRequests(int offset) { var updates = await _telegramClient.GetUpdatesAsync(offset); if (!updates.Any()) { return(null); } var nextOffset = updates.Max(u => u.Id) + 1; var userRequests = updates.Select(_reader.ReadUpdate).ToList(); var result = new UserRequestBatch(userRequests, nextOffset); return(result); }
public async Task DiscardNewUpdatesAsync(CancellationToken cancellationToken = default) { if (cancellationToken == default) { var source = new CancellationTokenSource(TimeSpan.FromSeconds(30)); cancellationToken = source.Token; } int offset = 0; while (!cancellationToken.IsCancellationRequested) { var updates = await _botClient.GetUpdatesAsync(offset, allowedUpdates : Array.Empty <UpdateType>(), cancellationToken : cancellationToken); if (updates.Length == 0) { break; } offset = updates.Last().Id + 1; } }
private async Task <int> Tick(ITelegramBotClient botClient, int offset) { var updates = await botClient.GetUpdatesAsync(offset); if (updates == null && !updates.Any()) { return(offset); } foreach (var update in updates) { offset = update.Id + 1; var service = new BirthdayNotificationBotService(_birthdayScheduleTelegramBotRepository, botClient); await service.ProccessMessage(update); } return(offset); }
public async void Init() { if (!string.IsNullOrWhiteSpace(_settings.WEBSITE_URL)) { await _client.SetWebhookAsync(_settings.WEBSITE_URL); } else { var whi = await _client.GetWebhookInfoAsync(); Console.WriteLine(JsonConvert.SerializeObject(whi)); if (!string.IsNullOrWhiteSpace(whi.Url)) { await _client.DeleteWebhookAsync(); } int lastId = -1; _timer = new Timer(async _ => { try { var updates = await _client.GetUpdatesAsync(lastId + 1); lastId = updates.LastOrDefault()?.Id ?? lastId; foreach (var up in updates) { try { await Process(up); } catch { } } } catch { } }, null, TimeSpan.FromSeconds(2), TimeSpan.FromSeconds(2)); } }
static async Task Main(string[] args) { try { Bot = new TelegramBotClient(Token); await Bot.SetWebhookAsync(""); int offset = 0; Console.WriteLine("Start!"); while (true) { var updates = await Bot.GetUpdatesAsync(offset); foreach (var update in updates) { var message = update.Message; if (message.Text == "/getShedule") { var keyboard = new ReplyKeyboardMarkup { Keyboard = new[] { new[] { new KeyboardButton("ИП-16-3"), new KeyboardButton("ИП-16-4"), new KeyboardButton("ИП-17-3"), new KeyboardButton("ИП-17-4"), new KeyboardButton("ИП-18-3"), new KeyboardButton("ИП-18-4") }, }, ResizeKeyboard = true }; await Bot.SendTextMessageAsync( message.Chat.Id, "Хорошо. Из какой ты группы?", ParseMode.Default, false, false, 0, keyboard); } if (message.Text.ToUpper().Trim() == "ИП-16-3" || message.Text.ToUpper().Trim() == "ИП-16-4" || message.Text.ToUpper().Trim() == "ИП-17-3" || message.Text.ToUpper().Trim() == "ИП-17-4" || message.Text.ToUpper().Trim() == "ИП-18-3" || message.Text.ToUpper().Trim() == "ИП-18-4") { string result = await Parser.Parse(message.Text.ToUpper().Trim()); dynamic shedule = JsonConvert.DeserializeObject <dynamic>(result); result = $"Понедельник: \n {shedule.shedule["Понедельник"]} \n" + $"Вторник: \n {shedule.shedule["Вторник"]} \n" + $"Среда: \n {shedule.shedule["Среда"]} \n" + $"Четверг: \n {shedule.shedule["Четверг"]} \n" + $"Пятница: \n {shedule.shedule["Пятница"]}"; int startIndex = result.Length / 2; var result1 = result .Substring(0, startIndex); var result2 = result .Substring(startIndex, result.Length - startIndex); await Bot.SendTextMessageAsync( message.Chat.Id, result1); await Bot.SendTextMessageAsync( message.Chat.Id, result2); } offset = update.Id + 1; } } } catch (Telegram.Bot.Exceptions.ApiRequestException ex) { Console.WriteLine(ex.Message); } Console.ReadKey(); }
private static async void Bot_OnMessage(object sender, Telegram.Bot.Args.MessageEventArgs e) { // return; var text = e.Message.Text; var message = e.Message; log.Message(e); //if (e.Message.From.Id == 652761067) // return; try { if (message.Type == Telegram.Bot.Types.Enums.MessageType.Contact) { db.SetUserPhone(message.From.Id, message.Contact.PhoneNumber); } switch (message.Text) { default: switch (db.GetAwaitInfoType(message.From.Id)) { case 0: break; case (int)awaitInfoType.name: db.SetName(text, message.From.Id, true); db.SetAwaitInfoType(message.From.Id, (int)awaitInfoType.none); await SetDiscCaptionAsync(message.Chat.Id, message.From.Id); break; case (int)awaitInfoType.price: db.SetPrice(message.Text, message.From.Id, true); db.SetAwaitInfoType(message.From.Id, (int)awaitInfoType.none); await SetDiscCaptionAsync(message.Chat.Id, message.From.Id); break; case (int)awaitInfoType.exchange: db.SetExchange(text, message.From.Id, true); db.SetAwaitInfoType(message.From.Id, (int)awaitInfoType.none); await SetDiscCaptionAsync(message.Chat.Id, message.From.Id); break; case (int)awaitInfoType.location: db.SetAwaitInfoType(message.From.Id, (int)awaitInfoType.none); db.SetLocation(text, message.From.Id); await bot.SendTextMessageAsync(message.From.Id, $"Профиль создан.", replyMarkup : IReplies.keyboards.main); Console.WriteLine(); return; case (int)awaitInfoType.photo: if (message.Photo == null) { break; } string photo = message.Photo[message.Photo.Length - 1].FileId; db.SetPhoto(photo, message.From.Id, true); await bot.EditMessageMediaAsync( chatId : message.Chat.Id, messageId : db.GetEditMessageId(message.From.Id), media : new Telegram.Bot.Types.InputMediaPhoto(photo)); await SetDiscCaptionAsync(message.Chat.Id, message.From.Id); break; case (int)awaitInfoType.discNumber: db.SetAwaitInfoType(message.From.Id, (int)awaitInfoType.none); var temp1 = await bot.SendPhotoAsync(message.Chat.Id, db.GetPhotoForList(message.From.Id, Convert.ToInt32(message.Text)), caption : db.GetSelectedFromListOffer(message.From.Id, Convert.ToInt32(message.Text)), replyMarkup : IReplies.editKeyboard(db.GetOfferPlatform(message.From.Id))); db.SetEditMessageId(message.From.Id, temp1.MessageId); break; case (int)awaitInfoType.searchResult: db.SetAwaitInfoType(message.From.Id, (int)awaitInfoType.none); int discId = Convert.ToInt32(message.Text.Substring(5).Split(':')[0]); db.SetSelectedOffer(message.From.Id, discId); await bot.SendPhotoAsync(message.Chat.Id, db.GetPhoto(discId), caption : db.GetCaption(discId), replyMarkup : IReplies.discKeyboard()); break; case (int)awaitInfoType.favNumber: if (Convert.ToInt32(message.Text) > db.GetAmountOfFav(message.From.Id) || Convert.ToInt32(message.Text) < 1) { break; } db.SetAwaitInfoType(message.From.Id, (int)awaitInfoType.none); int ownerId = db.GetOwnerId(db.GetSelectedOffer(message.From.Id)); var temp2 = await bot.SendPhotoAsync(message.Chat.Id, db.GetPhoto(db.GetFavDisc(message.From.Id, Convert.ToInt32(message.Text))), caption : db.GetSelectedFromFav(db.GetFavDisc(message.From.Id, Convert.ToInt32(message.Text))), replyMarkup : IReplies.favKeyboard()); db.SetEditMessageId(message.From.Id, temp2.MessageId); db.SetEditOfferId(message.From.Id, db.GetFavDisc(message.From.Id, Convert.ToInt32(message.Text))); break; default: Console.WriteLine("Unprocessed message found. Deleted.".Pastel(Color.Gold)); break; } await bot.DeleteMessageAsync(e.Message.Chat.Id, e.Message.MessageId); return; case "/start": db.NewUser(message.From.Id, message.From.Username); await bot.SendTextMessageAsync(message.From.Id, $"Привет {message.From.Username}, это бот по обмену дисками!"); await bot.SendTextMessageAsync(message.From.Id, $"Пожалуйста, введите ваш город проживания:"); db.SetAwaitInfoType(message.From.Id, (int)awaitInfoType.location); break; case "/keyboard": await bot.SendTextMessageAsync(message.Chat.Id, "Выберите опцию из меню ниже:", replyMarkup : IReplies.keyboards.main); break; case "Назад ↩️": await bot.SendTextMessageAsync(message.Chat.Id, "Выберите опцию из меню ниже:", replyMarkup : IReplies.keyboards.main); break; case "Контакты 📱": await bot.SendTextMessageAsync(message.Chat.Id, "Выберите опцию из меню ниже:", replyMarkup : IReplies.keyboards.contact); break; case "Помощь ❓": await bot.SendTextMessageAsync(message.Chat.Id, "Выберите опцию из меню ниже:", replyMarkup : IReplies.keyboards.help); break; case "Поиск 🔎": await bot.SendTextMessageAsync(message.Chat.Id, "Чтобы начать поиск игр, нажмите на кнопку ниже:", replyMarkup : IReplies.keyboards.search); break; case "Мой профиль 👤": await bot.SendTextMessageAsync(message.Chat.Id, "Выберите опцию из меню ниже:", replyMarkup : IReplies.keyboards.profile); break; case "Мои товары 💿": if (db.UserHasOffers(message.From.Id)) { await bot.SendTextMessageAsync(message.Chat.Id, db.GetUserOffers(message.From.Id)); db.SetAwaitInfoType(message.From.Id, (int)awaitInfoType.discNumber); } else { await bot.SendTextMessageAsync(message.Chat.Id, "У вас нет созданных дисков:", replyMarkup : IReplies.keyboards.profile); db.SetAwaitInfoType(message.From.Id, (int)awaitInfoType.none); } break; case "Добавить товар 💿": if (e.Message.From.Username == null && db.GetUserPhone(message.From.Id) == "") { await bot.SendTextMessageAsync(e.Message.Chat.Id, "ℹ️ Не удалось получить ваш никнейм.\n\n" + "Чтобы покупатель мог связатся с вами, добавьте свой номер телефона в настройках профиля.\n" + "Вы также можете создать свой никнейм и повторить попытку."); return; } db.NewOffer(message.From.Id); var temp = await bot.SendPhotoAsync(message.Chat.Id, "AgACAgIAAxkBAAIGZF9aSti3CZNeKoW3AjRGDco3-45KAAL3rjEb0L7RSjbSrDV25SE0ECFzly4AAwEAAwIAA3gAA3CNAAIbBA", caption : db.GetCaption(message.From.Id, true), replyMarkup : IReplies.editKeyboard(db.GetOfferPlatform(message.From.Id))); db.SetEditMessageId(message.From.Id, temp.MessageId); break; case "Избранное 🌟": if (db.UserHasFav(message.From.Id)) { await bot.SendTextMessageAsync(message.Chat.Id, db.GetUserFav(message.From.Id)); db.SetAwaitInfoType(message.From.Id, (int)awaitInfoType.favNumber); } else { db.SetAwaitInfoType(message.From.Id, (int)awaitInfoType.none); await bot.SendTextMessageAsync(message.Chat.Id, "У вас нет избранных товаров", replyMarkup : IReplies.keyboards.main); } break; } } catch (MessageIsNotModifiedException e1) { log.Error(e1.Message); return; } catch (FormatException e2) { log.Error(e2.Message); return; } catch (ApiRequestException e4) { log.Error(e4.Message); return; } catch (System.Net.Http.HttpRequestException e3) { log.Error(e3.Message); await bot.GetUpdatesAsync(); return; } }
#pragma warning disable AsyncFixer03 // Avoid fire & forget async void methods private static async void ReceiveAsync(this ITelegramBotClient client, ReceiverOptions options, CancellationToken cancellationToken) { var sw = new Stopwatch(); IsReceiving = true; while (!cancellationToken.IsCancellationRequested) { var timeout = 30; var updates = EmptyUpdates; sw.Reset(); try { //let's see if Telegram is responding slowly.... Program.log.Info("Starting a getUpdates request"); sw.Start(); updates = await client.GetUpdatesAsync( MessageOffset, timeout : timeout, limit : options.Limit, allowedUpdates : options.AllowedUpdates, cancellationToken : cancellationToken ).ConfigureAwait(false); sw.Stop(); Program.log.Info($"Time to receive updates: {sw.ElapsedMilliseconds}ms"); } catch (OperationCanceledException opException) { Program.log.Error("Error getting updates", opException); } catch (ApiRequestException apiException) { Program.log.Error("Error getting updates", apiException); OnReceiveError?.Invoke("receiver", apiException); } catch (Exception generalException) { Program.log.Error("Error getting updates", generalException); OnReceiveGeneralError?.Invoke("receiver", generalException); } try { Program.log.Info($"Received {updates.Length} updates, processing"); MessagesReceived += updates.Length; new Task(() => { foreach (var update in updates) { OnUpdateReceived(new UpdateEventArgs(update)); } }).Start(); if (updates.Length > 0) { MessageOffset = updates[updates.Length - 1].Id + 1; } } catch (Exception e) { Program.log.Error("Error getting updates", e); IsReceiving = false; throw; } } IsReceiving = false; }