3

I am developing telegram notifications in my existing asp.net core 3.1 project. I have written below code in controller.

#region Telegram

TelegramBotClient _botService;
private const string token = "332435:45345345345dflskdfjksdjskdjflkdd";

[HttpPost("Update")]
[AllowAnonymous]
public async Task<IActionResult> Update([FromBody] Update update)
{

    System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
    if (_botService == null)
        _botService = new TelegramBotClient(token);
    if (update.Type != UpdateType.Message)
        return Ok(new Response
        {
            code = (int)HttpStatusCode.OK,
            status = "Ok",
            message = "Success"
        });

    var message = update.Message;
    try
    {
        _logger.LogInformation("Received Message from {0}", message.Chat.Id);

        switch (message.Type)
        {
            case MessageType.Text:
                if (message.Text.Contains("/Reset"))
                {
                    //Delete(string chatid)
                    var response = _UserRepository.DeleteTeleBotChatID(message.Chat.Id);
                    if (response)
                        await _botService.SendTextMessageAsync(message.Chat.Id, "You have successfully unsubscribed.");
                    else
                        await _botService.SendTextMessageAsync(message.Chat.Id, "You are not registered yet.");
                }
                else
                if (message.Text.Contains("/") && !message.Text.ToLower().Contains("/start"))
                {
                    var user = Crypto.decrypt(Encoding.UTF8.GetString(Convert.FromBase64String(message.Text.Split('/').Last())));
                    var response = _UserRepository.UpdateTeleBotChatIDByUser(new TeleBotModel() { ChatId = message.Chat.Id, Username = user });
                    if (response)
                        await _botService.SendTextMessageAsync(message.Chat.Id, $"You have successfully subscribe notifications for {user}.");
                    else
                        await _botService.SendTextMessageAsync(message.Chat.Id, "Username is not valid");
                    // var chat=modifyus(string username,chatid)
                }
                else
                {
                    await _botService.SendTextMessageAsync(message.Chat.Id, "Enter your encrypted username.\n Type /Reset to unsubscribe.");
                }
                break;
            case MessageType.Photo:
                // Download Photo
                var fileId = message.Photo.LastOrDefault()?.FileId;
                var file = await _botService.GetFileAsync(fileId);

                var filename = file.FileId + "." + file.FilePath.Split('.').Last();
                using (var saveImageStream = System.IO.File.Open(filename, FileMode.Create))
                {
                    await _botService.DownloadFileAsync(file.FilePath, saveImageStream);
                }

                await _botService.SendTextMessageAsync(message.Chat.Id, "Thx for the Pics");
                break;
        }
    }
    catch (Exception exp)
    {
        //LoggerSimple.Error(exp);
        await _botService.SendTextMessageAsync(message.Chat.Id, "Wrong Bot command");
    }
    return Ok(new Response
    {
        code = (int)HttpStatusCode.OK,
        status = "Ok",
        message = "Success"
    });

}

[HttpPost]
public async Task<IActionResult> sendTeleMsg(TelegramMessgae Data)
{
    System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
    if (_botService == null)
        _botService = new TelegramBotClient(token);
    //check username exist 
    long ChatId = _UserRepository.GetChatIdByUsername(Data.Username);
    if (ChatId == -1)
    {
        return Ok(new Response
        {
            error = "true",
            code = HttpStatusCode.BadRequest,
            status = HttpStatus.OK,
            message = "Not registered with telegram bot"
        });
    }
    try
    {
        await _botService.SendTextMessageAsync(ChatId, string.Format("*{0}*\n{1}", parseMText(Data.Subject), parseMText(Data.Message)), ParseMode.Markdown);
        return Ok(new Response
        {
            code = HttpStatusCode.OK,
            status = HttpStatus.OK,
            message = "Message Sent"
        });
    }
    catch (Exception exp)
    {
        //if wrong chatid 
        _UserRepository.DeleteTeleBotChatID(ChatId);
        return Ok(new Response
        {
            error = "true",
            code = HttpStatusCode.BadRequest,
            status = HttpStatus.OK,
            message = exp.Message
        });
    }
}
private string parseMText(string txt)
{
    var vs = new string[] { "*", "_", "`", "[", "]" };
    foreach (var item in vs)
    {
        txt = txt.Replace(item, "\\" + item);
    }
    return txt;
}
#endregion

then used ngrok for tunnelling and exposed localhost so that I can connect with telegram bot. After creating and subscribing the bot, I am able to receive a breakpoint in above Update method but data was nothing. I sent messages on bot but always there is no data in update object. See below screenshot. I am unable to figure-out the issue in the code. Can anyone pls help? enter image description here enter image description here enter image description here

Jitendra Pancholi
  • 7,897
  • 12
  • 51
  • 84

1 Answers1

1

Calling AddNewtonsoftJson() function in starup.cs file fixed the issue.

services.AddControllers().AddNewtonsoftJson();

enter image description here

Jitendra Pancholi
  • 7,897
  • 12
  • 51
  • 84