telegramapi/main.py

35 lines
921 B
Python
Raw 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-06 10:36:03 +00:00
querry = f'limit=1&offset={offset}&timeout=10'
2021-07-06 10:30:51 +00:00
try:
2021-07-06 10:36:03 +00:00
resp = requests.get(url=f'https://api.telegram.org/bot{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
querry = f'chat_id={config["recipient"]}&text={text}'
requests.get(url=f'https://api.telegram.org/bot{config["token"]}/{"sendMessage"}?{querry}')
2021-07-06 10:30:51 +00:00
except Exception as e:
print(e)
resp.close()