解析电报机器人 api 响应
Parsing telegram bot api response
我正在尝试使用 editMessageText 在电报机器人上编辑消息,但它需要一个 message_id 整数,所以我需要以某种方式解析当我用
发送消息时的电报响应
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,以便稍后编辑它。
您需要反序列化来自 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
我正在尝试使用 editMessageText 在电报机器人上编辑消息,但它需要一个 message_id 整数,所以我需要以某种方式解析当我用
发送消息时的电报响应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,以便稍后编辑它。
您需要反序列化来自 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