简体   繁体   English

解析电报机器人 api 响应

[英]Parsing telegram bot api response

I am trying to edit messages on telegram bot with the editMessageText , but it requires a message_id integer, so i need to somehow parse the telegram response when i send a message with我正在尝试使用editMessageText在电报机器人上编辑消息,但它需要一个message_id integer,所以当我发送消息时我需要以某种方式解析电报响应

https://api.telegram.org/bot12345:abcdefghijk-lmnopqrstuvwxyz/sendMessage?text=Some%20Text&chat_id=123456789

it will respond with something like this:它会以这样的方式回应:

{"ok":true,"result":{"message_id":213557,"from":{"id":bot_id,"is_bot":true,"first_name":"BotName","username":"SpaceTheBot"},"chat":{"id":123456789,"title":"A Group","type":"supergroup"},"date":1612928163,"text":"Some text"}}

so i wanna parse the message_id, so i can edit it later on.所以我想解析message_id,所以我可以稍后编辑它。

You will need to deserialize the response from Telegram.您将需要反序列化来自 Telegram 的响应。 After that it will be a Python object.之后它将是 Python object。 In this case because it is a JSON object it will be turned into a dict and can be accessed as such.在这种情况下,因为它是一个 JSON object 它将被转换为一个字典并且可以这样访问。

import json

response = '{"ok":true,"result":{"message_id":213557,"from":{"id":"bot_id","is_bot":true,"first_name":"BotName","username":"SpaceTheBot"},"chat":{"id":123456789,"title":"A Group","type":"supergroup"},"date":1612928163,"text":"Some text"}}'
result = json.loads(response)

print(result["result"]["message_id"])
>>> 213557

If you are using requests, it has its own JSON encorder/decoders如果您使用请求,它有自己的JSON 编码器/解码器

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM