Compare commits

...

56 Commits

Author SHA1 Message Date
Leandro Toledo 16349ac69a Releasing v2.9.2 2015-11-11 11:31:20 -02:00
Leandro Toledo 235dcd2ad2 Merge branch 'master' of https://github.com/leandrotoledo/python-telegram-bot 2015-11-11 11:25:05 -02:00
Leandro Toledo ed92d1c254 Adds requirements.txt to MANIFEST 2015-11-11 11:24:49 -02:00
Jannes Höke 0b4c23f50e improve error handling on timeouts 2015-11-11 14:06:10 +01:00
leandrotoledo 206802cf4d Minor fix on docs 2015-11-10 20:33:14 -02:00
leandrotoledo 5eb4f8e5cd Minor pep8 fix 2015-11-10 20:31:51 -02:00
Jannes Höke 93afd3eabe remove check for network_delay 2015-11-10 23:12:20 +01:00
Jannes Höke 61dac76bee don't send network_delay to telegram servers 2015-11-10 22:40:19 +01:00
Jannes Höke 245f5abc45 further improved formatting 2015-11-10 21:32:54 +01:00
Jannes Höke 0f8f6584ce Fix for issue #81 2015-11-10 20:36:26 +01:00
Jannes Höke dd498ded00 Update to version 2.9.1 2015-11-10 20:22:58 +01:00
Jannes Höke 5d2999818b Update to version 2.9.1 2015-11-10 20:19:12 +01:00
Jannes Höke eb1f197ff4 2.9.1 release and generally improved formatting 2015-11-10 20:10:44 +01:00
Jannes Höke 4bc03ed56a Add parameter network_delay for slow connections and increase default to 2 seconds 2015-11-10 19:47:21 +01:00
Leandro Toledo 9191d333ca Adds future as requirement 2015-11-10 12:27:18 -02:00
Leandro Toledo c6533a2d69 Releasing v2.9 2015-11-10 12:21:04 -02:00
Leandro Toledo 6c13762c93 Fixes PEP8 and Lint minor issues 2015-11-10 12:10:50 -02:00
Leandro Toledo 06c09b96cf Fixes travis to support future module 2015-11-10 12:04:21 -02:00
Leandro Toledo 8a5ec3b2a1 Merge pull request #92 from jh0ker/emoticons
Decode Emoji byte strings into unicode strings if using Python 3 (Alternative)
2015-11-10 11:58:57 -02:00
Leandro Toledo 21c26aed2f Merge pull request #96 from leandrotoledo/revert-85-master
Revert 1879cff82d
2015-11-10 11:55:50 -02:00
Leandro Toledo 5fe1481ae9 Revert 1879cff82d 2015-11-10 11:55:42 -02:00
Leandro Toledo 1879cff82d Merge pull request #85 from jh0ker/master
Decode Emoji byte strings into unicode strings if using Python 3
2015-11-10 11:55:19 -02:00
Jannes Höke cd5e805692 added documentation 2015-11-10 05:16:16 +01:00
Jannes Höke 90a77ab7a1 Merge pull request #87 from franciscod/patch-1
Remove `.encode('utf-8')` from echobot
2015-11-10 04:58:21 +01:00
Jannes Höke 3928e27cf4 Merge pull request #90 from rahiel/master
raise exception if telegram times out on long-polling
2015-11-10 04:56:18 +01:00
Leandro Toledo 45b1124553 Merge pull request #95 from rahiel/readme
fix LGPLv3 badge
2015-11-09 16:53:47 -02:00
Rahiel Kasim 252b43dcb7 fix LGPLv3 badge 2015-11-09 19:06:30 +01:00
Leandro Toledo d3d5c1e907 Merge pull request #91 from jh0ker/useroptional
Make user_from optional to work with channels channels
2015-11-04 09:52:00 -02:00
Jannes Höke cbf66d411d add jh0ker to AUTHORS.rst 2015-11-03 14:47:26 +01:00
Jannes Höke 0e5b48f3b4 Add tests for Emoji class, since it now contains actual code 2015-11-03 14:47:13 +01:00
Jannes Höke df7cfdc8d0 create file requirements.txt and add 'future' 2015-11-03 14:42:16 +01:00
Jannes Höke 89015e5ecc fix for sending into a channel 2015-11-03 13:46:23 +01:00
Jannes Höke 025d4c9a75 fix emojis for python3 2015-11-03 12:24:44 +01:00
Jannes Höke d3bea4c3b4 make user_from optional, because of channels 2015-11-03 10:28:06 +01:00
Jannes Höke a6c12adda2 make user_from optional, because of channels 2015-11-03 10:20:45 +01:00
Rahiel Kasim dcb9129809 raise exception if telegram times out on long-polling 2015-11-02 20:30:37 +01:00
Francisco Demartino bd1f171f51 Remove .encode('utf-8') from echobot
This was making the bot throw TypeError on py3.

Closes #86
2015-10-23 16:48:26 -03:00
Jannes Höke 54efb034a4 add jh0ker to AUTHORS.rst 2015-10-23 01:18:05 +02:00
Jannes Höke fe94f146bb Add tests for Emoji class, since it now contains actual code 2015-10-23 01:16:10 +02:00
Jannes Höke 22b492762b Decode Emoji byte strings into unicode strings if using Python 3 (missed something) 2015-10-23 00:32:10 +02:00
Jannes Höke fea0c5cc2b Decode Emoji byte strings into unicode strings if using Python 3 2015-10-23 00:29:26 +02:00
Leandro Toledo 688d6af541 Releasing v2.8.7 2015-10-08 11:31:48 -03:00
Leandro Toledo bcbd32cdd3 Merge branch 'master' of https://github.com/leandrotoledo/python-telegram-bot 2015-10-08 11:30:16 -03:00
Leandro Toledo 3fa8b97ed2 Type as optional for GroupChat 2015-10-08 11:30:02 -03:00
Leandro Toledo 7cd4e2e205 Update README.rst 2015-10-08 10:40:27 -03:00
Leandro Toledo f2b0cb46a2 Releasing v2.8.6 2015-10-08 10:23:12 -03:00
Leandro Toledo cf5d184766 Add type to User and GroupChat classes 2015-10-08 10:19:05 -03:00
Leandro Toledo 5738dc553f Releasing v2.8.5 2015-09-24 09:29:23 -03:00
Leandro Toledo 386accab80 Merge pull request #74 from leandrotoledo/http_bad_gateway_as_except
Handles HTTP Bad Gateway error (503) on request module #63
2015-09-24 09:26:19 -03:00
Leandro Toledo e7686db759 Merge pull request #73 from leandrotoledo/stop_casting_unicode_fields
Fixes regression on Audio and Document models for unicode fields #65
2015-09-24 09:26:10 -03:00
Leandro Toledo 6c9490f2c6 Handles HTTP Bad Gateway error (503) on request module #63 2015-09-24 09:17:50 -03:00
Leandro Toledo 855ab19dea Fixes regression on Audio and Document models for unicode fields #65 2015-09-24 09:10:33 -03:00
Leandro Toledo 797a3e6ea4 Update README.rst 2015-09-22 09:41:31 -03:00
Leandro Toledo bbd443d397 Merge pull request #71 from zeehio/patch-1
[doc] fix "Telegram sticker" -> "Telegram user"
2015-09-22 09:39:19 -03:00
Sergio Oller 4e1597c614 [doc] fix "Telegram user" -> "telegram sticker" 2015-09-22 11:52:10 +02:00
Leandro Toledo 75e338d5df Releasing v2.8.4 2015-09-20 12:52:40 -03:00
23 changed files with 1188 additions and 981 deletions
+1
View File
@@ -8,6 +8,7 @@ python:
- "pypy3"
install:
- pip install coveralls
- pip install -r requirements.txt
script:
nosetests --with-coverage --cover-package telegram/
after_success:
+1
View File
@@ -13,6 +13,7 @@ The following wonderful people contributed directly or indirectly to this projec
- `ErgoZ Riftbit Vaper <https://github.com/ergoz>`_
- `franciscod <https://github.com/franciscod>`_
- `JASON0916 <https://github.com/JASON0916>`_
- `jh0ker <https://github.com/jh0ker>`_
- `JRoot3D <https://github.com/JRoot3D>`_
- `macrojames <https://github.com/macrojames>`_
- `njittam <https://github.com/njittam>`_
+203 -108
View File
@@ -1,171 +1,266 @@
2015-09-10
Released 2.8.3
Moved Bot._requestURL to its own class (telegram.utils.request)
Much better, such wow, Telegram Objects tests
Add consistency for str properties on Telegram Objects
Better design to test if chat_id is invalid
Add ability to set custom filename on Bot.sendDocument(..,filename='')
Fix Sticker as InputFile
Send JSON requests over urlencoded post data
Markdown support for Bot.sendMessage(..., parse_mode=ParseMode.MARKDOWN)
Refactor of TelegramError class (no more handling IOError or URLError)
**2015-11-11**
*Released 2.9.2*
- Error handling on request timeouts has been improved
**2015-11-10**
*Released 2.9.1*
- Add parameter ``network_delay`` to Bot.getUpdates for slow connections
**2015-11-10**
*Released 2.9*
- Emoji class now uses ``bytes_to_native_str`` from ``future`` 3rd party lib
- Make ``user_from`` optional to work with channels
- Raise exception if Telegram times out on long-polling
*Special thanks to @jh0ker for all hard work*
2015-09-05
Released 2.8.2
Fix regression on Telegram ReplyMarkup
Add certificate to is_inputfile method
**2015-10-08**
*Released 2.8.7*
- Type as optional for ``GroupChat`` class
2015-09-05
Released 2.8.1
Fix regression on Telegram objects with thumb properties
**2015-10-08**
*Released 2.8.6*
- Adds type to ``User`` and ``GroupChat`` classes (pre-release Telegram feature)
2015-09-04
Released 2.8
TelegramError when chat_id is empty for send* methods
setWebhook now supports sending self-signed certificate
Huge redesign of existing Telegram classes
Added support for PyPy
Added docstring for existing classes
**2015-09-24**
*Released 2.8.5*
- Handles HTTP Bad Gateway (503) errors on request
- Fixes regression on ``Audio`` and ``Document`` for unicode fields
2015-08-19
Released 2.7.1
Fixed JSON serialization for message
**2015-09-20**
*Released 2.8.4*
- ``getFile`` and ``File.download`` is now fully supported
2015-08-17
Released 2.7
Added support for Voice object and sendVoice method
Due backward compatibility performer or/and title will be required for sendAudio
Fixed JSON serialization when forwarded message
**2015-09-10**
*Released 2.8.3*
- Moved ``Bot._requestURL`` to its own class (``telegram.utils.request``)
- Much better, such wow, Telegram Objects tests
- Add consistency for ``str`` properties on Telegram Objects
- Better design to test if ``chat_id`` is invalid
- Add ability to set custom filename on ``Bot.sendDocument(..,filename='')``
- Fix Sticker as ``InputFile``
- Send JSON requests over urlencoded post data
- Markdown support for ``Bot.sendMessage(..., parse_mode=ParseMode.MARKDOWN)``
- Refactor of ``TelegramError`` class (no more handling ``IOError`` or ``URLError``)
2015-08-15
Released 2.6.1
Fixed parsing image header issue on < Python 2.7.3
**2015-09-05**
*Released 2.8.2*
- Fix regression on Telegram ReplyMarkup
- Add certificate to ``is_inputfile`` method
2015-08-14
Released 2.6.0
Depreciation of require_authentication and clearCredentials methods
Giving AUTHORS the proper credits for their contribution for this project
Message.date and Message.forward_date are now datetime objects
**2015-09-05**
*Released 2.8.1*
- Fix regression on Telegram objects with thumb properties
2015-08-12
Released 2.5.3
telegram.Bot now supports to be unpickled
**2015-09-04**
*Released 2.8*
- TelegramError when ``chat_id`` is empty for send* methods
- ``setWebhook`` now supports sending self-signed certificate
- Huge redesign of existing Telegram classes
- Added support for PyPy
- Added docstring for existing classes
2015-08-11
Released 2.5.2
New changes from Telegram Bot API have been applied
telegram.Bot now supports to be pickled
Return empty str instead None when message.text is empty
**2015-08-19**
*Released 2.7.1*
- Fixed JSON serialization for ``message``
2015-08-10
Released 2.5.1
Moved from GPLv2 to LGPLv3
**2015-08-17**
*Released 2.7*
- Added support for ``Voice`` object and ``sendVoice`` method
- Due backward compatibility performer or/and title will be required for ``sendAudio``
- Fixed JSON serialization when forwarded message
2015-08-09
Released 2.5
Fixes logging calls in API
**2015-08-15**
*Released 2.6.1*
- Fixed parsing image header issue on < Python 2.7.3
2015-08-08
Released 2.4
Fixes Emoji class for Python 3
PEP8 improvements
**2015-08-14**
*Released 2.6.0*
- Depreciation of ``require_authentication`` and ``clearCredentials`` methods
- Giving ``AUTHORS`` the proper credits for their contribution for this project
- ``Message.date`` and ``Message.forward_date`` are now ``datetime`` objects
2015-08-08
Released 2.3
Fixes ForceReply class
Remove logging.basicConfig from library
**2015-08-12**
*Released 2.5.3*
- ``telegram.Bot`` now supports to be unpickled
2015-07-25
Released 2.2
Allows debug=True when initializing telegram.Bot
**2015-08-11**
*Released 2.5.2*
- New changes from Telegram Bot API have been applied
- ``telegram.Bot`` now supports to be pickled
- Return empty ``str`` instead ``None`` when ``message.text`` is empty
2015-07-20
Released 2.1
Fix to_dict for Document and Video
**2015-08-10**
*Released 2.5.1*
- Moved from GPLv2 to LGPLv3
2015-07-19
**2015-08-09**
Released 2.0
Fixes bugs
Improves __str__ over to_json()
Creates abstractclass TelegramObject
*Released 2.5*
- Fixes logging calls in API
2015-07-15
**2015-08-08**
Released 1.9
Python 3 officially supported
PEP8 improvements
*Released 2.4*
- Fixes ``Emoji`` class for Python 3
- ``PEP8`` improvements
2015-07-12
**2015-08-08**
Released 1.8
Fixes crash when replying an unicode text message (special thanks to JRoot3D)
*Released 2.3*
- Fixes ``ForceReply`` class
- Remove ``logging.basicConfig`` from library
2015-07-11
**2015-07-25**
Released 1.7
Fixes crash when username is not defined on chat (special thanks to JRoot3D)
*Released 2.2*
- Allows ``debug=True`` when initializing ``telegram.Bot``
2015-07-10
**2015-07-20**
Released 1.6
Improvements for GAE support
*Released 2.1*
- Fix ``to_dict`` for ``Document`` and ``Video``
2015-07-10
**2015-07-19**
Released 1.5
Fixes randomly unicode issues when using InputFile
*Released 2.0*
- Fixes bugs
- Improves ``__str__`` over ``to_json()``
- Creates abstract class ``TelegramObject``
2015-07-10
**2015-07-15**
Released 1.4
requests lib is no longer required
Google App Engine (GAE) is supported
*Released 1.9*
- Python 3 officially supported
- ``PEP8`` improvements
2015-07-10
**2015-07-12**
Released 1.3
Added support to setWebhook (special thanks to macrojames)
*Released 1.8*
- Fixes crash when replying an unicode text message (special thanks to JRoot3D)
2015-07-09
**2015-07-11**
Released 1.2
CustomKeyboard classes now available
Emojis available
PEP8 improvements
*Released 1.7*
- Fixes crash when ``username`` is not defined on ``chat`` (special thanks to JRoot3D)
2015-07-08
**2015-07-10**
Released 1.1
PyPi package now available
*Released 1.6*
- Improvements for GAE support
2015-07-08
**2015-07-10**
Released 1.0
Initial checkin of python-telegram-bot
*Released 1.5*
- Fixes randomly unicode issues when using ``InputFile``
**2015-07-10**
*Released 1.4*
- ``requests`` lib is no longer required
- Google App Engine (GAE) is supported
**2015-07-10**
*Released 1.3*
- Added support to ``setWebhook`` (special thanks to macrojames)
**2015-07-09**
*Released 1.2*
- ``CustomKeyboard`` classes now available
- Emojis available
- ``PEP8`` improvements
**2015-07-08**
*Released 1.1*
- PyPi package now available
**2015-07-08**
*Released 1.0*
- Initial checkin of python-telegram-bot
+1 -1
View File
@@ -1 +1 @@
include LICENSE LICENSE.lesser Makefile
include LICENSE LICENSE.lesser Makefile requirements.txt
+4 -1
View File
@@ -1,4 +1,4 @@
.PHONY: clean pep8 lint test
.PHONY: clean pep8 lint test install
clean:
rm -fr build
@@ -16,6 +16,9 @@ lint:
test:
nosetests
install:
pip install -r requirements.txt
help:
@echo "Available targets:"
@echo "- clean Clean up the source directory"
+4 -2
View File
@@ -2,6 +2,8 @@ Python Telegram Bot
A Python wrapper around the Telegram Bot API.
*Stay tuned for library updates and new releases on our* `Telegram Channel <http://telegram.me/pythontelegrambotchannel>`_.
By `Leandro Toledo <leandrotoledodesouza@gmail.com>`_
.. image:: https://img.shields.io/pypi/v/python-telegram-bot.svg
@@ -16,7 +18,7 @@ By `Leandro Toledo <leandrotoledodesouza@gmail.com>`_
:target: https://readthedocs.org/projects/python-telegram-bot/?badge=latest
:alt: Documentation Status
.. image:: https://img.shields.io/github/license/leandrotoledo/python-telegram-bot.svg
.. image:: https://img.shields.io/pypi/l/python-telegram-bot.svg
:target: http://www.gnu.org/licenses/lgpl-3.0.html
:alt: LGPLv3 License
@@ -275,7 +277,7 @@ You may copy, distribute and modify the software provided that modifications are
_`Contact`
==========
Feel free to join to our `Telegram group <https://telegram.me/joinchat/00b9c0f802509b94d52953d3fa1ec504>`_.
Feel free to join to our `Telegram group <https://telegram.me/joinchat/ALnA-AJQm5SEwuAzar3nvw>`_.
If you face trouble joining in the group please ping me `via Telegram <https://telegram.me/leandrotoledo>`_, I'll be glad to add you.
+2 -2
View File
@@ -58,9 +58,9 @@ author = u'Leandro Toledo'
# built documents.
#
# The short X.Y version.
version = '2.8'
version = '2.9'
# The full version, including alpha/beta/rc tags.
release = '2.8.3'
release = '2.9.2'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
+5 -5
View File
@@ -51,15 +51,15 @@ def echo(bot):
for update in bot.getUpdates(offset=LAST_UPDATE_ID, timeout=10):
# chat_id is required to reply any message
chat_id = update.message.chat_id
message = update.message.text.encode('utf-8')
reply_text = update.message.text
if (message):
if reply_text:
# Reply the message
bot.sendMessage(chat_id=chat_id,
text=message)
text=reply_text)
# Updates global offset to get the new updates
LAST_UPDATE_ID = update.update_id + 1
# Updates global offset to get the new updates
LAST_UPDATE_ID = update.update_id + 1
if __name__ == '__main__':
+1
View File
@@ -0,0 +1 @@
future
+13 -1
View File
@@ -13,9 +13,20 @@ def read(*paths):
return f.read()
def requirements():
"""Build the requirements list for this project"""
requirements_list = []
with open('requirements.txt') as requirements:
for install in requirements:
requirements_list.append(install.strip())
return requirements_list
setup(
name='python-telegram-bot',
version='2.8.3',
version='2.9.2',
author='Leandro Toledo',
author_email='leandrotoledodesouza@gmail.com',
license='LGPLv3',
@@ -24,6 +35,7 @@ setup(
description='A Python wrapper around the Telegram Bot API',
long_description=(read('README.rst')),
packages=find_packages(exclude=['tests*']),
install_requires=requirements(),
include_package_data=True,
classifiers=[
'Development Status :: 5 - Production/Stable',
+1 -1
View File
@@ -19,7 +19,7 @@
"""A library that provides a Python interface to the Telegram Bot API"""
__author__ = 'leandrotoledodesouza@gmail.com'
__version__ = '2.8.3'
__version__ = '2.8.7'
from .base import TelegramObject
from .user import User
+2 -2
View File
@@ -52,8 +52,8 @@ class Audio(TelegramObject):
self.file_id = str(file_id)
self.duration = int(duration)
# Optionals
self.performer = str(kwargs.get('performer', ''))
self.title = str(kwargs.get('title', ''))
self.performer = kwargs.get('performer', '')
self.title = kwargs.get('title', '')
self.mime_type = str(kwargs.get('mime_type', ''))
self.file_size = int(kwargs.get('file_size', 0))
+8 -2
View File
@@ -649,7 +649,8 @@ class Bot(TelegramObject):
def getUpdates(self,
offset=None,
limit=100,
timeout=0):
timeout=0,
network_delay=2.):
"""Use this method to receive incoming updates using long polling.
Args:
@@ -665,6 +666,11 @@ class Bot(TelegramObject):
timeout:
Timeout in seconds for long polling. Defaults to 0, i.e. usual
short polling.
network_delay:
Additional timeout in seconds to allow the response from Telegram
to take some time when using long polling. Defaults to 2, which
should be enough for most connections. Increase it if it takes very
long for data to be transmitted from and to the Telegram servers.
Returns:
A list of telegram.Update objects are returned.
@@ -680,7 +686,7 @@ class Bot(TelegramObject):
if timeout:
data['timeout'] = timeout
result = request.post(url, data)
result = request.post(url, data, network_delay=network_delay)
if result:
self.logger.info(
+1 -1
View File
@@ -49,7 +49,7 @@ class Document(TelegramObject):
self.file_id = str(file_id)
# Optionals
self.thumb = kwargs.get('thumb')
self.file_name = str(kwargs.get('file_name', ''))
self.file_name = kwargs.get('file_name', '')
self.mime_type = str(kwargs.get('mime_type', ''))
self.file_size = int(kwargs.get('file_size', 0))
+844 -842
View File
File diff suppressed because it is too large Load Diff
+9 -1
View File
@@ -28,18 +28,26 @@ class GroupChat(TelegramObject):
Attributes:
id (int):
title (str):
type (str):
Args:
id (int):
title (str):
**kwargs: Arbitrary keyword arguments.
Keyword Args:
type (Optional[str]):
"""
def __init__(self,
id,
title):
title,
**kwargs):
# Required
self.id = int(id)
self.title = title
# Optionals
self.type = kwargs.get('type', '')
@staticmethod
def de_json(data):
+2 -2
View File
@@ -134,7 +134,7 @@ class Message(TelegramObject):
if not data:
return None
data['from_user'] = User.de_json(data['from'])
data['from_user'] = User.de_json(data.get('from'))
data['date'] = datetime.fromtimestamp(data['date'])
if 'first_name' in data.get('chat', ''):
data['chat'] = User.de_json(data.get('chat'))
@@ -185,7 +185,7 @@ class Message(TelegramObject):
data = super(Message, self).to_dict()
# Required
data['from'] = data.pop('from_user')
data['from'] = data.pop('from_user', None)
data['date'] = self._totimestamp(self.date)
# Optionals
if self.forward_date:
+2 -1
View File
@@ -17,7 +17,8 @@
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains a object that represents a Telegram Message Parse Modes"""
"""This module contains a object that represents a Telegram
Message Parse Modes"""
class ParseMode(object):
+4 -1
View File
@@ -23,13 +23,14 @@ from telegram import TelegramObject
class User(TelegramObject):
"""This object represents a Telegram Sticker.
"""This object represents a Telegram User.
Attributes:
id (int):
first_name (str):
last_name (str):
username (str):
type (str):
Args:
id (int):
@@ -37,6 +38,7 @@ class User(TelegramObject):
**kwargs: Arbitrary keyword arguments.
Keyword Args:
type (Optional[str]):
last_name (Optional[str]):
username (Optional[str]):
"""
@@ -49,6 +51,7 @@ class User(TelegramObject):
self.id = int(id)
self.first_name = first_name
# Optionals
self.type = kwargs.get('type', '')
self.last_name = kwargs.get('last_name', '')
self.username = kwargs.get('username', '')
+25 -6
View File
@@ -20,15 +20,16 @@
"""This module contains methods to make POST and GET requests"""
import json
import socket
from ssl import SSLError
try:
from urllib.parse import urlencode
from urllib.request import urlopen, urlretrieve, Request
from urllib.error import HTTPError, URLError
from urllib.error import HTTPError
except ImportError:
from urllib import urlencode, urlretrieve
from urllib import urlretrieve
from urllib2 import urlopen, Request
from urllib2 import HTTPError, URLError
from urllib2 import HTTPError
from telegram import (InputFile, TelegramError)
@@ -67,17 +68,29 @@ def get(url):
def post(url,
data):
data,
network_delay=2.):
"""Request an URL.
Args:
url:
The web location we want to retrieve.
data:
A dict of (str, unicode) key/value pairs.
network_delay:
Additional timeout in seconds to allow the response from Telegram to
take some time.
Returns:
A JSON object.
"""
# Add time to the timeout of urlopen to allow data to be transferred over
# the network.
if 'timeout' in data:
timeout = data['timeout'] + network_delay
else:
timeout = None
try:
if InputFile.is_inputfile(data):
data = InputFile(data)
@@ -90,14 +103,20 @@ def post(url,
data=data.encode(),
headers={'Content-Type': 'application/json'})
result = urlopen(request).read()
result = urlopen(request, timeout=timeout).read()
except HTTPError as error:
if error.getcode() == 403:
raise TelegramError('Unauthorized')
if error.getcode() == 502:
raise TelegramError('Bad Gateway')
message = _parse(error.read())
raise TelegramError(message)
except (SSLError, socket.timeout) as error:
if "operation timed out" in str(error):
raise TelegramError("Timed out")
raise TelegramError(str(error))
return _parse(result)
+44
View File
@@ -0,0 +1,44 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015 Leandro Toledo de Souza <leandrotoeldodesouza@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains a object that represents Tests for Telegram Emoji"""
import os
import unittest
import sys
sys.path.append('.')
import telegram
from telegram.emoji import Emoji
from tests.base import BaseTest
class EmojiTest(BaseTest, unittest.TestCase):
"""This object represents Tests for Telegram Emoji."""
def test_emoji(self):
"""Test Emoji class"""
print('Testing Emoji class')
for attr in dir(Emoji):
if attr[0] != '_': # TODO: dirty way to filter out functions
self.assertTrue(type(getattr(Emoji, attr)) is str)
if __name__ == '__main__':
unittest.main()
+5 -1
View File
@@ -33,10 +33,12 @@ class GroupChatTest(BaseTest, unittest.TestCase):
def setUp(self):
self.id = -28767330
self.title = 'ToledosPalaceBot - Group'
self.type = 'group'
self.json_dict = {
'id': self.id,
'title': self.title
'title': self.title,
'type': self.type
}
def test_group_chat_de_json_empty_json(self):
@@ -55,6 +57,7 @@ class GroupChatTest(BaseTest, unittest.TestCase):
self.assertEqual(group_chat.id, self.id)
self.assertEqual(group_chat.title, self.title)
self.assertEqual(group_chat.type, self.type)
def test_group_chat_to_json(self):
"""Test GroupChat.to_json() method"""
@@ -73,6 +76,7 @@ class GroupChatTest(BaseTest, unittest.TestCase):
self.assertTrue(self.is_dict(group_chat.to_dict()))
self.assertEqual(group_chat['id'], self.id)
self.assertEqual(group_chat['title'], self.title)
self.assertEqual(group_chat['type'], self.type)
if __name__ == '__main__':
unittest.main()
+6 -1
View File
@@ -35,12 +35,14 @@ class UserTest(BaseTest, unittest.TestCase):
self.first_name = "Leandro"
self.last_name = "S."
self.username = "leandrotoledo"
self.type = "private"
self.json_dict = {
'id': self.id,
'first_name': self.first_name,
'last_name': self.last_name,
'username': self.username
'username': self.username,
'type': self.type
}
def test_user_de_json(self):
@@ -53,6 +55,7 @@ class UserTest(BaseTest, unittest.TestCase):
self.assertEqual(user.first_name, self.first_name)
self.assertEqual(user.last_name, self.last_name)
self.assertEqual(user.username, self.username)
self.assertEqual(user.type, self.type)
self.assertEqual(user.name, '@leandrotoledo')
@@ -69,6 +72,7 @@ class UserTest(BaseTest, unittest.TestCase):
self.assertEqual(user.id, self.id)
self.assertEqual(user.first_name, self.first_name)
self.assertEqual(user.last_name, self.last_name)
self.assertEqual(user.type, self.type)
self.assertEqual(user.name, '%s %s' % (self.first_name, self.last_name))
@@ -108,6 +112,7 @@ class UserTest(BaseTest, unittest.TestCase):
self.assertEqual(user['first_name'], self.first_name)
self.assertEqual(user['last_name'], self.last_name)
self.assertEqual(user['username'], self.username)
self.assertEqual(user['type'], self.type)
if __name__ == '__main__':
unittest.main()