telegramapi/main.py

35 lines
963 B
Python
Raw Permalink Normal View History

2021-07-06 10:30:51 +00:00
try:
2021-07-06 10:36:03 +00:00
import urequests as requests #For MicroPython
2021-07-06 10:30:51 +00:00
except :
import requests
import json
with open("config.json", 'r') as f:
config = json.load(f)
offset = "0"
while True:
#long poll for response
2021-07-08 11:05:44 +00:00
querry = 'limit=1&offset={}&timeout=10'.format(offset)
2021-07-06 10:30:51 +00:00
try:
2021-07-08 11:05:44 +00:00
resp = requests.get(url='https://api.telegram.org/bot{}/{}?{}'.format(config["token"], "getUpdates", querry))
2021-07-06 10:30:51 +00:00
json = resp.json()
resp.close()
if json.get("result"):
#get latest message
offset = json.get("result")[0].get("update_id") + 1
text = json["result"][0]["message"]["text"]
print(text)
2021-07-06 10:36:03 +00:00
#echo message
2021-07-08 11:05:44 +00:00
querry = 'chat_id={}&text={}'.format(config["recipient"], text)
requests.get(url='https://api.telegram.org/bot{}/{}?{}'.format(config["token"], "sendMessage", querry))
2021-07-06 10:30:51 +00:00
except Exception as e:
print(e)
resp.close()