PEP8, lint and TelegramError class refactor

This commit is contained in:
Leandro Toledo 2015-09-10 20:08:24 -03:00
parent 354bfcad79
commit a7ac4193fe
4 changed files with 25 additions and 21 deletions

View file

@ -139,7 +139,7 @@ class Bot(TelegramObject):
url, data = func(self, *args, **kwargs)
if not data.get('chat_id'):
raise TelegramError('Invalid chat_id.')
raise TelegramError('Invalid chat_id')
if kwargs.get('reply_to_message_id'):
reply_to_message_id = kwargs.get('reply_to_message_id')

View file

@ -18,6 +18,8 @@
"""This module contains a object that represents a Telegram Error"""
import re
class TelegramError(Exception):
"""This object represents a Telegram Error."""
@ -29,7 +31,11 @@ class TelegramError(Exception):
"""
super(TelegramError, self).__init__()
self.message = message.split(':')[-1].strip().capitalize()
api_error = re.match(r'^Error: (?P<message>.*)', message)
if api_error:
self.message = api_error.group('message').capitalize()
else:
self.message = message
def __str__(self):
return '%s' % (self.message)

View file

@ -164,7 +164,7 @@ class InputFile(object):
if image:
return 'image/%s' % image
raise TelegramError({'message': 'Could not parse file content'})
raise TelegramError('Could not parse file content')
@staticmethod
def is_inputfile(data):

View file

@ -1,5 +1,5 @@
#!/usr/bin/env python
# pylint: disable=no-name-in-module
# pylint: disable=no-name-in-module,unused-import
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015 Leandro Toledo de Souza <leandrotoeldodesouza@gmail.com>
@ -44,13 +44,10 @@ def _parse(json_data):
Returns:
A JSON parsed as Python dict with results.
"""
try:
data = json.loads(json_data.decode())
if not data.get('ok') and data.get('description'):
return data['description']
except ValueError:
raise TelegramError({'message': 'JSON decoding'})
return data['result']
@ -84,20 +81,21 @@ def post(url,
try:
if InputFile.is_inputfile(data):
data = InputFile(data)
request = Request(url, data=data.to_form(),
request = Request(url,
data=data.to_form(),
headers=data.headers)
else:
data = json.dumps(data)
request = Request(url, data=data.encode(),
request = Request(url,
data=data.encode(),
headers={'Content-Type': 'application/json'})
result = urlopen(request).read()
except HTTPError as error:
if error.getcode() == 403:
raise TelegramError('Unauthorized')
message = _parse(error.read())
raise TelegramError(message)
except URLError as error:
raise TelegramError(str(error))
except IOError as error:
raise TelegramError(str(error))
return _parse(result)