简体   繁体   中英

How get id of the message I sent with my Telegram bot via Python?

To send the message on my Telegram channel, I use the following template that works perfectly:

import requests

headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36"
    }

chat_telegram = ['XXXXXXXXXXXXX']

textalert = f'Test'
botalert = 'YYYYYYYYYYYYYYYYYYYYY'
urlalert = f'https://api.telegram.org/bot{botalert}/sendMessage'
params = {'text':textalert, 'chat_id':chat_telegram, 'parse_mode':'HTML'}
return_request = requests.get(urlalert, headers=headers, params=params)

I've tried using all four of the following ways to try to retrieve the message ID that was sent:

print(return_request['update']['message']['message_id'])
print(return_request['message']['message_id'])
print(return_request.update.message.message_id)
print(return_request.message.message_id)

But none returned positively, how should I proceed to recover the value I need?

Here is the API map

The message id is stored in the response.text part of the response, you can retrieve it via the json method:

import requests

headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36"
    }

chat_id = ['chat id']

textalert = f'Test'
botalert = 'some token'
urlalert = f'https://api.telegram.org/bot{botalert}/sendMessage'
params = {'text':textalert, 'chat_id':chat_id, 'parse_mode':'HTML'}

response = requests.get(urlalert, headers=headers, params=params)
json_data = response.json()

# get the message id
print('message id', json_data['result']['message_id'])

alternatively, you can retrieve it with the json module:

import json
json_data = json.loads(response.text)
# json_data['result']['message_id']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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