-
Notifications
You must be signed in to change notification settings - Fork 0
/
handle_urls.py
executable file
·60 lines (49 loc) · 1.81 KB
/
handle_urls.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
import urllib
import json
import requests
import constants
class MessageException(Exception):
"""Just to specify a kind of Exception"""
pass
class HandleUrls:
def get_url(self, url):
"""get response content of given url"""
response = requests.get(url)
content = response.content.decode("utf8")
return content
def get_json_from_url(self, url):
"""get json content of the given url"""
content = self.get_url(url)
payload = json.loads(content)
return payload
def get_updates(self, offset=None):
"""request new information from API"""
url = constants.URL_TELEGRAM + "getUpdates?timeout=100"
if offset:
url += "&offset={}".format(offset)
payload = self.get_json_from_url(url)
return payload
def send_message(self, text, chat_id, reply_markup=None):
"""send message to the user"""
text = urllib.parse.quote_plus(text)
url = constants.URL_TELEGRAM + ("sendMessage?text={}&chat_id={}&parse_mode=Markdown"
.format(text, chat_id))
if reply_markup:
url += "&reply_markup={}".format(reply_markup)
self.get_url(url)
def get_last_update_id(self, updates):
"""get the last update"""
update_ids = []
for update in updates["result"]:
update_ids.append(int(update["update_id"]))
return max(update_ids)
def get_message(self, update):
"""return the message catched by update"""
if 'message' in update:
message = update['message']
elif 'edited_message' in update:
message = update['edited_message']
else:
print('Can\'t process! {}'.format(update))
raise MessageException('Not recognizable message')
return message