无法接收来自 Telegram webHook ASP.NET 的传入 JSON

Cannot receive incoming JSON from Telegram webHook ASP.NET

所以问题是我为我的 Telegram 机器人设置了一个 webHook 地址,如下所示: https://api.telegram.org/bot<TOKEN>/setWebHook?url=https://evolhookah.com/Home/ReceiveWebhook

之后,我收到 JSON 格式的确认,说明从现在起 Telegram 将向 URL 发送消息。

然后我创建了一个方法 ReceiveWebhook(),它负责处理传入的请求,这些方法以前看起来像这些方法(none 个有效):

    public ActionResult ReceiveJSON(int? id)
    {
        Stream req = Request.InputStream;
        req.Seek(0, System.IO.SeekOrigin.Begin);
        string receivedJson = new StreamReader(req).ReadToEnd();
        var bs = new TgDesserialize(); //Class containing JSON desserializing function
        PeopleAttributes people = bs.desserializer(receivedJson); //desserializer manages with desserializing received JSON and returns an object people filled up with necessary values
        return Content(people.firstName);
    }

不幸的是,流的想法不起作用,然后我决定接收传入的 JSON 作为字符串,这就是它的样子:

    public ActionResult JSONString(String receivedJSON)
    {
        var bs = new TgDesserialize(); 
        PeopleAttributes people = bs.desserializer(receivedJSON); 
        return Content(people.firstName);
    }

问题:每次我收到一个 webhook,我要么得到 null JSON,要么无法在控制器中正确接收它。

问题:

  1. 有什么方法可以检查 Telegram 在发送 webHook 时是否正在发送 JSON 内部数据?
  2. 为什么我总是得到NULL,而https://api.telegram.org/bot<TOKEN>/getUpdates却显示我里面有数据JSON?
  3. 我是否在控制器中以错误的方式接收了我的 JSON?如果是,处理传入 JSON 的最佳做法是什么?

您需要根据电报中的 JSON 创建一个 class。

示例:

电报 JSON:

{ 
    "update_id": 1
    "message": { ... fill in message json here},
    .... other properties here
}

然后您创建一个 class:

public class TelegramUpdate
{
    public int update_id {get; set;}
    public Message message {get; set;}
    // other properties here
}

public class Message
{
    // message properties here
}
// ... More nested classes go here

专业提示:如果您有示例 JSON 文件,您可以复制它,得到 Visual Studio=>编辑=>选择性粘贴=>粘贴 JSON 为 class。这将为您生成 classes

然后您可以将此 class 作为参数添加到您的 webhook:

public ActionResult JSONString(TelegramUpdate update)
{
    return Content(update.message.from.first_name);
}

首先,我建议你使用telegram.bot library and looking this example for Webhook。 但总的来说:

  1. 安装 Postman 和 post 手动消息,如电报 webhook 消息到您的控制器。然后确保您的控制器中没有错误。

邮递员示例:

{
    "update_id":10000,
    "message":{
      "date":1441645532,
      "chat":{
         "last_name":"Test Lastname",
         "id":1111111,
         "first_name":"Test",
         "username":"Test"
      },
      "message_id":1365,
      "from":{
         "last_name":"Test Lastname",
         "id":1111111,
         "first_name":"Test",
         "username":"Test"
      },
      "text":"/start"
    }

  1. 如果您的控制器是真的,您必须确保 Webhook 消息是由 Telegram 发送的。您可以下载 ngrok 并为您的本地主机创建一个 https 代理。

在 ngrok 中使用这个命令:

ngrok http 20201

20201 是您的本地主机端口 (localhost:20201)。 现在 ngrok 给你一个 https link,你必须将那个 link 设置为你的电报 webhook(就像你说的那样)。 此时,如果电报为您的机器人发送了一个 webhook 消息,那么您可以在本地主机中对其进行调试。

  1. 最后,如果您没有发现问题,您必须阅读 Marvin's Patent Pending Guide to All Things Webhook 以再次检查所有要求。
  1. Supports IPv4, IPv6 is currently not supported for Webhooks.
  2. Accepts incoming POSTs from 149.154.167.197-233 on port 443,80,88 or 8443.
  3. Is able to handle TLS1.0+ HTTPS-traffic.
  4. Provides a supported,non-wildcard, verified or self-signed certificate.
  5. Uses a CN or SAN.that matches the domain you’ve supplied on setup.
  6. Supplies all intermediate certificates to complete a verification chain.
[HttpPost]
public async Task<ActionResult> Index()
    {
        try
        {

            var req = Request.InputStream; //get Request from telegram 
            var responsString = new StreamReader(req).ReadToEnd(); //read request
            RootObject ro = JsonConvert.DeserializeObject<RootObject>(responsString);

        }
        catch (Exception ex)
        {
            return Content("Error");
        }


        // This code hint to telegram Ttat , I Get Message And dont need to send this message again
        return Content("{\"ok\":true}");

    }

然后您创建一个 class:

 public class From
{
    public int id { get; set; }
    public bool is_bot { get; set; }
    public string first_name { get; set; }
    public string username { get; set; }
    public string language_code { get; set; }
}

public class Chat
{
    public long id { get; set; }
    public string title { get; set; }
    public string type { get; set; }
    public string username { get; set; }
}

public class ForwardFromChat
{
    public long id { get; set; }
    public string title { get; set; }
    public string type { get; set; }
}

public class Document
{
    public string file_name { get; set; }
    public string mime_type { get; set; }
    public string file_id { get; set; }
    public int file_size { get; set; }
}
public class Audio
{
    public int duration { get; set; }
    public string mime_type { get; set; }
    public string title { get; set; }
    public string performer { get; set; }
    public string file_id { get; set; }
    public int file_size { get; set; }
}
public class Photo
{
    public string file_id { get; set; }
    public int file_size { get; set; }
    public int width { get; set; }
    public int height { get; set; }
}
public class Video
{
    public int duration { get; set; }
    public int width { get; set; }
    public int height { get; set; }
    public string mime_type { get; set; }
    public Thumb thumb { get; set; }
    public string file_id { get; set; }
    public int file_size { get; set; }
}
public class Thumb
{
    public string file_id { get; set; }
    public int file_size { get; set; }
    public int width { get; set; }
    public int height { get; set; }
}
public class Message
{
    public int message_id { get; set; }
    public From from { get; set; }
    public Chat chat { get; set; }
    public int date { get; set; }
    public string text { get; set; }
}

public class CaptionEntity
{
    public int offset { get; set; }
    public int length { get; set; }
    public string type { get; set; }
}

public class EditedChannelPost
{
    public int message_id { get; set; }
    public Chat chat { get; set; }
    public int date { get; set; }
    public int edit_date { get; set; }
    public string caption { get; set; }
    public List<CaptionEntity> caption_entities { get; set; }
    public string text { get; set; }
    public Document document { get; set; }
    public Video video { get; set; }
    public Audio audio { get; set; }
    public List<Photo> photo { get; set; }
}
public class ChannelPost
{
    public int message_id { get; set; }
    public Chat chat { get; set; }
    public int date { get; set; }
    public ForwardFromChat forward_from_chat { get; set; }
    public int forward_from_message_id { get; set; }
    public string forward_signature { get; set; }
    public int forward_date { get; set; }
    public string caption { get; set; }
    public string text { get; set; }
    public List<CaptionEntity> caption_entities { get; set; }
    public Document document { get; set; }
    public Video video { get; set; }
    public Audio audio { get; set; }
    public List<Photo> photo { get; set; }
}

public class RootObject
{
    public long update_id { get; set; }
    public ChannelPost channel_post { get; set; }
    public EditedChannelPost edited_channel_post { get; set; }
    public Message message { get; set; }
}

尽情享受吧!