/// <summary> /// Telegram bot message handler /// </summary> public async Task OnBotMessage(Message message) { try { var telegramUser = new TelegramUserInfo(message); if (message.Document != null) { await ProcessMessage(telegramUser, message, ProcessGpx); } else if (message.Text != null) { switch (message.Text.ToLower()) { case "/start": await ProcessMessage(telegramUser, message, MessageStart); break; case "/myid": await ProcessMessage(telegramUser, message, MessageMyid); break; case "/list": await ProcessMessage(telegramUser, message, MessageList); break; case var routeStr when new Regex("/renamelast ([^;]+)", RegexOptions.IgnoreCase).IsMatch(routeStr): await ProcessMessage(telegramUser, message, MessageRenameLast); break; case var routeStr when new Regex("/rename:([0-9]+) ([^;]+)", RegexOptions.IgnoreCase).IsMatch(routeStr): await ProcessMessage(telegramUser, message, MessageRename); break; case var routeStr when new Regex("/delete:([0-9]+)", RegexOptions.IgnoreCase).IsMatch(routeStr): await ProcessMessage(telegramUser, message, MessageDelete); break; default: await _telegramBot.SendTextMessageAsync(message.Chat, "Unknown command"); _logger.LogInformation("Unprocessed. From {@TelegramUser} has been received {Message}", telegramUser, message.Text); break; } } } catch (Exception ex) { var output = $"Error, unable to process. \n{ex.Message}"; _logger.LogWarning(ex, "Error processing {@Message}, {@User}, {@Document}, {Output}", message.Text, message.From, message.Document, output); await _telegramBot.SendTextMessageAsync(message.Chat, output); } }
private async Task ProcessMessage( TelegramUserInfo telegramUser, Message message, Func <Message, YasUser, Task <string> > processAction) { var yasUser = await LoadOrCreateYasUser(telegramUser); var output = await processAction(message, yasUser); try { await _telegramBot.SendTextMessageAsync(message.Chat, output, ParseMode.Html); } catch (Exception ex) { _logger.LogWarning(ex, "Unable to send formatted message, trying plane text. \n {Output}", output); await _telegramBot.SendTextMessageAsync(message.Chat, output, ParseMode.Default); } _logger.LogInformation("For {@TelegramUser} has been processed {Message} and returned {Output}", yasUser, message.Text, output); }
private async Task <YasUser> LoadOrCreateYasUser(TelegramUserInfo telegramUser) { await using var db = _dbFactory.Create(); var yasUserInfo = await db.GetTable <YasUser>() .Where(u => u.TelegramId == telegramUser.UserId) .SingleOrDefaultAsync(); if (yasUserInfo == null) { yasUserInfo = new YasUser() { TelegramId = telegramUser.UserId, PublicId = shortid.ShortId.Generate(new GenerationOptions { Length = 10, UseNumbers = true, UseSpecialCharacters = false }), UserName = telegramUser.UserName, RegisterTime = DateTime.UtcNow }; yasUserInfo.UserId = await db.GetTable <YasUser>().DataContext.InsertWithInt64IdentityAsync(yasUserInfo); } return(yasUserInfo); }