X Tutup
Skip to content

Commit e1edeb7

Browse files
committed
Improve design of this class
1 parent a409fc5 commit e1edeb7

File tree

1 file changed

+16
-24
lines changed

1 file changed

+16
-24
lines changed

telegram/utils/request.py

Lines changed: 16 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -38,19 +38,18 @@ def _parse(json_data):
3838
dictionary if there is any error.
3939
4040
Args:
41-
json_data:
42-
JSON results from Telegram Bot API.
41+
url:
42+
urllib.urlopen object
4343
4444
Returns:
4545
A JSON parsed as Python dict with results.
4646
"""
4747
try:
4848
data = json.loads(json_data.decode())
49-
if not data['ok']:
50-
raise TelegramError(data['description'])
49+
50+
if not data.get('ok') and data.get('description'):
51+
return data['description']
5152
except ValueError:
52-
if '<title>403 Forbidden</title>' in json_data:
53-
raise TelegramError({'message': 'API must be authenticated'})
5453
raise TelegramError({'message': 'JSON decoding'})
5554

5655
return data['result']
@@ -61,14 +60,13 @@ def get(url):
6160
Args:
6261
url:
6362
The web location we want to retrieve.
63+
6464
Returns:
6565
A JSON object.
6666
"""
67-
try:
68-
result = urlopen(url).read()
69-
return _parse(result)
70-
except URLError as error:
71-
raise TelegramError(str(error))
67+
result = urlopen(url).read()
68+
69+
return _parse(result)
7270

7371

7472
def post(url,
@@ -79,30 +77,24 @@ def post(url,
7977
The web location we want to retrieve.
8078
data:
8179
A dict of (str, unicode) key/value pairs.
80+
8281
Returns:
8382
A JSON object.
8483
"""
8584
try:
8685
if InputFile.is_inputfile(data):
8786
data = InputFile(data)
88-
89-
request = Request(
90-
url,
91-
data=data.to_form(),
92-
headers=data.headers
93-
)
87+
request = Request(url, data=data.to_form(), headers=data.headers)
9488

9589
result = urlopen(request).read()
9690
else:
97-
result = urlopen(
98-
url,
99-
urlencode(data).encode()
100-
).read()
101-
102-
return _parse(result)
91+
result = urlopen(url, urlencode(data).encode()).read()
10392
except HTTPError as error:
104-
raise TelegramError(str(error))
93+
message = _parse(error.read())
94+
raise TelegramError(message)
10595
except URLError as error:
10696
raise TelegramError(str(error))
10797
except IOError as error:
10898
raise TelegramError(str(error))
99+
100+
return _parse(result)

0 commit comments

Comments
 (0)
X Tutup