mirror of
https://github.com/python-telegram-bot/python-telegram-bot.git
synced 2026-06-26 19:25:16 +00:00
Compare commits
117 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 937be3d2e8 | |||
| aa3ebb1180 | |||
| 4473d620de | |||
| 4689a80c2e | |||
| 353410242f | |||
| 8acff56145 | |||
| d4b5bd40a5 | |||
| d2059ed184 | |||
| f8a17cddcb | |||
| 9e2357bc33 | |||
| 42daf96d20 | |||
| 87afd98e02 | |||
| 247577b2e2 | |||
| 94abf16a7f | |||
| 3d8abc184a | |||
| efbd951b74 | |||
| 3ff4cc4445 | |||
| 32afc007aa | |||
| c758c19ef4 | |||
| 3bef2fa752 | |||
| b4cabecca2 | |||
| 0a8abccc78 | |||
| 5ff34fc0ba | |||
| 78fee3c1dc | |||
| 38d6f4d9f2 | |||
| 1ec12343f0 | |||
| b5196f00b2 | |||
| 39c679e519 | |||
| 7a6d2be101 | |||
| ef74c525b2 | |||
| 6d453b7fa2 | |||
| 716f52684f | |||
| 42497367c1 | |||
| b77b329dd6 | |||
| 5efd5e2586 | |||
| cbfb7df643 | |||
| 712baf0c07 | |||
| 59659eaf5e | |||
| 3ccf40e8cc | |||
| 38e3b91a87 | |||
| e182046376 | |||
| 1530ed20e5 | |||
| 2b221da9b9 | |||
| d9f77d6ee1 | |||
| 698a91427a | |||
| 5956aae235 | |||
| 0811f566a2 | |||
| 69acd2b3bd | |||
| a6bf456645 | |||
| 811369d1a0 | |||
| b67ea7a691 | |||
| f6332d45a8 | |||
| b275031a16 | |||
| a9a503b9c3 | |||
| 3762792cca | |||
| 36a93e0636 | |||
| baec1bb554 | |||
| 746ae0caf3 | |||
| 0bed087542 | |||
| efea0361c5 | |||
| 91ae35e26c | |||
| ebcc40ae92 | |||
| dcb510e62c | |||
| c152d6583e | |||
| 9338dc4697 | |||
| 063704c0b9 | |||
| 62e76f1fba | |||
| f0dfdfb203 | |||
| c19e464324 | |||
| d5c9212f2e | |||
| 8690ba256e | |||
| d6b47da593 | |||
| ddf3a1fcad | |||
| 820f4e1d59 | |||
| eb67c039f1 | |||
| 2ca7ff82ef | |||
| a2c04313d3 | |||
| 0faa19726a | |||
| d347c0d45e | |||
| 5c8470e552 | |||
| 3d4e0500bf | |||
| 042d4bb2a4 | |||
| 1e22d570a3 | |||
| 2719c54899 | |||
| a5c8e98ee7 | |||
| 40113bb3ad | |||
| e8fac19de3 | |||
| 820ae3b7d6 | |||
| 4b3315db6f | |||
| 3ed05991ad | |||
| 38637ecf62 | |||
| bb5357a815 | |||
| f55018abd9 | |||
| 8df35fd53b | |||
| 23774383dc | |||
| 28680ac1d5 | |||
| ec9b16ac7b | |||
| bfad2fa1f3 | |||
| 8a8b1215c8 | |||
| 2aa456d637 | |||
| 445bcde686 | |||
| 6facde9534 | |||
| 046ec28361 | |||
| 3d00ae25df | |||
| aeedcfb874 | |||
| 6d7a61ae72 | |||
| d75e0f6014 | |||
| dbb3b16edc | |||
| 7c3bba42cc | |||
| 8754980448 | |||
| 5614af1847 | |||
| e362a5b59d | |||
| dd20237f55 | |||
| c5ab8930b9 | |||
| f5b746f1ba | |||
| 4fe4eea893 | |||
| e39b6abe61 |
@@ -1,5 +0,0 @@
|
||||
languages:
|
||||
Python: true
|
||||
exclude_paths:
|
||||
- "telegram/emoji.py"
|
||||
- "tests/*"
|
||||
@@ -40,6 +40,7 @@ htmlcov/
|
||||
.coverage
|
||||
.coverage.*
|
||||
.cache
|
||||
.pytest_cache
|
||||
nosetests.xml
|
||||
coverage.xml
|
||||
*,cover
|
||||
|
||||
@@ -6,10 +6,10 @@
|
||||
args:
|
||||
- --diff
|
||||
- repo: git://github.com/pre-commit/pre-commit-hooks
|
||||
sha: 78818b90cd694c29333ba54d38f9e60b6359ccfc
|
||||
sha: v1.2.0
|
||||
hooks:
|
||||
- id: flake8
|
||||
files: ^telegram/.*\.py$
|
||||
exclude: ^(setup.py|docs/source/conf.py)$
|
||||
- repo: git://github.com/pre-commit/mirrors-pylint
|
||||
sha: v1.7.1
|
||||
hooks:
|
||||
|
||||
@@ -5,5 +5,6 @@ formats:
|
||||
|
||||
python:
|
||||
setup_py_install: true
|
||||
version: 3
|
||||
|
||||
requirements_file: docs/requirements-docs.txt
|
||||
|
||||
+7
-6
@@ -1,12 +1,11 @@
|
||||
language: python
|
||||
python:
|
||||
- "2.7"
|
||||
- "3.3"
|
||||
- "3.4"
|
||||
- "3.5"
|
||||
- "3.6"
|
||||
- "3.7-dev"
|
||||
- "pypy-5.7.1"
|
||||
- "pypy3.5-5.8.0"
|
||||
|
||||
dist: trusty
|
||||
sudo: false
|
||||
@@ -24,15 +23,17 @@ before_cache:
|
||||
- rm -f $HOME/.pre-commit/pre-commit.log
|
||||
|
||||
install:
|
||||
- pip install coveralls pytest-cov
|
||||
- pip install -U wheel
|
||||
- pip install -U codecov pytest-cov
|
||||
- echo $TRAVIS_PYTHON_VERSION
|
||||
- if [[ $TRAVIS_PYTHON_VERSION == '3.7'* ]]; then pip install -U git+https://github.com/yaml/pyyaml.git; fi
|
||||
- pip install -U -r requirements.txt
|
||||
- pip install -U -r requirements-dev.txt
|
||||
- if [[ $TRAVIS_PYTHON_VERSION != 'pypy'* ]]; then pip install ujson; fi
|
||||
|
||||
script:
|
||||
- pytest -v --cov=telegram
|
||||
- pytest -v -m nocoverage
|
||||
- pytest -v -m "not nocoverage" --cov
|
||||
|
||||
after_success:
|
||||
- coverage combine
|
||||
- coveralls
|
||||
- codecov -F Travis
|
||||
|
||||
+12
-3
@@ -3,8 +3,8 @@ Credits
|
||||
|
||||
``python-telegram-bot`` was originally created by
|
||||
`Leandro Toledo <https://github.com/leandrotoledo>`_ and is now maintained by
|
||||
`Jannes Höke <https://github.com/jh0ker>`_ (`@jh0ker <https://t.me/jh0ker>`_ on Telegram) and
|
||||
`Noam Meltzer <https://github.com/tsnoam>`_.
|
||||
`Jannes Höke <https://github.com/jh0ker>`_ (`@jh0ker <https://t.me/jh0ker>`_ on Telegram),
|
||||
`Noam Meltzer <https://github.com/tsnoam>`_, `Pieter Schutz <https://github.com/eldinnie>`_ and `Jasmin Bom <https://github.com/jsmnbom>`_.
|
||||
|
||||
We're vendoring urllib3 as part of ``python-telegram-bot`` which is distributed under the MIT
|
||||
license. For more info, full credits & license terms, the sources can be found here:
|
||||
@@ -22,7 +22,9 @@ The following wonderful people contributed directly or indirectly to this projec
|
||||
- `bimmlerd <https://github.com/bimmlerd>`_
|
||||
- `d-qoi <https://github.com/d-qoi>`_
|
||||
- `daimajia <https://github.com/daimajia>`_
|
||||
- `Daniel Reed <https://github.com/nmlorg>`_
|
||||
- `Eli Gao <https://github.com/eligao>`_
|
||||
- `Emilio Molinari <https://github.com/xates>`_
|
||||
- `ErgoZ Riftbit Vaper <https://github.com/ergoz>`_
|
||||
- `Eugene Lisitsky <https://github.com/lisitsky>`_
|
||||
- `Eugenio Panadero <https://github.com/azogue>`_
|
||||
@@ -30,7 +32,7 @@ The following wonderful people contributed directly or indirectly to this projec
|
||||
- `franciscod <https://github.com/franciscod>`_
|
||||
- `Hugo Damer <https://github.com/HakimusGIT>`_
|
||||
- `ihoru <https://github.com/ihoru>`_
|
||||
- `Jacob Bom <https://github.com/bomjacob>`_
|
||||
- `Jasmin Bom <https://github.com/jsmnbom>`_
|
||||
- `JASON0916 <https://github.com/JASON0916>`_
|
||||
- `jeffffc <https://github.com/jeffffc>`_
|
||||
- `Jelle Besseling <https://github.com/pingiun>`_
|
||||
@@ -44,21 +46,28 @@ The following wonderful people contributed directly or indirectly to this projec
|
||||
- `Li-aung Yip <https://github.com/LiaungYip>`_
|
||||
- `macrojames <https://github.com/macrojames>`_
|
||||
- `Michael Elovskikh <https://github.com/wronglink>`_
|
||||
- `Mischa Krüger <https://github.com/Makman2>`_
|
||||
- `naveenvhegde <https://github.com/naveenvhegde>`_
|
||||
- `neurrone <https://github.com/neurrone>`_
|
||||
- `njittam <https://github.com/njittam>`_
|
||||
- `Noam Meltzer <https://github.com/tsnoam>`_
|
||||
- `Oleg Shlyazhko <https://github.com/ollmer>`_
|
||||
- `Oleg Sushchenko <https://github.com/feuillemorte>`_
|
||||
- `Or Bin <https://github.com/OrBin>`_
|
||||
- `overquota <https://github.com/overquota>`_
|
||||
- `Patrick Hofmann <https://github.com/PH89>`_
|
||||
- `Paul Larsen <https://github.com/PaulSonOfLars>`_
|
||||
- `Pieter Schutz <https://github.com/eldinnie>`_
|
||||
- `Rahiel Kasim <https://github.com/rahiel>`_
|
||||
- `Sascha <https://github.com/saschalalala>`_
|
||||
- `Shelomentsev D <https://github.com/shelomentsevd>`_
|
||||
- `Simon Schürrle <https://github.com/SitiSchu>`_
|
||||
- `sooyhwang <https://github.com/sooyhwang>`_
|
||||
- `thodnev <https://github.com/thodnev>`_
|
||||
- `Trainer Jono <https://github.com/Tr-Jono>`_
|
||||
- `Valentijn <https://github.com/Faalentijn>`_
|
||||
- `voider1 <https://github.com/voider1>`_
|
||||
- `Wagner Macedo <https://github.com/wagnerluis1982>`_
|
||||
- `wjt <https://github.com/wjt>`_
|
||||
|
||||
Please add yourself here alphabetically when you submit your first pull request.
|
||||
|
||||
+245
-1
@@ -1,6 +1,250 @@
|
||||
=======
|
||||
Changes
|
||||
=======
|
||||
|
||||
**2018-08-29**
|
||||
*Released 11.0.0*
|
||||
|
||||
Fully support Bot API version 4.0!
|
||||
(also some bugfixes :))
|
||||
|
||||
Telegram Passport (`#1174`_):
|
||||
|
||||
- Add full support for telegram passport.
|
||||
- New types: PassportData, PassportFile, EncryptedPassportElement, EncryptedCredentials, PassportElementError, PassportElementErrorDataField, PassportElementErrorFrontSide, PassportElementErrorReverseSide, PassportElementErrorSelfie, PassportElementErrorFile and PassportElementErrorFiles.
|
||||
- New bot method: set_passport_data_errors
|
||||
- New filter: Filters.passport_data
|
||||
- Field passport_data field on Message
|
||||
- PassportData can be easily decrypted.
|
||||
- PassportFiles are automatically decrypted if originating from decrypted PassportData.
|
||||
- See new passportbot.py example for details on how to use, or go to `our telegram passport wiki page`_ for more info
|
||||
- NOTE: Passport decryption requires new dependency `cryptography`.
|
||||
|
||||
Inputfile rework (`#1184`_):
|
||||
|
||||
- Change how Inputfile is handled internally
|
||||
- This allows support for specifying the thumbnails of photos and videos using the thumb= argument in the different send\_ methods.
|
||||
- Also allows Bot.send_media_group to actually finally send more than one media.
|
||||
- Add thumb to Audio, Video and Videonote
|
||||
- Add Bot.edit_message_media together with InputMediaAnimation, InputMediaAudio, and inputMediaDocument.
|
||||
|
||||
Other Bot API 4.0 changes:
|
||||
|
||||
- Add forusquare_type to Venue, InlineQueryResultVenue, InputVenueMessageContent, and Bot.send_venue. (`#1170`_)
|
||||
- Add vCard support by adding vcard field to Contact, InlineQueryResultContact, InputContactMessageContent, and Bot.send_contact. (`#1166`_)
|
||||
- Support new message entities: CASHTAG and PHONE_NUMBER. (`#1179`_)
|
||||
- Cashtag seems to be things like `$USD` and `$GBP`, but it seems telegram doesn't currently send them to bots.
|
||||
- Phone number also seems to have limited support for now
|
||||
- Add Bot.send_animation, add width, height, and duration to Animation, and add Filters.animation. (`#1172`_)
|
||||
|
||||
Non Bot API 4.0 changes:
|
||||
|
||||
- Minor integer comparison fix (`#1147`_)
|
||||
- Fix Filters.regex failing on non-text message (`#1158`_)
|
||||
- Fix ProcessLookupError if process finishes before we kill it (`#1126`_)
|
||||
- Add t.me links for User, Chat and Message if available and update User.mention_* (`#1092`_)
|
||||
- Fix mention_markdown/html on py2 (`#1112`_)
|
||||
|
||||
.. _`#1092`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1092
|
||||
.. _`#1112`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1112
|
||||
.. _`#1126`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1126
|
||||
.. _`#1147`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1147
|
||||
.. _`#1158`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1158
|
||||
.. _`#1166`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1166
|
||||
.. _`#1170`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1170
|
||||
.. _`#1174`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1174
|
||||
.. _`#1172`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1172
|
||||
.. _`#1179`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1179
|
||||
.. _`#1184`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1184
|
||||
.. _`our telegram passport wiki page`: https://git.io/fAvYd
|
||||
|
||||
**2018-05-02**
|
||||
*Released 10.1.0*
|
||||
|
||||
Fixes changing previous behaviour:
|
||||
|
||||
- Add urllib3 fix for socks5h support (`#1085`_)
|
||||
- Fix send_sticker() timeout=20 (`#1088`_)
|
||||
|
||||
Fixes:
|
||||
|
||||
- Add a caption_entity filter for filtering caption entities (`#1068`_)
|
||||
- Inputfile encode filenames (`#1086`_)
|
||||
- InputFile: Fix proper naming of file when reading from subprocess.PIPE (`#1079`_)
|
||||
- Remove pytest-catchlog from requirements (`#1099`_)
|
||||
- Documentation fixes (`#1061`_, `#1078`_, `#1081`_, `#1096`_)
|
||||
|
||||
.. _`#1061`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1061
|
||||
.. _`#1068`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1068
|
||||
.. _`#1078`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1078
|
||||
.. _`#1079`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1079
|
||||
.. _`#1081`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1081
|
||||
.. _`#1085`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1085
|
||||
.. _`#1086`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1086
|
||||
.. _`#1088`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1088
|
||||
.. _`#1096`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1096
|
||||
.. _`#1099`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1099
|
||||
|
||||
**2018-04-17**
|
||||
*Released 10.0.2*
|
||||
|
||||
Important fix:
|
||||
|
||||
- Handle utf8 decoding errors (`#1076`_)
|
||||
|
||||
New features:
|
||||
|
||||
- Added Filter.regex (`#1028`_)
|
||||
- Filters for Category and file types (`#1046`_)
|
||||
- Added video note filter (`#1067`_)
|
||||
|
||||
Fixes:
|
||||
|
||||
- Fix in telegram.Message (`#1042`_)
|
||||
- Make chat_id a positional argument inside shortcut methods of Chat and User classes (`#1050`_)
|
||||
- Make Bot.full_name return a unicode object. (`#1063`_)
|
||||
- CommandHandler faster check (`#1074`_)
|
||||
- Correct documentation of Dispatcher.add_handler (`#1071`_)
|
||||
- Various small fixes to documentation.
|
||||
|
||||
.. _`#1028`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1028
|
||||
.. _`#1042`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1042
|
||||
.. _`#1046`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1046
|
||||
.. _`#1050`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1050
|
||||
.. _`#1067`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1067
|
||||
.. _`#1063`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1063
|
||||
.. _`#1074`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1074
|
||||
.. _`#1076`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1076
|
||||
.. _`#1071`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1071
|
||||
|
||||
**2018-03-05**
|
||||
*Released 10.0.1*
|
||||
|
||||
Fixes:
|
||||
|
||||
- Fix conversationhandler timeout (PR `#1032`_)
|
||||
- Add missing docs utils (PR `#912`_)
|
||||
|
||||
.. _`#1032`: https://github.com/python-telegram-bot/python-telegram-bot/pull/826
|
||||
.. _`#912`: https://github.com/python-telegram-bot/python-telegram-bot/pull/826
|
||||
|
||||
**2018-03-02**
|
||||
*Released 10.0.0*
|
||||
|
||||
Non backward compatabile changes and changed defaults
|
||||
|
||||
- JobQueue: Remove deprecated prevent_autostart & put() (PR `#1012`_)
|
||||
- Bot, Updater: Remove deprecated network_delay (PR `#1012`_)
|
||||
- Remove deprecated Message.new_chat_member (PR `#1012`_)
|
||||
- Retry bootstrap phase indefinitely (by default) on network errors (PR `#1018`_)
|
||||
|
||||
New Features
|
||||
|
||||
- Support v3.6 API (PR `#1006`_)
|
||||
- User.full_name convinience property (PR `#949`_)
|
||||
- Add `send_phone_number_to_provider` and `send_email_to_provider` arguments to send_invoice (PR `#986`_)
|
||||
- Bot: Add shortcut methods reply_{markdown,html} (PR `#827`_)
|
||||
- Bot: Add shortcut method reply_media_group (PR `#994`_)
|
||||
- Added utils.helpers.effective_message_type (PR `#826`_)
|
||||
- Bot.get_file now allows passing a file in addition to file_id (PR `#963`_)
|
||||
- Add .get_file() to Audio, Document, PhotoSize, Sticker, Video, VideoNote and Voice (PR `#963`_)
|
||||
- Add .send_*() methods to User and Chat (PR `#963`_)
|
||||
- Get jobs by name (PR `#1011`_)
|
||||
- Add Message caption html/markdown methods (PR `#1013`_)
|
||||
- File.download_as_bytearray - new method to get a d/led file as bytearray (PR `#1019`_)
|
||||
- File.download(): Now returns a meaningful return value (PR `#1019`_)
|
||||
- Added conversation timeout in ConversationHandler (PR `#895`_)
|
||||
|
||||
Changes
|
||||
|
||||
- Store bot in PreCheckoutQuery (PR `#953`_)
|
||||
- Updater: Issue INFO log upon received signal (PR `#951`_)
|
||||
- JobQueue: Thread safety fixes (PR `#977`_)
|
||||
- WebhookHandler: Fix exception thrown during error handling (PR `#985`_)
|
||||
- Explicitly check update.effective_chat in ConversationHandler.check_update (PR `#959`_)
|
||||
- Updater: Better handling of timeouts during get_updates (PR `#1007`_)
|
||||
- Remove unnecessary to_dict() (PR `#834`_)
|
||||
- CommandHandler - ignore strings in entities and "/" followed by whitespace (PR `#1020`_)
|
||||
- Documentation & style fixes (PR `#942`_, PR `#956`_, PR `#962`_, PR `#980`_, PR `#983`_)
|
||||
|
||||
.. _`#826`: https://github.com/python-telegram-bot/python-telegram-bot/pull/826
|
||||
.. _`#827`: https://github.com/python-telegram-bot/python-telegram-bot/pull/827
|
||||
.. _`#834`: https://github.com/python-telegram-bot/python-telegram-bot/pull/834
|
||||
.. _`#895`: https://github.com/python-telegram-bot/python-telegram-bot/pull/895
|
||||
.. _`#942`: https://github.com/python-telegram-bot/python-telegram-bot/pull/942
|
||||
.. _`#949`: https://github.com/python-telegram-bot/python-telegram-bot/pull/949
|
||||
.. _`#951`: https://github.com/python-telegram-bot/python-telegram-bot/pull/951
|
||||
.. _`#956`: https://github.com/python-telegram-bot/python-telegram-bot/pull/956
|
||||
.. _`#953`: https://github.com/python-telegram-bot/python-telegram-bot/pull/953
|
||||
.. _`#962`: https://github.com/python-telegram-bot/python-telegram-bot/pull/962
|
||||
.. _`#959`: https://github.com/python-telegram-bot/python-telegram-bot/pull/959
|
||||
.. _`#963`: https://github.com/python-telegram-bot/python-telegram-bot/pull/963
|
||||
.. _`#977`: https://github.com/python-telegram-bot/python-telegram-bot/pull/977
|
||||
.. _`#980`: https://github.com/python-telegram-bot/python-telegram-bot/pull/980
|
||||
.. _`#983`: https://github.com/python-telegram-bot/python-telegram-bot/pull/983
|
||||
.. _`#985`: https://github.com/python-telegram-bot/python-telegram-bot/pull/985
|
||||
.. _`#986`: https://github.com/python-telegram-bot/python-telegram-bot/pull/986
|
||||
.. _`#994`: https://github.com/python-telegram-bot/python-telegram-bot/pull/994
|
||||
.. _`#1006`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1006
|
||||
.. _`#1007`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1007
|
||||
.. _`#1011`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1011
|
||||
.. _`#1012`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1012
|
||||
.. _`#1013`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1013
|
||||
.. _`#1018`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1018
|
||||
.. _`#1019`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1019
|
||||
.. _`#1020`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1020
|
||||
|
||||
**2017-12-08**
|
||||
*Released 9.0.0*
|
||||
|
||||
Breaking changes (possibly)
|
||||
|
||||
- Drop support for python 3.3 (PR `#930`_)
|
||||
|
||||
|
||||
New Features
|
||||
|
||||
- Support Bot API 3.5 (PR `#920`_)
|
||||
|
||||
|
||||
Changes
|
||||
|
||||
- Fix race condition in dispatcher start/stop (`#887`_)
|
||||
- Log error trace if there is no error handler registered (`#694`_)
|
||||
- Update examples with consistent string formatting (`#870`_)
|
||||
- Various changes and improvements to the docs.
|
||||
|
||||
.. _`#920`: https://github.com/python-telegram-bot/python-telegram-bot/pull/920
|
||||
.. _`#930`: https://github.com/python-telegram-bot/python-telegram-bot/pull/930
|
||||
.. _`#887`: https://github.com/python-telegram-bot/python-telegram-bot/pull/887
|
||||
.. _`#694`: https://github.com/python-telegram-bot/python-telegram-bot/pull/694
|
||||
.. _`#870`: https://github.com/python-telegram-bot/python-telegram-bot/pull/870
|
||||
|
||||
**2017-10-15**
|
||||
*Released 8.1.1*
|
||||
|
||||
- Fix Commandhandler crashing on single character messages (PR `#873`_).
|
||||
|
||||
.. _`#873`: https://github.com/python-telegram-bot/python-telegram-bot/pull/871
|
||||
|
||||
**2017-10-14**
|
||||
*Released 8.1.0*
|
||||
|
||||
New features
|
||||
- Support Bot API 3.4 (PR `#865`_).
|
||||
|
||||
Changes
|
||||
- MessageHandler & RegexHandler now consider channel_updates.
|
||||
- Fix command not recognized if it is directly followed by a newline (PR `#869`_).
|
||||
- Removed Bot._message_wrapper (PR `#822`_).
|
||||
- Unitests are now also running on AppVeyor (Windows VM).
|
||||
- Various unitest improvements.
|
||||
- Documentation fixes.
|
||||
|
||||
.. _`#822`: https://github.com/python-telegram-bot/python-telegram-bot/pull/822
|
||||
.. _`#865`: https://github.com/python-telegram-bot/python-telegram-bot/pull/865
|
||||
.. _`#869`: https://github.com/python-telegram-bot/python-telegram-bot/pull/869
|
||||
|
||||
**2017-09-01**
|
||||
*Released 8.0.0*
|
||||
|
||||
@@ -26,7 +270,7 @@ Changes
|
||||
- Warn on small con_pool_size during custom initalization of Updater (PR `#793`_).
|
||||
- Catch exceptions in error handlerfor errors that happen during polling (PR `#810`_).
|
||||
- For testing we switched to pytest (PR `#788`_).
|
||||
- Lot's of small improvements to our tests and documentation.
|
||||
- Lots of small improvements to our tests and documentation.
|
||||
|
||||
|
||||
.. _`see docs`: http://python-telegram-bot.readthedocs.io/en/stable/telegram.ext.dispatcher.html#telegram.ext.Dispatcher.add_handler
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
# Contributor Covenant Code of Conduct
|
||||
|
||||
## Our Pledge
|
||||
|
||||
In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.
|
||||
|
||||
## Our Standards
|
||||
|
||||
Examples of behavior that contributes to creating a positive environment include:
|
||||
|
||||
* Using welcoming and inclusive language
|
||||
* Being respectful of differing viewpoints and experiences
|
||||
* Gracefully accepting constructive criticism
|
||||
* Focusing on what is best for the community
|
||||
* Showing empathy towards other community members
|
||||
|
||||
Examples of unacceptable behavior by participants include:
|
||||
|
||||
* The use of sexualized language or imagery and unwelcome sexual attention or advances
|
||||
* Publication of any content supporting, justifying or otherwise affiliating with terror and/or hate towards others
|
||||
* Trolling, insulting/derogatory comments, and personal or political attacks
|
||||
* Public or private harassment
|
||||
* Publishing others' private information, such as a physical or electronic address, without explicit permission
|
||||
* Other conduct which could reasonably be considered inappropriate in a professional setting
|
||||
|
||||
## Our Responsibilities
|
||||
|
||||
Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
|
||||
|
||||
Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
|
||||
|
||||
## Scope
|
||||
|
||||
This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.
|
||||
|
||||
## Enforcement
|
||||
|
||||
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at devs@python-telegram-bot.org. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.
|
||||
|
||||
Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.
|
||||
|
||||
## Attribution
|
||||
|
||||
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version]
|
||||
|
||||
[homepage]: http://contributor-covenant.org
|
||||
[version]: http://contributor-covenant.org/version/1/4/
|
||||
+792
@@ -0,0 +1,792 @@
|
||||
NOTICE: You can find here the GPLv3 license and after the Lesser GPLv3 license.
|
||||
You may choose either license.
|
||||
|
||||
|
||||
GNU LESSER GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. [http://fsf.org/]
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
|
||||
This version of the GNU Lesser General Public License incorporates
|
||||
the terms and conditions of version 3 of the GNU General Public
|
||||
License, supplemented by the additional permissions listed below.
|
||||
|
||||
0. Additional Definitions.
|
||||
|
||||
As used herein, "this License" refers to version 3 of the GNU Lesser
|
||||
General Public License, and the "GNU GPL" refers to version 3 of the GNU
|
||||
General Public License.
|
||||
|
||||
"The Library" refers to a covered work governed by this License,
|
||||
other than an Application or a Combined Work as defined below.
|
||||
|
||||
An "Application" is any work that makes use of an interface provided
|
||||
by the Library, but which is not otherwise based on the Library.
|
||||
Defining a subclass of a class defined by the Library is deemed a mode
|
||||
of using an interface provided by the Library.
|
||||
|
||||
A "Combined Work" is a work produced by combining or linking an
|
||||
Application with the Library. The particular version of the Library
|
||||
with which the Combined Work was made is also called the "Linked
|
||||
Version".
|
||||
|
||||
The "Minimal Corresponding Source" for a Combined Work means the
|
||||
Corresponding Source for the Combined Work, excluding any source code
|
||||
for portions of the Combined Work that, considered in isolation, are
|
||||
based on the Application, and not on the Linked Version.
|
||||
|
||||
The "Corresponding Application Code" for a Combined Work means the
|
||||
object code and/or source code for the Application, including any data
|
||||
and utility programs needed for reproducing the Combined Work from the
|
||||
Application, but excluding the System Libraries of the Combined Work.
|
||||
|
||||
1. Exception to Section 3 of the GNU GPL.
|
||||
|
||||
You may convey a covered work under sections 3 and 4 of this License
|
||||
without being bound by section 3 of the GNU GPL.
|
||||
|
||||
2. Conveying Modified Versions.
|
||||
|
||||
If you modify a copy of the Library, and, in your modifications, a
|
||||
facility refers to a function or data to be supplied by an Application
|
||||
that uses the facility (other than as an argument passed when the
|
||||
facility is invoked), then you may convey a copy of the modified
|
||||
version:
|
||||
|
||||
a) under this License, provided that you make a good faith effort to
|
||||
ensure that, in the event an Application does not supply the
|
||||
function or data, the facility still operates, and performs
|
||||
whatever part of its purpose remains meaningful, or
|
||||
|
||||
b) under the GNU GPL, with none of the additional permissions of
|
||||
this License applicable to that copy.
|
||||
|
||||
3. Object Code Incorporating Material from Library Header Files.
|
||||
|
||||
The object code form of an Application may incorporate material from
|
||||
a header file that is part of the Library. You may convey such object
|
||||
code under terms of your choice, provided that, if the incorporated
|
||||
material is not limited to numerical parameters, data structure
|
||||
layouts and accessors, or small macros, inline functions and templates
|
||||
(ten or fewer lines in length), you do both of the following:
|
||||
|
||||
a) Give prominent notice with each copy of the object code that the
|
||||
Library is used in it and that the Library and its use are
|
||||
covered by this License.
|
||||
|
||||
b) Accompany the object code with a copy of the GNU GPL and this license
|
||||
document.
|
||||
|
||||
4. Combined Works.
|
||||
|
||||
You may convey a Combined Work under terms of your choice that,
|
||||
taken together, effectively do not restrict modification of the
|
||||
portions of the Library contained in the Combined Work and reverse
|
||||
engineering for debugging such modifications, if you also do each of
|
||||
the following:
|
||||
|
||||
a) Give prominent notice with each copy of the Combined Work that
|
||||
the Library is used in it and that the Library and its use are
|
||||
covered by this License.
|
||||
|
||||
b) Accompany the Combined Work with a copy of the GNU GPL and this license
|
||||
document.
|
||||
|
||||
c) For a Combined Work that displays copyright notices during
|
||||
execution, include the copyright notice for the Library among
|
||||
these notices, as well as a reference directing the user to the
|
||||
copies of the GNU GPL and this license document.
|
||||
|
||||
d) Do one of the following:
|
||||
|
||||
0) Convey the Minimal Corresponding Source under the terms of this
|
||||
License, and the Corresponding Application Code in a form
|
||||
suitable for, and under terms that permit, the user to
|
||||
recombine or relink the Application with a modified version of
|
||||
the Linked Version to produce a modified Combined Work, in the
|
||||
manner specified by section 6 of the GNU GPL for conveying
|
||||
Corresponding Source.
|
||||
|
||||
1) Use a suitable shared library mechanism for linking with the
|
||||
Library. A suitable mechanism is one that (a) uses at run time
|
||||
a copy of the Library already present on the user's computer
|
||||
system, and (b) will operate properly with a modified version
|
||||
of the Library that is interface-compatible with the Linked
|
||||
Version.
|
||||
|
||||
e) Provide Installation Information, but only if you would otherwise
|
||||
be required to provide such information under section 6 of the
|
||||
GNU GPL, and only to the extent that such information is
|
||||
necessary to install and execute a modified version of the
|
||||
Combined Work produced by recombining or relinking the
|
||||
Application with a modified version of the Linked Version. (If
|
||||
you use option 4d0, the Installation Information must accompany
|
||||
the Minimal Corresponding Source and Corresponding Application
|
||||
Code. If you use option 4d1, you must provide the Installation
|
||||
Information in the manner specified by section 6 of the GNU GPL
|
||||
for conveying Corresponding Source.)
|
||||
|
||||
5. Combined Libraries.
|
||||
|
||||
You may place library facilities that are a work based on the
|
||||
Library side by side in a single library together with other library
|
||||
facilities that are not Applications and are not covered by this
|
||||
License, and convey such a combined library under terms of your
|
||||
choice, if you do both of the following:
|
||||
|
||||
a) Accompany the combined library with a copy of the same work based
|
||||
on the Library, uncombined with any other library facilities,
|
||||
conveyed under the terms of this License.
|
||||
|
||||
b) Give prominent notice with the combined library that part of it
|
||||
is a work based on the Library, and explaining where to find the
|
||||
accompanying uncombined form of the same work.
|
||||
|
||||
6. Revised Versions of the GNU Lesser General Public License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions
|
||||
of the GNU Lesser General Public License from time to time. Such new
|
||||
versions will be similar in spirit to the present version, but may
|
||||
differ in detail to address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Library as you received it specifies that a certain numbered version
|
||||
of the GNU Lesser General Public License "or any later version"
|
||||
applies to it, you have the option of following the terms and
|
||||
conditions either of that published version or of any later version
|
||||
published by the Free Software Foundation. If the Library as you
|
||||
received it does not specify a version number of the GNU Lesser
|
||||
General Public License, you may choose any version of the GNU Lesser
|
||||
General Public License ever published by the Free Software Foundation.
|
||||
|
||||
If the Library as you received it specifies that a proxy can decide
|
||||
whether future versions of the GNU Lesser General Public License shall
|
||||
apply, that proxy's public statement of acceptance of any version is
|
||||
permanent authorization for you to choose that version for the
|
||||
Library.
|
||||
|
||||
|
||||
|
||||
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. [http://fsf.org/]
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
+17
-10
@@ -5,15 +5,17 @@
|
||||
|
||||
We have made you a wrapper you can't refuse
|
||||
|
||||
We have a vibrant community of developers helping each other in our `Telegram group <https://telegram.me/pythontelegrambotgroup>`_. Join us!
|
||||
|
||||
*Stay tuned for library updates and new releases on our* `Telegram Channel <https://telegram.me/pythontelegrambotchannel>`_.
|
||||
|
||||
.. image:: https://img.shields.io/pypi/v/python-telegram-bot.svg
|
||||
:target: https://pypi.python.org/pypi/python-telegram-bot
|
||||
:target: https://pypi.org/project/python-telegram-bot/
|
||||
:alt: PyPi Package Version
|
||||
|
||||
.. image:: https://img.shields.io/pypi/pyversions/python-telegram-bot.svg
|
||||
:target: https://pypi.python.org/pypi/python-telegram-bot
|
||||
:alt: Supported python versions
|
||||
:target: https://pypi.org/project/python-telegram-bot/
|
||||
:alt: Supported Python versions
|
||||
|
||||
.. image:: https://www.cpu.re/static/python-telegram-bot/downloads.svg
|
||||
:target: https://www.cpu.re/static/python-telegram-bot/downloads-by-python-version.txt
|
||||
@@ -31,13 +33,14 @@ We have made you a wrapper you can't refuse
|
||||
:target: https://travis-ci.org/python-telegram-bot/python-telegram-bot
|
||||
:alt: Travis CI Status
|
||||
|
||||
.. 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://img.shields.io/appveyor/ci/python-telegram-bot/python-telegram-bot/master.svg?logo=appveyor
|
||||
:target: https://ci.appveyor.com/project/python-telegram-bot/python-telegram-bot
|
||||
:alt: AppVeyor CI Status
|
||||
|
||||
.. 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
|
||||
|
||||
.. image:: https://codecov.io/gh/python-telegram-bot/python-telegram-bot/branch/master/graph/badge.svg
|
||||
:target: https://codecov.io/gh/python-telegram-bot/python-telegram-bot
|
||||
:alt: Code coverage
|
||||
|
||||
.. image:: http://isitmaintained.com/badge/resolution/python-telegram-bot/python-telegram-bot.svg
|
||||
:target: http://isitmaintained.com/project/python-telegram-bot/python-telegram-bot
|
||||
@@ -47,6 +50,10 @@ We have made you a wrapper you can't refuse
|
||||
:target: https://telegram.me/pythontelegrambotgroup
|
||||
:alt: Telegram Group
|
||||
|
||||
.. image:: https://img.shields.io/badge/IRC-Channel-blue.svg
|
||||
:target: https://webchat.freenode.net/?channels=##python-telegram-bot
|
||||
:alt: IRC Bridge
|
||||
|
||||
=================
|
||||
Table of contents
|
||||
=================
|
||||
@@ -88,7 +95,7 @@ make the development of bots easy and straightforward. These classes are contain
|
||||
Telegram API support
|
||||
====================
|
||||
|
||||
As of **23. July 2017**, all types and methods of the Telegram Bot API 3.2 are supported.
|
||||
All types and methods of the Telegram Bot API **4.0** are supported.
|
||||
|
||||
==========
|
||||
Installing
|
||||
|
||||
+19
-8
@@ -7,21 +7,32 @@ environment:
|
||||
# isn't covered by this document) at the time of writing.
|
||||
|
||||
- PYTHON: "C:\\Python27"
|
||||
- PYTHON: "C:\\Python33"
|
||||
- PYTHON: "C:\\Python34"
|
||||
- PYTHON: "C:\\Python35"
|
||||
- PYTHON: "C:\\Python36"
|
||||
|
||||
branches:
|
||||
only:
|
||||
- master
|
||||
|
||||
skip_branch_with_pr: true
|
||||
|
||||
max_jobs: 1
|
||||
|
||||
install:
|
||||
# We need wheel installed to build wheels
|
||||
- "SET PATH=%PYTHON%;%PYTHON%\\Scripts;%PATH%"
|
||||
- "git submodule update --init --recursive"
|
||||
- "%PYTHON%\\python.exe -m pip install -U wheel"
|
||||
- "%PYTHON%\\python.exe -m pip install -r requirements.txt"
|
||||
- "%PYTHON%\\python.exe -m pip install -r requirements-dev.txt"
|
||||
# Check that we have the expected version and architecture for Python
|
||||
- "python --version"
|
||||
# We need wheel installed to build wheels
|
||||
- "pip install -U codecov pytest-cov"
|
||||
- "pip install -r requirements.txt"
|
||||
- "pip install -r requirements-dev.txt"
|
||||
|
||||
build: off
|
||||
|
||||
cache: C:\Users\appveyor\pip\wheels
|
||||
|
||||
test_script:
|
||||
- "%python%\\Scripts\\pytest -v --cov=telegram"
|
||||
- "pytest -m \"not nocoverage\" --cov --cov-report xml:coverage.xml"
|
||||
|
||||
after_test:
|
||||
- "codecov -f coverage.xml -F Appveyor"
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
comment: false
|
||||
+4
-12
@@ -50,7 +50,7 @@ master_doc = 'index'
|
||||
|
||||
# General information about the project.
|
||||
project = u'Python Telegram Bot'
|
||||
copyright = u'2015-2017, Leandro Toledo'
|
||||
copyright = u'2015-2018, 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 = '8.0' # telegram.__version__[:3]
|
||||
version = '11.0' # telegram.__version__[:3]
|
||||
# The full version, including alpha/beta/rc tags.
|
||||
release = '8.0.0' # telegram.__version__
|
||||
release = '11.0.0' # telegram.__version__
|
||||
|
||||
# The language for content autogenerated by Sphinx. Refer to documentation
|
||||
# for a list of supported languages.
|
||||
@@ -291,17 +291,9 @@ texinfo_documents = [
|
||||
|
||||
# -- script stuff --------------------------------------------------------
|
||||
|
||||
import inspect
|
||||
|
||||
|
||||
def autodoc_skip_member(app, what, name, obj, skip, options):
|
||||
try:
|
||||
if inspect.getmodule(obj).__name__.startswith('telegram') and inspect.isfunction(obj):
|
||||
if name.lower() != name:
|
||||
return True
|
||||
except AttributeError:
|
||||
pass
|
||||
# Return None so napoleon can handle it
|
||||
pass
|
||||
|
||||
|
||||
def setup(app):
|
||||
|
||||
@@ -12,6 +12,10 @@ objects in the package reflect the types as defined by the `telegram bot api <ht
|
||||
.. toctree::
|
||||
telegram
|
||||
|
||||
Changelog
|
||||
---------
|
||||
|
||||
.. include:: ../../CHANGES.rst
|
||||
|
||||
Indices and tables
|
||||
==================
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
telegram.Credentials
|
||||
====================
|
||||
|
||||
.. autoclass:: telegram.Credentials
|
||||
:members:
|
||||
:show-inheritance:
|
||||
@@ -0,0 +1,6 @@
|
||||
telegram.DataCredentials
|
||||
========================
|
||||
|
||||
.. autoclass:: telegram.DataCredentials
|
||||
:members:
|
||||
:show-inheritance:
|
||||
@@ -0,0 +1,6 @@
|
||||
telegram.EncryptedCredentials
|
||||
=============================
|
||||
|
||||
.. autoclass:: telegram.EncryptedCredentials
|
||||
:members:
|
||||
:show-inheritance:
|
||||
@@ -0,0 +1,6 @@
|
||||
telegram.EncryptedPassportElement
|
||||
=================================
|
||||
|
||||
.. autoclass:: telegram.EncryptedPassportElement
|
||||
:members:
|
||||
:show-inheritance:
|
||||
@@ -0,0 +1,6 @@
|
||||
telegram.ext.Job
|
||||
=====================
|
||||
|
||||
.. autoclass:: telegram.ext.Job
|
||||
:members:
|
||||
:show-inheritance:
|
||||
@@ -6,6 +6,7 @@ telegram.ext package
|
||||
telegram.ext.updater
|
||||
telegram.ext.dispatcher
|
||||
telegram.ext.filters
|
||||
telegram.ext.job
|
||||
telegram.ext.jobqueue
|
||||
telegram.ext.messagequeue
|
||||
telegram.ext.delayqueue
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
telegram.FileCredentials
|
||||
========================
|
||||
|
||||
.. autoclass:: telegram.FileCredentials
|
||||
:members:
|
||||
:show-inheritance:
|
||||
@@ -0,0 +1,6 @@
|
||||
telegram.IdDocumentData
|
||||
=======================
|
||||
|
||||
.. autoclass:: telegram.IdDocumentData
|
||||
:members:
|
||||
:show-inheritance:
|
||||
@@ -0,0 +1,6 @@
|
||||
telegram.InputMedia
|
||||
===================
|
||||
|
||||
.. autoclass:: telegram.InputMedia
|
||||
:members:
|
||||
:show-inheritance:
|
||||
@@ -0,0 +1,6 @@
|
||||
telegram.InputMediaAnimation
|
||||
============================
|
||||
|
||||
.. autoclass:: telegram.InputMediaAnimation
|
||||
:members:
|
||||
:show-inheritance:
|
||||
@@ -0,0 +1,6 @@
|
||||
telegram.InputMediaAudio
|
||||
========================
|
||||
|
||||
.. autoclass:: telegram.InputMediaAudio
|
||||
:members:
|
||||
:show-inheritance:
|
||||
@@ -0,0 +1,6 @@
|
||||
telegram.InputMediaDocument
|
||||
===========================
|
||||
|
||||
.. autoclass:: telegram.InputMediaDocument
|
||||
:members:
|
||||
:show-inheritance:
|
||||
@@ -0,0 +1,6 @@
|
||||
telegram.InputMediaPhoto
|
||||
========================
|
||||
|
||||
.. autoclass:: telegram.InputMediaPhoto
|
||||
:members:
|
||||
:show-inheritance:
|
||||
@@ -0,0 +1,6 @@
|
||||
telegram.InputMediaVideo
|
||||
========================
|
||||
|
||||
.. autoclass:: telegram.InputMediaVideo
|
||||
:members:
|
||||
:show-inheritance:
|
||||
@@ -0,0 +1,6 @@
|
||||
telegram.PassportData
|
||||
=====================
|
||||
|
||||
.. autoclass:: telegram.PassportData
|
||||
:members:
|
||||
:show-inheritance:
|
||||
@@ -0,0 +1,6 @@
|
||||
telegram.PassportElementError
|
||||
=============================
|
||||
|
||||
.. autoclass:: telegram.PassportElementError
|
||||
:members:
|
||||
:show-inheritance:
|
||||
@@ -0,0 +1,6 @@
|
||||
telegram.PassportElementErrorDataField
|
||||
======================================
|
||||
|
||||
.. autoclass:: telegram.PassportElementErrorDataField
|
||||
:members:
|
||||
:show-inheritance:
|
||||
@@ -0,0 +1,6 @@
|
||||
telegram.PassportElementErrorFile
|
||||
=================================
|
||||
|
||||
.. autoclass:: telegram.PassportElementErrorFile
|
||||
:members:
|
||||
:show-inheritance:
|
||||
@@ -0,0 +1,6 @@
|
||||
telegram.PassportElementErrorFiles
|
||||
==================================
|
||||
|
||||
.. autoclass:: telegram.PassportElementErrorFiles
|
||||
:members:
|
||||
:show-inheritance:
|
||||
@@ -0,0 +1,6 @@
|
||||
telegram.PassportElementErrorFrontSide
|
||||
======================================
|
||||
|
||||
.. autoclass:: telegram.PassportElementErrorFrontSide
|
||||
:members:
|
||||
:show-inheritance:
|
||||
@@ -0,0 +1,6 @@
|
||||
telegram.PassportElementErrorReverseSide
|
||||
========================================
|
||||
|
||||
.. autoclass:: telegram.PassportElementErrorReverseSide
|
||||
:members:
|
||||
:show-inheritance:
|
||||
@@ -0,0 +1,6 @@
|
||||
telegram.PassportFile
|
||||
=====================
|
||||
|
||||
.. autoclass:: telegram.PassportFile
|
||||
:members:
|
||||
:show-inheritance:
|
||||
@@ -0,0 +1,6 @@
|
||||
telegram.PersonalDetails
|
||||
========================
|
||||
|
||||
.. autoclass:: telegram.PersonalDetails
|
||||
:members:
|
||||
:show-inheritance:
|
||||
@@ -0,0 +1,6 @@
|
||||
telegram.ResidentialAddress
|
||||
===========================
|
||||
|
||||
.. autoclass:: telegram.ResidentialAddress
|
||||
:members:
|
||||
:show-inheritance:
|
||||
@@ -4,6 +4,8 @@ telegram package
|
||||
.. toctree::
|
||||
|
||||
telegram.ext
|
||||
telegram.utils
|
||||
telegram.animation
|
||||
telegram.audio
|
||||
telegram.bot
|
||||
telegram.callbackquery
|
||||
@@ -20,6 +22,12 @@ telegram package
|
||||
telegram.inlinekeyboardbutton
|
||||
telegram.inlinekeyboardmarkup
|
||||
telegram.inputfile
|
||||
telegram.inputmedia
|
||||
telegram.inputmediaanimation
|
||||
telegram.inputmediaaudio
|
||||
telegram.inputmediadocument
|
||||
telegram.inputmediaphoto
|
||||
telegram.inputmediavideo
|
||||
telegram.keyboardbutton
|
||||
telegram.location
|
||||
telegram.message
|
||||
@@ -102,10 +110,33 @@ Games
|
||||
.. toctree::
|
||||
|
||||
telegram.game
|
||||
telegram.animation
|
||||
telegram.callbackgame
|
||||
telegram.gamehighscore
|
||||
|
||||
Passport
|
||||
--------
|
||||
|
||||
.. toctree::
|
||||
|
||||
telegram.passportelementerror
|
||||
telegram.passportelementerrorfile
|
||||
telegram.passportelementerrorreverseside
|
||||
telegram.passportelementerrorfrontside
|
||||
telegram.passportelementerrorfiles
|
||||
telegram.passportelementerrordatafield
|
||||
telegram.passportelementerrorfile
|
||||
telegram.credentials
|
||||
telegram.datacredentials
|
||||
telegram.securedata
|
||||
telegram.filecredentials
|
||||
telegram.iddocumentdata
|
||||
telegram.personaldetails
|
||||
telegram.residentialaddress
|
||||
telegram.passportdata
|
||||
telegram.passportfile
|
||||
telegram.encryptedpassportelement
|
||||
telegram.encryptedcredentials
|
||||
|
||||
|
||||
Module contents
|
||||
---------------
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
telegram.SecureData
|
||||
===================
|
||||
|
||||
.. autoclass:: telegram.SecureData
|
||||
:members:
|
||||
:show-inheritance:
|
||||
@@ -0,0 +1,6 @@
|
||||
telegram.utils.helpers Module
|
||||
=============================
|
||||
|
||||
.. automodule:: telegram.utils.helpers
|
||||
:members:
|
||||
:show-inheritance:
|
||||
@@ -0,0 +1,6 @@
|
||||
telegram.utils.promise.Promise
|
||||
==============================
|
||||
|
||||
.. autoclass:: telegram.utils.promise.Promise
|
||||
:members:
|
||||
:show-inheritance:
|
||||
@@ -0,0 +1,6 @@
|
||||
telegram.utils.request.Request
|
||||
==============================
|
||||
|
||||
.. autoclass:: telegram.utils.request.Request
|
||||
:members:
|
||||
:show-inheritance:
|
||||
@@ -0,0 +1,8 @@
|
||||
telegram.utils package
|
||||
======================
|
||||
|
||||
.. toctree::
|
||||
|
||||
telegram.utils.helpers
|
||||
telegram.utils.promise
|
||||
telegram.utils.request
|
||||
+4
-1
@@ -1,6 +1,6 @@
|
||||
# Examples
|
||||
|
||||
The examples in this folder are small bots meant to show you how a bot that is written with `python-telegram-bot` looks like. Some bots focus on one specific aspect of the Telegram Bot API while others focus on one of the mechanics of this library. Except for the `echobot.py` example, they all use the high-level framework this library provides with the `telegram.ext` submodule.
|
||||
In this folder there are small examples to show what a bot written with `python-telegram-bot` looks like. Some bots focus on one specific aspect of the Telegram Bot API while others focus on one of the mechanics of this library. Except for the [`echobot.py`](#pure-api) example, they all use the high-level framework this library provides with the [`telegram.ext`](https://python-telegram-bot.readthedocs.io/en/latest/telegram.ext.html) submodule.
|
||||
|
||||
All examples are licensed under the [CC0 License](https://github.com/python-telegram-bot/python-telegram-bot/blob/master/examples/LICENSE.txt) and are therefore fully dedicated to the public domain. You can use them as the base for your own bots without worrying about copyrights.
|
||||
|
||||
@@ -22,5 +22,8 @@ This example sheds some light on inline keyboards, callback queries and message
|
||||
### [`inlinebot.py`](https://github.com/python-telegram-bot/python-telegram-bot/blob/master/examples/inlinebot.py)
|
||||
A basic example of an [inline bot](https://core.telegram.org/bots/inline). Don't forget to enable inline mode with [@BotFather](https://telegram.me/BotFather).
|
||||
|
||||
### [`paymentbot.py`](https://github.com/python-telegram-bot/python-telegram-bot/blob/master/examples/paymentbot.py)
|
||||
A basic example of a bot that can accept payments. Don't forget to enable and configure payments with [@BotFather](https://telegram.me/BotFather).
|
||||
|
||||
## Pure API
|
||||
The [`echobot.py`](https://github.com/python-telegram-bot/python-telegram-bot/blob/master/examples/echobot.py) example uses only the pure, "bare-metal" API wrapper.
|
||||
|
||||
@@ -46,7 +46,7 @@ def start(bot, update):
|
||||
|
||||
def gender(bot, update):
|
||||
user = update.message.from_user
|
||||
logger.info("Gender of %s: %s" % (user.first_name, update.message.text))
|
||||
logger.info("Gender of %s: %s", user.first_name, update.message.text)
|
||||
update.message.reply_text('I see! Please send me a photo of yourself, '
|
||||
'so I know what you look like, or send /skip if you don\'t want to.',
|
||||
reply_markup=ReplyKeyboardRemove())
|
||||
@@ -58,7 +58,7 @@ def photo(bot, update):
|
||||
user = update.message.from_user
|
||||
photo_file = bot.get_file(update.message.photo[-1].file_id)
|
||||
photo_file.download('user_photo.jpg')
|
||||
logger.info("Photo of %s: %s" % (user.first_name, 'user_photo.jpg'))
|
||||
logger.info("Photo of %s: %s", user.first_name, 'user_photo.jpg')
|
||||
update.message.reply_text('Gorgeous! Now, send me your location please, '
|
||||
'or send /skip if you don\'t want to.')
|
||||
|
||||
@@ -67,7 +67,7 @@ def photo(bot, update):
|
||||
|
||||
def skip_photo(bot, update):
|
||||
user = update.message.from_user
|
||||
logger.info("User %s did not send a photo." % user.first_name)
|
||||
logger.info("User %s did not send a photo.", user.first_name)
|
||||
update.message.reply_text('I bet you look great! Now, send me your location please, '
|
||||
'or send /skip.')
|
||||
|
||||
@@ -77,8 +77,8 @@ def skip_photo(bot, update):
|
||||
def location(bot, update):
|
||||
user = update.message.from_user
|
||||
user_location = update.message.location
|
||||
logger.info("Location of %s: %f / %f"
|
||||
% (user.first_name, user_location.latitude, user_location.longitude))
|
||||
logger.info("Location of %s: %f / %f", user.first_name, user_location.latitude,
|
||||
user_location.longitude)
|
||||
update.message.reply_text('Maybe I can visit you sometime! '
|
||||
'At last, tell me something about yourself.')
|
||||
|
||||
@@ -87,7 +87,7 @@ def location(bot, update):
|
||||
|
||||
def skip_location(bot, update):
|
||||
user = update.message.from_user
|
||||
logger.info("User %s did not send a location." % user.first_name)
|
||||
logger.info("User %s did not send a location.", user.first_name)
|
||||
update.message.reply_text('You seem a bit paranoid! '
|
||||
'At last, tell me something about yourself.')
|
||||
|
||||
@@ -96,7 +96,7 @@ def skip_location(bot, update):
|
||||
|
||||
def bio(bot, update):
|
||||
user = update.message.from_user
|
||||
logger.info("Bio of %s: %s" % (user.first_name, update.message.text))
|
||||
logger.info("Bio of %s: %s", user.first_name, update.message.text)
|
||||
update.message.reply_text('Thank you! I hope we can talk again some day.')
|
||||
|
||||
return ConversationHandler.END
|
||||
@@ -104,7 +104,7 @@ def bio(bot, update):
|
||||
|
||||
def cancel(bot, update):
|
||||
user = update.message.from_user
|
||||
logger.info("User %s canceled the conversation." % user.first_name)
|
||||
logger.info("User %s canceled the conversation.", user.first_name)
|
||||
update.message.reply_text('Bye! I hope we can talk again some day.',
|
||||
reply_markup=ReplyKeyboardRemove())
|
||||
|
||||
@@ -112,7 +112,8 @@ def cancel(bot, update):
|
||||
|
||||
|
||||
def error(bot, update, error):
|
||||
logger.warn('Update "%s" caused error "%s"' % (update, error))
|
||||
"""Log Errors caused by Updates."""
|
||||
logger.warning('Update "%s" caused error "%s"', update, error)
|
||||
|
||||
|
||||
def main():
|
||||
|
||||
@@ -41,7 +41,7 @@ def facts_to_str(user_data):
|
||||
facts = list()
|
||||
|
||||
for key, value in user_data.items():
|
||||
facts.append('%s - %s' % (key, value))
|
||||
facts.append('{} - {}'.format(key, value))
|
||||
|
||||
return "\n".join(facts).join(['\n', '\n'])
|
||||
|
||||
@@ -58,7 +58,8 @@ def start(bot, update):
|
||||
def regular_choice(bot, update, user_data):
|
||||
text = update.message.text
|
||||
user_data['choice'] = text
|
||||
update.message.reply_text('Your %s? Yes, I would love to hear about that!' % text.lower())
|
||||
update.message.reply_text(
|
||||
'Your {}? Yes, I would love to hear about that!'.format(text.lower()))
|
||||
|
||||
return TYPING_REPLY
|
||||
|
||||
@@ -77,10 +78,9 @@ def received_information(bot, update, user_data):
|
||||
del user_data['choice']
|
||||
|
||||
update.message.reply_text("Neat! Just so you know, this is what you already told me:"
|
||||
"%s"
|
||||
"You can tell me more, or change your opinion on something."
|
||||
% facts_to_str(user_data),
|
||||
reply_markup=markup)
|
||||
"{}"
|
||||
"You can tell me more, or change your opinion on something.".format(
|
||||
facts_to_str(user_data)), reply_markup=markup)
|
||||
|
||||
return CHOOSING
|
||||
|
||||
@@ -90,15 +90,16 @@ def done(bot, update, user_data):
|
||||
del user_data['choice']
|
||||
|
||||
update.message.reply_text("I learned these facts about you:"
|
||||
"%s"
|
||||
"Until next time!" % facts_to_str(user_data))
|
||||
"{}"
|
||||
"Until next time!".format(facts_to_str(user_data)))
|
||||
|
||||
user_data.clear()
|
||||
return ConversationHandler.END
|
||||
|
||||
|
||||
def error(bot, update, error):
|
||||
logger.warn('Update "%s" caused error "%s"' % (update, error))
|
||||
"""Log Errors caused by Updates."""
|
||||
logger.warning('Update "%s" caused error "%s"', update, error)
|
||||
|
||||
|
||||
def main():
|
||||
|
||||
+9
-4
@@ -1,9 +1,11 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
#
|
||||
# Simple Bot to reply to Telegram messages. This is built on the API wrapper, see
|
||||
# echobot2.py to see the same example built on the telegram.ext bot framework.
|
||||
# This program is dedicated to the public domain under the CC0 license.
|
||||
"""Simple Bot to reply to Telegram messages.
|
||||
|
||||
This is built on the API wrapper, see echobot2.py to see the same example built
|
||||
on the telegram.ext bot framework.
|
||||
This program is dedicated to the public domain under the CC0 license.
|
||||
"""
|
||||
import logging
|
||||
import telegram
|
||||
from telegram.error import NetworkError, Unauthorized
|
||||
@@ -12,7 +14,9 @@ from time import sleep
|
||||
|
||||
update_id = None
|
||||
|
||||
|
||||
def main():
|
||||
"""Run the bot."""
|
||||
global update_id
|
||||
# Telegram Bot Authorization Token
|
||||
bot = telegram.Bot('TOKEN')
|
||||
@@ -37,6 +41,7 @@ def main():
|
||||
|
||||
|
||||
def echo(bot):
|
||||
"""Echo the message the user sent."""
|
||||
global update_id
|
||||
# Request updates after the last update_id
|
||||
for update in bot.get_updates(offset=update_id, timeout=10):
|
||||
|
||||
+11
-5
@@ -1,9 +1,10 @@
|
||||
#!/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.
|
||||
"""
|
||||
|
||||
"""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
|
||||
@@ -29,22 +30,27 @@ 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):
|
||||
"""Send a message when the command /start is issued."""
|
||||
update.message.reply_text('Hi!')
|
||||
|
||||
|
||||
def help(bot, update):
|
||||
"""Send a message when the command /help is issued."""
|
||||
update.message.reply_text('Help!')
|
||||
|
||||
|
||||
def echo(bot, update):
|
||||
"""Echo the user message."""
|
||||
update.message.reply_text(update.message.text)
|
||||
|
||||
|
||||
def error(bot, update, error):
|
||||
logger.warn('Update "%s" caused error "%s"' % (update, error))
|
||||
"""Log Errors caused by Updates."""
|
||||
logger.warning('Update "%s" caused error "%s"', update, error)
|
||||
|
||||
|
||||
def main():
|
||||
"""Start the bot."""
|
||||
# Create the EventHandler and pass it your bot's token.
|
||||
updater = Updater("TOKEN")
|
||||
|
||||
|
||||
+29
-30
@@ -1,9 +1,10 @@
|
||||
#!/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.
|
||||
"""
|
||||
|
||||
"""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
|
||||
@@ -17,7 +18,7 @@ bot.
|
||||
"""
|
||||
from uuid import uuid4
|
||||
|
||||
import re
|
||||
from telegram.utils.helpers import escape_markdown
|
||||
|
||||
from telegram import InlineQueryResultArticle, ParseMode, \
|
||||
InputTextMessageContent
|
||||
@@ -34,45 +35,43 @@ 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):
|
||||
"""Send a message when the command /start is issued."""
|
||||
update.message.reply_text('Hi!')
|
||||
|
||||
|
||||
def help(bot, update):
|
||||
"""Send a message when the command /help is issued."""
|
||||
update.message.reply_text('Help!')
|
||||
|
||||
|
||||
def escape_markdown(text):
|
||||
"""Helper function to escape telegram markup symbols"""
|
||||
escape_chars = '\*_`\['
|
||||
return re.sub(r'([%s])' % escape_chars, r'\\\1', text)
|
||||
|
||||
|
||||
def inlinequery(bot, update):
|
||||
"""Handle the inline query."""
|
||||
query = update.inline_query.query
|
||||
results = list()
|
||||
|
||||
results.append(InlineQueryResultArticle(id=uuid4(),
|
||||
title="Caps",
|
||||
input_message_content=InputTextMessageContent(
|
||||
query.upper())))
|
||||
|
||||
results.append(InlineQueryResultArticle(id=uuid4(),
|
||||
title="Bold",
|
||||
input_message_content=InputTextMessageContent(
|
||||
"*%s*" % escape_markdown(query),
|
||||
parse_mode=ParseMode.MARKDOWN)))
|
||||
|
||||
results.append(InlineQueryResultArticle(id=uuid4(),
|
||||
title="Italic",
|
||||
input_message_content=InputTextMessageContent(
|
||||
"_%s_" % escape_markdown(query),
|
||||
parse_mode=ParseMode.MARKDOWN)))
|
||||
results = [
|
||||
InlineQueryResultArticle(
|
||||
id=uuid4(),
|
||||
title="Caps",
|
||||
input_message_content=InputTextMessageContent(
|
||||
query.upper())),
|
||||
InlineQueryResultArticle(
|
||||
id=uuid4(),
|
||||
title="Bold",
|
||||
input_message_content=InputTextMessageContent(
|
||||
"*{}*".format(escape_markdown(query)),
|
||||
parse_mode=ParseMode.MARKDOWN)),
|
||||
InlineQueryResultArticle(
|
||||
id=uuid4(),
|
||||
title="Italic",
|
||||
input_message_content=InputTextMessageContent(
|
||||
"_{}_".format(escape_markdown(query)),
|
||||
parse_mode=ParseMode.MARKDOWN))]
|
||||
|
||||
update.inline_query.answer(results)
|
||||
|
||||
|
||||
def error(bot, update, error):
|
||||
logger.warning('Update "%s" caused error "%s"' % (update, error))
|
||||
"""Log Errors caused by Updates."""
|
||||
logger.warning('Update "%s" caused error "%s"', update, error)
|
||||
|
||||
|
||||
def main():
|
||||
|
||||
+23
-16
@@ -1,15 +1,16 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
#
|
||||
# Basic example for a bot that uses inline keyboards.
|
||||
# This program is dedicated to the public domain under the CC0 license.
|
||||
"""Basic example for a bot that uses inline keyboards.
|
||||
|
||||
# This program is dedicated to the public domain under the CC0 license.
|
||||
"""
|
||||
import logging
|
||||
from telegram import InlineKeyboardButton, InlineKeyboardMarkup
|
||||
from telegram.ext import Updater, CommandHandler, CallbackQueryHandler
|
||||
|
||||
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
|
||||
level=logging.INFO)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def start(bot, update):
|
||||
@@ -26,7 +27,7 @@ def start(bot, update):
|
||||
def button(bot, update):
|
||||
query = update.callback_query
|
||||
|
||||
bot.edit_message_text(text="Selected option: %s" % query.data,
|
||||
bot.edit_message_text(text="Selected option: {}".format(query.data),
|
||||
chat_id=query.message.chat_id,
|
||||
message_id=query.message.message_id)
|
||||
|
||||
@@ -36,20 +37,26 @@ def help(bot, update):
|
||||
|
||||
|
||||
def error(bot, update, error):
|
||||
logging.warning('Update "%s" caused error "%s"' % (update, error))
|
||||
"""Log Errors caused by Updates."""
|
||||
logger.warning('Update "%s" caused error "%s"', update, error)
|
||||
|
||||
|
||||
# Create the Updater and pass it your bot's token.
|
||||
updater = Updater("TOKEN")
|
||||
def main():
|
||||
# Create the Updater and pass it your bot's token.
|
||||
updater = Updater("TOKEN")
|
||||
|
||||
updater.dispatcher.add_handler(CommandHandler('start', start))
|
||||
updater.dispatcher.add_handler(CallbackQueryHandler(button))
|
||||
updater.dispatcher.add_handler(CommandHandler('help', help))
|
||||
updater.dispatcher.add_error_handler(error)
|
||||
updater.dispatcher.add_handler(CommandHandler('start', start))
|
||||
updater.dispatcher.add_handler(CallbackQueryHandler(button))
|
||||
updater.dispatcher.add_handler(CommandHandler('help', help))
|
||||
updater.dispatcher.add_error_handler(error)
|
||||
|
||||
# Start the Bot
|
||||
updater.start_polling()
|
||||
# Start the Bot
|
||||
updater.start_polling()
|
||||
|
||||
# Run the bot until the user presses Ctrl-C or the process receives SIGINT,
|
||||
# SIGTERM or SIGABRT
|
||||
updater.idle()
|
||||
# Run the bot until the user presses Ctrl-C or the process receives SIGINT,
|
||||
# SIGTERM or SIGABRT
|
||||
updater.idle()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<title>Telegram passport test!</title>
|
||||
<meta charset="utf-8">
|
||||
<meta http-equiv="X-UA-Compatible" content="IE=edge">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
|
||||
<!--- Needs file from https://github.com/TelegramMessenger/TGPassportJsSDK downloaded --->
|
||||
<script src="telegram-passport.js"></script>
|
||||
<script>
|
||||
"use strict";
|
||||
|
||||
Telegram.Passport.createAuthButton('telegram_passport_auth', {
|
||||
bot_id: BOT_ID, // YOUR BOT ID
|
||||
scope: {data: [{type: 'id_document', selfie: true}, 'address_document', 'phone_number', 'email'], v: 1}, // WHAT DATA YOU WANT TO RECEIVE
|
||||
public_key: '-----BEGIN PUBLIC KEY----- ...', // YOUR PUBLIC KEY
|
||||
payload: 'thisisatest', // YOUR BOT WILL RECEIVE THIS DATA WITH THE REQUEST
|
||||
callback_url: 'https://example.org' // TELEGRAM WILL SEND YOUR USER BACK TO THIS URL
|
||||
});
|
||||
|
||||
</script>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Telegram passport test</h1>
|
||||
|
||||
<div id="telegram_passport_auth"></div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,99 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
#
|
||||
# Simple Bot to print/download all incoming passport data
|
||||
# This program is dedicated to the public domain under the CC0 license.
|
||||
"""
|
||||
See https://telegram.org/blog/passport for info about what telegram passport is.
|
||||
|
||||
See https://git.io/fAvYd for how to use Telegram Passport properly with python-telegram-bot.
|
||||
|
||||
"""
|
||||
import logging
|
||||
|
||||
from telegram.ext import Updater, MessageHandler, Filters
|
||||
|
||||
# Enable logging
|
||||
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
|
||||
level=logging.DEBUG)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def msg(bot, update):
|
||||
# If we received any passport data
|
||||
passport_data = update.message.passport_data
|
||||
if passport_data:
|
||||
# If our payload doesn't match what we think, this Update did not originate from us
|
||||
# Ideally you would randomize the payload on the server
|
||||
if passport_data.decrypted_credentials.payload != 'thisisatest':
|
||||
return
|
||||
|
||||
# Print the decrypted credential data
|
||||
# For all elements
|
||||
# Print their decrypted data
|
||||
# Files will be downloaded to current directory
|
||||
for data in passport_data.decrypted_data: # This is where the data gets decrypted
|
||||
if data.type == 'phone_number':
|
||||
print('Phone: ', data.phone_number)
|
||||
elif data.type == 'email':
|
||||
print('Email: ', data.email)
|
||||
if data.type in ('personal_details', 'passport', 'driver_license', 'identity_card',
|
||||
'identity_passport', 'address'):
|
||||
print(data.type, data.data)
|
||||
if data.type in ('utility_bill', 'bank_statement', 'rental_agreement',
|
||||
'passport_registration', 'temporary_registration'):
|
||||
print(data.type, len(data.files), 'files')
|
||||
for file in data.files:
|
||||
actual_file = file.get_file()
|
||||
print(actual_file)
|
||||
actual_file.download()
|
||||
if data.type in ('passport', 'driver_license', 'identity_card',
|
||||
'internal_passport'):
|
||||
if data.front_side:
|
||||
file = data.front_side.get_file()
|
||||
print(data.type, file)
|
||||
file.download()
|
||||
if data.type in ('driver_license' and 'identity_card'):
|
||||
if data.reverse_side:
|
||||
file = data.reverse_side.get_file()
|
||||
print(data.type, file)
|
||||
file.download()
|
||||
if data.type in ('passport', 'driver_license', 'identity_card',
|
||||
'internal_passport'):
|
||||
if data.selfie:
|
||||
file = data.selfie.get_file()
|
||||
print(data.type, file)
|
||||
file.download()
|
||||
|
||||
|
||||
def error(bot, update, error):
|
||||
"""Log Errors caused by Updates."""
|
||||
logger.warning('Update "%s" caused error "%s"', update, error)
|
||||
|
||||
|
||||
def main():
|
||||
"""Start the bot."""
|
||||
# Create the Updater and pass it your token and private key
|
||||
updater = Updater("TOKEN", private_key=open('private.key', 'rb').read())
|
||||
|
||||
# Get the dispatcher to register handlers
|
||||
dp = updater.dispatcher
|
||||
|
||||
# On messages that include passport data call msg
|
||||
dp.add_handler(MessageHandler(Filters.passport_data, msg))
|
||||
|
||||
# log all errors
|
||||
dp.add_error_handler(error)
|
||||
|
||||
# Start the Bot
|
||||
updater.start_polling()
|
||||
|
||||
# Run the bot until you press 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()
|
||||
+10
-6
@@ -1,8 +1,10 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
#
|
||||
# Basic example for a bot that can receive payment from user.
|
||||
# This program is dedicated to the public domain under the CC0 license.
|
||||
"""Basic example for a bot that can receive payment from user.
|
||||
|
||||
This program is dedicated to the public domain under the CC0 license.
|
||||
"""
|
||||
|
||||
from telegram import (LabeledPrice, ShippingOption)
|
||||
from telegram.ext import (Updater, CommandHandler, MessageHandler,
|
||||
@@ -10,13 +12,15 @@ from telegram.ext import (Updater, CommandHandler, MessageHandler,
|
||||
import logging
|
||||
|
||||
# Enable logging
|
||||
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
|
||||
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
|
||||
level=logging.INFO)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def error(bot, update, error):
|
||||
logger.warn('Update "%s" caused error "%s"' % (update, error))
|
||||
"""Log Errors caused by Updates."""
|
||||
logger.warning('Update "%s" caused error "%s"', update, error)
|
||||
|
||||
|
||||
def start_callback(bot, update):
|
||||
@@ -31,7 +35,7 @@ def start_with_shipping_callback(bot, update):
|
||||
description = "Payment Example using python-telegram-bot"
|
||||
# select a payload just for you to recognize its the donation from your bot
|
||||
payload = "Custom-Payload"
|
||||
# get your provider_token at @botfather, see https://core.telegram.org/bots/payments#getting-a-token
|
||||
# In order to get a provider_token see https://core.telegram.org/bots/payments#getting-a-token
|
||||
provider_token = "PROVIDER_TOKEN"
|
||||
start_parameter = "test-payment"
|
||||
currency = "USD"
|
||||
@@ -55,7 +59,7 @@ def start_without_shipping_callback(bot, update):
|
||||
description = "Payment Example using python-telegram-bot"
|
||||
# select a payload just for you to recognize its the donation from your bot
|
||||
payload = "Custom-Payload"
|
||||
# get your provider_token at @botfather, see https://core.telegram.org/bots/payments#getting-a-token
|
||||
# In order to get a provider_token see https://core.telegram.org/bots/payments#getting-a-token
|
||||
provider_token = "PROVIDER_TOKEN"
|
||||
start_parameter = "test-payment"
|
||||
currency = "USD"
|
||||
|
||||
+14
-11
@@ -1,9 +1,11 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
#
|
||||
# Simple Bot to send timed Telegram messages
|
||||
|
||||
|
||||
"""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.
|
||||
|
||||
@@ -17,7 +19,7 @@ Press Ctrl-C on the command line or send a signal to the process to stop the
|
||||
bot.
|
||||
"""
|
||||
|
||||
from telegram.ext import Updater, CommandHandler, Job
|
||||
from telegram.ext import Updater, CommandHandler
|
||||
import logging
|
||||
|
||||
# Enable logging
|
||||
@@ -34,12 +36,12 @@ def start(bot, update):
|
||||
|
||||
|
||||
def alarm(bot, job):
|
||||
"""Function to send the alarm message"""
|
||||
"""Send the alarm message."""
|
||||
bot.send_message(job.context, text='Beep!')
|
||||
|
||||
|
||||
def set(bot, update, args, job_queue, chat_data):
|
||||
"""Adds a job to the queue"""
|
||||
def set_timer(bot, update, args, job_queue, chat_data):
|
||||
"""Add a job to the queue."""
|
||||
chat_id = update.message.chat_id
|
||||
try:
|
||||
# args[0] should contain the time for the timer in seconds
|
||||
@@ -59,8 +61,7 @@ def set(bot, update, args, job_queue, chat_data):
|
||||
|
||||
|
||||
def unset(bot, update, chat_data):
|
||||
"""Removes the job if the user changed their mind"""
|
||||
|
||||
"""Remove the job if the user changed their mind."""
|
||||
if 'job' not in chat_data:
|
||||
update.message.reply_text('You have no active timer')
|
||||
return
|
||||
@@ -73,10 +74,12 @@ def unset(bot, update, chat_data):
|
||||
|
||||
|
||||
def error(bot, update, error):
|
||||
logger.warning('Update "%s" caused error "%s"' % (update, error))
|
||||
"""Log Errors caused by Updates."""
|
||||
logger.warning('Update "%s" caused error "%s"', update, error)
|
||||
|
||||
|
||||
def main():
|
||||
"""Run bot."""
|
||||
updater = Updater("TOKEN")
|
||||
|
||||
# Get the dispatcher to register handlers
|
||||
@@ -85,7 +88,7 @@ def main():
|
||||
# on different commands - answer in Telegram
|
||||
dp.add_handler(CommandHandler("start", start))
|
||||
dp.add_handler(CommandHandler("help", start))
|
||||
dp.add_handler(CommandHandler("set", set,
|
||||
dp.add_handler(CommandHandler("set", set_timer,
|
||||
pass_args=True,
|
||||
pass_job_queue=True,
|
||||
pass_chat_data=True))
|
||||
|
||||
@@ -7,3 +7,4 @@ pre-commit
|
||||
beautifulsoup4
|
||||
pytest
|
||||
pytest-timeout
|
||||
wheel
|
||||
|
||||
@@ -1,2 +1,3 @@
|
||||
future>=0.16.0
|
||||
certifi
|
||||
cryptography
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
[wheel]
|
||||
universal = 1
|
||||
|
||||
[metadata]
|
||||
license_file = LICENSE.dual
|
||||
|
||||
[build_sphinx]
|
||||
source-dir = docs/source
|
||||
build-dir = docs/build
|
||||
|
||||
@@ -53,7 +53,6 @@ with codecs.open('README.rst', 'r', 'utf-8') as fd:
|
||||
'Programming Language :: Python :: 2',
|
||||
'Programming Language :: Python :: 2.7',
|
||||
'Programming Language :: Python :: 3',
|
||||
'Programming Language :: Python :: 3.3',
|
||||
'Programming Language :: Python :: 3.4',
|
||||
'Programming Language :: Python :: 3.5',
|
||||
'Programming Language :: Python :: 3.6'
|
||||
|
||||
+31
-4
@@ -1,7 +1,7 @@
|
||||
#!/usr/bin/env python
|
||||
#
|
||||
# A library that provides a Python interface to the Telegram Bot API
|
||||
# Copyright (C) 2015-2017
|
||||
# Copyright (C) 2015-2018
|
||||
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
@@ -27,6 +27,7 @@ from .files.photosize import PhotoSize
|
||||
from .files.audio import Audio
|
||||
from .files.voice import Voice
|
||||
from .files.document import Document
|
||||
from .files.animation import Animation
|
||||
from .files.sticker import Sticker, StickerSet, MaskPosition
|
||||
from .files.video import Video
|
||||
from .files.contact import Contact
|
||||
@@ -45,13 +46,17 @@ from .files.inputfile import InputFile
|
||||
from .files.file import File
|
||||
from .parsemode import ParseMode
|
||||
from .messageentity import MessageEntity
|
||||
from .games.animation import Animation
|
||||
from .games.game import Game
|
||||
from .games.callbackgame import CallbackGame
|
||||
from .payment.shippingaddress import ShippingAddress
|
||||
from .payment.orderinfo import OrderInfo
|
||||
from .payment.successfulpayment import SuccessfulPayment
|
||||
from .payment.invoice import Invoice
|
||||
from .passport.credentials import EncryptedCredentials
|
||||
from .passport.passportfile import PassportFile
|
||||
from .passport.data import IdDocumentData, PersonalDetails, ResidentialAddress
|
||||
from .passport.encryptedpassportelement import EncryptedPassportElement
|
||||
from .passport.passportdata import PassportData
|
||||
from .message import Message
|
||||
from .callbackquery import CallbackQuery
|
||||
from .choseninlineresult import ChosenInlineResult
|
||||
@@ -91,11 +96,25 @@ from .payment.shippingquery import ShippingQuery
|
||||
from .webhookinfo import WebhookInfo
|
||||
from .games.gamehighscore import GameHighScore
|
||||
from .update import Update
|
||||
from .files.inputmedia import (InputMedia, InputMediaVideo, InputMediaPhoto, InputMediaAnimation,
|
||||
InputMediaAudio, InputMediaDocument)
|
||||
from .bot import Bot
|
||||
from .constants import (MAX_MESSAGE_LENGTH, MAX_CAPTION_LENGTH, SUPPORTED_WEBHOOK_PORTS,
|
||||
MAX_FILESIZE_DOWNLOAD, MAX_FILESIZE_UPLOAD,
|
||||
MAX_MESSAGES_PER_SECOND_PER_CHAT, MAX_MESSAGES_PER_SECOND,
|
||||
MAX_MESSAGES_PER_MINUTE_PER_GROUP)
|
||||
from .passport.passportelementerrors import (PassportElementError,
|
||||
PassportElementErrorDataField,
|
||||
PassportElementErrorFile,
|
||||
PassportElementErrorFiles,
|
||||
PassportElementErrorFrontSide,
|
||||
PassportElementErrorReverseSide,
|
||||
PassportElementErrorSelfie)
|
||||
from .passport.credentials import (Credentials,
|
||||
DataCredentials,
|
||||
SecureData,
|
||||
FileCredentials,
|
||||
TelegramDecryptionError)
|
||||
from .version import __version__ # flake8: noqa
|
||||
|
||||
__author__ = 'devs@python-telegram-bot.org'
|
||||
@@ -113,7 +132,8 @@ __all__ = [
|
||||
'InlineQueryResultPhoto', 'InlineQueryResultVenue', 'InlineQueryResultVideo',
|
||||
'InlineQueryResultVoice', 'InlineQueryResultGame', 'InputContactMessageContent', 'InputFile',
|
||||
'InputLocationMessageContent', 'InputMessageContent', 'InputTextMessageContent',
|
||||
'InputVenueMessageContent', 'KeyboardButton', 'Location', 'Message', 'MessageEntity',
|
||||
'InputVenueMessageContent', 'KeyboardButton', 'Location', 'EncryptedCredentials',
|
||||
'PassportFile', 'EncryptedPassportElement', 'PassportData', 'Message', 'MessageEntity',
|
||||
'ParseMode', 'PhotoSize', 'ReplyKeyboardRemove', 'ReplyKeyboardMarkup', 'ReplyMarkup',
|
||||
'Sticker', 'TelegramError', 'TelegramObject', 'Update', 'User', 'UserProfilePhotos', 'Venue',
|
||||
'Video', 'Voice', 'MAX_MESSAGE_LENGTH', 'MAX_CAPTION_LENGTH', 'SUPPORTED_WEBHOOK_PORTS',
|
||||
@@ -121,5 +141,12 @@ __all__ = [
|
||||
'MAX_MESSAGES_PER_SECOND', 'MAX_MESSAGES_PER_MINUTE_PER_GROUP', 'WebhookInfo', 'Animation',
|
||||
'Game', 'GameHighScore', 'VideoNote', 'LabeledPrice', 'SuccessfulPayment', 'ShippingOption',
|
||||
'ShippingAddress', 'PreCheckoutQuery', 'OrderInfo', 'Invoice', 'ShippingQuery', 'ChatPhoto',
|
||||
'StickerSet', 'MaskPosition', 'CallbackGame'
|
||||
'StickerSet', 'MaskPosition', 'CallbackGame', 'InputMedia', 'InputMediaPhoto',
|
||||
'InputMediaVideo', 'PassportElementError', 'PassportElementErrorFile',
|
||||
'PassportElementErrorReverseSide', 'PassportElementErrorFrontSide',
|
||||
'PassportElementErrorFiles', 'PassportElementErrorDataField', 'PassportElementErrorFile',
|
||||
'Credentials', 'DataCredentials', 'SecureData', 'FileCredentials', 'IdDocumentData',
|
||||
'PersonalDetails', 'ResidentialAddress', 'InputMediaVideo', 'InputMediaAnimation',
|
||||
'InputMediaAudio', 'InputMediaDocument', 'TelegramDecryptionError',
|
||||
'PassportElementErrorSelfie'
|
||||
]
|
||||
|
||||
@@ -1,3 +1,21 @@
|
||||
# !/usr/bin/env python
|
||||
#
|
||||
# A library that provides a Python interface to the Telegram Bot API
|
||||
# Copyright (C) 2015-2018
|
||||
# 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/].
|
||||
import sys
|
||||
|
||||
import certifi
|
||||
|
||||
+9
-2
@@ -1,7 +1,7 @@
|
||||
#!/usr/bin/env python
|
||||
#
|
||||
# A library that provides a Python interface to the Telegram Bot API
|
||||
# Copyright (C) 2015-2017
|
||||
# Copyright (C) 2015-2018
|
||||
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
@@ -60,7 +60,12 @@ class TelegramObject(object):
|
||||
data = dict()
|
||||
|
||||
for key in iter(self.__dict__):
|
||||
if key in ('bot', '_id_attrs'):
|
||||
if key in ('bot',
|
||||
'_id_attrs',
|
||||
'_credentials',
|
||||
'_decrypted_credentials',
|
||||
'_decrypted_data',
|
||||
'_decrypted_secret'):
|
||||
continue
|
||||
|
||||
value = self.__dict__[key]
|
||||
@@ -70,6 +75,8 @@ class TelegramObject(object):
|
||||
else:
|
||||
data[key] = value
|
||||
|
||||
if data.get('from_user'):
|
||||
data['from'] = data.pop('from_user', None)
|
||||
return data
|
||||
|
||||
def __eq__(self, other):
|
||||
|
||||
+724
-111
File diff suppressed because it is too large
Load Diff
@@ -1,7 +1,7 @@
|
||||
#!/usr/bin/env python
|
||||
#
|
||||
# A library that provides a Python interface to the Telegram Bot API
|
||||
# Copyright (C) 2015-2017
|
||||
# Copyright (C) 2015-2018
|
||||
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
@@ -105,13 +105,6 @@ class CallbackQuery(TelegramObject):
|
||||
|
||||
return cls(bot=bot, **data)
|
||||
|
||||
def to_dict(self):
|
||||
data = super(CallbackQuery, self).to_dict()
|
||||
|
||||
# Required
|
||||
data['from'] = data.pop('from_user', None)
|
||||
return data
|
||||
|
||||
def answer(self, *args, **kwargs):
|
||||
"""Shortcut for::
|
||||
|
||||
|
||||
+137
-1
@@ -2,7 +2,7 @@
|
||||
# pylint: disable=C0103,W0622
|
||||
#
|
||||
# A library that provides a Python interface to the Telegram Bot API
|
||||
# Copyright (C) 2015-2017
|
||||
# Copyright (C) 2015-2018
|
||||
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
@@ -38,6 +38,9 @@ class Chat(TelegramObject):
|
||||
invite_link (:obj:`str`): Optional. Chat invite link, for supergroups and channel chats.
|
||||
pinned_message (:class:`telegram.Message`): Optional. Pinned message, for supergroups.
|
||||
Returned only in get_chat.
|
||||
sticker_set_name (:obj:`str`): Optional. For supergroups, name of Group sticker set.
|
||||
can_set_sticker_set (:obj:`bool`): Optional. ``True``, if the bot can change group the
|
||||
sticker set.
|
||||
|
||||
Args:
|
||||
id (:obj:`int`): Unique identifier for this chat. This number may be greater than 32 bits
|
||||
@@ -61,6 +64,10 @@ class Chat(TelegramObject):
|
||||
pinned_message (:class:`telegram.Message`, optional): Pinned message, for supergroups.
|
||||
Returned only in get_chat.
|
||||
bot (:class:`telegram.Bot`, optional): The Bot to use for instance methods.
|
||||
sticker_set_name (:obj:`str`, optional): For supergroups, name of Group sticker set.
|
||||
Returned only in get_chat.
|
||||
can_set_sticker_set (:obj:`bool`, optional): ``True``, if the bot can change group the
|
||||
sticker set. Returned only in get_chat.
|
||||
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
|
||||
|
||||
"""
|
||||
@@ -87,6 +94,8 @@ class Chat(TelegramObject):
|
||||
description=None,
|
||||
invite_link=None,
|
||||
pinned_message=None,
|
||||
sticker_set_name=None,
|
||||
can_set_sticker_set=None,
|
||||
**kwargs):
|
||||
# Required
|
||||
self.id = int(id)
|
||||
@@ -101,10 +110,20 @@ class Chat(TelegramObject):
|
||||
self.description = description
|
||||
self.invite_link = invite_link
|
||||
self.pinned_message = pinned_message
|
||||
self.sticker_set_name = sticker_set_name
|
||||
self.can_set_sticker_set = can_set_sticker_set
|
||||
|
||||
self.bot = bot
|
||||
self._id_attrs = (self.id,)
|
||||
|
||||
@property
|
||||
def link(self):
|
||||
""":obj:`str`: Convenience property. If the chat has a :attr:`username`, returns a t.me
|
||||
link of the chat."""
|
||||
if self.username:
|
||||
return "https://t.me/{}".format(self.username)
|
||||
return None
|
||||
|
||||
@classmethod
|
||||
def de_json(cls, data, bot):
|
||||
if not data:
|
||||
@@ -201,3 +220,120 @@ class Chat(TelegramObject):
|
||||
|
||||
"""
|
||||
return self.bot.unban_chat_member(self.id, *args, **kwargs)
|
||||
|
||||
def send_message(self, *args, **kwargs):
|
||||
"""Shortcut for::
|
||||
|
||||
bot.send_message(Chat.id, *args, **kwargs)
|
||||
|
||||
Where Chat is the current instance.
|
||||
|
||||
Returns:
|
||||
:class:`telegram.Message`: On success, instance representing the message posted.
|
||||
|
||||
"""
|
||||
return self.bot.send_message(self.id, *args, **kwargs)
|
||||
|
||||
def send_photo(self, *args, **kwargs):
|
||||
"""Shortcut for::
|
||||
|
||||
bot.send_photo(Chat.id, *args, **kwargs)
|
||||
|
||||
Where Chat is the current instance.
|
||||
|
||||
Returns:
|
||||
:class:`telegram.Message`: On success, instance representing the message posted.
|
||||
|
||||
"""
|
||||
return self.bot.send_photo(self.id, *args, **kwargs)
|
||||
|
||||
def send_audio(self, *args, **kwargs):
|
||||
"""Shortcut for::
|
||||
|
||||
bot.send_audio(Chat.id, *args, **kwargs)
|
||||
|
||||
Where Chat is the current instance.
|
||||
|
||||
Returns:
|
||||
:class:`telegram.Message`: On success, instance representing the message posted.
|
||||
|
||||
"""
|
||||
return self.bot.send_audio(self.id, *args, **kwargs)
|
||||
|
||||
def send_document(self, *args, **kwargs):
|
||||
"""Shortcut for::
|
||||
|
||||
bot.send_document(Chat.id, *args, **kwargs)
|
||||
|
||||
Where Chat is the current instance.
|
||||
|
||||
Returns:
|
||||
:class:`telegram.Message`: On success, instance representing the message posted.
|
||||
|
||||
"""
|
||||
return self.bot.send_document(self.id, *args, **kwargs)
|
||||
|
||||
def send_animation(self, *args, **kwargs):
|
||||
"""Shortcut for::
|
||||
|
||||
bot.send_animation(Chat.id, *args, **kwargs)
|
||||
|
||||
Where Chat is the current instance.
|
||||
|
||||
Returns:
|
||||
:class:`telegram.Message`: On success, instance representing the message posted.
|
||||
|
||||
"""
|
||||
return self.bot.send_animation(self.id, *args, **kwargs)
|
||||
|
||||
def send_sticker(self, *args, **kwargs):
|
||||
"""Shortcut for::
|
||||
|
||||
bot.send_sticker(Chat.id, *args, **kwargs)
|
||||
|
||||
Where Chat is the current instance.
|
||||
|
||||
Returns:
|
||||
:class:`telegram.Message`: On success, instance representing the message posted.
|
||||
|
||||
"""
|
||||
return self.bot.send_sticker(self.id, *args, **kwargs)
|
||||
|
||||
def send_video(self, *args, **kwargs):
|
||||
"""Shortcut for::
|
||||
|
||||
bot.send_video(Chat.id, *args, **kwargs)
|
||||
|
||||
Where Chat is the current instance.
|
||||
|
||||
Returns:
|
||||
:class:`telegram.Message`: On success, instance representing the message posted.
|
||||
|
||||
"""
|
||||
return self.bot.send_video(self.id, *args, **kwargs)
|
||||
|
||||
def send_video_note(self, *args, **kwargs):
|
||||
"""Shortcut for::
|
||||
|
||||
bot.send_video_note(Chat.id, *args, **kwargs)
|
||||
|
||||
Where Chat is the current instance.
|
||||
|
||||
Returns:
|
||||
:class:`telegram.Message`: On success, instance representing the message posted.
|
||||
|
||||
"""
|
||||
return self.bot.send_video_note(self.id, *args, **kwargs)
|
||||
|
||||
def send_voice(self, *args, **kwargs):
|
||||
"""Shortcut for::
|
||||
|
||||
bot.send_voice(Chat.id, *args, **kwargs)
|
||||
|
||||
Where Chat is the current instance.
|
||||
|
||||
Returns:
|
||||
:class:`telegram.Message`: On success, instance representing the message posted.
|
||||
|
||||
"""
|
||||
return self.bot.send_voice(self.id, *args, **kwargs)
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
# pylint: disable=R0903
|
||||
#
|
||||
# A library that provides a Python interface to the Telegram Bot API
|
||||
# Copyright (C) 2015-2017
|
||||
# Copyright (C) 2015-2018
|
||||
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#!/usr/bin/env python
|
||||
#
|
||||
# A library that provides a Python interface to the Telegram Bot API
|
||||
# Copyright (C) 2015-2017
|
||||
# Copyright (C) 2015-2018
|
||||
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
# pylint: disable=R0902,R0912,R0913
|
||||
#
|
||||
# A library that provides a Python interface to the Telegram Bot API
|
||||
# Copyright (C) 2015-2017
|
||||
# Copyright (C) 2015-2018
|
||||
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
@@ -79,11 +79,3 @@ class ChosenInlineResult(TelegramObject):
|
||||
data['location'] = Location.de_json(data.get('location'), bot)
|
||||
|
||||
return cls(**data)
|
||||
|
||||
def to_dict(self):
|
||||
data = super(ChosenInlineResult, self).to_dict()
|
||||
|
||||
# Required
|
||||
data['from'] = data.pop('from_user', None)
|
||||
|
||||
return data
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
# python-telegram-bot - a Python interface to the Telegram Bot API
|
||||
# Copyright (C) 2015-2017
|
||||
# Copyright (C) 2015-2018
|
||||
# by the python-telegram-bot contributors <devs@python-telegram-bot.org>
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
#!/usr/bin/env python
|
||||
#
|
||||
# A library that provides a Python interface to the Telegram Bot API
|
||||
# Copyright (C) 2015-2017
|
||||
# Copyright (C) 2015-2018
|
||||
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#!/usr/bin/env python
|
||||
#
|
||||
# A library that provides a Python interface to the Telegram Bot API
|
||||
# Copyright (C) 2015-2017
|
||||
# Copyright (C) 2015-2018
|
||||
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#!/usr/bin/env python
|
||||
#
|
||||
# A library that provides a Python interface to the Telegram Bot API
|
||||
# Copyright (C) 2015-2017
|
||||
# Copyright (C) 2015-2018
|
||||
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
@@ -50,7 +50,7 @@ class CallbackQueryHandler(Handler):
|
||||
|
||||
Note:
|
||||
:attr:`pass_user_data` and :attr:`pass_chat_data` determine whether a ``dict`` you
|
||||
can use to keep any data in will be sent to the :attr:`callback` function.. Related to
|
||||
can use to keep any data in will be sent to the :attr:`callback` function. Related to
|
||||
either the user or the chat that the update was sent in. For each update from the same user
|
||||
or in the same chat, it will be the same ``dict``.
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#!/usr/bin/env python
|
||||
#
|
||||
# A library that provides a Python interface to the Telegram Bot API
|
||||
# Copyright (C) 2015-2017
|
||||
# Copyright (C) 2015-2018
|
||||
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
@@ -39,7 +39,7 @@ class ChosenInlineResultHandler(Handler):
|
||||
|
||||
Note:
|
||||
:attr:`pass_user_data` and :attr:`pass_chat_data` determine whether a ``dict`` you
|
||||
can use to keep any data in will be sent to the :attr:`callback` function.. Related to
|
||||
can use to keep any data in will be sent to the :attr:`callback` function. Related to
|
||||
either the user or the chat that the update was sent in. For each update from the same user
|
||||
or in the same chat, it will be the same ``dict``.
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#!/usr/bin/env python
|
||||
#
|
||||
# A library that provides a Python interface to the Telegram Bot API
|
||||
# Copyright (C) 2015-2017
|
||||
# Copyright (C) 2015-2018
|
||||
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
@@ -52,7 +52,7 @@ class CommandHandler(Handler):
|
||||
|
||||
Note:
|
||||
:attr:`pass_user_data` and :attr:`pass_chat_data` determine whether a ``dict`` you
|
||||
can use to keep any data in will be sent to the :attr:`callback` function.. Related to
|
||||
can use to keep any data in will be sent to the :attr:`callback` function. Related to
|
||||
either the user or the chat that the update was sent in. For each update from the same user
|
||||
or in the same chat, it will be the same ``dict``.
|
||||
|
||||
@@ -133,25 +133,27 @@ class CommandHandler(Handler):
|
||||
and (update.message or update.edited_message and self.allow_edited)):
|
||||
message = update.message or update.edited_message
|
||||
|
||||
if message.text:
|
||||
command = message.text[1:].split(' ')[0].split('@')
|
||||
command.append(
|
||||
message.bot.username) # in case the command was send without a username
|
||||
if message.text and message.text.startswith('/') and len(message.text) > 1:
|
||||
first_word = message.text_html.split(None, 1)[0]
|
||||
if len(first_word) > 1 and first_word.startswith('/'):
|
||||
command = first_word[1:].split('@')
|
||||
command.append(
|
||||
message.bot.username) # in case the command was sent without a username
|
||||
|
||||
if self.filters is None:
|
||||
res = True
|
||||
elif isinstance(self.filters, list):
|
||||
res = any(func(message) for func in self.filters)
|
||||
else:
|
||||
res = self.filters(message)
|
||||
if not (command[0].lower() in self.command
|
||||
and command[1].lower() == message.bot.username.lower()):
|
||||
return False
|
||||
|
||||
return res and (message.text.startswith('/') and command[0].lower() in self.command
|
||||
and command[1].lower() == message.bot.username.lower())
|
||||
else:
|
||||
return False
|
||||
if self.filters is None:
|
||||
res = True
|
||||
elif isinstance(self.filters, list):
|
||||
res = any(func(message) for func in self.filters)
|
||||
else:
|
||||
res = self.filters(message)
|
||||
|
||||
else:
|
||||
return False
|
||||
return res
|
||||
|
||||
return False
|
||||
|
||||
def handle_update(self, update, dispatcher):
|
||||
"""Send the update to the :attr:`callback`.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#!/usr/bin/env python
|
||||
#
|
||||
# A library that provides a Python interface to the Telegram Bot API
|
||||
# Copyright (C) 2015-2017
|
||||
# Copyright (C) 2015-2018
|
||||
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
@@ -55,7 +55,7 @@ class ConversationHandler(Handler):
|
||||
To change the state of conversation, the callback function of a handler must return the new
|
||||
state after responding to the user. If it does not return anything (returning ``None`` by
|
||||
default), the state will not change. To end the conversation, the callback function must
|
||||
return :attr`END` or ``-1``.
|
||||
return :attr:`END` or ``-1``.
|
||||
|
||||
Attributes:
|
||||
entry_points (List[:class:`telegram.ext.Handler`]): A list of ``Handler`` objects that can
|
||||
@@ -76,6 +76,9 @@ class ConversationHandler(Handler):
|
||||
per_user (:obj:`bool`): Optional. If the conversationkey should contain the User's ID.
|
||||
per_message (:obj:`bool`): Optional. If the conversationkey should contain the Message's
|
||||
ID.
|
||||
conversation_timeout (:obj:`float`|:obj:`datetime.timedelta`): Optional. When this handler
|
||||
is inactive more than this timeout (in seconds), it will be automatically ended. If
|
||||
this value is 0 (default), there will be no timeout.
|
||||
|
||||
Args:
|
||||
entry_points (List[:class:`telegram.ext.Handler`]): A list of ``Handler`` objects that can
|
||||
@@ -107,6 +110,9 @@ class ConversationHandler(Handler):
|
||||
Default is ``True``.
|
||||
per_message (:obj:`bool`, optional): If the conversationkey should contain the Message's
|
||||
ID. Default is ``False``.
|
||||
conversation_timeout (:obj:`float`|:obj:`datetime.timedelta`, optional): When this handler
|
||||
is inactive more than this timeout (in seconds), it will be automatically ended. If
|
||||
this value is 0 or None (default), there will be no timeout.
|
||||
|
||||
Raises:
|
||||
ValueError
|
||||
@@ -124,7 +130,8 @@ class ConversationHandler(Handler):
|
||||
timed_out_behavior=None,
|
||||
per_chat=True,
|
||||
per_user=True,
|
||||
per_message=False):
|
||||
per_message=False,
|
||||
conversation_timeout=None):
|
||||
|
||||
self.entry_points = entry_points
|
||||
self.states = states
|
||||
@@ -136,7 +143,9 @@ class ConversationHandler(Handler):
|
||||
self.per_user = per_user
|
||||
self.per_chat = per_chat
|
||||
self.per_message = per_message
|
||||
self.conversation_timeout = conversation_timeout
|
||||
|
||||
self.timeout_jobs = dict()
|
||||
self.conversations = dict()
|
||||
self.current_conversation = None
|
||||
self.current_handler = None
|
||||
@@ -206,10 +215,11 @@ class ConversationHandler(Handler):
|
||||
|
||||
"""
|
||||
# Ignore messages in channels
|
||||
if (not isinstance(update, Update) or update.channel_post or self.per_chat
|
||||
and (update.inline_query or update.chosen_inline_result) or self.per_message
|
||||
and not update.callback_query or update.callback_query and self.per_chat
|
||||
and not update.callback_query.message):
|
||||
if (not isinstance(update, Update) or
|
||||
update.channel_post or
|
||||
self.per_chat and not update.effective_chat or
|
||||
self.per_message and not update.callback_query or
|
||||
update.callback_query and self.per_chat and not update.callback_query.message):
|
||||
return False
|
||||
|
||||
key = self._get_key(update)
|
||||
@@ -293,6 +303,15 @@ class ConversationHandler(Handler):
|
||||
|
||||
"""
|
||||
new_state = self.current_handler.handle_update(update, dispatcher)
|
||||
timeout_job = self.timeout_jobs.pop(self.current_conversation, None)
|
||||
|
||||
if timeout_job is not None:
|
||||
timeout_job.schedule_removal()
|
||||
if self.conversation_timeout and new_state != self.END:
|
||||
self.timeout_jobs[self.current_conversation] = dispatcher.job_queue.run_once(
|
||||
self._trigger_timeout, self.conversation_timeout,
|
||||
context=self.current_conversation
|
||||
)
|
||||
|
||||
self.update_state(new_state, self.current_conversation)
|
||||
|
||||
@@ -308,3 +327,7 @@ class ConversationHandler(Handler):
|
||||
|
||||
elif new_state is not None:
|
||||
self.conversations[key] = new_state
|
||||
|
||||
def _trigger_timeout(self, bot, job):
|
||||
del self.timeout_jobs[job.context]
|
||||
self.update_state(self.END, job.context)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#!/usr/bin/env python
|
||||
#
|
||||
# A library that provides a Python interface to the Telegram Bot API
|
||||
# Copyright (C) 2015-2017
|
||||
# Copyright (C) 2015-2018
|
||||
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
@@ -143,7 +143,7 @@ class Dispatcher(object):
|
||||
|
||||
"""
|
||||
if cls.__singleton is not None:
|
||||
return cls.__singleton()
|
||||
return cls.__singleton() # pylint: disable=not-callable
|
||||
else:
|
||||
raise RuntimeError('{} not initialized or multiple instances exist'.format(
|
||||
cls.__name__))
|
||||
@@ -183,14 +183,20 @@ class Dispatcher(object):
|
||||
self.__async_queue.put(promise)
|
||||
return promise
|
||||
|
||||
def start(self):
|
||||
def start(self, ready=None):
|
||||
"""Thread target of thread 'dispatcher'.
|
||||
|
||||
Runs in background and processes the update queue.
|
||||
|
||||
Args:
|
||||
ready (:obj:`threading.Event`, optional): If specified, the event will be set once the
|
||||
dispatcher is ready.
|
||||
|
||||
"""
|
||||
if self.running:
|
||||
self.logger.warning('already running')
|
||||
if ready is not None:
|
||||
ready.set()
|
||||
return
|
||||
|
||||
if self.__exception_event.is_set():
|
||||
@@ -202,6 +208,9 @@ class Dispatcher(object):
|
||||
self.running = True
|
||||
self.logger.debug('Dispatcher started')
|
||||
|
||||
if ready is not None:
|
||||
ready.set()
|
||||
|
||||
while 1:
|
||||
try:
|
||||
# Pop update from update queue.
|
||||
@@ -299,7 +308,7 @@ class Dispatcher(object):
|
||||
A handler must be an instance of a subclass of :class:`telegram.ext.Handler`. All handlers
|
||||
are organized in groups with a numeric value. The default group is 0. All groups will be
|
||||
evaluated for handling an update, but only 0 or 1 handler per group will be used. If
|
||||
:class:`telegram.DispatcherHandlerStop` is raised from one of the handlers, no further
|
||||
:class:`telegram.ext.DispatcherHandlerStop` is raised from one of the handlers, no further
|
||||
handlers (regardless of the group) will be called.
|
||||
|
||||
The priority/order of handlers is determined as follows:
|
||||
@@ -370,5 +379,10 @@ class Dispatcher(object):
|
||||
error (:class:`telegram.TelegramError`): The Telegram error that was raised.
|
||||
|
||||
"""
|
||||
for callback in self.error_handlers:
|
||||
callback(self.bot, update, error)
|
||||
if self.error_handlers:
|
||||
for callback in self.error_handlers:
|
||||
callback(self.bot, update, error)
|
||||
|
||||
else:
|
||||
self.logger.exception(
|
||||
'No error handlers are registered, logging exception.', exc_info=error)
|
||||
|
||||
+170
-8
@@ -1,7 +1,7 @@
|
||||
#!/usr/bin/env python
|
||||
#
|
||||
# A library that provides a Python interface to the Telegram Bot API
|
||||
# Copyright (C) 2015-2017
|
||||
# Copyright (C) 2015-2018
|
||||
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
@@ -17,6 +17,8 @@
|
||||
# You should have received a copy of the GNU Lesser Public License
|
||||
# along with this program. If not, see [http://www.gnu.org/licenses/].
|
||||
"""This module contains the Filters for use with the MessageHandler class."""
|
||||
|
||||
import re
|
||||
from telegram import Chat
|
||||
from future.utils import string_types
|
||||
|
||||
@@ -171,6 +173,35 @@ class Filters(object):
|
||||
command = _Command()
|
||||
""":obj:`Filter`: Messages starting with ``/``."""
|
||||
|
||||
class regex(BaseFilter):
|
||||
"""
|
||||
Filters updates by searching for an occurence of ``pattern`` in the message text.
|
||||
The ``re.search`` function is used to determine whether an update should be filtered.
|
||||
Refer to the documentation of the ``re`` module for more information.
|
||||
|
||||
Note: Does not allow passing groups or a groupdict like the ``RegexHandler`` yet,
|
||||
but this will probably be implemented in a future update, gradually phasing out the
|
||||
RegexHandler (see https://github.com/python-telegram-bot/python-telegram-bot/issues/835).
|
||||
|
||||
Examples:
|
||||
Example ``CommandHandler("start", deep_linked_callback, Filters.regex('parameter'))``
|
||||
|
||||
Args:
|
||||
pattern (:obj:`str` | :obj:`Pattern`): The regex pattern.
|
||||
"""
|
||||
|
||||
def __init__(self, pattern):
|
||||
self.pattern = re.compile(pattern)
|
||||
self.name = 'Filters.regex({})'.format(self.pattern)
|
||||
|
||||
# TODO: Once the callback revamp (#1026) is done, the regex filter should be able to pass
|
||||
# the matched groups and groupdict to the context object.
|
||||
|
||||
def filter(self, message):
|
||||
if message.text:
|
||||
return bool(self.pattern.search(message.text))
|
||||
return False
|
||||
|
||||
class _Reply(BaseFilter):
|
||||
name = 'Filters.reply'
|
||||
|
||||
@@ -192,12 +223,94 @@ class Filters(object):
|
||||
class _Document(BaseFilter):
|
||||
name = 'Filters.document'
|
||||
|
||||
class category(BaseFilter):
|
||||
"""This Filter filters documents by their category in the mime-type attribute
|
||||
|
||||
Note:
|
||||
This Filter only filters by the mime_type of the document,
|
||||
it doesn't check the validity of the document.
|
||||
The user can manipulate the mime-type of a message and
|
||||
send media with wrong types that don't fit to this handler.
|
||||
|
||||
Examples:
|
||||
Filters.documents.category('audio/') returnes `True` for all types
|
||||
of audio sent as file, for example 'audio/mpeg' or 'audio/x-wav'
|
||||
"""
|
||||
|
||||
def __init__(self, category):
|
||||
"""Initialize the category you want to filter
|
||||
|
||||
Args:
|
||||
category (str, optional): category of the media you want to filter"""
|
||||
self.category = category
|
||||
self.name = "Filters.document.category('{}')".format(self.category)
|
||||
|
||||
def filter(self, message):
|
||||
if message.document:
|
||||
return message.document.mime_type.startswith(self.category)
|
||||
|
||||
application = category('application/')
|
||||
audio = category('audio/')
|
||||
image = category('image/')
|
||||
video = category('video/')
|
||||
text = category('text/')
|
||||
|
||||
class mime_type(BaseFilter):
|
||||
"""This Filter filters documents by their mime-type attribute
|
||||
|
||||
Note:
|
||||
This Filter only filters by the mime_type of the document,
|
||||
it doesn't check the validity of document.
|
||||
The user can manipulate the mime-type of a message and
|
||||
send media with wrong types that don't fit to this handler.
|
||||
|
||||
Examples:
|
||||
Filters.documents.mime_type('audio/mpeg') filters all audio in mp3 format.
|
||||
"""
|
||||
|
||||
def __init__(self, mimetype):
|
||||
"""Initialize the category you want to filter
|
||||
|
||||
Args:
|
||||
filetype (str, optional): mime_type of the media you want to filter"""
|
||||
self.mimetype = mimetype
|
||||
self.name = "Filters.document.mime_type('{}')".format(self.mimetype)
|
||||
|
||||
def filter(self, message):
|
||||
if message.document:
|
||||
return message.document.mime_type == self.mimetype
|
||||
|
||||
apk = mime_type('application/vnd.android.package-archive')
|
||||
doc = mime_type('application/msword')
|
||||
docx = mime_type('application/vnd.openxmlformats-officedocument.wordprocessingml.document')
|
||||
exe = mime_type('application/x-ms-dos-executable')
|
||||
gif = mime_type('video/mp4')
|
||||
jpg = mime_type('image/jpeg')
|
||||
mp3 = mime_type('audio/mpeg')
|
||||
pdf = mime_type('application/pdf')
|
||||
py = mime_type('text/x-python')
|
||||
svg = mime_type('image/svg+xml')
|
||||
txt = mime_type('text/plain')
|
||||
targz = mime_type('application/x-compressed-tar')
|
||||
wav = mime_type('audio/x-wav')
|
||||
xml = mime_type('application/xml')
|
||||
zip = mime_type('application/zip')
|
||||
|
||||
def filter(self, message):
|
||||
return bool(message.document)
|
||||
|
||||
document = _Document()
|
||||
""":obj:`Filter`: Messages that contain :class:`telegram.Document`."""
|
||||
|
||||
class _Animation(BaseFilter):
|
||||
name = 'Filters.animation'
|
||||
|
||||
def filter(self, message):
|
||||
return bool(message.animation)
|
||||
|
||||
animation = _Animation()
|
||||
""":obj:`Filter`: Messages that contain :class:`telegram.Animation`."""
|
||||
|
||||
class _Photo(BaseFilter):
|
||||
name = 'Filters.photo'
|
||||
|
||||
@@ -234,6 +347,15 @@ class Filters(object):
|
||||
voice = _Voice()
|
||||
""":obj:`Filter`: Messages that contain :class:`telegram.Voice`."""
|
||||
|
||||
class _VideoNote(BaseFilter):
|
||||
name = 'Filters.video_note'
|
||||
|
||||
def filter(self, message):
|
||||
return bool(message.video_note)
|
||||
|
||||
video_note = _VideoNote()
|
||||
""":obj:`Filter`: Messages that contain :class:`telegram.VideoNote`."""
|
||||
|
||||
class _Contact(BaseFilter):
|
||||
name = 'Filters.contact'
|
||||
|
||||
@@ -265,7 +387,7 @@ class Filters(object):
|
||||
"""Subset for messages containing a status update.
|
||||
|
||||
Examples:
|
||||
Use these filters like: ``Filters.status_update.new_chat_member`` etc. Or use just
|
||||
Use these filters like: ``Filters.status_update.new_chat_members`` etc. Or use just
|
||||
``Filters.status_update`` for all status update messages.
|
||||
|
||||
"""
|
||||
@@ -277,7 +399,7 @@ class Filters(object):
|
||||
return bool(message.new_chat_members)
|
||||
|
||||
new_chat_members = _NewChatMembers()
|
||||
""":obj:`Filter`: Messages that contain :attr:`telegram.Message.new_chat_member`."""
|
||||
""":obj:`Filter`: Messages that contain :attr:`telegram.Message.new_chat_members`."""
|
||||
|
||||
class _LeftChatMember(BaseFilter):
|
||||
name = 'Filters.status_update.left_chat_member'
|
||||
@@ -335,7 +457,7 @@ class Filters(object):
|
||||
|
||||
migrate = _Migrate()
|
||||
""":obj:`Filter`: Messages that contain :attr:`telegram.Message.migrate_from_chat_id` or
|
||||
:attr: `telegram.Message.migrate_from_chat_id`."""
|
||||
:attr: `telegram.Message.migrate_to_chat_id`."""
|
||||
|
||||
class _PinnedMessage(BaseFilter):
|
||||
name = 'Filters.status_update.pinned_message'
|
||||
@@ -346,19 +468,29 @@ class Filters(object):
|
||||
pinned_message = _PinnedMessage()
|
||||
""":obj:`Filter`: Messages that contain :attr:`telegram.Message.pinned_message`."""
|
||||
|
||||
class _ConnectedWebsite(BaseFilter):
|
||||
name = 'Filters.status_update.connected_website'
|
||||
|
||||
def filter(self, message):
|
||||
return bool(message.connected_website)
|
||||
|
||||
connected_website = _ConnectedWebsite()
|
||||
""":obj:`Filter`: Messages that contain :attr:`telegram.Message.connected_website`."""
|
||||
|
||||
name = 'Filters.status_update'
|
||||
|
||||
def filter(self, message):
|
||||
return bool(self.new_chat_members(message) or self.left_chat_member(message) or
|
||||
self.new_chat_title(message) or self.new_chat_photo(message) or
|
||||
self.delete_chat_photo(message) or self.chat_created(message) or
|
||||
self.migrate(message) or self.pinned_message(message))
|
||||
self.migrate(message) or self.pinned_message(message) or
|
||||
self.connected_website(message))
|
||||
|
||||
status_update = _StatusUpdate()
|
||||
"""Subset for messages containing a status update.
|
||||
|
||||
Examples:
|
||||
Use these filters like: ``Filters.status_update.new_chat_member`` etc. Or use just
|
||||
Use these filters like: ``Filters.status_update.new_chat_members`` etc. Or use just
|
||||
``Filters.status_update`` for all status update messages.
|
||||
|
||||
Attributes:
|
||||
@@ -374,7 +506,7 @@ class Filters(object):
|
||||
:attr:`telegram.Message.migrate_from_chat_id` or
|
||||
:attr: `telegram.Message.migrate_from_chat_id`.
|
||||
new_chat_members (:obj:`Filter`): Messages that contain
|
||||
:attr:`telegram.Message.new_chat_member`.
|
||||
:attr:`telegram.Message.new_chat_members`.
|
||||
new_chat_photo (:obj:`Filter`): Messages that contain
|
||||
:attr:`telegram.Message.new_chat_photo`.
|
||||
new_chat_title (:obj:`Filter`): Messages that contain
|
||||
@@ -420,7 +552,28 @@ class Filters(object):
|
||||
self.name = 'Filters.entity({})'.format(self.entity_type)
|
||||
|
||||
def filter(self, message):
|
||||
return any([entity.type == self.entity_type for entity in message.entities])
|
||||
return any(entity.type == self.entity_type for entity in message.entities)
|
||||
|
||||
class caption_entity(BaseFilter):
|
||||
"""
|
||||
Filters media messages to only allow those which have a :class:`telegram.MessageEntity`
|
||||
where their `type` matches `entity_type`.
|
||||
|
||||
Examples:
|
||||
Example ``MessageHandler(Filters.caption_entity("hashtag"), callback_method)``
|
||||
|
||||
Args:
|
||||
entity_type: Caption Entity type to check for. All types can be found as constants
|
||||
in :class:`telegram.MessageEntity`.
|
||||
|
||||
"""
|
||||
|
||||
def __init__(self, entity_type):
|
||||
self.entity_type = entity_type
|
||||
self.name = 'Filters.caption_entity({})'.format(self.entity_type)
|
||||
|
||||
def filter(self, message):
|
||||
return any(entity.type == self.entity_type for entity in message.caption_entities)
|
||||
|
||||
class _Private(BaseFilter):
|
||||
name = 'Filters.private'
|
||||
@@ -533,6 +686,15 @@ class Filters(object):
|
||||
successful_payment = _SuccessfulPayment()
|
||||
""":obj:`Filter`: Messages that confirm a :class:`telegram.SuccessfulPayment`."""
|
||||
|
||||
class _PassportData(BaseFilter):
|
||||
name = 'Filters.passport_data'
|
||||
|
||||
def filter(self, message):
|
||||
return bool(message.passport_data)
|
||||
|
||||
passport_data = _PassportData()
|
||||
""":obj:`Filter`: Messages that contain a :class:`telegram.PassportData`"""
|
||||
|
||||
class language(BaseFilter):
|
||||
"""Filters messages to only allow those which are from users with a certain language code.
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#!/usr/bin/env python
|
||||
#
|
||||
# A library that provides a Python interface to the Telegram Bot API
|
||||
# Copyright (C) 2015-2017
|
||||
# Copyright (C) 2015-2018
|
||||
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
@@ -35,7 +35,7 @@ class Handler(object):
|
||||
|
||||
Note:
|
||||
:attr:`pass_user_data` and :attr:`pass_chat_data` determine whether a ``dict`` you
|
||||
can use to keep any data in will be sent to the :attr:`callback` function.. Related to
|
||||
can use to keep any data in will be sent to the :attr:`callback` function. Related to
|
||||
either the user or the chat that the update was sent in. For each update from the same user
|
||||
or in the same chat, it will be the same ``dict``.
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#!/usr/bin/env python
|
||||
#
|
||||
# A library that provides a Python interface to the Telegram Bot API
|
||||
# Copyright (C) 2015-2017
|
||||
# Copyright (C) 2015-2018
|
||||
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
@@ -50,7 +50,7 @@ class InlineQueryHandler(Handler):
|
||||
|
||||
Note:
|
||||
:attr:`pass_user_data` and :attr:`pass_chat_data` determine whether a ``dict`` you
|
||||
can use to keep any data in will be sent to the :attr:`callback` function.. Related to
|
||||
can use to keep any data in will be sent to the :attr:`callback` function. Related to
|
||||
either the user or the chat that the update was sent in. For each update from the same user
|
||||
or in the same chat, it will be the same ``dict``.
|
||||
|
||||
|
||||
+23
-64
@@ -1,8 +1,7 @@
|
||||
#!/usr/bin/env python
|
||||
# flake8: noqa E501
|
||||
#
|
||||
# A library that provides a Python interface to the Telegram Bot API
|
||||
# Copyright (C) 2015-2017
|
||||
# Copyright (C) 2015-2018
|
||||
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
@@ -21,7 +20,6 @@
|
||||
|
||||
import logging
|
||||
import time
|
||||
import warnings
|
||||
import datetime
|
||||
import weakref
|
||||
from numbers import Number
|
||||
@@ -38,23 +36,16 @@ class JobQueue(object):
|
||||
"""This class allows you to periodically perform tasks with the bot.
|
||||
|
||||
Attributes:
|
||||
queue (:obj:`PriorityQueue`): The queue that holds the Jobs.
|
||||
_queue (:obj:`PriorityQueue`): The queue that holds the Jobs.
|
||||
bot (:class:`telegram.Bot`): Bot that's send to the handlers.
|
||||
|
||||
Args:
|
||||
bot (:class:`telegram.Bot`): The bot instance that should be passed to the jobs.
|
||||
|
||||
Deprecated:
|
||||
prevent_autostart (:obj:`bool`, optional): Thread does not start during initialisation.
|
||||
Use `start` method instead.
|
||||
|
||||
"""
|
||||
|
||||
def __init__(self, bot, prevent_autostart=None):
|
||||
if prevent_autostart is not None:
|
||||
warnings.warn("prevent_autostart is being deprecated, use `start` method instead.")
|
||||
|
||||
self.queue = PriorityQueue()
|
||||
def __init__(self, bot):
|
||||
self._queue = PriorityQueue()
|
||||
self.bot = bot
|
||||
self.logger = logging.getLogger(self.__class__.__name__)
|
||||
self.__start_lock = Lock()
|
||||
@@ -64,37 +55,6 @@ class JobQueue(object):
|
||||
self._next_peek = None
|
||||
self._running = False
|
||||
|
||||
def put(self, job, next_t=None):
|
||||
"""Queue a new job.
|
||||
|
||||
Note:
|
||||
This method is deprecated. Please use: :attr:`run_once`, :attr:`run_daily`
|
||||
or :attr:`run_repeating` instead.
|
||||
|
||||
Args:
|
||||
job (:class:`telegram.ext.Job`): The ``Job`` instance representing the new job.
|
||||
next_t (:obj:`int` | :obj:`float` | :obj:`datetime.timedelta` | :obj:`datetime.datetime` | :obj:`datetime.time`, optional):
|
||||
Time in or at which the job should run for the first time. This parameter will
|
||||
be interpreted depending on its type.
|
||||
|
||||
* :obj:`int` or :obj:`float` will be interpreted as "seconds from now" in which the
|
||||
job should run.
|
||||
* :obj:`datetime.timedelta` will be interpreted as "time from now" in which the
|
||||
job should run.
|
||||
* :obj:`datetime.datetime` will be interpreted as a specific date and time at
|
||||
which the job should run.
|
||||
* :obj:`datetime.time` will be interpreted as a specific time at which the job
|
||||
should run. This could be either today or, if the time has already passed,
|
||||
tomorrow.
|
||||
|
||||
"""
|
||||
|
||||
warnings.warn("'JobQueue.put' is being deprecated, use 'JobQueue.run_once', "
|
||||
"'JobQueue.run_daily' or 'JobQueue.run_repeating' instead")
|
||||
if job.job_queue is None:
|
||||
job.job_queue = self
|
||||
self._put(job, next_t=next_t)
|
||||
|
||||
def _put(self, job, next_t=None, last_t=None):
|
||||
if next_t is None:
|
||||
next_t = job.interval
|
||||
@@ -119,7 +79,7 @@ class JobQueue(object):
|
||||
|
||||
self.logger.debug('Putting job %s with t=%f', job.name, next_t)
|
||||
|
||||
self.queue.put((next_t, job))
|
||||
self._queue.put((next_t, job))
|
||||
|
||||
# Wake up the loop if this job should be executed next
|
||||
self._set_next_peek(next_t)
|
||||
@@ -132,7 +92,8 @@ class JobQueue(object):
|
||||
job. It should take ``bot, job`` as parameters, where ``job`` is the
|
||||
:class:`telegram.ext.Job` instance. It can be used to access it's
|
||||
``job.context`` or change it to a repeating job.
|
||||
when (:obj:`int` | :obj:`float` | :obj:`datetime.timedelta` | :obj:`datetime.datetime` | :obj:`datetime.time`):
|
||||
when (:obj:`int` | :obj:`float` | :obj:`datetime.timedelta` | \
|
||||
:obj:`datetime.datetime` | :obj:`datetime.time`):
|
||||
Time in or at which the job should run. This parameter will be interpreted
|
||||
depending on its type.
|
||||
|
||||
@@ -171,7 +132,8 @@ class JobQueue(object):
|
||||
interval (:obj:`int` | :obj:`float` | :obj:`datetime.timedelta`): The interval in which
|
||||
the job will run. If it is an :obj:`int` or a :obj:`float`, it will be interpreted
|
||||
as seconds.
|
||||
first (:obj:`int` | :obj:`float` | :obj:`datetime.timedelta` | :obj:`datetime.datetime` | :obj:`datetime.time`, optional):
|
||||
first (:obj:`int` | :obj:`float` | :obj:`datetime.timedelta` | \
|
||||
:obj:`datetime.datetime` | :obj:`datetime.time`, optional):
|
||||
Time in or at which the job should run. This parameter will be interpreted
|
||||
depending on its type.
|
||||
|
||||
@@ -196,7 +158,6 @@ class JobQueue(object):
|
||||
queue.
|
||||
|
||||
"""
|
||||
|
||||
job = Job(callback,
|
||||
interval=interval,
|
||||
repeat=True,
|
||||
@@ -227,7 +188,6 @@ class JobQueue(object):
|
||||
queue.
|
||||
|
||||
"""
|
||||
|
||||
job = Job(callback,
|
||||
interval=datetime.timedelta(days=1),
|
||||
repeat=True,
|
||||
@@ -250,14 +210,13 @@ class JobQueue(object):
|
||||
|
||||
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 True:
|
||||
try:
|
||||
t, job = self.queue.get(False)
|
||||
t, job = self._queue.get(False)
|
||||
except Empty:
|
||||
break
|
||||
|
||||
@@ -270,7 +229,7 @@ class JobQueue(object):
|
||||
# 2. At the first iteration of the loop only if `self.put()` had triggered
|
||||
# `self.__tick` because `self._next_peek` wasn't set
|
||||
self.logger.debug("Next task isn't due yet. Finished!")
|
||||
self.queue.put((t, job))
|
||||
self._queue.put((t, job))
|
||||
self._set_next_peek(t)
|
||||
break
|
||||
|
||||
@@ -285,7 +244,7 @@ class JobQueue(object):
|
||||
self.logger.debug('Running job %s', job.name)
|
||||
job.run(self.bot)
|
||||
|
||||
except:
|
||||
except Exception:
|
||||
self.logger.exception('An uncaught error was raised while executing job %s',
|
||||
job.name)
|
||||
else:
|
||||
@@ -298,7 +257,6 @@ class JobQueue(object):
|
||||
|
||||
def start(self):
|
||||
"""Starts the job_queue thread."""
|
||||
|
||||
self.__start_lock.acquire()
|
||||
|
||||
if not self._running:
|
||||
@@ -335,7 +293,6 @@ class JobQueue(object):
|
||||
|
||||
def stop(self):
|
||||
"""Stops the thread."""
|
||||
|
||||
with self.__start_lock:
|
||||
self._running = False
|
||||
|
||||
@@ -345,8 +302,13 @@ class JobQueue(object):
|
||||
|
||||
def jobs(self):
|
||||
"""Returns a tuple of all jobs that are currently in the ``JobQueue``."""
|
||||
with self._queue.mutex:
|
||||
return tuple(job[1] for job in self._queue.queue if job)
|
||||
|
||||
return tuple(job[1] for job in self.queue.queue if job)
|
||||
def get_jobs_by_name(self, name):
|
||||
"""Returns a tuple of jobs with the given name that are currently in the ``JobQueue``"""
|
||||
with self._queue.mutex:
|
||||
return tuple(job[1] for job in self._queue.queue if job and job[1].name == name)
|
||||
|
||||
|
||||
class Job(object):
|
||||
@@ -373,7 +335,7 @@ class Job(object):
|
||||
name (:obj:`str`, optional): The name of the new job. Defaults to ``callback.__name__``.
|
||||
days (Tuple[:obj:`int`], optional): Defines on which days of the week the job should run.
|
||||
Defaults to ``Days.EVERY_DAY``
|
||||
job_queue (class:`telegram.ext.JobQueue`, optional): The ``JobQueue`` this job belongs to.
|
||||
job_queue (:class:`telegram.ext.JobQueue`, optional): The ``JobQueue`` this job belongs to.
|
||||
Only optional for backward compatibility with ``JobQueue.put()``.
|
||||
|
||||
"""
|
||||
@@ -407,7 +369,6 @@ class Job(object):
|
||||
|
||||
def run(self, bot):
|
||||
"""Executes the callback function."""
|
||||
|
||||
self.callback(bot, self)
|
||||
|
||||
def schedule_removal(self):
|
||||
@@ -416,7 +377,6 @@ class Job(object):
|
||||
its callback function again.
|
||||
|
||||
"""
|
||||
|
||||
self._remove.set()
|
||||
|
||||
@property
|
||||
@@ -459,10 +419,11 @@ class Job(object):
|
||||
@property
|
||||
def interval_seconds(self):
|
||||
""":obj:`int`: The interval for this job in seconds."""
|
||||
if isinstance(self.interval, datetime.timedelta):
|
||||
return self.interval.total_seconds()
|
||||
interval = self.interval
|
||||
if isinstance(interval, datetime.timedelta):
|
||||
return interval.total_seconds()
|
||||
else:
|
||||
return self.interval
|
||||
return interval
|
||||
|
||||
@property
|
||||
def repeat(self):
|
||||
@@ -478,7 +439,6 @@ class Job(object):
|
||||
@property
|
||||
def days(self):
|
||||
"""Tuple[:obj:`int`]: Optional. Defines on which days of the week the job should run."""
|
||||
|
||||
return self._days
|
||||
|
||||
@days.setter
|
||||
@@ -498,7 +458,6 @@ class Job(object):
|
||||
@property
|
||||
def job_queue(self):
|
||||
""":class:`telegram.ext.JobQueue`: Optional. The ``JobQueue`` this job belongs to."""
|
||||
|
||||
return self._job_queue
|
||||
|
||||
@job_queue.setter
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#!/usr/bin/env python
|
||||
#
|
||||
# A library that provides a Python interface to the Telegram Bot API
|
||||
# Copyright (C) 2015-2017
|
||||
# Copyright (C) 2015-2018
|
||||
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
@@ -20,8 +20,8 @@
|
||||
"""This module contains the MessageHandler class."""
|
||||
import warnings
|
||||
|
||||
from .handler import Handler
|
||||
from telegram import Update
|
||||
from .handler import Handler
|
||||
|
||||
|
||||
class MessageHandler(Handler):
|
||||
@@ -50,7 +50,7 @@ class MessageHandler(Handler):
|
||||
|
||||
Note:
|
||||
:attr:`pass_user_data` and :attr:`pass_chat_data` determine whether a ``dict`` you
|
||||
can use to keep any data in will be sent to the :attr:`callback` function.. Related to
|
||||
can use to keep any data in will be sent to the :attr:`callback` function. Related to
|
||||
either the user or the chat that the update was sent in. For each update from the same user
|
||||
or in the same chat, it will be the same ``dict``.
|
||||
|
||||
@@ -125,9 +125,9 @@ class MessageHandler(Handler):
|
||||
'instead. More info: https://git.io/vPTbc.')
|
||||
|
||||
def _is_allowed_update(self, update):
|
||||
return any([(self.message_updates and update.message),
|
||||
(self.edited_updates and update.edited_message),
|
||||
(self.channel_post_updates and update.channel_post)])
|
||||
return any([self.message_updates and update.message,
|
||||
self.edited_updates and (update.edited_message or update.edited_channel_post),
|
||||
self.channel_post_updates and update.channel_post])
|
||||
|
||||
def check_update(self, update):
|
||||
"""Determines whether an update should be passed to this handlers :attr:`callback`.
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
# Tymofii A. Khodniev (thodnev) <thodnev@mail.ru>
|
||||
#
|
||||
# A library that provides a Python interface to the Telegram Bot API
|
||||
# Copyright (C) 2015-2017
|
||||
# Copyright (C) 2015-2018
|
||||
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#!/usr/bin/env python
|
||||
#
|
||||
# A library that provides a Python interface to the Telegram Bot API
|
||||
# Copyright (C) 2015-2017
|
||||
# Copyright (C) 2015-2018
|
||||
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
@@ -38,7 +38,7 @@ class PreCheckoutQueryHandler(Handler):
|
||||
|
||||
Note:
|
||||
:attr:`pass_user_data` and :attr:`pass_chat_data` determine whether a ``dict`` you
|
||||
can use to keep any data in will be sent to the :attr:`callback` function.. Related to
|
||||
can use to keep any data in will be sent to the :attr:`callback` function. Related to
|
||||
either the user or the chat that the update was sent in. For each update from the same user
|
||||
or in the same chat, it will be the same ``dict``.
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#!/usr/bin/env python
|
||||
#
|
||||
# A library that provides a Python interface to the Telegram Bot API
|
||||
# Copyright (C) 2015-2017
|
||||
# Copyright (C) 2015-2018
|
||||
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
@@ -53,7 +53,7 @@ class RegexHandler(Handler):
|
||||
|
||||
Note:
|
||||
:attr:`pass_user_data` and :attr:`pass_chat_data` determine whether a ``dict`` you
|
||||
can use to keep any data in will be sent to the :attr:`callback` function.. Related to
|
||||
can use to keep any data in will be sent to the :attr:`callback` function. Related to
|
||||
either the user or the chat that the update was sent in. For each update from the same user
|
||||
or in the same chat, it will be the same ``dict``.
|
||||
|
||||
@@ -145,9 +145,9 @@ class RegexHandler(Handler):
|
||||
"""
|
||||
if not isinstance(update, Update) and not update.effective_message:
|
||||
return False
|
||||
if any([(self.message_updates and update.message),
|
||||
(self.edited_updates and update.edited_message),
|
||||
(self.channel_post_updates and update.channel_post)]) and \
|
||||
if any([self.message_updates and update.message,
|
||||
self.edited_updates and (update.edited_message or update.edited_channel_post),
|
||||
self.channel_post_updates and update.channel_post]) and \
|
||||
update.effective_message.text:
|
||||
match = re.match(self.pattern, update.effective_message.text)
|
||||
return bool(match)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#!/usr/bin/env python
|
||||
#
|
||||
# A library that provides a Python interface to the Telegram Bot API
|
||||
# Copyright (C) 2015-2017
|
||||
# Copyright (C) 2015-2018
|
||||
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
@@ -38,7 +38,7 @@ class ShippingQueryHandler(Handler):
|
||||
|
||||
Note:
|
||||
:attr:`pass_user_data` and :attr:`pass_chat_data` determine whether a ``dict`` you
|
||||
can use to keep any data in will be sent to the :attr:`callback` function.. Related to
|
||||
can use to keep any data in will be sent to the :attr:`callback` function. Related to
|
||||
either the user or the chat that the update was sent in. For each update from the same user
|
||||
or in the same chat, it will be the same ``dict``.
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#!/usr/bin/env python
|
||||
#
|
||||
# A library that provides a Python interface to the Telegram Bot API
|
||||
# Copyright (C) 2015-2017
|
||||
# Copyright (C) 2015-2018
|
||||
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#!/usr/bin/env python
|
||||
#
|
||||
# A library that provides a Python interface to the Telegram Bot API
|
||||
# Copyright (C) 2015-2017
|
||||
# Copyright (C) 2015-2018
|
||||
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#!/usr/bin/env python
|
||||
#
|
||||
# A library that provides a Python interface to the Telegram Bot API
|
||||
# Copyright (C) 2015-2017
|
||||
# Copyright (C) 2015-2018
|
||||
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
|
||||
+133
-82
@@ -1,7 +1,7 @@
|
||||
#!/usr/bin/env python
|
||||
#
|
||||
# A library that provides a Python interface to the Telegram Bot API
|
||||
# Copyright (C) 2015-2017
|
||||
# Copyright (C) 2015-2018
|
||||
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
@@ -21,7 +21,6 @@
|
||||
import logging
|
||||
import os
|
||||
import ssl
|
||||
import warnings
|
||||
from threading import Thread, Lock, current_thread, Event
|
||||
from time import sleep
|
||||
import subprocess
|
||||
@@ -30,7 +29,8 @@ from queue import Queue
|
||||
|
||||
from telegram import Bot, TelegramError
|
||||
from telegram.ext import Dispatcher, JobQueue
|
||||
from telegram.error import Unauthorized, InvalidToken, RetryAfter
|
||||
from telegram.error import Unauthorized, InvalidToken, RetryAfter, TimedOut
|
||||
from telegram.utils.helpers import get_signal_name
|
||||
from telegram.utils.request import Request
|
||||
from telegram.utils.webhookhandler import (WebhookServer, WebhookHandler)
|
||||
|
||||
@@ -66,11 +66,15 @@ class Updater(object):
|
||||
bot (:class:`telegram.Bot`, optional): A pre-initialized bot instance. If a pre-initialized
|
||||
bot is used, it is the user's responsibility to create it using a `Request`
|
||||
instance with a large enough connection pool.
|
||||
private_key (:obj:`bytes`, optional): Private key for decryption of telegram passport data.
|
||||
private_key_password (:obj:`bytes`, optional): Password for above private key.
|
||||
user_sig_handler (:obj:`function`, optional): Takes ``signum, frame`` as positional
|
||||
arguments. This will be called when a signal is received, defaults are (SIGINT,
|
||||
SIGTERM, SIGABRT) setable with :attr:`idle`.
|
||||
request_kwargs (:obj:`dict`, optional): Keyword args to control the creation of a request
|
||||
object (ignored if `bot` argument is used).
|
||||
request_kwargs (:obj:`dict`, optional): Keyword args to control the creation of a
|
||||
`telegram.utils.request.Request` object (ignored if `bot` argument is used). The
|
||||
request_kwargs are very useful for the advanced users who would like to control the
|
||||
default timeouts and/or control the proxy used for http communication.
|
||||
|
||||
Note:
|
||||
You must supply either a :attr:`bot` or a :attr:`token` argument.
|
||||
@@ -87,6 +91,8 @@ class Updater(object):
|
||||
base_url=None,
|
||||
workers=4,
|
||||
bot=None,
|
||||
private_key=None,
|
||||
private_key_password=None,
|
||||
user_sig_handler=None,
|
||||
request_kwargs=None):
|
||||
|
||||
@@ -94,6 +100,8 @@ class Updater(object):
|
||||
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 (private_key is not None) and (bot is not None):
|
||||
raise ValueError('`bot` and `private_key` are mutually exclusive')
|
||||
|
||||
self.logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -117,7 +125,8 @@ class Updater(object):
|
||||
if 'con_pool_size' not in request_kwargs:
|
||||
request_kwargs['con_pool_size'] = con_pool_size
|
||||
self._request = Request(**request_kwargs)
|
||||
self.bot = Bot(token, base_url, request=self._request)
|
||||
self.bot = Bot(token, base_url, request=self._request, private_key=private_key,
|
||||
private_key_password=private_key_password)
|
||||
self.user_sig_handler = user_sig_handler
|
||||
self.update_queue = Queue()
|
||||
self.job_queue = JobQueue(self.bot)
|
||||
@@ -147,16 +156,15 @@ class Updater(object):
|
||||
target(*args, **kwargs)
|
||||
except Exception:
|
||||
self.__exception_event.set()
|
||||
self.logger.exception('unhandled exception')
|
||||
self.logger.exception('unhandled exception in %s', thr_name)
|
||||
raise
|
||||
self.logger.debug('{0} - ended'.format(thr_name))
|
||||
|
||||
def start_polling(self,
|
||||
poll_interval=0.0,
|
||||
timeout=10,
|
||||
network_delay=None,
|
||||
clean=False,
|
||||
bootstrap_retries=0,
|
||||
bootstrap_retries=-1,
|
||||
read_latency=2.,
|
||||
allowed_updates=None):
|
||||
"""Starts polling updates from Telegram.
|
||||
@@ -170,8 +178,8 @@ class Updater(object):
|
||||
bootstrap_retries (:obj:`int`, optional): Whether the bootstrapping phase of the
|
||||
`Updater` will retry on failures on the Telegram server.
|
||||
|
||||
* < 0 - retry indefinitely
|
||||
* 0 - no retries (default)
|
||||
* < 0 - retry indefinitely (default)
|
||||
* 0 - no retries
|
||||
* > 0 - retry up to X times
|
||||
|
||||
allowed_updates (List[:obj:`str`], optional): Passed to
|
||||
@@ -179,28 +187,24 @@ class Updater(object):
|
||||
read_latency (:obj:`float` | :obj:`int`, optional): Grace time in seconds for receiving
|
||||
the reply from server. Will be added to the `timeout` value and used as the read
|
||||
timeout from server (Default: 2).
|
||||
network_delay: Deprecated. Will be honoured as :attr:`read_latency` for a while but
|
||||
will be removed in the future.
|
||||
|
||||
Returns:
|
||||
:obj:`Queue`: The update queue that can be filled from the main thread.
|
||||
|
||||
"""
|
||||
|
||||
if network_delay is not None:
|
||||
warnings.warn('network_delay is deprecated, use read_latency instead')
|
||||
read_latency = network_delay
|
||||
|
||||
with self.__lock:
|
||||
if not self.running:
|
||||
self.running = True
|
||||
|
||||
# Create & start threads
|
||||
self.job_queue.start()
|
||||
self._init_thread(self.dispatcher.start, "dispatcher")
|
||||
dispatcher_ready = Event()
|
||||
self._init_thread(self.dispatcher.start, "dispatcher", ready=dispatcher_ready)
|
||||
self._init_thread(self._start_polling, "updater", poll_interval, timeout,
|
||||
read_latency, bootstrap_retries, clean, allowed_updates)
|
||||
|
||||
dispatcher_ready.wait()
|
||||
|
||||
# Return the update queue so the main thread can insert updates
|
||||
return self.update_queue
|
||||
|
||||
@@ -232,8 +236,8 @@ class Updater(object):
|
||||
bootstrap_retries (:obj:`int`, optional): Whether the bootstrapping phase of the
|
||||
`Updater` will retry on failures on the Telegram server.
|
||||
|
||||
* < 0 - retry indefinitely
|
||||
* 0 - no retries (default)
|
||||
* < 0 - retry indefinitely (default)
|
||||
* 0 - no retries
|
||||
* > 0 - retry up to X times
|
||||
|
||||
webhook_url (:obj:`str`, optional): Explicitly specify the webhook url. Useful behind
|
||||
@@ -245,7 +249,6 @@ class Updater(object):
|
||||
:obj:`Queue`: The update queue that can be filled from the main thread.
|
||||
|
||||
"""
|
||||
|
||||
with self.__lock:
|
||||
if not self.running:
|
||||
self.running = True
|
||||
@@ -260,51 +263,80 @@ class Updater(object):
|
||||
return self.update_queue
|
||||
|
||||
def _start_polling(self, poll_interval, timeout, read_latency, bootstrap_retries, clean,
|
||||
allowed_updates):
|
||||
# """
|
||||
allowed_updates): # pragma: no cover
|
||||
# Thread target of thread 'updater'. Runs in background, pulls
|
||||
# updates from Telegram and inserts them in the update queue of the
|
||||
# Dispatcher.
|
||||
# """
|
||||
|
||||
cur_interval = poll_interval
|
||||
self.logger.debug('Updater thread started')
|
||||
self.logger.debug('Updater thread started (polling)')
|
||||
|
||||
self._bootstrap(bootstrap_retries, clean=clean, webhook_url='', allowed_updates=None)
|
||||
|
||||
while self.running:
|
||||
try:
|
||||
updates = self.bot.get_updates(
|
||||
self.last_update_id,
|
||||
timeout=timeout,
|
||||
read_latency=read_latency,
|
||||
allowed_updates=allowed_updates)
|
||||
except RetryAfter as e:
|
||||
self.logger.info(str(e))
|
||||
cur_interval = 0.5 + e.retry_after
|
||||
except TelegramError as te:
|
||||
self.logger.error("Error while getting Updates: {0}".format(te))
|
||||
self.logger.debug('Bootstrap done')
|
||||
|
||||
# Put the error into the update queue and let the Dispatcher
|
||||
# broadcast it
|
||||
self.update_queue.put(te)
|
||||
def polling_action_cb():
|
||||
updates = self.bot.get_updates(
|
||||
self.last_update_id, timeout=timeout, read_latency=read_latency,
|
||||
allowed_updates=allowed_updates)
|
||||
|
||||
cur_interval = self._increase_poll_interval(cur_interval)
|
||||
else:
|
||||
if updates:
|
||||
if not self.running:
|
||||
if len(updates) > 0:
|
||||
self.logger.debug('Updates ignored and will be pulled '
|
||||
'again on restart.')
|
||||
break
|
||||
|
||||
if updates:
|
||||
self.logger.debug('Updates ignored and will be pulled again on restart')
|
||||
else:
|
||||
for update in updates:
|
||||
self.update_queue.put(update)
|
||||
self.last_update_id = updates[-1].update_id + 1
|
||||
|
||||
cur_interval = poll_interval
|
||||
return True
|
||||
|
||||
sleep(cur_interval)
|
||||
def polling_onerr_cb(exc):
|
||||
# Put the error into the update queue and let the Dispatcher
|
||||
# broadcast it
|
||||
self.update_queue.put(exc)
|
||||
|
||||
self._network_loop_retry(polling_action_cb, polling_onerr_cb, 'getting Updates',
|
||||
poll_interval)
|
||||
|
||||
def _network_loop_retry(self, action_cb, onerr_cb, description, interval):
|
||||
"""Perform a loop calling `action_cb`, retrying after network errors.
|
||||
|
||||
Stop condition for loop: `self.running` evaluates False or return value of `action_cb`
|
||||
evaluates False.
|
||||
|
||||
Args:
|
||||
action_cb (:obj:`callable`): Network oriented callback function to call.
|
||||
onerr_cb (:obj:`callable`): Callback to call when TelegramError is caught. Receives the
|
||||
exception object as a parameter.
|
||||
description (:obj:`str`): Description text to use for logs and exception raised.
|
||||
interval (:obj:`float` | :obj:`int`): Interval to sleep between each call to
|
||||
`action_cb`.
|
||||
|
||||
"""
|
||||
self.logger.debug('Start network loop retry %s', description)
|
||||
cur_interval = interval
|
||||
while self.running:
|
||||
try:
|
||||
if not action_cb():
|
||||
break
|
||||
except RetryAfter as e:
|
||||
self.logger.info('%s', e)
|
||||
cur_interval = 0.5 + e.retry_after
|
||||
except TimedOut as toe:
|
||||
self.logger.debug('Timed out %s: %s', description, toe)
|
||||
# If failure is due to timeout, we should retry asap.
|
||||
cur_interval = 0
|
||||
except InvalidToken as pex:
|
||||
self.logger.error('Invalid token; aborting')
|
||||
raise pex
|
||||
except TelegramError as te:
|
||||
self.logger.error('Error while %s: %s', description, te)
|
||||
onerr_cb(te)
|
||||
cur_interval = self._increase_poll_interval(cur_interval)
|
||||
else:
|
||||
cur_interval = interval
|
||||
|
||||
if cur_interval:
|
||||
sleep(cur_interval)
|
||||
|
||||
@staticmethod
|
||||
def _increase_poll_interval(current_interval):
|
||||
@@ -319,7 +351,7 @@ class Updater(object):
|
||||
|
||||
def _start_webhook(self, listen, port, url_path, cert, key, bootstrap_retries, clean,
|
||||
webhook_url, allowed_updates):
|
||||
self.logger.debug('Updater thread started')
|
||||
self.logger.debug('Updater thread started (webhook)')
|
||||
use_ssl = cert is not None and key is not None
|
||||
if not url_path.startswith('/'):
|
||||
url_path = '/{0}'.format(url_path)
|
||||
@@ -356,7 +388,7 @@ class Updater(object):
|
||||
stderr=subprocess.STDOUT)
|
||||
except OSError:
|
||||
exit_code = 0
|
||||
if exit_code is 0:
|
||||
if exit_code == 0:
|
||||
try:
|
||||
self.httpd.socket = ssl.wrap_socket(
|
||||
self.httpd.socket, certfile=cert, keyfile=key, server_side=True)
|
||||
@@ -370,39 +402,56 @@ class Updater(object):
|
||||
def _gen_webhook_url(listen, port, url_path):
|
||||
return 'https://{listen}:{port}{path}'.format(listen=listen, port=port, path=url_path)
|
||||
|
||||
def _bootstrap(self, max_retries, clean, webhook_url, allowed_updates, cert=None):
|
||||
retries = 0
|
||||
while 1:
|
||||
def _bootstrap(self, max_retries, clean, webhook_url, allowed_updates, cert=None,
|
||||
bootstrap_interval=5):
|
||||
retries = [0]
|
||||
|
||||
try:
|
||||
if clean:
|
||||
# Disable webhook for cleaning
|
||||
self.bot.delete_webhook()
|
||||
self._clean_updates()
|
||||
sleep(1)
|
||||
def bootstrap_del_webhook():
|
||||
self.bot.delete_webhook()
|
||||
return False
|
||||
|
||||
self.bot.set_webhook(
|
||||
url=webhook_url, certificate=cert, allowed_updates=allowed_updates)
|
||||
except (Unauthorized, InvalidToken):
|
||||
raise
|
||||
except TelegramError:
|
||||
msg = 'error in bootstrap phase; try={0} max_retries={1}'.format(retries,
|
||||
max_retries)
|
||||
if max_retries < 0 or retries < max_retries:
|
||||
self.logger.warning(msg)
|
||||
retries += 1
|
||||
else:
|
||||
self.logger.exception(msg)
|
||||
raise
|
||||
def bootstrap_clean_updates():
|
||||
self.logger.debug('Cleaning updates from Telegram server')
|
||||
updates = self.bot.get_updates()
|
||||
while updates:
|
||||
updates = self.bot.get_updates(updates[-1].update_id + 1)
|
||||
return False
|
||||
|
||||
def bootstrap_set_webhook():
|
||||
self.bot.set_webhook(
|
||||
url=webhook_url, certificate=cert, allowed_updates=allowed_updates)
|
||||
return False
|
||||
|
||||
def bootstrap_onerr_cb(exc):
|
||||
if not isinstance(exc, Unauthorized) and (max_retries < 0 or retries[0] < max_retries):
|
||||
retries[0] += 1
|
||||
self.logger.warning('Failed bootstrap phase; try=%s max_retries=%s',
|
||||
retries[0], max_retries)
|
||||
else:
|
||||
break
|
||||
self.logger.error('Failed bootstrap phase after %s retries (%s)', retries[0], exc)
|
||||
raise exc
|
||||
|
||||
# Cleaning pending messages is done by polling for them - so we need to delete webhook if
|
||||
# one is configured.
|
||||
# We also take this chance to delete pre-configured webhook if this is a polling Updater.
|
||||
# NOTE: We don't know ahead if a webhook is configured, so we just delete.
|
||||
if clean or not webhook_url:
|
||||
self._network_loop_retry(bootstrap_del_webhook, bootstrap_onerr_cb,
|
||||
'bootstrap del webhook', bootstrap_interval)
|
||||
retries[0] = 0
|
||||
|
||||
# Clean pending messages, if requested.
|
||||
if clean:
|
||||
self._network_loop_retry(bootstrap_clean_updates, bootstrap_onerr_cb,
|
||||
'bootstrap clean updates', bootstrap_interval)
|
||||
retries[0] = 0
|
||||
sleep(1)
|
||||
|
||||
def _clean_updates(self):
|
||||
self.logger.debug('Cleaning updates from Telegram server')
|
||||
updates = self.bot.get_updates()
|
||||
while updates:
|
||||
updates = self.bot.get_updates(updates[-1].update_id + 1)
|
||||
# Restore/set webhook settings, if needed. Again, we don't know ahead if a webhook is set,
|
||||
# so we set it anyhow.
|
||||
if webhook_url:
|
||||
self._network_loop_retry(bootstrap_set_webhook, bootstrap_onerr_cb,
|
||||
'bootstrap set webhook', bootstrap_interval)
|
||||
|
||||
def stop(self):
|
||||
"""Stops the polling/webhook thread, the dispatcher and the job queue."""
|
||||
@@ -444,6 +493,8 @@ class Updater(object):
|
||||
def signal_handler(self, signum, frame):
|
||||
self.is_idle = False
|
||||
if self.running:
|
||||
self.logger.info('Received signal {} ({}), stopping...'.format(
|
||||
signum, get_signal_name(signum)))
|
||||
self.stop()
|
||||
if self.user_sig_handler:
|
||||
self.user_sig_handler(signum, frame)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#!/usr/bin/env python
|
||||
#
|
||||
# A library that provides a Python interface to the Telegram Bot API
|
||||
# Copyright (C) 2015-2017
|
||||
# Copyright (C) 2015-2018
|
||||
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
@@ -26,6 +26,9 @@ class Animation(TelegramObject):
|
||||
|
||||
Attributes:
|
||||
file_id (:obj:`str`): Unique file identifier.
|
||||
width (:obj:`int`): Video width as defined by sender.
|
||||
height (:obj:`int`): Video height as defined by sender.
|
||||
duration (:obj:`int`): Duration of the video in seconds as defined by sender.
|
||||
thumb (:class:`telegram.PhotoSize`): Optional. Animation thumbnail as defined
|
||||
by sender.
|
||||
file_name (:obj:`str`): Optional. Original animation filename as defined by sender.
|
||||
@@ -34,6 +37,9 @@ class Animation(TelegramObject):
|
||||
|
||||
Args:
|
||||
file_id (:obj:`str`): Unique file identifier.
|
||||
width (:obj:`int`): Video width as defined by sender.
|
||||
height (:obj:`int`): Video height as defined by sender.
|
||||
duration (:obj:`int`): Duration of the video in seconds as defined by sender.
|
||||
thumb (:class:`telegram.PhotoSize`, optional): Animation thumbnail as defined by sender.
|
||||
file_name (:obj:`str`, optional): Original animation filename as defined by sender.
|
||||
mime_type (:obj:`str`, optional): MIME type of the file as defined by sender.
|
||||
@@ -43,12 +49,19 @@ class Animation(TelegramObject):
|
||||
|
||||
def __init__(self,
|
||||
file_id,
|
||||
width,
|
||||
height,
|
||||
duration,
|
||||
thumb=None,
|
||||
file_name=None,
|
||||
mime_type=None,
|
||||
file_size=None,
|
||||
**kwargs):
|
||||
self.file_id = file_id
|
||||
# Required
|
||||
self.file_id = str(file_id)
|
||||
self.width = int(width)
|
||||
self.height = int(height)
|
||||
self.duration = duration
|
||||
self.thumb = thumb
|
||||
self.file_name = file_name
|
||||
self.mime_type = mime_type
|
||||
+33
-3
@@ -1,7 +1,7 @@
|
||||
#!/usr/bin/env python
|
||||
#
|
||||
# A library that provides a Python interface to the Telegram Bot API
|
||||
# Copyright (C) 2015-2017
|
||||
# Copyright (C) 2015-2018
|
||||
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
@@ -18,7 +18,7 @@
|
||||
# along with this program. If not, see [http://www.gnu.org/licenses/].
|
||||
"""This module contains an object that represents a Telegram Audio."""
|
||||
|
||||
from telegram import TelegramObject
|
||||
from telegram import TelegramObject, PhotoSize
|
||||
|
||||
|
||||
class Audio(TelegramObject):
|
||||
@@ -32,6 +32,9 @@ class Audio(TelegramObject):
|
||||
title (:obj:`str`): Optional. Title of the audio as defined by sender or by audio tags.
|
||||
mime_type (:obj:`str`): Optional. MIME type of the file as defined by sender.
|
||||
file_size (:obj:`int`): Optional. File size.
|
||||
thumb (:class:`telegram.PhotoSize`): Optional. Thumbnail of the album cover to
|
||||
which the music file belongs
|
||||
bot (:class:`telegram.Bot`): Optional. The Bot to use for instance methods.
|
||||
|
||||
Args:
|
||||
file_id (:obj:`str`): Unique identifier for this file.
|
||||
@@ -41,6 +44,9 @@ class Audio(TelegramObject):
|
||||
title (:obj:`str`, optional): Title of the audio as defined by sender or by audio tags.
|
||||
mime_type (:obj:`str`, optional): MIME type of the file as defined by sender.
|
||||
file_size (:obj:`int`, optional): File size.
|
||||
thumb (:class:`telegram.PhotoSize`, optional): Thumbnail of the album cover to
|
||||
which the music file belongs
|
||||
bot (:class:`telegram.Bot`, optional): The Bot to use for instance methods.
|
||||
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
|
||||
|
||||
"""
|
||||
@@ -52,6 +58,8 @@ class Audio(TelegramObject):
|
||||
title=None,
|
||||
mime_type=None,
|
||||
file_size=None,
|
||||
thumb=None,
|
||||
bot=None,
|
||||
**kwargs):
|
||||
# Required
|
||||
self.file_id = str(file_id)
|
||||
@@ -61,6 +69,8 @@ class Audio(TelegramObject):
|
||||
self.title = title
|
||||
self.mime_type = mime_type
|
||||
self.file_size = file_size
|
||||
self.thumb = thumb
|
||||
self.bot = bot
|
||||
|
||||
self._id_attrs = (self.file_id,)
|
||||
|
||||
@@ -69,4 +79,24 @@ class Audio(TelegramObject):
|
||||
if not data:
|
||||
return None
|
||||
|
||||
return cls(**data)
|
||||
data['thumb'] = PhotoSize.de_json(data.get('thumb'), bot)
|
||||
|
||||
return cls(bot=bot, **data)
|
||||
|
||||
def get_file(self, timeout=None, **kwargs):
|
||||
"""Convenience wrapper over :attr:`telegram.Bot.get_file`
|
||||
|
||||
Args:
|
||||
timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as
|
||||
the read timeout from the server (instead of the one specified during creation of
|
||||
the connection pool).
|
||||
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
|
||||
|
||||
Returns:
|
||||
:class:`telegram.File`
|
||||
|
||||
Raises:
|
||||
:class:`telegram.TelegramError`
|
||||
|
||||
"""
|
||||
return self.bot.get_file(self.file_id, timeout=timeout, **kwargs)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#!/usr/bin/env python
|
||||
#
|
||||
# A library that provides a Python interface to the Telegram Bot API
|
||||
# Copyright (C) 2015-2017
|
||||
# Copyright (C) 2015-2018
|
||||
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#!/usr/bin/env python
|
||||
#
|
||||
# A library that provides a Python interface to the Telegram Bot API
|
||||
# Copyright (C) 2015-2017
|
||||
# Copyright (C) 2015-2018
|
||||
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
@@ -29,23 +29,27 @@ class Contact(TelegramObject):
|
||||
first_name (:obj:`str`): Contact's first name.
|
||||
last_name (:obj:`str`): Optional. Contact's last name.
|
||||
user_id (:obj:`int`): Optional. Contact's user identifier in Telegram.
|
||||
vcard (:obj:`str`): Optional. Additional data about the contact in the form of a vCard.
|
||||
|
||||
Args:
|
||||
phone_number (:obj:`str`): Contact's phone number.
|
||||
first_name (:obj:`str`): Contact's first name.
|
||||
last_name (:obj:`str`, optional): Contact's last name.
|
||||
user_id (:obj:`int`, optional): Contact's user identifier in Telegram.
|
||||
vcard (:obj:`str`, optional): Additional data about the contact in the form of a vCard.
|
||||
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
|
||||
|
||||
"""
|
||||
|
||||
def __init__(self, phone_number, first_name, last_name=None, user_id=None, **kwargs):
|
||||
def __init__(self, phone_number, first_name, last_name=None, user_id=None, vcard=None,
|
||||
**kwargs):
|
||||
# Required
|
||||
self.phone_number = str(phone_number)
|
||||
self.first_name = first_name
|
||||
# Optionals
|
||||
self.last_name = last_name
|
||||
self.user_id = user_id
|
||||
self.vcard = vcard
|
||||
|
||||
self._id_attrs = (self.phone_number,)
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#!/usr/bin/env python
|
||||
#
|
||||
# A library that provides a Python interface to the Telegram Bot API
|
||||
# Copyright (C) 2015-2017
|
||||
# Copyright (C) 2015-2018
|
||||
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
@@ -30,6 +30,7 @@ class Document(TelegramObject):
|
||||
file_name (:obj:`str`): Original filename.
|
||||
mime_type (:obj:`str`): Optional. MIME type of the file.
|
||||
file_size (:obj:`int`): Optional. File size.
|
||||
bot (:class:`telegram.Bot`): Optional. The Bot to use for instance methods.
|
||||
|
||||
Args:
|
||||
file_id (:obj:`str`): Unique file identifier
|
||||
@@ -37,6 +38,7 @@ class Document(TelegramObject):
|
||||
file_name (:obj:`str`, optional): Original filename as defined by sender.
|
||||
mime_type (:obj:`str`, optional): MIME type of the file as defined by sender.
|
||||
file_size (:obj:`int`, optional): File size.
|
||||
bot (:class:`telegram.Bot`, optional): The Bot to use for instance methods.
|
||||
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
|
||||
|
||||
"""
|
||||
@@ -48,6 +50,7 @@ class Document(TelegramObject):
|
||||
file_name=None,
|
||||
mime_type=None,
|
||||
file_size=None,
|
||||
bot=None,
|
||||
**kwargs):
|
||||
# Required
|
||||
self.file_id = str(file_id)
|
||||
@@ -56,6 +59,7 @@ class Document(TelegramObject):
|
||||
self.file_name = file_name
|
||||
self.mime_type = mime_type
|
||||
self.file_size = file_size
|
||||
self.bot = bot
|
||||
|
||||
self._id_attrs = (self.file_id,)
|
||||
|
||||
@@ -68,4 +72,22 @@ class Document(TelegramObject):
|
||||
|
||||
data['thumb'] = PhotoSize.de_json(data.get('thumb'), bot)
|
||||
|
||||
return cls(**data)
|
||||
return cls(bot=bot, **data)
|
||||
|
||||
def get_file(self, timeout=None, **kwargs):
|
||||
"""Convenience wrapper over :attr:`telegram.Bot.get_file`
|
||||
|
||||
Args:
|
||||
timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as
|
||||
the read timeout from the server (instead of the one specified during creation of
|
||||
the connection pool).
|
||||
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
|
||||
|
||||
Returns:
|
||||
:class:`telegram.File`
|
||||
|
||||
Raises:
|
||||
:class:`telegram.TelegramError`
|
||||
|
||||
"""
|
||||
return self.bot.get_file(self.file_id, timeout=timeout, **kwargs)
|
||||
|
||||
+51
-10
@@ -1,7 +1,7 @@
|
||||
#!/usr/bin/env python
|
||||
#
|
||||
# A library that provides a Python interface to the Telegram Bot API
|
||||
# Copyright (C) 2015-2017
|
||||
# Copyright (C) 2015-2018
|
||||
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
@@ -22,6 +22,7 @@ from os.path import basename
|
||||
from future.backports.urllib import parse as urllib_parse
|
||||
|
||||
from telegram import TelegramObject
|
||||
from telegram.passport.credentials import decrypt
|
||||
|
||||
|
||||
class File(TelegramObject):
|
||||
@@ -45,6 +46,10 @@ class File(TelegramObject):
|
||||
bot (:obj:`telegram.Bot`, optional): Bot to use with shortcut method.
|
||||
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
|
||||
|
||||
Note:
|
||||
If you obtain an instance of this class from :attr:`telegram.PassportFile.get_file`,
|
||||
then it will automatically be decrypted as it downloads when you call :attr:`download()`.
|
||||
|
||||
"""
|
||||
|
||||
def __init__(self, file_id, bot=None, file_size=None, file_path=None, **kwargs):
|
||||
@@ -56,6 +61,7 @@ class File(TelegramObject):
|
||||
self.file_path = file_path
|
||||
|
||||
self.bot = bot
|
||||
self._credentials = None
|
||||
|
||||
self._id_attrs = (self.file_id,)
|
||||
|
||||
@@ -74,36 +80,71 @@ class File(TelegramObject):
|
||||
that object using the ``out.write`` method.
|
||||
|
||||
Note:
|
||||
`custom_path` and `out` are mutually exclusive.
|
||||
:attr:`custom_path` and :attr:`out` are mutually exclusive.
|
||||
|
||||
Args:
|
||||
custom_path (:obj:`str`, optional): Custom path.
|
||||
out (:obj:`object`, optional): A file-like object. Must be opened in binary mode, if
|
||||
applicable.
|
||||
out (:obj:`io.BufferedWriter`, optional): A file-like object. Must be opened for
|
||||
writing in binary mode, if applicable.
|
||||
timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as
|
||||
the read timeout from the server (instead of the one specified during creation of
|
||||
the connection pool).
|
||||
|
||||
Returns:
|
||||
:obj:`str` | :obj:`io.BufferedWriter`: The same object as :attr:`out` if specified.
|
||||
Otherwise, returns the filename downloaded to.
|
||||
|
||||
Raises:
|
||||
ValueError: If both ``custom_path`` and ``out`` are passed.
|
||||
ValueError: If both :attr:`custom_path` and :attr:`out` are passed.
|
||||
|
||||
"""
|
||||
if custom_path is not None and out is not None:
|
||||
raise ValueError('custom_path and out are mutually exclusive')
|
||||
|
||||
# Convert any UTF-8 char into a url encoded ASCII string.
|
||||
sres = urllib_parse.urlsplit(self.file_path)
|
||||
url = urllib_parse.urlunsplit(urllib_parse.SplitResult(
|
||||
sres.scheme, sres.netloc, urllib_parse.quote(sres.path), sres.query, sres.fragment))
|
||||
url = self._get_encoded_url()
|
||||
|
||||
if out:
|
||||
buf = self.bot.request.retrieve(url)
|
||||
if self._credentials:
|
||||
buf = decrypt(self._credentials.secret, self._credentials.hash, buf, file=True)
|
||||
out.write(buf)
|
||||
|
||||
return out
|
||||
else:
|
||||
if custom_path:
|
||||
filename = custom_path
|
||||
else:
|
||||
filename = basename(self.file_path)
|
||||
|
||||
self.bot.request.download(url, filename, timeout=timeout)
|
||||
buf = self.bot.request.retrieve(url, timeout=timeout)
|
||||
if self._credentials:
|
||||
buf = decrypt(self._credentials.secret, self._credentials.hash, buf, file=True)
|
||||
with open(filename, 'wb') as fobj:
|
||||
fobj.write(buf)
|
||||
return filename
|
||||
|
||||
def _get_encoded_url(self):
|
||||
"""Convert any UTF-8 char in :obj:`File.file_path` into a url encoded ASCII string."""
|
||||
sres = urllib_parse.urlsplit(self.file_path)
|
||||
return urllib_parse.urlunsplit(urllib_parse.SplitResult(
|
||||
sres.scheme, sres.netloc, urllib_parse.quote(sres.path), sres.query, sres.fragment))
|
||||
|
||||
def download_as_bytearray(self, buf=None):
|
||||
"""Download this file and return it as a bytearray.
|
||||
|
||||
Args:
|
||||
buf (:obj:`bytearray`, optional): Extend the given bytearray with the downloaded data.
|
||||
|
||||
Returns:
|
||||
:obj:`bytearray`: The same object as :attr:`buf` if it was specified. Otherwise a newly
|
||||
allocated :obj:`bytearray`.
|
||||
|
||||
"""
|
||||
if buf is None:
|
||||
buf = bytearray()
|
||||
|
||||
buf.extend(self.bot.request.retrieve(self._get_encoded_url()))
|
||||
return buf
|
||||
|
||||
def set_credentials(self, credentials):
|
||||
self._credentials = credentials
|
||||
|
||||
+41
-112
@@ -2,7 +2,7 @@
|
||||
# pylint: disable=W0622,E0611
|
||||
#
|
||||
# A library that provides a Python interface to the Telegram Bot API
|
||||
# Copyright (C) 2015-2017
|
||||
# Copyright (C) 2015-2018
|
||||
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
@@ -19,126 +19,68 @@
|
||||
# along with this program. If not, see [http://www.gnu.org/licenses/].
|
||||
"""This module contains an object that represents a Telegram InputFile."""
|
||||
|
||||
try:
|
||||
# python 3
|
||||
from email.generator import _make_boundary as choose_boundary
|
||||
except ImportError:
|
||||
# python 2
|
||||
from mimetools import choose_boundary
|
||||
|
||||
import imghdr
|
||||
import mimetypes
|
||||
import os
|
||||
import sys
|
||||
from uuid import uuid4
|
||||
|
||||
from telegram import TelegramError
|
||||
|
||||
DEFAULT_MIME_TYPE = 'application/octet-stream'
|
||||
USER_AGENT = 'Python Telegram Bot (https://github.com/python-telegram-bot/python-telegram-bot)'
|
||||
FILE_TYPES = ('audio', 'document', 'photo', 'sticker', 'video', 'voice', 'certificate',
|
||||
'video_note', 'png_sticker')
|
||||
|
||||
|
||||
class InputFile(object):
|
||||
"""This object represents a Telegram InputFile.
|
||||
|
||||
Attributes:
|
||||
data (:obj:`dict`): Data containing an inputfile.
|
||||
input_file_content (:obj:`bytes`): The binaray content of the file to send.
|
||||
filename (:obj:`str`): Optional, Filename for the file to be sent.
|
||||
attach (:obj:`str`): Optional, attach id for sending multiple files.
|
||||
|
||||
Args:
|
||||
data (:obj:`dict`): Data containing an inputfile.
|
||||
obj (:obj:`File handler`): An open file descriptor.
|
||||
filename (:obj:`str`, optional): Filename for this InputFile.
|
||||
attach (:obj:`bool`, optional): Whether this should be send as one file or is part of a
|
||||
collection of files.
|
||||
|
||||
Raises:
|
||||
TelegramError
|
||||
|
||||
"""
|
||||
|
||||
def __init__(self, data):
|
||||
self.data = data
|
||||
self.boundary = choose_boundary()
|
||||
def __init__(self, obj, filename=None, attach=None):
|
||||
self.filename = None
|
||||
self.input_file_content = obj.read()
|
||||
self.attach = 'attached' + uuid4().hex if attach else None
|
||||
|
||||
for t in FILE_TYPES:
|
||||
if t in data:
|
||||
self.input_name = t
|
||||
self.input_file = data.pop(t)
|
||||
break
|
||||
else:
|
||||
raise TelegramError('Unknown inputfile type')
|
||||
if filename:
|
||||
self.filename = filename
|
||||
elif (hasattr(obj, 'name') and
|
||||
not isinstance(obj.name, int) and # py3
|
||||
obj.name != '<fdopen>'): # py2
|
||||
# on py2.7, pylint fails to understand this properly
|
||||
# pylint: disable=E1101
|
||||
self.filename = os.path.basename(obj.name)
|
||||
|
||||
if hasattr(self.input_file, 'read'):
|
||||
self.filename = None
|
||||
self.input_file_content = self.input_file.read()
|
||||
if 'filename' in data:
|
||||
self.filename = self.data.pop('filename')
|
||||
elif hasattr(self.input_file, 'name'):
|
||||
# on py2.7, pylint fails to understand this properly
|
||||
# pylint: disable=E1101
|
||||
self.filename = os.path.basename(self.input_file.name)
|
||||
try:
|
||||
self.mimetype = self.is_image(self.input_file_content)
|
||||
except TelegramError:
|
||||
if self.filename:
|
||||
self.mimetype = mimetypes.guess_type(
|
||||
self.filename)[0] or DEFAULT_MIME_TYPE
|
||||
else:
|
||||
self.mimetype = DEFAULT_MIME_TYPE
|
||||
if not self.filename or '.' not in self.filename:
|
||||
self.filename = self.mimetype.replace('/', '.')
|
||||
|
||||
try:
|
||||
self.mimetype = self.is_image(self.input_file_content)
|
||||
if not self.filename or '.' not in self.filename:
|
||||
self.filename = self.mimetype.replace('/', '.')
|
||||
except TelegramError:
|
||||
if self.filename:
|
||||
self.mimetype = mimetypes.guess_type(
|
||||
self.filename)[0] or DEFAULT_MIME_TYPE
|
||||
else:
|
||||
self.mimetype = DEFAULT_MIME_TYPE
|
||||
if sys.version_info < (3,):
|
||||
if isinstance(self.filename, unicode): # flake8: noqa pylint: disable=E0602
|
||||
self.filename = self.filename.encode('utf-8', 'replace')
|
||||
|
||||
@property
|
||||
def headers(self):
|
||||
""":obj:`dict`: Headers."""
|
||||
|
||||
return {'User-agent': USER_AGENT, 'Content-type': self.content_type}
|
||||
|
||||
@property
|
||||
def content_type(self):
|
||||
""":obj:`str`: Content type"""
|
||||
return 'multipart/form-data; boundary=%s' % self.boundary
|
||||
|
||||
def to_form(self):
|
||||
"""Transform the inputfile to multipart/form data.
|
||||
|
||||
Returns:
|
||||
:obj:`str`
|
||||
|
||||
"""
|
||||
form = []
|
||||
form_boundary = '--' + self.boundary
|
||||
|
||||
# Add data fields
|
||||
for name in iter(self.data):
|
||||
value = self.data[name]
|
||||
form.extend([
|
||||
form_boundary, 'Content-Disposition: form-data; name="%s"' % name, '', str(value)
|
||||
])
|
||||
|
||||
# Add input_file to upload
|
||||
form.extend([
|
||||
form_boundary, 'Content-Disposition: form-data; name="%s"; filename="%s"' %
|
||||
(self.input_name,
|
||||
self.filename), 'Content-Type: %s' % self.mimetype, '', self.input_file_content
|
||||
])
|
||||
|
||||
form.append('--' + self.boundary + '--')
|
||||
form.append('')
|
||||
|
||||
return self._parse(form)
|
||||
|
||||
@staticmethod
|
||||
def _parse(form):
|
||||
if sys.version_info > (3,):
|
||||
# on Python 3 form needs to be byte encoded
|
||||
encoded_form = []
|
||||
for item in form:
|
||||
try:
|
||||
encoded_form.append(item.encode())
|
||||
except AttributeError:
|
||||
encoded_form.append(item)
|
||||
|
||||
return b'\r\n'.join(encoded_form)
|
||||
return '\r\n'.join(form)
|
||||
def field_tuple(self):
|
||||
return self.filename, self.input_file_content, self.mimetype
|
||||
|
||||
@staticmethod
|
||||
def is_image(stream):
|
||||
@@ -158,22 +100,9 @@ class InputFile(object):
|
||||
raise TelegramError('Could not parse file content')
|
||||
|
||||
@staticmethod
|
||||
def is_inputfile(data):
|
||||
"""Check if the request is a file request.
|
||||
def is_file(obj):
|
||||
return hasattr(obj, 'read')
|
||||
|
||||
Args:
|
||||
data (Dict[:obj:`str`, :obj:`str`]): A dict of (str, str) key/value pairs.
|
||||
|
||||
Returns:
|
||||
:obj:`bool`
|
||||
|
||||
"""
|
||||
if data:
|
||||
file_type = [i for i in iter(data) if i in FILE_TYPES]
|
||||
|
||||
if file_type:
|
||||
file_content = data[file_type[0]]
|
||||
|
||||
return hasattr(file_content, 'read')
|
||||
|
||||
return False
|
||||
def to_dict(self):
|
||||
if self.attach:
|
||||
return 'attach://' + self.attach
|
||||
|
||||
@@ -0,0 +1,351 @@
|
||||
#!/usr/bin/env python
|
||||
#
|
||||
# A library that provides a Python interface to the Telegram Bot API
|
||||
# Copyright (C) 2015-2018
|
||||
# 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/].
|
||||
"""Base class for Telegram InputMedia Objects."""
|
||||
|
||||
from telegram import TelegramObject, InputFile, PhotoSize, Animation, Video, Audio, Document
|
||||
|
||||
|
||||
class InputMedia(TelegramObject):
|
||||
"""Base class for Telegram InputMedia Objects.
|
||||
|
||||
See :class:`telegram.InputMediaAnimation`, :class:`telegram.InputMediaAudio`,
|
||||
:class:`telegram.InputMediaDocument`, :class:`telegram.InputMediaPhoto` and
|
||||
:class:`telegram.InputMediaVideo` for detailed use.
|
||||
|
||||
"""
|
||||
pass
|
||||
|
||||
|
||||
class InputMediaAnimation(InputMedia):
|
||||
"""Represents an animation file (GIF or H.264/MPEG-4 AVC video without sound) to be sent.
|
||||
|
||||
Attributes:
|
||||
type (:obj:`str`): ``animation``.
|
||||
media (:obj:`str`): File to send. Pass a file_id to send a file that exists on the Telegram
|
||||
servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet.
|
||||
Lastly you can pass an existing :class:`telegram.Animation` object to send.
|
||||
thumb (`filelike object`): Optional. Thumbnail of the
|
||||
file sent. The thumbnail should be in JPEG format and less than 200 kB in size.
|
||||
A thumbnail's width and height should not exceed 90. Ignored if the file is not
|
||||
is passed as a string or file_id.
|
||||
caption (:obj:`str`): Optional. Caption of the animation to be sent, 0-200 characters.
|
||||
parse_mode (:obj:`str`): Optional. Send Markdown or HTML, if you want Telegram apps to show
|
||||
bold, italic, fixed-width text or inline URLs in the media caption. See the constants
|
||||
in :class:`telegram.ParseMode` for the available modes.
|
||||
width (:obj:`int`): Optional. Animation width.
|
||||
height (:obj:`int`): Optional. Animation height.
|
||||
duration (:obj:`int`): Optional. Animation duration.
|
||||
|
||||
|
||||
Args:
|
||||
media (:obj:`str`): File to send. Pass a file_id to send a file that exists on the Telegram
|
||||
servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet.
|
||||
Lastly you can pass an existing :class:`telegram.Animation` object to send.
|
||||
thumb (`filelike object`, optional): Thumbnail of the
|
||||
file sent. The thumbnail should be in JPEG format and less than 200 kB in size.
|
||||
A thumbnail's width and height should not exceed 90. Ignored if the file is not
|
||||
is passed as a string or file_id.
|
||||
caption (:obj:`str`, optional): Caption of the animation to be sent, 0-200 characters.
|
||||
parse_mode (:obj:`str`, optional): Send Markdown or HTML, if you want Telegram apps to show
|
||||
bold, italic, fixed-width text or inline URLs in the media caption. See the constants
|
||||
in :class:`telegram.ParseMode` for the available modes.
|
||||
width (:obj:`int`, optional): Animation width.
|
||||
height (:obj:`int`, optional): Animation height.
|
||||
duration (:obj:`int`, optional): Animation duration.
|
||||
|
||||
Note:
|
||||
When using a :class:`telegram.Animation` for the :attr:`media` attribute. It will take the
|
||||
width, height and duration from that video, unless otherwise specified with the optional
|
||||
arguments.
|
||||
"""
|
||||
|
||||
def __init__(self, media, thumb=None, caption=None, parse_mode=None, width=None, height=None,
|
||||
duration=None):
|
||||
self.type = 'animation'
|
||||
|
||||
if isinstance(media, Animation):
|
||||
self.media = media.file_id
|
||||
self.width = media.width
|
||||
self.height = media.height
|
||||
self.duration = media.duration
|
||||
elif InputFile.is_file(media):
|
||||
self.media = InputFile(media, attach=True)
|
||||
else:
|
||||
self.media = media
|
||||
|
||||
if thumb:
|
||||
self.thumb = thumb
|
||||
if InputFile.is_file(self.thumb):
|
||||
self.thumb = InputFile(self.thumb, attach=True)
|
||||
|
||||
if caption:
|
||||
self.caption = caption
|
||||
if parse_mode:
|
||||
self.parse_mode = parse_mode
|
||||
if width:
|
||||
self.width = width
|
||||
if height:
|
||||
self.height = height
|
||||
if duration:
|
||||
self.duration = duration
|
||||
|
||||
|
||||
class InputMediaPhoto(InputMedia):
|
||||
"""Represents a photo to be sent.
|
||||
|
||||
Attributes:
|
||||
type (:obj:`str`): ``photo``.
|
||||
media (:obj:`str`): File to send. Pass a file_id to send a file that exists on the
|
||||
Telegram servers (recommended), pass an HTTP URL for Telegram to get a file from the
|
||||
Internet. Lastly you can pass an existing :class:`telegram.PhotoSize` object to send.
|
||||
caption (:obj:`str`): Optional. Caption of the photo to be sent, 0-200 characters.
|
||||
parse_mode (:obj:`str`): Optional. Send Markdown or HTML, if you want Telegram apps to show
|
||||
bold, italic, fixed-width text or inline URLs in the media caption. See the constants
|
||||
in :class:`telegram.ParseMode` for the available modes.
|
||||
|
||||
Args:
|
||||
media (:obj:`str`): File to send. Pass a file_id to send a file that exists on the
|
||||
Telegram servers (recommended), pass an HTTP URL for Telegram to get a file from the
|
||||
Internet. Lastly you can pass an existing :class:`telegram.PhotoSize` object to send.
|
||||
caption (:obj:`str`, optional ): Caption of the photo to be sent, 0-200 characters.
|
||||
parse_mode (:obj:`str`, optional): Send Markdown or HTML, if you want Telegram apps to show
|
||||
bold, italic, fixed-width text or inline URLs in the media caption. See the constants
|
||||
in :class:`telegram.ParseMode` for the available modes.
|
||||
"""
|
||||
|
||||
def __init__(self, media, caption=None, parse_mode=None):
|
||||
self.type = 'photo'
|
||||
|
||||
if isinstance(media, PhotoSize):
|
||||
self.media = media.file_id
|
||||
elif InputFile.is_file(media):
|
||||
self.media = InputFile(media, attach=True)
|
||||
else:
|
||||
self.media = media
|
||||
|
||||
if caption:
|
||||
self.caption = caption
|
||||
if parse_mode:
|
||||
self.parse_mode = parse_mode
|
||||
|
||||
|
||||
class InputMediaVideo(InputMedia):
|
||||
"""Represents a video to be sent.
|
||||
|
||||
Attributes:
|
||||
type (:obj:`str`): ``video``.
|
||||
media (:obj:`str`): File to send. Pass a file_id to send a file that exists on the Telegram
|
||||
servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet.
|
||||
Lastly you can pass an existing :class:`telegram.Video` object to send.
|
||||
caption (:obj:`str`): Optional. Caption of the video to be sent, 0-200 characters.
|
||||
parse_mode (:obj:`str`): Optional. Send Markdown or HTML, if you want Telegram apps to show
|
||||
bold, italic, fixed-width text or inline URLs in the media caption. See the constants
|
||||
in :class:`telegram.ParseMode` for the available modes.
|
||||
width (:obj:`int`): Optional. Video width.
|
||||
height (:obj:`int`): Optional. Video height.
|
||||
duration (:obj:`int`): Optional. Video duration.
|
||||
supports_streaming (:obj:`bool`): Optional. Pass True, if the uploaded video is suitable
|
||||
for streaming.
|
||||
thumb (`filelike object`): Optional. Thumbnail of the
|
||||
file sent. The thumbnail should be in JPEG format and less than 200 kB in size.
|
||||
A thumbnail's width and height should not exceed 90. Ignored if the file is not
|
||||
is passed as a string or file_id.
|
||||
|
||||
Args:
|
||||
media (:obj:`str`): File to send. Pass a file_id to send a file that exists on the Telegram
|
||||
servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet.
|
||||
Lastly you can pass an existing :class:`telegram.Video` object to send.
|
||||
caption (:obj:`str`, optional): Caption of the video to be sent, 0-200 characters.
|
||||
parse_mode (:obj:`str`, optional): Send Markdown or HTML, if you want Telegram apps to show
|
||||
bold, italic, fixed-width text or inline URLs in the media caption. See the constants
|
||||
in :class:`telegram.ParseMode` for the available modes.
|
||||
width (:obj:`int`, optional): Video width.
|
||||
height (:obj:`int`, optional): Video height.
|
||||
duration (:obj:`int`, optional): Video duration.
|
||||
supports_streaming (:obj:`bool`, optional): Pass True, if the uploaded video is suitable
|
||||
for streaming.
|
||||
thumb (`filelike object`, optional): Thumbnail of the
|
||||
file sent. The thumbnail should be in JPEG format and less than 200 kB in size.
|
||||
A thumbnail's width and height should not exceed 90. Ignored if the file is not
|
||||
is passed as a string or file_id.
|
||||
|
||||
Note:
|
||||
When using a :class:`telegram.Video` for the :attr:`media` attribute. It will take the
|
||||
width, height and duration from that video, unless otherwise specified with the optional
|
||||
arguments.
|
||||
"""
|
||||
|
||||
def __init__(self, media, caption=None, width=None, height=None, duration=None,
|
||||
supports_streaming=None, parse_mode=None, thumb=None):
|
||||
self.type = 'video'
|
||||
|
||||
if isinstance(media, Video):
|
||||
self.media = media.file_id
|
||||
self.width = media.width
|
||||
self.height = media.height
|
||||
self.duration = media.duration
|
||||
elif InputFile.is_file(media):
|
||||
self.media = InputFile(media, attach=True)
|
||||
else:
|
||||
self.media = media
|
||||
|
||||
if thumb:
|
||||
self.thumb = thumb
|
||||
if InputFile.is_file(self.thumb):
|
||||
self.thumb = InputFile(self.thumb, attach=True)
|
||||
|
||||
if caption:
|
||||
self.caption = caption
|
||||
if parse_mode:
|
||||
self.parse_mode = parse_mode
|
||||
if width:
|
||||
self.width = width
|
||||
if height:
|
||||
self.height = height
|
||||
if duration:
|
||||
self.duration = duration
|
||||
if supports_streaming:
|
||||
self.supports_streaming = supports_streaming
|
||||
|
||||
|
||||
class InputMediaAudio(InputMedia):
|
||||
"""Represents an audio file to be treated as music to be sent.
|
||||
|
||||
Attributes:
|
||||
type (:obj:`str`): ``audio``.
|
||||
media (:obj:`str`): File to send. Pass a file_id to send a file that exists on the Telegram
|
||||
servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet.
|
||||
Lastly you can pass an existing :class:`telegram.Audio` object to send.
|
||||
caption (:obj:`str`): Optional. Caption of the audio to be sent, 0-200 characters.
|
||||
parse_mode (:obj:`str`): Optional. Send Markdown or HTML, if you want Telegram apps to show
|
||||
bold, italic, fixed-width text or inline URLs in the media caption. See the constants
|
||||
in :class:`telegram.ParseMode` for the available modes.
|
||||
duration (:obj:`int`): Duration of the audio in seconds.
|
||||
performer (:obj:`str`): Optional. Performer of the audio as defined by sender or by audio
|
||||
tags.
|
||||
title (:obj:`str`): Optional. Title of the audio as defined by sender or by audio tags.
|
||||
thumb (`filelike object`): Optional. Thumbnail of the
|
||||
file sent. The thumbnail should be in JPEG format and less than 200 kB in size.
|
||||
A thumbnail's width and height should not exceed 90. Ignored if the file is not
|
||||
is passed as a string or file_id.
|
||||
|
||||
Args:
|
||||
media (:obj:`str`): File to send. Pass a file_id to send a file that exists on the Telegram
|
||||
servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet.
|
||||
Lastly you can pass an existing :class:`telegram.Document` object to send.
|
||||
caption (:obj:`str`, optional): Caption of the audio to be sent, 0-200 characters.
|
||||
parse_mode (:obj:`str`, optional): Send Markdown or HTML, if you want Telegram apps to show
|
||||
bold, italic, fixed-width text or inline URLs in the media caption. See the constants
|
||||
in :class:`telegram.ParseMode` for the available modes.
|
||||
duration (:obj:`int`): Duration of the audio in seconds as defined by sender.
|
||||
performer (:obj:`str`, optional): Performer of the audio as defined by sender or by audio
|
||||
tags.
|
||||
title (:obj:`str`, optional): Title of the audio as defined by sender or by audio tags.
|
||||
thumb (`filelike object`, optional): Thumbnail of the
|
||||
file sent. The thumbnail should be in JPEG format and less than 200 kB in size.
|
||||
A thumbnail's width and height should not exceed 90. Ignored if the file is not
|
||||
is passed as a string or file_id.
|
||||
|
||||
Note:
|
||||
When using a :class:`telegram.Audio` for the :attr:`media` attribute. It will take the
|
||||
duration, performer and title from that video, unless otherwise specified with the
|
||||
optional arguments.
|
||||
"""
|
||||
|
||||
def __init__(self, media, thumb=None, caption=None, parse_mode=None,
|
||||
duration=None, performer=None, title=None):
|
||||
self.type = 'audio'
|
||||
|
||||
if isinstance(media, Audio):
|
||||
self.media = media.file_id
|
||||
self.duration = media.duration
|
||||
self.performer = media.performer
|
||||
self.title = media.title
|
||||
elif InputFile.is_file(media):
|
||||
self.media = InputFile(media, attach=True)
|
||||
else:
|
||||
self.media = media
|
||||
|
||||
if thumb:
|
||||
self.thumb = thumb
|
||||
if InputFile.is_file(self.thumb):
|
||||
self.thumb = InputFile(self.thumb, attach=True)
|
||||
|
||||
if caption:
|
||||
self.caption = caption
|
||||
if parse_mode:
|
||||
self.parse_mode = parse_mode
|
||||
if duration:
|
||||
self.duration = duration
|
||||
if performer:
|
||||
self.performer = performer
|
||||
if title:
|
||||
self.title = title
|
||||
|
||||
|
||||
class InputMediaDocument(InputMedia):
|
||||
"""Represents a general file to be sent.
|
||||
|
||||
Attributes:
|
||||
type (:obj:`str`): ``document``.
|
||||
media (:obj:`str`): File to send. Pass a file_id to send a file that exists on the Telegram
|
||||
servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet.
|
||||
Lastly you can pass an existing :class:`telegram.Document` object to send.
|
||||
caption (:obj:`str`): Optional. Caption of the document to be sent, 0-200 characters.
|
||||
parse_mode (:obj:`str`): Optional. Send Markdown or HTML, if you want Telegram apps to show
|
||||
bold, italic, fixed-width text or inline URLs in the media caption. See the constants
|
||||
in :class:`telegram.ParseMode` for the available modes.
|
||||
thumb (`filelike object`): Optional. Thumbnail of the
|
||||
file sent. The thumbnail should be in JPEG format and less than 200 kB in size.
|
||||
A thumbnail's width and height should not exceed 90. Ignored if the file is not
|
||||
is passed as a string or file_id.
|
||||
|
||||
Args:
|
||||
media (:obj:`str`): File to send. Pass a file_id to send a file that exists on the Telegram
|
||||
servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet.
|
||||
Lastly you can pass an existing :class:`telegram.Document` object to send.
|
||||
caption (:obj:`str`, optional): Caption of the document to be sent, 0-200 characters.
|
||||
parse_mode (:obj:`str`, optional): Send Markdown or HTML, if you want Telegram apps to show
|
||||
bold, italic, fixed-width text or inline URLs in the media caption. See the constants
|
||||
in :class:`telegram.ParseMode` for the available modes.
|
||||
thumb (`filelike object`, optional): Thumbnail of the
|
||||
file sent. The thumbnail should be in JPEG format and less than 200 kB in size.
|
||||
A thumbnail's width and height should not exceed 90. Ignored if the file is not
|
||||
is passed as a string or file_id.
|
||||
"""
|
||||
|
||||
def __init__(self, media, thumb=None, caption=None, parse_mode=None):
|
||||
self.type = 'document'
|
||||
|
||||
if isinstance(media, Document):
|
||||
self.media = media.file_id
|
||||
elif InputFile.is_file(media):
|
||||
self.media = InputFile(media, attach=True)
|
||||
else:
|
||||
self.media = media
|
||||
|
||||
if thumb:
|
||||
self.thumb = thumb
|
||||
if InputFile.is_file(self.thumb):
|
||||
self.thumb = InputFile(self.thumb, attach=True)
|
||||
|
||||
if caption:
|
||||
self.caption = caption
|
||||
if parse_mode:
|
||||
self.parse_mode = parse_mode
|
||||
@@ -1,7 +1,7 @@
|
||||
#!/usr/bin/env python
|
||||
#
|
||||
# A library that provides a Python interface to the Telegram Bot API
|
||||
# Copyright (C) 2015-2017
|
||||
# Copyright (C) 2015-2018
|
||||
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#!/usr/bin/env python
|
||||
#
|
||||
# A library that provides a Python interface to the Telegram Bot API
|
||||
# Copyright (C) 2015-2017
|
||||
# Copyright (C) 2015-2018
|
||||
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
@@ -29,23 +29,26 @@ class PhotoSize(TelegramObject):
|
||||
width (:obj:`int`): Photo width.
|
||||
height (:obj:`int`): Photo height.
|
||||
file_size (:obj:`int`): Optional. File size.
|
||||
bot (:class:`telegram.Bot`): Optional. The Bot to use for instance methods.
|
||||
|
||||
Args:
|
||||
file_id (:obj:`str`): Unique identifier for this file.
|
||||
width (:obj:`int`): Photo width.
|
||||
height (:obj:`int`): Photo height.
|
||||
file_size (:obj:`int`, optional): File size.
|
||||
bot (:class:`telegram.Bot`, optional): The Bot to use for instance methods.
|
||||
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
|
||||
|
||||
"""
|
||||
|
||||
def __init__(self, file_id, width, height, file_size=None, **kwargs):
|
||||
def __init__(self, file_id, width, height, file_size=None, bot=None, **kwargs):
|
||||
# Required
|
||||
self.file_id = str(file_id)
|
||||
self.width = int(width)
|
||||
self.height = int(height)
|
||||
# Optionals
|
||||
self.file_size = file_size
|
||||
self.bot = bot
|
||||
|
||||
self._id_attrs = (self.file_id,)
|
||||
|
||||
@@ -54,7 +57,7 @@ class PhotoSize(TelegramObject):
|
||||
if not data:
|
||||
return None
|
||||
|
||||
return cls(**data)
|
||||
return cls(bot=bot, **data)
|
||||
|
||||
@classmethod
|
||||
def de_list(cls, data, bot):
|
||||
@@ -66,3 +69,21 @@ class PhotoSize(TelegramObject):
|
||||
photos.append(cls.de_json(photo, bot))
|
||||
|
||||
return photos
|
||||
|
||||
def get_file(self, timeout=None, **kwargs):
|
||||
"""Convenience wrapper over :attr:`telegram.Bot.get_file`
|
||||
|
||||
Args:
|
||||
timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as
|
||||
the read timeout from the server (instead of the one specified during creation of
|
||||
the connection pool).
|
||||
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
|
||||
|
||||
Returns:
|
||||
:class:`telegram.File`
|
||||
|
||||
Raises:
|
||||
:class:`telegram.TelegramError`
|
||||
|
||||
"""
|
||||
return self.bot.get_file(self.file_id, timeout=timeout, **kwargs)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#!/usr/bin/env python
|
||||
#
|
||||
# A library that provides a Python interface to the Telegram Bot API
|
||||
# Copyright (C) 2015-2017
|
||||
# Copyright (C) 2015-2018
|
||||
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
@@ -35,6 +35,7 @@ class Sticker(TelegramObject):
|
||||
mask_position (:class:`telegram.MaskPosition`): Optional. For mask stickers, the position
|
||||
where the mask should be placed.
|
||||
file_size (:obj:`int`): Optional. File size.
|
||||
bot (:class:`telegram.Bot`): Optional. The Bot to use for instance methods.
|
||||
|
||||
Args:
|
||||
file_id (:obj:`str`): Unique identifier for this file.
|
||||
@@ -48,7 +49,8 @@ class Sticker(TelegramObject):
|
||||
mask_position (:class:`telegram.MaskPosition`, optional): For mask stickers, the
|
||||
position where the mask should be placed.
|
||||
file_size (:obj:`int`, optional): File size.
|
||||
**kwargs (obj:`dict`): Arbitrary keyword arguments.
|
||||
**kwargs (obj:`dict`): Arbitrary keyword arguments.7
|
||||
bot (:class:`telegram.Bot`, optional): The Bot to use for instance methods.
|
||||
|
||||
"""
|
||||
|
||||
@@ -61,6 +63,7 @@ class Sticker(TelegramObject):
|
||||
file_size=None,
|
||||
set_name=None,
|
||||
mask_position=None,
|
||||
bot=None,
|
||||
**kwargs):
|
||||
# Required
|
||||
self.file_id = str(file_id)
|
||||
@@ -72,6 +75,7 @@ class Sticker(TelegramObject):
|
||||
self.file_size = file_size
|
||||
self.set_name = set_name
|
||||
self.mask_position = mask_position
|
||||
self.bot = bot
|
||||
|
||||
self._id_attrs = (self.file_id,)
|
||||
|
||||
@@ -85,7 +89,7 @@ class Sticker(TelegramObject):
|
||||
data['thumb'] = PhotoSize.de_json(data.get('thumb'), bot)
|
||||
data['mask_position'] = MaskPosition.de_json(data.get('mask_position'), bot)
|
||||
|
||||
return cls(**data)
|
||||
return cls(bot=bot, **data)
|
||||
|
||||
@classmethod
|
||||
def de_list(cls, data, bot):
|
||||
@@ -94,6 +98,24 @@ class Sticker(TelegramObject):
|
||||
|
||||
return [cls.de_json(d, bot) for d in data]
|
||||
|
||||
def get_file(self, timeout=None, **kwargs):
|
||||
"""Convenience wrapper over :attr:`telegram.Bot.get_file`
|
||||
|
||||
Args:
|
||||
timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as
|
||||
the read timeout from the server (instead of the one specified during creation of
|
||||
the connection pool).
|
||||
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
|
||||
|
||||
Returns:
|
||||
:class:`telegram.File`
|
||||
|
||||
Raises:
|
||||
:class:`telegram.TelegramError`
|
||||
|
||||
"""
|
||||
return self.bot.get_file(self.file_id, timeout=timeout, **kwargs)
|
||||
|
||||
|
||||
class StickerSet(TelegramObject):
|
||||
"""This object represents a sticker set.
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user