user1781336
user1781336

Reputation: 85

Telegram Bot /getUpdates and parse JSON response?

I am looking to parson the JSON response from executing the Telegram API call: https://api.telegram.org/bot<token>/getUpdates

From that response, I want to store all the chat_IDs somewhere. I would like to loop through all those IDs to send a message via the bot into each group chat.

import requests

def telegram_bot_sendtext(bot_message):

    bot_token = ''
    bot_chatID = ''
    bot_message = ''

    get_updates = 'https://api.telegram.org/bot' + bot_chatID + '/getUpdates'
    response = requests.get(get_updates)
    final = json.loads(response.text)

    Dict = {final['result']['update_id']}


    send_text = 'https://api.telegram.org/bot' + bot_token + '/sendMessage?chat_id=' + bot_chatID + '&parse_mode=Markdown&text=' + bot_message

    response = requests.get(send_text)

    return response.json()

I know I am not creating this dictionary from the response correctly. How do I create this dictionary or array correctly and then loop through that object to send the bot_message in each of those groups?

Upvotes: 0

Views: 6401

Answers (1)

Dickens A S
Dickens A S

Reputation: 4054

result is an array of objects, you can use this kind of code to loop through it

 Dict = final['result']

 for obj in Dict:
   print(obj['update_id'])

I tested this, if you want to read the message then

   obj['message']['text']

Upvotes: 1

Related Questions