From 61530aeb34ab9527363adc91881499fa9ca8730f Mon Sep 17 00:00:00 2001 From: leandrotoledo Date: Mon, 20 Jul 2015 07:53:58 -0300 Subject: [PATCH] Adding logging decorator --- telegram/__init__.py | 2 +- telegram/audio.py | 2 +- telegram/base.py | 2 +- telegram/bot.py | 107 +++++++++++++++++++++++----------- telegram/contact.py | 2 +- telegram/document.py | 2 +- telegram/forcereply.py | 2 +- telegram/groupchat.py | 2 +- telegram/location.py | 2 +- telegram/message.py | 4 +- telegram/photosize.py | 2 +- telegram/replymarkup.py | 2 +- telegram/sticker.py | 2 +- telegram/update.py | 2 +- telegram/user.py | 2 +- telegram/userprofilephotos.py | 2 +- telegram/video.py | 2 +- 17 files changed, 91 insertions(+), 50 deletions(-) diff --git a/telegram/__init__.py b/telegram/__init__.py index 5f510f125..dac66684c 100644 --- a/telegram/__init__.py +++ b/telegram/__init__.py @@ -5,6 +5,7 @@ __author__ = 'leandrotoledodesouza@gmail.com' __version__ = '1.9' +from .base import TelegramObject from .user import User from .message import Message from .update import Update @@ -25,7 +26,6 @@ from .forcereply import ForceReply from .inputfile import InputFile from .error import TelegramError from .emoji import Emoji -from .base import TelegramObject from .bot import Bot __all__ = ['Bot', 'Emoji', 'TelegramError', 'InputFile', 'ReplyMarkup', diff --git a/telegram/audio.py b/telegram/audio.py index 926051d92..db2705cb5 100644 --- a/telegram/audio.py +++ b/telegram/audio.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -from .base import TelegramObject +from telegram import TelegramObject class Audio(TelegramObject): diff --git a/telegram/base.py b/telegram/base.py index cc7ac6d35..491a5e717 100644 --- a/telegram/base.py +++ b/telegram/base.py @@ -11,7 +11,7 @@ class TelegramObject(object): __metaclass__ = ABCMeta def __str__(self): - return self.to_data() + return str(self.to_data()) def __getitem__(self, item): return self.__dict__[item] diff --git a/telegram/bot.py b/telegram/bot.py index eec1c81db..9cd4be879 100644 --- a/telegram/bot.py +++ b/telegram/bot.py @@ -13,16 +13,25 @@ except ImportError: from urllib2 import urlopen, Request from urllib2 import HTTPError, URLError import functools +import logging from telegram import (User, Message, Update, UserProfilePhotos, TelegramError, - ReplyMarkup, InputFile) + ReplyMarkup, InputFile, TelegramObject) + +logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') -class Bot(object): +class Bot(TelegramObject): def __init__(self, token, - base_url=None): + base_url=None, + debug=True): + self.log = logging.getLogger(__name__) + if debug: + self.log.setLevel(logging.DEBUG) + else: + self.log.setLevel(logging.INFO) self.token = token @@ -45,39 +54,27 @@ class Bot(object): @property def name(self): - if self.username: - return '@%s' % self.username - if self.last_name: - return '%s %s' % (self.first_name, self.last_name) - return self.first_name + return '@%s' % self.username - def clearCredentials(self): - """Clear any credentials for this instance. - """ - self.__auth = False + def log(func): + logger = logging.getLogger(func.__module__) - def getMe(self): - """A simple method for testing your bot's auth token. - - Returns: - A telegram.User instance representing that bot if the - credentials are valid, None otherwise. - """ - url = '%s/getMe' % self.base_url - - json_data = self._requestUrl(url, 'GET') - data = self._parseAndCheckTelegram(json_data) - - return User.de_json(data) + @functools.wraps(func) + def decorator(self, *args, **kwargs): + logger.debug('Entering %s' % func.__name__) + result = func(self, *args, **kwargs) + logger.debug(result) + logger.debug('Exiting %s' % func.__name__) + return result + return decorator def message(func): """ Returns: A telegram.Message instance representing the message posted. """ - functools.wraps(func) - - def wrap(self, *args, **kwargs): + @functools.wraps(func) + def decorator(self, *args, **kwargs): url, data = func(self, *args, **kwargs) if kwargs.get('reply_to_message_id'): @@ -98,18 +95,41 @@ class Bot(object): return data return Message.de_json(data) - return wrap + return decorator def require_authentication(func): - functools.wraps(func) - - def wrap(self, *args, **kwargs): + @functools.wraps(func) + def decorator(self, *args, **kwargs): if not self.__auth: raise TelegramError({'message': "API must be authenticated."}) return func(self, *args, **kwargs) - return wrap + return decorator + + @log + @require_authentication + def clearCredentials(self): + """Clear any credentials for this instance. + """ + self.__auth = False + + @log + def getMe(self): + """A simple method for testing your bot's auth token. + + Returns: + A telegram.User instance representing that bot if the + credentials are valid, None otherwise. + """ + url = '%s/getMe' % self.base_url + + json_data = self._requestUrl(url, 'GET') + data = self._parseAndCheckTelegram(json_data) + + return User.de_json(data) + + @log @message @require_authentication def sendMessage(self, @@ -149,6 +169,7 @@ class Bot(object): return url, data + @log @message @require_authentication def forwardMessage(self, @@ -182,6 +203,7 @@ class Bot(object): return url, data + @log @message @require_authentication def sendPhoto(self, @@ -223,6 +245,7 @@ class Bot(object): return url, data + @log @message @require_authentication def sendAudio(self, @@ -260,6 +283,7 @@ class Bot(object): return url, data + @log @message @require_authentication def sendDocument(self, @@ -294,6 +318,7 @@ class Bot(object): return url, data + @log @message @require_authentication def sendSticker(self, @@ -328,6 +353,7 @@ class Bot(object): return url, data + @log @message @require_authentication def sendVideo(self, @@ -363,6 +389,7 @@ class Bot(object): return url, data + @log @message @require_authentication def sendLocation(self, @@ -399,6 +426,7 @@ class Bot(object): return url, data + @log @message @require_authentication def sendChatAction(self, @@ -430,6 +458,7 @@ class Bot(object): return url, data + @log @require_authentication def getUserProfilePhotos(self, user_id, @@ -465,6 +494,7 @@ class Bot(object): return UserProfilePhotos.de_json(data) + @log @require_authentication def getUpdates(self, offset=None, @@ -505,6 +535,7 @@ class Bot(object): return [Update.de_json(x) for x in data] + @log @require_authentication def setWebhook(self, webhook_url): @@ -531,6 +562,7 @@ class Bot(object): return True + @log def _requestUrl(self, url, method, @@ -581,6 +613,7 @@ class Bot(object): return 0 # if not a POST or GET request + @log def _parseAndCheckTelegram(self, json_data): """Try and parse the JSON returned from Telegram and return an empty @@ -604,3 +637,11 @@ class Bot(object): raise TelegramError({'message': 'JSON decoding'}) return data['result'] + + def to_data(self): + data = {'id': self.id, + 'username': self.username, + 'first_name': self.username} + if self.last_name: + data['last_name'] = self.last_name + return data diff --git a/telegram/contact.py b/telegram/contact.py index 5dc39c130..c8a365da0 100644 --- a/telegram/contact.py +++ b/telegram/contact.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -from .base import TelegramObject +from telegram import TelegramObject class Contact(TelegramObject): diff --git a/telegram/document.py b/telegram/document.py index 64a8decd3..9077a7152 100644 --- a/telegram/document.py +++ b/telegram/document.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -from .base import TelegramObject +from telegram import TelegramObject class Document(TelegramObject): diff --git a/telegram/forcereply.py b/telegram/forcereply.py index 8f2dcf78b..3501bea48 100644 --- a/telegram/forcereply.py +++ b/telegram/forcereply.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -from .base import TelegramObject +from telegram import TelegramObject class ForceReply(TelegramObject): diff --git a/telegram/groupchat.py b/telegram/groupchat.py index e60f67115..340854a90 100644 --- a/telegram/groupchat.py +++ b/telegram/groupchat.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -from .base import TelegramObject +from telegram import TelegramObject class GroupChat(TelegramObject): diff --git a/telegram/location.py b/telegram/location.py index 4e05b9e00..73a3f99eb 100644 --- a/telegram/location.py +++ b/telegram/location.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -from .base import TelegramObject +from telegram import TelegramObject class Location(TelegramObject): diff --git a/telegram/message.py b/telegram/message.py index 4f22275b0..d0ea9b196 100644 --- a/telegram/message.py +++ b/telegram/message.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -from .base import TelegramObject +from telegram import TelegramObject class Message(TelegramObject): @@ -181,7 +181,7 @@ class Message(TelegramObject): if self.document: data['document'] = self.document.to_data() if self.photo: - data['photo'] = self.photo.to_data() + data['photo'] = [p.to_data() for p in self.photo] if self.sticker: data['sticker'] = self.sticker.to_data() if self.video: diff --git a/telegram/photosize.py b/telegram/photosize.py index 82030926c..c0a458a15 100644 --- a/telegram/photosize.py +++ b/telegram/photosize.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -from .base import TelegramObject +from telegram import TelegramObject class PhotoSize(TelegramObject): diff --git a/telegram/replymarkup.py b/telegram/replymarkup.py index 7d4d998f6..edb664cac 100644 --- a/telegram/replymarkup.py +++ b/telegram/replymarkup.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -from .base import TelegramObject +from telegram import TelegramObject class ReplyMarkup(TelegramObject): diff --git a/telegram/sticker.py b/telegram/sticker.py index 46ef1af4c..fa02b322f 100644 --- a/telegram/sticker.py +++ b/telegram/sticker.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -from .base import TelegramObject +from telegram import TelegramObject class Sticker(TelegramObject): diff --git a/telegram/update.py b/telegram/update.py index 9030fafbf..072207bae 100644 --- a/telegram/update.py +++ b/telegram/update.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -from .base import TelegramObject +from telegram import TelegramObject class Update(TelegramObject): diff --git a/telegram/user.py b/telegram/user.py index d9dd67701..fd7098d31 100644 --- a/telegram/user.py +++ b/telegram/user.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -from .base import TelegramObject +from telegram import TelegramObject class User(TelegramObject): diff --git a/telegram/userprofilephotos.py b/telegram/userprofilephotos.py index 64395ff34..c6cb99ffe 100644 --- a/telegram/userprofilephotos.py +++ b/telegram/userprofilephotos.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -from .base import TelegramObject +from telegram import TelegramObject class UserProfilePhotos(TelegramObject): diff --git a/telegram/video.py b/telegram/video.py index e5fac4f6e..1ea192f56 100644 --- a/telegram/video.py +++ b/telegram/video.py @@ -1,7 +1,7 @@ #!/usr/bin/env python -from .base import TelegramObject +from telegram import TelegramObject class Video(TelegramObject):