Compare commits

...

112 Commits

Author SHA1 Message Date
Jannes Höke da4ed9b316 🚑 Bump version to v5.3.1
#579
2017-04-25 16:54:05 +02:00
Jannes Höke a5660234e5 🚑 enforce urllib3==1.20
#579
2017-04-25 16:50:11 +02:00
Jannes Höke 71530f404d Bump version to v5.3.0 2016-12-11 23:51:51 +01:00
Jannes Höke 0cd7ecab50 fix test_filters_reply 2016-12-11 23:16:10 +01:00
Jeong Arm c5f9e53d44 Add "reply" filter (#465)
* Add "reply" filter

This filter will filter messages that reply to other's message.

* Add test for "reply" filter

* Add "Kjwon15" to AUTHORS.rst
2016-12-11 22:45:51 +01:00
Noam Meltzer acf1541395 Botapi2.3 (#471)
* New fields channel_post and edited_channel_post for Update

refs #468

* setGameScore() changes

 - Changed behaviour: messages with high scores will be update with new
   high scores by default. (documentation fix)
 - Use (new) disable_edit_message in setGameScore to disable the above new
   behaviour.
 - The edit_message parameter from setGameScore is no longer in use. For
   backward compatibility, it will be taken into account for a while,
   unless disable_edit_message is passed explicitly.

refs #468

* New field forward_from_message_id for Message.

refs #468

* New parameter cache_time for answerCallbackQuery

refs #468

* replykeyboardhide renamed to replykeyboardremove

refs #468

* Unitests for updated setGameScore semantics

refs #468

* Backward compatibility for ReplyKeyboardHide

refs #468

* Fix docstrings of wrapper methods in Message

* Unitest new field forward_from_message_id of Message

refs #468

* Fix testMaxCaptionLength

Telegram servers changed their behaviour - now they truncate a long
caption instead of returning an error.

* MessageHandler: Added support for channel posts

* Fix flake8 complaints in a manner which yapf will like it too.

* fix rst markup
2016-12-11 22:44:52 +01:00
Jacob Bom 906a1b8d7d message.edit_reply_markup now correctly edits reply_markup (#473) 2016-12-08 13:23:51 +01:00
lisitsky a2fddbe85c Fix telegram API change, returning '404 Not found' (#461)
* Fix telegram API change, returning '404 Not found' with raising own TelegramError rather native exception

* Change exception to InvalidToken in test and request util

* Added myself to AUTHORS. Thx for appreciation :)
2016-11-09 14:36:42 +01:00
Wesley Gahr 68e87db909 Job queue time units (#452)
* Adding timeunit and day support to the jobqueue

* Adding tests

* Changed the file permission back to 644.

* Changed AssertEqual argument order to (actual, expectd).

* Removed the TimeUnit enum and unit param, instead use datetime.time for interval.

* Removing the TimeUnits enum and unit param in favour of optionally using a datetime.time as the interval.

* Removing the TimeUnits enumeration, forgot the remove it in the last one.

* Removed some old docstrings refering to the TimeUnits enum.

* Removed the old TimeUnits import.

* Adding some error handling for the 'days' argument (only a 'tuple' with 'Days')

* Writing the error message directly in the exception.

* Moving a debug statement wrongfully saying a job would be running on days it wouldn't.

* Writing error messages directly in the exceptions instead of making an extra variable.

* Replacing datetime.time in favour of datetime.timedelta because of the get_seconds() method.

* Adding error handling for the method .

* Splitting the tests up in multiple ones, no float test because I haven't found a reliable way to test it.

* Excluding .exrc file.

* Removing \ at EOF of ValueError.

* Replacing Enums with plain new-style classes.

* Using numbers.number to check for ints/floats instead of seperate int/float checks.

* Fixing typo, number -> Number.

* Changed lower_case Days attributes to UPPER_CASE.

* Different formatting for Days class, removed the get_days function in favour of a tuple.

* Removed redundant function get_days.

* Edited the docstring for next_t to also take datetime.timedelta.

* Removed for-loop in favour of any().

* Changed docstring for interval.

* Removed debug print.

* Changing some docstrings.

* Changing some docstrings (again).
2016-11-08 23:39:25 +01:00
Blue a7bfb0c3a1 hide inline keyboard in conversationbot example (#439) 2016-11-08 22:14:11 +01:00
Jannes Höke e76ee6bb57 [ci skip] docs: add even more missing classes (wtf) 2016-11-01 09:37:03 +01:00
Jannes Höke 65061f8a99 [ci skip] docs: add all missing classes 2016-11-01 09:01:36 +01:00
Jannes Höke dabbbcafcb [ci skip] docs: remove superfluous text in index.rst 2016-11-01 08:15:51 +01:00
Jannes Höke 1eb4b40dbf [ci skip] docs: add logo to html and pdf builds 2016-11-01 08:09:25 +01:00
Jannes Höke 7167936692 [ci skip] pdf docs: use a4paper, update motto 2016-11-01 07:54:04 +01:00
Jannes Höke aa3ca38837 Sphinx restructuring: Now builds PDF and better HTML docs (#449)
* update sphinx source files to properly build latexpdf and improve html build

* fix docstrings and sphinx sources to get rid of warnings

* add telegram.contrib.rst
2016-11-01 06:53:51 +01:00
Jannes Höke b22c3cc5c0 [ci skip] add state diagrams for conversation handler examples 2016-10-28 08:26:02 +02:00
Jannes Höke 2786252a51 Bump version to v5.2.0 2016-10-25 20:10:36 +02:00
Jannes Höke 3f30f74024 update examples to use bitwise filters 2016-10-25 19:51:56 +02:00
Jannes Höke 79fc3be9cd Update README.md 2016-10-25 19:37:19 +02:00
Jannes Höke 71c73bdc74 Update README.md 2016-10-25 19:36:57 +02:00
neutronnnate 761547e71d Issue 422: Fixed start_polling with clean=True can cause 'Too Many Requests' error from Telegram. (#437) 2016-10-25 19:30:05 +02:00
Jannes Höke 10bdf8212c Add pass_user_data and pass_chat_data to Handler (#436)
* initial commit for user_data

* add chat_data and use defaultdict

* fix chat_data copy-paste error

* add test for user_data and chat_data

* fix case where chat is None

* remove braces from import line
2016-10-25 19:28:34 +02:00
Kristofer Kirss 45936c9982 Remove deprecated argument from Updater docstring (#444)
Argument (job_queue_tick_interval) was removed with commit 3aedd78 but the docstring in updater.py wasn't.
2016-10-23 00:31:44 +03:00
Jannes Höke fae1896232 Switch to readthedocs (#443)
* replace pythonhosted by readthedocs

* fix rtd links in examples/README
2016-10-19 18:00:33 +02:00
Jacob Bom 2518ddac22 Update comtributing guide with explicit kwargs 2016-10-19 13:07:20 +02:00
Jacob Bom 61fe438a8b Merge pull request #431 from python-telegram-bot/october3
Add api changes as of october 3
2016-10-19 12:59:00 +02:00
Jacob Bom 960862ccb1 Merge branch 'master' into october3
# Conflicts:
#	telegram/bot.py
#	telegram/callbackquery.py
#	telegram/chat.py
#	telegram/ext/messagehandler.py
#	telegram/inlinekeyboardbutton.py
#	telegram/inlinequeryresultcachedaudio.py
#	telegram/message.py
#	tests/test_filters.py
2016-10-19 12:35:50 +02:00
Jacob Bom 4e5f4582dd Merge pull request #411 from python-telegram-bot/bitwise-filters
Make filters and/or-able using bitwise operators.
2016-10-19 11:40:35 +02:00
Jacob Bom 225bc24c2a Merge pull request #442 from python-telegram-bot/explicit-kwargs
Use explicit kwargs and change/add a bunch of documentation.
2016-10-19 11:36:19 +02:00
Noam Meltzer a5f9aa3171 more documentation 2016-10-17 23:44:40 +03:00
Noam Meltzer 78088f4f6a Fix grammer: 'a object' -> 'an object' 2016-10-17 01:22:40 +03:00
Noam Meltzer 59fa717023 Documentation improvements + small style fixes 2016-10-17 01:11:20 +03:00
Noam Meltzer 31cab0d1b4 editMessageCaption & editMessageReplyMarkup: more validation on input 2016-10-17 01:09:44 +03:00
Jacob Bom 7fafaa1ea3 Update support date in readme. 2016-10-16 16:54:08 +02:00
Jacob Bom e367b8519d Use explicit kwargs for all class inits in pure api.
While not stickily necessary for most classes (since user isn't directly creating them) it still unifies our approach.
However for some like ReplyKeyboardHide where users are making the classes themselves it should improve IDE autocomplete support.
2016-10-16 16:24:13 +02:00
Jacob Bom b610316667 Use explicit kwargs for all bot methods.
This improves support for many IDEs' autocompletion.
2016-10-16 15:54:48 +02:00
Jacob Bom 39832d2f6b __str__ behaves differntly on py2 apparently. 2016-10-16 13:19:42 +02:00
Jacob Bom 5408c23e33 assertRegexMatches still exists for now. Use it. 2016-10-16 12:48:45 +02:00
Jacob Bom 62dd3a33e6 Better kwargs defaults. 2016-10-16 12:41:12 +02:00
Jacob Bom 3754cdafb2 send_game has differnt kwargs. 2016-10-16 12:41:12 +02:00
Jacob Bom 305ff93018 set_game_score might return True 2016-10-16 12:41:12 +02:00
Jacob Bom 29e0cc64e9 Fix py2 compat 2016-10-15 23:29:46 +02:00
Jacob Bom a5671a8fb1 Merge pull request #423 from python-telegram-bot/edit-class-method
Add edit_* class methods
2016-10-15 23:03:43 +02:00
Jacob Bom f99b2f8f3b Inprove coverage 2016-10-15 22:59:41 +02:00
Jacob Bom c626044a30 Add "all" filter
Since and empty list cannot (in the future, currently only deprecated) be used.
2016-10-15 22:58:55 +02:00
Noam Meltzer a68cf8d464 Respect RetryAfter with polling Updater 2016-10-15 23:39:50 +03:00
Jacob Bom de96cc87ea Only build master branch and PRs on travis. Yapf only on py3.5. 2016-10-14 11:24:00 +02:00
Jacob Bom ca5e3146c6 Fix docstring according to Jannes' commentns. 2016-10-14 10:32:12 +02:00
Noam Meltzer 53a574bbbb Improve unitests coverage 2016-10-13 22:52:53 +03:00
Noam Meltzer 5b8efe0c14 upgrade yapf to ver 0.12.2 2016-10-12 23:56:57 +03:00
Noam Meltzer d07a1c3f67 yapf: use our own mirror of yapf & update to version 0.12.2 2016-10-12 23:51:46 +03:00
Noam Meltzer 32a78722ae yapf fixes 2016-10-12 23:33:52 +03:00
Jacob Bom 04feeeff55 Update test cases
Needs proper animation file_id and size.
Also assertEqual can't test if two objects have the same data, so we just check the file_id instead.
2016-10-12 20:30:34 +02:00
Jannes Höke a1495956aa temporary fix for documentation builds on readthedocs 2016-10-10 12:51:12 +02:00
Patrick Hofmann 8dc10fc7b2 fixes broken test cases with PhotoSize, Game and Animation classes (#435)
* fixes broken test with PhotoSize, Game and Animation

However:
testSendGame and test_set_game_score both produces *BadRequest: u'Wrong file identifier/HTTP URL specified'*.

* fixes test_set_game_score

* adds to_dict method to Game to prevent extra collection type checks in base.TelegramObject
2016-10-10 11:44:40 +02:00
Jacob Bom 7ad92dcc65 Add test for set_game_score 2016-10-09 12:39:05 +02:00
Jacob Bom d1ddfaddf0 Add tests for Game, Animation and sendGame.
Still need setGameScore (I'm thinking we can set it to the ever increasing
envvar 'TRAVIS_BUILD_NUMBER') and getGameHighScores.
The tests currently don't work... Since I don't really understand how
PhotoSize works... Please halp :P
2016-10-07 23:57:10 +02:00
Jacob Bom b7c7612b3f Add game filter 2016-10-07 22:37:29 +02:00
Jacob Bom ade89772f4 Fix tests
Data is an optional kwargs in CallbackQuery according to Telegram
2016-10-07 22:32:54 +02:00
Jacob Bom 67b98e3190 Merge pull request #433 from PH89/october3
small fix for game related parts
2016-10-07 22:25:52 +02:00
Patrick Hofmann e672625a41 add myself to AUTHORS.rst 2016-10-06 18:17:42 +02:00
Patrick Hofmann 8cab735342 small fix for game related parts
* bot.py fix copy paste error in url
* callbackquery.py make data field optional
* message.py introduce optional game field
2016-10-06 17:52:53 +02:00
Noam Meltzer bfb4c63d60 add unitest for getWebhookInfo 2016-10-06 00:11:28 +03:00
Noam Meltzer 01a5a1c5b3 small documentation fix 2016-10-05 23:22:55 +03:00
Noam Meltzer 1db1b76a7c fix test_video unitest 2016-10-05 23:19:17 +03:00
Jacob Bom 976f34082f Add possibly good-enough test for all_members_are_admin
Should be good enough... If we /really/ wanted to we could get two different chats from telegram and check them, but it really shouldn't be necessary.
2016-10-05 17:55:00 +02:00
Jacob Bom 6b7788570c Add tests for captions in audio and voice 2016-10-05 17:50:48 +02:00
Noam Meltzer 1f9d3163dd Game: use explicit keyword args + added docmentation 2016-10-04 02:17:12 +03:00
Noam Meltzer 837e9d2964 Animation: use explicit keyword args + added documentation 2016-10-04 02:16:33 +03:00
Noam Meltzer fab97df58a GameHighScore: added attributes documentation 2016-10-04 02:06:22 +03:00
Noam Meltzer d70fc48e94 getGameHighScores(): added documentation + fixed copy-paste errors 2016-10-04 01:57:19 +03:00
Noam Meltzer 36192912c2 setGameScore: fixes
- fix copy/paste errors
 - return Message object
2016-10-04 01:56:05 +03:00
Noam Meltzer 34748ec228 callbackgame: small documentation fix 2016-10-04 01:50:34 +03:00
Noam Meltzer d5567cd9cd sendGame(): mall fixes 2016-10-04 01:37:44 +03:00
Noam Meltzer 2463b4b9c8 New exception: RetryAfter
Also, small fix to the description text of ChatMigrated
2016-10-04 01:27:45 +03:00
Noam Meltzer 7cf5009517 small documentation fixes 2016-10-04 01:10:30 +03:00
Noam Meltzer 9b74625d4a answerCallbackQuery: fix copy/paste: show_alert -> url 2016-10-04 00:55:29 +03:00
Noam Meltzer 4180c069b3 InputFile: use self instead of explicit class name 2016-10-04 00:25:32 +03:00
Noam Meltzer 3a0f219783 inputfile: define the file types as constant and use iterator 2016-10-04 00:25:05 +03:00
Noam Meltzer 3c889655c1 Allow http url as a file_id
N.B. test_send_video_mp4_file_url() is still failing, probably because
of telegram servers bug. Will contact telegram bot support about that.
2016-10-04 00:20:17 +03:00
Jacob Bom c2b8c4bf95 Fix regexGroupHandlerCallbackQuery test 2016-10-03 21:29:30 +02:00
Jacob Bom 8234321a20 Fix tests for Inline Voice Queries 2016-10-03 21:28:35 +02:00
Jacob Bom 5e2d96b47d Make tests actually run at all 2016-10-03 21:07:41 +02:00
Jacob Bom 551f6c556c Add game parameters in various places
Also chat_instance in CallbackQuery which will break a lot of tests probably
2016-10-03 21:01:38 +02:00
Jacob Bom ae17eb3272 Add InlineQueryResultGame 2016-10-03 20:55:21 +02:00
Jacob Bom 358dd795c7 Add the rest of game_ methods to bot. 2016-10-03 20:43:02 +02:00
Jacob Bom 151a441af7 Add send_game 2016-10-03 20:40:17 +02:00
Noam Meltzer 1f67623615 Fix import order 2016-10-03 21:34:08 +03:00
Noam Meltzer 8737b5de63 fix syntax error by some weird char 2016-10-03 21:17:04 +03:00
Jacob Bom f3b8a3a5e9 Merge remote-tracking branch 'origin/october3' into october3 2016-10-03 20:10:14 +02:00
Jacob Bom 9e9309eb90 Add all new Game related classes
Missing docstrings for now though, wanna add everything first
2016-10-03 20:09:57 +02:00
Noam Meltzer e8a34d8eef cosmetic fixes and documentation for getWebhookInfo 2016-10-03 20:43:10 +03:00
Jacob Bom 34c62a633b Add url to answerCallbackQuery 2016-10-03 15:25:07 +02:00
Jacob Bom 868d9217bc Add WebhookInfo and getWebhookInfo
Still needs tests though
2016-10-03 15:16:43 +02:00
Jacob Bom f7ede4baea Add caption fields to voice and audio
Or at least the methods/classes for sending.
2016-10-03 15:05:49 +02:00
Jacob Bom c3e07b1056 Add switch_inline_query_current_chat 2016-10-03 14:52:58 +02:00
Jacob Bom 79bdfe4c5d Allow filters to be passed without list.
Also deprecates actually using a list.
2016-09-29 19:10:22 +02:00
Michael Elovskikh 46657afa95 Start additional threads only when necessary (#415)
* Start all additional threads only when necessary.

* Deprecate prevent_autostart in the c'tor of JobQueue.
2016-09-27 10:21:35 +03:00
Jacob Bom 79e065a730 Add __str__ and __repr__ to MergedFilter. 2016-09-25 16:31:06 +02:00
Jacob Bom 9928a1eefc Add test for edit_text 2016-09-25 16:11:19 +02:00
Jacob Bom 0e2c3666c0 Add edit_* family of methods to CallbackQuery.
Either edits the message attribute, or the message associated with the inline_message_id.
2016-09-25 16:03:06 +02:00
Jacob Bom a996e8873f Add edit_* family of methods to Message. 2016-09-25 15:50:58 +02:00
Jacob Bom 3244417f61 Add docs for filters. 2016-09-25 00:30:04 +02:00
Jacob Bom 61596400e1 __call__ should return the result
Also add tests with both & and |.
2016-09-24 18:56:54 +02:00
Jacob Bom be0f5bc519 Merge branch 'master' into bitwise-filters
# Conflicts:
#	telegram/ext/messagehandler.py
#	tests/test_filters.py
2016-09-24 18:30:58 +02:00
Jacob Bom 921fbae2f3 Merge branch 'master' into bitwise-filters 2016-09-24 18:21:06 +02:00
Jacob Bom 2161681131 Use filter method instead of __call__
__call__ is scary looking for users wanted to create their own filters.
Also allows us to put additional logic in __call__ if we want in the future.
2016-09-24 18:20:32 +02:00
Jannes Höke 9d0e0386d9 Link echobot2 example from master 2016-09-24 16:30:39 +02:00
Rahiel Kasim dc7a459511 README: formatting (adding a newline) 2016-09-24 15:46:02 +02:00
Jannes Höke be675f0118 update all examples to use instance methods (#421) 2016-09-24 15:32:22 +02:00
Jacob Bom 71e74da0a2 Make filters and/or-able using bitwise operators.
See associated PR for more info.
2016-09-14 19:29:15 +02:00
207 changed files with 3832 additions and 1466 deletions
+2 -2
View File
@@ -184,8 +184,8 @@ break the API classes. For example:
.. code-block:: python
# GOOD
def __init__(self, id, name, **kwargs):
self.last_name = kwargs.get('last_name', '')
def __init__(self, id, name, last_name='', **kwargs):
self.last_name = last_name
# BAD
def __init__(self, id, name, last_name=''):
+6
View File
@@ -68,3 +68,9 @@ telegram.mp4
telegram.ogg
telegram.png
telegram.webp
# original files from merges
*.orig
# Exclude .exrc file for Vim
.exrc
+2 -2
View File
@@ -1,5 +1,5 @@
- repo: git://github.com/pre-commit/mirrors-yapf
sha: v0.11.0
- repo: git://github.com/python-telegram-bot/mirrors-yapf
sha: v0.12.2
hooks:
- id: yapf
files: ^(telegram|tests)/.*\.py$
+4 -1
View File
@@ -6,6 +6,9 @@ python:
- "3.5"
- "pypy"
- "pypy3"
branches:
only:
- master
install:
- pip install coveralls
- pip install -r requirements.txt
@@ -13,6 +16,6 @@ install:
- if [[ $TRAVIS_PYTHON_VERSION != 'pypy'* ]]; then pip install ujson; fi
script:
- nosetests -v --with-flaky --no-flaky-report --with-coverage --cover-package=telegram/
- if [ $TRAVIS_PYTHON_VERSION != 3.3 ] && [ $TRAVIS_PYTHON_VERSION != pypy3 ]; then pre-commit run --all-files; fi
- if [[ $TRAVIS_PYTHON_VERSION == 3.5 ]]; then pre-commit run --all-files; fi
after_success:
coveralls
+5
View File
@@ -13,23 +13,28 @@ The following wonderful people contributed directly or indirectly to this projec
- `bimmlerd <https://github.com/bimmlerd>`_
- `Eli Gao <https://github.com/eligao>`_
- `ErgoZ Riftbit Vaper <https://github.com/ergoz>`_
- `Eugene Lisitsky <https://github.com/lisitsky>`_
- `franciscod <https://github.com/franciscod>`_
- `Jacob Bom <https://github.com/bomjacob>`_
- `JASON0916 <https://github.com/JASON0916>`_
- `jh0ker <https://github.com/jh0ker>`_
- `JRoot3D <https://github.com/JRoot3D>`_
- `jlmadurga <https://github.com/jlmadurga>`_
- `Kjwon15 <https://github.com/kjwon15>`_
- `Li-aung Yip <https://github.com/LiaungYip>`_
- `macrojames <https://github.com/macrojames>`_
- `Michael Elovskikh <https://github.com/wronglink>`_
- `naveenvhegde <https://github.com/naveenvhegde>`_
- `njittam <https://github.com/njittam>`_
- `Noam Meltzer <https://github.com/tsnoam>`_
- `Oleg Shlyazhko <https://github.com/ollmer>`_
- `overquota <https://github.com/overquota>`_
- `Patrick Hofmann <https://github.com/PH89>`_
- `Rahiel Kasim <https://github.com/rahiel>`_
- `Shelomentsev D <https://github.com/shelomentsevd>`_
- `sooyhwang <https://github.com/sooyhwang>`_
- `Valentijn <https://github.com/Faalentijn>`_
- `voider1 <https://github.com/voider1>`_
- `wjt <https://github.com/wjt>`_
Please add yourself here alphabetically when you submit your first pull request.
+27
View File
@@ -2,6 +2,33 @@
Changes
=======
**2017-04-17**
*Released 5.3.1*
- Hotfix release due to bug introduced by urllib3 version 1.21
**2016-12-11**
*Released 5.3*
- Implement API changes of November 21st (Bot API 2.3)
- ``JobQueue`` now supports ``datetime.timedelta`` in addition to seconds
- ``JobQueue`` now supports running jobs only on certain days
- New ``Filters.reply`` filter
- Bugfix for ``Message.edit_reply_markup``
- Other bugfixes
**2016-10-25**
*Released 5.2*
- Implement API changes of October 3rd (games update)
- Add ``Message.edit_*`` methods
- Filters for the ``MessageHandler`` can now be combined using bitwise operators (``& and |``)
- Add a way to save user- and chat-related data temporarily
- Other bugfixes and improvements
**2016-09-24**
*Released 5.1*
+6 -5
View File
@@ -16,7 +16,7 @@ We have made you a wrapper you can't refuse
:alt: Supported python versions
.. image:: https://img.shields.io/badge/docs-latest-af1a97.svg
:target: https://pythonhosted.org/python-telegram-bot/
:target: https://python-telegram-bot.readthedocs.io/
:alt: Documentation Status
.. image:: https://img.shields.io/pypi/l/python-telegram-bot.svg
@@ -37,7 +37,7 @@ We have made you a wrapper you can't refuse
.. image:: http://isitmaintained.com/badge/resolution/python-telegram-bot/python-telegram-bot.svg
:target: http://isitmaintained.com/project/python-telegram-bot/python-telegram-bot
:alt: Average time to resolve an issue
:alt: Median time to resolve an issue
.. image:: https://img.shields.io/badge/Telegram-Group-blue.svg
:target: https://telegram.me/pythontelegrambotgroup
@@ -84,7 +84,7 @@ make the development of bots easy and straightforward. These classes are contain
Telegram API support
====================
As of **28. May 2016**, all types and methods of the Telegram Bot API are supported.
As of **3. Oct 2016**, all types and methods of the Telegram Bot API are supported.
==========
Installing
@@ -103,6 +103,7 @@ Or you can install from source with:
$ git clone https://github.com/python-telegram-bot/python-telegram-bot
$ cd python-telegram-bot
$ python setup.py install
===============
Getting started
===============
@@ -115,7 +116,7 @@ Our Wiki contains a lot of resources to get you started with ``python-telegram-b
Other references:
- `Telegram API documentation <https://core.telegram.org/bots/api>`_
- `python-telegram-bot documentation <https://pythonhosted.org/python-telegram-bot/>`_
- `python-telegram-bot documentation <https://python-telegram-bot.readthedocs.io/>`_
-------------------
Learning by example
@@ -161,7 +162,7 @@ If you want DEBUG logs instead:
Documentation
=============
``python-telegram-bot``'s documentation lives at `pythonhosted.org <https://pythonhosted.org/python-telegram-bot/>`_.
``python-telegram-bot``'s documentation lives at `readthedocs.io <https://python-telegram-bot.readthedocs.io/>`_.
============
Getting help
+12 -9
View File
@@ -15,7 +15,7 @@
import sys
import os
import shlex
import telegram
# import telegram
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
@@ -59,9 +59,9 @@ author = u'Leandro Toledo'
# built documents.
#
# The short X.Y version.
version = telegram.__version__[:3]
version = '5.3' # telegram.__version__[:3]
# The full version, including alpha/beta/rc tags.
release = telegram.__version__
release = '5.3.1' # telegram.__version__
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
@@ -131,7 +131,7 @@ html_theme = 'sphinx_rtd_theme'
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
html_logo = 'ptb-logo-orange.png'
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
@@ -209,14 +209,17 @@ htmlhelp_basename = 'PythonTelegramBotdoc'
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
'papersize': 'a4paper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
'preamble': r'''\setcounter{tocdepth}{2}
\usepackage{enumitem}
\setlistdepth{99}''',
# Latex figure (float) alignment
#'figure_align': 'htbp',
@@ -227,12 +230,12 @@ latex_elements = {
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, 'PythonTelegramBot.tex', u'Python Telegram Bot Documentation',
u'Leandro Toledo', 'manual'),
author, 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
latex_logo = 'ptb-logo_1024.png'
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
@@ -271,7 +274,7 @@ man_pages = [
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'PythonTelegramBot', u'Python Telegram Bot Documentation',
author, 'PythonTelegramBot', 'Not just a Python wrapper around the Telegram Bot API',
author, 'PythonTelegramBot', "We have made you a wrapper you can't refuse",
'Miscellaneous'),
]
+1 -5
View File
@@ -6,12 +6,8 @@
Welcome to Python Telegram Bot's documentation!
===============================================
Contents:
telegram
.. toctree::
:maxdepth: 2
telegram
Indices and tables
-7
View File
@@ -1,7 +0,0 @@
telegram
========
.. toctree::
:maxdepth: 4
telegram
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 74 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 71 KiB

+7
View File
@@ -0,0 +1,7 @@
telegram.animation module
=========================
.. automodule:: telegram.animation
:members:
:undoc-members:
:show-inheritance:
+7
View File
@@ -0,0 +1,7 @@
telegram.callbackgame module
============================
.. automodule:: telegram.callbackgame
:members:
:undoc-members:
:show-inheritance:
+7
View File
@@ -0,0 +1,7 @@
telegram.callbackquery module
=============================
.. automodule:: telegram.callbackquery
:members:
:undoc-members:
:show-inheritance:
+7
View File
@@ -0,0 +1,7 @@
telegram.chatmember module
==========================
.. automodule:: telegram.chatmember
:members:
:undoc-members:
:show-inheritance:
+17
View File
@@ -0,0 +1,17 @@
telegram.contrib package
========================
Submodules
----------
.. toctree::
telegram.contrib.botan
Module contents
---------------
.. automodule:: telegram.contrib
:members:
:undoc-members:
:show-inheritance:
@@ -1,7 +1,7 @@
telegram.nullhandler module
telegram.ext.filters module
===========================
.. automodule:: telegram.nullhandler
.. automodule:: telegram.ext.filters
:members:
:undoc-members:
:show-inheritance:
+2
View File
@@ -10,11 +10,13 @@ Submodules
telegram.ext.dispatcher
telegram.ext.jobqueue
telegram.ext.handler
telegram.ext.callbackqueryhandler
telegram.ext.choseninlineresulthandler
telegram.ext.conversationhandler
telegram.ext.commandhandler
telegram.ext.inlinequeryhandler
telegram.ext.messagehandler
telegram.ext.filters
telegram.ext.regexhandler
telegram.ext.stringcommandhandler
telegram.ext.stringregexhandler
+7
View File
@@ -0,0 +1,7 @@
telegram.file module
====================
.. automodule:: telegram.file
:members:
:undoc-members:
:show-inheritance:
+7
View File
@@ -0,0 +1,7 @@
telegram.game module
====================
.. automodule:: telegram.game
:members:
:undoc-members:
:show-inheritance:
+7
View File
@@ -0,0 +1,7 @@
telegram.gamehighscore module
=============================
.. automodule:: telegram.gamehighscore
:members:
:undoc-members:
:show-inheritance:
@@ -1,5 +1,5 @@
telegram.inlinekeyboardbutton module
===========================
====================================
.. automodule:: telegram.inlinekeyboardbutton
:members:
@@ -1,5 +1,5 @@
telegram.inlinekeyboardmarkup module
==========================
====================================
.. automodule:: telegram.inlinekeyboardmarkup
:members:
@@ -1,5 +1,5 @@
telegram.inlinequeryresultarticle module
=================================
========================================
.. automodule:: telegram.inlinequeryresultarticle
:members:
@@ -1,5 +1,5 @@
telegram.inlinequeryresultaudio module
=================================
======================================
.. automodule:: telegram.inlinequeryresultaudio
:members:
@@ -1,5 +1,5 @@
telegram.inlinequeryresultcachedaudio module
=================================
============================================
.. automodule:: telegram.inlinequeryresultcachedaudio
:members:
@@ -1,5 +1,5 @@
telegram.inlinequeryresultcacheddocument module
=================================
===============================================
.. automodule:: telegram.inlinequeryresultcacheddocument
:members:
@@ -1,5 +1,5 @@
telegram.inlinequeryresultcachedgif module
=================================
==========================================
.. automodule:: telegram.inlinequeryresultcachedgif
:members:
@@ -1,5 +1,5 @@
telegram.inlinequeryresultcachedmpeg4gif module
=================================
===============================================
.. automodule:: telegram.inlinequeryresultcachedmpeg4gif
:members:
@@ -1,5 +1,5 @@
telegram.inlinequeryresultcachedphoto module
=================================
============================================
.. automodule:: telegram.inlinequeryresultcachedphoto
:members:
@@ -1,5 +1,5 @@
telegram.inlinequeryresultcachedsticker module
=================================
==============================================
.. automodule:: telegram.inlinequeryresultcachedsticker
:members:
@@ -1,5 +1,5 @@
telegram.inlinequeryresultcachedvideo module
=================================
============================================
.. automodule:: telegram.inlinequeryresultcachedvideo
:members:
@@ -1,5 +1,5 @@
telegram.inlinequeryresultcachedvoice module
=================================
============================================
.. automodule:: telegram.inlinequeryresultcachedvoice
:members:
@@ -1,5 +1,5 @@
telegram.inlinequeryresultcontact module
=================================
========================================
.. automodule:: telegram.inlinequeryresultcontact
:members:
@@ -1,5 +1,5 @@
telegram.inlinequeryresultdocument module
=================================
=========================================
.. automodule:: telegram.inlinequeryresultdocument
:members:
@@ -0,0 +1,7 @@
telegram.inlinequeryresultgame module
=====================================
.. automodule:: telegram.inlinequeryresultgame
:members:
:undoc-members:
:show-inheritance:
@@ -1,5 +1,5 @@
telegram.inlinequeryresultgif module
=================================
====================================
.. automodule:: telegram.inlinequeryresultgif
:members:
@@ -1,5 +1,5 @@
telegram.inlinequeryresultlocation module
=================================
=========================================
.. automodule:: telegram.inlinequeryresultlocation
:members:
@@ -1,5 +1,5 @@
telegram.inlinequeryresultmpeg4gif module
=================================
=========================================
.. automodule:: telegram.inlinequeryresultmpeg4gif
:members:
@@ -1,5 +1,5 @@
telegram.inlinequeryresultphoto module
=================================
======================================
.. automodule:: telegram.inlinequeryresultphoto
:members:
@@ -1,5 +1,5 @@
telegram.inlinequeryresultvenue module
=================================
======================================
.. automodule:: telegram.inlinequeryresultvenue
:members:
@@ -1,5 +1,5 @@
telegram.inlinequeryresultvideo module
=================================
======================================
.. automodule:: telegram.inlinequeryresultvideo
:members:
@@ -1,5 +1,5 @@
telegram.inlinequeryresultvoice module
=================================
======================================
.. automodule:: telegram.inlinequeryresultvoice
:members:
@@ -0,0 +1,7 @@
telegram.inputcontactmessagecontent module
==========================================
.. automodule:: telegram.inputcontactmessagecontent
:members:
:undoc-members:
:show-inheritance:
@@ -0,0 +1,7 @@
telegram.inputlocationmessagecontent module
===========================================
.. automodule:: telegram.inputlocationmessagecontent
:members:
:undoc-members:
:show-inheritance:
@@ -0,0 +1,7 @@
telegram.inputmessagecontent module
===================================
.. automodule:: telegram.inputmessagecontent
:members:
:undoc-members:
:show-inheritance:
@@ -0,0 +1,7 @@
telegram.inputtextmessagecontent module
=======================================
.. automodule:: telegram.inputtextmessagecontent
:members:
:undoc-members:
:show-inheritance:
@@ -0,0 +1,7 @@
telegram.inputvenuemessagecontent module
========================================
.. automodule:: telegram.inputvenuemessagecontent
:members:
:undoc-members:
:show-inheritance:
+7
View File
@@ -0,0 +1,7 @@
telegram.keyboardbutton module
==============================
.. automodule:: telegram.keyboardbutton
:members:
:undoc-members:
:show-inheritance:
+7
View File
@@ -0,0 +1,7 @@
telegram.messageentity module
=============================
.. automodule:: telegram.messageentity
:members:
:undoc-members:
:show-inheritance:
+7
View File
@@ -0,0 +1,7 @@
telegram.parsemode module
=========================
.. automodule:: telegram.parsemode
:members:
:undoc-members:
:show-inheritance:
@@ -1,7 +0,0 @@
telegram.replykeyboardhide module
=================================
.. automodule:: telegram.replykeyboardhide
:members:
:undoc-members:
:show-inheritance:
@@ -0,0 +1,7 @@
telegram.replykeyboardremove module
===================================
.. automodule:: telegram.replykeyboardremove
:members:
:undoc-members:
:show-inheritance:
+31 -13
View File
@@ -6,14 +6,30 @@ Submodules
.. toctree::
telegram.contrib
telegram.ext
telegram.animation
telegram.audio
telegram.base
telegram.bot
telegram.ext
telegram.inlinequery
telegram.inlinequeryresult
telegram.callbackgame
telegram.callbackquery
telegram.chat
telegram.chataction
telegram.chatmember
telegram.choseninlineresult
telegram.constants
telegram.contact
telegram.document
telegram.error
telegram.file
telegram.forcereply
telegram.game
telegram.gamehighscore
telegram.inlinekeyboardbutton
telegram.inlinekeyboardmarkup
telegram.inlinequery
telegram.inlinequeryresult
telegram.inlinequeryresultarticle
telegram.inlinequeryresultaudio
telegram.inlinequeryresultcachedaudio
@@ -26,6 +42,7 @@ Submodules
telegram.inlinequeryresultcachedvoice
telegram.inlinequeryresultcontact
telegram.inlinequeryresultdocument
telegram.inlinequeryresultgame
telegram.inlinequeryresultgif
telegram.inlinequeryresultlocation
telegram.inlinequeryresultmpeg4gif
@@ -33,28 +50,29 @@ Submodules
telegram.inlinequeryresultvenue
telegram.inlinequeryresultvideo
telegram.inlinequeryresultvoice
telegram.choseninlineresult
telegram.chataction
telegram.contact
telegram.document
telegram.emoji
telegram.error
telegram.forcereply
telegram.chat
telegram.inputcontactmessagecontent
telegram.inputfile
telegram.inputlocationmessagecontent
telegram.inputmessagecontent
telegram.inputtextmessagecontent
telegram.inputvenuemessagecontent
telegram.keyboardbutton
telegram.location
telegram.message
telegram.nullhandler
telegram.messageentity
telegram.parsemode
telegram.photosize
telegram.replykeyboardhide
telegram.replykeyboardremove
telegram.replykeyboardmarkup
telegram.replymarkup
telegram.sticker
telegram.update
telegram.user
telegram.userprofilephotos
telegram.venue
telegram.video
telegram.voice
telegram.webhookinfo
Module contents
---------------
+7
View File
@@ -0,0 +1,7 @@
telegram.venue module
=====================
.. automodule:: telegram.venue
:members:
:undoc-members:
:show-inheritance:
+7
View File
@@ -0,0 +1,7 @@
telegram.webhookinfo module
===========================
.. automodule:: telegram.webhookinfo
:members:
:undoc-members:
:show-inheritance:
+6 -3
View File
@@ -4,14 +4,17 @@ The examples in this folder are small bots meant to show you how a bot that is w
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.
### [`echobot2.py`](https://github.com/python-telegram-bot/python-telegram-bot/blob/v5.0/examples/echobot2.py)
### [`echobot2.py`](https://github.com/python-telegram-bot/python-telegram-bot/blob/master/examples/echobot2.py)
This is probably the base for most of the bots made with `python-telegram-bot`. It simply replies to each text message with a message that contains the same text.
### [`timerbot.py`](https://github.com/python-telegram-bot/python-telegram-bot/blob/master/examples/timerbot.py)
This bot uses the [`JobQueue`](https://pythonhosted.org/python-telegram-bot/telegram.ext.jobqueue.html) class to send timed messages. The user sets a timer by using `/set` command with a specific time, for example `/set 30`. The bot then sets up a job to send a message to that user after 30 seconds. The user can also cancel the timer by sending `/unset`. To learn more about the `JobQueue`, read [this wiki article](https://github.com/python-telegram-bot/python-telegram-bot/wiki/Extensions-%E2%80%93-JobQueue).
This bot uses the [`JobQueue`](https://python-telegram-bot.readthedocs.io/en/latest/telegram.ext.jobqueue.html) class to send timed messages. The user sets a timer by using `/set` command with a specific time, for example `/set 30`. The bot then sets up a job to send a message to that user after 30 seconds. The user can also cancel the timer by sending `/unset`. To learn more about the `JobQueue`, read [this wiki article](https://github.com/python-telegram-bot/python-telegram-bot/wiki/Extensions-%E2%80%93-JobQueue).
### [`conversationbot.py`](https://github.com/python-telegram-bot/python-telegram-bot/blob/master/examples/conversationbot.py)
A common task for a bot is to ask information from the user. In v5.0 of this library, we introduced the [`ConversationHandler`](https://pythonhosted.org/python-telegram-bot/telegram.ext.conversationhandler.html) for that exact purpose. This example uses it to retrieve user-information in a conversation-like style.
A common task for a bot is to ask information from the user. In v5.0 of this library, we introduced the [`ConversationHandler`](https://python-telegram-bot.readthedocs.io/en/latest/telegram.ext.conversationhandler.html) for that exact purpose. This example uses it to retrieve user-information in a conversation-like style. To get a better understanding, take a look at the [state diagram](https://github.com/python-telegram-bot/python-telegram-bot/blob/master/examples/conversationbot.png).
### [`conversationbot2.py`](https://github.com/python-telegram-bot/python-telegram-bot/blob/master/examples/conversationbot2.py)
A more complex example of a bot that uses the `ConversationHandler`. It is also more confusing. Good thing there is a [fancy state diagram](https://github.com/python-telegram-bot/python-telegram-bot/blob/master/examples/conversationbot2.png) for this one, too!
### [`inlinekeyboard.py`](https://github.com/python-telegram-bot/python-telegram-bot/blob/master/examples/inlinekeyboard.py)
This example sheds some light on inline keyboards, callback queries and message editing.
Binary file not shown.

After

Width:  |  Height:  |  Size: 82 KiB

+23 -24
View File
@@ -17,7 +17,7 @@ Press Ctrl-C on the command line or send a signal to the process to stop the
bot.
"""
from telegram import (ReplyKeyboardMarkup)
from telegram import (ReplyKeyboardMarkup, ReplyKeyboardRemove)
from telegram.ext import (Updater, CommandHandler, MessageHandler, Filters, RegexHandler,
ConversationHandler)
@@ -35,11 +35,11 @@ GENDER, PHOTO, LOCATION, BIO = range(4)
def start(bot, update):
reply_keyboard = [['Boy', 'Girl', 'Other']]
bot.sendMessage(update.message.chat_id,
text='Hi! My name is Professor Bot. I will hold a conversation with you. '
'Send /cancel to stop talking to me.\n\n'
'Are you a boy or a girl?',
reply_markup=ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True))
update.message.reply_text(
'Hi! My name is Professor Bot. I will hold a conversation with you. '
'Send /cancel to stop talking to me.\n\n'
'Are you a boy or a girl?',
reply_markup=ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True))
return GENDER
@@ -47,9 +47,9 @@ 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))
bot.sendMessage(update.message.chat_id,
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.')
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())
return PHOTO
@@ -59,8 +59,8 @@ def photo(bot, update):
photo_file = bot.getFile(update.message.photo[-1].file_id)
photo_file.download('user_photo.jpg')
logger.info("Photo of %s: %s" % (user.first_name, 'user_photo.jpg'))
bot.sendMessage(update.message.chat_id, text='Gorgeous! Now, send me your location please, '
'or send /skip if you don\'t want to.')
update.message.reply_text('Gorgeous! Now, send me your location please, '
'or send /skip if you don\'t want to.')
return LOCATION
@@ -68,8 +68,8 @@ 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)
bot.sendMessage(update.message.chat_id, text='I bet you look great! Now, send me your '
'location please, or send /skip.')
update.message.reply_text('I bet you look great! Now, send me your location please, '
'or send /skip.')
return LOCATION
@@ -79,8 +79,8 @@ def location(bot, update):
user_location = update.message.location
logger.info("Location of %s: %f / %f"
% (user.first_name, user_location.latitude, user_location.longitude))
bot.sendMessage(update.message.chat_id, text='Maybe I can visit you sometime! '
'At last, tell me something about yourself.')
update.message.reply_text('Maybe I can visit you sometime! '
'At last, tell me something about yourself.')
return BIO
@@ -88,8 +88,8 @@ 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)
bot.sendMessage(update.message.chat_id, text='You seem a bit paranoid! '
'At last, tell me something about yourself.')
update.message.reply_text('You seem a bit paranoid! '
'At last, tell me something about yourself.')
return BIO
@@ -97,8 +97,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))
bot.sendMessage(update.message.chat_id,
text='Thank you! I hope we can talk again some day.')
update.message.reply_text('Thank you! I hope we can talk again some day.')
return ConversationHandler.END
@@ -106,8 +105,8 @@ def bio(bot, update):
def cancel(bot, update):
user = update.message.from_user
logger.info("User %s canceled the conversation." % user.first_name)
bot.sendMessage(update.message.chat_id,
text='Bye! I hope we can talk again some day.')
update.message.reply_text('Bye! I hope we can talk again some day.',
reply_markup=ReplyKeyboardRemove())
return ConversationHandler.END
@@ -130,13 +129,13 @@ def main():
states={
GENDER: [RegexHandler('^(Boy|Girl|Other)$', gender)],
PHOTO: [MessageHandler([Filters.photo], photo),
PHOTO: [MessageHandler(Filters.photo, photo),
CommandHandler('skip', skip_photo)],
LOCATION: [MessageHandler([Filters.location], location),
LOCATION: [MessageHandler(Filters.location, location),
CommandHandler('skip', skip_location)],
BIO: [MessageHandler([Filters.text], bio)]
BIO: [MessageHandler(Filters.text, bio)]
},
fallbacks=[CommandHandler('cancel', cancel)]
Binary file not shown.

After

Width:  |  Height:  |  Size: 82 KiB

+152
View File
@@ -0,0 +1,152 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Simple Bot to reply to Telegram messages
# This program is dedicated to the public domain under the CC0 license.
"""
This Bot uses the Updater class to handle the bot.
First, a few callback functions are defined. Then, those functions are passed to
the Dispatcher and registered at their respective places.
Then, the bot is started and runs until we press Ctrl-C on the command line.
Usage:
Example of a bot-user conversation using ConversationHandler.
Send /start to initiate the conversation.
Press Ctrl-C on the command line or send a signal to the process to stop the
bot.
"""
from telegram import ReplyKeyboardMarkup
from telegram.ext import (Updater, CommandHandler, MessageHandler, Filters, RegexHandler,
ConversationHandler)
import logging
# Enable logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO)
logger = logging.getLogger(__name__)
CHOOSING, TYPING_REPLY, TYPING_CHOICE = range(3)
reply_keyboard = [['Age', 'Favourite colour'],
['Number of siblings', 'Something else...'],
['Done']]
markup = ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True)
def facts_to_str(user_data):
facts = list()
for key, value in user_data.items():
facts.append('%s - %s' % (key, value))
return "\n".join(facts).join(['\n', '\n'])
def start(bot, update):
update.message.reply_text(
"Hi! My name is Doctor Botter. I will hold a more complex conversation with you. "
"Why don't you tell me something about yourself?",
reply_markup=markup)
return CHOOSING
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())
return TYPING_REPLY
def custom_choice(bot, update):
update.message.reply_text('Alright, please send me the category first, '
'for example "Most impressive skill"')
return TYPING_CHOICE
def received_information(bot, update, user_data):
text = update.message.text
category = user_data['choice']
user_data[category] = text
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)
return CHOOSING
def done(bot, update, user_data):
if 'choice' in 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))
user_data.clear()
return ConversationHandler.END
def error(bot, update, error):
logger.warn('Update "%s" caused error "%s"' % (update, error))
def main():
# Create the Updater and pass it your bot's token.
updater = Updater("TOKEN")
# Get the dispatcher to register handlers
dp = updater.dispatcher
# Add conversation handler with the states GENDER, PHOTO, LOCATION and BIO
conv_handler = ConversationHandler(
entry_points=[CommandHandler('start', start)],
states={
CHOOSING: [RegexHandler('^(Age|Favourite colour|Number of siblings)$',
regular_choice,
pass_user_data=True),
RegexHandler('^Something else...$',
custom_choice),
],
TYPING_CHOICE: [MessageHandler(Filters.text,
regular_choice,
pass_user_data=True),
],
TYPING_REPLY: [MessageHandler(Filters.text,
received_information,
pass_user_data=True),
],
},
fallbacks=[RegexHandler('^Done$', done, pass_user_data=True)]
)
dp.add_handler(conv_handler)
# log all errors
dp.add_error_handler(error)
# Start the Bot
updater.start_polling()
# Run the bot until the you presses Ctrl-C or the process receives SIGINT,
# SIGTERM or SIGABRT. This should be used most of the time, since
# start_polling() is non-blocking and will stop the bot gracefully.
updater.idle()
if __name__ == '__main__':
main()
+1 -1
View File
@@ -46,7 +46,7 @@ def echo(bot):
if update.message: # your bot can receive updates without messages
# Reply to the message
bot.sendMessage(chat_id=chat_id, text=update.message.text)
update.message.reply_text(update.message.text)
if __name__ == '__main__':
+1 -1
View File
@@ -56,7 +56,7 @@ def main():
dp.add_handler(CommandHandler("help", help))
# on noncommand i.e message - echo the message on Telegram
dp.add_handler(MessageHandler([Filters.text], echo))
dp.add_handler(MessageHandler(Filters.text, echo))
# log all errors
dp.add_error_handler(error)
+3 -3
View File
@@ -34,11 +34,11 @@ logger = logging.getLogger(__name__)
# Define a few command handlers. These usually take the two arguments bot and
# update. Error handlers also receive the raised TelegramError object in error.
def start(bot, update):
bot.sendMessage(update.message.chat_id, text='Hi!')
update.message.reply_text('Hi!')
def help(bot, update):
bot.sendMessage(update.message.chat_id, text='Help!')
update.message.reply_text('Help!')
def escape_markdown(text):
@@ -68,7 +68,7 @@ def inlinequery(bot, update):
"_%s_" % escape_markdown(query),
parse_mode=ParseMode.MARKDOWN)))
bot.answerInlineQuery(update.inline_query.id, results=results)
update.inline_query.answer(results)
def error(bot, update, error):
+2 -2
View File
@@ -20,7 +20,7 @@ def start(bot, update):
reply_markup = InlineKeyboardMarkup(keyboard)
bot.sendMessage(update.message.chat_id, text="Please choose:", reply_markup=reply_markup)
update.message.reply_text('Please choose:', reply_markup=reply_markup)
def button(bot, update):
@@ -32,7 +32,7 @@ def button(bot, update):
def help(bot, update):
bot.sendMessage(update.message.chat_id, text="Use /start to test this bot.")
update.message.reply_text("Use /start to test this bot.")
def error(bot, update, error):
+8 -8
View File
@@ -31,7 +31,7 @@ timers = dict()
# Define a few command handlers. These usually take the two arguments bot and
# update. Error handlers also receive the raised TelegramError object in error.
def start(bot, update):
bot.sendMessage(update.message.chat_id, text='Hi! Use /set <seconds> to ' 'set a timer')
update.message.reply_text('Hi! Use /set <seconds> to set a timer')
def alarm(bot, job):
@@ -46,7 +46,7 @@ def set(bot, update, args, job_queue):
# args[0] should contain the time for the timer in seconds
due = int(args[0])
if due < 0:
bot.sendMessage(chat_id, text='Sorry we can not go back to future!')
update.message.reply_text('Sorry we can not go back to future!')
return
# Add job to queue
@@ -54,25 +54,25 @@ def set(bot, update, args, job_queue):
timers[chat_id] = job
job_queue.put(job)
bot.sendMessage(chat_id, text='Timer successfully set!')
update.message.reply_text('Timer successfully set!')
except (IndexError, ValueError):
bot.sendMessage(chat_id, text='Usage: /set <seconds>')
update.message.reply_text('Usage: /set <seconds>')
def unset(bot, update, job_queue):
def unset(bot, update):
"""Removes the job if the user changed their mind"""
chat_id = update.message.chat_id
if chat_id not in timers:
bot.sendMessage(chat_id, text='You have no active timer')
update.message.reply_text('You have no active timer')
return
job = timers[chat_id]
job.schedule_removal()
del timers[chat_id]
bot.sendMessage(chat_id, text='Timer successfully unset!')
update.message.reply_text('Timer successfully unset!')
def error(bot, update, error):
@@ -89,7 +89,7 @@ def main():
dp.add_handler(CommandHandler("start", start))
dp.add_handler(CommandHandler("help", start))
dp.add_handler(CommandHandler("set", set, pass_args=True, pass_job_queue=True))
dp.add_handler(CommandHandler("unset", unset, pass_job_queue=True))
dp.add_handler(CommandHandler("unset", unset))
# log all errors
dp.add_error_handler(error)
+1 -1
View File
@@ -1,3 +1,3 @@
future>=0.15.2
urllib3>=1.10
urllib3==1.20
certifi
+1 -1
View File
@@ -30,7 +30,7 @@ with codecs.open('README.rst', 'r', 'utf-8') as fd:
license='LGPLv3',
url='https://python-telegram-bot.org/',
keywords='python telegram bot api wrapper',
description='Not just a Python wrapper around the Telegram Bot API',
description="We have made you a wrapper you can't refuse",
long_description=fd.read(),
packages=find_packages(exclude=['tests*']),
install_requires=requirements(),
+27 -20
View File
@@ -38,7 +38,7 @@ from .userprofilephotos import UserProfilePhotos
from .keyboardbutton import KeyboardButton
from .replymarkup import ReplyMarkup
from .replykeyboardmarkup import ReplyKeyboardMarkup
from .replykeyboardhide import ReplyKeyboardHide
from .replykeyboardremove import ReplyKeyboardRemove, ReplyKeyboardHide
from .forcereply import ForceReply
from .error import TelegramError
from .inputfile import InputFile
@@ -46,6 +46,8 @@ from .file import File
from .emoji import Emoji
from .parsemode import ParseMode
from .messageentity import MessageEntity
from .animation import Animation
from .game import Game
from .message import Message
from .inputmessagecontent import InputMessageContent
from .callbackquery import CallbackQuery
@@ -73,10 +75,13 @@ from .inlinequeryresultphoto import InlineQueryResultPhoto
from .inlinequeryresultvenue import InlineQueryResultVenue
from .inlinequeryresultvideo import InlineQueryResultVideo
from .inlinequeryresultvoice import InlineQueryResultVoice
from .inlinequeryresultgame import InlineQueryResultGame
from .inputtextmessagecontent import InputTextMessageContent
from .inputlocationmessagecontent import InputLocationMessageContent
from .inputvenuemessagecontent import InputVenueMessageContent
from .inputcontactmessagecontent import InputContactMessageContent
from .webhookinfo import WebhookInfo
from .gamehighscore import GameHighScore
from .update import Update
from .bot import Bot
from .constants import (MAX_MESSAGE_LENGTH, MAX_CAPTION_LENGTH, SUPPORTED_WEBHOOK_PORTS,
@@ -87,22 +92,24 @@ from .version import __version__ # flake8: noqa
__author__ = 'devs@python-telegram-bot.org'
__all__ = ['Audio', 'Bot', 'Chat', 'ChatMember', 'ChatAction', 'ChosenInlineResult',
'CallbackQuery', 'Contact', 'Document', 'Emoji', 'File', 'ForceReply',
'InlineKeyboardButton', 'InlineKeyboardMarkup', 'InlineQuery', 'InlineQueryResult',
'InlineQueryResult', 'InlineQueryResultArticle', 'InlineQueryResultAudio',
'InlineQueryResultCachedAudio', 'InlineQueryResultCachedDocument',
'InlineQueryResultCachedGif', 'InlineQueryResultCachedMpeg4Gif',
'InlineQueryResultCachedPhoto', 'InlineQueryResultCachedSticker',
'InlineQueryResultCachedVideo', 'InlineQueryResultCachedVoice',
'InlineQueryResultContact', 'InlineQueryResultDocument', 'InlineQueryResultGif',
'InlineQueryResultLocation', 'InlineQueryResultMpeg4Gif', 'InlineQueryResultPhoto',
'InlineQueryResultVenue', 'InlineQueryResultVideo', 'InlineQueryResultVoice',
'InputContactMessageContent', 'InputFile', 'InputLocationMessageContent',
'InputMessageContent', 'InputTextMessageContent', 'InputVenueMessageContent',
'KeyboardButton', 'Location', 'Message', 'MessageEntity', 'ParseMode', 'PhotoSize',
'ReplyKeyboardHide', 'ReplyKeyboardMarkup', 'ReplyMarkup', 'Sticker', 'TelegramError',
'TelegramObject', 'Update', 'User', 'UserProfilePhotos', 'Venue', 'Video', 'Voice',
'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']
__all__ = [
'Audio', 'Bot', 'Chat', 'ChatMember', 'ChatAction', 'ChosenInlineResult', 'CallbackQuery',
'Contact', 'Document', 'Emoji', 'File', 'ForceReply', 'InlineKeyboardButton',
'InlineKeyboardMarkup', 'InlineQuery', 'InlineQueryResult', 'InlineQueryResult',
'InlineQueryResultArticle', 'InlineQueryResultAudio', 'InlineQueryResultCachedAudio',
'InlineQueryResultCachedDocument', 'InlineQueryResultCachedGif',
'InlineQueryResultCachedMpeg4Gif', 'InlineQueryResultCachedPhoto',
'InlineQueryResultCachedSticker', 'InlineQueryResultCachedVideo',
'InlineQueryResultCachedVoice', 'InlineQueryResultContact', 'InlineQueryResultDocument',
'InlineQueryResultGif', 'InlineQueryResultLocation', 'InlineQueryResultMpeg4Gif',
'InlineQueryResultPhoto', 'InlineQueryResultVenue', 'InlineQueryResultVideo',
'InlineQueryResultVoice', 'InlineQueryResultGame', 'InputContactMessageContent', 'InputFile',
'InputLocationMessageContent', 'InputMessageContent', 'InputTextMessageContent',
'InputVenueMessageContent', 'KeyboardButton', 'Location', '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',
'MAX_FILESIZE_DOWNLOAD', 'MAX_FILESIZE_UPLOAD', 'MAX_MESSAGES_PER_SECOND_PER_CHAT',
'MAX_MESSAGES_PER_SECOND', 'MAX_MESSAGES_PER_MINUTE_PER_GROUP', 'WebhookInfo', 'Animation',
'Game', 'GameHighScore'
]
+7 -2
View File
@@ -14,5 +14,10 @@ def print_ver_info():
print('future {0}'.format(future.__version__))
print('Python {0}'.format(sys.version.replace('\n', ' ')))
# main
print_ver_info()
def main():
print_ver_info()
if __name__ == '__main__':
main()
+60
View File
@@ -0,0 +1,60 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2016
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram Animation."""
from telegram import PhotoSize
from telegram import TelegramObject
class Animation(TelegramObject):
"""This object represents a Telegram Animation.
Attributes:
file_id (str): Unique file identifier.
Keyword Args:
thumb (Optional[:class:`telegram.PhotoSize`]): Animation thumbnail as defined by sender.
file_name (Optional[str]): Original animation filename as defined by sender.
mime_type (Optional[str]): MIME type of the file as defined by sender.
file_size (Optional[int]): File size.
"""
def __init__(self, file_id, **kwargs):
self.file_id = file_id
self.thumb = kwargs.get('thumb')
self.file_name = kwargs.get('file_name')
self.mime_type = kwargs.get('mime_type')
self.file_size = kwargs.get('file_size')
@staticmethod
def de_json(data, bot):
"""
Args:
data (dict):
bot (telegram.Bot):
Returns:
telegram.Game:
"""
if not data:
return None
data['thumb'] = PhotoSize.de_json(data.get('thumb'), bot)
return Animation(**data)
+15 -9
View File
@@ -16,7 +16,7 @@
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains a object that represents a Telegram Audio."""
"""This module contains an object that represents a Telegram Audio."""
from telegram import TelegramObject
@@ -35,24 +35,30 @@ class Audio(TelegramObject):
Args:
file_id (str):
duration (int):
**kwargs: Arbitrary keyword arguments.
Keyword Args:
performer (Optional[str]):
title (Optional[str]):
mime_type (Optional[str]):
file_size (Optional[int]):
**kwargs: Arbitrary keyword arguments.
"""
def __init__(self, file_id, duration, **kwargs):
def __init__(self,
file_id,
duration,
performer='',
title='',
mime_type='',
file_size=0,
**kwargs):
# Required
self.file_id = str(file_id)
self.duration = int(duration)
# Optionals
self.performer = kwargs.get('performer', '')
self.title = kwargs.get('title', '')
self.mime_type = str(kwargs.get('mime_type', ''))
self.file_size = int(kwargs.get('file_size', 0))
self.performer = performer
self.title = title
self.mime_type = str(mime_type)
self.file_size = int(file_size)
@staticmethod
def de_json(data, bot):
+690 -583
View File
File diff suppressed because it is too large Load Diff
+25
View File
@@ -0,0 +1,25 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2016
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram CallbackGame."""
from telegram import TelegramObject
class CallbackGame(TelegramObject):
"""A placeholder, currently holds no information. Use BotFather to set up your game."""
+65 -6
View File
@@ -16,8 +16,7 @@
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains a object that represents a Telegram
CallbackQuery"""
"""This module contains an object that represents a Telegram CallbackQuery"""
from telegram import TelegramObject, Message, User
@@ -25,14 +24,25 @@ from telegram import TelegramObject, Message, User
class CallbackQuery(TelegramObject):
"""This object represents a Telegram CallbackQuery."""
def __init__(self, id, from_user, data, bot=None, **kwargs):
def __init__(self,
id,
from_user,
chat_instance,
message=None,
data=None,
inline_message_id=None,
game_short_name=None,
bot=None,
**kwargs):
# Required
self.id = id
self.from_user = from_user
self.data = data
self.chat_instance = chat_instance
# Optionals
self.message = kwargs.get('message')
self.inline_message_id = kwargs.get('inline_message_id', '')
self.message = message
self.data = data
self.inline_message_id = inline_message_id
self.game_short_name = game_short_name
self.bot = bot
@@ -69,3 +79,52 @@ class CallbackQuery(TelegramObject):
def answer(self, *args, **kwargs):
"""Shortcut for ``bot.answerCallbackQuery(update.callback_query.id, *args, **kwargs)``"""
return self.bot.answerCallbackQuery(self.id, *args, **kwargs)
def edit_message_text(self, *args, **kwargs):
"""
Shortcut for either ``bot.editMessageText(chat_id=update.callback_query.message.chat_id, \
message_id=update.callback_query.message.message_id, \
*args, **kwargs)``
or ``bot.editMessageText(inline_message_id=update.callback_query.inline_message_id, \
*args, **kwargs)``
"""
if self.inline_message_id:
return self.bot.edit_message_text(
inline_message_id=self.inline_message_id, *args, **kwargs)
else:
return self.bot.edit_message_text(
chat_id=self.message.chat_id, message_id=self.message.message_id, *args, **kwargs)
def edit_message_caption(self, *args, **kwargs):
"""
Shortcut for either
``bot.editMessageCaption(chat_id=update.callback_query.message.chat_id, \
message_id=update.callback_query.message.message_id, \
*args, **kwargs)``
or
``bot.editMessageCaption(inline_message_id=update.callback_query.inline_message_id, \
*args, **kwargs)``
"""
if self.inline_message_id:
return self.bot.edit_message_caption(
inline_message_id=self.inline_message_id, *args, **kwargs)
else:
return self.bot.edit_message_caption(
chat_id=self.message.chat_id, message_id=self.message.message_id, *args, **kwargs)
def edit_message_reply_markup(self, *args, **kwargs):
"""
Shortcut for either
``bot.editMessageReplyMarkup(chat_id=update.callback_query.message.chat_id, \
message_id=update.callback_query.message.message_id, \
*args, **kwargs)``
or
``bot.editMessageReplyMarkup(inline_message_id=update.callback_query.inline_message_id, \
*args, **kwargs)``
"""
if self.inline_message_id:
return self.bot.edit_message_reply_markup(
inline_message_id=self.inline_message_id, *args, **kwargs)
else:
return self.bot.edit_message_reply_markup(
chat_id=self.message.chat_id, message_id=self.message.message_id, *args, **kwargs)
+23 -11
View File
@@ -17,7 +17,7 @@
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains a object that represents a Telegram Chat."""
"""This module contains an object that represents a Telegram Chat."""
from telegram import TelegramObject
@@ -32,31 +32,43 @@ class Chat(TelegramObject):
username (str): Username, for private chats and channels if available
first_name (str): First name of the other party in a private chat
last_name (str): Last name of the other party in a private chat
all_members_are_admins (bool): True if a group has 'All Members Are Admins' enabled.
Args:
id (int):
type (str):
**kwargs: Arbitrary keyword arguments.
Keyword Args:
type (Optional[str]):
title (Optional[str]):
username(Optional[str]):
first_name(Optional[str]):
last_name(Optional[str]):
bot (Optional[Bot]): The Bot to use for instance methods
"""
**kwargs (dict): Arbitrary keyword arguments.
"""
PRIVATE = 'private'
GROUP = 'group'
SUPERGROUP = 'supergroup'
CHANNEL = 'channel'
def __init__(self, id, type, bot=None, **kwargs):
def __init__(self,
id,
type,
title='',
username='',
first_name='',
last_name='',
all_members_are_admins=False,
bot=None,
**kwargs):
# Required
self.id = int(id)
self.type = type
# Optionals
self.title = kwargs.get('title', '')
self.username = kwargs.get('username', '')
self.first_name = kwargs.get('first_name', '')
self.last_name = kwargs.get('last_name', '')
self.title = title
self.username = username
self.first_name = first_name
self.last_name = last_name
self.all_members_are_admins = all_members_are_admins
self.bot = bot
+1 -1
View File
@@ -17,7 +17,7 @@
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains a object that represents a Telegram ChatAction."""
"""This module contains an object that represents a Telegram ChatAction."""
class ChatAction(object):
+3 -2
View File
@@ -16,7 +16,7 @@
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains a object that represents a Telegram ChatMember."""
"""This module contains an object that represents a Telegram ChatMember."""
from telegram import User, TelegramObject
@@ -32,8 +32,9 @@ class ChatMember(TelegramObject):
Args:
user (:class:`telegram.User`):
status (str):
"""
**kwargs (dict): Arbitrary keyword arguments.
"""
CREATOR = 'creator'
ADMINISTRATOR = 'administrator'
MEMBER = 'member'
+7 -2
View File
@@ -17,7 +17,7 @@
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""
This module contains a object that represents a Telegram ChosenInlineResult
This module contains an object that represents a Telegram ChosenInlineResult
"""
from telegram import TelegramObject, User, Location
@@ -33,11 +33,16 @@ class ChosenInlineResult(TelegramObject):
result_id (str):
from_user (:class:`telegram.User`):
query (str):
location (:class:`telegram.Location`):
inline_message_id (str):
Args:
result_id (str):
from_user (:class:`telegram.User`):
query (str):
location (Optional[:class:`telegram.Location`]):
inline_message_id (Optional[str]):
**kwargs (dict): Arbitrary keyword arguments.
"""
@@ -69,7 +74,7 @@ class ChosenInlineResult(TelegramObject):
if not data:
return None
# Required
# Required
data['from_user'] = User.de_json(data.pop('from'), bot)
# Optionals
data['location'] = Location.de_json(data.get('location'), bot)
+6 -7
View File
@@ -16,7 +16,7 @@
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains a object that represents a Telegram Contact."""
"""This module contains an object that represents a Telegram Contact."""
from telegram import TelegramObject
@@ -33,20 +33,19 @@ class Contact(TelegramObject):
Args:
phone_number (str):
first_name (str):
**kwargs: Arbitrary keyword arguments.
Keyword Args:
last_name (Optional[str]):
user_id (Optional[int]):
**kwargs: Arbitrary keyword arguments.
"""
def __init__(self, phone_number, first_name, **kwargs):
def __init__(self, phone_number, first_name, last_name='', user_id=0, **kwargs):
# Required
self.phone_number = str(phone_number)
self.first_name = first_name
# Optionals
self.last_name = kwargs.get('last_name', '')
self.user_id = int(kwargs.get('user_id', 0))
self.last_name = last_name
self.user_id = int(user_id)
@staticmethod
def de_json(data, bot):
+8 -9
View File
@@ -16,7 +16,7 @@
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains a object that represents a Telegram Document."""
"""This module contains an object that represents a Telegram Document."""
from telegram import PhotoSize, TelegramObject
@@ -33,23 +33,22 @@ class Document(TelegramObject):
Args:
file_id (str):
**kwargs: Arbitrary keyword arguments.
Keyword Args:
thumb (Optional[:class:`telegram.PhotoSize`]):
file_name (Optional[str]):
mime_type (Optional[str]):
file_size (Optional[int]):
**kwargs (dict): Arbitrary keyword arguments.
"""
def __init__(self, file_id, **kwargs):
def __init__(self, file_id, thumb=None, file_name='', mime_type='', file_size=0, **kwargs):
# Required
self.file_id = str(file_id)
# Optionals
self.thumb = kwargs.get('thumb')
self.file_name = kwargs.get('file_name', '')
self.mime_type = str(kwargs.get('mime_type', ''))
self.file_size = int(kwargs.get('file_size', 0))
self.thumb = thumb
self.file_name = file_name
self.mime_type = str(mime_type)
self.file_size = int(file_size)
@staticmethod
def de_json(data, bot):
+1 -1
View File
@@ -18,7 +18,7 @@
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains a object that represents an Emoji.
"""This module contains an object that represents an Emoji.
This module will be removed in the future.
"""
+16 -4
View File
@@ -16,7 +16,7 @@
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains a object that represents a Telegram Error."""
"""This module contains an object that represents a Telegram Error."""
def _lstrip_str(in_s, lstr):
@@ -94,8 +94,20 @@ class ChatMigrated(TelegramError):
Args:
new_chat_id (int):
Returns:
"""
super(ChatMigrated,
self).__init__('Group migrated to supergroup. New chat id: {}'.format(new_chat_id))
self.new_chat_id = new_chat_id
class RetryAfter(TelegramError):
def __init__(self, retry_after):
"""
Args:
retry_after (int):
"""
super(ChatMigrated, self).__init__('Chat migrated')
self.new_chat_id = new_chat_id
super(RetryAfter,
self).__init__('Flood control exceeded. Retry in {} seconds'.format(retry_after))
self.retry_after = float(retry_after)
+3 -2
View File
@@ -26,7 +26,8 @@ from .choseninlineresulthandler import ChosenInlineResultHandler
from .commandhandler import CommandHandler
from .handler import Handler
from .inlinequeryhandler import InlineQueryHandler
from .messagehandler import MessageHandler, Filters
from .messagehandler import MessageHandler
from .filters import BaseFilter, Filters
from .regexhandler import RegexHandler
from .stringcommandhandler import StringCommandHandler
from .stringregexhandler import StringRegexHandler
@@ -35,5 +36,5 @@ from .conversationhandler import ConversationHandler
__all__ = ('Dispatcher', 'JobQueue', 'Job', 'Updater', 'CallbackQueryHandler',
'ChosenInlineResultHandler', 'CommandHandler', 'Handler', 'InlineQueryHandler',
'MessageHandler', 'Filters', 'RegexHandler', 'StringCommandHandler',
'MessageHandler', 'BaseFilter', 'Filters', 'RegexHandler', 'StringCommandHandler',
'StringRegexHandler', 'TypeHandler', 'ConversationHandler')
+18 -4
View File
@@ -39,7 +39,7 @@ class CallbackQueryHandler(Handler):
pass_update_queue (optional[bool]): If set to ``True``, a keyword argument called
``update_queue`` will be passed to the callback function. It will be the ``Queue``
instance used by the ``Updater`` and ``Dispatcher`` that contains new updates which can
be used to insert updates. Default is ``False``.
be used to insert updates. Default is ``False``.
pass_job_queue (optional[bool]): If set to ``True``, a keyword argument called
``job_queue`` will be passed to the callback function. It will be a ``JobQueue``
instance created by the ``Updater`` which can be used to schedule new jobs.
@@ -52,6 +52,14 @@ class CallbackQueryHandler(Handler):
pass_groupdict (optional[bool]): If the callback should be passed the
result of ``re.match(pattern, data).groupdict()`` as a keyword
argument called ``groupdict``. Default is ``False``
pass_user_data (optional[bool]): If set to ``True``, a keyword argument called
``user_data`` will be passed to the callback function. It will be a ``dict`` you
can use to keep any data related to the user that sent the update. For each update of
the same user, it will be the same ``dict``. Default is ``False``.
pass_chat_data (optional[bool]): If set to ``True``, a keyword argument called
``chat_data`` will be passed to the callback function. It will be a ``dict`` you
can use to keep any data related to the chat that the update was sent in.
For each update in the same chat, it will be the same ``dict``. Default is ``False``.
"""
def __init__(self,
@@ -60,9 +68,15 @@ class CallbackQueryHandler(Handler):
pass_job_queue=False,
pattern=None,
pass_groups=False,
pass_groupdict=False):
pass_groupdict=False,
pass_user_data=False,
pass_chat_data=False):
super(CallbackQueryHandler, self).__init__(
callback, pass_update_queue=pass_update_queue, pass_job_queue=pass_job_queue)
callback,
pass_update_queue=pass_update_queue,
pass_job_queue=pass_job_queue,
pass_user_data=pass_user_data,
pass_chat_data=pass_chat_data)
if isinstance(pattern, string_types):
pattern = re.compile(pattern)
@@ -81,7 +95,7 @@ class CallbackQueryHandler(Handler):
return True
def handle_update(self, update, dispatcher):
optional_args = self.collect_optional_args(dispatcher)
optional_args = self.collect_optional_args(dispatcher, update)
if self.pattern:
match = re.match(self.pattern, update.callback_query.data)
+21 -4
View File
@@ -35,22 +35,39 @@ class ChosenInlineResultHandler(Handler):
pass_update_queue (optional[bool]): If set to ``True``, a keyword argument called
``update_queue`` will be passed to the callback function. It will be the ``Queue``
instance used by the ``Updater`` and ``Dispatcher`` that contains new updates which can
be used to insert updates. Default is ``False``.
be used to insert updates. Default is ``False``.
pass_job_queue (optional[bool]): If set to ``True``, a keyword argument called
``job_queue`` will be passed to the callback function. It will be a ``JobQueue``
instance created by the ``Updater`` which can be used to schedule new jobs.
Default is ``False``.
pass_user_data (optional[bool]): If set to ``True``, a keyword argument called
``user_data`` will be passed to the callback function. It will be a ``dict`` you
can use to keep any data related to the user that sent the update. For each update of
the same user, it will be the same ``dict``. Default is ``False``.
pass_chat_data (optional[bool]): If set to ``True``, a keyword argument called
``chat_data`` will be passed to the callback function. It will be a ``dict`` you
can use to keep any data related to the chat that the update was sent in.
For each update in the same chat, it will be the same ``dict``. Default is ``False``.
"""
def __init__(self, callback, pass_update_queue=False, pass_job_queue=False):
def __init__(self,
callback,
pass_update_queue=False,
pass_job_queue=False,
pass_user_data=False,
pass_chat_data=False):
super(ChosenInlineResultHandler, self).__init__(
callback, pass_update_queue=pass_update_queue, pass_job_queue=pass_job_queue)
callback,
pass_update_queue=pass_update_queue,
pass_job_queue=pass_job_queue,
pass_user_data=pass_user_data,
pass_chat_data=pass_chat_data)
def check_update(self, update):
return isinstance(update, Update) and update.chosen_inline_result
def handle_update(self, update, dispatcher):
optional_args = self.collect_optional_args(dispatcher)
optional_args = self.collect_optional_args(dispatcher, update)
return self.callback(dispatcher.bot, update, **optional_args)
+18 -4
View File
@@ -44,11 +44,19 @@ class CommandHandler(Handler):
pass_update_queue (optional[bool]): If set to ``True``, a keyword argument called
``update_queue`` will be passed to the callback function. It will be the ``Queue``
instance used by the ``Updater`` and ``Dispatcher`` that contains new updates which can
be used to insert updates. Default is ``False``.
be used to insert updates. Default is ``False``.
pass_job_queue (optional[bool]): If set to ``True``, a keyword argument called
``job_queue`` will be passed to the callback function. It will be a ``JobQueue``
instance created by the ``Updater`` which can be used to schedule new jobs.
Default is ``False``.
pass_user_data (optional[bool]): If set to ``True``, a keyword argument called
``user_data`` will be passed to the callback function. It will be a ``dict`` you
can use to keep any data related to the user that sent the update. For each update of
the same user, it will be the same ``dict``. Default is ``False``.
pass_chat_data (optional[bool]): If set to ``True``, a keyword argument called
``chat_data`` will be passed to the callback function. It will be a ``dict`` you
can use to keep any data related to the chat that the update was sent in.
For each update in the same chat, it will be the same ``dict``. Default is ``False``.
"""
def __init__(self,
@@ -57,9 +65,15 @@ class CommandHandler(Handler):
allow_edited=False,
pass_args=False,
pass_update_queue=False,
pass_job_queue=False):
pass_job_queue=False,
pass_user_data=False,
pass_chat_data=False):
super(CommandHandler, self).__init__(
callback, pass_update_queue=pass_update_queue, pass_job_queue=pass_job_queue)
callback,
pass_update_queue=pass_update_queue,
pass_job_queue=pass_job_queue,
pass_user_data=pass_user_data,
pass_chat_data=pass_chat_data)
self.command = command
self.allow_edited = allow_edited
self.pass_args = pass_args
@@ -76,7 +90,7 @@ class CommandHandler(Handler):
return False
def handle_update(self, update, dispatcher):
optional_args = self.collect_optional_args(dispatcher)
optional_args = self.collect_optional_args(dispatcher, update)
message = update.message or update.edited_message
+2 -23
View File
@@ -22,6 +22,7 @@ import logging
from telegram import Update
from telegram.ext import Handler
from telegram.utils.helpers import extract_chat_and_user
from telegram.utils.promise import Promise
@@ -115,29 +116,7 @@ class ConversationHandler(Handler):
if not isinstance(update, Update):
return False
user = None
chat = None
if update.message:
user = update.message.from_user
chat = update.message.chat
elif update.edited_message:
user = update.edited_message.from_user
chat = update.edited_message.chat
elif update.inline_query:
user = update.inline_query.from_user
elif update.chosen_inline_result:
user = update.chosen_inline_result.from_user
elif update.callback_query:
user = update.callback_query.from_user
chat = update.callback_query.message.chat if update.callback_query.message else None
else:
return False
chat, user = extract_chat_and_user(update)
key = (chat.id, user.id) if chat else (None, user.id)
state = self.conversations.get(key)
+10 -4
View File
@@ -24,6 +24,7 @@ from functools import wraps
from threading import Thread, Lock, Event, current_thread, BoundedSemaphore
from time import sleep
from uuid import uuid4
from collections import defaultdict
from queue import Queue, Empty
@@ -84,6 +85,12 @@ class Dispatcher(object):
self.bot = bot
self.update_queue = update_queue
self.job_queue = job_queue
self.workers = workers
self.user_data = defaultdict(dict)
""":type: dict[int, dict]"""
self.chat_data = defaultdict(dict)
""":type: dict[int, dict]"""
self.handlers = {}
""":type: dict[int, list[Handler]"""
@@ -105,8 +112,6 @@ class Dispatcher(object):
else:
self._set_singleton(None)
self._init_async_threads(uuid4(), workers)
@classmethod
def _reset_singleton(cls):
# NOTE: This method was added mainly for test_updater benefit and specifically pypy. Never
@@ -193,6 +198,7 @@ class Dispatcher(object):
self.logger.error(msg)
raise TelegramError(msg)
self._init_async_threads(uuid4(), self.workers)
self.running = True
self.logger.debug('Dispatcher started')
@@ -303,7 +309,7 @@ class Dispatcher(object):
which handlers were added to the group defines the priority.
Args:
handler (Handler): A Handler instance
handler (telegram.ext.Handler): A Handler instance
group (Optional[int]): The group identifier. Default is 0
"""
@@ -324,7 +330,7 @@ class Dispatcher(object):
Remove a handler from the specified group
Args:
handler (Handler): A Handler instance
handler (telegram.ext.Handler): A Handler instance
group (optional[object]): The group identifier. Default is 0
"""
if handler in self.handlers[group]:
+223
View File
@@ -0,0 +1,223 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2016
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
""" This module contains the Filters for use with the MessageHandler class """
class BaseFilter(object):
"""Base class for all Message Filters
Subclassing from this class filters to be combined using bitwise operators:
And:
>>> (Filters.text & Filters.entity(MENTION))
Or:
>>> (Filters.audio | Filters.video)
Also works with more than two filters:
>>> (Filters.text & (Filters.entity(URL) | Filters.entity(TEXT_LINK)))
If you want to create your own filters create a class inheriting from this class and implement
a `filter` method that returns a boolean: `True` if the message should be handled, `False`
otherwise. Note that the filters work only as class instances, not actual class objects
(so remember to initialize your filter classes).
"""
def __call__(self, message):
return self.filter(message)
def __and__(self, other):
return MergedFilter(self, and_filter=other)
def __or__(self, other):
return MergedFilter(self, or_filter=other)
def filter(self, message):
raise NotImplementedError
class MergedFilter(BaseFilter):
"""Represents a filter consisting of two other filters.
Args:
base_filter: Filter 1 of the merged filter
and_filter: Optional filter to "and" with base_filter. Mutually exclusive with or_filter.
or_filter: Optional filter to "or" with base_filter. Mutually exclusive with and_filter.
"""
def __init__(self, base_filter, and_filter=None, or_filter=None):
self.base_filter = base_filter
self.and_filter = and_filter
self.or_filter = or_filter
def filter(self, message):
if self.and_filter:
return self.base_filter(message) and self.and_filter(message)
elif self.or_filter:
return self.base_filter(message) or self.or_filter(message)
def __str__(self):
return ("<telegram.ext.filters.MergedFilter consisting of"
" {} {} {}>").format(self.base_filter, "and" if self.and_filter else "or",
self.and_filter or self.or_filter)
__repr__ = __str__
class Filters(object):
"""
Predefined filters for use with the `filter` argument of :class:`telegram.ext.MessageHandler`.
"""
class _All(BaseFilter):
def filter(self, message):
return True
all = _All()
class _Text(BaseFilter):
def filter(self, message):
return bool(message.text and not message.text.startswith('/'))
text = _Text()
class _Command(BaseFilter):
def filter(self, message):
return bool(message.text and message.text.startswith('/'))
class _Reply(BaseFilter):
def filter(self, message):
return bool(message.reply_to_message)
reply = _Reply()
command = _Command()
class _Audio(BaseFilter):
def filter(self, message):
return bool(message.audio)
audio = _Audio()
class _Document(BaseFilter):
def filter(self, message):
return bool(message.document)
document = _Document()
class _Photo(BaseFilter):
def filter(self, message):
return bool(message.photo)
photo = _Photo()
class _Sticker(BaseFilter):
def filter(self, message):
return bool(message.sticker)
sticker = _Sticker()
class _Video(BaseFilter):
def filter(self, message):
return bool(message.video)
video = _Video()
class _Voice(BaseFilter):
def filter(self, message):
return bool(message.voice)
voice = _Voice()
class _Contact(BaseFilter):
def filter(self, message):
return bool(message.contact)
contact = _Contact()
class _Location(BaseFilter):
def filter(self, message):
return bool(message.location)
location = _Location()
class _Venue(BaseFilter):
def filter(self, message):
return bool(message.venue)
venue = _Venue()
class _StatusUpdate(BaseFilter):
def filter(self, message):
return bool(message.new_chat_member or message.left_chat_member
or message.new_chat_title or message.new_chat_photo
or message.delete_chat_photo or message.group_chat_created
or message.supergroup_chat_created or message.channel_chat_created
or message.migrate_to_chat_id or message.migrate_from_chat_id
or message.pinned_message)
status_update = _StatusUpdate()
class _Forwarded(BaseFilter):
def filter(self, message):
return bool(message.forward_date)
forwarded = _Forwarded()
class _Game(BaseFilter):
def filter(self, message):
return bool(message.game)
game = _Game()
class entity(BaseFilter):
"""Filters messages to only allow those which have a :class:`telegram.MessageEntity`
where their `type` matches `entity_type`.
Args:
entity_type: Entity type to check for. All types can be found as constants
in :class:`telegram.MessageEntity`.
Returns: function to use as filter
"""
def __init__(self, entity_type):
self.entity_type = entity_type
def filter(self, message):
return any([entity.type == self.entity_type for entity in message.entities])
+30 -5
View File
@@ -20,6 +20,7 @@
Dispatcher """
from telegram.utils.deprecate import deprecate
from telegram.utils.helpers import extract_chat_and_user
class Handler(object):
@@ -34,17 +35,32 @@ class Handler(object):
pass_update_queue (optional[bool]): If set to ``True``, a keyword argument called
``update_queue`` will be passed to the callback function. It will be the ``Queue``
instance used by the ``Updater`` and ``Dispatcher`` that contains new updates which can
be used to insert updates. Default is ``False``.
be used to insert updates. Default is ``False``.
pass_job_queue (optional[bool]): If set to ``True``, a keyword argument called
``job_queue`` will be passed to the callback function. It will be a ``JobQueue``
instance created by the ``Updater`` which can be used to schedule new jobs.
Default is ``False``.
pass_user_data (optional[bool]): If set to ``True``, a keyword argument called
``user_data`` will be passed to the callback function. It will be a ``dict`` you
can use to keep any data related to the user that sent the update. For each update of
the same user, it will be the same ``dict``. Default is ``False``.
pass_chat_data (optional[bool]): If set to ``True``, a keyword argument called
``chat_data`` will be passed to the callback function. It will be a ``dict`` you
can use to keep any data related to the chat that the update was sent in.
For each update in the same chat, it will be the same ``dict``. Default is ``False``.
"""
def __init__(self, callback, pass_update_queue=False, pass_job_queue=False):
def __init__(self,
callback,
pass_update_queue=False,
pass_job_queue=False,
pass_user_data=False,
pass_chat_data=False):
self.callback = callback
self.pass_update_queue = pass_update_queue
self.pass_job_queue = pass_job_queue
self.pass_user_data = pass_user_data
self.pass_chat_data = pass_chat_data
def check_update(self, update):
"""
@@ -69,24 +85,33 @@ class Handler(object):
Args:
update (object): The update to be handled
dispatcher (Dispatcher): The dispatcher to collect optional args
dispatcher (telegram.ext.Dispatcher): The dispatcher to collect optional args
"""
raise NotImplementedError
def collect_optional_args(self, dispatcher):
def collect_optional_args(self, dispatcher, update=None):
"""
Prepares the optional arguments that are the same for all types of
handlers
Args:
dispatcher (Dispatcher):
dispatcher (telegram.ext.Dispatcher):
"""
optional_args = dict()
if self.pass_update_queue:
optional_args['update_queue'] = dispatcher.update_queue
if self.pass_job_queue:
optional_args['job_queue'] = dispatcher.job_queue
if self.pass_user_data or self.pass_chat_data:
chat, user = extract_chat_and_user(update)
if self.pass_user_data:
optional_args['user_data'] = dispatcher.user_data[user.id]
if self.pass_chat_data:
optional_args['chat_data'] = dispatcher.chat_data[chat.id if chat else None]
return optional_args
+18 -4
View File
@@ -38,7 +38,7 @@ class InlineQueryHandler(Handler):
pass_update_queue (optional[bool]): If set to ``True``, a keyword argument called
``update_queue`` will be passed to the callback function. It will be the ``Queue``
instance used by the ``Updater`` and ``Dispatcher`` that contains new updates which can
be used to insert updates. Default is ``False``.
be used to insert updates. Default is ``False``.
pass_job_queue (optional[bool]): If set to ``True``, a keyword argument called
``job_queue`` will be passed to the callback function. It will be a ``JobQueue``
instance created by the ``Updater`` which can be used to schedule new jobs.
@@ -51,6 +51,14 @@ class InlineQueryHandler(Handler):
pass_groupdict (optional[bool]): If the callback should be passed the
result of ``re.match(pattern, query).groupdict()`` as a keyword
argument called ``groupdict``. Default is ``False``
pass_user_data (optional[bool]): If set to ``True``, a keyword argument called
``user_data`` will be passed to the callback function. It will be a ``dict`` you
can use to keep any data related to the user that sent the update. For each update of
the same user, it will be the same ``dict``. Default is ``False``.
pass_chat_data (optional[bool]): If set to ``True``, a keyword argument called
``chat_data`` will be passed to the callback function. It will be a ``dict`` you
can use to keep any data related to the chat that the update was sent in.
For each update in the same chat, it will be the same ``dict``. Default is ``False``.
"""
def __init__(self,
@@ -59,9 +67,15 @@ class InlineQueryHandler(Handler):
pass_job_queue=False,
pattern=None,
pass_groups=False,
pass_groupdict=False):
pass_groupdict=False,
pass_user_data=False,
pass_chat_data=False):
super(InlineQueryHandler, self).__init__(
callback, pass_update_queue=pass_update_queue, pass_job_queue=pass_job_queue)
callback,
pass_update_queue=pass_update_queue,
pass_job_queue=pass_job_queue,
pass_user_data=pass_user_data,
pass_chat_data=pass_chat_data)
if isinstance(pattern, string_types):
pattern = re.compile(pattern)
@@ -80,7 +94,7 @@ class InlineQueryHandler(Handler):
return True
def handle_update(self, update, dispatcher):
optional_args = self.collect_optional_args(dispatcher)
optional_args = self.collect_optional_args(dispatcher, update)
if self.pattern:
match = re.match(self.pattern, update.inline_query.query)
+53 -21
View File
@@ -20,25 +20,37 @@
import logging
import time
import warnings
import datetime
from numbers import Number
from threading import Thread, Lock, Event
from queue import PriorityQueue, Empty
class Days(object):
MON, TUE, WED, THU, FRI, SAT, SUN = range(7)
EVERY_DAY = tuple(range(7))
class JobQueue(object):
"""This class allows you to periodically perform tasks with the bot.
Attributes:
queue (PriorityQueue):
bot (Bot):
prevent_autostart (Optional[bool]): If ``True``, the job queue will not be started
automatically. Defaults to ``False``
bot (telegram.Bot):
Args:
bot (Bot): The bot instance that should be passed to the jobs
bot (telegram.Bot): The bot instance that should be passed to the jobs
Deprecated: 5.2
prevent_autostart (Optional[bool]): Thread does not start during initialisation.
Use `start` method instead.
"""
def __init__(self, bot, prevent_autostart=False):
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()
self.bot = bot
self.logger = logging.getLogger(self.__class__.__name__)
@@ -51,23 +63,30 @@ class JobQueue(object):
""":type: float"""
self._running = False
if not prevent_autostart:
self.logger.debug('Auto-starting %s', self.__class__.__name__)
self.start()
def put(self, job, next_t=None):
"""Queue a new job. If the JobQueue is not running, it will be started.
"""Queue a new job.
Args:
job (Job): The ``Job`` instance representing the new job
next_t (Optional[float]): Time in seconds in which the job should be executed first.
Defaults to ``job.interval``
job (telegram.ext.Job): The ``Job`` instance representing the new job
next_t (Optional[int, float, datetime.timedelta]): Time in which the job
should be executed first. Defaults to ``job.interval``. ``int`` and ``float``
will be interpreted as seconds.
"""
job.job_queue = self
if next_t is None:
next_t = job.interval
interval = job.interval
if isinstance(interval, Number):
next_t = interval
elif isinstance(interval, datetime.timedelta):
next_t = interval.total_seconds()
else:
raise ValueError("The interval argument should be of type datetime.timedelta,"
" int or float")
elif isinstance(next_t, datetime.timedelta):
next_t = next_t.total_second()
now = time.time()
next_t += now
@@ -122,11 +141,11 @@ class JobQueue(object):
continue
if job.enabled:
self.logger.debug('Running job %s', job.name)
try:
job.run(self.bot)
current_week_day = datetime.datetime.now().weekday()
if any(day == current_week_day for day in job.days):
self.logger.debug('Running job %s', job.name)
job.run(self.bot)
except:
self.logger.exception('An uncaught error was raised while executing job %s',
job.name)
@@ -199,6 +218,7 @@ class Job(object):
Attributes:
callback (function):
interval (float):
days: (tuple)
repeat (bool):
name (str):
enabled (bool): Boolean property that decides if this job is currently active
@@ -207,22 +227,34 @@ class Job(object):
callback (function): The callback function that should be executed by the Job. It should
take two parameters ``bot`` and ``job``, where ``job`` is the ``Job`` instance. It
can be used to terminate the job or modify its interval.
interval (float): The interval in which this job should execute its callback function in
seconds.
interval ([int, float, datetime.timedelta]): The interval in which the job will execute its
callback function. ``int`` and ``float`` will be interpreted as seconds.
repeat (Optional[bool]): If this job should be periodically execute its callback function
(``True``) or only once (``False``). Defaults to ``True``
context (Optional[object]): Additional data needed for the callback function. Can be
accessed through ``job.context`` in the callback. Defaults to ``None``
days (Tuple): Defines on which days the job should be ran.
"""
job_queue = None
def __init__(self, callback, interval, repeat=True, context=None):
def __init__(self, callback, interval, repeat=True, context=None, days=Days.EVERY_DAY):
self.callback = callback
self.interval = interval
self.repeat = repeat
self.context = context
if not isinstance(days, tuple):
raise ValueError("The 'days argument should be of type 'tuple'")
if not all(isinstance(day, int) for day in days):
raise ValueError("The elements of the 'days' argument should be of type 'int'")
if not all(day >= 0 and day <= 6 for day in days):
raise ValueError("The elements of the 'days' argument should be from 0 up to and "
"including 6")
self.days = days
self.name = callback.__name__
self._remove = Event()
self._enabled = Event()
+57 -94
View File
@@ -17,92 +17,13 @@
# 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 MessageHandler class """
import warnings
from .handler import Handler
from telegram import Update
from telegram.utils.deprecate import deprecate
class Filters(object):
"""
Convenient namespace (class) & methods for the filter funcs of the
MessageHandler class.
"""
@staticmethod
def text(message):
return message.text and not message.text.startswith('/')
@staticmethod
def command(message):
return message.text and message.text.startswith('/')
@staticmethod
def audio(message):
return bool(message.audio)
@staticmethod
def document(message):
return bool(message.document)
@staticmethod
def photo(message):
return bool(message.photo)
@staticmethod
def sticker(message):
return bool(message.sticker)
@staticmethod
def video(message):
return bool(message.video)
@staticmethod
def voice(message):
return bool(message.voice)
@staticmethod
def contact(message):
return bool(message.contact)
@staticmethod
def location(message):
return bool(message.location)
@staticmethod
def venue(message):
return bool(message.venue)
@staticmethod
def status_update(message):
return bool(message.new_chat_member or message.left_chat_member or message.new_chat_title
or message.new_chat_photo or message.delete_chat_photo
or message.group_chat_created or message.supergroup_chat_created
or message.channel_chat_created or message.migrate_to_chat_id
or message.migrate_from_chat_id or message.pinned_message)
@staticmethod
def forwarded(message):
return bool(message.forward_date)
@staticmethod
def entity(entity_type):
"""Filters messages to only allow those which have a :class:`telegram.MessageEntity`
where their `type` matches `entity_type`.
Args:
entity_type: Entity type to check for. All types can be found as constants
in :class:`telegram.MessageEntity`.
Returns: function to use as filter
"""
def entities_filter(message):
return any([entity.type == entity_type for entity in message.entities])
return entities_filter
class MessageHandler(Handler):
"""
Handler class to handle telegram messages. Messages are Telegram Updates
@@ -110,12 +31,10 @@ class MessageHandler(Handler):
updates.
Args:
filters (list[function]): A list of filter functions. Standard filters
can be found in the Filters class above.
| Each `function` takes ``Update`` as arg and returns ``bool``.
| All messages that match at least one of those filters will be
accepted. If ``bool(filters)`` evaluates to ``False``, messages are
not filtered.
filters (telegram.ext.BaseFilter): A filter inheriting from
:class:`telegram.ext.filters.BaseFilter`. Standard filters can be found in
:class:`telegram.ext.filters.Filters`. Filters can be combined using bitwise
operators (& for and, | for or).
callback (function): A function that takes ``bot, update`` as
positional arguments. It will be called when the ``check_update``
has determined that an update should be processed by this handler.
@@ -124,6 +43,19 @@ class MessageHandler(Handler):
pass_update_queue (optional[bool]): If the handler should be passed the
update queue as a keyword argument called ``update_queue``. It can
be used to insert updates. Default is ``False``
pass_user_data (optional[bool]): If set to ``True``, a keyword argument called
``user_data`` will be passed to the callback function. It will be a ``dict`` you
can use to keep any data related to the user that sent the update. For each update of
the same user, it will be the same ``dict``. Default is ``False``.
pass_chat_data (optional[bool]): If set to ``True``, a keyword argument called
``chat_data`` will be passed to the callback function. It will be a ``dict`` you
can use to keep any data related to the chat that the update was sent in.
For each update in the same chat, it will be the same ``dict``. Default is ``False``.
message_updates (Optional[bool]): Should "normal" message updates be handled? Default is
``True``.
channel_posts_updates (Optional[bool]): Should channel posts updates be handled? Default is
``True``.
"""
def __init__(self,
@@ -131,22 +63,54 @@ class MessageHandler(Handler):
callback,
allow_edited=False,
pass_update_queue=False,
pass_job_queue=False):
pass_job_queue=False,
pass_user_data=False,
pass_chat_data=False,
message_updates=True,
channel_posts_updates=True):
if not message_updates and not channel_posts_updates:
raise ValueError('Both message_updates & channel_post_updates are False')
super(MessageHandler, self).__init__(
callback, pass_update_queue=pass_update_queue, pass_job_queue=pass_job_queue)
callback,
pass_update_queue=pass_update_queue,
pass_job_queue=pass_job_queue,
pass_user_data=pass_user_data,
pass_chat_data=pass_chat_data)
self.filters = filters
self.allow_edited = allow_edited
self.message_updates = message_updates
self.channel_posts_updates = channel_posts_updates
# We put this up here instead of with the rest of checking code
# in check_update since we don't wanna spam a ton
if isinstance(self.filters, list):
warnings.warn('Using a list of filters in MessageHandler is getting '
'deprecated, please use bitwise operators (& and |) '
'instead. More info: https://git.io/vPTbc.')
def _is_allowed_message(self, update):
return (self.message_updates
and (update.message or (update.edited_message and self.allow_edited)))
def _is_allowed_channel_post(self, update):
return (self.channel_posts_updates
and (update.channel_post or (update.edited_channel_post and self.allow_edited)))
def check_update(self, update):
if (isinstance(update, Update)
and (update.message or update.edited_message and self.allow_edited)):
and (self._is_allowed_message(update) or self._is_allowed_channel_post(update))):
if not self.filters:
res = True
else:
message = update.message or update.edited_message
res = any(func(message) for func in self.filters)
message = (update.message or update.edited_message or update.channel_post
or update.edited_channel_post)
if isinstance(self.filters, list):
res = any(func(message) for func in self.filters)
else:
res = self.filters(message)
else:
res = False
@@ -154,12 +118,11 @@ class MessageHandler(Handler):
return res
def handle_update(self, update, dispatcher):
optional_args = self.collect_optional_args(dispatcher)
optional_args = self.collect_optional_args(dispatcher, update)
return self.callback(dispatcher.bot, update, **optional_args)
# old non-PEP8 Handler methods
# old non-PEP8 Handler methods
m = "telegram.MessageHandler."
checkUpdate = deprecate(check_update, m + "checkUpdate", m + "check_update")
handleUpdate = deprecate(handle_update, m + "handleUpdate", m + "handle_update")
+19 -5
View File
@@ -48,11 +48,19 @@ class RegexHandler(Handler):
pass_update_queue (optional[bool]): If set to ``True``, a keyword argument called
``update_queue`` will be passed to the callback function. It will be the ``Queue``
instance used by the ``Updater`` and ``Dispatcher`` that contains new updates which can
be used to insert updates. Default is ``False``.
be used to insert updates. Default is ``False``.
pass_job_queue (optional[bool]): If set to ``True``, a keyword argument called
``job_queue`` will be passed to the callback function. It will be a ``JobQueue``
instance created by the ``Updater`` which can be used to schedule new jobs.
Default is ``False``.
pass_user_data (optional[bool]): If set to ``True``, a keyword argument called
``user_data`` will be passed to the callback function. It will be a ``dict`` you
can use to keep any data related to the user that sent the update. For each update of
the same user, it will be the same ``dict``. Default is ``False``.
pass_chat_data (optional[bool]): If set to ``True``, a keyword argument called
``chat_data`` will be passed to the callback function. It will be a ``dict`` you
can use to keep any data related to the chat that the update was sent in.
For each update in the same chat, it will be the same ``dict``. Default is ``False``.
"""
def __init__(self,
@@ -61,9 +69,15 @@ class RegexHandler(Handler):
pass_groups=False,
pass_groupdict=False,
pass_update_queue=False,
pass_job_queue=False):
pass_job_queue=False,
pass_user_data=False,
pass_chat_data=False):
super(RegexHandler, self).__init__(
callback, pass_update_queue=pass_update_queue, pass_job_queue=pass_job_queue)
callback,
pass_update_queue=pass_update_queue,
pass_job_queue=pass_job_queue,
pass_user_data=pass_user_data,
pass_chat_data=pass_chat_data)
if isinstance(pattern, string_types):
pattern = re.compile(pattern)
@@ -73,14 +87,14 @@ class RegexHandler(Handler):
self.pass_groupdict = pass_groupdict
def check_update(self, update):
if (isinstance(update, Update) and update.message and update.message.text):
if isinstance(update, Update) and update.message and update.message.text:
match = re.match(self.pattern, update.message.text)
return bool(match)
else:
return False
def handle_update(self, update, dispatcher):
optional_args = self.collect_optional_args(dispatcher)
optional_args = self.collect_optional_args(dispatcher, update)
match = re.match(self.pattern, update.message.text)
if self.pass_groups:
+1 -1
View File
@@ -40,7 +40,7 @@ class StringCommandHandler(Handler):
pass_update_queue (optional[bool]): If set to ``True``, a keyword argument called
``update_queue`` will be passed to the callback function. It will be the ``Queue``
instance used by the ``Updater`` and ``Dispatcher`` that contains new updates which can
be used to insert updates. Default is ``False``.
be used to insert updates. Default is ``False``.
pass_job_queue (optional[bool]): If set to ``True``, a keyword argument called
``job_queue`` will be passed to the callback function. It will be a ``JobQueue``
instance created by the ``Updater`` which can be used to schedule new jobs.
+1 -1
View File
@@ -47,7 +47,7 @@ class StringRegexHandler(Handler):
pass_update_queue (optional[bool]): If set to ``True``, a keyword argument called
``update_queue`` will be passed to the callback function. It will be the ``Queue``
instance used by the ``Updater`` and ``Dispatcher`` that contains new updates which can
be used to insert updates. Default is ``False``.
be used to insert updates. Default is ``False``.
pass_job_queue (optional[bool]): If set to ``True``, a keyword argument called
``job_queue`` will be passed to the callback function. It will be a ``JobQueue``
instance created by the ``Updater`` which can be used to schedule new jobs.
+1 -1
View File
@@ -37,7 +37,7 @@ class TypeHandler(Handler):
pass_update_queue (optional[bool]): If set to ``True``, a keyword argument called
``update_queue`` will be passed to the callback function. It will be the ``Queue``
instance used by the ``Updater`` and ``Dispatcher`` that contains new updates which can
be used to insert updates. Default is ``False``.
be used to insert updates. Default is ``False``.
pass_job_queue (optional[bool]): If set to ``True``, a keyword argument called
``job_queue`` will be passed to the callback function. It will be a ``JobQueue``
instance created by the ``Updater`` which can be used to schedule new jobs.
+7 -3
View File
@@ -30,7 +30,7 @@ from queue import Queue
from telegram import Bot, TelegramError
from telegram.ext import Dispatcher, JobQueue
from telegram.error import Unauthorized, InvalidToken
from telegram.error import Unauthorized, InvalidToken, RetryAfter
from telegram.utils.request import Request
from telegram.utils.webhookhandler import (WebhookServer, WebhookHandler)
@@ -61,8 +61,6 @@ class Updater(object):
bot (Optional[Bot]): A pre-initialized bot instance. If a pre-initizlied bot is used, it is
the user's responsibility to create it using a `Request` instance with a large enough
connection pool.
job_queue_tick_interval(Optional[float]): The interval the queue should
be checked for new tasks. Defaults to 1.0
Raises:
ValueError: If both `token` and `bot` are passed or none of them.
@@ -157,6 +155,7 @@ class Updater(object):
self.running = True
# Create & start threads
self.job_queue.start()
self._init_thread(self.dispatcher.start, "dispatcher")
self._init_thread(self._start_polling, "updater", poll_interval, timeout,
network_delay, bootstrap_retries, clean)
@@ -208,6 +207,7 @@ class Updater(object):
self.running = True
# Create & start threads
self.job_queue.start()
self._init_thread(self.dispatcher.start, "dispatcher"),
self._init_thread(self._start_webhook, "updater", listen, port, url_path, cert,
key, bootstrap_retries, clean, webhook_url)
@@ -231,6 +231,9 @@ class Updater(object):
try:
updates = self.bot.getUpdates(
self.last_update_id, timeout=timeout, network_delay=network_delay)
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))
@@ -327,6 +330,7 @@ class Updater(object):
# Disable webhook for cleaning
self.bot.setWebhook(webhook_url='')
self._clean_updates()
sleep(1)
self.bot.setWebhook(webhook_url=webhook_url, certificate=cert)
except (Unauthorized, InvalidToken):

Some files were not shown because too many files have changed in this diff Show More