Skip to content

Commit 804db52

Browse files
committed
Adding TelegramError for handling
1 parent 0c7f649 commit 804db52

3 files changed

Lines changed: 58 additions & 7 deletions

File tree

telegram/__init__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,4 +25,5 @@
2525
# from replykeyboardmarkup import ReplyKeyboardMarkup
2626
# from replykeyboardhide import ReplyKeyboardHide
2727
# from forcereply import ForceReply
28+
from error import TelegramError
2829
from bot import Bot

telegram/bot.py

Lines changed: 47 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
import json
77
import requests
88

9-
from telegram import (User, Message, Update, UserProfilePhotos)
9+
from telegram import (User, Message, Update, UserProfilePhotos, TelegramError)
1010

1111

1212
class Bot(object):
@@ -55,6 +55,7 @@ def sendMessage(self,
5555
Additional interface options. A JSON-serialized object for a custom
5656
reply keyboard, instructions to hide keyboard or to force a reply
5757
from the user. [Optional]
58+
5859
Returns:
5960
A telegram.Message instance representing the message posted.
6061
"""
@@ -89,6 +90,7 @@ def forwardMessage(self,
8990
— User or GroupChat id.
9091
message_id:
9192
Unique message identifier.
93+
9294
Returns:
9395
A telegram.Message instance representing the message forwarded.
9496
"""
@@ -132,6 +134,7 @@ def sendPhoto(self,
132134
Additional interface options. A JSON-serialized object for a custom
133135
reply keyboard, instructions to hide keyboard or to force a reply
134136
from the user. [Optional]
137+
135138
Returns:
136139
A telegram.Message instance representing the message posted.
137140
"""
@@ -176,6 +179,7 @@ def sendAudio(self,
176179
Additional interface options. A JSON-serialized object for a
177180
custom reply keyboard, instructions to hide keyboard or to force a
178181
reply from the user. [Optional]
182+
179183
Returns:
180184
A telegram.Message instance representing the message posted.
181185
"""
@@ -215,6 +219,7 @@ def sendDocument(self,
215219
Additional interface options. A JSON-serialized object for a
216220
custom reply keyboard, instructions to hide keyboard or to force a
217221
reply from the user. [Optional]
222+
218223
Returns:
219224
A telegram.Message instance representing the message posted.
220225
"""
@@ -254,6 +259,7 @@ def sendSticker(self,
254259
Additional interface options. A JSON-serialized object for a
255260
custom reply keyboard, instructions to hide keyboard or to force a
256261
reply from the user. [Optional]
262+
257263
Returns:
258264
A telegram.Message instance representing the message posted.
259265
"""
@@ -294,6 +300,7 @@ def sendVideo(self,
294300
Additional interface options. A JSON-serialized object for a
295301
custom reply keyboard, instructions to hide keyboard or to force a
296302
reply from the user. [Optional]
303+
297304
Returns:
298305
A telegram.Message instance representing the message posted.
299306
"""
@@ -334,6 +341,7 @@ def sendLocation(self,
334341
Additional interface options. A JSON-serialized object for a
335342
custom reply keyboard, instructions to hide keyboard or to force a
336343
reply from the user. [Optional]
344+
337345
Returns:
338346
A telegram.Message instance representing the message posted.
339347
"""
@@ -374,6 +382,7 @@ def sendChatAction(self,
374382
- ChatAction.UPLOAD_AUDIO or upload_audio for audio files,
375383
- ChatAction.UPLOAD_DOCUMENT for general files,
376384
- ChatAction.FIND_LOCATION for location data.
385+
377386
Returns:
378387
?
379388
"""
@@ -400,6 +409,7 @@ def getUserProfilePhotos(self,
400409
limit:
401410
Limits the number of photos to be retrieved. Values between 1—100
402411
are accepted. Defaults to 100. [Optional]
412+
403413
Returns:
404414
Returns a telegram.UserProfilePhotos object.
405415
"""
@@ -437,6 +447,7 @@ def getUpdates(self,
437447
timeout:
438448
Timeout in seconds for long polling. Defaults to 0, i.e. usual
439449
short polling.
450+
440451
Returns:
441452
A list of telegram.Update objects are returned.
442453
"""
@@ -472,6 +483,7 @@ def _requestUrl(self,
472483
Either POST or GET.
473484
data:
474485
A dict of (str, unicode) key/value pairs.
486+
475487
Returns:
476488
A JSON object.
477489
"""
@@ -487,7 +499,7 @@ def _requestUrl(self,
487499
files={'photo': photo}
488500
)
489501
except requests.RequestException as e:
490-
pass
502+
raise TelegramError(str(e))
491503
if 'audio' in data and isinstance(data['audio'], file):
492504
try:
493505
audio = data.pop('audio')
@@ -498,7 +510,7 @@ def _requestUrl(self,
498510
files={'audio': audio}
499511
)
500512
except requests.RequestException as e:
501-
pass
513+
raise TelegramError(str(e))
502514
if 'document' in data and isinstance(data['document'], file):
503515
try:
504516
document = data.pop('document')
@@ -509,28 +521,56 @@ def _requestUrl(self,
509521
files={'document': document}
510522
)
511523
except requests.RequestException as e:
512-
pass
524+
raise TelegramError(str(e))
513525
else:
514526
try:
515527
return requests.post(
516528
url,
517529
data=data
518530
)
519531
except requests.RequestException as e:
520-
pass
532+
raise TelegramError(str(e))
521533
if method == 'GET':
522534
try:
523535
return requests.get(url)
524536
except requests.RequestException as e:
525-
pass # raise TelegramError(str(e))
537+
raise TelegramError(str(e))
526538
return 0
527539

528540
def _parseAndCheckTelegram(self,
529541
json_data):
542+
"""Try and parse the JSON returned from Telegram and return an empty
543+
dictionary if there is any error.
544+
545+
Args:
546+
json_data:
547+
JSON results from Telegram Bot API.
548+
549+
Returns:
550+
A JSON parsed as Python dict with results.
551+
"""
530552

531553
try:
532554
data = json.loads(json_data)
555+
self._checkForTelegramError(data)
533556
except ValueError:
534-
pass
557+
if '<title>403 Forbidden</title>' in json_data:
558+
raise TelegramError({'message': 'API must be authenticated'})
559+
raise TelegramError({'message': 'JSON decoding'})
535560

536561
return data['result']
562+
563+
def _checkForTelegramError(self,
564+
data):
565+
"""Raises a TelegramError if Telegram returns an error message.
566+
567+
Args:
568+
data:
569+
A Python dict created from the Telegram JSON response.
570+
571+
Raises:
572+
TelegramError wrapping the Telegram error message if one exists.
573+
"""
574+
575+
if not data['ok']:
576+
raise TelegramError(data)

telegram/error.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
#!/usr/bin/env python
2+
3+
4+
class TelegramError(Exception):
5+
"""Base class for Telegram errors."""
6+
7+
@property
8+
def message(self):
9+
'''Returns the first argument used to construct this error.'''
10+
return self.args[0]

0 commit comments

Comments
 (0)