mirror of
https://github.com/python-telegram-bot/python-telegram-bot.git
synced 2026-06-19 07:35:19 +00:00
Compare commits
190 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| aa8966832b | |||
| e27427676d | |||
| 8175fd7b53 | |||
| 2875bae881 | |||
| c756aa1c02 | |||
| c2f04331f3 | |||
| 5293ec49ff | |||
| 9319903343 | |||
| 95e2aad9bd | |||
| 73f4f26da5 | |||
| 24b2bf335c | |||
| fc3fa0f515 | |||
| 87657bcd70 | |||
| 81b58c7d00 | |||
| dd7d1255d1 | |||
| f813d4f5ec | |||
| 623863cee1 | |||
| aa125e59fb | |||
| 68c844df0c | |||
| 3779d454f3 | |||
| 5d168bd479 | |||
| 1c8bb21790 | |||
| 054c976ad6 | |||
| bc2679f2ae | |||
| 17dae68654 | |||
| 7734c1d6a6 | |||
| aeca3ca174 | |||
| 21fdaa4ff7 | |||
| 79f29c4b9e | |||
| a2d8ca3663 | |||
| 6f76bfc2de | |||
| 97ebebefc1 | |||
| 119743433d | |||
| b0ad07f30f | |||
| 114cb787ea | |||
| 5d1ef673a3 | |||
| 3e1cb08567 | |||
| 29a4062945 | |||
| 2ff6fe9901 | |||
| 34b91f5062 | |||
| cc6c4a6eb9 | |||
| fc9456e1a8 | |||
| 41ba57f064 | |||
| b205751aee | |||
| c4f13bd1bb | |||
| 7d7397317e | |||
| 631954e5d9 | |||
| 90ed128a61 | |||
| 2a2b679362 | |||
| f75e329225 | |||
| ea7c54ba07 | |||
| 3c7b037eaa | |||
| c15a1bc151 | |||
| 9e7314134e | |||
| 37271e4a02 | |||
| 0e78606d37 | |||
| cb0736fb3d | |||
| e0233a59a0 | |||
| 6e158042e1 | |||
| d791a6ee89 | |||
| 5a3e142358 | |||
| 37a58fe1ad | |||
| 80281cc66d | |||
| fffa9d8a7c | |||
| 806b71030f | |||
| 764c5dac53 | |||
| 007dc5807a | |||
| 16534872a7 | |||
| a13245dfbf | |||
| 6622ea3ec0 | |||
| bcadfc5398 | |||
| 89ecb04a85 | |||
| 56ab40d94f | |||
| f5ac1ae067 | |||
| 23507202e8 | |||
| 185bff7117 | |||
| 9f07900d99 | |||
| 809fe4b74f | |||
| 8a4d5c5de7 | |||
| 1976822dd0 | |||
| e60694a8cc | |||
| 14b4c1ac62 | |||
| d5890d403b | |||
| ef569b68c6 | |||
| 628a4c4eac | |||
| 83d2ca3aa7 | |||
| 29cdfe671e | |||
| f21b6046c5 | |||
| 8090658ab4 | |||
| f49f592f0d | |||
| c2853fa1ef | |||
| e1f3f346bc | |||
| 1005ad57ce | |||
| 0b72acc7c8 | |||
| 8d267ed896 | |||
| 83812f3af6 | |||
| 658b5ff1c0 | |||
| 593153128c | |||
| d91f210f7c | |||
| 65177e791f | |||
| 15501e185b | |||
| 1782d0d19b | |||
| 88fbf3b5cf | |||
| c7a1d8dca3 | |||
| 3e732a0736 | |||
| 628e1b743a | |||
| e4de3f00b8 | |||
| 32c021fdd5 | |||
| a6e5a71e05 | |||
| 4d87e236be | |||
| 29ab0556f0 | |||
| fca8aee177 | |||
| 6a80a33aef | |||
| 7c9928c58f | |||
| 0cd7aa92ae | |||
| 6626d4534e | |||
| 6b309397e8 | |||
| 618df51811 | |||
| d38add1a1c | |||
| 1c7e784662 | |||
| 0006294f29 | |||
| c1f194a310 | |||
| cccd6e5baf | |||
| a0baa68cf3 | |||
| 62b79df0a4 | |||
| 1246039872 | |||
| ed6dd76ae8 | |||
| 70de2bd3f1 | |||
| 8bde310ec7 | |||
| be368f7d74 | |||
| 9defc41774 | |||
| ee8b78aa0d | |||
| 0b8fd24771 | |||
| 396dc6cd3c | |||
| ba3d174fde | |||
| ab313488ad | |||
| d808462fb6 | |||
| 71e73c3999 | |||
| a55df8b5e1 | |||
| f59efe0f4b | |||
| 1b79a57673 | |||
| ae59a18e2d | |||
| 12201f392d | |||
| 8f3fe123e3 | |||
| 04050ca883 | |||
| c3b3d51286 | |||
| 10451509f1 | |||
| ff0d724f32 | |||
| c64e577049 | |||
| f08dca0af6 | |||
| 8c0bcbf5bb | |||
| 596fc2aeda | |||
| 968b19e8b7 | |||
| 7993328ff7 | |||
| 16349ac69a | |||
| 45712c52f1 | |||
| 235dcd2ad2 | |||
| ed92d1c254 | |||
| 0b4c23f50e | |||
| 63c895c0a0 | |||
| 3162bc60e9 | |||
| 206802cf4d | |||
| 5eb4f8e5cd | |||
| 0a27e3927b | |||
| 401add78d3 | |||
| af375eb402 | |||
| 2797111ced | |||
| d7d4889c50 | |||
| bf356e124f | |||
| d7fd43ca79 | |||
| 42e11d169e | |||
| c1fae0b5ee | |||
| ef99bab435 | |||
| 93afd3eabe | |||
| 61dac76bee | |||
| 245f5abc45 | |||
| 0f8f6584ce | |||
| dd498ded00 | |||
| 5d2999818b | |||
| eb1f197ff4 | |||
| 4bc03ed56a | |||
| 9191d333ca | |||
| c19a84ac05 | |||
| 404fdc2dd7 | |||
| 2ec56abe7e | |||
| 63a8700258 | |||
| d363185031 | |||
| aabaaa9049 | |||
| eb2be61eac | |||
| 0688691974 |
@@ -61,3 +61,10 @@ target/
|
||||
|
||||
# Sublime Text 2
|
||||
*.sublime*
|
||||
|
||||
# unitests files
|
||||
telegram.mp3
|
||||
telegram.mp4
|
||||
telegram.ogg
|
||||
telegram.png
|
||||
telegram.webp
|
||||
|
||||
+5
-2
@@ -7,9 +7,12 @@ python:
|
||||
- "pypy"
|
||||
- "pypy3"
|
||||
install:
|
||||
- pip install coveralls
|
||||
- pip install pylint flake8 coveralls
|
||||
- pip install -r requirements.txt
|
||||
- 'if [[ $TRAVIS_PYTHON_VERSION == 2.6 ]]; then pip install unittest2; fi'
|
||||
script:
|
||||
nosetests --with-coverage --cover-package telegram/
|
||||
- nosetests --with-coverage --cover-package telegram/
|
||||
- flake8 telegram
|
||||
- 'if [[ $TRAVIS_PYTHON_VERSION != 2.6 ]]; then pylint -E telegram --disable=no-name-in-module,import-error; fi'
|
||||
after_success:
|
||||
coveralls
|
||||
|
||||
@@ -9,6 +9,7 @@ Contributors
|
||||
The following wonderful people contributed directly or indirectly to this project:
|
||||
|
||||
- `Avanatiker <https://github.com/Avanatiker>`_
|
||||
- `Balduro <https://github.com/Balduro>`_
|
||||
- `bimmlerd <https://github.com/bimmlerd>`_
|
||||
- `ErgoZ Riftbit Vaper <https://github.com/ergoz>`_
|
||||
- `franciscod <https://github.com/franciscod>`_
|
||||
@@ -16,7 +17,9 @@ The following wonderful people contributed directly or indirectly to this projec
|
||||
- `jh0ker <https://github.com/jh0ker>`_
|
||||
- `JRoot3D <https://github.com/JRoot3D>`_
|
||||
- `macrojames <https://github.com/macrojames>`_
|
||||
- `naveenvhegde <https://github.com/naveenvhegde>`_
|
||||
- `njittam <https://github.com/njittam>`_
|
||||
- `Noam Meltzer <https://github.com/tsnoam>`_
|
||||
- `Rahiel Kasim <https://github.com/rahiel>`_
|
||||
- `sooyhwang <https://github.com/sooyhwang>`_
|
||||
- `wjt <https://github.com/wjt>`_
|
||||
|
||||
+240
-127
@@ -1,189 +1,302 @@
|
||||
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 channels
|
||||
Raise exception if Telegram times out on long-polling
|
||||
*Special thanks to @jh0ker for all hard work*
|
||||
**2016-01-05**
|
||||
|
||||
*Released 3.2.0*
|
||||
|
||||
- Introducing ``JobQueue`` (original author: @franciscod)
|
||||
- Streamlining all exceptions to ``TelegramError`` (Special thanks to @tsnoam)
|
||||
- Proper locking of ``Updater`` and ``Dispatcher`` ``start`` and ``stop`` methods
|
||||
- Small bugfixes
|
||||
|
||||
**2015-12-29**
|
||||
|
||||
*Released 3.1.2*
|
||||
|
||||
- Fix custom path for file downloads
|
||||
- Don't stop the dispatcher thread on uncaught errors in handlers
|
||||
|
||||
**2015-12-21**
|
||||
|
||||
*Released 3.1.1*
|
||||
|
||||
- Fix a bug where asynchronous handlers could not have additional arguments
|
||||
- Add ``groups`` and ``groupdict`` as additional arguments for regex-based handlers
|
||||
|
||||
**2015-12-16**
|
||||
|
||||
*Released 3.1.0*
|
||||
|
||||
- The ``chat``-field in ``Message`` is now of type ``Chat``. (API update Oct 8 2015)
|
||||
- ``Message`` now contains the optional fields ``supergroup_chat_created``, ``migrate_to_chat_id``, ``migrate_from_chat_id`` and ``channel_chat_created``. (API update Nov 2015)
|
||||
|
||||
**2015-12-08**
|
||||
|
||||
*Released 3.0.0*
|
||||
|
||||
- Introducing the ``Updater`` and ``Dispatcher`` classes
|
||||
|
||||
**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-10-08
|
||||
Released 2.8.7
|
||||
Type as optional for GroupChat class
|
||||
**2015-10-08**
|
||||
|
||||
*Released 2.8.7*
|
||||
|
||||
- Type as optional for ``GroupChat`` class
|
||||
|
||||
|
||||
2015-10-08
|
||||
Released 2.8.6
|
||||
Adds type to User and GroupChat classes (pre-release Telegram feature)
|
||||
**2015-10-08**
|
||||
|
||||
*Released 2.8.6*
|
||||
|
||||
- Adds type to ``User`` and ``GroupChat`` classes (pre-release Telegram feature)
|
||||
|
||||
|
||||
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-09-24**
|
||||
|
||||
*Released 2.8.5*
|
||||
|
||||
- Handles HTTP Bad Gateway (503) errors on request
|
||||
- Fixes regression on ``Audio`` and ``Document`` for unicode fields
|
||||
|
||||
|
||||
2015-09-20
|
||||
Released 2.8.4
|
||||
getFile and File.download is now fully supported
|
||||
**2015-09-20**
|
||||
|
||||
*Released 2.8.4*
|
||||
|
||||
- ``getFile`` and ``File.download`` is now fully supported
|
||||
|
||||
|
||||
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-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-09-05
|
||||
Released 2.8.2
|
||||
Fix regression on Telegram ReplyMarkup
|
||||
Add certificate to is_inputfile method
|
||||
**2015-09-05**
|
||||
|
||||
*Released 2.8.2*
|
||||
|
||||
- Fix regression on Telegram ReplyMarkup
|
||||
- Add certificate to ``is_inputfile`` method
|
||||
|
||||
|
||||
2015-09-05
|
||||
Released 2.8.1
|
||||
Fix regression on Telegram objects with thumb properties
|
||||
**2015-09-05**
|
||||
|
||||
*Released 2.8.1*
|
||||
|
||||
- Fix regression on Telegram objects with thumb properties
|
||||
|
||||
|
||||
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-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-19
|
||||
Released 2.7.1
|
||||
Fixed JSON serialization for message
|
||||
**2015-08-19**
|
||||
|
||||
*Released 2.7.1*
|
||||
|
||||
- Fixed JSON serialization for ``message``
|
||||
|
||||
|
||||
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-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-15
|
||||
Released 2.6.1
|
||||
Fixed parsing image header issue on < Python 2.7.3
|
||||
**2015-08-15**
|
||||
|
||||
*Released 2.6.1*
|
||||
|
||||
- Fixed parsing image header issue on < Python 2.7.3
|
||||
|
||||
|
||||
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-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-12
|
||||
Released 2.5.3
|
||||
telegram.Bot now supports to be unpickled
|
||||
**2015-08-12**
|
||||
|
||||
*Released 2.5.3*
|
||||
|
||||
- ``telegram.Bot`` now supports to be unpickled
|
||||
|
||||
|
||||
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-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-10
|
||||
Released 2.5.1
|
||||
Moved from GPLv2 to LGPLv3
|
||||
**2015-08-10**
|
||||
|
||||
*Released 2.5.1*
|
||||
|
||||
- Moved from GPLv2 to LGPLv3
|
||||
|
||||
|
||||
2015-08-09
|
||||
Released 2.5
|
||||
Fixes logging calls in API
|
||||
**2015-08-09**
|
||||
|
||||
*Released 2.5*
|
||||
|
||||
- Fixes logging calls in API
|
||||
|
||||
|
||||
2015-08-08
|
||||
Released 2.4
|
||||
Fixes Emoji class for Python 3
|
||||
PEP8 improvements
|
||||
**2015-08-08**
|
||||
|
||||
*Released 2.4*
|
||||
|
||||
- Fixes ``Emoji`` class for Python 3
|
||||
- ``PEP8`` improvements
|
||||
|
||||
|
||||
2015-08-08
|
||||
Released 2.3
|
||||
Fixes ForceReply class
|
||||
Remove logging.basicConfig from library
|
||||
**2015-08-08**
|
||||
|
||||
*Released 2.3*
|
||||
|
||||
- Fixes ``ForceReply`` class
|
||||
- Remove ``logging.basicConfig`` from library
|
||||
|
||||
|
||||
2015-07-25
|
||||
Released 2.2
|
||||
Allows debug=True when initializing telegram.Bot
|
||||
**2015-07-25**
|
||||
|
||||
*Released 2.2*
|
||||
|
||||
- Allows ``debug=True`` when initializing ``telegram.Bot``
|
||||
|
||||
|
||||
2015-07-20
|
||||
Released 2.1
|
||||
Fix to_dict for Document and Video
|
||||
**2015-07-20**
|
||||
|
||||
*Released 2.1*
|
||||
|
||||
- Fix ``to_dict`` for ``Document`` and ``Video``
|
||||
|
||||
|
||||
2015-07-19
|
||||
Released 2.0
|
||||
Fixes bugs
|
||||
Improves __str__ over to_json()
|
||||
Creates abstractclass TelegramObject
|
||||
**2015-07-19**
|
||||
|
||||
*Released 2.0*
|
||||
|
||||
- Fixes bugs
|
||||
- Improves ``__str__`` over ``to_json()``
|
||||
- Creates abstract class ``TelegramObject``
|
||||
|
||||
|
||||
2015-07-15
|
||||
Released 1.9
|
||||
Python 3 officially supported
|
||||
PEP8 improvements
|
||||
**2015-07-15**
|
||||
|
||||
*Released 1.9*
|
||||
|
||||
- Python 3 officially supported
|
||||
- ``PEP8`` improvements
|
||||
|
||||
|
||||
2015-07-12
|
||||
Released 1.8
|
||||
Fixes crash when replying an unicode text message (special thanks to JRoot3D)
|
||||
**2015-07-12**
|
||||
|
||||
*Released 1.8*
|
||||
|
||||
- Fixes crash when replying an unicode text message (special thanks to JRoot3D)
|
||||
|
||||
|
||||
2015-07-11
|
||||
Released 1.7
|
||||
Fixes crash when username is not defined on chat (special thanks to JRoot3D)
|
||||
**2015-07-11**
|
||||
|
||||
*Released 1.7*
|
||||
|
||||
- Fixes crash when ``username`` is not defined on ``chat`` (special thanks to JRoot3D)
|
||||
|
||||
|
||||
2015-07-10
|
||||
Released 1.6
|
||||
Improvements for GAE support
|
||||
**2015-07-10**
|
||||
|
||||
*Released 1.6*
|
||||
|
||||
- Improvements for GAE support
|
||||
|
||||
|
||||
2015-07-10
|
||||
Released 1.5
|
||||
Fixes randomly unicode issues when using InputFile
|
||||
**2015-07-10**
|
||||
|
||||
*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.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-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-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.1*
|
||||
|
||||
- PyPi package now available
|
||||
|
||||
|
||||
2015-07-08
|
||||
Released 1.0
|
||||
Initial checkin of python-telegram-bot
|
||||
**2015-07-08**
|
||||
|
||||
*Released 1.0*
|
||||
|
||||
- Initial checkin of python-telegram-bot
|
||||
|
||||
+2
-2
@@ -35,5 +35,5 @@ If you have any question or concerns, feel free to reach out to me.
|
||||
.. _`Code of Conduct`: https://www.python.org/psf/codeofconduct/
|
||||
.. _`Google Python Style Guide`: https://google-styleguide.googlecode.com/svn/trunk/pyguide.html
|
||||
.. _`Google Python Style Docstrings`: http://sphinx-doc.org/latest/ext/example_google.html
|
||||
.. _CHANGES: https://github.com/leandrotoledo/python-telegram-bot/blob/master/CHANGES
|
||||
.. _AUTHORS.rst: https://github.com/leandrotoledo/python-telegram-bot/blob/master/AUTHORS.rst
|
||||
.. _CHANGES: https://github.com/python-telegram-bot/python-telegram-bot/blob/master/CHANGES
|
||||
.. _AUTHORS.rst: https://github.com/python-telegram-bot/python-telegram-bot/blob/master/AUTHORS.rst
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
include LICENSE LICENSE.lesser Makefile
|
||||
include LICENSE LICENSE.lesser Makefile requirements.txt
|
||||
|
||||
+131
-24
@@ -1,11 +1,12 @@
|
||||
Python Telegram Bot
|
||||
.. image:: https://github.com/python-telegram-bot/logos/blob/master/logo-text/png/ptb-logo-text_768.png?raw=true
|
||||
:align: center
|
||||
:target: https://github.com/python-telegram-bot/logos
|
||||
:alt: python-telegram-bot Logo
|
||||
|
||||
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
|
||||
:target: https://pypi.python.org/pypi/python-telegram-bot
|
||||
:alt: PyPi Package Version
|
||||
@@ -22,16 +23,16 @@ By `Leandro Toledo <leandrotoledodesouza@gmail.com>`_
|
||||
:target: http://www.gnu.org/licenses/lgpl-3.0.html
|
||||
:alt: LGPLv3 License
|
||||
|
||||
.. image:: https://travis-ci.org/leandrotoledo/python-telegram-bot.svg?branch=master
|
||||
:target: https://travis-ci.org/leandrotoledo/python-telegram-bot
|
||||
.. image:: https://travis-ci.org/python-telegram-bot/python-telegram-bot.svg?branch=master
|
||||
:target: https://travis-ci.org/python-telegram-bot/python-telegram-bot
|
||||
:alt: Travis CI Status
|
||||
|
||||
.. image:: https://codeclimate.com/github/leandrotoledo/python-telegram-bot/badges/gpa.svg
|
||||
:target: https://codeclimate.com/github/leandrotoledo/python-telegram-bot
|
||||
.. image:: https://codeclimate.com/github/python-telegram-bot/python-telegram-bot/badges/gpa.svg
|
||||
:target: https://codeclimate.com/github/python-telegram-bot/python-telegram-bot
|
||||
:alt: Code Climate
|
||||
|
||||
.. image:: https://coveralls.io/repos/leandrotoledo/python-telegram-bot/badge.svg?branch=master&service=github
|
||||
:target: https://coveralls.io/github/leandrotoledo/python-telegram-bot?branch=master
|
||||
.. image:: https://coveralls.io/repos/python-telegram-bot/python-telegram-bot/badge.svg?branch=master&service=github
|
||||
:target: https://coveralls.io/github/python-telegram-bot/python-telegram-bot?branch=master
|
||||
:alt: Coveralls
|
||||
|
||||
=================
|
||||
@@ -52,13 +53,17 @@ Table of contents
|
||||
|
||||
- `Getting started`_
|
||||
|
||||
1. `API`_
|
||||
1. `The Updater class`_
|
||||
|
||||
2. `API`_
|
||||
|
||||
3. `JobQueue`_
|
||||
|
||||
2. `Logging`_
|
||||
4. `Logging`_
|
||||
|
||||
3. `Examples`_
|
||||
5. `Examples`_
|
||||
|
||||
4. `Documentation`_
|
||||
6. `Documentation`_
|
||||
|
||||
- `License`_
|
||||
|
||||
@@ -131,11 +136,11 @@ Or upgrade to the latest version::
|
||||
_`Getting the code`
|
||||
===================
|
||||
|
||||
The code is hosted at https://github.com/leandrotoledo/python-telegram-bot
|
||||
The code is hosted at https://github.com/python-telegram-bot/python-telegram-bot
|
||||
|
||||
Check out the latest development version anonymously with::
|
||||
|
||||
$ git clone https://github.com/leandrotoledo/python-telegram-bot
|
||||
$ git clone https://github.com/python-telegram-bot/python-telegram-bot
|
||||
$ cd python-telegram-bot
|
||||
|
||||
Run tests:
|
||||
@@ -152,10 +157,72 @@ _`Getting started`
|
||||
|
||||
View the last release API documentation at: https://core.telegram.org/bots/api
|
||||
|
||||
--------------------
|
||||
_`The Updater class`
|
||||
--------------------
|
||||
|
||||
The ``Updater`` class is the new way to create bots with ``python-telegram-bot``. It provides an easy-to-use interface to the ``telegram.Bot`` by caring about getting new updates from telegram and forwarding them to the ``Dispatcher`` class. We can register handler functions in the ``Dispatcher`` to make our bot react to Telegram commands, messages and even arbitrary updates.
|
||||
|
||||
As with the old method, we'll need an Access Token. To generate an Access Token, we have to talk to `BotFather <https://telegram.me/botfather>`_ and follow a few simple steps (described `here <https://core.telegram.org/bots#botfather>`_).
|
||||
|
||||
First, we create an ``Updater`` object::
|
||||
|
||||
>>> from telegram import Updater
|
||||
>>> updater = Updater(token='token')
|
||||
|
||||
For quicker access to the ``Dispatcher`` used by our ``Updater``, we can introduce it locally::
|
||||
|
||||
>>> dispatcher = updater.dispatcher
|
||||
|
||||
Now, we need to define a function that should process a specific type of update::
|
||||
|
||||
>>> def start(bot, update):
|
||||
... bot.sendMessage(chat_id=update.message.chat_id, text="I'm a bot, please talk to me!")
|
||||
|
||||
We want this function to be called on a Telegram message that contains the ``/start`` command, so we need to register it in the dispatcher::
|
||||
|
||||
>>> dispatcher.addTelegramCommandHandler('start', start)
|
||||
|
||||
The last step is to tell the ``Updater`` to start working::
|
||||
|
||||
>>> updater.start_polling()
|
||||
|
||||
Our bot is now up and running (go ahead and try it)! It's not doing anything yet, besides answering to the ``/start`` command. Let's add another handler function and register it::
|
||||
|
||||
>>> def echo(bot, update):
|
||||
... bot.sendMessage(chat_id=update.message.chat_id, text=update.message.text)
|
||||
...
|
||||
>>> dispatcher.addTelegramMessageHandler(echo)
|
||||
|
||||
Our bot should now reply to all messages that are not a command with a message that has the same content.
|
||||
|
||||
People might try to send commands to the bot that it doesn't understand, so we should get that covered as well::
|
||||
|
||||
>>> def unknown(bot, update):
|
||||
... bot.sendMessage(chat_id=update.message.chat_id, text="Sorry, I didn't understand that command.")
|
||||
...
|
||||
>>> dispatcher.addUnknownTelegramCommandHandler(unknown)
|
||||
|
||||
Let's add some functionality to our bot. We want to add the ``/caps`` command, that will take some text as parameter and return it in all caps. We can get the arguments that were passed to the command in the handler function simply by adding it to the parameter list::
|
||||
|
||||
>>> def caps(bot, update, args):
|
||||
... text_caps = ' '.join(args).upper()
|
||||
... bot.sendMessage(chat_id=update.message.chat_id, text=text_caps)
|
||||
...
|
||||
>>> dispatcher.addTelegramCommandHandler('caps', caps)
|
||||
|
||||
Now it's time to stop the bot::
|
||||
|
||||
>>> updater.stop()
|
||||
|
||||
Check out more examples in the `examples folder <https://github.com/python-telegram-bot/python-telegram-bot/tree/master/examples>`_!
|
||||
|
||||
------
|
||||
_`API`
|
||||
------
|
||||
|
||||
Note: Using the ``Bot`` class directly is the 'old' method, but some of this is still important information, even if you're using the ``Updater`` class!
|
||||
|
||||
The API is exposed via the ``telegram.Bot`` class.
|
||||
|
||||
To generate an Access Token you have to talk to `BotFather <https://telegram.me/botfather>`_ and follow a few simple steps (described `here <https://core.telegram.org/bots#botfather>`_).
|
||||
@@ -234,9 +301,39 @@ There are many more API methods, to read the full API documentation::
|
||||
$ pydoc telegram.Bot
|
||||
|
||||
-----------
|
||||
_`Logging`
|
||||
_`JobQueue`
|
||||
-----------
|
||||
|
||||
The ``JobQueue`` allows you to perform tasks with a delay or even periodically. The ``Updater`` will create one for you::
|
||||
|
||||
>>> from telegram import Updater
|
||||
>>> u = Updater('TOKEN')
|
||||
>>> j = u.job_queue
|
||||
|
||||
The job queue uses functions for tasks, so we define one and add it to the queue. Usually, when the first job is added to the queue, it wil start automatically. We can prevent this by setting ``prevent_autostart=True``::
|
||||
|
||||
>>> def job1(bot):
|
||||
... bot.sendMessage(chat_id='@examplechannel', text='One message every minute')
|
||||
>>> j.put(job1, 60, next_t=0, prevent_autostart=True)
|
||||
|
||||
You can also have a job that will not be executed repeatedly::
|
||||
|
||||
>>> def job2(bot):
|
||||
... bot.sendMessage(chat_id='@examplechannel', text='A single message with 30s delay')
|
||||
>>> j.put(job2, 30, repeat=False)
|
||||
|
||||
Now, because we didn't prevent the auto start this time, the queue will start ticking. It runs in a seperate thread, so it is non-blocking. When we stop the Updater, the related queue will be stopped as well::
|
||||
|
||||
>>> u.stop()
|
||||
|
||||
We can also stop the job queue by itself::
|
||||
|
||||
>>> j.stop()
|
||||
|
||||
----------
|
||||
_`Logging`
|
||||
----------
|
||||
|
||||
You can get logs in your main application by calling `logging` and setting the log level you want::
|
||||
|
||||
>>> import logging
|
||||
@@ -253,14 +350,28 @@ _`Examples`
|
||||
|
||||
Here follows some examples to help you to get your own Bot up to speed:
|
||||
|
||||
- `echobot <https://github.com/leandrotoledo/python-telegram-bot/blob/master/examples/echobot.py>`_ replies back messages.
|
||||
- `echobot2 <https://github.com/python-telegram-bot/python-telegram-bot/blob/master/examples/echobot2.py>`_ replies back messages.
|
||||
|
||||
- `roboed <https://github.com/leandrotoledo/python-telegram-bot/blob/master/examples/roboed.py>`_ talks to `Robô Ed <http://www.ed.conpet.gov.br/br/converse.php>`_.
|
||||
- `clibot <https://github.com/python-telegram-bot/python-telegram-bot/blob/master/examples/clibot.py>`_ has a command line interface.
|
||||
|
||||
- `timerbot <https://github.com/python-telegram-bot/python-telegram-bot/blob/master/examples/timerbot.py>`_ uses the ``JobQueue`` to send timed messages.
|
||||
|
||||
- `Welcome Bot <https://github.com/jh0ker/welcomebot>`_ greets everyone who joins a group chat.
|
||||
|
||||
Legacy examples (pre-3.0):
|
||||
|
||||
- `echobot <https://github.com/python-telegram-bot/python-telegram-bot/blob/master/examples/legacy/echobot.py>`_ replies back messages.
|
||||
|
||||
- `roboed <https://github.com/python-telegram-bot/python-telegram-bot/blob/master/examples/legacy/roboed.py>`_ talks to `Robô Ed <http://www.ed.conpet.gov.br/br/converse.php>`_.
|
||||
|
||||
- `Simple-Echo-Telegram-Bot <https://github.com/sooyhwang/Simple-Echo-Telegram-Bot>`_ simple Python Telegram bot that echoes your input with Flask microframework, setWebhook method, and Google App Engine (optional) - by @sooyhwang.
|
||||
|
||||
- `DevOps Reaction Bot <https://github.com/leandrotoledo/gae-devops-reaction-telegram-bot>`_ sends latest or random posts from `DevOps Reaction <http://devopsreactions.tumblr.com/>`_. Running on `Google App Engine <https://cloud.google.com/appengine>`_ (billing has to be enabled for fully Socket API support).
|
||||
|
||||
Other notable examples:
|
||||
|
||||
- `TwitterForwarderBot <https://github.com/franciscod/telegram-twitter-forwarder-bot>`_ forwards you tweets from people that you have subscribed to.
|
||||
|
||||
================
|
||||
_`Documentation`
|
||||
================
|
||||
@@ -277,14 +388,10 @@ 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/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.
|
||||
Feel free to join to our `Telegram group <https://telegram.me/joinchat/ALnA-AJQm5R7Km9hdCgyng>`_.
|
||||
|
||||
=======
|
||||
_`TODO`
|
||||
=======
|
||||
|
||||
Patches and bug reports are `welcome <https://github.com/leandrotoledo/python-telegram-bot/issues/new>`_, just please keep the style consistent with the original source.
|
||||
|
||||
- Add commands handler.
|
||||
Patches and bug reports are `welcome <https://github.com/python-telegram-bot/python-telegram-bot/issues/new>`_, just please keep the style consistent with the original source.
|
||||
|
||||
+3
-3
@@ -50,7 +50,7 @@ master_doc = 'index'
|
||||
|
||||
# General information about the project.
|
||||
project = u'Python Telegram Bot'
|
||||
copyright = u'2015, Leandro Toledo'
|
||||
copyright = u'2015-2016, Leandro Toledo'
|
||||
author = u'Leandro Toledo'
|
||||
|
||||
# The version info for the project you're documenting, acts as replacement for
|
||||
@@ -58,9 +58,9 @@ author = u'Leandro Toledo'
|
||||
# built documents.
|
||||
#
|
||||
# The short X.Y version.
|
||||
version = '2.9'
|
||||
version = '3.2'
|
||||
# The full version, including alpha/beta/rc tags.
|
||||
release = '2.9'
|
||||
release = '3.2.0'
|
||||
|
||||
# The language for content autogenerated by Sphinx. Refer to documentation
|
||||
# for a list of supported languages.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
telegram.groupchat module
|
||||
telegram.chat module
|
||||
=========================
|
||||
|
||||
.. automodule:: telegram.groupchat
|
||||
.. automodule:: telegram.chat
|
||||
:members:
|
||||
:undoc-members:
|
||||
:show-inheritance:
|
||||
@@ -0,0 +1,7 @@
|
||||
telegram.dispatcher module
|
||||
=========================
|
||||
|
||||
.. automodule:: telegram.dispatcher
|
||||
:members:
|
||||
:undoc-members:
|
||||
:show-inheritance:
|
||||
@@ -0,0 +1,7 @@
|
||||
telegram.jobqueue module
|
||||
========================
|
||||
|
||||
.. automodule:: telegram.jobqueue
|
||||
:members:
|
||||
:undoc-members:
|
||||
:show-inheritance:
|
||||
@@ -9,13 +9,16 @@ Submodules
|
||||
telegram.audio
|
||||
telegram.base
|
||||
telegram.bot
|
||||
telegram.updater
|
||||
telegram.dispatcher
|
||||
telegram.jobqueue
|
||||
telegram.chataction
|
||||
telegram.contact
|
||||
telegram.document
|
||||
telegram.emoji
|
||||
telegram.error
|
||||
telegram.forcereply
|
||||
telegram.groupchat
|
||||
telegram.chat
|
||||
telegram.inputfile
|
||||
telegram.location
|
||||
telegram.message
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
telegram.updater module
|
||||
=========================
|
||||
|
||||
.. automodule:: telegram.updater
|
||||
:members:
|
||||
:undoc-members:
|
||||
:show-inheritance:
|
||||
@@ -0,0 +1,116 @@
|
||||
CC0 1.0 Universal
|
||||
|
||||
Statement of Purpose
|
||||
|
||||
The laws of most jurisdictions throughout the world automatically confer
|
||||
exclusive Copyright and Related Rights (defined below) upon the creator and
|
||||
subsequent owner(s) (each and all, an "owner") of an original work of
|
||||
authorship and/or a database (each, a "Work").
|
||||
|
||||
Certain owners wish to permanently relinquish those rights to a Work for the
|
||||
purpose of contributing to a commons of creative, cultural and scientific
|
||||
works ("Commons") that the public can reliably and without fear of later
|
||||
claims of infringement build upon, modify, incorporate in other works, reuse
|
||||
and redistribute as freely as possible in any form whatsoever and for any
|
||||
purposes, including without limitation commercial purposes. These owners may
|
||||
contribute to the Commons to promote the ideal of a free culture and the
|
||||
further production of creative, cultural and scientific works, or to gain
|
||||
reputation or greater distribution for their Work in part through the use and
|
||||
efforts of others.
|
||||
|
||||
For these and/or other purposes and motivations, and without any expectation
|
||||
of additional consideration or compensation, the person associating CC0 with a
|
||||
Work (the "Affirmer"), to the extent that he or she is an owner of Copyright
|
||||
and Related Rights in the Work, voluntarily elects to apply CC0 to the Work
|
||||
and publicly distribute the Work under its terms, with knowledge of his or her
|
||||
Copyright and Related Rights in the Work and the meaning and intended legal
|
||||
effect of CC0 on those rights.
|
||||
|
||||
1. Copyright and Related Rights. A Work made available under CC0 may be
|
||||
protected by copyright and related or neighboring rights ("Copyright and
|
||||
Related Rights"). Copyright and Related Rights include, but are not limited
|
||||
to, the following:
|
||||
|
||||
i. the right to reproduce, adapt, distribute, perform, display, communicate,
|
||||
and translate a Work;
|
||||
|
||||
ii. moral rights retained by the original author(s) and/or performer(s);
|
||||
|
||||
iii. publicity and privacy rights pertaining to a person's image or likeness
|
||||
depicted in a Work;
|
||||
|
||||
iv. rights protecting against unfair competition in regards to a Work,
|
||||
subject to the limitations in paragraph 4(a), below;
|
||||
|
||||
v. rights protecting the extraction, dissemination, use and reuse of data in
|
||||
a Work;
|
||||
|
||||
vi. database rights (such as those arising under Directive 96/9/EC of the
|
||||
European Parliament and of the Council of 11 March 1996 on the legal
|
||||
protection of databases, and under any national implementation thereof,
|
||||
including any amended or successor version of such directive); and
|
||||
|
||||
vii. other similar, equivalent or corresponding rights throughout the world
|
||||
based on applicable law or treaty, and any national implementations thereof.
|
||||
|
||||
2. Waiver. To the greatest extent permitted by, but not in contravention of,
|
||||
applicable law, Affirmer hereby overtly, fully, permanently, irrevocably and
|
||||
unconditionally waives, abandons, and surrenders all of Affirmer's Copyright
|
||||
and Related Rights and associated claims and causes of action, whether now
|
||||
known or unknown (including existing as well as future claims and causes of
|
||||
action), in the Work (i) in all territories worldwide, (ii) for the maximum
|
||||
duration provided by applicable law or treaty (including future time
|
||||
extensions), (iii) in any current or future medium and for any number of
|
||||
copies, and (iv) for any purpose whatsoever, including without limitation
|
||||
commercial, advertising or promotional purposes (the "Waiver"). Affirmer makes
|
||||
the Waiver for the benefit of each member of the public at large and to the
|
||||
detriment of Affirmer's heirs and successors, fully intending that such Waiver
|
||||
shall not be subject to revocation, rescission, cancellation, termination, or
|
||||
any other legal or equitable action to disrupt the quiet enjoyment of the Work
|
||||
by the public as contemplated by Affirmer's express Statement of Purpose.
|
||||
|
||||
3. Public License Fallback. Should any part of the Waiver for any reason be
|
||||
judged legally invalid or ineffective under applicable law, then the Waiver
|
||||
shall be preserved to the maximum extent permitted taking into account
|
||||
Affirmer's express Statement of Purpose. In addition, to the extent the Waiver
|
||||
is so judged Affirmer hereby grants to each affected person a royalty-free,
|
||||
non transferable, non sublicensable, non exclusive, irrevocable and
|
||||
unconditional license to exercise Affirmer's Copyright and Related Rights in
|
||||
the Work (i) in all territories worldwide, (ii) for the maximum duration
|
||||
provided by applicable law or treaty (including future time extensions), (iii)
|
||||
in any current or future medium and for any number of copies, and (iv) for any
|
||||
purpose whatsoever, including without limitation commercial, advertising or
|
||||
promotional purposes (the "License"). The License shall be deemed effective as
|
||||
of the date CC0 was applied by Affirmer to the Work. Should any part of the
|
||||
License for any reason be judged legally invalid or ineffective under
|
||||
applicable law, such partial invalidity or ineffectiveness shall not
|
||||
invalidate the remainder of the License, and in such case Affirmer hereby
|
||||
affirms that he or she will not (i) exercise any of his or her remaining
|
||||
Copyright and Related Rights in the Work or (ii) assert any associated claims
|
||||
and causes of action with respect to the Work, in either case contrary to
|
||||
Affirmer's express Statement of Purpose.
|
||||
|
||||
4. Limitations and Disclaimers.
|
||||
|
||||
a. No trademark or patent rights held by Affirmer are waived, abandoned,
|
||||
surrendered, licensed or otherwise affected by this document.
|
||||
|
||||
b. Affirmer offers the Work as-is and makes no representations or warranties
|
||||
of any kind concerning the Work, express, implied, statutory or otherwise,
|
||||
including without limitation warranties of title, merchantability, fitness
|
||||
for a particular purpose, non infringement, or the absence of latent or
|
||||
other defects, accuracy, or the present or absence of errors, whether or not
|
||||
discoverable, all to the greatest extent permissible under applicable law.
|
||||
|
||||
c. Affirmer disclaims responsibility for clearing rights of other persons
|
||||
that may apply to the Work or any use thereof, including without limitation
|
||||
any person's Copyright and Related Rights in the Work. Further, Affirmer
|
||||
disclaims responsibility for obtaining any necessary consents, permissions
|
||||
or other rights required for any use of the Work.
|
||||
|
||||
d. Affirmer understands and acknowledges that Creative Commons is not a
|
||||
party to this document and has no duty or obligation with respect to this
|
||||
CC0 or use of the Work.
|
||||
|
||||
For more information, please see
|
||||
<http://creativecommons.org/publicdomain/zero/1.0/>
|
||||
@@ -0,0 +1,177 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
#
|
||||
# Example Bot to show some of the functionality of the library
|
||||
# This program is dedicated to the public domain under the CC0 license.
|
||||
|
||||
"""
|
||||
This Bot uses the Updater class to handle the bot.
|
||||
|
||||
First, a few handler functions are defined. Then, those functions are passed to
|
||||
the Dispatcher and registered at their respective places.
|
||||
Then, the bot is started and the CLI-Loop is entered, where all text inputs are
|
||||
inserted into the update queue for the bot to handle.
|
||||
|
||||
Usage:
|
||||
Repeats messages with a delay.
|
||||
Reply to last chat from the command line by typing "/reply <text>"
|
||||
Type 'stop' on the command line to stop the bot.
|
||||
"""
|
||||
|
||||
from telegram import Updater
|
||||
from telegram.dispatcher import run_async
|
||||
from time import sleep
|
||||
import logging
|
||||
|
||||
# Enable Logging
|
||||
logging.basicConfig(
|
||||
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
|
||||
level=logging.INFO)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# We use this var to save the last chat id, so we can reply to it
|
||||
last_chat_id = 0
|
||||
|
||||
|
||||
# Define a few (command) handlers. These usually take the two arguments bot and
|
||||
# update. Error handlers also receive the raised TelegramError object in error.
|
||||
def start(bot, update):
|
||||
""" Answer in Telegram """
|
||||
bot.sendMessage(update.message.chat_id, text='Hi!')
|
||||
|
||||
|
||||
def help(bot, update):
|
||||
""" Answer in Telegram """
|
||||
bot.sendMessage(update.message.chat_id, text='Help!')
|
||||
|
||||
|
||||
def any_message(bot, update):
|
||||
""" Print to console """
|
||||
|
||||
# Save last chat_id to use in reply handler
|
||||
global last_chat_id
|
||||
last_chat_id = update.message.chat_id
|
||||
|
||||
logger.info("New message\nFrom: %s\nchat_id: %d\nText: %s" %
|
||||
(update.message.from_user,
|
||||
update.message.chat_id,
|
||||
update.message.text))
|
||||
|
||||
|
||||
def unknown_command(bot, update):
|
||||
""" Answer in Telegram """
|
||||
bot.sendMessage(update.message.chat_id, text='Command not recognized!')
|
||||
|
||||
|
||||
@run_async
|
||||
def message(bot, update, **kwargs):
|
||||
"""
|
||||
Example for an asynchronous handler. It's not guaranteed that replies will
|
||||
be in order when using @run_async. Also, you have to include **kwargs in
|
||||
your parameter list. The kwargs contain all optional parameters that are
|
||||
"""
|
||||
|
||||
sleep(2) # IO-heavy operation here
|
||||
bot.sendMessage(update.message.chat_id, text='Echo: %s' %
|
||||
update.message.text)
|
||||
|
||||
|
||||
# These handlers are for updates of type str. We use them to react to inputs
|
||||
# on the command line interface
|
||||
def cli_reply(bot, update, args):
|
||||
"""
|
||||
For any update of type telegram.Update or str that contains a command, you
|
||||
can get the argument list by appending args to the function parameters.
|
||||
Here, we reply to the last active chat with the text after the command.
|
||||
"""
|
||||
if last_chat_id is not 0:
|
||||
bot.sendMessage(chat_id=last_chat_id, text=' '.join(args))
|
||||
|
||||
|
||||
def cli_noncommand(bot, update, update_queue):
|
||||
"""
|
||||
You can also get the update queue as an argument in any handler by
|
||||
appending it to the argument list. Be careful with this though.
|
||||
Here, we put the input string back into the queue, but as a command.
|
||||
|
||||
To learn more about those optional handler parameters, read:
|
||||
http://python-telegram-bot.readthedocs.org/en/latest/telegram.dispatcher.html
|
||||
"""
|
||||
update_queue.put('/%s' % update)
|
||||
|
||||
|
||||
def unknown_cli_command(bot, update):
|
||||
logger.warn("Command not found: %s" % update)
|
||||
|
||||
|
||||
def error(bot, update, error):
|
||||
""" Print error to console """
|
||||
logger.warn('Update %s caused error %s' % (update, error))
|
||||
|
||||
|
||||
def main():
|
||||
# Create the EventHandler and pass it your bot's token.
|
||||
token = 'TOKEN'
|
||||
updater = Updater(token, workers=10)
|
||||
|
||||
# Get the dispatcher to register handlers
|
||||
dp = updater.dispatcher
|
||||
|
||||
# This is how we add handlers for Telegram messages
|
||||
dp.addTelegramCommandHandler("start", start)
|
||||
dp.addTelegramCommandHandler("help", help)
|
||||
dp.addUnknownTelegramCommandHandler(unknown_command)
|
||||
# Message handlers only receive updates that don't contain commands
|
||||
dp.addTelegramMessageHandler(message)
|
||||
# Regex handlers will receive all updates on which their regex matches
|
||||
dp.addTelegramRegexHandler('.*', any_message)
|
||||
|
||||
# String handlers work pretty much the same
|
||||
dp.addStringCommandHandler('reply', cli_reply)
|
||||
dp.addUnknownStringCommandHandler(unknown_cli_command)
|
||||
dp.addStringRegexHandler('[^/].*', cli_noncommand)
|
||||
|
||||
# All TelegramErrors are caught for you and delivered to the error
|
||||
# handler(s). Other types of Errors are not caught.
|
||||
dp.addErrorHandler(error)
|
||||
|
||||
# Start the Bot and store the update Queue, so we can insert updates
|
||||
update_queue = updater.start_polling(poll_interval=0.1, timeout=10)
|
||||
|
||||
'''
|
||||
# Alternatively, run with webhook:
|
||||
updater.bot.setWebhook(webhook_url='https://example.com/%s' % token,
|
||||
certificate=open('cert.pem', 'rb'))
|
||||
|
||||
update_queue = updater.start_webhook('0.0.0.0',
|
||||
443,
|
||||
url_path=token,
|
||||
cert='cert.pem',
|
||||
key='key.key')
|
||||
|
||||
# Or, if SSL is handled by a reverse proxy, the webhook URL is already set
|
||||
# and the reverse proxy is configured to deliver directly to port 6000:
|
||||
|
||||
update_queue = updater.start_webhook('0.0.0.0',
|
||||
6000)
|
||||
'''
|
||||
|
||||
# Start CLI-Loop
|
||||
while True:
|
||||
try:
|
||||
text = raw_input()
|
||||
except NameError:
|
||||
text = input()
|
||||
|
||||
# Gracefully stop the event handler
|
||||
if text == 'stop':
|
||||
updater.stop()
|
||||
break
|
||||
|
||||
# else, put the text into the update queue to be handled by our handlers
|
||||
elif len(text) > 0:
|
||||
update_queue.put(text)
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -1,66 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
#
|
||||
# Simple Bot to reply Telegram messages
|
||||
# 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/].
|
||||
|
||||
|
||||
import logging
|
||||
import telegram
|
||||
|
||||
|
||||
LAST_UPDATE_ID = None
|
||||
|
||||
|
||||
def main():
|
||||
global LAST_UPDATE_ID
|
||||
|
||||
logging.basicConfig(
|
||||
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
|
||||
|
||||
# Telegram Bot Authorization Token
|
||||
bot = telegram.Bot('TOKEN')
|
||||
|
||||
# This will be our global variable to keep the latest update_id when requesting
|
||||
# for updates. It starts with the latest update_id if available.
|
||||
try:
|
||||
LAST_UPDATE_ID = bot.getUpdates()[-1].update_id
|
||||
except IndexError:
|
||||
LAST_UPDATE_ID = None
|
||||
|
||||
while True:
|
||||
echo(bot)
|
||||
|
||||
|
||||
def echo(bot):
|
||||
global LAST_UPDATE_ID
|
||||
|
||||
# Request updates after the last updated_id
|
||||
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
|
||||
reply_text = update.message.text
|
||||
|
||||
if (reply_text):
|
||||
# Reply the message
|
||||
bot.sendMessage(chat_id=chat_id,
|
||||
text=reply_text)
|
||||
|
||||
# Updates global offset to get the new updates
|
||||
LAST_UPDATE_ID = update.update_id + 1
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,75 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
#
|
||||
# Simple Bot to reply to Telegram messages
|
||||
# This program is dedicated to the public domain under the CC0 license.
|
||||
|
||||
"""
|
||||
This Bot uses the Updater class to handle the bot.
|
||||
|
||||
First, a few handler functions are defined. Then, those functions are passed to
|
||||
the Dispatcher and registered at their respective places.
|
||||
Then, the bot is started and runs until we press Ctrl-C on the command line.
|
||||
|
||||
Usage:
|
||||
Basic Echobot example, repeats messages.
|
||||
Press Ctrl-C on the command line or send a signal to the process to stop the
|
||||
bot.
|
||||
"""
|
||||
|
||||
from telegram import Updater
|
||||
import logging
|
||||
|
||||
# Enable logging
|
||||
logging.basicConfig(
|
||||
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
|
||||
level=logging.INFO)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
# Define a few command handlers. These usually take the two arguments bot and
|
||||
# update. Error handlers also receive the raised TelegramError object in error.
|
||||
def start(bot, update):
|
||||
bot.sendMessage(update.message.chat_id, text='Hi!')
|
||||
|
||||
|
||||
def help(bot, update):
|
||||
bot.sendMessage(update.message.chat_id, text='Help!')
|
||||
|
||||
|
||||
def echo(bot, update):
|
||||
bot.sendMessage(update.message.chat_id, text=update.message.text)
|
||||
|
||||
|
||||
def error(bot, update, error):
|
||||
logger.warn('Update "%s" caused error "%s"' % (update, error))
|
||||
|
||||
|
||||
def main():
|
||||
# Create the EventHandler and pass it your bot's token.
|
||||
updater = Updater("TOKEN")
|
||||
|
||||
# Get the dispatcher to register handlers
|
||||
dp = updater.dispatcher
|
||||
|
||||
# on different commands - answer in Telegram
|
||||
dp.addTelegramCommandHandler("start", start)
|
||||
dp.addTelegramCommandHandler("help", help)
|
||||
|
||||
# on noncommand i.e message - echo the message on Telegram
|
||||
dp.addTelegramMessageHandler(echo)
|
||||
|
||||
# log all errors
|
||||
dp.addErrorHandler(error)
|
||||
|
||||
# Start the Bot
|
||||
updater.start_polling()
|
||||
|
||||
# Run the bot until the you presses Ctrl-C or the process receives SIGINT,
|
||||
# SIGTERM or SIGABRT. This should be used most of the time, since
|
||||
# start_polling() is non-blocking and will stop the bot gracefully.
|
||||
updater.idle()
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,66 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
#
|
||||
# Simple Bot to reply to Telegram messages
|
||||
# This program is dedicated to the public domain under the CC0 license.
|
||||
|
||||
import logging
|
||||
import telegram
|
||||
from time import sleep
|
||||
|
||||
try:
|
||||
from urllib.error import URLError
|
||||
except ImportError:
|
||||
from urllib2 import URLError # python 2
|
||||
|
||||
|
||||
def main():
|
||||
# Telegram Bot Authorization Token
|
||||
bot = telegram.Bot('TOKEN')
|
||||
|
||||
# get the first pending update_id, this is so we can skip over it in case
|
||||
# we get an "Unauthorized" exception.
|
||||
try:
|
||||
update_id = bot.getUpdates()[0].update_id
|
||||
except IndexError:
|
||||
update_id = None
|
||||
|
||||
logging.basicConfig(
|
||||
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
|
||||
|
||||
while True:
|
||||
try:
|
||||
update_id = echo(bot, update_id)
|
||||
except telegram.TelegramError as e:
|
||||
# These are network problems with Telegram.
|
||||
if e.message in ("Bad Gateway", "Timed out"):
|
||||
sleep(1)
|
||||
elif e.message == "Unauthorized":
|
||||
# The user has removed or blocked the bot.
|
||||
update_id += 1
|
||||
else:
|
||||
raise e
|
||||
except URLError as e:
|
||||
# These are network problems on our end.
|
||||
sleep(1)
|
||||
|
||||
|
||||
def echo(bot, update_id):
|
||||
|
||||
# Request updates after the last update_id
|
||||
for update in bot.getUpdates(offset=update_id, timeout=10):
|
||||
# chat_id is required to reply to any message
|
||||
chat_id = update.message.chat_id
|
||||
update_id = update.update_id + 1
|
||||
message = update.message.text
|
||||
|
||||
if message:
|
||||
# Reply to the message
|
||||
bot.sendMessage(chat_id=chat_id,
|
||||
text=message)
|
||||
|
||||
return update_id
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -2,23 +2,7 @@
|
||||
# encoding: utf-8
|
||||
#
|
||||
# Robô Ed Telegram Bot
|
||||
# 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/].
|
||||
|
||||
|
||||
__author__ = 'leandrotoledodesouza@gmail.com'
|
||||
# This program is dedicated to the public domain under the CC0 license.
|
||||
|
||||
import logging
|
||||
import telegram
|
||||
@@ -0,0 +1,91 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
#
|
||||
# Simple Bot to send timed Telegram messages
|
||||
# This program is dedicated to the public domain under the CC0 license.
|
||||
|
||||
"""
|
||||
This Bot uses the Updater class to handle the bot and the JobQueue to send
|
||||
timed messages.
|
||||
|
||||
First, a few handler functions are defined. Then, those functions are passed to
|
||||
the Dispatcher and registered at their respective places.
|
||||
Then, the bot is started and runs until we press Ctrl-C on the command line.
|
||||
|
||||
Usage:
|
||||
Basic Alarm Bot example, sends a message after a set time.
|
||||
Press Ctrl-C on the command line or send a signal to the process to stop the
|
||||
bot.
|
||||
"""
|
||||
|
||||
from telegram import Updater
|
||||
import logging
|
||||
|
||||
# Enable logging
|
||||
logging.basicConfig(
|
||||
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
|
||||
level=logging.INFO)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
job_queue = None
|
||||
|
||||
|
||||
# Define a few command handlers. These usually take the two arguments bot and
|
||||
# update. Error handlers also receive the raised TelegramError object in error.
|
||||
def start(bot, update):
|
||||
bot.sendMessage(update.message.chat_id, text='Hi! Use /set <seconds> to '
|
||||
'set a timer')
|
||||
|
||||
|
||||
def set(bot, update, args):
|
||||
""" Adds a job to the queue """
|
||||
chat_id = update.message.chat_id
|
||||
try:
|
||||
# args[0] should contain the time for the timer in seconds
|
||||
due = int(args[0])
|
||||
|
||||
def alarm(bot):
|
||||
""" Inner function to send the alarm message """
|
||||
bot.sendMessage(chat_id, text='Beep!')
|
||||
|
||||
# Add job to queue
|
||||
job_queue.put(alarm, due, repeat=False)
|
||||
bot.sendMessage(chat_id, text='Timer successfully set!')
|
||||
|
||||
except IndexError:
|
||||
bot.sendMessage(chat_id, text='Usage: /set <seconds>')
|
||||
except ValueError:
|
||||
bot.sendMessage(chat_id, text='Usage: /set <seconds>')
|
||||
|
||||
|
||||
def error(bot, update, error):
|
||||
logger.warn('Update "%s" caused error "%s"' % (update, error))
|
||||
|
||||
|
||||
def main():
|
||||
global job_queue
|
||||
|
||||
updater = Updater("148447715:AAFj2qskb3_sMMzlDhgTuoP7VAABNHpT0BU")
|
||||
job_queue = updater.job_queue
|
||||
|
||||
# Get the dispatcher to register handlers
|
||||
dp = updater.dispatcher
|
||||
|
||||
# on different commands - answer in Telegram
|
||||
dp.addTelegramCommandHandler("start", start)
|
||||
dp.addTelegramCommandHandler("help", start)
|
||||
dp.addTelegramCommandHandler("set", set)
|
||||
|
||||
# log all errors
|
||||
dp.addErrorHandler(error)
|
||||
|
||||
# Start the Bot
|
||||
updater.start_polling()
|
||||
|
||||
# Block until the you presses Ctrl-C or the process receives SIGINT,
|
||||
# SIGTERM or SIGABRT. This should be used most of the time, since
|
||||
# start_polling() is non-blocking and will stop the bot gracefully.
|
||||
updater.idle()
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -13,17 +13,29 @@ 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.9',
|
||||
version='3.2.0',
|
||||
author='Leandro Toledo',
|
||||
author_email='leandrotoledodesouza@gmail.com',
|
||||
author_email='devs@python-telegram-bot.org',
|
||||
license='LGPLv3',
|
||||
url='https://github.com/leandrotoledo/python-telegram-bot',
|
||||
url='https://github.com/python-telegram-bot/python-telegram-bot',
|
||||
keywords='python telegram bot api wrapper',
|
||||
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',
|
||||
|
||||
+14
-10
@@ -1,7 +1,8 @@
|
||||
#!/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>
|
||||
# Copyright (C) 2015-2016
|
||||
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Lesser Public License as published by
|
||||
@@ -18,12 +19,12 @@
|
||||
|
||||
"""A library that provides a Python interface to the Telegram Bot API"""
|
||||
|
||||
__author__ = 'leandrotoledodesouza@gmail.com'
|
||||
__version__ = '2.8.7'
|
||||
__author__ = 'devs@python-telegram-bot.org'
|
||||
__version__ = '3.2.0'
|
||||
|
||||
from .base import TelegramObject
|
||||
from .user import User
|
||||
from .groupchat import GroupChat
|
||||
from .chat import Chat
|
||||
from .photosize import PhotoSize
|
||||
from .audio import Audio
|
||||
from .voice import Voice
|
||||
@@ -47,10 +48,13 @@ from .parsemode import ParseMode
|
||||
from .message import Message
|
||||
from .update import Update
|
||||
from .bot import Bot
|
||||
from .dispatcher import Dispatcher
|
||||
from .jobqueue import JobQueue
|
||||
from .updater import Updater
|
||||
|
||||
__all__ = ['Bot', 'Emoji', 'TelegramError', 'InputFile', 'ReplyMarkup',
|
||||
'ForceReply', 'ReplyKeyboardHide', 'ReplyKeyboardMarkup',
|
||||
'UserProfilePhotos', 'ChatAction', 'Location', 'Contact',
|
||||
'Video', 'Sticker', 'Document', 'File', 'Audio', 'PhotoSize',
|
||||
'GroupChat', 'Update', 'ParseMode', 'Message', 'User',
|
||||
'TelegramObject', 'NullHandler', 'Voice']
|
||||
__all__ = ['Bot', 'Updater', 'Dispatcher', 'Emoji', 'TelegramError',
|
||||
'InputFile', 'ReplyMarkup', 'ForceReply', 'ReplyKeyboardHide',
|
||||
'ReplyKeyboardMarkup', 'UserProfilePhotos', 'ChatAction',
|
||||
'Location', 'Contact', 'Video', 'Sticker', 'Document', 'File',
|
||||
'Audio', 'PhotoSize', 'Chat', 'Update', 'ParseMode', 'Message',
|
||||
'User', 'TelegramObject', 'NullHandler', 'Voice', 'JobQueue']
|
||||
|
||||
+2
-1
@@ -1,7 +1,8 @@
|
||||
#!/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>
|
||||
# Copyright (C) 2015-2016
|
||||
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Lesser Public License as published by
|
||||
|
||||
+2
-1
@@ -1,7 +1,8 @@
|
||||
#!/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>
|
||||
# Copyright (C) 2015-2016
|
||||
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Lesser Public License as published by
|
||||
|
||||
+30
-16
@@ -2,7 +2,8 @@
|
||||
# pylint: disable=E0611,E0213,E1102,C0103,E1101,W0613,R0913,R0904
|
||||
#
|
||||
# A library that provides a Python interface to the Telegram Bot API
|
||||
# Copyright (C) 2015 Leandro Toledo de Souza <leandrotoeldodesouza@gmail.com>
|
||||
# Copyright (C) 2015-2016
|
||||
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Lesser Public License as published by
|
||||
@@ -52,7 +53,7 @@ class Bot(TelegramObject):
|
||||
def __init__(self,
|
||||
token,
|
||||
base_url=None):
|
||||
self.token = token
|
||||
self.token = self._valid_token(token)
|
||||
|
||||
if base_url is None:
|
||||
self.base_url = 'https://api.telegram.org/bot%s' % self.token
|
||||
@@ -191,8 +192,7 @@ class Bot(TelegramObject):
|
||||
|
||||
Args:
|
||||
chat_id:
|
||||
Unique identifier for the message recipient - telegram.User or
|
||||
telegram.GroupChat id.
|
||||
Unique identifier for the message recipient - telegram.Chat id.
|
||||
parse_mode:
|
||||
Send Markdown, if you want Telegram apps to show bold, italic and
|
||||
inline URLs in your bot's message. For the moment, only Telegram
|
||||
@@ -234,10 +234,10 @@ class Bot(TelegramObject):
|
||||
|
||||
Args:
|
||||
chat_id:
|
||||
Unique identifier for the message recipient - User or GroupChat id.
|
||||
Unique identifier for the message recipient - Chat id.
|
||||
from_chat_id:
|
||||
Unique identifier for the chat where the original message was sent
|
||||
- User or GroupChat id.
|
||||
- Chat id.
|
||||
message_id:
|
||||
Unique message identifier.
|
||||
|
||||
@@ -268,7 +268,7 @@ class Bot(TelegramObject):
|
||||
|
||||
Args:
|
||||
chat_id:
|
||||
Unique identifier for the message recipient - User or GroupChat id.
|
||||
Unique identifier for the message recipient - Chat id.
|
||||
photo:
|
||||
Photo to send. You can either pass a file_id as String to resend a
|
||||
photo that is already on the Telegram servers, or upload a new
|
||||
@@ -319,7 +319,7 @@ class Bot(TelegramObject):
|
||||
|
||||
Args:
|
||||
chat_id:
|
||||
Unique identifier for the message recipient - User or GroupChat id.
|
||||
Unique identifier for the message recipient - Chat id.
|
||||
audio:
|
||||
Audio file to send. You can either pass a file_id as String to
|
||||
resend an audio that is already on the Telegram servers, or upload
|
||||
@@ -366,7 +366,7 @@ class Bot(TelegramObject):
|
||||
|
||||
Args:
|
||||
chat_id:
|
||||
Unique identifier for the message recipient - User or GroupChat id.
|
||||
Unique identifier for the message recipient - Chat id.
|
||||
document:
|
||||
File to send. You can either pass a file_id as String to resend a
|
||||
file that is already on the Telegram servers, or upload a new file
|
||||
@@ -405,7 +405,7 @@ class Bot(TelegramObject):
|
||||
|
||||
Args:
|
||||
chat_id:
|
||||
Unique identifier for the message recipient - User or GroupChat id.
|
||||
Unique identifier for the message recipient - Chat id.
|
||||
sticker:
|
||||
Sticker to send. You can either pass a file_id as String to resend
|
||||
a sticker that is already on the Telegram servers, or upload a new
|
||||
@@ -441,7 +441,7 @@ class Bot(TelegramObject):
|
||||
|
||||
Args:
|
||||
chat_id:
|
||||
Unique identifier for the message recipient - User or GroupChat id.
|
||||
Unique identifier for the message recipient - Chat id.
|
||||
video:
|
||||
Video to send. You can either pass a file_id as String to resend a
|
||||
video that is already on the Telegram servers, or upload a new
|
||||
@@ -490,7 +490,7 @@ class Bot(TelegramObject):
|
||||
|
||||
Args:
|
||||
chat_id:
|
||||
Unique identifier for the message recipient - User or GroupChat id.
|
||||
Unique identifier for the message recipient - Chat id.
|
||||
voice:
|
||||
Audio file to send. You can either pass a file_id as String to
|
||||
resend an audio that is already on the Telegram servers, or upload
|
||||
@@ -529,7 +529,7 @@ class Bot(TelegramObject):
|
||||
|
||||
Args:
|
||||
chat_id:
|
||||
Unique identifier for the message recipient - User or GroupChat id.
|
||||
Unique identifier for the message recipient - Chat id.
|
||||
latitude:
|
||||
Latitude of location.
|
||||
longitude:
|
||||
@@ -565,7 +565,7 @@ class Bot(TelegramObject):
|
||||
|
||||
Args:
|
||||
chat_id:
|
||||
Unique identifier for the message recipient - User or GroupChat id.
|
||||
Unique identifier for the message recipient - Chat id.
|
||||
action:
|
||||
Type of action to broadcast. Choose one, depending on what the user
|
||||
is about to receive:
|
||||
@@ -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(
|
||||
@@ -739,3 +745,11 @@ class Bot(TelegramObject):
|
||||
def __reduce__(self):
|
||||
return (self.__class__, (self.token,
|
||||
self.base_url.replace(self.token, '')))
|
||||
|
||||
@staticmethod
|
||||
def _valid_token(token):
|
||||
"""a very basic validation on token"""
|
||||
left, sep, _right = token.partition(':')
|
||||
if (not sep) or (not left.isdigit()) or (len(left) < 3):
|
||||
raise TelegramError('Invalid token')
|
||||
return token
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
# pylint: disable=C0103,W0622
|
||||
#
|
||||
# A library that provides a Python interface to the Telegram Bot API
|
||||
# Copyright (C) 2015 Leandro Toledo de Souza <leandrotoeldodesouza@gmail.com>
|
||||
# Copyright (C) 2015-2016
|
||||
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Lesser Public License as published by
|
||||
@@ -17,22 +18,25 @@
|
||||
# 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 GroupChat"""
|
||||
"""This module contains a object that represents a Telegram Chat"""
|
||||
|
||||
from telegram import TelegramObject
|
||||
|
||||
|
||||
class GroupChat(TelegramObject):
|
||||
"""This object represents a Telegram GroupChat.
|
||||
class Chat(TelegramObject):
|
||||
"""This object represents a Telegram Chat.
|
||||
|
||||
Attributes:
|
||||
id (int):
|
||||
title (str):
|
||||
type (str):
|
||||
type (str): Can be 'private', 'group', 'supergroup' or 'channel'
|
||||
title (str): Title, for channels and group chats
|
||||
username (str): Username, for private chats and channels if available
|
||||
first_name (str): First name of the other party in a private chat
|
||||
last_name (str): Last name of the other party in a private chat
|
||||
|
||||
Args:
|
||||
id (int):
|
||||
title (str):
|
||||
type (str):
|
||||
**kwargs: Arbitrary keyword arguments.
|
||||
|
||||
Keyword Args:
|
||||
@@ -41,24 +45,27 @@ class GroupChat(TelegramObject):
|
||||
|
||||
def __init__(self,
|
||||
id,
|
||||
title,
|
||||
type,
|
||||
**kwargs):
|
||||
# Required
|
||||
self.id = int(id)
|
||||
self.title = title
|
||||
self.type = type
|
||||
# Optionals
|
||||
self.type = kwargs.get('type', '')
|
||||
self.title = kwargs.get('title', '')
|
||||
self.username = kwargs.get('username', '')
|
||||
self.first_name = kwargs.get('first_name', '')
|
||||
self.last_name = kwargs.get('last_name', '')
|
||||
|
||||
@staticmethod
|
||||
def de_json(data):
|
||||
"""
|
||||
Args:
|
||||
data (str):
|
||||
data (dict):
|
||||
|
||||
Returns:
|
||||
telegram.GroupChat:
|
||||
telegram.Chat:
|
||||
"""
|
||||
if not data:
|
||||
return None
|
||||
|
||||
return GroupChat(**data)
|
||||
return Chat(**data)
|
||||
@@ -2,7 +2,8 @@
|
||||
# pylint: disable=R0903
|
||||
#
|
||||
# A library that provides a Python interface to the Telegram Bot API
|
||||
# Copyright (C) 2015 Leandro Toledo de Souza <leandrotoeldodesouza@gmail.com>
|
||||
# Copyright (C) 2015-2016
|
||||
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Lesser Public License as published by
|
||||
|
||||
+2
-1
@@ -1,7 +1,8 @@
|
||||
#!/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>
|
||||
# Copyright (C) 2015-2016
|
||||
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Lesser Public License as published by
|
||||
|
||||
@@ -0,0 +1,637 @@
|
||||
#!/usr/bin/env python
|
||||
#
|
||||
# A library that provides a Python interface to the Telegram Bot API
|
||||
# Copyright (C) 2015-2016
|
||||
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Lesser 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 Lesser Public License for more details.
|
||||
#
|
||||
# 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 the Dispatcher class.
|
||||
"""
|
||||
import logging
|
||||
from functools import wraps
|
||||
from inspect import getargspec
|
||||
from threading import Thread, BoundedSemaphore, Lock
|
||||
from re import match
|
||||
|
||||
from telegram import (TelegramError, Update, NullHandler)
|
||||
|
||||
H = NullHandler()
|
||||
logging.getLogger(__name__).addHandler(H)
|
||||
|
||||
semaphore = None
|
||||
running_async = 0
|
||||
async_lock = Lock()
|
||||
|
||||
|
||||
def run_async(func):
|
||||
"""
|
||||
Function decorator that will run the function in a new thread. A function
|
||||
decorated with this will have to include **kwargs in their parameter list,
|
||||
which will contain all optional parameters.
|
||||
|
||||
Args:
|
||||
func (function): The function to run in the thread.
|
||||
|
||||
Returns:
|
||||
function:
|
||||
"""
|
||||
|
||||
@wraps(func)
|
||||
def pooled(*pargs, **kwargs):
|
||||
"""
|
||||
A wrapper to run a thread in a thread pool
|
||||
"""
|
||||
global running_async, async_lock
|
||||
result = func(*pargs, **kwargs)
|
||||
semaphore.release()
|
||||
with async_lock:
|
||||
running_async -= 1
|
||||
return result
|
||||
|
||||
@wraps(func)
|
||||
def async_func(*pargs, **kwargs):
|
||||
"""
|
||||
A wrapper to run a function in a thread
|
||||
"""
|
||||
global running_async, async_lock
|
||||
thread = Thread(target=pooled, args=pargs, kwargs=kwargs)
|
||||
semaphore.acquire()
|
||||
with async_lock:
|
||||
running_async += 1
|
||||
thread.start()
|
||||
return thread
|
||||
|
||||
return async_func
|
||||
|
||||
|
||||
class Dispatcher:
|
||||
"""
|
||||
This class dispatches all kinds of updates to its registered handlers.
|
||||
A handler is a function that usually takes the following parameters
|
||||
|
||||
bot:
|
||||
The telegram.Bot instance that received the message
|
||||
update:
|
||||
The update that should be handled by the handler
|
||||
|
||||
Error handlers take an additional parameter
|
||||
|
||||
error:
|
||||
The TelegramError instance that was raised during processing the
|
||||
update
|
||||
|
||||
All handlers, except error handlers, can also request more information by
|
||||
appending one or more of the following arguments in their argument list for
|
||||
convenience
|
||||
|
||||
update_queue:
|
||||
The Queue instance which contains all new updates and is
|
||||
processed by the Dispatcher. Be careful with this - you might
|
||||
create an infinite loop.
|
||||
args:
|
||||
If the update is an instance str or telegram.Update, this will be
|
||||
a list that contains the content of the message split on spaces,
|
||||
except the first word (usually the command).
|
||||
Example: '/add item1 item2 item3' -> ['item1', 'item2', 'item3']
|
||||
For other updates, args will be None
|
||||
|
||||
For regex-based handlers, you can also request information about the match.
|
||||
For all other handlers, these will be None
|
||||
|
||||
groups:
|
||||
A tuple that contains the result of
|
||||
re.match(matcher, ...).groups()
|
||||
groupdict:
|
||||
A dictionary that contains the result of
|
||||
re.match(matcher, ...).groupdict()
|
||||
|
||||
Args:
|
||||
bot (telegram.Bot): The bot object that should be passed to the
|
||||
handlers
|
||||
update_queue (queue.Queue): The synchronized queue that will
|
||||
contain the updates.
|
||||
"""
|
||||
def __init__(self, bot, update_queue, workers=4):
|
||||
self.bot = bot
|
||||
self.update_queue = update_queue
|
||||
self.telegram_message_handlers = []
|
||||
self.telegram_command_handlers = {}
|
||||
self.telegram_regex_handlers = {}
|
||||
self.string_regex_handlers = {}
|
||||
self.string_command_handlers = {}
|
||||
self.type_handlers = {}
|
||||
self.unknown_telegram_command_handlers = []
|
||||
self.unknown_string_command_handlers = []
|
||||
self.error_handlers = []
|
||||
self.logger = logging.getLogger(__name__)
|
||||
self.running = False
|
||||
self.__lock = Lock()
|
||||
|
||||
global semaphore
|
||||
if not semaphore:
|
||||
semaphore = BoundedSemaphore(value=workers)
|
||||
else:
|
||||
self.logger.info("Semaphore already initialized, skipping.")
|
||||
|
||||
class _Stop(object):
|
||||
"""
|
||||
A class which objects can be passed into the update queue to stop the
|
||||
thread
|
||||
"""
|
||||
pass
|
||||
|
||||
def start(self):
|
||||
"""
|
||||
Thread target of thread 'dispatcher'. Runs in background and processes
|
||||
the update queue.
|
||||
"""
|
||||
|
||||
self.__lock.acquire()
|
||||
if not self.running:
|
||||
self.running = True
|
||||
self.__lock.release()
|
||||
self.logger.info('Dispatcher thread started')
|
||||
|
||||
while True:
|
||||
update = None
|
||||
|
||||
try:
|
||||
# Pop update from update queue.
|
||||
# Blocks if no updates are available.
|
||||
update = self.update_queue.get()
|
||||
|
||||
if type(update) is self._Stop:
|
||||
break
|
||||
|
||||
self.processUpdate(update)
|
||||
self.logger.debug('Processed Update: %s' % update)
|
||||
|
||||
# Dispatch any errors
|
||||
except TelegramError as te:
|
||||
self.logger.warn("Error was raised while processing "
|
||||
"Update.")
|
||||
self.dispatchError(update, te)
|
||||
|
||||
# All other errors should not stop the thread, just print them
|
||||
except:
|
||||
self.logger.exception("An uncaught error was raised while "
|
||||
"processing an update")
|
||||
else:
|
||||
self.__lock.release()
|
||||
self.logger.info('Dispatcher thread stopped')
|
||||
|
||||
def stop(self):
|
||||
"""
|
||||
Stops the thread
|
||||
"""
|
||||
with self.__lock:
|
||||
if self.running:
|
||||
self.running = False
|
||||
self.update_queue.put(self._Stop())
|
||||
|
||||
def processUpdate(self, update):
|
||||
"""
|
||||
Processes a single update.
|
||||
|
||||
Args:
|
||||
update (any):
|
||||
"""
|
||||
|
||||
handled = False
|
||||
|
||||
# Custom type handlers
|
||||
for t in self.type_handlers:
|
||||
if isinstance(update, t):
|
||||
self.dispatchType(update)
|
||||
handled = True
|
||||
|
||||
# string update
|
||||
if type(update) is str and update.startswith('/'):
|
||||
self.dispatchStringCommand(update)
|
||||
handled = True
|
||||
elif type(update) is str:
|
||||
self.dispatchRegex(update)
|
||||
handled = True
|
||||
|
||||
# An error happened while polling
|
||||
if isinstance(update, TelegramError):
|
||||
self.dispatchError(None, update)
|
||||
handled = True
|
||||
|
||||
# Telegram update (regex)
|
||||
if isinstance(update, Update):
|
||||
self.dispatchRegex(update)
|
||||
handled = True
|
||||
|
||||
# Telegram update (command)
|
||||
if isinstance(update, Update) \
|
||||
and update.message.text.startswith('/'):
|
||||
self.dispatchTelegramCommand(update)
|
||||
handled = True
|
||||
|
||||
# Telegram update (message)
|
||||
elif isinstance(update, Update):
|
||||
self.dispatchTelegramMessage(update)
|
||||
handled = True
|
||||
|
||||
# Update not recognized
|
||||
if not handled:
|
||||
self.dispatchError(update, TelegramError(
|
||||
"Received update of unknown type %s" % type(update)))
|
||||
|
||||
# Add Handlers
|
||||
def addTelegramMessageHandler(self, handler):
|
||||
"""
|
||||
Registers a message handler in the Dispatcher.
|
||||
|
||||
Args:
|
||||
handler (function): A function that takes (Bot, Update, *args) as
|
||||
arguments.
|
||||
"""
|
||||
|
||||
self.telegram_message_handlers.append(handler)
|
||||
|
||||
def addTelegramCommandHandler(self, command, handler):
|
||||
"""
|
||||
Registers a command handler in the Dispatcher.
|
||||
|
||||
Args:
|
||||
command (str): The command keyword that this handler should be
|
||||
listening to.
|
||||
handler (function): A function that takes (Bot, Update, *args) as
|
||||
arguments.
|
||||
"""
|
||||
|
||||
if command not in self.telegram_command_handlers:
|
||||
self.telegram_command_handlers[command] = []
|
||||
|
||||
self.telegram_command_handlers[command].append(handler)
|
||||
|
||||
def addTelegramRegexHandler(self, matcher, handler):
|
||||
"""
|
||||
Registers a regex handler in the Dispatcher. If handlers will be
|
||||
called if re.match(matcher, update.message.text) is True.
|
||||
|
||||
Args:
|
||||
matcher (str/__Regex): A regex string or compiled regex object that
|
||||
matches on messages that handler should be listening to
|
||||
handler (function): A function that takes (Bot, Update, *args) as
|
||||
arguments.
|
||||
"""
|
||||
|
||||
if matcher not in self.telegram_regex_handlers:
|
||||
self.telegram_regex_handlers[matcher] = []
|
||||
|
||||
self.telegram_regex_handlers[matcher].append(handler)
|
||||
|
||||
def addStringCommandHandler(self, command, handler):
|
||||
"""
|
||||
Registers a string-command handler in the Dispatcher.
|
||||
|
||||
Args:
|
||||
command (str): The command keyword that this handler should be
|
||||
listening to.
|
||||
handler (function): A function that takes (Bot, str, *args) as
|
||||
arguments.
|
||||
"""
|
||||
|
||||
if command not in self.string_command_handlers:
|
||||
self.string_command_handlers[command] = []
|
||||
|
||||
self.string_command_handlers[command].append(handler)
|
||||
|
||||
def addStringRegexHandler(self, matcher, handler):
|
||||
"""
|
||||
Registers a regex handler in the Dispatcher. If handlers will be
|
||||
called if re.match(matcher, string) is True.
|
||||
|
||||
Args:
|
||||
matcher (str/__Regex): A regex string or compiled regex object that
|
||||
matches on the string input that handler should be listening to
|
||||
handler (function): A function that takes (Bot, Update, *args) as
|
||||
arguments.
|
||||
"""
|
||||
|
||||
if matcher not in self.string_regex_handlers:
|
||||
self.string_regex_handlers[matcher] = []
|
||||
|
||||
self.string_regex_handlers[matcher].append(handler)
|
||||
|
||||
def addUnknownTelegramCommandHandler(self, handler):
|
||||
"""
|
||||
Registers a command handler in the Dispatcher, that will receive all
|
||||
commands that have no associated handler.
|
||||
|
||||
Args:
|
||||
handler (function): A function that takes (Bot, Update, *args) as
|
||||
arguments.
|
||||
"""
|
||||
|
||||
self.unknown_telegram_command_handlers.append(handler)
|
||||
|
||||
def addUnknownStringCommandHandler(self, handler):
|
||||
"""
|
||||
Registers a string-command handler in the Dispatcher, that will
|
||||
receive all commands that have no associated handler.
|
||||
|
||||
Args:
|
||||
handler (function): A function that takes (Bot, str, *args) as
|
||||
arguments.
|
||||
"""
|
||||
|
||||
self.unknown_string_command_handlers.append(handler)
|
||||
|
||||
def addErrorHandler(self, handler):
|
||||
"""
|
||||
Registers an error handler in the Dispatcher.
|
||||
|
||||
Args:
|
||||
handler (function): A function that takes (Bot, TelegramError) as
|
||||
arguments.
|
||||
"""
|
||||
|
||||
self.error_handlers.append(handler)
|
||||
|
||||
def addTypeHandler(self, the_type, handler):
|
||||
"""
|
||||
Registers a type handler in the Dispatcher. This allows you to send
|
||||
any type of object into the update queue.
|
||||
|
||||
Args:
|
||||
the_type (type): The type this handler should listen to
|
||||
handler (function): A function that takes (Bot, type, *args) as
|
||||
arguments.
|
||||
"""
|
||||
|
||||
if the_type not in self.type_handlers:
|
||||
self.type_handlers[the_type] = []
|
||||
|
||||
self.type_handlers[the_type].append(handler)
|
||||
|
||||
# Remove Handlers
|
||||
def removeTelegramMessageHandler(self, handler):
|
||||
"""
|
||||
De-registers a message handler.
|
||||
|
||||
Args:
|
||||
handler (any):
|
||||
"""
|
||||
|
||||
if handler in self.telegram_message_handlers:
|
||||
self.telegram_message_handlers.remove(handler)
|
||||
|
||||
def removeTelegramCommandHandler(self, command, handler):
|
||||
"""
|
||||
De-registers a command handler.
|
||||
|
||||
Args:
|
||||
command (str): The command
|
||||
handler (any):
|
||||
"""
|
||||
|
||||
if command in self.telegram_command_handlers \
|
||||
and handler in self.telegram_command_handlers[command]:
|
||||
self.telegram_command_handlers[command].remove(handler)
|
||||
|
||||
def removeTelegramRegexHandler(self, matcher, handler):
|
||||
"""
|
||||
De-registers a regex handler.
|
||||
|
||||
Args:
|
||||
matcher (str/__Regex): The regex matcher object or string
|
||||
handler (any):
|
||||
"""
|
||||
|
||||
if matcher in self.telegram_regex_handlers \
|
||||
and handler in self.telegram_regex_handlers[matcher]:
|
||||
self.telegram_regex_handlers[matcher].remove(handler)
|
||||
|
||||
def removeStringCommandHandler(self, command, handler):
|
||||
"""
|
||||
De-registers a string-command handler.
|
||||
|
||||
Args:
|
||||
command (str): The command
|
||||
handler (any):
|
||||
"""
|
||||
|
||||
if command in self.string_command_handlers \
|
||||
and handler in self.string_command_handlers[command]:
|
||||
self.string_command_handlers[command].remove(handler)
|
||||
|
||||
def removeStringRegexHandler(self, matcher, handler):
|
||||
"""
|
||||
De-registers a regex handler.
|
||||
|
||||
Args:
|
||||
matcher (str/__Regex): The regex matcher object or string
|
||||
handler (any):
|
||||
"""
|
||||
|
||||
if matcher in self.string_regex_handlers \
|
||||
and handler in self.string_regex_handlers[matcher]:
|
||||
self.string_regex_handlers[matcher].remove(handler)
|
||||
|
||||
def removeUnknownTelegramCommandHandler(self, handler):
|
||||
"""
|
||||
De-registers an unknown-command handler.
|
||||
|
||||
Args:
|
||||
handler (any):
|
||||
"""
|
||||
|
||||
if handler in self.unknown_telegram_command_handlers:
|
||||
self.unknown_telegram_command_handlers.remove(handler)
|
||||
|
||||
def removeUnknownStringCommandHandler(self, handler):
|
||||
"""
|
||||
De-registers an unknown-command handler.
|
||||
|
||||
Args:
|
||||
handler (any):
|
||||
"""
|
||||
|
||||
if handler in self.unknown_string_command_handlers:
|
||||
self.unknown_string_command_handlers.remove(handler)
|
||||
|
||||
def removeErrorHandler(self, handler):
|
||||
"""
|
||||
De-registers an error handler.
|
||||
|
||||
Args:
|
||||
handler (any):
|
||||
"""
|
||||
|
||||
if handler in self.error_handlers:
|
||||
self.error_handlers.remove(handler)
|
||||
|
||||
def removeTypeHandler(self, the_type, handler):
|
||||
"""
|
||||
De-registers a type handler.
|
||||
|
||||
Args:
|
||||
handler (any):
|
||||
"""
|
||||
|
||||
if the_type in self.type_handlers \
|
||||
and handler in self.type_handlers[the_type]:
|
||||
self.type_handlers[the_type].remove(handler)
|
||||
|
||||
def dispatchTelegramCommand(self, update):
|
||||
"""
|
||||
Dispatches an update that contains a command.
|
||||
|
||||
Args:
|
||||
command (str): The command keyword
|
||||
update (telegram.Update): The Telegram update that contains the
|
||||
command
|
||||
"""
|
||||
|
||||
command = update.message.text.split(' ')[0][1:].split('@')[0]
|
||||
|
||||
if command in self.telegram_command_handlers:
|
||||
self.dispatchTo(self.telegram_command_handlers[command], update)
|
||||
else:
|
||||
self.dispatchTo(self.unknown_telegram_command_handlers, update)
|
||||
|
||||
def dispatchRegex(self, update):
|
||||
"""
|
||||
Dispatches an update to all string or telegram regex handlers that
|
||||
match the string/message content.
|
||||
|
||||
Args:
|
||||
update (str, Update): The update that should be checked for matches
|
||||
"""
|
||||
|
||||
if isinstance(update, Update):
|
||||
handlers = self.telegram_regex_handlers
|
||||
to_match = update.message.text
|
||||
elif isinstance(update, str):
|
||||
handlers = self.string_regex_handlers
|
||||
to_match = update
|
||||
|
||||
for matcher in handlers:
|
||||
m = match(matcher, to_match)
|
||||
if m:
|
||||
for handler in handlers[matcher]:
|
||||
self.call_handler(handler,
|
||||
update,
|
||||
groups=m.groups(),
|
||||
groupdict=m.groupdict())
|
||||
|
||||
def dispatchStringCommand(self, update):
|
||||
"""
|
||||
Dispatches a string-update that contains a command.
|
||||
|
||||
Args:
|
||||
update (str): The string input
|
||||
"""
|
||||
|
||||
command = update.split(' ')[0][1:]
|
||||
|
||||
if command in self.string_command_handlers:
|
||||
self.dispatchTo(self.string_command_handlers[command], update)
|
||||
else:
|
||||
self.dispatchTo(self.unknown_string_command_handlers, update)
|
||||
|
||||
def dispatchType(self, update):
|
||||
"""
|
||||
Dispatches an update of any type.
|
||||
|
||||
Args:
|
||||
update (any): The update
|
||||
"""
|
||||
|
||||
for t in self.type_handlers:
|
||||
if isinstance(update, t):
|
||||
self.dispatchTo(self.type_handlers[t], update)
|
||||
|
||||
def dispatchTelegramMessage(self, update):
|
||||
"""
|
||||
Dispatches an update that contains a regular message.
|
||||
|
||||
Args:
|
||||
update (telegram.Update): The Telegram update that contains the
|
||||
message.
|
||||
"""
|
||||
|
||||
self.dispatchTo(self.telegram_message_handlers, update)
|
||||
|
||||
def dispatchError(self, update, error):
|
||||
"""
|
||||
Dispatches an error.
|
||||
|
||||
Args:
|
||||
update (any): The pdate that caused the error
|
||||
error (telegram.TelegramError): The Telegram error that was raised.
|
||||
"""
|
||||
|
||||
for handler in self.error_handlers:
|
||||
handler(self.bot, update, error)
|
||||
|
||||
def dispatchTo(self, handlers, update, **kwargs):
|
||||
"""
|
||||
Dispatches an update to a list of handlers.
|
||||
|
||||
Args:
|
||||
handlers (list): A list of handler-functions.
|
||||
update (any): The update to be dispatched
|
||||
"""
|
||||
|
||||
for handler in handlers:
|
||||
self.call_handler(handler, update, **kwargs)
|
||||
|
||||
def call_handler(self, handler, update, **kwargs):
|
||||
"""
|
||||
Calls an update handler. Checks the handler for keyword arguments and
|
||||
fills them, if possible.
|
||||
|
||||
Args:
|
||||
handler (function): An update handler function
|
||||
update (any): An update
|
||||
"""
|
||||
|
||||
target_kwargs = {}
|
||||
fargs = getargspec(handler).args
|
||||
|
||||
'''
|
||||
async handlers will receive all optional arguments, since we can't
|
||||
their argument list.
|
||||
'''
|
||||
|
||||
is_async = 'pargs' == getargspec(handler).varargs
|
||||
|
||||
if is_async or 'update_queue' in fargs:
|
||||
target_kwargs['update_queue'] = self.update_queue
|
||||
|
||||
if is_async or 'args' in fargs:
|
||||
if isinstance(update, Update):
|
||||
args = update.message.text.split(' ')[1:]
|
||||
elif isinstance(update, str):
|
||||
args = update.split(' ')[1:]
|
||||
else:
|
||||
args = None
|
||||
|
||||
target_kwargs['args'] = args
|
||||
|
||||
if is_async or 'groups' in fargs:
|
||||
target_kwargs['groups'] = kwargs.get('groups', None)
|
||||
|
||||
if is_async or 'groupdict' in fargs:
|
||||
target_kwargs['groupdict'] = kwargs.get('groupdict', None)
|
||||
|
||||
handler(self.bot, update, **target_kwargs)
|
||||
@@ -1,7 +1,8 @@
|
||||
#!/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>
|
||||
# Copyright (C) 2015-2016
|
||||
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Lesser Public License as published by
|
||||
|
||||
+2
-1
@@ -3,7 +3,8 @@
|
||||
# pylint: disable=C0103,C0301,R0903
|
||||
#
|
||||
# A library that provides a Python interface to the Telegram Bot API
|
||||
# Copyright (C) 2015 Leandro Toledo de Souza <leandrotoeldodesouza@gmail.com>
|
||||
# Copyright (C) 2015-2016
|
||||
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Lesser Public License as published by
|
||||
|
||||
+28
-8
@@ -1,7 +1,8 @@
|
||||
#!/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>
|
||||
# Copyright (C) 2015-2016
|
||||
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Lesser Public License as published by
|
||||
@@ -18,7 +19,22 @@
|
||||
|
||||
"""This module contains a object that represents a Telegram Error"""
|
||||
|
||||
import re
|
||||
|
||||
def _lstrip_str(in_s, lstr):
|
||||
"""
|
||||
Args:
|
||||
in_s (str): in string
|
||||
lstr (str): substr to strip from left side
|
||||
|
||||
Returns:
|
||||
str:
|
||||
|
||||
"""
|
||||
if in_s.startswith(lstr):
|
||||
res = in_s[len(lstr):]
|
||||
else:
|
||||
res = in_s
|
||||
return res
|
||||
|
||||
|
||||
class TelegramError(Exception):
|
||||
@@ -26,16 +42,20 @@ class TelegramError(Exception):
|
||||
|
||||
def __init__(self, message):
|
||||
"""
|
||||
Args:
|
||||
message (str):
|
||||
|
||||
Returns:
|
||||
str:
|
||||
|
||||
"""
|
||||
super(TelegramError, self).__init__()
|
||||
|
||||
api_error = re.match(r'^Error: (?P<message>.*)', message)
|
||||
if api_error:
|
||||
self.message = api_error.group('message').capitalize()
|
||||
else:
|
||||
self.message = message
|
||||
msg = _lstrip_str(message, 'Error: ')
|
||||
msg = _lstrip_str(msg, '[Error]: ')
|
||||
if msg != message:
|
||||
# api_error - capitalize the msg...
|
||||
msg = msg.capitalize()
|
||||
self.message = msg
|
||||
|
||||
def __str__(self):
|
||||
return '%s' % (self.message)
|
||||
|
||||
+3
-2
@@ -1,7 +1,8 @@
|
||||
#!/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>
|
||||
# Copyright (C) 2015-2016
|
||||
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Lesser Public License as published by
|
||||
@@ -74,7 +75,7 @@ class File(TelegramObject):
|
||||
url = self.file_path
|
||||
|
||||
if custom_path:
|
||||
filename = basename(custom_path)
|
||||
filename = custom_path
|
||||
else:
|
||||
filename = basename(url)
|
||||
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
#!/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>
|
||||
# Copyright (C) 2015-2016
|
||||
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Lesser Public License as published by
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
# pylint: disable=W0622,E0611
|
||||
#
|
||||
# A library that provides a Python interface to the Telegram Bot API
|
||||
# Copyright (C) 2015 Leandro Toledo de Souza <leandrotoeldodesouza@gmail.com>
|
||||
# Copyright (C) 2015-2016
|
||||
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Lesser Public License as published by
|
||||
@@ -35,7 +36,7 @@ from telegram import TelegramError
|
||||
|
||||
DEFAULT_MIME_TYPE = 'application/octet-stream'
|
||||
USER_AGENT = 'Python Telegram Bot' \
|
||||
' (https://github.com/leandrotoledo/python-telegram-bot)'
|
||||
' (https://github.com/python-telegram-bot/python-telegram-bot)'
|
||||
|
||||
|
||||
class InputFile(object):
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
#!/usr/bin/env python
|
||||
#
|
||||
# A library that provides a Python interface to the Telegram Bot API
|
||||
# Copyright (C) 2015-2016
|
||||
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Lesser 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 Lesser Public License for more details.
|
||||
#
|
||||
# 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 the class JobQueue
|
||||
"""
|
||||
|
||||
import logging
|
||||
import time
|
||||
from threading import Thread, Lock
|
||||
|
||||
try:
|
||||
from queue import PriorityQueue
|
||||
except ImportError:
|
||||
from Queue import PriorityQueue
|
||||
|
||||
|
||||
class JobQueue(object):
|
||||
"""
|
||||
This class allows you to periodically perform tasks with the bot.
|
||||
|
||||
Attributes:
|
||||
tick_interval (float):
|
||||
queue (PriorityQueue):
|
||||
bot (Bot):
|
||||
running (bool):
|
||||
|
||||
Args:
|
||||
bot (Bot): The bot instance that should be passed to the jobs
|
||||
|
||||
Keyword Args:
|
||||
tick_interval (Optional[float]): The interval this queue should check
|
||||
the newest task in seconds. Defaults to 1.0
|
||||
"""
|
||||
|
||||
def __init__(self, bot, tick_interval=1.0):
|
||||
self.tick_interval = tick_interval
|
||||
self.queue = PriorityQueue()
|
||||
self.bot = bot
|
||||
self.logger = logging.getLogger(__name__)
|
||||
self.__lock = Lock()
|
||||
self.running = False
|
||||
|
||||
def put(self,
|
||||
run,
|
||||
interval,
|
||||
repeat=True,
|
||||
next_t=None,
|
||||
prevent_autostart=False):
|
||||
"""
|
||||
Queue a new job. If the JobQueue is not running, it will be started.
|
||||
|
||||
Args:
|
||||
run (function): A function that takes the parameter `bot`
|
||||
interval (float): The interval in seconds in which `run` should be
|
||||
executed
|
||||
repeat (Optional[bool]): If `False`, job will only be executed once
|
||||
next_t (Optional[float]): Time in seconds in which run should be
|
||||
executed first. Defaults to `interval`
|
||||
prevent_autostart (Optional[bool]): If `True`, the job queue will
|
||||
not be started automatically if it is not running.
|
||||
"""
|
||||
name = run.__name__
|
||||
|
||||
job = JobQueue.Job()
|
||||
job.run = run
|
||||
job.interval = interval
|
||||
job.name = name
|
||||
job.repeat = repeat
|
||||
|
||||
if next_t is None:
|
||||
next_t = interval
|
||||
|
||||
next_t += time.time()
|
||||
|
||||
self.logger.debug("Putting a %s with t=%f" % (job.name, next_t))
|
||||
self.queue.put((next_t, job))
|
||||
|
||||
if not self.running and not prevent_autostart:
|
||||
self.logger.info("Auto-starting JobQueue")
|
||||
self.start()
|
||||
|
||||
def tick(self):
|
||||
"""
|
||||
Run all jobs that are due and re-enqueue them with their interval
|
||||
"""
|
||||
now = time.time()
|
||||
|
||||
self.logger.debug("Ticking jobs with t=%f" % now)
|
||||
while not self.queue.empty():
|
||||
t, j = self.queue.queue[0]
|
||||
self.logger.debug("Peeked at %s with t=%f" % (j.name, t))
|
||||
|
||||
if t < now:
|
||||
self.queue.get()
|
||||
self.logger.info("Running job %s" % j.name)
|
||||
try:
|
||||
j.run(self.bot)
|
||||
except:
|
||||
self.logger.exception("An uncaught error was raised while "
|
||||
"executing job %s" % j.name)
|
||||
if j.repeat:
|
||||
self.put(j.run, j.interval)
|
||||
continue
|
||||
|
||||
self.logger.debug("Next task isn't due yet. Finished!")
|
||||
break
|
||||
|
||||
def start(self):
|
||||
"""
|
||||
Starts the job_queue thread.
|
||||
"""
|
||||
self.__lock.acquire()
|
||||
if not self.running:
|
||||
self.running = True
|
||||
self.__lock.release()
|
||||
job_queue_thread = Thread(target=self._start,
|
||||
name="job_queue")
|
||||
job_queue_thread.start()
|
||||
self.logger.info('Job Queue thread started')
|
||||
else:
|
||||
self.__lock.release()
|
||||
|
||||
def _start(self):
|
||||
"""
|
||||
Thread target of thread 'job_queue'. Runs in background and performs
|
||||
ticks on the job queue.
|
||||
"""
|
||||
while self.running:
|
||||
self.tick()
|
||||
time.sleep(self.tick_interval)
|
||||
|
||||
self.logger.info('Job Queue thread stopped')
|
||||
|
||||
def stop(self):
|
||||
"""
|
||||
Stops the thread
|
||||
"""
|
||||
with self.__lock:
|
||||
self.running = False
|
||||
|
||||
class Job(object):
|
||||
""" Inner class that represents a job """
|
||||
interval = None
|
||||
name = None
|
||||
repeat = None
|
||||
|
||||
def run(self):
|
||||
pass
|
||||
|
||||
def __lt__(self, other):
|
||||
return False
|
||||
@@ -1,7 +1,8 @@
|
||||
#!/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>
|
||||
# Copyright (C) 2015-2016
|
||||
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Lesser Public License as published by
|
||||
|
||||
+12
-8
@@ -2,7 +2,8 @@
|
||||
# pylint: disable=R0902,R0912,R0913
|
||||
#
|
||||
# A library that provides a Python interface to the Telegram Bot API
|
||||
# Copyright (C) 2015 Leandro Toledo de Souza <leandrotoeldodesouza@gmail.com>
|
||||
# Copyright (C) 2015-2016
|
||||
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Lesser Public License as published by
|
||||
@@ -22,7 +23,7 @@
|
||||
from datetime import datetime
|
||||
from time import mktime
|
||||
|
||||
from telegram import (Audio, Contact, Document, GroupChat, Location, PhotoSize,
|
||||
from telegram import (Audio, Contact, Document, Chat, Location, PhotoSize,
|
||||
Sticker, TelegramObject, User, Video, Voice)
|
||||
|
||||
|
||||
@@ -60,7 +61,7 @@ class Message(TelegramObject):
|
||||
message_id (int):
|
||||
from_user (:class:`telegram.User`):
|
||||
date (:class:`datetime.datetime`):
|
||||
chat (:class:`telegram.User` or :class:`telegram.GroupChat`):
|
||||
chat (:class:`telegram.Chat`):
|
||||
**kwargs: Arbitrary keyword arguments.
|
||||
|
||||
Keyword Args:
|
||||
@@ -116,6 +117,12 @@ class Message(TelegramObject):
|
||||
self.new_chat_photo = kwargs.get('new_chat_photo')
|
||||
self.delete_chat_photo = bool(kwargs.get('delete_chat_photo', False))
|
||||
self.group_chat_created = bool(kwargs.get('group_chat_created', False))
|
||||
self.supergroup_chat_created = bool(kwargs.get(
|
||||
'supergroup_chat_created', False))
|
||||
self.migrate_to_chat_id = int(kwargs.get('migrate_to_chat_id', 0))
|
||||
self.migrate_from_chat_id = int(kwargs.get('migrate_from_chat_id', 0))
|
||||
self.channel_chat_created = bool(kwargs.get('channel_chat_created',
|
||||
False))
|
||||
|
||||
@property
|
||||
def chat_id(self):
|
||||
@@ -126,7 +133,7 @@ class Message(TelegramObject):
|
||||
def de_json(data):
|
||||
"""
|
||||
Args:
|
||||
data (str):
|
||||
data (dict):
|
||||
|
||||
Returns:
|
||||
telegram.Message:
|
||||
@@ -136,10 +143,7 @@ class Message(TelegramObject):
|
||||
|
||||
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'))
|
||||
elif 'title' in data.get('chat', ''):
|
||||
data['chat'] = GroupChat.de_json(data.get('chat'))
|
||||
data['chat'] = Chat.de_json(data.get('chat'))
|
||||
data['forward_from'] = \
|
||||
User.de_json(data.get('forward_from'))
|
||||
data['forward_date'] = \
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
#!/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>
|
||||
# Copyright (C) 2015-2016
|
||||
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Lesser Public License as published by
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
# pylint: disable=R0903
|
||||
#
|
||||
# A library that provides a Python interface to the Telegram Bot API
|
||||
# Copyright (C) 2015 Leandro Toledo de Souza <leandrotoeldodesouza@gmail.com>
|
||||
# Copyright (C) 2015-2016
|
||||
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Lesser Public License as published by
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
#!/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>
|
||||
# Copyright (C) 2015-2016
|
||||
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Lesser Public License as published by
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
#!/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>
|
||||
# Copyright (C) 2015-2016
|
||||
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Lesser Public License as published by
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
#!/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>
|
||||
# Copyright (C) 2015-2016
|
||||
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Lesser Public License as published by
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
#!/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>
|
||||
# Copyright (C) 2015-2016
|
||||
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Lesser Public License as published by
|
||||
|
||||
+2
-1
@@ -1,7 +1,8 @@
|
||||
#!/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>
|
||||
# Copyright (C) 2015-2016
|
||||
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Lesser Public License as published by
|
||||
|
||||
+2
-1
@@ -1,7 +1,8 @@
|
||||
#!/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>
|
||||
# Copyright (C) 2015-2016
|
||||
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Lesser Public License as published by
|
||||
|
||||
@@ -0,0 +1,313 @@
|
||||
#!/usr/bin/env python
|
||||
#
|
||||
# A library that provides a Python interface to the Telegram Bot API
|
||||
# Copyright (C) 2015-2016
|
||||
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Lesser 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 Lesser Public License for more details.
|
||||
#
|
||||
# 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 the class Updater, which tries to make creating Telegram
|
||||
Bots intuitive!
|
||||
"""
|
||||
import logging
|
||||
import os
|
||||
import ssl
|
||||
from threading import Thread, Lock
|
||||
from time import sleep
|
||||
import subprocess
|
||||
from signal import signal, SIGINT, SIGTERM, SIGABRT
|
||||
from telegram import (Bot, TelegramError, dispatcher, Dispatcher,
|
||||
NullHandler, JobQueue)
|
||||
from telegram.utils.webhookhandler import (WebhookServer, WebhookHandler)
|
||||
|
||||
# Adjust for differences in Python versions
|
||||
try:
|
||||
from Queue import Queue
|
||||
except ImportError:
|
||||
from queue import Queue
|
||||
|
||||
try:
|
||||
from urllib2 import URLError
|
||||
except ImportError:
|
||||
from urllib.error import URLError
|
||||
|
||||
H = NullHandler()
|
||||
logging.getLogger(__name__).addHandler(H)
|
||||
|
||||
|
||||
class Updater:
|
||||
"""
|
||||
This class, which employs the Dispatcher class, provides a frontend to
|
||||
telegram.Bot to the programmer, so they can focus on coding the bot. It's
|
||||
purpose is to receive the updates from Telegram and to deliver them to said
|
||||
dispatcher. It also runs in a separate thread, so the user can interact
|
||||
with the bot, for example on the command line. The dispatcher supports
|
||||
handlers for different kinds of data: Updates from Telegram, basic text
|
||||
commands and even arbitrary types.
|
||||
The updater can be started as a polling service or, for production, use a
|
||||
webhook to receive updates. This is achieved using the WebhookServer and
|
||||
WebhookHandler classes.
|
||||
|
||||
|
||||
Attributes:
|
||||
|
||||
Args:
|
||||
token (Optional[str]): The bot's token given by the @BotFather
|
||||
base_url (Optional[str]):
|
||||
workers (Optional[int]): Amount of threads in the thread pool for
|
||||
functions decorated with @run_async
|
||||
bot (Optional[Bot]):
|
||||
|
||||
Raises:
|
||||
ValueError: If both `token` and `bot` are passed or none of them.
|
||||
"""
|
||||
|
||||
def __init__(self,
|
||||
token=None,
|
||||
base_url=None,
|
||||
workers=4,
|
||||
bot=None,
|
||||
job_queue_tick_interval=1.0):
|
||||
if (token is None) and (bot is None):
|
||||
raise ValueError('`token` or `bot` must be passed')
|
||||
if (token is not None) and (bot is not None):
|
||||
raise ValueError('`token` and `bot` are mutually exclusive')
|
||||
|
||||
if bot is not None:
|
||||
self.bot = bot
|
||||
else:
|
||||
self.bot = Bot(token, base_url)
|
||||
self.update_queue = Queue()
|
||||
self.job_queue = JobQueue(self.bot, job_queue_tick_interval)
|
||||
self.dispatcher = Dispatcher(self.bot, self.update_queue,
|
||||
workers=workers)
|
||||
self.last_update_id = 0
|
||||
self.logger = logging.getLogger(__name__)
|
||||
self.running = False
|
||||
self.is_idle = False
|
||||
self.httpd = None
|
||||
self.__lock = Lock()
|
||||
|
||||
def start_polling(self, poll_interval=0.0, timeout=10, network_delay=2):
|
||||
"""
|
||||
Starts polling updates from Telegram.
|
||||
|
||||
Args:
|
||||
poll_interval (Optional[float]): Time to wait between polling
|
||||
updates from Telegram in seconds. Default is 0.0
|
||||
timeout (Optional[float]): Passed to Bot.getUpdates
|
||||
network_delay (Optional[float]): Passed to Bot.getUpdates
|
||||
|
||||
Returns:
|
||||
Queue: The update queue that can be filled from the main thread
|
||||
"""
|
||||
|
||||
with self.__lock:
|
||||
if not self.running:
|
||||
self.running = True
|
||||
|
||||
# Create Thread objects
|
||||
dispatcher_thread = Thread(target=self.dispatcher.start,
|
||||
name="dispatcher")
|
||||
updater_thread = Thread(target=self._start_polling,
|
||||
name="updater",
|
||||
args=(poll_interval,
|
||||
timeout,
|
||||
network_delay))
|
||||
|
||||
# Start threads
|
||||
dispatcher_thread.start()
|
||||
updater_thread.start()
|
||||
|
||||
# Return the update queue so the main thread can insert updates
|
||||
return self.update_queue
|
||||
|
||||
def start_webhook(self,
|
||||
listen='127.0.0.1',
|
||||
port=80,
|
||||
url_path='',
|
||||
cert=None,
|
||||
key=None):
|
||||
"""
|
||||
Starts a small http server to listen for updates via webhook. If cert
|
||||
and key are not provided, the webhook will be started directly on
|
||||
http://listen:port/url_path, so SSL can be handled by another
|
||||
application. Else, the webhook will be started on
|
||||
https://listen:port/url_path
|
||||
|
||||
Args:
|
||||
listen (Optional[str]): IP-Address to listen on
|
||||
port (Optional[int]): Port the bot should be listening on
|
||||
url_path (Optional[str]): Path inside url
|
||||
cert (Optional[str]): Path to the SSL certificate file
|
||||
key (Optional[str]): Path to the SSL key file
|
||||
|
||||
Returns:
|
||||
Queue: The update queue that can be filled from the main thread
|
||||
"""
|
||||
|
||||
with self.__lock:
|
||||
if not self.running:
|
||||
self.running = True
|
||||
|
||||
# Create Thread objects
|
||||
dispatcher_thread = Thread(target=self.dispatcher.start,
|
||||
name="dispatcher")
|
||||
updater_thread = Thread(target=self._start_webhook,
|
||||
name="updater",
|
||||
args=(listen,
|
||||
port,
|
||||
url_path,
|
||||
cert,
|
||||
key))
|
||||
|
||||
# Start threads
|
||||
dispatcher_thread.start()
|
||||
updater_thread.start()
|
||||
|
||||
# Return the update queue so the main thread can insert updates
|
||||
return self.update_queue
|
||||
|
||||
def _start_polling(self, poll_interval, timeout, network_delay):
|
||||
"""
|
||||
Thread target of thread 'updater'. Runs in background, pulls
|
||||
updates from Telegram and inserts them in the update queue of the
|
||||
Dispatcher.
|
||||
"""
|
||||
|
||||
current_interval = poll_interval
|
||||
self.logger.info('Updater thread started')
|
||||
|
||||
# Remove webhook
|
||||
self.bot.setWebhook(webhook_url=None)
|
||||
|
||||
while self.running:
|
||||
try:
|
||||
updates = self.bot.getUpdates(self.last_update_id,
|
||||
timeout=timeout,
|
||||
network_delay=network_delay)
|
||||
if not self.running:
|
||||
if len(updates) > 0:
|
||||
self.logger.info('Updates ignored and will be pulled '
|
||||
'again on restart.')
|
||||
break
|
||||
|
||||
for update in updates:
|
||||
self.update_queue.put(update)
|
||||
self.last_update_id = update.update_id + 1
|
||||
current_interval = poll_interval
|
||||
|
||||
sleep(current_interval)
|
||||
except TelegramError as te:
|
||||
# Put the error into the update queue and let the Dispatcher
|
||||
# broadcast it
|
||||
self.update_queue.put(te)
|
||||
sleep(current_interval)
|
||||
|
||||
except URLError as e:
|
||||
self.logger.error("Error while getting Updates: %s" % e)
|
||||
# increase waiting times on subsequent errors up to 30secs
|
||||
if current_interval == 0:
|
||||
current_interval = 1
|
||||
elif current_interval < 30:
|
||||
current_interval += current_interval / 2
|
||||
elif current_interval > 30:
|
||||
current_interval = 30
|
||||
|
||||
self.logger.info('Updater thread stopped')
|
||||
|
||||
def _start_webhook(self, listen, port, url_path, cert, key):
|
||||
self.logger.info('Updater thread started')
|
||||
use_ssl = cert is not None and key is not None
|
||||
url_path = "/%s" % url_path
|
||||
|
||||
# Create and start server
|
||||
self.httpd = WebhookServer((listen, port), WebhookHandler,
|
||||
self.update_queue, url_path)
|
||||
|
||||
if use_ssl:
|
||||
# Check SSL-Certificate with openssl, if possible
|
||||
try:
|
||||
exit_code = subprocess.call(["openssl", "x509", "-text",
|
||||
"-noout", "-in", cert],
|
||||
stdout=open(os.devnull, 'wb'),
|
||||
stderr=subprocess.STDOUT)
|
||||
except OSError:
|
||||
exit_code = 0
|
||||
|
||||
if exit_code is 0:
|
||||
try:
|
||||
self.httpd.socket = ssl.wrap_socket(self.httpd.socket,
|
||||
certfile=cert,
|
||||
keyfile=key,
|
||||
server_side=True)
|
||||
except ssl.SSLError as error:
|
||||
raise TelegramError(str(error))
|
||||
else:
|
||||
raise TelegramError('SSL Certificate invalid')
|
||||
|
||||
self.httpd.serve_forever(poll_interval=1)
|
||||
self.logger.info('Updater thread stopped')
|
||||
|
||||
def stop(self):
|
||||
"""
|
||||
Stops the polling/webhook thread, the dispatcher and the job queue
|
||||
"""
|
||||
|
||||
self.job_queue.stop()
|
||||
with self.__lock:
|
||||
if self.running:
|
||||
self.running = False
|
||||
self.logger.info('Stopping Updater and Dispatcher...')
|
||||
self.logger.debug('This might take a long time if you set a '
|
||||
'high value as polling timeout.')
|
||||
|
||||
if self.httpd:
|
||||
self.logger.info(
|
||||
'Waiting for current webhook connection to be '
|
||||
'closed... Send a Telegram message to the bot to exit '
|
||||
'immediately.')
|
||||
self.httpd.shutdown()
|
||||
self.httpd = None
|
||||
|
||||
self.logger.debug("Requesting Dispatcher to stop...")
|
||||
self.dispatcher.stop()
|
||||
while dispatcher.running_async > 0:
|
||||
sleep(1)
|
||||
|
||||
self.logger.debug("Dispatcher stopped.")
|
||||
|
||||
def signal_handler(self, signum, frame):
|
||||
self.is_idle = False
|
||||
self.stop()
|
||||
|
||||
def idle(self, stop_signals=(SIGINT, SIGTERM, SIGABRT)):
|
||||
"""
|
||||
Blocks until one of the signals are received and stops the updater
|
||||
|
||||
Args:
|
||||
stop_signals: Iterable containing signals from the signal module
|
||||
that should be subscribed to. Updater.stop() will be called on
|
||||
receiving one of those signals. Defaults to (SIGINT, SIGTERM,
|
||||
SIGABRT)
|
||||
"""
|
||||
for sig in stop_signals:
|
||||
signal(sig, self.signal_handler)
|
||||
|
||||
self.is_idle = True
|
||||
|
||||
while self.is_idle:
|
||||
sleep(1)
|
||||
+2
-1
@@ -2,7 +2,8 @@
|
||||
# pylint: disable=C0103,W0622
|
||||
#
|
||||
# A library that provides a Python interface to the Telegram Bot API
|
||||
# Copyright (C) 2015 Leandro Toledo de Souza <leandrotoeldodesouza@gmail.com>
|
||||
# Copyright (C) 2015-2016
|
||||
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Lesser Public License as published by
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
#!/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>
|
||||
# Copyright (C) 2015-2016
|
||||
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Lesser Public License as published by
|
||||
|
||||
+58
-31
@@ -2,7 +2,8 @@
|
||||
# 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>
|
||||
# Copyright (C) 2015-2016
|
||||
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Lesser Public License as published by
|
||||
@@ -19,7 +20,9 @@
|
||||
|
||||
"""This module contains methods to make POST and GET requests"""
|
||||
|
||||
import functools
|
||||
import json
|
||||
import socket
|
||||
from ssl import SSLError
|
||||
|
||||
try:
|
||||
@@ -44,7 +47,11 @@ def _parse(json_data):
|
||||
Returns:
|
||||
A JSON parsed as Python dict with results.
|
||||
"""
|
||||
data = json.loads(json_data.decode())
|
||||
decoded_s = json_data.decode('utf-8')
|
||||
try:
|
||||
data = json.loads(decoded_s)
|
||||
except ValueError:
|
||||
raise TelegramError('Invalid server response')
|
||||
|
||||
if not data.get('ok') and data.get('description'):
|
||||
return data['description']
|
||||
@@ -52,6 +59,34 @@ def _parse(json_data):
|
||||
return data['result']
|
||||
|
||||
|
||||
def _try_except_req(func):
|
||||
"""Decorator for requests to handle known exceptions"""
|
||||
@functools.wraps(func)
|
||||
def decorator(*args, **kwargs):
|
||||
try:
|
||||
return func(*args, **kwargs)
|
||||
except HTTPError as error:
|
||||
if error.getcode() == 403:
|
||||
raise TelegramError('Unauthorized')
|
||||
if error.getcode() == 502:
|
||||
raise TelegramError('Bad Gateway')
|
||||
|
||||
try:
|
||||
message = _parse(error.read())
|
||||
except ValueError:
|
||||
message = 'Unknown HTTPError {0}'.format(error.getcode())
|
||||
|
||||
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 decorator
|
||||
|
||||
|
||||
@_try_except_req
|
||||
def get(url):
|
||||
"""Request an URL.
|
||||
Args:
|
||||
@@ -66,55 +101,47 @@ def get(url):
|
||||
return _parse(result)
|
||||
|
||||
|
||||
@_try_except_req
|
||||
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 one second to the timeout of urlopen to allow data to be transferred
|
||||
# over the network.
|
||||
# Add time to the timeout of urlopen to allow data to be transferred over
|
||||
# the network.
|
||||
if 'timeout' in data:
|
||||
timeout = data['timeout'] + 1.
|
||||
timeout = data['timeout'] + network_delay
|
||||
else:
|
||||
timeout = None
|
||||
|
||||
try:
|
||||
if InputFile.is_inputfile(data):
|
||||
data = InputFile(data)
|
||||
request = Request(url,
|
||||
data=data.to_form(),
|
||||
headers=data.headers)
|
||||
else:
|
||||
data = json.dumps(data)
|
||||
request = Request(url,
|
||||
data=data.encode(),
|
||||
headers={'Content-Type': 'application/json'})
|
||||
if InputFile.is_inputfile(data):
|
||||
data = InputFile(data)
|
||||
request = Request(url,
|
||||
data=data.to_form(),
|
||||
headers=data.headers)
|
||||
else:
|
||||
data = json.dumps(data)
|
||||
request = Request(url,
|
||||
data=data.encode(),
|
||||
headers={'Content-Type': 'application/json'})
|
||||
|
||||
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 as error:
|
||||
if "The read operation timed out" == error.message:
|
||||
raise TelegramError("Timed out")
|
||||
|
||||
raise TelegramError(error.message)
|
||||
result = urlopen(request, timeout=timeout).read()
|
||||
return _parse(result)
|
||||
|
||||
|
||||
@_try_except_req
|
||||
def download(url,
|
||||
filename):
|
||||
"""Download a file by its URL.
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
import logging
|
||||
|
||||
from telegram import Update, NullHandler
|
||||
from future.utils import bytes_to_native_str as n
|
||||
from threading import Lock
|
||||
import json
|
||||
try:
|
||||
import BaseHTTPServer
|
||||
except ImportError:
|
||||
import http.server as BaseHTTPServer
|
||||
|
||||
|
||||
H = NullHandler()
|
||||
logging.getLogger(__name__).addHandler(H)
|
||||
|
||||
|
||||
class WebhookServer(BaseHTTPServer.HTTPServer, object):
|
||||
def __init__(self, server_address, RequestHandlerClass, update_queue,
|
||||
webhook_path):
|
||||
super(WebhookServer, self).__init__(server_address,
|
||||
RequestHandlerClass)
|
||||
self.logger = logging.getLogger(__name__)
|
||||
self.update_queue = update_queue
|
||||
self.webhook_path = webhook_path
|
||||
self.is_running = False
|
||||
self.server_lock = Lock()
|
||||
self.shutdown_lock = Lock()
|
||||
|
||||
def serve_forever(self, poll_interval=0.5):
|
||||
with self.server_lock:
|
||||
self.is_running = True
|
||||
self.logger.info("Webhook Server started.")
|
||||
super(WebhookServer, self).serve_forever(poll_interval)
|
||||
self.logger.info("Webhook Server stopped.")
|
||||
|
||||
def shutdown(self):
|
||||
with self.shutdown_lock:
|
||||
if not self.is_running:
|
||||
self.logger.warn("Webhook Server already stopped.")
|
||||
return
|
||||
else:
|
||||
super(WebhookServer, self).shutdown()
|
||||
self.is_running = False
|
||||
|
||||
|
||||
# WebhookHandler, process webhook calls
|
||||
# Based on: https://github.com/eternnoir/pyTelegramBotAPI/blob/master/
|
||||
# examples/webhook_examples/webhook_cpython_echo_bot.py
|
||||
class WebhookHandler(BaseHTTPServer.BaseHTTPRequestHandler, object):
|
||||
server_version = "WebhookHandler/1.0"
|
||||
|
||||
def __init__(self, request, client_address, server):
|
||||
self.logger = logging.getLogger(__name__)
|
||||
super(WebhookHandler, self).__init__(request, client_address, server)
|
||||
|
||||
def do_HEAD(self):
|
||||
self.send_response(200)
|
||||
self.end_headers()
|
||||
|
||||
def do_GET(self):
|
||||
self.send_response(200)
|
||||
self.end_headers()
|
||||
|
||||
def do_POST(self):
|
||||
self.logger.debug("Webhook triggered")
|
||||
if self.path == self.server.webhook_path and \
|
||||
'content-type' in self.headers and \
|
||||
'content-length' in self.headers and \
|
||||
self.headers['content-type'] == 'application/json':
|
||||
json_string = \
|
||||
n(self.rfile.read(int(self.headers['content-length'])))
|
||||
|
||||
self.send_response(200)
|
||||
self.end_headers()
|
||||
|
||||
self.logger.debug("Webhook received data: " + json_string)
|
||||
|
||||
update = Update.de_json(json.loads(json_string))
|
||||
self.logger.info("Received Update with ID %d on Webhook" %
|
||||
update.update_id)
|
||||
self.server.update_queue.put(update)
|
||||
|
||||
else:
|
||||
self.send_error(403)
|
||||
self.end_headers()
|
||||
+2
-1
@@ -1,7 +1,8 @@
|
||||
#!/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>
|
||||
# Copyright (C) 2015-2016
|
||||
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Lesser Public License as published by
|
||||
|
||||
+2
-1
@@ -1,7 +1,8 @@
|
||||
#!/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>
|
||||
# Copyright (C) 2015-2016
|
||||
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Lesser Public License as published by
|
||||
|
||||
+2
-1
@@ -1,7 +1,8 @@
|
||||
#!/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>
|
||||
# Copyright (C) 2015-2016
|
||||
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
||||
#
|
||||
# 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
|
||||
|
||||
+2
-1
@@ -1,7 +1,8 @@
|
||||
#!/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>
|
||||
# Copyright (C) 2015-2016
|
||||
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
||||
#
|
||||
# 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
|
||||
|
||||
+37
-3
@@ -2,7 +2,8 @@
|
||||
# encoding: utf-8
|
||||
#
|
||||
# A library that provides a Python interface to the Telegram Bot API
|
||||
# Copyright (C) 2015 Leandro Toledo de Souza <leandrotoeldodesouza@gmail.com>
|
||||
# Copyright (C) 2015-2016
|
||||
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
||||
#
|
||||
# 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
|
||||
@@ -20,9 +21,14 @@
|
||||
"""This module contains a object that represents Tests for Telegram Bot"""
|
||||
|
||||
import os
|
||||
import unittest
|
||||
from datetime import datetime
|
||||
import sys
|
||||
|
||||
if sys.version_info[0:2] == (2, 6):
|
||||
import unittest2 as unittest
|
||||
else:
|
||||
import unittest
|
||||
|
||||
sys.path.append('.')
|
||||
|
||||
import telegram
|
||||
@@ -135,7 +141,35 @@ class BotTest(BaseTest, unittest.TestCase):
|
||||
upf = self._bot.getUserProfilePhotos(user_id=self._chat_id)
|
||||
|
||||
self.assertTrue(self.is_json(upf.to_json()))
|
||||
self.assertEqual(upf.photos[0][0].file_size, 6547)
|
||||
self.assertEqual(upf.photos[0][0].file_size, 12421)
|
||||
|
||||
def _test_invalid_token(self, token):
|
||||
print('Testing invalid token: {0}'.format(token))
|
||||
self.assertRaisesRegexp(telegram.TelegramError, 'Invalid token', telegram.Bot, token)
|
||||
|
||||
def testInvalidToken1(self):
|
||||
self._test_invalid_token('123')
|
||||
|
||||
def testInvalidToken2(self):
|
||||
self._test_invalid_token('12a:')
|
||||
|
||||
def testInvalidToken3(self):
|
||||
self._test_invalid_token('12:')
|
||||
|
||||
def testUnauthToken(self):
|
||||
print('Testing unauthorized token')
|
||||
with self.assertRaisesRegexp(telegram.TelegramError, 'Unauthorized'):
|
||||
bot = telegram.Bot('1234:abcd1234')
|
||||
bot.getMe()
|
||||
|
||||
def testInvalidSrvResp(self):
|
||||
print('Testing invalid server response')
|
||||
with self.assertRaisesRegexp(telegram.TelegramError, 'Invalid server response'):
|
||||
# bypass the valid token check
|
||||
bot_cls = type('bot_cls', (telegram.Bot, ), {'_valid_token': lambda self, token: token})
|
||||
bot = bot_cls('12')
|
||||
bot.getMe()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
#!/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>
|
||||
# Copyright (C) 2015-2016
|
||||
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
||||
#
|
||||
# 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
|
||||
@@ -16,7 +17,7 @@
|
||||
# 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 GroupChat"""
|
||||
"""This module contains a object that represents Tests for Telegram Chat"""
|
||||
|
||||
import os
|
||||
import unittest
|
||||
@@ -27,8 +28,8 @@ import telegram
|
||||
from tests.base import BaseTest
|
||||
|
||||
|
||||
class GroupChatTest(BaseTest, unittest.TestCase):
|
||||
"""This object represents Tests for Telegram GroupChat."""
|
||||
class ChatTest(BaseTest, unittest.TestCase):
|
||||
"""This object represents Tests for Telegram Chat."""
|
||||
|
||||
def setUp(self):
|
||||
self.id = -28767330
|
||||
@@ -42,36 +43,36 @@ class GroupChatTest(BaseTest, unittest.TestCase):
|
||||
}
|
||||
|
||||
def test_group_chat_de_json_empty_json(self):
|
||||
"""Test GroupChat.de_json() method"""
|
||||
print('Testing GroupChat.de_json() - Empty JSON')
|
||||
"""Test Chat.de_json() method"""
|
||||
print('Testing Chat.de_json() - Empty JSON')
|
||||
|
||||
group_chat = telegram.GroupChat.de_json({})
|
||||
group_chat = telegram.Chat.de_json({})
|
||||
|
||||
self.assertEqual(group_chat, None)
|
||||
|
||||
def test_group_chat_de_json(self):
|
||||
"""Test GroupChat.de_json() method"""
|
||||
print('Testing GroupChat.de_json()')
|
||||
"""Test Chat.de_json() method"""
|
||||
print('Testing Chat.de_json()')
|
||||
|
||||
group_chat = telegram.GroupChat.de_json(self.json_dict)
|
||||
group_chat = telegram.Chat.de_json(self.json_dict)
|
||||
|
||||
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"""
|
||||
print('Testing GroupChat.to_json()')
|
||||
"""Test Chat.to_json() method"""
|
||||
print('Testing Chat.to_json()')
|
||||
|
||||
group_chat = telegram.GroupChat.de_json(self.json_dict)
|
||||
group_chat = telegram.Chat.de_json(self.json_dict)
|
||||
|
||||
self.assertTrue(self.is_json(group_chat.to_json()))
|
||||
|
||||
def test_group_chat_to_dict(self):
|
||||
"""Test GroupChat.to_dict() method"""
|
||||
print('Testing GroupChat.to_dict()')
|
||||
"""Test Chat.to_dict() method"""
|
||||
print('Testing Chat.to_dict()')
|
||||
|
||||
group_chat = telegram.GroupChat.de_json(self.json_dict)
|
||||
group_chat = telegram.Chat.de_json(self.json_dict)
|
||||
|
||||
self.assertTrue(self.is_dict(group_chat.to_dict()))
|
||||
self.assertEqual(group_chat['id'], self.id)
|
||||
@@ -1,7 +1,8 @@
|
||||
#!/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>
|
||||
# Copyright (C) 2015-2016
|
||||
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
||||
#
|
||||
# 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
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
#!/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>
|
||||
# Copyright (C) 2015-2016
|
||||
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
||||
#
|
||||
# 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
|
||||
|
||||
+2
-1
@@ -1,7 +1,8 @@
|
||||
#!/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>
|
||||
# Copyright (C) 2015-2016
|
||||
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
||||
#
|
||||
# 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
|
||||
|
||||
+2
-1
@@ -1,7 +1,8 @@
|
||||
#!/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>
|
||||
# Copyright (C) 2015-2016
|
||||
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
||||
#
|
||||
# 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
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
#!/usr/bin/env python
|
||||
# encoding: utf-8
|
||||
#
|
||||
# A library that provides a Python interface to the Telegram Bot API
|
||||
# Copyright (C) 2015-2016
|
||||
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
||||
#
|
||||
# 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 JobQueue
|
||||
"""
|
||||
import logging
|
||||
import sys
|
||||
from time import sleep
|
||||
|
||||
if sys.version_info[0:2] == (2, 6):
|
||||
import unittest2 as unittest
|
||||
else:
|
||||
import unittest
|
||||
|
||||
try:
|
||||
from urllib2 import urlopen, Request
|
||||
except ImportError:
|
||||
from urllib.request import Request, urlopen
|
||||
|
||||
sys.path.append('.')
|
||||
|
||||
from telegram import JobQueue, Updater
|
||||
from tests.base import BaseTest
|
||||
|
||||
# Enable logging
|
||||
root = logging.getLogger()
|
||||
root.setLevel(logging.INFO)
|
||||
|
||||
ch = logging.StreamHandler(sys.stdout)
|
||||
ch.setLevel(logging.WARN)
|
||||
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
|
||||
ch.setFormatter(formatter)
|
||||
root.addHandler(ch)
|
||||
|
||||
|
||||
class JobQueueTest(BaseTest, unittest.TestCase):
|
||||
"""
|
||||
This object represents Tests for Updater, Dispatcher, WebhookServer and
|
||||
WebhookHandler
|
||||
"""
|
||||
|
||||
def setUp(self):
|
||||
self.jq = JobQueue("Bot", tick_interval=0.005)
|
||||
self.result = 0
|
||||
|
||||
def tearDown(self):
|
||||
if self.jq is not None:
|
||||
self.jq.stop()
|
||||
|
||||
def job1(self, bot):
|
||||
self.result += 1
|
||||
|
||||
def job2(self, bot):
|
||||
raise Exception("Test Error")
|
||||
|
||||
def test_basic(self):
|
||||
print('Testing basic job queue function')
|
||||
self.jq.put(self.job1, 0.1)
|
||||
sleep(1.5)
|
||||
self.assertGreaterEqual(self.result, 10)
|
||||
|
||||
def test_noRepeat(self):
|
||||
print('Testing job queue without repeat')
|
||||
self.jq.put(self.job1, 0.1, repeat=False)
|
||||
sleep(0.5)
|
||||
self.assertEqual(1, self.result)
|
||||
|
||||
def test_nextT(self):
|
||||
print('Testing job queue with a set next_t value')
|
||||
self.jq.put(self.job1, 0.1, next_t=0.5)
|
||||
sleep(0.45)
|
||||
self.assertEqual(0, self.result)
|
||||
sleep(0.1)
|
||||
self.assertEqual(1, self.result)
|
||||
|
||||
def test_multiple(self):
|
||||
print('Testing job queue with multiple jobs')
|
||||
self.jq.put(self.job1, 0.1, repeat=False)
|
||||
self.jq.put(self.job1, 0.2, repeat=False)
|
||||
self.jq.put(self.job1, 0.4)
|
||||
sleep(1)
|
||||
self.assertEqual(4, self.result)
|
||||
|
||||
def test_error(self):
|
||||
print('Testing job queue starting twice with an erroneous job')
|
||||
self.jq.put(self.job2, 0.1)
|
||||
self.jq.put(self.job1, 0.2)
|
||||
self.jq.start()
|
||||
sleep(0.4)
|
||||
self.assertEqual(1, self.result)
|
||||
|
||||
def test_inUpdater(self):
|
||||
print('Testing job queue created by updater')
|
||||
u = Updater(bot="MockBot", job_queue_tick_interval=0.005)
|
||||
u.job_queue.put(self.job1, 0.1)
|
||||
sleep(0.15)
|
||||
self.assertEqual(1, self.result)
|
||||
u.stop()
|
||||
sleep(0.4)
|
||||
self.assertEqual(1, self.result)
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -1,7 +1,8 @@
|
||||
#!/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>
|
||||
# Copyright (C) 2015-2016
|
||||
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
||||
#
|
||||
# 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
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
#!/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>
|
||||
# Copyright (C) 2015-2016
|
||||
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
||||
#
|
||||
# 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
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
#!/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>
|
||||
# Copyright (C) 2015-2016
|
||||
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
||||
#
|
||||
# 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
|
||||
@@ -38,6 +39,7 @@ class UpdateTest(BaseTest, unittest.TestCase):
|
||||
'last_name': "S.",
|
||||
'username': "leandrotoledo"},
|
||||
'chat': {'id': 12173560,
|
||||
'type': 'private',
|
||||
'first_name': "Leandro",
|
||||
'last_name': "S.",
|
||||
'username': "leandrotoledo"},
|
||||
|
||||
@@ -0,0 +1,539 @@
|
||||
#!/usr/bin/env python
|
||||
# encoding: utf-8
|
||||
#
|
||||
# A library that provides a Python interface to the Telegram Bot API
|
||||
# Copyright (C) 2015-2016
|
||||
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
||||
#
|
||||
# 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 Updater, Dispatcher,
|
||||
WebhookServer and WebhookHandler
|
||||
"""
|
||||
import logging
|
||||
import sys
|
||||
import re
|
||||
import os
|
||||
import signal
|
||||
from random import randrange
|
||||
from time import sleep
|
||||
from datetime import datetime
|
||||
|
||||
if sys.version_info[0:2] == (2, 6):
|
||||
import unittest2 as unittest
|
||||
else:
|
||||
import unittest
|
||||
|
||||
try:
|
||||
from urllib2 import urlopen, Request
|
||||
except ImportError:
|
||||
from urllib.request import Request, urlopen
|
||||
|
||||
sys.path.append('.')
|
||||
|
||||
from telegram import Update, Message, TelegramError, User, Chat, Updater, Bot
|
||||
from telegram.dispatcher import run_async
|
||||
from tests.base import BaseTest
|
||||
from threading import Lock, Thread
|
||||
|
||||
# Enable logging
|
||||
root = logging.getLogger()
|
||||
root.setLevel(logging.INFO)
|
||||
|
||||
ch = logging.StreamHandler(sys.stdout)
|
||||
ch.setLevel(logging.WARN)
|
||||
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
|
||||
ch.setFormatter(formatter)
|
||||
root.addHandler(ch)
|
||||
|
||||
|
||||
class UpdaterTest(BaseTest, unittest.TestCase):
|
||||
"""
|
||||
This object represents Tests for Updater, Dispatcher, WebhookServer and
|
||||
WebhookHandler
|
||||
"""
|
||||
|
||||
def setUp(self):
|
||||
self.updater = None
|
||||
self.received_message = None
|
||||
self.message_count = 0
|
||||
self.lock = Lock()
|
||||
|
||||
def _setup_updater(self, *args, **kwargs):
|
||||
bot = MockBot(*args, **kwargs)
|
||||
self.updater = Updater(workers=2, bot=bot)
|
||||
|
||||
def tearDown(self):
|
||||
if self.updater is not None:
|
||||
self.updater.stop()
|
||||
|
||||
def reset(self):
|
||||
self.message_count = 0
|
||||
self.received_message = None
|
||||
|
||||
def telegramHandlerTest(self, bot, update):
|
||||
self.received_message = update.message.text
|
||||
self.message_count += 1
|
||||
|
||||
@run_async
|
||||
def asyncHandlerTest(self, bot, update, **kwargs):
|
||||
sleep(1)
|
||||
with self.lock:
|
||||
self.received_message = update.message.text
|
||||
self.message_count += 1
|
||||
|
||||
def stringHandlerTest(self, bot, update):
|
||||
self.received_message = update
|
||||
self.message_count += 1
|
||||
|
||||
def regexGroupHandlerTest(self, bot, update, groups=None, groupdict=None):
|
||||
self.received_message = (groups, groupdict)
|
||||
self.message_count += 1
|
||||
|
||||
def additionalArgsTest(self, bot, update, update_queue, args):
|
||||
self.received_message = update
|
||||
self.message_count += 1
|
||||
if args[0] == 'resend':
|
||||
update_queue.put('/test5 noresend')
|
||||
elif args[0] == 'noresend':
|
||||
pass
|
||||
|
||||
@run_async
|
||||
def asyncAdditionalHandlerTest(self, bot, update, update_queue=None,
|
||||
**kwargs):
|
||||
sleep(1)
|
||||
with self.lock:
|
||||
if update_queue is not None:
|
||||
self.received_message = update.message.text
|
||||
self.message_count += 1
|
||||
|
||||
def errorRaisingHandlerTest(self, bot, update):
|
||||
raise TelegramError(update)
|
||||
|
||||
def errorHandlerTest(self, bot, update, error):
|
||||
self.received_message = error.message
|
||||
self.message_count += 1
|
||||
|
||||
def test_addRemoveTelegramMessageHandler(self):
|
||||
print('Testing add/removeTelegramMessageHandler')
|
||||
self._setup_updater('Test')
|
||||
d = self.updater.dispatcher
|
||||
d.addTelegramMessageHandler(
|
||||
self.telegramHandlerTest)
|
||||
self.updater.start_polling(0.01)
|
||||
sleep(.1)
|
||||
self.assertEqual(self.received_message, 'Test')
|
||||
|
||||
# Remove handler
|
||||
d.removeTelegramMessageHandler(self.telegramHandlerTest)
|
||||
self.reset()
|
||||
|
||||
self.updater.bot.send_messages = 1
|
||||
sleep(.1)
|
||||
self.assertTrue(None is self.received_message)
|
||||
|
||||
def test_addTelegramMessageHandlerMultipleMessages(self):
|
||||
print('Testing addTelegramMessageHandler and send 100 messages...')
|
||||
self._setup_updater('Multiple', 100)
|
||||
self.updater.dispatcher.addTelegramMessageHandler(
|
||||
self.telegramHandlerTest)
|
||||
self.updater.start_polling(0.0)
|
||||
sleep(2)
|
||||
self.assertEqual(self.received_message, 'Multiple')
|
||||
self.assertEqual(self.message_count, 100)
|
||||
|
||||
def test_addRemoveTelegramRegexHandler(self):
|
||||
print('Testing add/removeStringRegexHandler')
|
||||
self._setup_updater('Test2')
|
||||
d = self.updater.dispatcher
|
||||
regobj = re.compile('Te.*')
|
||||
self.updater.dispatcher.addTelegramRegexHandler(regobj,
|
||||
self.telegramHandlerTest)
|
||||
self.updater.start_polling(0.01)
|
||||
sleep(.1)
|
||||
self.assertEqual(self.received_message, 'Test2')
|
||||
|
||||
# Remove handler
|
||||
d.removeTelegramRegexHandler(regobj, self.telegramHandlerTest)
|
||||
self.reset()
|
||||
|
||||
self.updater.bot.send_messages = 1
|
||||
sleep(.1)
|
||||
self.assertTrue(None is self.received_message)
|
||||
|
||||
def test_addRemoveTelegramCommandHandler(self):
|
||||
print('Testing add/removeTelegramCommandHandler')
|
||||
self._setup_updater('/test')
|
||||
d = self.updater.dispatcher
|
||||
self.updater.dispatcher.addTelegramCommandHandler(
|
||||
'test', self.telegramHandlerTest)
|
||||
self.updater.start_polling(0.01)
|
||||
sleep(.1)
|
||||
self.assertEqual(self.received_message, '/test')
|
||||
|
||||
# Remove handler
|
||||
d.removeTelegramCommandHandler('test', self.telegramHandlerTest)
|
||||
self.reset()
|
||||
|
||||
self.updater.bot.send_messages = 1
|
||||
sleep(.1)
|
||||
self.assertTrue(None is self.received_message)
|
||||
|
||||
def test_addRemoveUnknownTelegramCommandHandler(self):
|
||||
print('Testing add/removeUnknownTelegramCommandHandler')
|
||||
self._setup_updater('/test2')
|
||||
d = self.updater.dispatcher
|
||||
self.updater.dispatcher.addUnknownTelegramCommandHandler(
|
||||
self.telegramHandlerTest)
|
||||
self.updater.start_polling(0.01)
|
||||
sleep(.1)
|
||||
self.assertEqual(self.received_message, '/test2')
|
||||
|
||||
# Remove handler
|
||||
d.removeUnknownTelegramCommandHandler(self.telegramHandlerTest)
|
||||
self.reset()
|
||||
|
||||
self.updater.bot.send_messages = 1
|
||||
sleep(.1)
|
||||
self.assertTrue(None is self.received_message)
|
||||
|
||||
def test_addRemoveStringRegexHandler(self):
|
||||
print('Testing add/removeStringRegexHandler')
|
||||
self._setup_updater('', messages=0)
|
||||
d = self.updater.dispatcher
|
||||
d.addStringRegexHandler('Te.*', self.stringHandlerTest)
|
||||
queue = self.updater.start_polling(0.01)
|
||||
queue.put('Test3')
|
||||
sleep(.1)
|
||||
self.assertEqual(self.received_message, 'Test3')
|
||||
|
||||
# Remove handler
|
||||
d.removeStringRegexHandler('Te.*', self.stringHandlerTest)
|
||||
self.reset()
|
||||
|
||||
queue.put('Test3')
|
||||
sleep(.1)
|
||||
self.assertTrue(None is self.received_message)
|
||||
|
||||
def test_addRemoveStringCommandHandler(self):
|
||||
print('Testing add/removeStringCommandHandler')
|
||||
self._setup_updater('', messages=0)
|
||||
d = self.updater.dispatcher
|
||||
d.addStringCommandHandler(
|
||||
'test3', self.stringHandlerTest)
|
||||
|
||||
queue = self.updater.start_polling(0.01)
|
||||
queue.put('/test3')
|
||||
sleep(.1)
|
||||
self.assertEqual(self.received_message, '/test3')
|
||||
|
||||
# Remove handler
|
||||
d.removeStringCommandHandler('test3', self.stringHandlerTest)
|
||||
self.reset()
|
||||
|
||||
queue.put('/test3')
|
||||
sleep(.1)
|
||||
self.assertTrue(None is self.received_message)
|
||||
|
||||
def test_addRemoveUnknownStringCommandHandler(self):
|
||||
print('Testing add/removeUnknownStringCommandHandler')
|
||||
self._setup_updater('/test')
|
||||
d = self.updater.dispatcher
|
||||
d.addUnknownStringCommandHandler(
|
||||
self.stringHandlerTest)
|
||||
queue = self.updater.start_polling(0.01)
|
||||
queue.put('/test4')
|
||||
sleep(.1)
|
||||
self.assertEqual(self.received_message, '/test4')
|
||||
|
||||
# Remove handler
|
||||
d.removeUnknownStringCommandHandler(self.stringHandlerTest)
|
||||
self.reset()
|
||||
|
||||
self.updater.bot.send_messages = 1
|
||||
sleep(.1)
|
||||
self.assertTrue(None is self.received_message)
|
||||
|
||||
def test_addRemoveErrorHandler(self):
|
||||
print('Testing add/removeErrorHandler')
|
||||
self._setup_updater('', messages=0)
|
||||
d = self.updater.dispatcher
|
||||
d.addErrorHandler(self.errorHandlerTest)
|
||||
queue = self.updater.start_polling(0.01)
|
||||
error = TelegramError("Unauthorized.")
|
||||
queue.put(error)
|
||||
sleep(.1)
|
||||
self.assertEqual(self.received_message, "Unauthorized.")
|
||||
|
||||
# Remove handler
|
||||
d.removeErrorHandler(self.errorHandlerTest)
|
||||
self.reset()
|
||||
|
||||
queue.put(error)
|
||||
sleep(.1)
|
||||
self.assertTrue(None is self.received_message)
|
||||
|
||||
def test_errorInHandler(self):
|
||||
print('Testing error in Handler')
|
||||
self._setup_updater('', messages=0)
|
||||
d = self.updater.dispatcher
|
||||
d.addStringRegexHandler('.*',
|
||||
self.errorRaisingHandlerTest)
|
||||
self.updater.dispatcher.addErrorHandler(self.errorHandlerTest)
|
||||
queue = self.updater.start_polling(0.01)
|
||||
|
||||
queue.put('Test Error 1')
|
||||
sleep(.1)
|
||||
self.assertEqual(self.received_message, 'Test Error 1')
|
||||
|
||||
def test_errorOnGetUpdates(self):
|
||||
print('Testing error on getUpdates')
|
||||
self._setup_updater('', raise_error=True)
|
||||
d = self.updater.dispatcher
|
||||
d.addErrorHandler(self.errorHandlerTest)
|
||||
self.updater.start_polling(0.01)
|
||||
sleep(.1)
|
||||
self.assertEqual(self.received_message, "Test Error 2")
|
||||
|
||||
def test_addRemoveTypeHandler(self):
|
||||
print('Testing add/removeTypeHandler')
|
||||
self._setup_updater('', messages=0)
|
||||
d = self.updater.dispatcher
|
||||
d.addTypeHandler(dict, self.stringHandlerTest)
|
||||
queue = self.updater.start_polling(0.01)
|
||||
payload = {"Test": 42}
|
||||
queue.put(payload)
|
||||
sleep(.1)
|
||||
self.assertEqual(self.received_message, payload)
|
||||
|
||||
# Remove handler
|
||||
d.removeTypeHandler(dict, self.stringHandlerTest)
|
||||
self.reset()
|
||||
|
||||
queue.put(payload)
|
||||
sleep(.1)
|
||||
self.assertTrue(None is self.received_message)
|
||||
|
||||
def test_runAsync(self):
|
||||
print('Testing @run_async')
|
||||
self._setup_updater('Test5', messages=2)
|
||||
d = self.updater.dispatcher
|
||||
d.addTelegramMessageHandler(
|
||||
self.asyncHandlerTest)
|
||||
self.updater.start_polling(0.01)
|
||||
sleep(1.2)
|
||||
self.assertEqual(self.received_message, 'Test5')
|
||||
self.assertEqual(self.message_count, 2)
|
||||
|
||||
def test_additionalArgs(self):
|
||||
print('Testing additional arguments for handlers')
|
||||
self._setup_updater('', messages=0)
|
||||
self.updater.dispatcher.addStringCommandHandler(
|
||||
'test5', self.additionalArgsTest)
|
||||
|
||||
queue = self.updater.start_polling(0.01)
|
||||
queue.put('/test5 resend')
|
||||
sleep(.1)
|
||||
self.assertEqual(self.received_message, '/test5 noresend')
|
||||
self.assertEqual(self.message_count, 2)
|
||||
|
||||
def test_regexGroupHandler(self):
|
||||
print('Testing optional groups and groupdict parameters')
|
||||
self._setup_updater('', messages=0)
|
||||
d = self.updater.dispatcher
|
||||
d.addStringRegexHandler('^(This).*?(?P<testgroup>regex group).*',
|
||||
self.regexGroupHandlerTest)
|
||||
queue = self.updater.start_polling(0.01)
|
||||
queue.put('This is a test message for regex group matching.')
|
||||
sleep(.1)
|
||||
self.assertEqual(self.received_message, (('This', 'regex group'),
|
||||
{'testgroup': 'regex group'}))
|
||||
|
||||
|
||||
def test_runAsyncWithAdditionalArgs(self):
|
||||
print('Testing @run_async with additional parameters')
|
||||
self._setup_updater('Test6', messages=2)
|
||||
d = self.updater.dispatcher
|
||||
d.addTelegramMessageHandler(
|
||||
self.asyncAdditionalHandlerTest)
|
||||
self.updater.start_polling(0.01)
|
||||
sleep(1.2)
|
||||
self.assertEqual(self.received_message, 'Test6')
|
||||
self.assertEqual(self.message_count, 2)
|
||||
|
||||
def test_webhook(self):
|
||||
print('Testing Webhook')
|
||||
self._setup_updater('', messages=0)
|
||||
d = self.updater.dispatcher
|
||||
d.addTelegramMessageHandler(
|
||||
self.telegramHandlerTest)
|
||||
|
||||
# Select random port for travis
|
||||
port = randrange(1024, 49152)
|
||||
self.updater.start_webhook('127.0.0.1', port,
|
||||
url_path='TOKEN',
|
||||
cert='./tests/test_updater.py',
|
||||
key='./tests/test_updater.py')
|
||||
sleep(0.5)
|
||||
# SSL-Wrapping will fail, so we start the server without SSL
|
||||
Thread(target=self.updater.httpd.serve_forever).start()
|
||||
|
||||
# Now, we send an update to the server via urlopen
|
||||
message = Message(1, User(1, "Tester"), datetime.now(),
|
||||
Chat(1, "group", title="Test Group"))
|
||||
|
||||
message.text = "Webhook Test"
|
||||
update = Update(1)
|
||||
update.message = message
|
||||
|
||||
try:
|
||||
payload = bytes(update.to_json(), encoding='utf-8')
|
||||
except TypeError:
|
||||
payload = bytes(update.to_json())
|
||||
|
||||
header = {
|
||||
'content-type': 'application/json',
|
||||
'content-length': str(len(payload))
|
||||
}
|
||||
|
||||
r = Request('http://127.0.0.1:%d/TOKEN' % port,
|
||||
data=payload,
|
||||
headers=header)
|
||||
|
||||
urlopen(r)
|
||||
|
||||
sleep(1)
|
||||
self.assertEqual(self.received_message, 'Webhook Test')
|
||||
|
||||
print("Test other webhook server functionalities...")
|
||||
request = Request('http://localhost:%d/webookhandler.py' % port)
|
||||
response = urlopen(request)
|
||||
self.assertEqual(b'', response.read())
|
||||
self.assertEqual(200, response.code)
|
||||
|
||||
request.get_method = lambda: 'HEAD'
|
||||
|
||||
response = urlopen(request)
|
||||
self.assertEqual(b'', response.read())
|
||||
self.assertEqual(200, response.code)
|
||||
|
||||
# Test multiple shutdown() calls
|
||||
self.updater.httpd.shutdown()
|
||||
self.updater.httpd.shutdown()
|
||||
self.assertTrue(True)
|
||||
|
||||
def test_webhook_no_ssl(self):
|
||||
print('Testing Webhook without SSL')
|
||||
self._setup_updater('', messages=0)
|
||||
d = self.updater.dispatcher
|
||||
d.addTelegramMessageHandler(
|
||||
self.telegramHandlerTest)
|
||||
|
||||
# Select random port for travis
|
||||
port = randrange(1024, 49152)
|
||||
self.updater.start_webhook('127.0.0.1', port)
|
||||
sleep(0.5)
|
||||
|
||||
# Now, we send an update to the server via urlopen
|
||||
message = Message(1, User(1, "Tester 2"), datetime.now(),
|
||||
Chat(1, 'group', title="Test Group 2"))
|
||||
|
||||
message.text = "Webhook Test 2"
|
||||
update = Update(1)
|
||||
update.message = message
|
||||
|
||||
try:
|
||||
payload = bytes(update.to_json(), encoding='utf-8')
|
||||
except TypeError:
|
||||
payload = bytes(update.to_json())
|
||||
|
||||
header = {
|
||||
'content-type': 'application/json',
|
||||
'content-length': str(len(payload))
|
||||
}
|
||||
|
||||
r = Request('http://127.0.0.1:%d/' % port,
|
||||
data=payload,
|
||||
headers=header)
|
||||
|
||||
urlopen(r)
|
||||
sleep(1)
|
||||
self.assertEqual(self.received_message, 'Webhook Test 2')
|
||||
|
||||
def signalsender(self):
|
||||
sleep(0.5)
|
||||
os.kill(os.getpid(), signal.SIGTERM)
|
||||
|
||||
def test_idle(self):
|
||||
print('Testing idle')
|
||||
self._setup_updater('Test6', messages=0)
|
||||
self.updater.start_polling(poll_interval=0.01)
|
||||
Thread(target=self.signalsender).start()
|
||||
self.updater.idle()
|
||||
# If we get this far, idle() ran through
|
||||
sleep(1)
|
||||
self.updater.running = False
|
||||
|
||||
def test_createBot(self):
|
||||
updater = Updater('123:abcd')
|
||||
self.assertIsNotNone(updater.bot)
|
||||
|
||||
def test_mutualExclusiveTokenBot(self):
|
||||
bot = Bot('123:zyxw')
|
||||
self.assertRaises(ValueError, Updater, token='123:abcd', bot=bot)
|
||||
|
||||
def test_noTokenOrBot(self):
|
||||
self.assertRaises(ValueError, Updater)
|
||||
|
||||
|
||||
class MockBot:
|
||||
|
||||
def __init__(self, text, messages=1, raise_error=False):
|
||||
self.text = text
|
||||
self.send_messages = messages
|
||||
self.raise_error = raise_error
|
||||
self.token = "TOKEN"
|
||||
pass
|
||||
|
||||
@staticmethod
|
||||
def mockUpdate(text):
|
||||
message = Message(0, None, None, None)
|
||||
message.text = text
|
||||
update = Update(0)
|
||||
update.message = message
|
||||
return update
|
||||
|
||||
def setWebhook(self, webhook_url=None, certificate=None):
|
||||
pass
|
||||
|
||||
def getUpdates(self,
|
||||
offset=None,
|
||||
limit=100,
|
||||
timeout=0,
|
||||
network_delay=2.):
|
||||
|
||||
if self.raise_error:
|
||||
raise TelegramError('Test Error 2')
|
||||
elif self.send_messages >= 2:
|
||||
self.send_messages -= 2
|
||||
return self.mockUpdate(self.text), self.mockUpdate(self.text)
|
||||
elif self.send_messages == 1:
|
||||
self.send_messages -= 1
|
||||
return self.mockUpdate(self.text),
|
||||
else:
|
||||
return []
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
+2
-1
@@ -1,7 +1,8 @@
|
||||
#!/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>
|
||||
# Copyright (C) 2015-2016
|
||||
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
||||
#
|
||||
# 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
|
||||
|
||||
+2
-1
@@ -1,7 +1,8 @@
|
||||
#!/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>
|
||||
# Copyright (C) 2015-2016
|
||||
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
||||
#
|
||||
# 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
|
||||
|
||||
+2
-1
@@ -1,7 +1,8 @@
|
||||
#!/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>
|
||||
# Copyright (C) 2015-2016
|
||||
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
||||
#
|
||||
# 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
|
||||
|
||||
Reference in New Issue
Block a user