forked from syxolk/telegram-server-monitor
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathdaemon.py
executable file
·82 lines (66 loc) · 2.4 KB
/
daemon.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#!/usr/bin/env python3
import requests
import config
import methods
import atexit
import time
import argparse
import sys, select
last_update_id = 0
parser = argparse.ArgumentParser(description='Telegram Server Monitor')
parser.add_argument('--console', action='store_true',
help='Don\'t communicate with telegram but rather just test on the console')
args = parser.parse_args()
if not config.TOKEN:
print("No TOKEN found in config")
args.console = True
if args.console:
print("Running in console mode")
if not args.console:
methods.startupMessage(args.console)
atexit.register(methods.shutdownMessage)
server_retry = config.SERVER_RETRY_TIMEOUT
while True:
methods.alarms(args.console)
#print("Make request: {0}".format(last_update_id))
try:
if args.console:
i, o, e = select.select( [sys.stdin], [], [], config.TIMEOUT )
result = {}
result["ok"] = True
if i:
entry = { "message": {
"text": sys.stdin.readline().strip(),
"chat": { "id": 0 }
},
"update_id": last_update_id + 1
}
result["result"] = [ entry ]
else:
result["result"] = [ ]
else:
r = requests.post( config.API_URL + "getUpdates"
, json={ "offset" : last_update_id + 1
, "timeout" : config.TIMEOUT
}
, timeout=config.TIMEOUT + 5
)
result = r.json()
if result["ok"]:
limit = 10
for update in result["result"]:
limit-=1
if limit <= 0: break
update_id = update["update_id"]
if update_id > last_update_id:
last_update_id = update_id
methods.processMessage(update["message"], args.console)
server_retry = config.SERVER_RETRY_TIMEOUT
else:
# TODO error handling
print(result)
except (ValueError, requests.exceptions.ConnectionError, requests.exceptions.ReadTimeout) as err:
print("Connection Error {0}\nRetrying in {1} seconds".format(err, server_retry))
time.sleep(server_retry)
server_retry *= 2
#print(result)