private TelegramUpdate AdjustResponse(object items) { TelegramUpdate telegramUpdate = new TelegramUpdate(); IDictionary <string, dynamic> dictionaryItems = (IDictionary <string, dynamic>)items; telegramUpdate.Ok = bool.Parse(dictionaryItems["ok"].ToString()); IList lstResults = (IList)dictionaryItems["result"]; foreach (dynamic result in lstResults) { IDictionary <string, dynamic> messageItens = (IDictionary <string, dynamic>)result["message"]; IDictionary <string, dynamic> messageFrom = (IDictionary <string, dynamic>)messageItens["from"]; IDictionary <string, dynamic> messageChat = (IDictionary <string, dynamic>)messageItens["chat"]; Update updateToBeAdded = new Update { UpdateId = long.Parse(result["update_id"].ToString()) }; updateToBeAdded.MessageData = new Message(); updateToBeAdded.MessageData.ChatId = messageChat.ContainsKey("id") ? long.Parse(messageChat["id"].ToString()) : 0; updateToBeAdded.MessageData.DateMessage = messageItens.ContainsKey("date") ? DateTimeParser(double.Parse(messageItens["date"].ToString())) : DateTime.MinValue; updateToBeAdded.MessageData.FirstName = messageFrom.ContainsKey("first_name") ? messageFrom["first_name"].ToString() : string.Empty; updateToBeAdded.MessageData.LastName = messageFrom.ContainsKey("last_name") ? messageFrom["last_name"].ToString() : string.Empty; updateToBeAdded.MessageData.MessageId = messageItens.ContainsKey("message_id") ? long.Parse(messageItens["message_id"].ToString()) : 0; updateToBeAdded.MessageData.Text = messageItens.ContainsKey("text") ? messageItens["text"].ToString() : string.Empty; updateToBeAdded.MessageData.UserId = messageFrom.ContainsKey("id") ? long.Parse(messageFrom["id"].ToString()) : 0; updateToBeAdded.MessageData.Username = messageFrom.ContainsKey("username") ? messageFrom["username"].ToString() : string.Empty; telegramUpdate.Updates.Add(updateToBeAdded); } return(telegramUpdate); }
//make from static or ctor private void FromTelegram(string body) { TelegramUpdate update = JsonConvert.DeserializeObject <TelegramUpdate>(body, Utils.ConverterSettingsSnake); switch (update.Type) { case UpdateType.Message: Id = update.Message.MessageId.ToString(); Text = update.Message.Text; Payload = ""; User = new User(update.Message.From); TelegramCommand = new TelegramCommand(update.Message); break; case UpdateType.CallbackQuery: Id = update.CallbackQuery.Message.MessageId.ToString(); Text = ""; Payload = update.CallbackQuery.Data; User = new User(update.CallbackQuery.From); TelegramCommand = new TelegramCommand(update.Message); break; default: throw new ArgumentException("This update type is not supported"); } }
public OkResult HandleWebhook(string token, [FromBody] TelegramUpdate telegramUpdate) { try { if (token != _token) { return(Ok()); } if (telegramUpdate?.TelegramMesssage?.TelegramChat == null) { return(Ok()); } var chat = telegramUpdate.TelegramMesssage.TelegramChat; if (telegramUpdate.TelegramMesssage.TelegramChat.Type != ChatTypes.Private) { _messageParser.AddUpdateChatListing(chat); } var response = _messageParser.GetChatResponse(telegramUpdate.TelegramMesssage.Text); if (string.IsNullOrWhiteSpace(response)) { return(Ok()); } _telegramRepository.SendMessage(response, chat.Id); } catch (Exception ex) { Trace.TraceError(ex.ToString()); return(Ok()); //stop telegram spamming our webhook if we fail } return(Ok()); }
public static async Task <HttpResponseMessage> Run([HttpTrigger(WebHookType = "genericJson")] HttpRequestMessage req, ILogger log) { _log = log; log.LogInformation("DarioBot was triggered!"); MonitorReportList.Clear(); try { string botToken = DarioBotConfiguration.Get(DarioBotConfiguration.BotTokenKey); _logToId = int.Parse(DarioBotConfiguration.Get(DarioBotConfiguration.LogToIdKey)); _telegramClient = new TelegramBot(botToken); string jsonContent = await req.Content.ReadAsStringAsync(); log.LogInformation(jsonContent); _telegramUpdate = JsonConvert.DeserializeObject <TelegramUpdate>(jsonContent); TelegramFrom telegramFrom = GetFrom(_telegramUpdate); string message = GetMessage(_telegramUpdate); LogMessage($"received message from {telegramFrom?.FirstName} {telegramFrom?.LastName}. {message}"); string toId = DarioBotConfiguration.Get(DarioBotConfiguration.ForwardToIdKey); string resourcesPath = DarioBotConfiguration.Get(DarioBotConfiguration.RemoteResourcesPathKey); string azureStorageConnectionString = DarioBotConfiguration.Get(DarioBotConfiguration.StorageConnectionStringKey); string azureStorage = DarioBotConfiguration.Get(DarioBotConfiguration.AzureStorageNameKey); log.LogInformation($"forwardId: {toId}"); DarioBot darioBot = new DarioBot( botToken, toId, new AzureFileRepository(azureStorageConnectionString, resourcesPath, azureStorage)); IDarioBotReply reply = darioBot.ReplyBack(_telegramUpdate); LogMessage( $"DarioBot reply to {telegramFrom?.FirstName} {telegramFrom?.LastName}. {message} --> {reply.Type}"); await reply.SendBackReplay(); LogMessage($"DarioBot replied with success"); } catch (JsonSerializationException e) { LogError(e.Message); LogError(e.StackTrace); return(req.CreateResponse(HttpStatusCode.BadRequest)); } catch (Exception e) { LogError(e.Message); LogError(e.StackTrace); return(req.CreateResponse(HttpStatusCode.InternalServerError)); } finally { SendReport(); } return(req.CreateResponse(HttpStatusCode.OK)); }
public static Task ReceiveTelegramUpdateAsync( [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req, ILogger log, ExecutionContext context ) { return(Function.ExecuteAsync(log, nameof(ReceiveTelegramUpdateAsync), async() => { var flightNotifier = Container.Build(context, log).GetFlightNotifier(); var update = await DeserializeMessageAsync(); if (update.Message == null) { log.LogInformation("Message text is null, quiting"); return new OkObjectResult("ok"); } var telegramUpdate = new TelegramUpdate(update); await flightNotifier.ProcessTelegramUpdateAsync(telegramUpdate, log); return new OkObjectResult("ok"); })); async Task <Update> DeserializeMessageAsync() { using (var streamReader = new StreamReader(req.Body)) { var bytes = await streamReader.ReadToEndAsync(); return(JsonConvert.DeserializeObject <Update>(bytes)); } } }
public static TelegramMessage Create(TelegramUpdate update) { if (!IsTelegramMessage(update)) { throw new Exception("Update is not a valid TelegramMessage"); } return(new TelegramMessage(update.Id, update.Message)); }
private static HttpRequestMessage CreateRequest(out ILogger logger, TelegramUpdate requestPayload) { var request = TestFactory.CreateHttpRequest(HttpMethod.Post, ""); logger = TestFactory.CreateLogger(); ; request.Content = new ObjectContent <TelegramUpdate>(requestPayload, new JsonMediaTypeFormatter()); return(request); }
public static TelegramUpdate CreateFakeTelegramUpdate(UpdateType type) { var update = new TelegramUpdate(); switch (type) { case UpdateType.Unknown: break; case UpdateType.Message: update.Message = new Message(); break; case UpdateType.InlineQuery: update.InlineQuery = new InlineQuery(); break; case UpdateType.ChosenInlineResult: update.ChosenInlineResult = new ChosenInlineResult(); break; case UpdateType.CallbackQuery: update.CallbackQuery = new CallbackQuery(); break; case UpdateType.EditedMessage: update.EditedMessage = new Message(); break; case UpdateType.ChannelPost: update.ChannelPost = new Message(); break; case UpdateType.EditedChannelPost: update.EditedChannelPost = new Message(); break; case UpdateType.ShippingQuery: update.ShippingQuery = new ShippingQuery(); break; case UpdateType.PreCheckoutQuery: update.PreCheckoutQuery = new PreCheckoutQuery(); break; case UpdateType.Poll: update.Poll = new Poll(); break; default: throw new ArgumentOutOfRangeException(nameof(type), type, null); } return(update); }
public async Task Post_should_call_service() { var fakeService = new Mock <IHandleTelegramUpdate>(); var fakeUpdate = new TelegramUpdate { Id = 42 }; var controller = new TelegramController(fakeService.Object); await controller.Post(new TelegramUpdate { Id = 42 }); fakeService.Verify(x => x.HandleAsync(It.Is <TelegramUpdate>(u => u.Id == fakeUpdate.Id)), Times.Once); }
private async Task HandleUpdateAsync(TelegramUpdate update) { if (update == null) { return; } _logger.LogDebug("Update Received"); switch (update.Type) { case UpdateType.Message: await _messageHandler.HandleAsync(TelegramMessage.Create(update)); break; case UpdateType.Unknown: break; case UpdateType.InlineQuery: break; case UpdateType.ChosenInlineResult: break; case UpdateType.CallbackQuery: break; case UpdateType.EditedMessage: break; case UpdateType.ChannelPost: break; case UpdateType.EditedChannelPost: break; case UpdateType.ShippingQuery: break; case UpdateType.PreCheckoutQuery: break; case UpdateType.Poll: break; default: throw new ArgumentOutOfRangeException(); } }
public async Task HandleAsync(IUpdateContext context, UpdateDelegate next, CancellationToken cancellationToken) { //Logs update message var update = new TelegramUpdate() { Update = context.Update }; await _logs.InsertOneAsync(update, cancellationToken : cancellationToken); //Gets or creates user var user = GetUser(context.Update); TelegramUser telegramUser = (await _users .FindAsync(x => x.Id == user.Id, cancellationToken: cancellationToken)).FirstOrDefault(); if (telegramUser == null) { telegramUser = new TelegramUser() { UserData = user, Id = user.Id, FirstSeen = DateTime.Now }; await _users.InsertOneAsync(telegramUser, cancellationToken : cancellationToken); } var gameObject = new GameObject(); gameObject.User = telegramUser; if (telegramUser.LastMessage != null) { gameObject.PreviousUpdate = (await _logs.FindAsync(x => x.Id == telegramUser.LastMessage, cancellationToken: cancellationToken)).FirstOrDefault(); } context.Items.Add("game", gameObject); try { await next(context, cancellationToken); } finally { Console.WriteLine("Saving User"); telegramUser.LastMessage = update.Id; await _users.FindOneAndReplaceAsync(x => x.Id == telegramUser.Id, telegramUser, cancellationToken : cancellationToken); } }
public static void ProcessMessages() { TelegramUpdatesController updController = new TelegramUpdatesController(); TelegramMessagesSenderController messageSenderController = new TelegramMessagesSenderController(); TelegramUpdate latestUpdates = updController.GetUpdates(); if (!latestUpdates.Ok) { throw new Exception("Error getting latest updates from Telegram!"); } if (latestUpdates.Updates.Count() <= 0) { throw new Exception("Error! There is no updates."); } messageSenderController.ReturnMessages(FilterNewMessages(latestUpdates.Updates)); }
private void HandleNewMessage(TelegramUpdate m) { var user = m?.Message?.User?.Username ?? ""; var msg = m?.Message?.Text ?? ""; var parts = msg.Split(' ', StringSplitOptions.RemoveEmptyEntries); if (parts.Length < 1) { return; } switch (parts[0].Trim().ToUpperInvariant()) { case "/BIRTHCOMMANDS": ListCommands(); break; case "/BIRTHQUIT": if (!IsAdmin(user)) { break; } _telegramApi.Send("Exiting BirthdayBot"); Program.OnExit(); break; case "/BIRTHADD": AddBirthday(parts, user); break; case "/BIRTHDELETE": if (!IsAdmin(user)) { break; } DeleteBirthday(parts); break; case "/BIRTHLIST": ListBirthdays(); break; } }
public async Task ProcessTelegramUpdateAsync(TelegramUpdate update, ILogger log) { log.LogInformation($"Received update: {JsonConvert.SerializeObject(update)}"); var telegramUsername = update.Username; var chatId = update.ChatId; var userId = update.UserId; var subscriber = await GetSubscriberAsync(telegramUsername, chatId, userId); var parseResult = commandParser.Parse(update.Text); if (!parseResult.IsSuccess) { await telegramClient.SendMessageAsync(chatId, $"Не могу понять тебя. Ошибка: {parseResult.ErrorMessage}"); return; } var command = parseResult.Command; await command.ExecuteAsync(subscriber, chatId); }
public async Task HandleAsync(TelegramUpdate update) { try { await HandleUpdateAsync(update); } catch (Exception e) { if (_configuration.EnableExceptionForwarding) { //TODO: Create a properly formatted exception message await _botService.Client .SendTextMessageAsync( new ChatId(_configuration.ExceptionChatId), $"```\n{e}\n```", ParseMode.Markdown); } else { throw; } } }
public IDarioBotReply ReplyBack(TelegramUpdate telegramMsg) { TelegramMessage message = telegramMsg.Message; TelegramCallbackQuery callbackQuery = telegramMsg.CallbackQuery; if (callbackQuery != null) { return(ReplyFor(callbackQuery)); } else { if (message.Voice != null) { return(ReplyFor(message.From, message.Voice)); } if (message.Text == null) { return(new UnhandledInput(_telegramApi, _repository, message.From)); } return(ReplyFor(message)); } }
private static TelegramFrom GetFrom(TelegramUpdate telegramMsg) => telegramMsg ?.Message?.From ?? telegramMsg?.CallbackQuery?.From;
public static bool IsTelegramMessage(TelegramUpdate update) { return(update != null && update.Type == UpdateType.Message && update.Message != null); }
private static string GetMessage(TelegramUpdate telegramMsg) => telegramMsg ?.Message?.Text ?? telegramMsg?.CallbackQuery?.Data ?? "";
public async Task <IActionResult> Post(TelegramUpdate update) { await _telegramUpdateHandler.HandleAsync(update); return(Ok()); }