forked from jordiprats/micropython-utelegram
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utelegram.py
79 lines (65 loc) · 2.38 KB
/
utelegram.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
import time
import gc
import ujson
import urequests
class ubot:
def __init__(self, token):
self.url = 'https://api.telegram.org/bot' + token
self.commands = {}
self.default_handler = None
self.message_offset = 0
self.sleep_btw_updates = 3
messages = self.read_messages()
if messages:
for message in messages:
if message['update_id'] > self.message_offset:
self.message_offset = message['update_id']
def send(self, chat_id, text):
data = {'chat_id': chat_id, 'text': text}
try:
headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
response = urequests.post(self.url + '/sendMessage', json=data, headers=headers)
return True
except:
return False
def read_messages(self):
result = []
self.query_updates = {
'offset': self.message_offset,
'limit': 1,
'timeout': 30,
'allowed_updates': ['message']}
try:
update_messages = urequests.post(self.url + '/getUpdates', json=self.query_updates).json()
if 'result' in update_messages:
for item in update_messages['result']:
if 'text' in item['message']:
result.append(item)
return result
except:
return None
def listen(self):
while True:
self.read_once()
time.sleep(self.sleep_btw_updates)
gc.collect()
def read_once(self):
messages = self.read_messages()
if messages:
for message in messages:
if message['update_id'] > self.message_offset:
self.message_handler(message)
self.message_offset = message['update_id']
def register(self, command, handler):
self.commands[command] = handler
def set_default_handler(self, handler):
self.default_handler = handler
def set_sleep_btw_updates(self, sleep_time):
self.sleep_btw_updates = sleep_time
def message_handler(self, message):
parts = message['message']['text'].split(' ')
if parts[0] in self.commands:
self.commands[parts[0]](message)
else:
if self.default_handler:
self.default_handler(message)