X Tutup
Skip to content

Commit b20f5af

Browse files
committed
Improving the design of existing Telegram classes and adding docstrings
1 parent ce58f72 commit b20f5af

File tree

7 files changed

+242
-61
lines changed

7 files changed

+242
-61
lines changed

telegram/__init__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
# You should have received a copy of the GNU Lesser Public License
1717
# along with this program. If not, see [http://www.gnu.org/licenses/].
1818

19+
"""A library that provides a Python interface to the Telegram Bot API"""
1920

2021
__author__ = 'leandrotoledodesouza@gmail.com'
2122
__version__ = '2.7.1'

telegram/base.py

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,13 +16,14 @@
1616
# You should have received a copy of the GNU Lesser Public License
1717
# along with this program. If not, see [http://www.gnu.org/licenses/].
1818

19+
"""Base class for Telegram Objects"""
1920

2021
import json
2122
from abc import ABCMeta, abstractmethod
2223

2324

2425
class TelegramObject(object):
25-
"""Base class for most telegram object"""
26+
"""Base class for most telegram objects"""
2627

2728
__metaclass__ = ABCMeta
2829

@@ -34,11 +35,26 @@ def __getitem__(self, item):
3435

3536
@staticmethod
3637
def de_json(data):
38+
"""
39+
Args:
40+
data (str):
41+
42+
Returns:
43+
telegram.TelegramObject:
44+
"""
3745
raise NotImplementedError
3846

3947
def to_json(self):
48+
"""
49+
Returns:
50+
str:
51+
"""
4052
return json.dumps(self.to_dict())
4153

4254
@abstractmethod
4355
def to_dict(self):
56+
"""
57+
Returns:
58+
dict:
59+
"""
4460
return None

telegram/bot.py

Lines changed: 71 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
#!/usr/bin/env python
2+
# pylint: disable=E0611,E0213,E1102,C0103,E1101,W0613,R0913,R0904
23
#
34
# A library that provides a Python interface to the Telegram Bot API
45
# Copyright (C) 2015 Leandro Toledo de Souza <leandrotoeldodesouza@gmail.com>
@@ -16,6 +17,7 @@
1617
# You should have received a copy of the GNU Lesser Public License
1718
# along with this program. If not, see [http://www.gnu.org/licenses/].
1819

20+
"""This module contains a object that represents a Telegram Bot"""
1921

2022
import json
2123
try:
@@ -32,11 +34,27 @@
3234
from telegram import (User, Message, Update, UserProfilePhotos, TelegramError,
3335
ReplyMarkup, InputFile, TelegramObject, NullHandler)
3436

35-
h = NullHandler()
36-
logging.getLogger(__name__).addHandler(h)
37+
H = NullHandler()
38+
logging.getLogger(__name__).addHandler(H)
3739

3840

3941
class Bot(TelegramObject):
42+
"""This object represents a Telegram Bot.
43+
44+
Attributes:
45+
id (int):
46+
first_name (str):
47+
last_name (str):
48+
username (str):
49+
name (str):
50+
51+
Args:
52+
token (str):
53+
**kwargs: Arbitrary keyword arguments.
54+
55+
Keyword Args:
56+
base_url (Optional[str]):
57+
"""
4058

4159
def __init__(self,
4260
token,
@@ -50,11 +68,17 @@ def __init__(self,
5068

5169
self.bot = None
5270

53-
self.log = logging.getLogger(__name__)
71+
self.logger = logging.getLogger(__name__)
5472

5573
def info(func):
74+
"""
75+
bla
76+
"""
5677
@functools.wraps(func)
5778
def decorator(self, *args, **kwargs):
79+
"""
80+
bla
81+
"""
5882
if not self.bot:
5983
self.getMe()
6084

@@ -65,36 +89,48 @@ def decorator(self, *args, **kwargs):
6589
@property
6690
@info
6791
def id(self):
92+
"""int: """
6893
return self.bot.id
6994

7095
@property
7196
@info
7297
def first_name(self):
98+
"""str: """
7399
return self.bot.first_name
74100

75101
@property
76102
@info
77103
def last_name(self):
104+
"""str: """
78105
return self.bot.last_name
79106

80107
@property
81108
@info
82109
def username(self):
110+
"""str: """
83111
return self.bot.username
84112

85113
@property
86114
def name(self):
115+
"""str: """
87116
return '@%s' % self.username
88117

89118
def log(func):
119+
"""
120+
Returns:
121+
A telegram.Message instance representing the message posted.
122+
"""
90123
logger = logging.getLogger(func.__module__)
91124

92125
@functools.wraps(func)
93126
def decorator(self, *args, **kwargs):
94-
logger.debug('Entering: %s' % func.__name__)
127+
"""
128+
decorator
129+
"""
130+
logger.debug('Entering: %s', func.__name__)
95131
result = func(self, *args, **kwargs)
96132
logger.debug(result)
97-
logger.debug('Exiting: %s' % func.__name__)
133+
logger.debug('Exiting: %s', func.__name__)
98134
return result
99135
return decorator
100136

@@ -105,6 +141,9 @@ def message(func):
105141
"""
106142
@functools.wraps(func)
107143
def decorator(self, *args, **kwargs):
144+
"""
145+
decorator
146+
"""
108147
url, data = func(self, *args, **kwargs)
109148

110149
if kwargs.get('reply_to_message_id'):
@@ -118,8 +157,8 @@ def decorator(self, *args, **kwargs):
118157
else:
119158
data['reply_markup'] = reply_markup
120159

121-
json_data = self._requestUrl(url, 'POST', data=data)
122-
data = self._parseAndCheckTelegram(json_data)
160+
json_data = Bot._requestUrl(url, 'POST', data=data)
161+
data = Bot._parseAndCheckTelegram(json_data)
123162

124163
if data is True:
125164
return data
@@ -150,8 +189,7 @@ def sendMessage(self,
150189
chat_id,
151190
text,
152191
disable_web_page_preview=None,
153-
reply_to_message_id=None,
154-
reply_markup=None):
192+
**kwargs):
155193
"""Use this method to send text messages.
156194
157195
Args:
@@ -222,8 +260,7 @@ def sendPhoto(self,
222260
chat_id,
223261
photo,
224262
caption=None,
225-
reply_to_message_id=None,
226-
reply_markup=None):
263+
**kwargs):
227264
"""Use this method to send photos.
228265
229266
Args:
@@ -265,8 +302,7 @@ def sendAudio(self,
265302
duration=None,
266303
performer=None,
267304
title=None,
268-
reply_to_message_id=None,
269-
reply_markup=None):
305+
**kwargs):
270306
"""Use this method to send audio files, if you want Telegram clients to
271307
display them in the music player. Your audio must be in an .mp3 format.
272308
On success, the sent Message is returned. Bots can currently send audio
@@ -321,8 +357,7 @@ def sendAudio(self,
321357
def sendDocument(self,
322358
chat_id,
323359
document,
324-
reply_to_message_id=None,
325-
reply_markup=None):
360+
**kwargs):
326361
"""Use this method to send general files.
327362
328363
Args:
@@ -355,8 +390,7 @@ def sendDocument(self,
355390
def sendSticker(self,
356391
chat_id,
357392
sticker,
358-
reply_to_message_id=None,
359-
reply_markup=None):
393+
**kwargs):
360394
"""Use this method to send .webp stickers.
361395
362396
Args:
@@ -391,8 +425,7 @@ def sendVideo(self,
391425
video,
392426
duration=None,
393427
caption=None,
394-
reply_to_message_id=None,
395-
reply_markup=None):
428+
**kwargs):
396429
"""Use this method to send video files, Telegram clients support mp4
397430
videos (other formats may be sent as telegram.Document).
398431
@@ -437,8 +470,7 @@ def sendVoice(self,
437470
chat_id,
438471
voice,
439472
duration=None,
440-
reply_to_message_id=None,
441-
reply_markup=None):
473+
**kwargs):
442474
"""Use this method to send audio files, if you want Telegram clients to
443475
display the file as a playable voice message. For this to work, your
444476
audio must be in an .ogg file encoded with OPUS (other formats may be
@@ -482,8 +514,7 @@ def sendLocation(self,
482514
chat_id,
483515
latitude,
484516
longitude,
485-
reply_to_message_id=None,
486-
reply_markup=None):
517+
**kwargs):
487518
"""Use this method to send point on the map.
488519
489520
Args:
@@ -617,10 +648,10 @@ def getUpdates(self,
617648
data = self._parseAndCheckTelegram(json_data)
618649

619650
if data:
620-
self.log.info(
621-
'Getting updates: %s' % [u['update_id'] for u in data])
651+
self.logger.info(
652+
'Getting updates: %s', [u['update_id'] for u in data])
622653
else:
623-
self.log.info('No new updates found.')
654+
self.logger.info('No new updates found.')
624655

625656
return [Update.de_json(x) for x in data]
626657

@@ -650,8 +681,8 @@ def setWebhook(self,
650681

651682
return True
652683

653-
def _requestUrl(self,
654-
url,
684+
@staticmethod
685+
def _requestUrl(url,
655686
method,
656687
data=None):
657688
"""Request an URL.
@@ -688,21 +719,21 @@ def _requestUrl(self,
688719
url,
689720
urlencode(data).encode()
690721
).read()
691-
except IOError as e:
692-
raise TelegramError(str(e))
693722
except HTTPError as e:
694723
raise TelegramError(str(e))
695724
except URLError as e:
696725
raise TelegramError(str(e))
726+
except IOError as e:
727+
raise TelegramError(str(e))
697728

698729
if method == 'GET':
699730
try:
700731
return urlopen(url).read()
701732
except URLError as e:
702733
raise TelegramError(str(e))
703734

704-
def _parseAndCheckTelegram(self,
705-
json_data):
735+
@staticmethod
736+
def _parseAndCheckTelegram(json_data):
706737
"""Try and parse the JSON returned from Telegram and return an empty
707738
dictionary if there is any error.
708739
@@ -725,7 +756,15 @@ def _parseAndCheckTelegram(self,
725756

726757
return data['result']
727758

759+
@staticmethod
760+
def de_json(data):
761+
pass
762+
728763
def to_dict(self):
764+
"""
765+
Returns:
766+
dict:
767+
"""
729768
data = {'id': self.id,
730769
'username': self.username,
731770
'first_name': self.username}

0 commit comments

Comments
 (0)
X Tutup