2

I am trying to make a simple echo bot on Telegram with Python, hosted as a microservice on hook.io.

Problem: Cannot parse the POST data from the Hook object.

I tried the JavaScript method from here in another bot, worked fine. Tried to make the same thing in Python as follows:

import requests 

bottoken = 'TOKEN_GOES_HERE'
baseURL = 'https://api.telegram.org/bot'
  
if __name__ == '__main__':
    data = {
    "chat_id" : Hook['params']['message']['chat']['id'],
    "text" : Hook['params']['message']['text']
    }
    sendURL = baseURL + bottoken + "/sendMessage"
    requests.post(sendURL, json=data)

But not getting any response.

Update:

I resolved the problem by doing a json.dumps followed by json.loads on Hook['params'].

Here's the full code:

import requests
import json
  
bottoken = 'TOKEN_GOES_HERE'
baseURL = 'http://api.telegram.org/bot'
  
if __name__ == '__main__':
    data = json.loads(json.dumps(Hook['params']))
    chat_id = data['message']['chat']['id']
    sendmsg = data['message']['text']
    data = { "chat_id" : chat_id, "text" : sendmsg }
    sendURL = baseURL + bottoken + "/sendMessage"
    payload = json.dumps(data)
    headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
    requests.post(sendURL, data=payload, headers=headers, verify=False)
Community
  • 1
  • 1
cogito404
  • 21
  • 3

0 Answers0