我正在尝试使用 editMessageText 编辑电报机器人上的消息,但它需要一个 message_id 整数,因此当我发送消息时,我需要以某种方式解析电报响应< /p>
https://api.telegram.org/bot12345:abcdefghijk-lmnopqrstuvwxyz/sendMessage?text=Some%20Text&chat_id=123456789
它会以这样的方式响应:
{"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"}}
所以我想解析 message_id,以便我以后可以编辑它。
答案 0 :(得分:1)
您需要反序列化来自 Telegram 的响应。之后它将是一个 Python 对象。在这种情况下,因为它是一个 JSON 对象,所以它会变成一个 dict 并且可以这样访问。
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
如果您使用请求,它有自己的 JSON encorder/decoders