protected override async Task ExecuteAsync(CancellationToken stoppingToken) { try { _logger.LogInformation("[DEBUG]Bot program is running under long polling mode"); //Bind bot handler _botService.Client.OnUpdate += async(sender, e) => { _logger.LogInformation("[DEBUG]Pulling updates from Telegram"); await _updateService.EchoAsync(e.Update); }; //Start receiving _botService.Client.StartReceiving(); await Task.FromCanceled(stoppingToken) .ContinueWith(task => { //End receiving _logger.LogInformation("[DEBUG]Exiting long polling mode"); _botService.Client.StopReceiving(); }); } catch (Exception ex) { if (!stoppingToken.IsCancellationRequested) { _logger.LogInformation($"[DEBUG]Error:{ex.Message}"); } else { _logger.LogInformation("[DEBUG]Exiting long polling mode"); _botService.Client.StopReceiving(); } } }
public async Task <IActionResult> Webhook(string secret, [FromBody] dynamic jsonresult) { try { Update w = JsonConvert.DeserializeObject <Update>(jsonresult.ToString()); // Return if the secret is not correct if (secret != AppSettingsProvider.WebHookSecret) { return(Unauthorized()); } if (w != null) { await _updateService.EchoAsync(w); } } catch (Exception ex) { var log = new Log(); log.LogMessage(ex.Message + " " + ex.StackTrace + " " + ex.InnerException); _appdb.Logger.Add(log); _appdb.SaveChangesAsync().Wait(); } return(Ok()); }
public async Task <IActionResult> EchoMessages(CancellationToken cancellationToken, [FromBody] RequestUpdate update = null) { if (update?.Message == null) { return(Ok()); } await _updateService.EchoAsync(update, cancellationToken); return(Ok()); }
public async Task <IActionResult> Post([FromBody] Update update) { if (update == null) { return(Ok()); } await _updateService.EchoAsync(update); return(Ok()); }
public async Task <IActionResult> Post([FromBody] Update update) { const string TRAFFICCONTROL = "trafficControl"; string cacheKey = $"{TRAFFICCONTROL}_{update.Message.Chat.Id}"; var trafficControl = await _cache.GetStringAsync(cacheKey); if (string.IsNullOrWhiteSpace(trafficControl)) { _cache.SetStringAsync(key: cacheKey, value: "1").Wait(); _updateService.EchoAsync(update).Wait(); await _cache.RemoveAsync(key : cacheKey).ConfigureAwait(false); } else { await _updateService.WaitForReturnAsync(update).ConfigureAwait(false); } return(Ok()); }
public async Task <IActionResult> Post([FromBody] Update update) { await _updateService.EchoAsync(update, "hello world"); return(Ok()); }
public async Task <OkResult> Update([FromBody] Update update) { try { var remoteIpAddress = Request?.HttpContext?.Connection?.RemoteIpAddress; _logger.LogInformation("Remote Ip Address {0}, {1}", remoteIpAddress, remoteIpAddress?.MapToIPv4()); var inputData = System.Text.Json.JsonSerializer.Serialize(update); var msg = update.Message; if (msg == null) { _logger.LogInformation("Incoming empty message"); Ok(); } _logger.LogInformation("Incomming message from {0}, contact {1}, message {2}", string.Concat(update?.Message?.From?.Id, ":", update?.Message?.From?.FirstName, " ", update?.Message?.From?.LastName), update?.Message?.Contact?.PhoneNumber, update?.Message?.Text); ChatInfo chatInfo = null; if (true) { using (ApplicationContext db = new ApplicationContext()) { Chat chat = msg?.Chat; if (chat != null) { chatInfo = _mapper.Map <ChatInfo>(chat); Save(db, chatInfo); } User from = GetFrom(update); if (update?.Message?.Contact != null) { } if (from == null) { return(Ok()); } var fromUser = _mapper.Map <TelegramUser>(from); var user = db.TelegramUsers.FirstOrDefault(p => p.Id == fromUser.Id); if (user == null) { db.TelegramUsers.Add(fromUser); db.SaveChanges(); } if (update.Type == UpdateType.CallbackQuery) { await _updateService.AddLike(db, update, from); return(Ok()); } db.SaveChanges(); if (!ProcessCommand(update, msg?.Text, db, fromUser, update)) { var questText = msg?.Text; if (questText == null) { //if (msg?.Photo.Length > 0) //{ // var stream = new MemoryStream(); // var types = await _updateService.GetPhoto(msg.Photo, stream); // FIBITMAP bitmap = FreeImage.LoadFromStream(stream); // BITMAPINFO imageInfo = FreeImage.GetInfoEx(bitmap); // FREE_IMAGE_FORMAT imageType = FreeImage.GetFileTypeFromStream(stream); //} //return Ok(); } bool isToThisBot = questText != null && questText.StartsWith(_config.BotName); if (from.IsBot && questText != null) { questText = Regex.Replace(questText, @"^@\S+\s", String.Empty); } if (update.Type == UpdateType.Message) { //questText = update.InlineQuery.Query; var quest = db.Questions.FirstOrDefault(p => p.Text == questText); if (quest == null && isToThisBot) { quest = new Question { Text = questText.Substring(0, Math.Min(questText.Length, 128)), CreatedDate = DateTime.UtcNow, CreatorId = from.Id, Quantity = 1 }; db.Questions.Add(quest); } else if (quest != null) { quest.UpdatedDate = DateTime.UtcNow; quest.UpdatedId = from.Id; quest.Quantity++; } else if (!isToThisBot && !string.IsNullOrEmpty(questText) && !string.IsNullOrEmpty(msg?.ReplyToMessage?.Text)) { //Add replies human to human as quest and answer string replyText = msg.ReplyToMessage.Text; replyText = Regex.Replace(replyText, "[\n\r]", " ").Trim(); replyText = replyText.Substring(0, Math.Min(replyText.Length, 128)); var replyQuest = db.Questions.FirstOrDefault(p => p.Text.Equals(replyText)); if (replyQuest == null) { replyQuest = new Question { Text = replyText, CreatedDate = DateTime.UtcNow, CreatorId = msg.ReplyToMessage.From.Id, Quantity = 1, Answers = new List <Answer>() }; db.Questions.Add(replyQuest); } else { replyQuest.UpdatedDate = DateTime.UtcNow; replyQuest.UpdatedId = msg.ReplyToMessage.From.Id; replyQuest.Quantity++; } var answeText = questText.Substring(0, Math.Min(questText.Length, 512)); answeText = Regex.Replace(answeText, "[\n\r]", " ").Trim(); var q = db.Answers.Where(p => p.QuestionId == 88).ToList(); var answer = db.Answers .Where(p => p.Text == answeText && p.QuestionId == replyQuest.Id) .FirstOrDefault(); if (answer == null) { answer = new Answer { Text = answeText, }; replyQuest.Answers.Add(answer); } db.SaveChanges(); return(Ok()); } } if (!string.IsNullOrEmpty(questText)) { questText = Regex.Replace(questText, "[\n\r]", " ").Trim(); string toSend = null; int answerId = 0; if (isToThisBot) { var answers = GetBotAnswers(db, questText, ".4"); answerId = SelectMessage(answers, answerId, ref toSend); } else { var n = (new Random()).Next(10); var rating = n > 6 ? ".4" : ".7"; var answers = GetBotAnswers(db, questText, rating); if (answers.Any()) { answerId = SelectMessage(answers, answerId, ref toSend); } else { _logger.LogInformation($"No any items with rating >{rating}"); } } if (!string.IsNullOrWhiteSpace(toSend) && (chatInfo == null || !chatInfo.IsSelentMode)) { var responce = await _updateService.EchoAsync(update, toSend); if (responce != null) { var sended = new SendedAnswer { AnswerId = answerId, CreatedDate = DateTime.UtcNow, MessageId = responce.MessageId, }; db.SendedAnswers.Add(sended); var inputMessage = new InputMessage { MessageId = responce.MessageId, Text = questText }; db.InputMessages.Add(inputMessage); db.SaveChanges(); } } } } } } } catch (Exception e) { _logger.LogError(e, "Error"); } return(Ok()); }
public IActionResult Update([FromBody] Update message) { _updateService.EchoAsync(message); return(Ok()); }
public async Task <IActionResult> Post(string token, [FromBody] Update update) { if (token != _token) { return(Unauthorized("Invalid bot token")); } if (update.Type == UpdateType.Message) { var message = update.Message; ChatId chatId = message.Chat.Id; // if the message is a command if (message.EntityValues != null && message.EntityValues.Any()) { var command = message.EntityValues.First(); var commandProps = message.Entities.First(); switch (command) { case "/water": { var commandText = message.Text.Substring(commandProps.Offset + commandProps.Length).Trim().ToLower(); bool value; string msgText; switch (commandText) { case "on": value = true; msgText = "enabled"; break; case "off": value = false; msgText = "disabled"; break; default: InvalidCommand(chatId); return(Ok()); } var chat = await _context.ChatTracker.Where(c => c.ChatId == chatId.Identifier).FirstOrDefaultAsync(); if (chat == null) { return(BadRequest("Chat not found")); } if (chat.WaterReminder != value) { chat.WaterReminder = value; await _context.SaveChangesAsync(); await _updateService.SendMessageAsync(chatId, $"Water notifications {msgText}"); } else { await _updateService.SendMessageAsync(chatId, $"Water notifications already {msgText}"); } break; } case "/echo": await _updateService.EchoAsync(message, commandProps); break; case "/joke": { var request = new HttpRequestMessage(HttpMethod.Get, "https://icanhazdadjoke.com/"); request.Headers.Add("Accept", "text/plain"); var client = _clientFactory.CreateClient(); var response = await client.SendAsync(request); if (response.IsSuccessStatusCode) { var joke = await response.Content.ReadAsStringAsync(); await _updateService.SendMessageAsync(chatId, joke); } else { await _updateService.SendMessageAsync(chatId, "Error getting joke :("); } client.Dispose(); break; } default: InvalidCommand(chatId); break; } } } return(Ok()); }
public async Task <IActionResult> Post([FromBody] Update MessageFromTelegram) { await _updateService.EchoAsync(MessageFromTelegram); return(Ok()); }
public async Task <IActionResult> Listener([FromBody] Update update) { await _updateService.EchoAsync(update); return(Ok()); }
private async void Responder(string novaMensagem) { _update.Message.Text = novaMensagem; await _updateService.EchoAsync(_update); }