Compare commits

...

331 Commits

Author SHA1 Message Date
Hinrich Mahler 15268acb27 Bump to v12.8 2020-06-22 20:20:00 +02:00
Poolitzer 927502e588 API 4.9 (#1980)
* Add Basketball Dice

Added Basketball Dice Variation

* Update dice.py

* Update dice.py

* Update telegram/dice.py

Co-authored-by: Bibo-Joshi <hinrich.mahler@freenet.de>

* Update bot.py

* Update filters.py

* Update test_filters.py

* Fixed whitespaces

* Update dice.py

* Fix line length

* adding dice values to docstring

* adding via_bot to message and thumb_mime_type to iqresults

* feat: updating docs

* feat: improving message attribute test

* Fix flake8

Co-authored-by: Jannik <32801117+code1mountain@users.noreply.github.com>
Co-authored-by: Bibo-Joshi <hinrich.mahler@freenet.de>
2020-06-22 20:09:52 +02:00
Yan 0af5cc2db8 Don't override builtin method help() in examples (#1997)
* Do not override builtin method help()

* Rename inlinebot and inlinekeyboard /help function to not conflict with builtin
2020-06-16 17:07:05 +02:00
Bibo-Joshi 6005861f46 Stabilize CI (#2000) 2020-06-15 18:45:38 +02:00
Nils K 8406889179 Remove Python 2 Support (#1715)
* Remove usages of python-future lib

* Remove python2 datetime.timezone replacement

* Remove python2 workaround in InputFile.__init__

* Remove import of str necessary for python2

* Remove urllib2 import necessary for python2

* Remove a mention of python 2 in doc

* Remove python 2 from travis config file

* Remove python 2 from appveyor config

* Remove python2 from debian build rules

* Remove unnecessarry aliasing of time.perf_counter

* Remove python 2 from github workflow

* Remove mention of python 2 in descriptions/readme

* Remove version check for queue import

* Remove version checks in tests

* Adjust docs to correctly mention supported version

* Fix indentation

* Remove unused 'sys' imports

* Fix indentation

* Remove references to mq.curtime in tests

* Replace super calls by argumentsless version

* Remove future dependency

* Fix error in de_json declaration

* Use python3 metaclass syntax

* Use implicit inheriting from object

* Remove accidentally committed .vscode folder

* Use nameless f-string and raw string

* Fix regex string literal syntax

* Remove old style classes

* Run pyupgrade

* Fix leftover from automatic merge

* Fix lint errors

* Update telegram/files/sticker.py

Co-authored-by: Bibo-Joshi <hinrich.mahler@freenet.de>
2020-06-15 18:20:51 +02:00
n5y a4e78f6183 Add standalone example on error handlers (#1983)
* Remove error handlers from examples

Most examples use the same error handler, that error handler logs
update.to_dict but doesn't log error traceback. Hiding error traceback
is quite bad, removing the error handler entirely causes PTB to use
default error logging which does include error traceback.

* adding error handling example

* Change error handler example

Including:
- Change the telegram message to include usual python error message.
- HTML-escape the strings used to build the telegram message.
- Capitalize comments and add more empty lines to hopefully unify the
  style with other examples, at least a bit.
- Reorder imports.

* Add an error-rising command to the error handler example

* Slightly change example error handler docstring and comments

* Make telegram message sent by the error handler example more readable

* Rename error_handler.py to errorhandlerbot.py and add a start command

* Change error handler example to work without developer chat id

* Revert "Change error handler example to work without developer chat id"

This reverts commit c4efea6f

* Make bot token a module level constant in the error handler example

Otherwise the example will require two edits 40 lines apart to run.

* Show chat id in start command of the error handler example

The example requires you to set developer chat id, this change will
make things easier for users that don't know how to see their chat id.

* Add errorhandlerbot.py to the examples folder readme

Co-authored-by: poolitzer <25934244+poolitzer@users.noreply.github.com>
Co-authored-by: Bibo-Joshi <hinrich.mahler@freenet.de>
2020-06-12 18:50:12 +02:00
Bibo-Joshi 8c6cb44a85 Update examples Readme (#1995) 2020-06-12 13:58:20 +02:00
n5y ac7cc7fe5e Ignore private attributes in TelegramObject.to_dict() (#1989) 2020-06-10 22:21:25 +02:00
Bibo-Joshi a42b68933c Add User.send_poll (#1968) 2020-05-27 21:59:49 +02:00
ѕнιναм c2d91c752f Typo-Fix (#1962) 2020-05-22 15:32:03 +02:00
Bibo-Joshi 5057825586 Doc fixes (#1940)
* Update notes on editing messages

* Update thumb and InputMedia* doc strings

* Fix attribute docstring for Updater.user_sig_handler

* Improve rendering for CCs attributes

* fix doc str for InputMedia*.media attribute

* Minor fix
2020-05-15 15:59:41 +02:00
Bibo-Joshi 613175b2c4 Allow updating ids/usernames of Filters.{user, chat} (#1757)
* Make Filters.user attrs mutable

* Add test_filters_user_empty_args

* Add test_filters_user_empty_args

* fix locks

* Make codecov happy

* Make user_ids and usernames sets

* Correct doc string

* Address review

* Review Vol. II

* Apply suggestions from code review

Co-authored-by: Noam Meltzer <tsnoam@gmail.com>

* Review Vol III.

* propery setter is now only a wrapper to a private method + more cleanups

pylint complained on some extra stuff, so cleaned them as well

* Review Vol. IV

* Review Vol. V

* Apply changes to Filters.chat

Co-authored-by: Noam Meltzer <tsnoam@gmail.com>
2020-05-10 12:15:11 +02:00
Bibo-Joshi 1330696259 Improve readability of nested conversation example (#1943) 2020-05-04 16:59:51 +02:00
n5y 5898e1fe7a Remove NullHandlers (#1913) 2020-05-03 10:28:03 +02:00
Bibo-Joshi b6dec118c1 Update contribution guide and stale bot (#1937)
* * Remove developers Mail from contrib guide
* stricter settings for stale bot

* Remove link, too ...

* Link to TG Group instead
2020-05-02 22:24:12 +02:00
Hinrich Mahler 186fd1b418 Bump version to v12.7 2020-05-02 12:14:38 +02:00
Hinrich Mahler 284786fdb8 Fix doc string of run_monthly 2020-05-02 12:14:01 +02:00
Bibo-Joshi c7c56ad24e Api 4.8 (#1917)
* API 4.8

* Elaborate docs

* Address review

* Fix Message.to_json/dict() test

* More coverage

* Update telegram/bot.py

Co-authored-by: Noam Meltzer <tsnoam@gmail.com>

Co-authored-by: Noam Meltzer <tsnoam@gmail.com>
2020-05-02 11:56:52 +02:00
D David Livingston ae17ce977e Add JobQueue.run_monthly() (#1705)
* added monthly job

* removed fold argument

* addressed pr comments

* addressed pr comments

* made changes from pr review

* updated comments

* clean up code

* Update .pre-commit-config.yaml

* Minor cleanup

* Update according to #1685, minor robustness changes

Co-authored-by: Hinrich Mahler <hinrich.mahler@freenet.de>
2020-05-02 08:59:50 +02:00
Bibo-Joshi 7e231183c4 Add tzinfo kwarg to from_timestamp() (#1621)
* Add tz kwarg to from_timestamp()

* Correct handling of tzinfo=None

* Small Improvements

* None-tz yields naive dto

* Remove legacey compatibility of UTC stuff

* Update telegram/utils/helpers.py

Co-authored-by: Noam Meltzer <tsnoam@gmail.com>
2020-05-01 22:55:13 +02:00
Bibo-Joshi 8427346a0d Add supegroup for each test bot (#1919) 2020-05-01 21:29:18 +03:00
Bibo-Joshi 632b989d90 Use @abstractmethod instead of raising NotImplementedError (#1905) 2020-05-01 21:27:34 +03:00
Bibo-Joshi 76567ba635 Stabilize CI (#1931) 2020-05-01 13:27:46 +02:00
Bibo-Joshi 2bd3f2a65a Render Notes correctly (#1914)
* Renders Notes in JobQueues docs correctly

* Notes: -> Note:
2020-04-25 12:34:13 +02:00
Bibo-Joshi 26a5006bf1 Update question template (#1910)
* Update formulation in question template

* grammar
2020-04-20 18:11:48 +02:00
Andrej730 110e2df443 Job.next_t (#1685)
* next_t property is added to Job class

Added new property to Job class - next_t, it will show the datetime when the job will be executed next time.
The property is updated during JobQueue._put method, right after job is added to queue.
Related to #1676

* Fixed newline and trailing whitespace

* Fixed PR issues, added test

1. Added setter for next_t - now JobQueue doesn't access protected Job._next_t.
2. Fixed Job class docstring.
3. Added test for next_t property.
4. Set next_t to None for run_once jobs that already ran.

* Fixed Flake8 issues

* Added next_t setter for datetime, added test

1. next_t setter now can accept datetime type.
2. added test for setting datetime to next_t and added some asserts that check tests results.
3. Also noticed Job.days setter raises ValueError when it's more appropriate to raise TypeError.

* Fixed test_warnings, added Number type to next_t setter

1. Changed type of error raised by interval setter from ValueError to TypeError..
2. Fixed test_warning after changing type of errors in Job.days and Job.interval.
3. Added Number type to next_t setter - now it can accept int too.

* Python 2 compatibility for test_job_next_t_property

Added _UTC and _UtcOffsetTimezone for python 2 compatibility

* Fixed PR issues

1. Replaced "datetime.replace tzinfo" with "datetime.astimezone"
2. Moved testing next_t setter to separate test.
3. Changed test_job_next_t_setter so it now uses non UTC timezone.

* Defining tzinfo from run_once, run_repeating

1. Added option to define Job.tzinfo from run_once (by when.tzinfo) and run_repeating (first.tzinfo)
2. Added test to check that tzinfo is always passed correctly.

* address review

Co-authored-by: Hinrich Mahler <hinrich.mahler@freenet.de>
2020-04-18 15:08:16 +02:00
Bibo-Joshi 57546795c5 Notes on Filters.text accepting command messages (#1902) 2020-04-18 12:16:14 +02:00
Hinrich Mahler 314f87ec44 Bump version to v12.6.1 2020-04-11 09:53:29 +02:00
Bibo-Joshi 4bbcd51ef5 Fix serialization of reply_markups (#1889) 2020-04-11 09:44:40 +02:00
Hinrich Mahler 38a33581b1 Bump version to v12.6 2020-04-10 23:52:08 +02:00
Hinrich Mahler fe821c08e6 Doc Fixes 2020-04-10 23:43:58 +02:00
Harshil 0a9f4bfbdd Doc fixes (#1884)
* Bot.py doc fixes

All docs obtained from official Bot API docs

* made flake8 happy

* address review

Also improved consistency of `returns:` in docs

Co-authored-by: Hinrich Mahler <hinrich.mahler@freenet.de>
2020-04-10 20:05:01 +02:00
Bibo-Joshi c4364c7166 GitHub Actions: Use checkout@v2 (#1887) 2020-04-10 19:57:52 +02:00
Bibo-Joshi d63e710784 API 4.7 (#1858)
* Pure API changes

* Address review

* set Bot.commands on successfull call of set_my_commands

* Get started on tests

* More tests!

* More Coverage!

* Reset changes in utils.request

* Filters.dice, Filters.dice.text

* more coverage

* Address review

* Address review

* Test stop_poll with reply_markup

* Test stop_poll also without reply_markup

* Rephrase note on 'dice'

* Fix grammar in note on Filters.dice

* update api version readme

* address review
2020-04-10 19:22:45 +02:00
Bibo-Joshi f379f54d5a Tweak persistence handling (#1827)
* Unify persistence updates in dispatcher

* Ensure user/chat_data is not None when updating it

* Update persistence after job runs

* Increase coverage
2020-04-10 13:23:13 +02:00
Bibo-Joshi bdf0cb91f3 Pass last valid context to TIMEOUT handlers (#1826) 2020-04-10 13:18:43 +02:00
Bibo-Joshi 3101ea8432 Favor concrete types over "Iterable" (#1882)
* Use concrete types instead of 'iterable'

* Fix overlooked docstring

* address review
2020-04-08 22:49:01 +02:00
Harshil beb8ba3db0 Doc Fixes (#1874)
* doc fixes

* Update AUTHORS.rst

* More doc fixes

All docs were obtained from official Bot API docs.

* Shortened line length

Did this so it passes codacy check

* Revert id docstring changes

* typo

Co-authored-by: Hinrich Mahler <hinrich.mahler@freenet.de>
2020-04-07 17:25:17 +02:00
Bibo-Joshi f0b1aeb6fd Customize issue template chooser (#1880)
* Customize issue template chooser

* Improve wording
2020-04-07 15:45:17 +02:00
Bibo-Joshi d65558888e Add note on UTC to run_{repeating, once} (#1854) 2020-03-31 00:05:08 +02:00
Bibo-Joshi 61a66a32c8 Add tests for empty string as switch_inline_query(_current_chat) (#1635) 2020-03-31 00:03:45 +02:00
Hinrich Mahler 392d4e1a9c Bump version to v12.5.1 2020-03-30 18:25:53 +02:00
Andrej730 9cb34af65a Fix UTC as default tzinfo for Jobs (#1696)
1. Made sure that default tzinfo in JobQueue is UTC #1693.
2. Added test that checks that all methods by default set job.tzinfo as UTC.
2020-03-30 18:10:27 +02:00
Bibo-Joshi e9cb6675ca PrefixHandlers command and prefix editable (#1636)
* Rename internal list of PrefixHandler

* Make PFH.prefix and .command setable attributes

* Improve coverage
2020-03-30 17:49:50 +02:00
Bibo-Joshi 982f6707e1 Make ConversationHandler attributes immutable (#1756)
* Make ConversationHandler attributes immutable

* Add forgotten name property to test_immutable
2020-03-30 17:37:37 +02:00
Rys Artem d55d981e22 Reorder tests to make them more stable (#1835) 2020-03-30 17:06:24 +02:00
Iulian Onofrei f20953f7a9 Fix docs wording (#1855) 2020-03-30 00:32:06 +03:00
Bibo-Joshi e18220be10 Add docs for PollHandler and PollAnswerHandler (#1853) 2020-03-29 11:24:44 +02:00
Hinrich Mahler 90729c21d7 Bump version to v12.5 2020-03-29 10:01:11 +02:00
Poolitzer 55e3ecf9f8 API 4.6 (#1723)
* First take on 4.6 support

* improved docs

* Minor doc formattings

* added poll and poll_answer to filters

* added tests, fixed mentioned issues

* added poll_answer + poll filter tests

* Update docs according to official API docs

* introducing pollhandler and pollanswerhandler

* First take on 4.6 support

* improved docs

* Minor doc formattings

* added poll and poll_answer to filters

* added tests, fixed mentioned issues

* added poll_answer + poll filter tests

* Update docs according to official API docs

* introducing pollhandler and pollanswerhandler

* correct_option_id validated with None

when trying to send a poll with correct option id 0 it was failing. Now None check is done so that even when 0 is passed it is assigned.

* improving example

* improving code

* adding poll filter example to the pollbot.py

* Update Readme

* simplify pollbot.py and add some comments

* add tests for Poll(Answer)Handler

* We just want Filters.poll, not Filters.update.poll

* Make test_official fail again

* Handle ME.language in M._parse_*

Co-authored-by: Hinrich Mahler <hinrich.mahler@freenet.de>
Co-authored-by: Sharun Kumar <715417+sharunkumar@users.noreply.github.com>
2020-03-29 09:52:30 +02:00
Bibo-Joshi 8d2c7af1f3 API 4.5 (#1508)
* Allow for nested MessageEntities in Message._parse_markdown/html, adjust tests

* remove testing relict

* Use MessageEntitys new equality check (#1465)

* Remove unused variable

* Update to custom_title feature and slow_mode_delay option

Changes:

 - custom_title for ChatMember
 - new method setChatAdministratorCustomTitle for Bot
 - new slow_mode_delay for Chat

Update due to new API future `custom_title` from API 4.5 (https://core.telegram.org/bots/api#december-31-2019)

* Minor typo fix

* Comply with Flake8

* Add new MessageEntities and MarkdownV2

* Added file_unique_id attrs from API 4.5 and updated tests for it

* Fixed test and checked using flake8

* Fixed ChatPhoto documentation

* Fix Flake8

* Add setChatAdminCstmTitle to Bot

* Rename MDV2 methods

* Change files id attrs to unique id

* correct id_attrs for chat_photo

* Revert "temporarily skip tests failing b/c missing api 4.5 (#1738)"

This reverts commit 7cde6ca268.

* Fix text_markdown_v2 for monospace and text_links

* closing remarks from pieter

* Minor fix in escape_markdown, improve tests for it

* Fix offset bug in Message._parse_*

* Add test_chatphoto.py

* remove debug print from test_message.py

* try making codecov happy

* Update readme

* all hail codecov

* Improve Link handling for MarkdownV1 and adjust tests. Closes #1654

* Dont use beginning of pre-entity as language in _parse_markdown

* Remove debug print

* Dummy commit to try fix codecov

Co-authored-by: Hoi Dmytro <dmytro.hoi@gmail.com>
Co-authored-by: Dmytro Hoi <code@dmytrohoi.com>
Co-authored-by: poolitzer <25934244+poolitzer@users.noreply.github.com>
2020-03-28 16:37:26 +01:00
Pietu R e86ae25a62 Update CallbackQuery docstrings (#1818)
* mark chat_instance as required

* change ordering and add bot
2020-03-28 15:52:37 +01:00
Bibo-Joshi 2d3357bfeb Ignore Message.default_quote in test_official (#1848) 2020-03-28 14:32:16 +01:00
Bibo-Joshi b6f4783fd3 Revert accitendtal change in vendored urllib3 (#1775) 2020-03-28 12:15:51 +01:00
Bibo-Joshi f94ea9acbb Answer CQs and use edit_message_text in examples (#1721) 2020-03-28 12:07:23 +01:00
Aleksey 157652cfdf Fixe typo in edit_message_media (#1779) 2020-03-28 12:01:06 +01:00
Bibo-Joshi 104d0127aa Doc Fixes (#1778)
* Update docs according to official docs

* Add note to Updater according to #1772

* Add note on ChatPermissions

* Fix rendering for arg type of conversation_timeout
2020-03-28 11:49:47 +01:00
Bibo-Joshi e0b22e60b4 Update label in question template (#1840) 2020-03-20 23:19:32 +02:00
Bibo-Joshi 16613d7ce0 Don't comment when labeling issue as stale (#1829) 2020-03-12 10:14:00 +02:00
Bibo-Joshi eac7f02211 Add Py3.8 to docs (#1824) 2020-03-11 23:36:34 +02:00
Ak4zh 28ded6718e Add link property to Bot (#1770)
* added link property to bot

link property was available in User and Chat objects but not in Bot which was inconsistent.

* added 'link' property to Bot object

Bot will always have username so it does not require hasattr check

* add tests

Co-authored-by: Hinrich Mahler <hinrich.mahler@freenet.de>
2020-03-09 23:17:05 +02:00
Noam Meltzer 13a641b3d7 Python 3.8 support (#1614)
* github workflow: Add python-3.8

* workaround for tornado issue on win with py>=3.8

* add workaround to webhookhandler

* Try making codecov and codacy happy

* Fix stupid mistake

Co-authored-by: Hinrich Mahler <hinrich.mahler@freenet.de>
2020-03-09 23:13:16 +02:00
Bibo-Joshi 27cccc7734 Add stale bot (#1820)
* add stale.yml for stale bot

* move stale.yml to the right directory
2020-03-08 23:40:22 +02:00
Noam Meltzer f7ec7a7c4c Use temporary directories in test_persistence (#1808) 2020-03-04 23:58:19 +02:00
Bibo-Joshi 8d6970ab02 Remove references to travis and appveyor (#1791) 2020-02-23 23:04:56 +02:00
Bibo-Joshi 1dc67dcbda Remove builtin names where possible (#1792) 2020-02-23 23:03:58 +02:00
Poolitzer 14f712b3c4 Update pre-commit config file (#1787) 2020-02-21 07:43:48 +02:00
Poolitzer 0fb0fbb93f Remove legacy CI files (#1783) 2020-02-20 17:33:03 +02:00
Pieter Schutz 72ecc696cb Bump to v12.4.2 2020-02-10 11:39:26 +01:00
Bibo-Joshi a447760411 Make sure PP can read files that dont have bot_data (#1760)
* Make sure PP can read files that dont have bot_data

* Improve workaround
2020-02-08 19:24:35 +02:00
Bibo-Joshi 6da529c46b Pass correct parse_mode to InlineResults if bot.defaults is None (#1763)
* Pass correct parse_mode to InlineResults if bot.defaults is None

* Add tests for inlinequeryresults with (default)parse_mode

* enhance tests
2020-02-08 18:52:22 +02:00
Noam Meltzer bd1b2fb6c1 Bump version to v12.4.1 2020-02-08 15:06:05 +02:00
Bibo-Joshi f9a8cd924c Make Filters.command only accept MessageEntity commands (#1744)
* Make Filters.command only accept MessageEntitie commands

* Add option to filters.command to allow cmds anywhere in the message

* Make codecov happy, also retroactive for #1631
2020-02-08 14:54:21 +02:00
Bibo-Joshi 7b3b278c7c Bump version to v12.4 2020-02-08 10:01:41 +02:00
Bibo-Joshi cf3635d408 make test_webhook_invalid_posts flaky (#1758) 2020-02-07 18:32:38 +02:00
Bibo-Joshi 84cfc6f7fa Rename Test suite … (#1750)
* Rename Test suite

* Actually change the badge in readme

* fix download without path arguments (#1591)

* fix download without path arguments

* fix download without path arguments

* solved downloading a file without file_path or custom_path

* if no file_path, download as file_id

* Add test case

* Elaborate doc string

Co-authored-by: Bibo-Joshi <hinrich.mahler@freenet.de>

* Add default values (#1490)

* added parse_mode parameter in Updater and in Bot class to set a default parse mode for bot

* DefaultValue

* Add default parse_mode everywhere

* Renome to default_parse_mode

* Test def parse_mode for send_*, edit_message_*

* Remove duplicate code in Input* classes

* Improve handling of def_p_m for Bot methods

* Remove unneeded deletion of kwargs

* Make @log preserve signature, add bots with defaults to tests

* Fix Codacy

* Fix Travis Error

* Add default_disable_notification

* Add default_disable_web_page_preview

* Add default_disable_timeout

* add default_disable_web_page_preview for InputTextMessageContent

* add default_quote

* Try fixing test_pin_and_unpin

* Just run 3.5 tests for paranoia

* add tests for Defaults

* Revert "Just run 3.5 tests for paranoia"

This reverts commit 1baa91a3a1.

* Tidy up parameters, move Defaults to ext

* Stage new files, because im an idiot

* remove debug prints

* change equality checks for DEFAULT_NONE

* Some last changes

* fix S&R error so that tests actually run

Co-authored-by: Ak4zh <agwl.akash@gmail.com>
Co-authored-by: Eldinnie <Eldinnie@users.noreply.github.com>

* Skip test relying on ordered dicts for 3.5 (#1752)

* Rename Test suite

* Actually change the badge in readme

Co-authored-by: Gabriel Simonetto <42247511+GabrielSimonetto@users.noreply.github.com>
Co-authored-by: Ak4zh <agwl.akash@gmail.com>
Co-authored-by: Eldinnie <Eldinnie@users.noreply.github.com>
2020-02-06 11:38:21 +01:00
Bibo-Joshi bf06fa2c18 Skip test relying on ordered dicts for 3.5 (#1752) 2020-02-06 11:28:27 +01:00
Bibo-Joshi 960c7a0c70 Add default values (#1490)
* added parse_mode parameter in Updater and in Bot class to set a default parse mode for bot

* DefaultValue

* Add default parse_mode everywhere

* Renome to default_parse_mode

* Test def parse_mode for send_*, edit_message_*

* Remove duplicate code in Input* classes

* Improve handling of def_p_m for Bot methods

* Remove unneeded deletion of kwargs

* Make @log preserve signature, add bots with defaults to tests

* Fix Codacy

* Fix Travis Error

* Add default_disable_notification

* Add default_disable_web_page_preview

* Add default_disable_timeout

* add default_disable_web_page_preview for InputTextMessageContent

* add default_quote

* Try fixing test_pin_and_unpin

* Just run 3.5 tests for paranoia

* add tests for Defaults

* Revert "Just run 3.5 tests for paranoia"

This reverts commit 1baa91a3a1.

* Tidy up parameters, move Defaults to ext

* Stage new files, because im an idiot

* remove debug prints

* change equality checks for DEFAULT_NONE

* Some last changes

* fix S&R error so that tests actually run

Co-authored-by: Ak4zh <agwl.akash@gmail.com>
Co-authored-by: Eldinnie <Eldinnie@users.noreply.github.com>
2020-02-06 11:22:56 +01:00
Gabriel Simonetto bacabbe767 fix download without path arguments (#1591)
* fix download without path arguments

* fix download without path arguments

* solved downloading a file without file_path or custom_path

* if no file_path, download as file_id

* Add test case

* Elaborate doc string

Co-authored-by: Bibo-Joshi <hinrich.mahler@freenet.de>
2020-02-06 11:21:21 +01:00
Eldinnie d8dcdeea75 fix test_pin_and_unpin_message (#1749)
Make it flaky and timeout
2020-02-02 23:39:08 +01:00
isinstance 818475bd93 Fix Server response could not be decoded using UTF-8 (#1623)
Co-authored-by: Noam Meltzer <tsnoam@gmail.com>
2020-02-03 00:12:27 +02:00
Bibo-Joshi f97ac90af7 skip test_json on TestDictPersistence on py3.5 (#1748) 2020-02-03 00:10:48 +02:00
billchenchina 90eeb40ae8 Add base_file_url support for telegram.ext.Updater (#1679)
Co-authored-by: Noam Meltzer <tsnoam@gmail.com>
2020-02-02 23:47:02 +02:00
Bibo-Joshi 6d9d11b8bd Handler persistence for nested ConversationHandlers (#1711)
* Handler persistence for nested ConversationHandlers

* Add tests for persistence w/ nested CHs
2020-02-02 22:31:56 +01:00
Bibo-Joshi f6b663f175 bot_data as global memory (V12 version of #1322) (#1325)
* Update AUTHORS.rst

* Update AUTHORS.rst

* Add bot_data to CallbackContext as global memory

* Minor fixes in docstrings

* Incorp. req. changes, Flake8 Fixes

* Persist before stop

* Fix CI errors

* Implement #1342 for bot_data

* Add check pickle_persistence_only_bot similar to #1462

* Fix test_persistence

* Try dispatching error before logging it

* Fix test

Co-authored-by: Eldinnie <Eldinnie@users.noreply.github.com>
2020-02-02 22:20:31 +01:00
Noam Meltzer 43bfebb150 Update copyright date to 2020 (#1746) 2020-02-02 23:08:54 +02:00
Jelle Besseling 743e2fce07 Add --with-upstream-urllib3 option to remove vendored version (#1725)
Co-authored-by: Noam Meltzer <tsnoam@gmail.com>
2020-02-02 22:56:25 +02:00
Shreyas Thirumalai 4c2a3d07ce Remove duplicate entries from docs. (#1739)
Fixes #1726
2020-02-02 20:35:52 +01:00
Poolitzer 423794f473 fixing message.link (#1741)
* fixing message.link

* improving if clause
2020-02-02 20:27:53 +01:00
Bibo-Joshi a397e6c3c6 Doc fixes (#1642)
* Add missing DispatcherHandlerStop to docs

* Forgot to stage new file ...

* update docstring for bot.edit_message_*

* make job callback docs context based

* Flake8

* Fix doc strings of message.reply_

* Update thumb size docs

* Add missing DispatcherHandlerStop to docs

* Forgot to stage new file ...

* update docstring for bot.edit_message_*

* make job callback docs context based

* Flake8

* Fix doc strings of message.reply_

* Update thumb size docs

* Update docs on InlineQuery.query length

* Minor doc updates

* change module to class in to_float_timestamp doc string
2020-02-02 20:20:54 +01:00
Bibo-Joshi 7cde6ca268 temporarily skip tests failing b/c missing api 4.5 (#1738) 2020-01-30 20:57:16 +02:00
Bibo-Joshi 408062dd43 Add note on how to run test_official to contrib guide (#1740) 2020-01-29 22:43:57 +02:00
Poolitzer d96d233dc5 dropping 2.7, 3.3, 3.4 support from setup.py and README.rst (#1734)
Fixes #1720
2020-01-26 23:47:52 +02:00
Bibo-Joshi 3eb2cef600 Make Filters.text accept leading slash (#1680)
Fixes #1678
2020-01-26 23:19:38 +02:00
Poolitzer 0b87f4b274 contibuting guide: warning about adding requirements (#1718) 2020-01-26 23:15:42 +02:00
Bibo-Joshi 0df526d390 jobqueue: Log datetimes correctly (minor change) (#1714) 2020-01-26 23:08:33 +02:00
Bibo-Joshi cb9af36937 Fix None check in JobQueue._put() (#1707)
fixes #1701
2020-01-26 23:07:17 +02:00
Poolitzer fbb7e0e645 No more unitests for py2.7 (#1731)
Still not removing any py2.7 specific code, but no reason to waste precious CPU and unitest time on py2.7.
2020-01-26 23:01:29 +02:00
Eana Hufwe d9d65cc2ac Add poll messages support to filters (#1673) 2020-01-26 22:57:48 +02:00
Bibo-Joshi 62f514f068 CallbackContext: Expose dispatcher as a property (#1684)
Co-authored-by: Poolitzer <25934244+Poolitzer@users.noreply.github.com>
2020-01-26 22:55:00 +02:00
David Auer 08bbeca8ec Fix typo in example text (#1703) 2020-01-26 22:35:34 +02:00
Mayur Newase 38b9f4b9bc Dispatcher.__init__: Remove double assignmed to self.job_queue (#1698)
Co-authored-by: mayur741 <mayur@wipadika.com>
2020-01-26 22:34:25 +02:00
Viktor Oreshkin 3d59b2f581 Docstring fix: thumb limits were changed with Bot API 4.2 (#1669) 2020-01-26 22:30:26 +02:00
rizlas e3c8466e41 Rename enocde_conversations_to_json() -> enocde_conversations_to_json() (#1661)
Fixes #1660
2020-01-26 22:24:00 +02:00
compSciKai 1d92f52c6a Minor documentation fix (#1647) 2020-01-26 22:19:59 +02:00
Bibo-Joshi 33280a7fe0 Add missing name for Filters.update classes (#1632) 2020-01-26 22:18:29 +02:00
Poolitzer 4b5ba15d31 both google python style links have been moved (#1624)
I choose https://sphinxcontrib-napoleon.readthedocs.io/en/latest/example_google.html, based on https://web.archive.org/web/20160322212330/http://www.sphinx-doc.org/en/stable/ext/example_google.html
and http://google.github.io/styleguide/pyguide.html based on https://web.archive.org/web/20160304111857/https://google.github.io/styleguide/pyguide.html
2020-01-26 22:16:19 +02:00
Poolitzer d2466f1e6e CI: Fix running on master after push + official can fail (#1716)
allowing official to fail is only temporary until we'll add the latest bot api support
2020-01-26 22:07:24 +02:00
Bibo-Joshi 883c6b5901 Add dispatcher argument to Updater (#1484) 2020-01-26 21:59:47 +02:00
Noam Meltzer 1e7f4fae6f Bump version to v12.3.0 2020-01-11 21:21:46 +02:00
Noam Meltzer dae5ab47a0 CHANGES.rst: Update towards v12.3.0 release 2020-01-11 21:08:03 +02:00
Bibo-Joshi a9d9b1d750 Add #1653 to changelog 2020-01-11 20:57:58 +02:00
Hinrich Mahler 90496f70a5 Prepare for v12.3.0 2020-01-11 20:57:58 +02:00
tobiaswicker 940b42e048 ConversationHandler: Fix wrong signature call for timeout handlers
Fixes #1652

Co-authored-by: Eldinnie <Eldinnie@users.noreply.github.com>
2020-01-11 20:51:31 +02:00
Poolitzer a582515766 README.rst: replace travis and appveyor with github (#1645) 2020-01-11 20:47:21 +02:00
Eldinnie 3d42df3366 Fix documentation about return values in message (#1656)
* Fix documentation about return values in message

* flake8 satisfaction
2019-12-16 14:22:11 +01:00
Poolitzer 2c67a9833b add private /c links to message.links object (#1619)
* add private /c links to message.links object

* fixing ids for basic groups

* fixing ids for non basic chats and the test

* Improve tests for Message.link

* Simplify id_to_link
2019-11-29 13:50:44 +01:00
Bibo-Joshi 5e8a961669 Refactor msg_in (#1631)
* Revert "Add msg_in filter (new) (#1570)"

This reverts commit 34bdbc632a.

* Refactor msg_in, add Filters.caption on the fly

* Update docstrings

* Fix copy-paste typo
2019-11-29 13:09:44 +01:00
Bibo-Joshi a5ba64becb Remove checks for None on assignement for opt args (#1600) 2019-11-23 18:05:03 +02:00
Noam Meltzer 2a3169a22f Fix deprecation warning with Python 3.8 triggered by vendored urllib3 (#1618)
Fixes #1586
2019-11-16 14:37:15 +02:00
Poolitzer 894d8281ab github workflow: add a cron job (#1615) 2019-11-16 00:19:47 +02:00
Noam Meltzer 2fdf48023b github workflow: give pre-commit its own job (#1612) 2019-11-15 23:35:44 +02:00
Paolo Lammens 4e717a172b Fix UTC/local inconsistencies for naive datetimes (#1506) 2019-11-15 22:51:22 +02:00
Noam Meltzer 10c9ec2313 workflow: run test-official in its own job (#1607) 2019-11-09 22:38:23 +02:00
Noam Meltzer 096a7c3593 Allow PRs to test (#1606) 2019-11-09 22:13:02 +02:00
Noam Meltzer e9d9f01bd4 Fix windows actions (#1605)
* Stop testing with ujson

* Fix timing issue with test_delete_message

* ignore pip deprecation warning. hopefully it will fix windows+py2.7

* telegram replies to deleteing old messages are not consistent
2019-11-09 20:33:51 +02:00
Jasmin Bom 8b4b22cc89 Implement Github Actions CI (#1556)
* Add test workflow

* Attempt github grouping

* Improve bot info fetching

- Add support for b64+json encoded github secret with all the vars
- Add bot_name and bot_username since it's needed for a proper get_me test

* Improve test workflow a lot

- Add coverage
- Install ujson
- test_official only run on in single job
- Pass bot info to pytest

* Improve github grouping by having shorter titles

* Run pytest with coverage

* Improve coverage report

* Proper exitcode behaviour for pytest

* Proper test official handling

* Proper error handling

* Skip jobqueue tests on windows

* run coverage tests even if nocoverage ones fail

* Skip messagequeue tests on windows

* Clean up to satisfy flake8

* Run meta tests
2019-10-27 14:28:33 +01:00
Bibo-Joshi b294c92bad question template: Add info about users' group (#1577) 2019-10-27 14:33:30 +02:00
Poolitzer 264de2b7c1 Github actions - notify maintainers about changed examples (#1555) 2019-10-27 01:42:47 +03:00
Julian Ste ac64027580 Fixed comments in examples (#1566) 2019-10-27 01:15:09 +03:00
Bibo-Joshi 34bdbc632a Add msg_in filter (new) (#1570)
Closes #1144
2019-10-27 01:12:54 +03:00
Bibo-Joshi bbcff96804 Doc fixes (#1572)
Fixes #1576
2019-10-27 01:04:48 +03:00
Bibo-Joshi 93449443b2 Add *args, **kwargs to Message.forward() (#1574) 2019-10-27 01:00:27 +03:00
Poolitzer 8cdb20a85a updating example to V12 (#1579) 2019-10-27 00:51:29 +03:00
Jannes Höke 6fddb49af5 📝 Update section "Getting help" 2019-10-22 00:04:31 +02:00
Jannes Höke b0aef0c718 🔀 Update issue templates (#1569)
* 📝 Update issue templates

* 👌 Update question template

* 🔥 Delete old issue template
2019-10-21 23:51:58 +02:00
Iulian Onofrei 88eccc6608 Add MAX_PHOTOSIZE_UPLOAD size limit constant (#1560)
* Add MAX_PHOTOSIZE_UPLOAD size limit constant

* Add the other source of the constants' values
2019-10-17 22:24:44 +02:00
Lorenzo Rossi 3d8771bbdf 🔀 Add mutex protection on ConversationHandler (#1533)
* Add mutex protection on ConversationHandler

* Remove timeout job before child update

* Make locks private

* Add conversation timeout conflict test
2019-10-17 00:03:53 +02:00
Iulian Onofrei 7152b5aaf9 Fix CONTRIBUTING.rst not to install requirements as root (#1558) 2019-10-16 21:50:38 +03:00
Noam Meltzer 98147fce32 Bump version to v12.2.0 2019-10-14 21:12:13 +03:00
Poolitzer e54e9f2347 moving flake config to one file (#1546) 2019-10-14 11:10:51 +03:00
Poolitzer 3545139dd7 adding to_dict test (#1544)
fixes #1541
2019-10-12 23:40:42 +03:00
Poolitzer d0c27e2d46 adding 3.8 to travis and appveyor (#1543)
Fixes #1542
2019-10-12 16:12:41 +03:00
Paolo Lammens 3318239cf6 tests: refactor `test_commandhandler.py` (#1408)
- Improved usage of fixtures
    - Replaced fixtures for directly callable factories where
    multiple mock objects were needed in the same test function
    - Extracted fixtures where possible (in place of literals or
    global constants)
  - Moved some fixtures to ``conftest.py`` to be used by other
  modules
  - Made a common base class for both ``TestCommandHandler`` and
  ``TestPrefixHandler``, extracting common methods, patterns and
  signatures
    - The extracted patterns in test methods have been named with
    leading ``_test``
  - Extracted other repeatedly used test utilities into functions
  (e.g. ``is_match``) and methods (e.g. ``make_default_handler``)
2019-10-12 16:11:09 +03:00
Bibo-Joshi aadb6df271 Nested ConversationHandlers (#1512)
Fixes #405
2019-10-11 22:59:36 +03:00
Noah Evans 2cc9aac7dc Fix Bot.to_dict to use proper first_name (#1525)
Fixes #1519
2019-10-11 22:37:28 +03:00
Trainer Jono 1d007b1b60 Fix typos in examples (#1537) 2019-10-11 21:10:21 +03:00
Noam Meltzer 3257148d13 travis.yaml: TEST_OFFICIAL removed from allowed_failures
it was originally added to allowed_failures until we completed API 4.4
support
2019-10-11 21:02:32 +03:00
Poolitzer 805a798b50 Fix CI failures due to non-backward compat attrs depndency (#1540) 2019-10-11 21:01:25 +03:00
Noam Meltzer e60a42010b Bump version to v12.1.1 2019-09-17 11:30:52 +03:00
Noam Meltzer ae88129f0f Revert accidental change to the git revision of the urllib3 submodule (#1517)
Fixes #1516
2019-09-17 11:25:54 +03:00
Noam Meltzer 3812251dac small fix for documentation to compile 2019-09-13 22:31:02 +03:00
Noam Meltzer e1193425ca Bump version to v12.1.0 2019-09-13 22:29:06 +03:00
Joscha Götzer ccf5e6c692 Implemented Tools for deep linking (#1049) 2019-09-13 22:09:05 +03:00
zeshuaro 32dd415fb8 Add instance methods to Animation and ChatPhoto (#1489)
get_file, get_small_file, get_big_file
2019-09-13 22:07:56 +03:00
Bibo-Joshi f13aeaa2a1 Doc fixes (#1499) 2019-09-13 21:49:04 +03:00
Bibo-Joshi 4cd07361d1 Inline Keyboard example (#1502)
Supersedes. aka. fixes #884
2019-09-13 21:43:03 +03:00
Paolo Lammens b38a1840b2 docs: Add info on documentation to CONTRIBUTING.rst (#1500)
I didn't find this information elsewhere in the repository;
I thought it might be useful for new contributors.
2019-09-09 10:01:04 +02:00
Bibo-Joshi fba3cc90d9 API 4.4 small code cleanup (#1510) 2019-09-07 12:42:26 +03:00
Bibo-Joshi 965ad17af8 API 4.4 (#1464) 2019-09-06 22:41:43 +03:00
Poolitzer d5399de99b raise attribute errors when someone tries to assign values to chat/us… (#1495)
* raise attribute errors when someone tries to assign values to chat/user_data (closes #1402)

* fix test

* something something not switching entirely and using a messy patch and no not anymore and argh
2019-09-05 22:48:28 +02:00
Bibo-Joshi 280306d1e9 Remove note about V12b in examples (#1503) 2019-09-05 13:51:26 +02:00
Noam Meltzer c84e21d8eb Bump version to v<VERSION> 2019-08-29 21:33:51 +03:00
Noam Meltzer 738e5a0784 V12 changelog (#1480)
* python3.4 is no longer supported

* Prepare CHANGES.RST & README.rst for v12.0.0 release

* CHANGES.rst: small fix

* Add Bibo-Joshi to Credits

* update the changelog - in anticipation for release

* remove line about api 4.4

* fix spelling

* move too long descriptions to wiki
2019-08-29 19:30:29 +02:00
Poolitzer ec6dc7fa10 fix typo in PicklePersistence (#1488)
* fix single typo

* fix unitests for picle singe_file -> single_file
2019-08-29 19:09:38 +02:00
Noam Meltzer b71196dad3 Run test_official in a seperate travis job (#1491) 2019-08-28 22:58:58 +03:00
Bibo-Joshi 425912da4a Use UTC in from_timestamp (breaking change) (#1485) 2019-08-28 22:06:41 +03:00
Poolitzer 2c92c356b8 Error handlers now handle all errors (#1483)
* python3.4 is no longer supported

* Prepare CHANGES.RST & README.rst for v12.0.0 release

* CHANGES.rst: small fix

* Add Bibo-Joshi to Credits

* improving error_handler

* fixing affected tests
2019-08-27 09:09:02 +02:00
Noam Meltzer f379a34ccd Run test_official only on py3.7 2019-08-24 01:13:40 +03:00
Noam Meltzer 4328eaefb2 Fix test_photo.py (#1479)
Telegram had changed their server behaviour again
2019-08-24 01:10:30 +03:00
Noam Meltzer 79dc6edf25 Merge remote-tracking branch 'origin/V12' 2019-08-24 01:04:10 +03:00
Bibo-Joshi c7e9281068 Make MessageEntity objects comparable (#1465) 2019-08-24 00:54:04 +03:00
Eldinnie edad6e8b53 Add a prefix to threads (#1358)
* Add a prefix to worker thread

This adds a prefix of `Bot:<id>:worker:` to the name of the worker threads.
Fixes #1332

* Also prefix other threads

* Fix test

* Fix test and remove helper method.
2019-08-23 22:57:08 +02:00
zeshuaro 7eb7c30741 updated inputmedia docstring (#1436) 2019-08-23 22:03:43 +02:00
Eldinnie 3ae14dda80 Remove deprecated regexhandler from examples (#1426) 2019-08-23 22:32:12 +03:00
Eldinnie ac60d057a5 All api 4.2 and 4.3 changes (#1418) 2019-08-23 22:20:41 +03:00
Marchello00 e492d5b97b Fix send_location() - latitude may be 0 (#1437)
Fixes #1435
2019-08-23 22:13:29 +03:00
René Filip 3afb0ae6c3 Improve timer_bot.py example (#1440)
Fixes #1439
2019-08-23 22:09:46 +03:00
Ales Dokshanin 179cf14bd8 #1410 Call task_done() on update queue after update processing finished (#1428) 2019-08-23 21:54:07 +03:00
Bibo-Joshi a1eabc0cae Fix for #1452 (#1462)
Dispatcher force updating persistence object's chat data attribute
2019-08-23 21:52:14 +03:00
Bibo-Joshi 5e90231f4e Make updates persist even on DispatcherHandlerStop (#1463) 2019-08-23 21:38:29 +03:00
Zhuoyun Wei 2cb6377dab examples/conversationbot2.py: Use context.error in error() (#1474) 2019-08-23 18:24:19 +03:00
Bibo-Joshi 316d046628 Indent return statement in parse*entities (#1473) 2019-08-23 18:20:07 +03:00
Marco Marinello 5e0e4c01ff Prepare debian packetization (#1476) 2019-08-23 17:47:00 +03:00
Bibo-Joshi 24546bda67 Make all categories lower case to avoid KeyErrors (#1475) 2019-08-18 18:39:29 +03:00
Pieter Schutz d70577b9cf remove 3.4 from Appveyor 2019-06-05 22:52:26 +02:00
Pieter Schutz 3fc57479f3 Merge branch '4.3' into RC1 2019-06-05 22:19:48 +02:00
Pieter Schutz e11efa2e5b Add bot api 4.3
Add LoginUrl to InlineKeyboardButton

Add reply_markup to message
2019-06-05 22:15:32 +02:00
Pieter Schutz d84551134b Merge branch 'api4.2-poll' into RC1 2019-06-05 22:11:44 +02:00
Pieter Schutz cebd2d6a86 test poll de_json 2019-06-05 22:11:28 +02:00
Pieter Schutz 725c21b88d API 4.2 changes
actually works now

Add tests

Fix flake8 issues.

Add poll argument to Update.

Fix pre-commit config
Finalizing 4.2

No notify on pin
2019-06-05 15:00:07 +02:00
Noam Meltzer 9d005d5124 jobqueue: Add docstring note about intervals and DST (#1397)
Fixes #1381
2019-04-27 20:10:56 +02:00
Jason Rhinelander 2cde878d1e Fix webhook listen (#1383)
The `listen` argument wasn't being passed through to Tornado; this fixes
it.

Fixes #1382
2019-04-15 10:28:41 +03:00
Jasmin Bom 984bea16d1 Fix trailing whitespace (flake8 error) 2019-04-05 20:03:44 +02:00
Jasmin Bom 474ff8ae41 Add missing message.text check in PrefixHandler check_update (#1375)
* Add missing message.text check in PrefixHandler check_update

* Remove message length check
2019-04-05 12:59:50 +02:00
Loo Zheng Yuan 2ed4cbd26d Fix #1366: _trigger_timeout() missing 1 required positional argument: 'job' (#1367)
* Fix #1366: _trigger_timeout() missing 1 required positional argument: 'job'

* Add comments
2019-04-05 12:59:32 +02:00
Jasmin Bom 7944805627 Fix bot tests
- telegram how throws an error if you try to reply to nonexistent msg
- telegram also changed the message when you try to delete old msg
2019-04-01 13:05:45 +02:00
Jasmin Bom b5891a6a61 Making merged filters short-circuit (#1350)
* Making merged filters short-circuit

* Add notes to docs about short-circuiting
2019-03-14 09:03:21 +01:00
Jasmin Bom df813c46e1 Pin pre-commit pylint to v2.3.0
Fixes issue seen at https://travis-ci.org/python-telegram-bot/python-telegram-bot/jobs/499853384#L702
2019-02-28 22:02:08 +01:00
Eldinnie 36a74da4f4 fix setting bot on ShippingQuery (#1355)
* fix setting bot on ShippingQuery

* Fix test to test de_json
2019-02-23 21:33:03 +01:00
Eldinnie 0c10c537f7 fix typo in master
[CI skip]
2019-02-23 17:39:04 +01:00
Jasmin Bom 26ce9bb343 Documentation fixes (#1348)
* Clarify InlineKeyboardButton callback-data docstring

Fixes #1267

* Improve documentation slightly

- Prettier changelog
- Link to examples on frontpage
- Link to wiki on frontpage
- Put telegram.ext in own sidebar thingy

* Improve ext.Filters documentation

Superseeds #1089

- Remove `:obj:Filter` as it's pretty obvious that it's a filter since it's in this module. It also made the html output about 1/3 times longer to scroll through.
- Add an __all__ to reorder so Filter is at the top instead of BaseFilter
- Add a proper docstring for document that documents the attributes (this is the #1089 part)
- Also fix a couple of grammar errors.

* Fix indentation in telegram.rst

* Add `git describe --long --tags` to the `python -m telegram` output

* Use admonition for examples to make them *pop* better

* Remove automodule telegram

Sphinx was whining a lot and it doesn't actually seem to be needed in any way?

* Fix Filters.document docstring per CR

Co-Authored-By: jsmnbom <jsmnbom@gmail.com>

* Fix spelling error in docs index

Co-Authored-By: jsmnbom <jsmnbom@gmail.com>

* Setting needs_sphinx to 1.7.9

so we don't have more issues with incongruent versions

* Fixed last warnings

* Make pre-commit happy
2019-02-18 20:04:52 +01:00
Jasmin Bom 39d686b1a1 Tiny spelling fix in CHANGES.rst [ci skip] 2019-02-14 12:31:00 +01:00
Kirill Vasin 60f2044bbd Entry returns None ends conversation (#1270)
* Fix unresolvable promises

* added async test and description

* added test_none_on_first_message for conv_handler

* Small change in ConversationHandler docstring

* Fix test to work with new commandhandler
2019-02-14 12:29:58 +01:00
Jasmin Bom dda7ca18cd Update CHANGES.rst
Also include #1270 even though not merged yet, but it should be very soon :)
2019-02-14 12:03:20 +01:00
Jasmin Bom 07c51d236b Fix spelling error in example notice 2019-02-14 11:53:09 +01:00
Jasmin Bom 9f1eccf569 Merge branch 'master' into V12 2019-02-14 11:52:31 +01:00
Eldinnie cd7c642f49 Add WAITING state and behavior (#1344)
* Add WAITING state and behavior

* Remove `run_async_timeout` and `timed_out_behavior` arguments
* replace with `WAITING` constant and behavior from states
* never wait for promise to resolve (will hang up entire update queue
* see #1250 for discussion

* Fixing pytest version to 4.2.0

Pytest 4.2.1 has a weird bug on top level collect in 4.2.1 Fixing version to 4.2.0
2019-02-14 11:00:21 +01:00
Bibo-Joshi f7abb21323 Adjust persistence on exit behaviour (#1312)
* Adjust persistence of exit behaviour

* Fix binary operators in on_flush

* Fix docstring

* Add test
2019-02-13 23:30:29 +01:00
Eldinnie 7e2dbdd4b3 Fix #1297 (#1342)
* Fix #1297

This makes a deepcopy of the user_data and chat_data dict as suggested by @Bibo-Joshi

* Fix dictpersistence aswel.
2019-02-13 23:28:48 +01:00
Jasmin Bom b64698e4b6 Use warnings.warn for conversationhandler warnings. (#1343)
* FIXED: ConversationHandler errors were logged to root logger

* Use warnings.warn instead of self.logger.warning.
2019-02-13 23:28:23 +01:00
Ambro d0936f76ad Only one warning for multiple CallbackqueryHandler's on ConversationHandler (#1319) 2019-02-13 22:08:49 +01:00
Jasmin Bom da342af7ed Small flake8 fixes 2019-02-13 16:04:48 +01:00
Jasmin Bom 446c54cf8d Bump to version 12.0.0b1 2019-02-13 13:41:04 +01:00
Jasmin Bom f5bfe2f29c Update example comments and docstrings to note the V12 beta 2019-02-13 13:38:07 +01:00
Eldinnie b02b68880f Make dispatcher use one context per update (#1283)
* Make dispatcher use one context per update

It gives user the option to `overload` context with their own properties in a lower group handler if they like

* Improve callbackcontext & run_async docstring

- Add note about how you can add custom attributes to context.
- Add warnings about how run_async and custom attributes should not be used together.

* Small documentation improvements. [ci skip]
2019-02-13 12:18:37 +01:00
Eldinnie 2c5eade4f0 Update Filters, CommandHandler and MessageHandler (#1221)
* update_filter attribute on filters

Makes it possible to have filters work on an update instead of message, while keeping behavior for current filters

* add update_type filter

* Messagehandler rework

- remove allow_edited (deprecated for a while)
- set deprecated defaults to None
- Raise deprecation warning when they're used
- add sensible defaults for filters.
- rework tests

* Commandhandler rework

* Remove deprecation test from new handler

* Some tweaks per CR

- rename update_types -> updates
- added some clarification to docstrings

* run webhook set test only on 3.6 on appveyor

* update_filter attribute on filters

Makes it possible to have filters work on an update instead of message, while keeping behavior for current filters

* add update_type filter

* Messagehandler rework

- remove allow_edited (deprecated for a while)
- set deprecated defaults to None
- Raise deprecation warning when they're used
- add sensible defaults for filters.
- rework tests

* Commandhandler rework

* Remove deprecation test from new handler

* Some tweaks per CR

- rename update_types -> updates
- added some clarification to docstrings

* run webhook set test only on 3.6 on appveyor

* Changes per CR

* Update travis to build v12

* small doc update

* try to make ci build version branches

* doc for BaseFilter

* Modify regexfilter and mergedfilter

Now returns a list of match objects for every regexfilter

* Change callbackcontext (+ docs)

* integrate in CommandHandler and PrefixHandler

* integrate in MessageHandler

* cbqhandler, iqhandler and srhandler

* make regexhandler a shell over MessageHandler

And raise deprecationWarning on creation

* clean up code and add some comments

* Rework based on internal group feedback

- use data_filter instead of regex_filter on BaseFilter
- have these filters return a dict that is then updated onto CallbackContext instead of using a list is before
- Add a .match property on CallbackContext that returns .matches[0] or None

* Fix and add test for callbackcontext.match

* Lots of documentation fixes and improvements [ci skip]
2019-02-13 12:07:25 +01:00
Jasmin Bom 950ec35970 Remove message decorator to fix default timeouts. (#1156)
* Remove message decorator to fix default timeouts.

* Make message wrapper method private.

* Make tests pass

* Fix callbackquery shortcuts

Closes #1180

* Fix callbackquery shortcut tests

* Fix merge

* Address CR

* Add missing default timeout=20 for some bot file uploads

* Fix wrong return value in convhandler

Probably stems from a combination of bad merge plus quickly merged hacktoberfest PR.
2019-02-13 11:37:13 +01:00
Jasmin Bom d33e1d9913 Small flake8 fix 2019-02-09 18:45:34 +01:00
Jasmin Bom 2e203e41e4 Merge branch 'master' into V12 2019-02-09 18:45:00 +01:00
Jasmin Bom e54a3188ce Revert "Fix bug: unable to save jobs with timezone aware dates (#1308)"
This reverts commit 23fe991b

See https://github.com/python-telegram-bot/python-telegram-bot/pull/1308 for more details.

NOTE: Keeping Ambro17 in AUTHORS.rst as I'm pretty sure they've contributed more since then :)
2019-02-09 18:44:04 +01:00
Jasmin Bom 710f43a23a travis: Use xenial dist for pypy
Cryptography started complaning about old openssl - hopefully xenial has a newer version
2019-02-09 18:26:17 +01:00
Jasmin Bom 27b757df32 Reorder some stickset tests to hopefully make them pass 2019-02-09 18:21:12 +01:00
Jasmin Bom 66e43c5932 Fix a bunch of flake8 W504 errors 2019-02-08 20:55:40 +01:00
Jasmin Bom 7fcbfc19f5 Mark location sending test as xfail as it seems to fail randomly 2019-02-08 20:22:44 +01:00
Jasmin Bom a60c07f549 Update test animation size
Telegram must've again chagned internal stuff
2019-02-08 20:21:24 +01:00
Jasmin Bom 1b52e6148e Merge branch 'master' into V12 2019-02-08 12:49:28 +01:00
Ambro 487bce18dd Improve regex filter docstring and avoid compiling compiled regex (#1314)
* Improve regex docstring and add test case

* Add Ambro17 as contributor

* rename regex filter

* Fix sphinx documentation for Filters.regex

* Add spacing to render Note with blue background
2019-02-08 11:12:49 +01:00
Gregory Petukhov 5c45e469d5 Fix #1335: Message.MESSAGE_TYPES does not contain "left_chat_member" (#1336) 2019-02-08 11:02:54 +01:00
Jasmin Bom 25e5449e97 Fix TestDispatcher::test_error_handler using pytest >= 4.0 2019-01-30 20:56:15 +01:00
Jasmin Bom a8bade4d73 Fix a bunch of tests
Looks like it's once again time for: Telegram changed some weird internal stuff and how thumbnails take up either 4 times as much space or half as much space. Oh and they also seemingly randomized the width and height of said thumbnails....
2019-01-30 20:40:53 +01:00
Jasmin Bom e08afe7fb2 Fix flake8 errors that only show in CI?? 2019-01-30 20:20:35 +01:00
Jasmin Bom 9817310788 Reflow docstrings in replykeyboardmarkup to satisfy flake8 2019-01-30 19:50:33 +01:00
Jasmin Bom ed33c4a7a9 Merge remote-tracking branch 'origin/master' 2019-01-30 19:45:37 +01:00
Jasmin Bom 1ee53e9e17 Updating the pylint that pre-commit uses
Fixes #1321
2019-01-30 19:42:57 +01:00
Gregory Petukhov 3e8d71582d Fix #1328: custom timeout argument does not work (#1330)
* Fix #1328: custom timeout argument does not work

* Remove unused import
2019-01-30 19:38:15 +01:00
Tanuj c03160c07f Add convenience classmethods for InlineKeyboardMarkup (fixes #1186) (#1260)
* Add convenience classmethods for InlineKeyboardMarkup (#1186)

* Switch to row and column methods

* Also add convenience classmethods for ReplyKeyboardMarkup

* Add some simple tests
2019-01-04 21:04:45 +01:00
Ambro 23fe991b85 Fix bug: unable to save jobs with timezone aware dates (#1308)
* Fix bug on jobs with timezone aware dates

* Add Ambro17 as colaborator
2019-01-04 20:29:07 +01:00
Bibo-Joshi 7eeb670a59 Fix check for effective chat/user in persistence (#1303) 2018-12-05 00:12:43 +01:00
Bibo-Joshi f23298a13b Fix typos in telegram/bot.py (#1305) 2018-12-04 15:06:48 +01:00
Konstantin Zemlyak 92f407bfb3 Update setup.py (#1306) 2018-12-04 15:06:22 +01:00
Steve Sandke 0cf0cccbc5 Fix description for JobQueue's run_daily and run_repeating methods. (#1299) 2018-11-22 13:03:58 +01:00
Jasmin Bom 378784f55e Fix persistence with non telegram.Update updates (#1271)
* Allow persistence with no telegram.Update updates

For use with TypeHandler

* Add test
2018-11-09 11:44:20 +01:00
Pieter Schutz 384173115f Merge branch 'master' into V12 2018-11-01 11:45:51 +01:00
Pieter Schutz ea5b301b59 fix pre-commit hooks 2018-11-01 11:08:09 +01:00
Pieter Schutz 9b66681ee4 fix pre-commit hooks 2018-11-01 11:08:09 +01:00
Pieter Schutz 92e7427689 Merge remote-tracking branch 'origin/master' 2018-11-01 10:53:46 +01:00
Pieter Schutz f82ceee777 Merge remote-tracking branch 'origin/master' 2018-11-01 10:53:46 +01:00
Pieter Schutz d2e2fe9ccc fix last flake8 errors 2018-11-01 10:52:36 +01:00
Pieter Schutz 76a72e9742 fix last flake8 errors 2018-11-01 10:52:36 +01:00
Noam Meltzer cf69a234d4 fix accidental commit to submodule config 2018-11-01 11:25:52 +02:00
Noam Meltzer eaf6dc2b88 fix accidental commit to submodule config 2018-11-01 11:25:52 +02:00
Noam Meltzer 9596343efd pep8 fixes 2018-11-01 11:18:07 +02:00
Noam Meltzer 30cc0f8cf9 pep8 fixes 2018-11-01 11:18:07 +02:00
Pieter Schutz f252436cd4 Merge remote-tracking branch 'origin/master' into V12 2018-11-01 09:32:55 +01:00
Jasmin Bom c9630ee8c5 Add Conflict error (HTTP error code 409) (#1154)
* Add conflicting bot id to conflict error message.

* Add test and comment to conflict error

* Don't extract bot id in Conflict exception per PR comments
2018-10-29 22:08:52 +01:00
Eldinnie 9d99660ba9 Change MAX_CAPTION_LENGTH to 1024 (#1262)
* update MAX_CAPTION_LENGTH

Telegram silently changed the max length for captions to 1024 chars.

* Update test_constants.py

* change docstrings to reflect new length

* remove message

* clear message and proper match
2018-10-16 19:51:57 +02:00
Jasmin Bom eca0ccf6b3 Update tests to support new test bots 2018-10-14 12:15:27 +02:00
Pavel Shakhov 9ece7fdb1c Mistake in MessageQueue.__call__'s docstring (#1249) 2018-10-08 15:36:59 +02:00
Evan Haberecht 4861d1a20d Removed unneccessary else and replaced with comment (#1247)
* Resolved issue #1163: Removed unneccessary else and replaced with comment

* Added myself to AUTHORS.rst
2018-10-08 08:18:33 +02:00
simonvorobjev dbf364e168 Allowed to use Handlers on conversation timeout (#1217)
* handler for ConversationHandler.END (timeout one) #1136

* review fixes

* review fixes

* review fixes

* review fixes

* docs and tests

* fixing stuff

* Fix problem

* fix conftest

* now it should work

* Add ConversationTimeoutContext

As discussed in the developers group. Use a class as the jobs context over using a dict.

* less verbosity
2018-10-04 08:58:40 +02:00
dbxnr d6d0dec6e0 remove extra else clause (#1239)
Fix #1236
2018-10-02 11:29:30 +02:00
Eldinnie 0bbca65a95 add sleep to bailout error test (#1241)
Hopefully it won;t hit the race condition so often on appveyor
2018-10-02 09:00:38 +02:00
Holden Oullette 1d715f0d36 Removed empty quotes (#1237) 2018-10-01 23:29:46 +02:00
Eldinnie f6f8667d6c add codacy badge to readme (#1232) 2018-10-01 22:16:48 +02:00
Pieter Schutz 8731365911 Merge branch 'master' into V12 2018-10-01 21:12:21 +02:00
Jasmin Bom d9ae4be2b3 Add 3.7 to travis and make pypy allowed_failures (#1215)
* Add 3.7 to travis build matrix using workaround

See https://github.com/travis-ci/travis-ci/issues/9815 for workaround discussion

* Add 3.7 to pypi classifiers

* Format build matrix differently

* Try adding pypy6.0.0 to travis build matrix

* Add py3.7 to appveyor

* Try pypy 5.10.1 instead

6.0.0 isn't on travis yet: https://github.com/travis-ci/travis-ci/issues/9542

* pypy2-5.10.0 isn't on travis yet either...

* allow failures on travis pypy
2018-10-01 20:50:44 +02:00
Pieter Schutz b5a3d7852a try to make ci build version branches 2018-10-01 11:48:10 +02:00
Pieter Schutz 3d8ab23d66 try to make ci build version branches 2018-10-01 11:46:48 +02:00
Pieter Schutz 6c36316aed Change yamls to build v12 on travis an appveyor 2018-10-01 10:25:06 +02:00
Jasmin Bom 4c66ba3a8d Allow filenames without dots in them when sending files (#1228)
* Fix issue 1227 by allowing filenames without dots in them

* Touch new test data file

* Satisfy flake8
2018-09-30 12:07:17 +02:00
reablaz c714a177d1 Update data.py to be compatible with example (#1213)
* Update data.py to be compatible with example

for now, if you process personal_info with example code, then you got an error if there is no set option to get native fist and last name.

setting default value will allow to process personal_info without native name/surname transation

* fixing line length

i hope i understood right this. sorry for delay, just starting using github!
2018-09-26 15:46:25 +02:00
Ehsan 3829666a53 add text mention for message parse (#1206)
* add text mention for message parse

* add author

* Update .gitignore
2018-09-25 20:07:55 +02:00
Pieter Schutz 9c1b493f37 Make persistence example context-based 2018-09-21 13:57:44 +02:00
Pieter Schutz af2d716129 Fix test_persistence
* To work with new CommandHandler
* To make tests context-based
2018-09-21 13:57:36 +02:00
Jasmin Bom 5252a493cb Pass check result into handle_update
Missed during merge
2018-09-21 09:20:35 +02:00
Jasmin Bom e75615cbf6 Revert "Revert "CommandHandler overhaul and PrefixHandler added (#1114)""
This reverts commit 9e2357b
2018-09-21 08:57:43 +02:00
Jasmin Bom cf95027308 Revert "Revert "Context based callbacks (#1100)""
This reverts commit f8a17cd
2018-09-21 08:57:01 +02:00
Eldinnie 439790375e Persistence (#1017)
* BasePersistence

* basic construct

* Keep working

* Continue work

Add tests for Basepersistence

* Finish up BasePersistence and implementation

* PickelPersistence and start tests

* Finishing up

* Oops, left in some typings

* Compatibilty issues regarding py2 solved

For Py2 compatibility

* increasing coverage

* Small changes due to CR

* All persistence tests in one file

* add DictPersistence

* Last changes per CR

* forgot change

* changes per CR

* call update_* only with relevant data

As discussed with @jsmnbom

* Add conversationbot Example

* should not have committed API-key
2018-09-20 22:50:40 +02:00
Marcelo G. de Andrade b9f56ca479 fixes comment on examples/conversationbot2.py (#1216) 2018-09-12 21:27:35 +02:00
Jasmin Bom e247fa7c2c Fix uploading files with unicode filenames (#1214)
* Patch urllib3RequestField to make it *not* support RFC2231

* Add new required test data file

* Fix on py2

* Remove weird legacy code from inputfile

Not needed anymore, and also makes it not work... so that was not great
2018-09-10 21:08:05 +02:00
Kirill Vasin b8c288ff4a Make ConversationHandler and run_async work together properly (#1176)
* #1175

* fix issue with timeout

* exception in promise resolve is treated as None result

* removed useless variables
2018-09-10 20:05:45 +02:00
Jasmin Bom bbe633e571 Remove GAE support message
We still kinda support it, but not more so than other providers.
2018-09-10 15:58:25 +02:00
Kirill Vasin f2b06728e9 Replace http.server with Tornado (#1191)
Fixes #1189
2018-09-08 23:25:48 +03:00
Jasmin Bom b2fb4264a3 Small test fixes to make them more stable on travis CI 2018-09-07 16:07:27 +02:00
Noam Meltzer 19591c955a Allow SOCKSConnection to parse username and password from URL (#1211) 2018-09-07 15:21:01 +02:00
Jasmin Bom 259a1faedc Releasing v11.1 2018-09-01 17:27:35 +02:00
Jasmin Bom 09bdb88822 Bot api 4.1 (#1198)
* Fix passport decryption failing at random times

Sometimes a decrypted secret was being treated as b64 and therefore got decoded even further. Fix by decoding b64 right before call to decrypt so we have better control of when not to do it

* Bot api 4.1

Telegram passport 1.1
Added support for middle names.
Added support for translations for documents
Add errors for translations for documents
Added support for requesting names in the language of the user's country of residence
Replaced the payload parameter with the new parameter nonce

NOTE: Scope stuff is NOT implemented, as we wanna STRONGLY encourage users to use the telegram provided SDKs anyway (and not generate telegram auth links in their bot, but rather on a server)

* Minor fixes

* Add hash to EncryptedPassportElement

For use with PassportElementErrorUnspecified apparently
2018-09-01 16:58:08 +02:00
Jasmin Bom 937be3d2e8 Use a dual license file until we can add two files. 2018-08-29 15:49:52 +02:00
Jasmin Bom aa3ebb1180 Add LICENSE.lesser as wheel license
Really we need both the LICENSE and LICENSE.lesser, but we can't until wheel releases a build with https://github.com/pypa/wheel/commit/59976ab294e1b118f42cab404d95df66ed55f7e4 merged.
2018-08-29 15:39:44 +02:00
Jasmin Bom 4473d620de Prepare for 11.0.0 release 2018-08-29 15:21:02 +02:00
Eldinnie 4689a80c2e Bot API 4.0 (#1168)
Telegram Passport (#1174):

- Add full support for telegram passport.
    - New types: PassportData, PassportFile, EncryptedPassportElement, EncryptedCredentials, PassportElementError, PassportElementErrorDataField, PassportElementErrorFrontSide, PassportElementErrorReverseSide, PassportElementErrorSelfie, PassportElementErrorFile and PassportElementErrorFiles.
    - New bot method: set_passport_data_errors
    - New filter: Filters.passport_data
    - Field passport_data field on Message
    - PassportData is automagically decrypted when you specify your private key when creating Updater or Bot.
    - PassportFiles is also automagically decrypted as you download/retrieve them.
- See new passportbot.py example for details on how to use, or go to our telegram passport wiki page for more info
- NOTE: Passport decryption requires new dependency `cryptography`.

Inputfile rework (#1184):

- Change how Inputfile is handled internally
- This allows support for specifying the thumbnails of photos and videos using the thumb= argument in the different send_ methods.
- Also allows Bot.send_media_group to actually finally send more than one media.
- Add thumb to Audio, Video and Videonote
- Add Bot.edit_message_media together with InputMediaAnimation, InputMediaAudio, and inputMediaDocument.

Other Bot API 4.0 changes:

- Add forusquare_type to Venue, InlineQueryResultVenue, InputVenueMessageContent, and Bot.send_venue. (#1170)
- Add vCard support by adding vcard field to Contact, InlineQueryResultContact, InputContactMessageContent, and Bot.send_contact. (#1166)
- Support new message entities: CASHTAG and PHONE_NUMBER. (#1179)
    - Cashtag seems to be things like $USD and $GBP, but it seems telegram doesn't currently send them to bots.
    - Phone number also seems to have limited support for now
- Add Bot.send_animation, add width, height, and duration to Animation, and add Filters.animation. (#1172)


Co-authored-by: Jasmin Bom <jsmnbom@gmail.com>
Co-authored-by: code1mountain <32801117+code1mountain@users.noreply.github.com>
Co-authored-by: Eldinnie <pieter.schutz+github@gmail.com>
Co-authored-by: mathefreak1 <mathefreak@hi2.in>
2018-08-29 14:18:58 +02:00
Jannes Höke 353410242f 🐛 Use '==' operator for integer comparison (#1147) 2018-08-26 20:39:19 +02:00
Dmitry Grigoryev 8acff56145 Fix Filters.regex failing on non-text message (#1158)
* Fix #1115

* Improve regex filter test
2018-08-26 20:39:01 +02:00
Jasmin Bom d4b5bd40a5 Update AUTHORS.rst
Name change, plus adding @eldinnie and I to maintainers.
2018-06-26 19:51:45 +02:00
Marcos Del Sol Vives d2059ed184 Fix ProcessLookupError if process finishes before we kill it (#1126) 2018-06-01 23:27:09 +03:00
Jacob Bom f8a17cddcb Revert "Context based callbacks (#1100)"
This reverts commit 247577b2e2.
2018-05-31 14:22:57 +02:00
Eldinnie 9e2357bc33 Revert "CommandHandler overhaul and PrefixHandler added (#1114)"
This reverts commit 87afd98e02.
2018-05-31 14:22:43 +02:00
Eldinnie 42daf96d20 mention_markdown/html py2 fixes + unitests (#1112)
Fixes #1108
2018-05-28 23:51:39 +03:00
Eldinnie 87afd98e02 CommandHandler overhaul and PrefixHandler added (#1114)
* Commandhandler reworked

* Make CommandHandler strict

Only register valid botcommands, else raise ValueError

* Add PrefixHandler

* declare encoding on test_commandhandler

* Fix some tests dependend on CommandHandler

* CR changes

* small docfix.

* Test all possibilities for PrefixHandler
2018-05-22 21:44:20 +02:00
Jacob Bom 247577b2e2 Context based callbacks (#1100)
See https://github.com/python-telegram-bot/python-telegram-bot/wiki/Transition-guide-to-Version-11.0 under Context based callbacks and Filters in handlers for a good guide on the changes in this commit.

* Change handlers so context is supported

* Attempt to make parameter "guessing" work on py < 3.5

* Document use_context in all handlers

* Add Context to docs

* Minor fixes to context handling

* Add tests for context stuff

* Allow the signature check to work on py<3.5 with methods

* Fix order of operations

* Address most issues raised in CR

* Make CommandHandler no longer support filter lists

* Fix indent

(pycharm can be an arse sometimes)

* Improve readability in conversationhandler

* Make context have Match instead of groups & groupdict

* Remove filter list support from messagehandler too

* Small fix to StringCommandHandler

* More small fixes to handlers

* Amend CHANGES

* Fix tests and fix bugs raised by tests

* Don't allow users to ignore errors without messing with the warning filters themselves

* Ignore our own deprecation warnings when testing

* Skipping deprecationwarning test on py2

* Forgot some changes

* Handler: Improved documentation and text of deprecation warnings

* HandlerContext: Keep only dispatcher and use properties; improved doc

* Complete fixing the documentation.

 - Fixes per Eldinnie's comments.
 - Fixes per warnings when running sphinx.

* Some small doc fixes (interlinks and optionals)

* Change add_error_handler to use HandlerContext too

* More context based changes

Context Based Handlers -> Context Based Callbacks

No longer use_context args on every single Handler

Instead set dispatcher/updater .use_context=True to use

Works with
- Handler callbacks
- Error handler callbacks
- Job callbacks

Change examples to context based callbacks so new users are not confused

Rename and move the context object from Handlers.HandlerContext to CallbackContext, since it doesn't only apply to handlers anymore.

Fix tests by adding a new fixture `cpd` which is a dispatcher with use_context=True

* Forgot about conversationhandler

* Forgot jobqueue

* Add tests for callbackcontext & for context based callback job

* Fix as per review :)
2018-05-21 15:00:47 +02:00
Trainer Jono 94abf16a7f Add t.me links for User, Chat and Message if available and update User.mention_* (#1092)
* Add User.link and update User.mention_*
* Add Chat.link
* Add Message.link
* Link returns None on default
* Add test link
2018-05-09 11:42:12 +02:00
Eldinnie 3d8abc184a Add 3.7-dev to travis (#1106) 2018-05-08 15:51:56 +03:00
Eldinnie efbd951b74 Remove wheel from yamls 2018-05-05 17:28:07 +02:00
Noam Meltzer 3ff4cc4445 requirements-dev.txt: Added missing 'wheel' package
Without it we can't run 'setup.py bdist_wheel'
2018-05-05 00:47:34 +03:00
Noam Meltzer 32afc007aa Bump version to v10.1.0 2018-05-05 00:37:13 +03:00
Noam Meltzer c758c19ef4 bot.py: Remove an inaccurate note from docstring 2018-05-05 00:22:23 +03:00
Eldinnie 3bef2fa752 Updating sphinx to py3 (#1096)
* Use python 3 on read the docs

This has multiple improvements on the inspection of classes. Mainly that method signatures propely display the arguments for the method.

* Add note to telegram.Bot about camelCase

Switching to py3 means that the camelCase method descriptors will no longer be displayed in the docs. Adding a note to Bot to clarify they exist.

* Add Alias links for all camelCase
2018-05-03 15:34:50 +02:00
Jacob Bom b4cabecca2 Remove pytest-catchlog from requirements (#1099) 2018-05-03 16:28:57 +03:00
Noam Meltzer 0a8abccc78 InputFile: Fix proper naming of file when reading from subprocess.PIPE (#1079) 2018-05-03 00:17:54 +03:00
Igor Strebezhev 5ff34fc0ba Fix send_sticker() timeout=20 (#1088)
Documentation was correct. Code wasn't.
2018-05-01 22:48:31 +03:00
Trainer Jono 78fee3c1dc Fixed docstring of {User,Chat}.send_* methods (#1081)
* Changed all "User.chat_id"s to "User.id"
* Chat.chat_id --> Chat.id
2018-04-25 23:21:11 +03:00
Noam Meltzer 38d6f4d9f2 Inputfile encode filenames (#1086)
* Unitest to recreate issue #1083

* InputFile: Encode unicode filenames

Fixes #1083
2018-04-25 23:13:00 +03:00
Noam Meltzer 1ec12343f0 Add urllib3 fix for socks5h support (#1085)
FIxes #1077
Changes semantics of socks proxy behaviour.
Until now - socks5:// was actually socs5h:// and we didn't really have socks5://
2018-04-25 21:23:48 +03:00
Paul Larsen b5196f00b2 Add a caption_entity filter for filtering caption entities (#1068)
* Add a caption_entity filter for filtering caption entities

* remove unneeded list comprehensions
2018-04-20 13:24:40 +02:00
Noam Meltzer 39c679e519 Update all appveyor links in README 2018-04-19 16:56:12 +03:00
Noam Meltzer 7a6d2be101 README fixes (#1078)
* Link for the group on the README top

* Fix widget to appveyor build
2018-04-19 16:52:38 +03:00
Dillon Flamand ef74c525b2 Simplify sentence in examples/README.md (#1061) 2018-04-19 15:20:16 +03:00
Pieter Schutz 6d453b7fa2 Bump to v10.0.2 2018-04-17 09:07:19 +02:00
Rahiel Kasim 716f52684f pypi.python.org -> pypi.org (#1059) 2018-04-17 07:45:05 +03:00
Joel Williams 42497367c1 Correct documentation of Dispatcher.add_handler (#1071) 2018-04-17 07:42:09 +03:00
Jannes Höke b77b329dd6 Handle utf8 decoding errors (#1076) 2018-04-17 07:40:02 +03:00
Wagner Macedo 5efd5e2586 CommandHandler faster check (#1074)
Fixes #1073
2018-04-17 07:37:29 +03:00
Daniel Reed cbfb7df643 Explicitly make Bot.full_name return a unicode object, rather than implicitly a unicode object in Python 3 and a str object on Python 2. (#1063) 2018-04-16 10:37:41 +02:00
Or Bin 712baf0c07 Added video note filter (#1067) 2018-04-14 21:53:54 +02:00
Eldinnie 59659eaf5e Update README.rst 2018-04-09 21:30:37 +02:00
Emilio Molinari 3ccf40e8cc Make chat_id a positional argument inside shortcut methods of Chat and User classes #1048 (#1050)
* Make chat_id a positional argument #1048

* Fixed tests
2018-03-17 00:10:11 +01:00
Jannik 38e3b91a87 Filters for Category and file types (#1046)
* Added extra Filters for File Type and Category

Added extra Filters for File Type and Category, based on the provided Mime-Type

* Added tests for the new Filters

Added Tests for the Category and File Types Filters.

* Fixed Tests

Fixed the Tests from the last commit

* Little Fix

* Revert of unwanted changes

* Update filters.py

* Changed the strings

* Changed file_type to mime_type

* Fixed Tests
2018-03-16 23:41:48 +01:00
Eldinnie e182046376 Fix in telegram.Message (#1042)
* Fix in telegram.Message

The `_parse_(html|markdown)` methods now properly return `None` on an empty `Message.text` or an empty `Message.caption`

* As per CR
2018-03-16 21:42:39 +01:00
Joscha Götzer 1530ed20e5 New filter: regex (#1028) 2018-03-15 06:59:27 +02:00
Eldinnie 2b221da9b9 extra whitespace needed on header 2018-03-05 13:57:21 +01:00
341 changed files with 24195 additions and 5187 deletions
+36 -5
View File
@@ -25,7 +25,7 @@ Setting things up
.. code-block:: bash
$ sudo pip install -r requirements.txt -r requirements-dev.txt
$ pip install -r requirements.txt -r requirements-dev.txt
5. Install pre-commit hooks:
@@ -41,7 +41,9 @@ If you already know what you'd like to work on, you can skip this section.
If you have an idea for something to do, first check if it's already been filed on the `issue tracker`_. If so, add a comment to the issue saying you'd like to work on it, and we'll help you get started! Otherwise, please file a new issue and assign yourself to it.
Another great way to start contributing is by writing tests. Tests are really important because they help prevent developers from accidentally breaking existing code, allowing them to build cool things faster. If you're interested in helping out, let the development team know by posting to the `developers' mailing list`_, and we'll help you get started.
Another great way to start contributing is by writing tests. Tests are really important because they help prevent developers from accidentally breaking existing code, allowing them to build cool things faster. If you're interested in helping out, let the development team know by posting to the `Telegram group`_ (use `@admins` to mention the maintainers), and we'll help you get started.
That being said, we want to mention that we are very hesitant about adding new requirements to our projects. If you intend to do this, please state this in an issue and get a verification from one of the maintainers.
Instructions for making a code change
#####################################
@@ -66,6 +68,26 @@ Here's how to make a one-off code change.
- You can refer to relevant issues in the commit message by writing, e.g., "#105".
- Your code should adhere to the `PEP 8 Style Guide`_, with the exception that we have a maximum line length of 99.
- Document your code. This project uses `sphinx`_ to generate static HTML docs. To build them, first make sure you have the required dependencies:
.. code-block:: bash
$ pip install -r docs/requirements-docs.txt
then run the following from the PTB root directory:
.. code-block:: bash
$ make -C docs html
or, if you don't have ``make`` available (e.g. on Windows):
.. code-block:: bash
$ sphinx-build docs/source docs/build/html
Once the process terminates, you can view the built documentation by opening ``docs/build/html/index.html`` with a browser.
- For consistency, please conform to `Google Python Style Guide`_ and `Google Python Style Docstrings`_. In addition, code should be formatted consistently with other code around it.
@@ -91,6 +113,14 @@ Here's how to make a one-off code change.
$ pytest -v
To run ``test_official`` (particularly useful if you made API changes), run
.. code-block::
$ export TEST_OFFICIAL=true
prior to running the tests.
- To actually make the commit (this will trigger tests for yapf, lint and pep8 automatically):
.. code-block:: bash
@@ -215,8 +245,9 @@ break the API classes. For example:
.. _`Code of Conduct`: https://www.python.org/psf/codeofconduct/
.. _`issue tracker`: https://github.com/python-telegram-bot/python-telegram-bot/issues
.. _`developers' mailing list`: mailto:devs@python-telegram-bot.org
.. _`Telegram group`: https://telegram.me/pythontelegrambotgroup
.. _`PEP 8 Style Guide`: https://www.python.org/dev/peps/pep-0008/
.. _`Google Python Style Guide`: https://google-styleguide.googlecode.com/svn/trunk/pyguide.html
.. _`Google Python Style Docstrings`: http://sphinx-doc.org/latest/ext/example_google.html
.. _`sphinx`: http://sphinx-doc.org
.. _`Google Python Style Guide`: http://google.github.io/styleguide/pyguide.html
.. _`Google Python Style Docstrings`: https://sphinxcontrib-napoleon.readthedocs.io/en/latest/example_google.html
.. _AUTHORS.rst: ../AUTHORS.rst
@@ -1,9 +1,16 @@
---
name: Bug report
about: Create a report to help us improve
title: "[BUG]"
labels: 'bug :bug:'
assignees: ''
---
<!--
Thanks for reporting issues of python-telegram-bot!
Use this template to notify us if you found a bug, or if you want to request a new feature.
If you're looking for help with programming your bot using our library, feel free to ask your
questions in out telegram group at: https://t.me/pythontelegrambotgroup
Use this template to notify us if you found a bug.
To make it easier for us to help you please enter detailed information below.
+8
View File
@@ -0,0 +1,8 @@
blank_issues_enabled: false
contact_links:
- name: Telegram Group
url: https://telegram.me/pythontelegrambotgroup
about: Questions asked on the group usually get answered faster.
- name: IRC Channel
url: https://webchat.freenode.net/?channels=##python-telegram-bot
about: In case you are unable to join our group due to Telegram restrictions, you can use our IRC channel
+24
View File
@@ -0,0 +1,24 @@
---
name: Feature request
about: Suggest an idea for this project
title: "[FEATURE]"
labels: enhancement
assignees: ''
---
#### Is your feature request related to a problem? Please describe.
A clear and concise description of what the problem is.
Ex. *I want to do X, but there is no way to do it.*
#### Describe the solution you'd like
A clear and concise description of what you want to happen.
Ex. *I think it would be nice if you would add feature Y so it will make it easier.*
#### Describe alternatives you've considered
A clear and concise description of any alternative solutions or features you've considered.
Ex. *I considered Z, but that didn't work because...*
#### Additional context
Add any other context or screenshots about the feature request here.
Ex. *Here's a photo of my cat!*
+29
View File
@@ -0,0 +1,29 @@
---
name: Question
about: Get help with errors or general questions
title: "[QUESTION]"
labels: question
assignees: ''
---
<!--
Hey there, you have a question? We are happy to answer. Please make sure no similar question was opened already.
To make it easier for us to help you, please try to follow the template below as closely as possible.
Please mind that there is also a users' Telegram group at https://t.me/pythontelegrambotgroup for questions about the library. Questions asked there might be answered quicker than here. In case you are unable to join our group due to Telegram restrictions, you can use our IRC channel at https://webchat.freenode.net/?channels=##python-telegram-bot to participate in the group.
-->
### Issue I am facing
Please describe the issue here in as much detail as possible
### Traceback to the issue
```
put it here
```
### Related part of your code
```python
put it here
```
+14
View File
@@ -0,0 +1,14 @@
# Number of days of inactivity before an issue becomes stale
daysUntilStale: 3
# Number of days of inactivity before a stale issue is closed
daysUntilClose: 2
# Only issues or pull requests with all of these labels are check if stale. Defaults to `[]` (disabled)
onlyLabels: question
# Label to use when marking an issue as stale
staleLabel: stale
# Comment to post when marking as stale. Set to `false` to disable
markComment: false
# Comment to post when closing a stale issue. Set to `false` to disable
closeComment: >
This issue has been automatically closed due to inactivity. Feel free to comment in order to reopen
or ask again in our Telegram support group at https://t.me/pythontelegrambotgroup.
+14
View File
@@ -0,0 +1,14 @@
name: Warning maintainers
on:
pull_request:
paths: examples/**
jobs:
job:
runs-on: ubuntu-latest
name: about example change
steps:
- name: running the check
uses: Poolitzer/notifier-action@master
with:
notify-message: Hey there. Relax, I am just a little warning for the maintainers to release directly after merging your PR, otherwise we have broken examples and people might get confused :)
repo-token: ${{ secrets.GITHUB_TOKEN }}
+119
View File
@@ -0,0 +1,119 @@
name: GitHub Actions
on:
pull_request:
branches:
- master
schedule:
- cron: 7 3 * * *
push:
branches:
- master
jobs:
pytest:
name: pytest
runs-on: ${{matrix.os}}
strategy:
matrix:
python-version: [3.5, 3.6, 3.7, 3.8]
os: [ubuntu-latest, windows-latest]
include:
- os: ubuntu-latest
python-version: 3.7
test-build: True
- os: windows-latest
python-version: 3.7
test-build: True
fail-fast: False
steps:
- uses: actions/checkout@v2
- name: Initialize vendored libs
run:
git submodule update --init --recursive
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v1
with:
python-version: ${{ matrix.python-version }}
- name: Install dependencies
run: |
python -W ignore -m pip install --upgrade pip
python -W ignore -m pip install -U codecov pytest-cov
python -W ignore -m pip install -r requirements.txt
python -W ignore -m pip install -r requirements-dev.txt
- name: Test with pytest
run: |
pytest -v -m nocoverage
nocov_exit=$?
pytest -v -m "not nocoverage" --cov
cov_exit=$?
global_exit=$(( nocov_exit > cov_exit ? nocov_exit : cov_exit ))
exit ${global_exit}
env:
JOB_INDEX: ${{ strategy.job-index }}
BOTS: W3sidG9rZW4iOiAiNjk2MTg4NzMyOkFBR1Z3RUtmSEhsTmpzY3hFRE5LQXdraEdzdFpfa28xbUMwIiwgInBheW1lbnRfcHJvdmlkZXJfdG9rZW4iOiAiMjg0Njg1MDYzOlRFU1Q6WldGaU1UUmxNbVF5TnpNeSIsICJib3RfbmFtZSI6ICJQVEIgdGVzdHMgb24gVHJhdmlzIHVzaW5nIENQeXRob24gMi43IiwgInN1cGVyX2dyb3VwX2lkIjogIi0xMDAxMzkwOTgzOTk3IiwgImJvdF91c2VybmFtZSI6ICJAcHRiX3RyYXZpc19jcHl0aG9uXzI3X2JvdCJ9LCB7InRva2VuIjogIjY3MTQ2ODg4NjpBQUdQR2ZjaVJJQlVORmU4MjR1SVZkcTdKZTNfWW5BVE5HdyIsICJwYXltZW50X3Byb3ZpZGVyX3Rva2VuIjogIjI4NDY4NTA2MzpURVNUOlpHWXdPVGxrTXpNeE4yWTIiLCAiYm90X25hbWUiOiAiUFRCIHRlc3RzIG9uIFRyYXZpcyB1c2luZyBDUHl0aG9uIDMuNCIsICJzdXBlcl9ncm91cF9pZCI6ICItMTAwMTQ0NjAyMjUyMiIsICJib3RfdXNlcm5hbWUiOiAiQHB0Yl90cmF2aXNfY3B5dGhvbl8zNF9ib3QifSwgeyJ0b2tlbiI6ICI2MjkzMjY1Mzg6QUFGUnJaSnJCN29CM211ekdzR0pYVXZHRTVDUXpNNUNVNG8iLCAicGF5bWVudF9wcm92aWRlcl90b2tlbiI6ICIyODQ2ODUwNjM6VEVTVDpNbU01WVdKaFl6a3hNMlUxIiwgImJvdF9uYW1lIjogIlBUQiB0ZXN0cyBvbiBUcmF2aXMgdXNpbmcgQ1B5dGhvbiAzLjUiLCAic3VwZXJfZ3JvdXBfaWQiOiAiLTEwMDE0OTY5MTc3NTAiLCAiYm90X3VzZXJuYW1lIjogIkBwdGJfdHJhdmlzX2NweXRob25fMzVfYm90In0sIHsidG9rZW4iOiAiNjQwMjA4OTQzOkFBRmhCalFwOXFtM1JUeFN6VXBZekJRakNsZS1Kano1aGNrIiwgInBheW1lbnRfcHJvdmlkZXJfdG9rZW4iOiAiMjg0Njg1MDYzOlRFU1Q6WXpoa1pUZzFOamMxWXpWbCIsICJib3RfbmFtZSI6ICJQVEIgdGVzdHMgb24gVHJhdmlzIHVzaW5nIENQeXRob24gMy42IiwgInN1cGVyX2dyb3VwX2lkIjogIi0xMDAxMzMzODcxNDYxIiwgImJvdF91c2VybmFtZSI6ICJAcHRiX3RyYXZpc19jcHl0aG9uXzM2X2JvdCJ9LCB7InRva2VuIjogIjY5NTEwNDA4ODpBQUhmenlsSU9qU0lJUy1lT25JMjB5MkUyMEhvZEhzZnotMCIsICJwYXltZW50X3Byb3ZpZGVyX3Rva2VuIjogIjI4NDY4NTA2MzpURVNUOk9HUTFNRGd3WmpJd1pqRmwiLCAiYm90X25hbWUiOiAiUFRCIHRlc3RzIG9uIFRyYXZpcyB1c2luZyBDUHl0aG9uIDMuNyIsICJzdXBlcl9ncm91cF9pZCI6ICItMTAwMTQ3ODI5MzcxNCIsICJib3RfdXNlcm5hbWUiOiAiQHB0Yl90cmF2aXNfY3B5dGhvbl8zN19ib3QifSwgeyJ0b2tlbiI6ICI2OTE0MjM1NTQ6QUFGOFdrakNaYm5IcVBfaTZHaFRZaXJGRWxackdhWU9oWDAiLCAicGF5bWVudF9wcm92aWRlcl90b2tlbiI6ICIyODQ2ODUwNjM6VEVTVDpZamM1TlRoaU1tUXlNV1ZoIiwgImJvdF9uYW1lIjogIlBUQiB0ZXN0cyBvbiBUcmF2aXMgdXNpbmcgUHlQeSAyLjciLCAic3VwZXJfZ3JvdXBfaWQiOiAiLTEwMDEzNjM5MzI1NzMiLCAiYm90X3VzZXJuYW1lIjogIkBwdGJfdHJhdmlzX3B5cHlfMjdfYm90In0sIHsidG9rZW4iOiAiNjg0MzM5OTg0OkFBRk1nRUVqcDAxcjVyQjAwN3lDZFZOc2c4QWxOc2FVLWNjIiwgInBheW1lbnRfcHJvdmlkZXJfdG9rZW4iOiAiMjg0Njg1MDYzOlRFU1Q6TVRBek1UWTNNR1V5TmpnMCIsICJib3RfbmFtZSI6ICJQVEIgdGVzdHMgb24gVHJhdmlzIHVzaW5nIFB5UHkgMy41IiwgInN1cGVyX2dyb3VwX2lkIjogIi0xMDAxNDA3ODM2NjA1IiwgImJvdF91c2VybmFtZSI6ICJAcHRiX3RyYXZpc19weXB5XzM1X2JvdCJ9LCB7InRva2VuIjogIjY5MDA5MTM0NzpBQUZMbVI1cEFCNVljcGVfbU9oN3pNNEpGQk9oMHozVDBUbyIsICJwYXltZW50X3Byb3ZpZGVyX3Rva2VuIjogIjI4NDY4NTA2MzpURVNUOlpEaGxOekU1TURrd1lXSmkiLCAiYm90X25hbWUiOiAiUFRCIHRlc3RzIG9uIEFwcFZleW9yIHVzaW5nIENQeXRob24gMy40IiwgInN1cGVyX2dyb3VwX2lkIjogIi0xMDAxMjc5NjAwMDI2IiwgImJvdF91c2VybmFtZSI6ICJAcHRiX2FwcHZleW9yX2NweXRob25fMzRfYm90In0sIHsidG9rZW4iOiAiNjk0MzA4MDUyOkFBRUIyX3NvbkNrNTVMWTlCRzlBTy1IOGp4aVBTNTVvb0JBIiwgInBheW1lbnRfcHJvdmlkZXJfdG9rZW4iOiAiMjg0Njg1MDYzOlRFU1Q6WW1aaVlXWm1NakpoWkdNeSIsICJib3RfbmFtZSI6ICJQVEIgdGVzdHMgb24gQXBwVmV5b3IgdXNpbmcgQ1B5dGhvbiAyLjciLCAic3VwZXJfZ3JvdXBfaWQiOiAiLTEwMDEyOTMwNzkxNjUiLCAiYm90X3VzZXJuYW1lIjogIkBwdGJfYXBwdmV5b3JfY3B5dGhvbl8yN19ib3QifSwgeyJ0b2tlbiI6ICIxMDU1Mzk3NDcxOkFBRzE4bkJfUzJXQXd1SjNnN29oS0JWZ1hYY2VNbklPeVNjIiwgInBheW1lbnRfcHJvdmlkZXJfdG9rZW4iOiAiMjg0Njg1MDYzOlRFU1Q6TmpBd056QXpZalZpTkdOayIsICJuYW1lIjogIlBUQiB0ZXN0cyBbMF0iLCAic3VwZXJfZ3JvdXBfaWQiOiAiLTEwMDExODU1MDk2MzYiLCAidXNlcm5hbWUiOiAicHRiXzBfYm90In0sIHsidG9rZW4iOiAiMTA0NzMyNjc3MTpBQUY4bk90ODFGcFg4bGJidno4VWV3UVF2UmZUYkZmQnZ1SSIsICJwYXltZW50X3Byb3ZpZGVyX3Rva2VuIjogIjI4NDY4NTA2MzpURVNUOllUVTFOVEk0WkdSallqbGkiLCAibmFtZSI6ICJQVEIgdGVzdHMgWzFdIiwgInN1cGVyX2dyb3VwX2lkIjogIi0xMDAxNDg0Nzk3NjEyIiwgInVzZXJuYW1lIjogInB0Yl8xX2JvdCJ9LCB7InRva2VuIjogIjk3MTk5Mjc0NTpBQUdPa09hVzBOSGpnSXY1LTlqUWJPajR2R3FkaFNGLVV1cyIsICJwYXltZW50X3Byb3ZpZGVyX3Rva2VuIjogIjI4NDY4NTA2MzpURVNUOk5XWmtNV1ZoWWpsallqVTUiLCAibmFtZSI6ICJQVEIgdGVzdHMgWzJdIiwgInN1cGVyX2dyb3VwX2lkIjogIi0xMDAxNDAyMjU1MDcwIiwgInVzZXJuYW1lIjogInB0Yl8yX2JvdCJ9XQ==
TEST_BUILD: ${{ matrix.test-build }}
TEST_PRE_COMMIT: ${{ matrix.test-pre-commit }}
shell: bash --noprofile --norc {0}
- name: Submit coverage
run: |
if [ "$CODECOV_TOKEN" != "" ]; then
codecov -F github -t $CODECOV_TOKEN --name "${{ matrix.os }}-${{ matrix.python-version }}"
fi
env:
CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}
shell: bash
test_official:
name: test-official
runs-on: ${{matrix.os}}
strategy:
matrix:
python-version: [3.7]
os: [ubuntu-latest]
fail-fast: False
steps:
- uses: actions/checkout@v2
- name: Initialize vendored libs
run:
git submodule update --init --recursive
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v1
with:
python-version: ${{ matrix.python-version }}
- name: Install dependencies
run: |
python -W ignore -m pip install --upgrade pip
python -W ignore -m pip install -r requirements.txt
python -W ignore -m pip install -r requirements-dev.txt
- name: Compare to official api
run: |
pytest -v tests/test_official.py
exit $?
env:
TEST_OFFICIAL: "true"
shell: bash --noprofile --norc {0}
test_pre_commit:
name: test-pre-commit
runs-on: ${{matrix.os}}
strategy:
matrix:
python-version: [3.7]
os: [ubuntu-latest]
fail-fast: False
steps:
- uses: actions/checkout@v2
- name: Initialize vendored libs
run:
git submodule update --init --recursive
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v1
with:
python-version: ${{ matrix.python-version }}
- name: Install dependencies
run: |
python -W ignore -m pip install --upgrade pip
python -W ignore -m pip install -r requirements.txt
python -W ignore -m pip install -r requirements-dev.txt
- name: Run pre-commit tests
run: pre-commit run --all-files
+6
View File
@@ -23,6 +23,11 @@ var/
.installed.cfg
*.egg
.env
.pybuild
debian/tmp
debian/python3-telegram
debian/python3-telegram-doc
debian/.debhelper
# PyInstaller
# Usually these files are written by a python script from a template
@@ -64,6 +69,7 @@ target/
*.sublime*
# unitests files
game.gif
telegram.mp3
telegram.mp4
telegram2.mp4
+5 -5
View File
@@ -1,17 +1,17 @@
repos:
- repo: git://github.com/python-telegram-bot/mirrors-yapf
sha: master
rev: 5769e088ef6e0a0d1eb63bd6d0c1fe9f3606d6c8
hooks:
- id: yapf
files: ^(telegram|tests)/.*\.py$
args:
- --diff
- repo: git://github.com/pre-commit/pre-commit-hooks
sha: v1.2.0
- repo: https://gitlab.com/pycqa/flake8
rev: 3.7.1
hooks:
- id: flake8
exclude: ^(setup.py|docs/source/conf.py)$
- repo: git://github.com/pre-commit/mirrors-pylint
sha: v1.7.1
rev: 9d8dcbc2b86c796275680f239c1e90dcd50bd398
hooks:
- id: pylint
files: ^telegram/.*\.py$
+1
View File
@@ -5,5 +5,6 @@ formats:
python:
setup_py_install: true
version: 3
requirements_file: docs/requirements-docs.txt
-37
View File
@@ -1,37 +0,0 @@
language: python
python:
- "2.7"
- "3.4"
- "3.5"
- "3.6"
- "pypy-5.7.1"
dist: trusty
sudo: false
branches:
only:
- master
cache:
directories:
- $HOME/.cache/pip
- $HOME/.pre-commit
before_cache:
- rm -f $HOME/.cache/pip/log/debug.log
- rm -f $HOME/.pre-commit/pre-commit.log
install:
- pip install -U codecov pytest-cov
- pip install -U wheel
- pip install -U -r requirements.txt
- pip install -U -r requirements-dev.txt
- if [[ $TRAVIS_PYTHON_VERSION != 'pypy'* ]]; then pip install ujson; fi
script:
- pytest -v -m nocoverage
- pytest -v -m "not nocoverage" --cov
after_success:
- coverage combine
- codecov -F Travis
+26 -3
View File
@@ -3,8 +3,8 @@ Credits
``python-telegram-bot`` was originally created by
`Leandro Toledo <https://github.com/leandrotoledo>`_ and is now maintained by
`Jannes Höke <https://github.com/jh0ker>`_ (`@jh0ker <https://t.me/jh0ker>`_ on Telegram) and
`Noam Meltzer <https://github.com/tsnoam>`_.
`Jannes Höke <https://github.com/jh0ker>`_ (`@jh0ker <https://t.me/jh0ker>`_ on Telegram),
`Noam Meltzer <https://github.com/tsnoam>`_, `Pieter Schutz <https://github.com/eldinnie>`_, `Jasmin Bom <https://github.com/jsmnbom>`_ and `Hinrich Mahler <https://github.com/Bibo-Joshi>`_.
We're vendoring urllib3 as part of ``python-telegram-bot`` which is distributed under the MIT
license. For more info, full credits & license terms, the sources can be found here:
@@ -16,22 +16,33 @@ Contributors
The following wonderful people contributed directly or indirectly to this project:
- `Alateas <https://github.com/alateas>`_
- `Ales Dokshanin <https://github.com/alesdokshanin>`_
- `Ambro17 <https://github.com/Ambro17>`_
- `Andrej Zhilenkov <https://github.com/Andrej730>`_
- `Anton Tagunov <https://github.com/anton-tagunov>`_
- `Avanatiker <https://github.com/Avanatiker>`_
- `Balduro <https://github.com/Balduro>`_
- `Bibo-Joshi <https://github.com/Bibo-Joshi>`_
- `bimmlerd <https://github.com/bimmlerd>`_
- `d-qoi <https://github.com/d-qoi>`_
- `daimajia <https://github.com/daimajia>`_
- `Daniel Reed <https://github.com/nmlorg>`_
- `D David Livingston <https://github.com/daviddl9>`_
- `Eana Hufwe <https://github.com/blueset>`_
- `Ehsan Online <https://github.com/ehsanonline>`_
- `Eli Gao <https://github.com/eligao>`_
- `Emilio Molinari <https://github.com/xates>`_
- `ErgoZ Riftbit Vaper <https://github.com/ergoz>`_
- `Eugene Lisitsky <https://github.com/lisitsky>`_
- `Eugenio Panadero <https://github.com/azogue>`_
- `Evan Haberecht <https://github.com/habereet>`_
- `evgfilim1 <https://github.com/evgfilim1>`_
- `franciscod <https://github.com/franciscod>`_
- `gamgi <https://github.com/gamgi>`_
- `Harshil <https://github.com/harshil21>`_
- `Hugo Damer <https://github.com/HakimusGIT>`_
- `ihoru <https://github.com/ihoru>`_
- `Jacob Bom <https://github.com/bomjacob>`_
- `Jasmin Bom <https://github.com/jsmnbom>`_
- `JASON0916 <https://github.com/JASON0916>`_
- `jeffffc <https://github.com/jeffffc>`_
- `Jelle Besseling <https://github.com/pingiun>`_
@@ -41,8 +52,10 @@ The following wonderful people contributed directly or indirectly to this projec
- `Joscha Götzer <https://github.com/Rostgnom>`_
- `jossalgon <https://github.com/jossalgon>`_
- `JRoot3D <https://github.com/JRoot3D>`_
- `Kirill Vasin <https://github.com/vasinkd>`_
- `Kjwon15 <https://github.com/kjwon15>`_
- `Li-aung Yip <https://github.com/LiaungYip>`_
- `Loo Zheng Yuan <https://github.com/loozhengyuan>`_
- `macrojames <https://github.com/macrojames>`_
- `Michael Elovskikh <https://github.com/wronglink>`_
- `Mischa Krüger <https://github.com/Makman2>`_
@@ -52,18 +65,28 @@ The following wonderful people contributed directly or indirectly to this projec
- `Noam Meltzer <https://github.com/tsnoam>`_
- `Oleg Shlyazhko <https://github.com/ollmer>`_
- `Oleg Sushchenko <https://github.com/feuillemorte>`_
- `Or Bin <https://github.com/OrBin>`_
- `overquota <https://github.com/overquota>`_
- `Patrick Hofmann <https://github.com/PH89>`_
- `Paul Larsen <https://github.com/PaulSonOfLars>`_
- `Pieter Schutz <https://github.com/eldinnie>`_
- `Poolitzer <https://github.com/Poolitzer>`_
- `Rahiel Kasim <https://github.com/rahiel>`_
- `Riko Naka <https://github.com/rikonaka>`_
- `Rizlas <https://github.com/rizlas>`_
- `Sahil Sharma <https://github.com/sahilsharma811>`_
- `Sascha <https://github.com/saschalalala>`_
- `Shelomentsev D <https://github.com/shelomentsevd>`_
- `Simon Schürrle <https://github.com/SitiSchu>`_
- `sooyhwang <https://github.com/sooyhwang>`_
- `syntx <https://github.com/syntx>`_
- `thodnev <https://github.com/thodnev>`_
- `Trainer Jono <https://github.com/Tr-Jono>`_
- `Valentijn <https://github.com/Faalentijn>`_
- `voider1 <https://github.com/voider1>`_
- `Vorobjev Simon <https://github.com/simonvorobjev>`_
- `Wagner Macedo <https://github.com/wagnerluis1982>`_
- `wjt <https://github.com/wjt>`_
- `zeshuaro <https://github.com/zeshuaro>`_
Please add yourself here alphabetically when you submit your first pull request.
+693 -19
View File
@@ -1,18 +1,683 @@
=======
Changes
=======
**2018-03-05**
*Released 10.0.1*
=========
Changelog
=========
Version 12.8
============
*Released 2020-06-22*
**Major Changes:**
- Remove Python 2 support (`#1715`_)
- Bot API 4.9 support (`#1980`_)
- IDs/Usernames of ``Filters.user`` and ``Filters.chat`` can now be updated (`#1757`_)
**Minor changes, CI improvements, doc fixes or bug fixes:**
- Update contribution guide and stale bot (`#1937`_)
- Remove ``NullHandlers`` (`#1913`_)
- Improve and expand examples (`#1943`_, `#1995`_, `#1983`_, `#1997`_)
- Doc fixes (`#1940`_, `#1962`_)
- Add ``User.send_poll()`` shortcut (`#1968`_)
- Ignore private attributes en ``TelegramObject.to_dict()`` (`#1989`_)
- Stabilize CI (`#2000`_)
.. _`#1937`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1937
.. _`#1913`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1913
.. _`#1943`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1943
.. _`#1757`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1757
.. _`#1940`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1940
.. _`#1962`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1962
.. _`#1968`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1968
.. _`#1989`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1989
.. _`#1995`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1995
.. _`#1983`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1983
.. _`#1715`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1715
.. _`#2000`: https://github.com/python-telegram-bot/python-telegram-bot/pull/2000
.. _`#1997`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1997
.. _`#1980`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1980
Version 12.7
============
*Released 2020-05-02*
**Major Changes:**
- Bot API 4.8 support. **Note:** The ``Dice`` object now has a second positional argument ``emoji``. This is relevant, if you instantiate ``Dice`` objects manually. (`#1917`_)
**New Features:**
- New method ``run_mothly`` for the ``JobQueue`` (`#1705`_)
- ``Job.next_t`` now gives the datetime of the jobs next execution (`#1685`_)
**Minor changes, CI improvements, doc fixes or bug fixes:**
- Added ``tzinfo`` argument to ``helpers.from_timestamp`` (`#1621`_)
- Stabalize CI (`#1919`_, `#1931`_)
- Use ABCs ``@abstractmethod`` instead of raising ``NotImplementedError`` for ``Handler``, ``BasePersistence`` and ``BaseFilter`` (`#1905`_)
- Doc fixes (`#1914`_, `#1902`_, `#1910`_)
.. _`#1902`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1902
.. _`#1685`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1685
.. _`#1910`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1910
.. _`#1914`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1914
.. _`#1931`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1931
.. _`#1905`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1905
.. _`#1919`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1919
.. _`#1621`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1621
.. _`#1705`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1705
.. _`#1917`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1917
Version 12.6.1
==============
*Released 2020-04-11*
**Bug fixes:**
- Fix serialization of ``reply_markup`` in media messages (`#1889`_)
.. _`#1889`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1889
Version 12.6
============
*Released 2020-04-10*
**Major Changes:**
- Bot API 4.7 support. **Note:** In ``Bot.create_new_sticker_set`` and ``Bot.add_sticker_to_set``, the order of the parameters had be changed, as the ``png_sticker`` parameter is now optional. (`#1858`_)
**Minor changes, CI improvements or bug fixes:**
- Add tests for ``swtich_inline_query(_current_chat)`` with empty string (`#1635`_)
- Doc fixes (`#1854`_, `#1874`_, `#1884`_)
- Update issue templates (`#1880`_)
- Favor concrete types over "Iterable" (`#1882`_)
- Pass last valid ``CallbackContext`` to ``TIMEOUT`` handlers of ``ConversationHandler`` (`#1826`_)
- Tweak handling of persistence and update persistence after job calls (`#1827`_)
- Use checkout@v2 for GitHub actions (`#1887`_)
.. _`#1858`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1858
.. _`#1635`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1635
.. _`#1854`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1854
.. _`#1874`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1874
.. _`#1884`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1884
.. _`#1880`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1880
.. _`#1882`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1882
.. _`#1826`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1826
.. _`#1827`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1827
.. _`#1887`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1887
Version 12.5.1
==============
*Released 2020-03-30*
**Minor changes, doc fixes or bug fixes:**
- Add missing docs for `PollHandler` and `PollAnswerHandler` (`#1853`_)
- Fix wording in `Filters` docs (`#1855`_)
- Reorder tests to make them more stable (`#1835`_)
- Make `ConversationHandler` attributes immutable (`#1756`_)
- Make `PrefixHandler` attributes `command` and `prefix` editable (`#1636`_)
- Fix UTC as default `tzinfo` for `Job` (`#1696`_)
.. _`#1853`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1853
.. _`#1855`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1855
.. _`#1835`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1835
.. _`#1756`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1756
.. _`#1636`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1636
.. _`#1696`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1696
Version 12.5
============
*Released 2020-03-29*
**New Features:**
- `Bot.link` gives the `t.me` link of the bot (`#1770`_)
**Major Changes:**
- Bot API 4.5 and 4.6 support. (`#1508`_, `#1723`_)
**Minor changes, CI improvements or bug fixes:**
- Remove legacy CI files (`#1783`_, `#1791`_)
- Update pre-commit config file (`#1787`_)
- Remove builtin names (`#1792`_)
- CI improvements (`#1808`_, `#1848`_)
- Support Python 3.8 (`#1614`_, `#1824`_)
- Use stale bot for auto closing stale issues (`#1820`_, `#1829`_, `#1840`_)
- Doc fixes (`#1778`_, `#1818`_)
- Fix typo in `edit_message_media` (`#1779`_)
- In examples, answer CallbackQueries and use `edit_message_text` shortcut (`#1721`_)
- Revert accidental change in vendored urllib3 (`#1775`_)
.. _`#1783`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1783
.. _`#1787`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1787
.. _`#1792`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1792
.. _`#1791`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1791
.. _`#1808`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1808
.. _`#1614`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1614
.. _`#1770`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1770
.. _`#1824`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1824
.. _`#1820`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1820
.. _`#1829`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1829
.. _`#1840`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1840
.. _`#1778`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1778
.. _`#1779`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1779
.. _`#1721`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1721
.. _`#1775`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1775
.. _`#1848`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1848
.. _`#1818`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1818
.. _`#1508`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1508
.. _`#1723`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1723
Version 12.4.2
==============
*Released 2020-02-10*
**Bug Fixes**
- Pass correct parse_mode to InlineResults if bot.defaults is None (`#1763`_)
- Make sure PP can read files that dont have bot_data (`#1760`_)
.. _`#1763`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1763
.. _`#1760`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1760
Version 12.4.1
==============
*Released 2020-02-08*
This is a quick release for `#1744`_ which was accidently left out of v12.4.0 though mentioned in the
release notes.
Version 12.4.0
==============
*Released 2020-02-08*
**New features:**
- Set default values for arguments appearing repeatedly. We also have a `wiki page for the new defaults`_. (`#1490`_)
- Store data in ``CallbackContext.bot_data`` to access it in every callback. Also persists. (`#1325`_)
- ``Filters.poll`` allows only messages containing a poll (`#1673`_)
**Major changes:**
- ``Filters.text`` now accepts messages that start with a slash, because ``CommandHandler`` checks for ``MessageEntity.BOT_COMMAND`` since v12. This might lead to your MessageHandlers receiving more updates than before (`#1680`_).
- ``Filters.command`` new checks for ``MessageEntity.BOT_COMMAND`` instead of just a leading slash. Also by ``Filters.command(False)`` you can now filters for messages containing a command `anywhere` in the text (`#1744`_).
**Minor changes, CI improvements or bug fixes:**
- Add ``disptacher`` argument to ``Updater`` to allow passing a customized ``Dispatcher`` (`#1484`_)
- Add missing names for ``Filters`` (`#1632`_)
- Documentation fixes (`#1624`_, `#1647`_, `#1669`_, `#1703`_, `#1718`_, `#1734`_, `#1740`_, `#1642`_, `#1739`_, `#1746`_)
- CI improvements (`#1716`_, `#1731`_, `#1738`_, `#1748`_, `#1749`_, `#1750`_, `#1752`_)
- Fix spelling issue for ``encode_conversations_to_json`` (`#1661`_)
- Remove double assignement of ``Dispatcher.job_queue`` (`#1698`_)
- Expose dispatcher as property for ``CallbackContext`` (`#1684`_)
- Fix ``None`` check in ``JobQueue._put()`` (`#1707`_)
- Log datetimes correctly in ``JobQueue`` (`#1714`_)
- Fix false ``Message.link`` creation for private groups (`#1741`_)
- Add option ``--with-upstream-urllib3`` to `setup.py` to allow using non-vendored version (`#1725`_)
- Fix persistence for nested ``ConversationHandlers`` (`#1679`_)
- Improve handling of non-decodable server responses (`#1623`_)
- Fix download for files without ``file_path`` (`#1591`_)
- test_webhook_invalid_posts is now considered flaky and retried on failure (`#1758`_)
.. _`wiki page for the new defaults`: https://github.com/python-telegram-bot/python-telegram-bot/wiki/Adding-defaults-to-your-bot
.. _`#1744`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1744
.. _`#1752`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1752
.. _`#1750`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1750
.. _`#1591`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1591
.. _`#1490`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1490
.. _`#1749`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1749
.. _`#1623`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1623
.. _`#1748`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1748
.. _`#1679`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1679
.. _`#1711`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1711
.. _`#1325`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1325
.. _`#1746`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1746
.. _`#1725`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1725
.. _`#1739`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1739
.. _`#1741`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1741
.. _`#1642`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1642
.. _`#1738`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1738
.. _`#1740`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1740
.. _`#1734`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1734
.. _`#1680`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1680
.. _`#1718`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1718
.. _`#1714`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1714
.. _`#1707`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1707
.. _`#1731`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1731
.. _`#1673`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1673
.. _`#1684`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1684
.. _`#1703`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1703
.. _`#1698`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1698
.. _`#1669`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1669
.. _`#1661`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1661
.. _`#1647`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1647
.. _`#1632`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1632
.. _`#1624`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1624
.. _`#1716`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1716
.. _`#1484`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1484
.. _`#1758`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1484
Version 12.3.0
==============
*Released 2020-01-11*
**New features:**
- `Filters.caption` allows only messages with caption (`#1631`_).
- Filter for exact messages/captions with new capability of `Filters.text` and `Filters.caption`. Especially useful in combination with ReplyKeyboardMarkup. (`#1631`_).
**Major changes:**
- Fix inconsistent handling of naive datetimes (`#1506`_).
**Minor changes, CI improvements or bug fixes:**
- Documentation fixes (`#1558`_, `#1569`_, `#1579`_, `#1572`_, `#1566`_, `#1577`_, `#1656`_).
- Add mutex protection on `ConversationHandler` (`#1533`_).
- Add `MAX_PHOTOSIZE_UPLOAD` constant (`#1560`_).
- Add args and kwargs to `Message.forward()` (`#1574`_).
- Transfer to GitHub Actions CI (`#1555`_, `#1556`_, `#1605`_, `#1606`_, `#1607`_, `#1612`_, `#1615`_, `#1645`_).
- Fix deprecation warning with Py3.8 by vendored urllib3 (`#1618`_).
- Simplify assignements for optional arguments (`#1600`_)
- Allow private groups for `Message.link` (`#1619`_).
- Fix wrong signature call for `ConversationHandler.TIMEOUT` handlers (`#1653`_).
.. _`#1631`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1631
.. _`#1506`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1506
.. _`#1558`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1558
.. _`#1569`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1569
.. _`#1579`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1579
.. _`#1572`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1572
.. _`#1566`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1566
.. _`#1577`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1577
.. _`#1533`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1533
.. _`#1560`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1560
.. _`#1574`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1574
.. _`#1555`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1555
.. _`#1556`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1556
.. _`#1605`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1605
.. _`#1606`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1606
.. _`#1607`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1607
.. _`#1612`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1612
.. _`#1615`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1615
.. _`#1618`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1618
.. _`#1600`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1600
.. _`#1619`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1619
.. _`#1653`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1653
.. _`#1656`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1656
.. _`#1645`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1645
Version 12.2.0
==============
*Released 2019-10-14*
**New features:**
- Nested ConversationHandlers (`#1512`_).
**Minor changes, CI improvments or bug fixes:**
- Fix CI failures due to non-backward compat attrs depndency (`#1540`_).
- travis.yaml: TEST_OFFICIAL removed from allowed_failures.
- Fix typos in examples (`#1537`_).
- Fix Bot.to_dict to use proper first_name (`#1525`_).
- Refactor ``test_commandhandler.py`` (`#1408`_).
- Add Python 3.8 (RC version) to Travis testing matrix (`#1543`_).
- test_bot.py: Add to_dict test (`#1544`_).
- Flake config moved into setup.cfg (`#1546`_).
.. _`#1512`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1512
.. _`#1540`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1540
.. _`#1537`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1537
.. _`#1525`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1525
.. _`#1408`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1408
.. _`#1543`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1543
.. _`#1544`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1544
.. _`#1546`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1546
Version 12.1.1
==============
*Released 2019-09-18*
**Hot fix release**
Fixed regression in the vendored urllib3 (`#1517`_).
.. _`#1517`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1517
Version 12.1.0
================
*Released 2019-09-13*
**Major changes:**
- Bot API 4.4 support (`#1464`_, `#1510`_)
- Add `get_file` method to `Animation` & `ChatPhoto`. Add, `get_small_file` & `get_big_file`
methods to `ChatPhoto` (`#1489`_)
- Tools for deep linking (`#1049`_)
**Minor changes and/or bug fixes:**
- Documentation fixes (`#1500`_, `#1499`_)
- Improved examples (`#1502`_)
.. _`#1464`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1464
.. _`#1502`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1502
.. _`#1499`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1499
.. _`#1500`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1500
.. _`#1049`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1049
.. _`#1489`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1489
.. _`#1510`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1510
Version 12.0.0
================
*Released 2019-08-29*
Well... This felt like decades. But here we are with a new release.
Expect minor releases soon (mainly complete Bot API 4.4 support)
**Major and/or breaking changes:**
- Context based callbacks
- Persistence
- PrefixHandler added (Handler overhaul)
- Deprecation of RegexHandler and edited_messages, channel_post, etc. arguments (Filter overhaul)
- Various ConversationHandler changes and fixes
- Bot API 4.1, 4.2, 4.3 support
- Python 3.4 is no longer supported
- Error Handler now handles all types of exceptions (`#1485`_)
- Return UTC from from_timestamp() (`#1485`_)
**See the wiki page at https://git.io/fxJuV for a detailed guide on how to migrate from version 11 to version 12.**
Context based callbacks (`#1100`_)
----------------------------------
- Use of ``pass_`` in handlers is deprecated.
- Instead use ``use_context=True`` on ``Updater`` or ``Dispatcher`` and change callback from (bot, update, others...) to (update, context).
- This also applies to error handlers ``Dispatcher.add_error_handler`` and JobQueue jobs (change (bot, job) to (context) here).
- For users with custom handlers subclassing Handler, this is mostly backwards compatible, but to use the new context based callbacks you need to implement the new collect_additional_context method.
- Passing bot to ``JobQueue.__init__`` is deprecated. Use JobQueue.set_dispatcher with a dispatcher instead.
- Dispatcher makes sure to use a single `CallbackContext` for a entire update. This means that if an update is handled by multiple handlers (by using the group argument), you can add custom arguments to the `CallbackContext` in a lower group handler and use it in higher group handler. NOTE: Never use with @run_async, see docs for more info. (`#1283`_)
- If you have custom handlers they will need to be updated to support the changes in this release.
- Update all examples to use context based callbacks.
Persistence (`#1017`_)
----------------------
- Added PicklePersistence and DictPersistence for adding persistence to your bots.
- BasePersistence can be subclassed for all your persistence needs.
- Add a new example that shows a persistent ConversationHandler bot
Handler overhaul (`#1114`_)
---------------------------
- CommandHandler now only triggers on actual commands as defined by telegram servers (everything that the clients mark as a tabable link).
- PrefixHandler can be used if you need to trigger on prefixes (like all messages starting with a "/" (old CommandHandler behaviour) or even custom prefixes like "#" or "!").
Filter overhaul (`#1221`_)
--------------------------
- RegexHandler is deprecated and should be replaced with a MessageHandler with a regex filter.
- Use update filters to filter update types instead of arguments (message_updates, channel_post_updates and edited_updates) on the handlers.
- Completely remove allow_edited argument - it has been deprecated for a while.
- data_filters now exist which allows filters that return data into the callback function. This is how the regex filter is implemented.
- All this means that it no longer possible to use a list of filters in a handler. Use bitwise operators instead!
ConversationHandler
-------------------
- Remove ``run_async_timeout`` and ``timed_out_behavior`` arguments (`#1344`_)
- Replace with ``WAITING`` constant and behavior from states (`#1344`_)
- Only emit one warning for multiple CallbackQueryHandlers in a ConversationHandler (`#1319`_)
- Use warnings.warn for ConversationHandler warnings (`#1343`_)
- Fix unresolvable promises (`#1270`_)
Bug fixes & improvements
------------------------
- Handlers should be faster due to deduped logic.
- Avoid compiling compiled regex in regex filter. (`#1314`_)
- Add missing ``left_chat_member`` to Message.MESSAGE_TYPES (`#1336`_)
- Make custom timeouts actually work properly (`#1330`_)
- Add convenience classmethods (from_button, from_row and from_column) to InlineKeyboardMarkup
- Small typo fix in setup.py (`#1306`_)
- Add Conflict error (HTTP error code 409) (`#1154`_)
- Change MAX_CAPTION_LENGTH to 1024 (`#1262`_)
- Remove some unnecessary clauses (`#1247`_, `#1239`_)
- Allow filenames without dots in them when sending files (`#1228`_)
- Fix uploading files with unicode filenames (`#1214`_)
- Replace http.server with Tornado (`#1191`_)
- Allow SOCKSConnection to parse username and password from URL (`#1211`_)
- Fix for arguments in passport/data.py (`#1213`_)
- Improve message entity parsing by adding text_mention (`#1206`_)
- Documentation fixes (`#1348`_, `#1397`_, `#1436`_)
- Merged filters short-circuit (`#1350`_)
- Fix webhook listen with tornado (`#1383`_)
- Call task_done() on update queue after update processing finished (`#1428`_)
- Fix send_location() - latitude may be 0 (`#1437`_)
- Make MessageEntity objects comparable (`#1465`_)
- Add prefix to thread names (`#1358`_)
Buf fixes since v12.0.0b1
-------------------------
- Fix setting bot on ShippingQuery (`#1355`_)
- Fix _trigger_timeout() missing 1 required positional argument: 'job' (`#1367`_)
- Add missing message.text check in PrefixHandler check_update (`#1375`_)
- Make updates persist even on DispatcherHandlerStop (`#1463`_)
- Dispatcher force updating persistence object's chat data attribute(`#1462`_)
.. _`#1100`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1100
.. _`#1283`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1283
.. _`#1017`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1017
.. _`#1325`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1325
.. _`#1301`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1301
.. _`#1312`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1312
.. _`#1324`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1324
.. _`#1114`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1114
.. _`#1221`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1221
.. _`#1314`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1314
.. _`#1336`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1336
.. _`#1330`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1330
.. _`#1306`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1306
.. _`#1154`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1154
.. _`#1262`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1262
.. _`#1247`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1247
.. _`#1239`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1239
.. _`#1228`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1228
.. _`#1214`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1214
.. _`#1191`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1191
.. _`#1211`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1211
.. _`#1213`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1213
.. _`#1206`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1206
.. _`#1344`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1344
.. _`#1319`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1319
.. _`#1343`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1343
.. _`#1270`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1270
.. _`#1348`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1348
.. _`#1350`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1350
.. _`#1383`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1383
.. _`#1397`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1397
.. _`#1428`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1428
.. _`#1436`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1436
.. _`#1437`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1437
.. _`#1465`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1465
.. _`#1358`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1358
.. _`#1355`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1355
.. _`#1367`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1367
.. _`#1375`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1375
.. _`#1463`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1463
.. _`#1462`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1462
.. _`#1483`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1483
.. _`#1485`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1485
Internal improvements
---------------------
- Finally fix our CI builds mostly (too many commits and PRs to list)
- Use multiple bots for CI to improve testing times significantly.
- Allow pypy to fail in CI.
- Remove the last CamelCase CheckUpdate methods from the handlers we missed earlier.
- test_official is now executed in a different job
Version 11.1.0
==============
*Released 2018-09-01*
Fixes and updates for Telegram Passport: (`#1198`_)
- Fix passport decryption failing at random times
- Added support for middle names.
- Added support for translations for documents
- Add errors for translations for documents
- Added support for requesting names in the language of the user's country of residence
- Replaced the payload parameter with the new parameter nonce
- Add hash to EncryptedPassportElement
.. _`#1198`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1198
Version 11.0.0
==============
*Released 2018-08-29*
Fully support Bot API version 4.0!
(also some bugfixes :))
Telegram Passport (`#1174`_):
- Add full support for telegram passport.
- New types: PassportData, PassportFile, EncryptedPassportElement, EncryptedCredentials, PassportElementError, PassportElementErrorDataField, PassportElementErrorFrontSide, PassportElementErrorReverseSide, PassportElementErrorSelfie, PassportElementErrorFile and PassportElementErrorFiles.
- New bot method: set_passport_data_errors
- New filter: Filters.passport_data
- Field passport_data field on Message
- PassportData can be easily decrypted.
- PassportFiles are automatically decrypted if originating from decrypted PassportData.
- See new passportbot.py example for details on how to use, or go to `our telegram passport wiki page`_ for more info
- NOTE: Passport decryption requires new dependency `cryptography`.
Inputfile rework (`#1184`_):
- Change how Inputfile is handled internally
- This allows support for specifying the thumbnails of photos and videos using the thumb= argument in the different send\_ methods.
- Also allows Bot.send_media_group to actually finally send more than one media.
- Add thumb to Audio, Video and Videonote
- Add Bot.edit_message_media together with InputMediaAnimation, InputMediaAudio, and inputMediaDocument.
Other Bot API 4.0 changes:
- Add forusquare_type to Venue, InlineQueryResultVenue, InputVenueMessageContent, and Bot.send_venue. (`#1170`_)
- Add vCard support by adding vcard field to Contact, InlineQueryResultContact, InputContactMessageContent, and Bot.send_contact. (`#1166`_)
- Support new message entities: CASHTAG and PHONE_NUMBER. (`#1179`_)
- Cashtag seems to be things like `$USD` and `$GBP`, but it seems telegram doesn't currently send them to bots.
- Phone number also seems to have limited support for now
- Add Bot.send_animation, add width, height, and duration to Animation, and add Filters.animation. (`#1172`_)
Non Bot API 4.0 changes:
- Minor integer comparison fix (`#1147`_)
- Fix Filters.regex failing on non-text message (`#1158`_)
- Fix ProcessLookupError if process finishes before we kill it (`#1126`_)
- Add t.me links for User, Chat and Message if available and update User.mention_* (`#1092`_)
- Fix mention_markdown/html on py2 (`#1112`_)
.. _`#1092`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1092
.. _`#1112`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1112
.. _`#1126`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1126
.. _`#1147`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1147
.. _`#1158`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1158
.. _`#1166`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1166
.. _`#1170`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1170
.. _`#1174`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1174
.. _`#1172`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1172
.. _`#1179`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1179
.. _`#1184`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1184
.. _`our telegram passport wiki page`: https://git.io/fAvYd
Version 10.1.0
==============
*Released 2018-05-02*
Fixes changing previous behaviour:
- Add urllib3 fix for socks5h support (`#1085`_)
- Fix send_sticker() timeout=20 (`#1088`_)
Fixes:
- Add a caption_entity filter for filtering caption entities (`#1068`_)
- Inputfile encode filenames (`#1086`_)
- InputFile: Fix proper naming of file when reading from subprocess.PIPE (`#1079`_)
- Remove pytest-catchlog from requirements (`#1099`_)
- Documentation fixes (`#1061`_, `#1078`_, `#1081`_, `#1096`_)
.. _`#1061`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1061
.. _`#1068`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1068
.. _`#1078`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1078
.. _`#1079`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1079
.. _`#1081`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1081
.. _`#1085`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1085
.. _`#1086`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1086
.. _`#1088`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1088
.. _`#1096`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1096
.. _`#1099`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1099
Version 10.0.2
==============
*Released 2018-04-17*
Important fix:
- Handle utf8 decoding errors (`#1076`_)
New features:
- Added Filter.regex (`#1028`_)
- Filters for Category and file types (`#1046`_)
- Added video note filter (`#1067`_)
Fixes:
- Fix in telegram.Message (`#1042`_)
- Make chat_id a positional argument inside shortcut methods of Chat and User classes (`#1050`_)
- Make Bot.full_name return a unicode object. (`#1063`_)
- CommandHandler faster check (`#1074`_)
- Correct documentation of Dispatcher.add_handler (`#1071`_)
- Various small fixes to documentation.
.. _`#1028`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1028
.. _`#1042`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1042
.. _`#1046`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1046
.. _`#1050`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1050
.. _`#1067`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1067
.. _`#1063`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1063
.. _`#1074`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1074
.. _`#1076`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1076
.. _`#1071`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1071
Version 10.0.1
==============
*Released 2018-03-05*
Fixes:
- Fix conversationhandler timeout (PR `#1032`_)
- Add missing docs utils (PR `#912`_)
.. _`#1032`: https://github.com/python-telegram-bot/python-telegram-bot/pull/826
.. _`#912`: https://github.com/python-telegram-bot/python-telegram-bot/pull/826
**2018-03-02**
*Released 10.0.0*
Version 10.0.0
==============
*Released 2018-03-02*
Non backward compatabile changes and changed defaults
@@ -77,8 +742,9 @@ Changes
.. _`#1019`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1019
.. _`#1020`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1020
**2017-12-08**
*Released 9.0.0*
Version 9.0.0
=============
*Released 2017-12-08*
Breaking changes (possibly)
@@ -103,15 +769,17 @@ Changes
.. _`#694`: https://github.com/python-telegram-bot/python-telegram-bot/pull/694
.. _`#870`: https://github.com/python-telegram-bot/python-telegram-bot/pull/870
**2017-10-15**
*Released 8.1.1*
Version 8.1.1
=============
*Released 2017-10-15*
- Fix Commandhandler crashing on single character messages (PR `#873`_).
.. _`#873`: https://github.com/python-telegram-bot/python-telegram-bot/pull/871
**2017-10-14**
*Released 8.1.0*
Version 8.1.0
=============
*Released 2017-10-14*
New features
- Support Bot API 3.4 (PR `#865`_).
@@ -128,8 +796,9 @@ Changes
.. _`#865`: https://github.com/python-telegram-bot/python-telegram-bot/pull/865
.. _`#869`: https://github.com/python-telegram-bot/python-telegram-bot/pull/869
**2017-09-01**
*Released 8.0.0*
Version 8.0.0
=============
*Released 2017-09-01*
New features
@@ -170,14 +839,16 @@ Changes
.. _`#793`: https://github.com/python-telegram-bot/python-telegram-bot/pull/793
.. _`#810`: https://github.com/python-telegram-bot/python-telegram-bot/pull/810
**2017-07-28**
*Released 7.0.1*
Version 7.0.1
===============
*Released 2017-07-28*
- Fix TypeError exception in RegexHandler (PR #751).
- Small documentation fix (PR #749).
**2017-07-25**
*Released 7.0.0*
Version 7.0.0
=============
*Released 2017-07-25*
- Fully support Bot API 3.2.
- New filters for handling messages from specific chat/user id (PR #677).
@@ -195,6 +866,9 @@ Changes
- Improved documentation.
- Improved unitests.
Pre-version 7.0
===============
**2017-06-18**
*Released 6.1.0*
+792
View File
@@ -0,0 +1,792 @@
NOTICE: You can find here the GPLv3 license and after the Lesser GPLv3 license.
You may choose either license.
GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. [http://fsf.org/]
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
This version of the GNU Lesser General Public License incorporates
the terms and conditions of version 3 of the GNU General Public
License, supplemented by the additional permissions listed below.
0. Additional Definitions.
As used herein, "this License" refers to version 3 of the GNU Lesser
General Public License, and the "GNU GPL" refers to version 3 of the GNU
General Public License.
"The Library" refers to a covered work governed by this License,
other than an Application or a Combined Work as defined below.
An "Application" is any work that makes use of an interface provided
by the Library, but which is not otherwise based on the Library.
Defining a subclass of a class defined by the Library is deemed a mode
of using an interface provided by the Library.
A "Combined Work" is a work produced by combining or linking an
Application with the Library. The particular version of the Library
with which the Combined Work was made is also called the "Linked
Version".
The "Minimal Corresponding Source" for a Combined Work means the
Corresponding Source for the Combined Work, excluding any source code
for portions of the Combined Work that, considered in isolation, are
based on the Application, and not on the Linked Version.
The "Corresponding Application Code" for a Combined Work means the
object code and/or source code for the Application, including any data
and utility programs needed for reproducing the Combined Work from the
Application, but excluding the System Libraries of the Combined Work.
1. Exception to Section 3 of the GNU GPL.
You may convey a covered work under sections 3 and 4 of this License
without being bound by section 3 of the GNU GPL.
2. Conveying Modified Versions.
If you modify a copy of the Library, and, in your modifications, a
facility refers to a function or data to be supplied by an Application
that uses the facility (other than as an argument passed when the
facility is invoked), then you may convey a copy of the modified
version:
a) under this License, provided that you make a good faith effort to
ensure that, in the event an Application does not supply the
function or data, the facility still operates, and performs
whatever part of its purpose remains meaningful, or
b) under the GNU GPL, with none of the additional permissions of
this License applicable to that copy.
3. Object Code Incorporating Material from Library Header Files.
The object code form of an Application may incorporate material from
a header file that is part of the Library. You may convey such object
code under terms of your choice, provided that, if the incorporated
material is not limited to numerical parameters, data structure
layouts and accessors, or small macros, inline functions and templates
(ten or fewer lines in length), you do both of the following:
a) Give prominent notice with each copy of the object code that the
Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the object code with a copy of the GNU GPL and this license
document.
4. Combined Works.
You may convey a Combined Work under terms of your choice that,
taken together, effectively do not restrict modification of the
portions of the Library contained in the Combined Work and reverse
engineering for debugging such modifications, if you also do each of
the following:
a) Give prominent notice with each copy of the Combined Work that
the Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the Combined Work with a copy of the GNU GPL and this license
document.
c) For a Combined Work that displays copyright notices during
execution, include the copyright notice for the Library among
these notices, as well as a reference directing the user to the
copies of the GNU GPL and this license document.
d) Do one of the following:
0) Convey the Minimal Corresponding Source under the terms of this
License, and the Corresponding Application Code in a form
suitable for, and under terms that permit, the user to
recombine or relink the Application with a modified version of
the Linked Version to produce a modified Combined Work, in the
manner specified by section 6 of the GNU GPL for conveying
Corresponding Source.
1) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (a) uses at run time
a copy of the Library already present on the user's computer
system, and (b) will operate properly with a modified version
of the Library that is interface-compatible with the Linked
Version.
e) Provide Installation Information, but only if you would otherwise
be required to provide such information under section 6 of the
GNU GPL, and only to the extent that such information is
necessary to install and execute a modified version of the
Combined Work produced by recombining or relinking the
Application with a modified version of the Linked Version. (If
you use option 4d0, the Installation Information must accompany
the Minimal Corresponding Source and Corresponding Application
Code. If you use option 4d1, you must provide the Installation
Information in the manner specified by section 6 of the GNU GPL
for conveying Corresponding Source.)
5. Combined Libraries.
You may place library facilities that are a work based on the
Library side by side in a single library together with other library
facilities that are not Applications and are not covered by this
License, and convey such a combined library under terms of your
choice, if you do both of the following:
a) Accompany the combined library with a copy of the same work based
on the Library, uncombined with any other library facilities,
conveyed under the terms of this License.
b) Give prominent notice with the combined library that part of it
is a work based on the Library, and explaining where to find the
accompanying uncombined form of the same work.
6. Revised Versions of the GNU Lesser General Public License.
The Free Software Foundation may publish revised and/or new versions
of the GNU Lesser General Public License from time to time. Such new
versions will be similar in spirit to the present version, but may
differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the
Library as you received it specifies that a certain numbered version
of the GNU Lesser General Public License "or any later version"
applies to it, you have the option of following the terms and
conditions either of that published version or of any later version
published by the Free Software Foundation. If the Library as you
received it does not specify a version number of the GNU Lesser
General Public License, you may choose any version of the GNU Lesser
General Public License ever published by the Free Software Foundation.
If the Library as you received it specifies that a proxy can decide
whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Library.
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. [http://fsf.org/]
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
+21 -20
View File
@@ -5,15 +5,17 @@
We have made you a wrapper you can't refuse
We have a vibrant community of developers helping each other in our `Telegram group <https://telegram.me/pythontelegrambotgroup>`_. Join us!
*Stay tuned for library updates and new releases on our* `Telegram Channel <https://telegram.me/pythontelegrambotchannel>`_.
.. image:: https://img.shields.io/pypi/v/python-telegram-bot.svg
:target: https://pypi.python.org/pypi/python-telegram-bot
:target: https://pypi.org/project/python-telegram-bot/
:alt: PyPi Package Version
.. image:: https://img.shields.io/pypi/pyversions/python-telegram-bot.svg
:target: https://pypi.python.org/pypi/python-telegram-bot
:alt: Supported python versions
:target: https://pypi.org/project/python-telegram-bot/
:alt: Supported Python versions
.. image:: https://www.cpu.re/static/python-telegram-bot/downloads.svg
:target: https://www.cpu.re/static/python-telegram-bot/downloads-by-python-version.txt
@@ -27,14 +29,9 @@ We have made you a wrapper you can't refuse
:target: https://www.gnu.org/licenses/lgpl-3.0.html
:alt: LGPLv3 License
.. image:: https://travis-ci.org/python-telegram-bot/python-telegram-bot.svg?branch=master
:target: https://travis-ci.org/python-telegram-bot/python-telegram-bot
:alt: Travis CI Status
.. image:: https://img.shields.io/appveyor/ci/Eldinnie/python-telegram-bot/master.svg?logo=appveyor
:target: https://ci.appveyor.com/project/Eldinnie/python-telegram-bot
:alt: AppVeyor CI Status
.. image:: https://github.com/python-telegram-bot/python-telegram-bot/workflows/GitHub%20Actions/badge.svg?event=schedule
:target: https://github.com/python-telegram-bot/python-telegram-bot/
:alt: Github Actions workflow
.. image:: https://codecov.io/gh/python-telegram-bot/python-telegram-bot/branch/master/graph/badge.svg
:target: https://codecov.io/gh/python-telegram-bot/python-telegram-bot
@@ -44,6 +41,10 @@ We have made you a wrapper you can't refuse
:target: http://isitmaintained.com/project/python-telegram-bot/python-telegram-bot
:alt: Median time to resolve an issue
.. image:: https://api.codacy.com/project/badge/Grade/99d901eaa09b44b4819aec05c330c968
:target: https://www.codacy.com/app/python-telegram-bot/python-telegram-bot?utm_source=github.com&amp;utm_medium=referral&amp;utm_content=python-telegram-bot/python-telegram-bot&amp;utm_campaign=Badge_Grade
:alt: Code quality
.. image:: https://img.shields.io/badge/Telegram-Group-blue.svg
:target: https://telegram.me/pythontelegrambotgroup
:alt: Telegram Group
@@ -82,8 +83,7 @@ Introduction
This library provides a pure Python interface for the
`Telegram Bot API <https://core.telegram.org/bots/api>`_.
It's compatible with Python versions 2.7, 3.3+ and `PyPy <http://pypy.org/>`_.
It also works with `Google App Engine <https://cloud.google.com/appengine>`_.
It's compatible with Python versions 3.5+ and `PyPy <http://pypy.org/>`_.
In addition to the pure API implementation, this library features a number of high-level classes to
make the development of bots easy and straightforward. These classes are contained in the
@@ -93,7 +93,7 @@ make the development of bots easy and straightforward. These classes are contain
Telegram API support
====================
All types and methods of the Telegram Bot API 3.4 are supported.
All types and methods of the Telegram Bot API **4.8** are supported.
==========
Installing
@@ -137,9 +137,9 @@ Other references:
Learning by example
-------------------
We believe that the best way to learn and understand this simple package is by example. So here
are some examples for you to review. Even if it's not your approach for learning, please take a
look at ``echobot2``, it is de facto the base for most of the bots out there. Best of all,
We believe that the best way to learn this package is by example. Here
are some examples for you to review. Even if it is not your approach for learning, please take a
look at ``echobot2``, it is the de facto base for most of the bots out there. Best of all,
the code for these examples are released to the public domain, so you can start by grabbing the
code and building on top of it.
@@ -187,11 +187,12 @@ You can get help in several ways:
1. We have a vibrant community of developers helping each other in our `Telegram group <https://telegram.me/pythontelegrambotgroup>`_. Join us!
2. Our `Wiki pages <https://github.com/python-telegram-bot/python-telegram-bot/wiki/>`_ offer a growing amount of resources.
2. Report bugs, request new features or ask questions by `creating an issue <https://github.com/python-telegram-bot/python-telegram-bot/issues/new/choose>`_.
3. You can ask for help on Stack Overflow using the `python-telegram-bot tag <https://stackoverflow.com/questions/tagged/python-telegram-bot>`_.
3. Our `Wiki pages <https://github.com/python-telegram-bot/python-telegram-bot/wiki/>`_ offer a growing amount of resources.
4. You can even ask for help on Stack Overflow using the `python-telegram-bot tag <https://stackoverflow.com/questions/tagged/python-telegram-bot>`_.
4. As last resort, the developers are ready to help you with `serious issues <https://github.com/python-telegram-bot/python-telegram-bot/issues/new>`_.
============
-39
View File
@@ -1,39 +0,0 @@
environment:
matrix:
# For Python versions available on Appveyor, see
# http://www.appveyor.com/docs/installed-software#python
# The list here is complete (excluding Python 2.6, which
# isn't covered by this document) at the time of writing.
- PYTHON: "C:\\Python27"
- PYTHON: "C:\\Python34"
- PYTHON: "C:\\Python35"
- PYTHON: "C:\\Python36"
branches:
only:
- master
skip_branch_with_pr: true
max_jobs: 1
install:
- "SET PATH=%PYTHON%;%PYTHON%\\Scripts;%PATH%"
- "git submodule update --init --recursive"
# Check that we have the expected version and architecture for Python
- "python --version"
# We need wheel installed to build wheels
- "pip install -U codecov pytest-cov"
- "pip install -U wheel"
- "pip install -r requirements.txt"
- "pip install -r requirements-dev.txt"
build: off
test_script:
- "pytest -m \"not nocoverage\" --cov --cov-report xml:coverage.xml"
after_test:
- "codecov -f coverage.xml -F Appveyor"
+7
View File
@@ -0,0 +1,7 @@
#!/bin/bash
cp -R contrib/debian .
debuild -us -uc
debian/rules clean
rm -rf debian
+6
View File
@@ -0,0 +1,6 @@
telegram (12.0.0b1) unstable; urgency=medium
* Debian packaging;
* Initial Release.
-- Marco Marinello <me@marcomarinello.it> Thu, 22 Aug 2019 20:36:47 +0200
+1
View File
@@ -0,0 +1 @@
11
+25
View File
@@ -0,0 +1,25 @@
Source: telegram
Section: utils
Priority: optional
Maintainer: Marco Marinello <me@marcomarinello.it>
Build-Depends: debhelper (>= 11), dh-python, python3-all, python3-setuptools
Standards-Version: 4.1.3
Homepage: https://python-telegram-bot.org
X-Python-Version: >= 3.2
Vcs-Browser: https://github.com/python-telegram-bot/python-telegram-bot
Vcs-Git: https://github.com/python-telegram-bot/python-telegram-bot.git
Package: python3-telegram-bot
Architecture: any
Depends: ${python3:Depends}, ${misc:Depends}
Description: We have made you a wrapper you can't refuse!
The Python Telegram bot (Python 3)
This library provides a pure Python interface for the Telegram Bot API.
It's compatible with Python versions 3.5+ and PyPy.
.
In addition to the pure API implementation, this library features
a number of high-level
classes to make the development of bots easy and straightforward.
These classes are contained in the telegram.ext submodule.
.
This package installs the library for Python 3.
+30
View File
@@ -0,0 +1,30 @@
Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
Upstream-Name: telegram
Source: https://github.com/python-telegram-bot/python-telegram-bot
Files: *
Copyright: 2019 Leandro Toledo
2019 see AUTHORS file
License: LGPLv3
Files: debian/*
Copyright: 2019 Marco Marinello <me@marcomarinello.it>
License: GPL-3.0+
License: GPL-3.0+
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
.
This package is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
.
On Debian systems, the complete text of the GNU General
Public License version 3 can be found in "/usr/share/common-licenses/GPL-3".
+1
View File
@@ -0,0 +1 @@
AUTHORS.rst /usr/share/doc/python3-telegram-bot
+18
View File
@@ -0,0 +1,18 @@
#!/usr/bin/make -f
# See debhelper(7) (uncomment to enable)
# output every command that modifies files on the build system.
#export DH_VERBOSE = 1
export PYBUILD_NAME=telegram
%:
DEB_BUILD_OPTIONS=nocheck dh $@ --with python3 --buildsystem=pybuild
# If you need to rebuild the Sphinx documentation
# Add spinxdoc to the dh --with line
#override_dh_auto_build:
# dh_auto_build
# PYTHONPATH=. http_proxy='127.0.0.1:9' sphinx-build -N -bhtml docs/ build/html # HTML generator
# PYTHONPATH=. http_proxy='127.0.0.1:9' sphinx-build -N -bman docs/ build/man # Manpage generator
+1
View File
@@ -0,0 +1 @@
3.0 (native)
+1
View File
@@ -0,0 +1 @@
extend-diff-ignore = "^[^/]*[.]egg-info/"
+1 -1
View File
@@ -1,3 +1,3 @@
sphinx>=1.5.4
sphinx>=1.7.9
sphinx_rtd_theme
sphinx-pypi-upload
+1
View File
@@ -0,0 +1 @@
.. include:: ../../CHANGES.rst
+9 -13
View File
@@ -24,7 +24,7 @@ sys.path.insert(0, os.path.abspath('../..'))
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
needs_sphinx = '1.5.4' # fixes issues with autodoc-skip-member and napoleon
needs_sphinx = '1.7.9'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
@@ -50,7 +50,7 @@ master_doc = 'index'
# General information about the project.
project = u'Python Telegram Bot'
copyright = u'2015-2018, Leandro Toledo'
copyright = u'2015-2020, Leandro Toledo'
author = u'Leandro Toledo'
# The version info for the project you're documenting, acts as replacement for
@@ -58,9 +58,9 @@ author = u'Leandro Toledo'
# built documents.
#
# The short X.Y version.
version = '10.0' # telegram.__version__[:3]
version = '12.8' # telegram.__version__[:3]
# The full version, including alpha/beta/rc tags.
release = '10.0.1' # telegram.__version__
release = '12.8' # telegram.__version__
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
@@ -289,19 +289,15 @@ texinfo_documents = [
# If true, do not generate a @detailmenu in the "Top" node's menu.
#texinfo_no_detailmenu = False
# -- script stuff --------------------------------------------------------
# Napoleon stuff
import inspect
napoleon_use_admonition_for_examples = True
# -- script stuff --------------------------------------------------------
def autodoc_skip_member(app, what, name, obj, skip, options):
try:
if inspect.getmodule(obj).__name__.startswith('telegram') and inspect.isfunction(obj):
if name.lower() != name:
return True
except AttributeError:
pass
# Return None so napoleon can handle it
pass
def setup(app):
+20 -9
View File
@@ -6,8 +6,23 @@
Welcome to Python Telegram Bot's documentation!
===============================================
Below you can find the documentation for the python-telegram-bot library. except for the .ext package most of the
objects in the package reflect the types as defined by the `telegram bot api <https://core.telegram.org/bots/api>`_.
Guides and tutorials
====================
If you're just starting out with the library, we recommend following our `"Your first Bot" <https://github.com/python-telegram-bot/python-telegram-bot/wiki/Extensions-%E2%80%93-Your-first-Bot>`_ tutorial that you can find on our `wiki <https://github.com/python-telegram-bot/python-telegram-bot/wiki>`_.
On our wiki you will also find guides like how to use handlers, webhooks, emoji, proxies and much more.
Examples
========
A great way to learn is by looking at examples. Ours can be found at our `github in the examples folder <https://github.com/python-telegram-bot/python-telegram-bot/tree/master/examples>`_.
Reference
=========
Below you can find a reference of all the classes and methods in python-telegram-bot.
Apart from the `telegram.ext` package the objects should reflect the types defined in the `official telegram bot api documentation <https://core.telegram.org/bots/api>`_.
.. toctree::
telegram
@@ -15,13 +30,9 @@ objects in the package reflect the types as defined by the `telegram bot api <ht
Changelog
---------
.. include:: ../../CHANGES.rst
.. toctree::
:maxdepth: 2
Indices and tables
==================
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`
changelog
+6
View File
@@ -0,0 +1,6 @@
telegram.BotCommand
===================
.. autoclass:: telegram.BotCommand
:members:
:show-inheritance:
+6
View File
@@ -0,0 +1,6 @@
telegram.ChatPermissions
========================
.. autoclass:: telegram.ChatPermissions
:members:
:show-inheritance:
+6
View File
@@ -0,0 +1,6 @@
telegram.Credentials
====================
.. autoclass:: telegram.Credentials
:members:
:show-inheritance:
+6
View File
@@ -0,0 +1,6 @@
telegram.DataCredentials
========================
.. autoclass:: telegram.DataCredentials
:members:
:show-inheritance:
+6
View File
@@ -0,0 +1,6 @@
telegram.Dice
=============
.. autoclass:: telegram.Dice
:members:
:show-inheritance:
@@ -0,0 +1,6 @@
telegram.EncryptedCredentials
=============================
.. autoclass:: telegram.EncryptedCredentials
:members:
:show-inheritance:
@@ -0,0 +1,6 @@
telegram.EncryptedPassportElement
=================================
.. autoclass:: telegram.EncryptedPassportElement
:members:
:show-inheritance:
@@ -0,0 +1,6 @@
telegram.ext.BasePersistence
============================
.. autoclass:: telegram.ext.BasePersistence
:members:
:show-inheritance:
@@ -0,0 +1,5 @@
telegram.ext.CallbackContext
============================
.. autoclass:: telegram.ext.CallbackContext
:members:
+6
View File
@@ -0,0 +1,6 @@
telegram.ext.Defaults
=====================
.. autoclass:: telegram.ext.Defaults
:members:
:show-inheritance:
@@ -0,0 +1,6 @@
telegram.ext.DictPersistence
============================
.. autoclass:: telegram.ext.DictPersistence
:members:
:show-inheritance:
@@ -0,0 +1,6 @@
telegram.ext.DispatcherHandlerStop
==================================
.. autoclass:: telegram.ext.DispatcherHandlerStop
:members:
:show-inheritance:
@@ -0,0 +1,6 @@
telegram.ext.PicklePersistence
==============================
.. autoclass:: telegram.ext.PicklePersistence
:members:
:show-inheritance:
@@ -0,0 +1,6 @@
telegram.ext.PollAnswerHandler
==============================
.. autoclass:: telegram.ext.PollAnswerHandler
:members:
:show-inheritance:
+6
View File
@@ -0,0 +1,6 @@
telegram.ext.PollHandler
========================
.. autoclass:: telegram.ext.PollHandler
:members:
:show-inheritance:
@@ -0,0 +1,6 @@
telegram.ext.PrefixHandler
===========================
.. autoclass:: telegram.ext.PrefixHandler
:members:
:show-inheritance:
+15
View File
@@ -5,11 +5,14 @@ telegram.ext package
telegram.ext.updater
telegram.ext.dispatcher
telegram.ext.dispatcherhandlerstop
telegram.ext.filters
telegram.ext.job
telegram.ext.jobqueue
telegram.ext.messagequeue
telegram.ext.delayqueue
telegram.ext.callbackcontext
telegram.ext.defaults
Handlers
--------
@@ -23,9 +26,21 @@ Handlers
telegram.ext.commandhandler
telegram.ext.inlinequeryhandler
telegram.ext.messagehandler
telegram.ext.pollanswerhandler
telegram.ext.pollhandler
telegram.ext.precheckoutqueryhandler
telegram.ext.prefixhandler
telegram.ext.regexhandler
telegram.ext.shippingqueryhandler
telegram.ext.stringcommandhandler
telegram.ext.stringregexhandler
telegram.ext.typehandler
Persistence
-----------
.. toctree::
telegram.ext.basepersistence
telegram.ext.picklepersistence
telegram.ext.dictpersistence
+6
View File
@@ -0,0 +1,6 @@
telegram.FileCredentials
========================
.. autoclass:: telegram.FileCredentials
:members:
:show-inheritance:
+6
View File
@@ -0,0 +1,6 @@
telegram.IdDocumentData
=======================
.. autoclass:: telegram.IdDocumentData
:members:
:show-inheritance:
@@ -0,0 +1,6 @@
telegram.InputMediaAnimation
============================
.. autoclass:: telegram.InputMediaAnimation
:members:
:show-inheritance:
+6
View File
@@ -0,0 +1,6 @@
telegram.InputMediaAudio
========================
.. autoclass:: telegram.InputMediaAudio
:members:
:show-inheritance:
@@ -0,0 +1,6 @@
telegram.InputMediaDocument
===========================
.. autoclass:: telegram.InputMediaDocument
:members:
:show-inheritance:
@@ -0,0 +1,6 @@
telegram.KeyboardButtonPollType
===============================
.. autoclass:: telegram.KeyboardButtonPollType
:members:
:show-inheritance:
+6
View File
@@ -0,0 +1,6 @@
telegram.LoginUrl
=================
.. autoclass:: telegram.LoginUrl
:members:
:show-inheritance:
+6
View File
@@ -0,0 +1,6 @@
telegram.PassportData
=====================
.. autoclass:: telegram.PassportData
:members:
:show-inheritance:
@@ -0,0 +1,6 @@
telegram.PassportElementError
=============================
.. autoclass:: telegram.PassportElementError
:members:
:show-inheritance:
@@ -0,0 +1,6 @@
telegram.PassportElementErrorDataField
======================================
.. autoclass:: telegram.PassportElementErrorDataField
:members:
:show-inheritance:
@@ -0,0 +1,6 @@
telegram.PassportElementErrorFile
=================================
.. autoclass:: telegram.PassportElementErrorFile
:members:
:show-inheritance:
@@ -0,0 +1,6 @@
telegram.PassportElementErrorFiles
==================================
.. autoclass:: telegram.PassportElementErrorFiles
:members:
:show-inheritance:
@@ -0,0 +1,6 @@
telegram.PassportElementErrorFrontSide
======================================
.. autoclass:: telegram.PassportElementErrorFrontSide
:members:
:show-inheritance:
@@ -0,0 +1,6 @@
telegram.PassportElementErrorReverseSide
========================================
.. autoclass:: telegram.PassportElementErrorReverseSide
:members:
:show-inheritance:
+6
View File
@@ -0,0 +1,6 @@
telegram.PassportFile
=====================
.. autoclass:: telegram.PassportFile
:members:
:show-inheritance:
+6
View File
@@ -0,0 +1,6 @@
telegram.PersonalDetails
========================
.. autoclass:: telegram.PersonalDetails
:members:
:show-inheritance:
+6
View File
@@ -0,0 +1,6 @@
telegram.Poll
=============
.. autoclass:: telegram.Poll
:members:
:show-inheritance:
+6
View File
@@ -0,0 +1,6 @@
telegram.PollAnswer
===================
.. autoclass:: telegram.PollAnswer
:members:
:show-inheritance:
+6
View File
@@ -0,0 +1,6 @@
telegram.PollOption
===================
.. autoclass:: telegram.PollOption
:members:
:show-inheritance:
@@ -0,0 +1,6 @@
telegram.ResidentialAddress
===========================
.. autoclass:: telegram.ResidentialAddress
:members:
:show-inheritance:
+117 -89
View File
@@ -1,121 +1,149 @@
.. include:: telegram.ext.rst
telegram package
================
.. toctree::
telegram.ext
telegram.utils
telegram.audio
telegram.bot
telegram.callbackquery
telegram.chat
telegram.chataction
telegram.chatmember
telegram.chatphoto
telegram.constants
telegram.contact
telegram.document
telegram.error
telegram.file
telegram.forcereply
telegram.inlinekeyboardbutton
telegram.inlinekeyboardmarkup
telegram.inputfile
telegram.inputmedia
telegram.inputmediaphoto
telegram.inputmediavideo
telegram.keyboardbutton
telegram.location
telegram.message
telegram.messageentity
telegram.parsemode
telegram.photosize
telegram.replykeyboardremove
telegram.replykeyboardmarkup
telegram.replymarkup
telegram.telegramobject
telegram.update
telegram.user
telegram.userprofilephotos
telegram.venue
telegram.video
telegram.videonote
telegram.voice
telegram.webhookinfo
telegram.animation
telegram.audio
telegram.bot
telegram.botcommand
telegram.callbackquery
telegram.chat
telegram.chataction
telegram.chatmember
telegram.chatpermissions
telegram.chatphoto
telegram.constants
telegram.contact
telegram.dice
telegram.document
telegram.error
telegram.file
telegram.forcereply
telegram.inlinekeyboardbutton
telegram.inlinekeyboardmarkup
telegram.inputfile
telegram.inputmedia
telegram.inputmediaanimation
telegram.inputmediaaudio
telegram.inputmediadocument
telegram.inputmediaphoto
telegram.inputmediavideo
telegram.keyboardbutton
telegram.keyboardbuttonpolltype
telegram.location
telegram.loginurl
telegram.message
telegram.messageentity
telegram.parsemode
telegram.photosize
telegram.poll
telegram.pollanswer
telegram.polloption
telegram.replykeyboardremove
telegram.replykeyboardmarkup
telegram.replymarkup
telegram.telegramobject
telegram.update
telegram.user
telegram.userprofilephotos
telegram.venue
telegram.video
telegram.videonote
telegram.voice
telegram.webhookinfo
Stickers
--------
.. toctree::
telegram.sticker
telegram.stickerset
telegram.maskposition
telegram.sticker
telegram.stickerset
telegram.maskposition
Inline Mode
-----------
.. toctree::
telegram.inlinequery
telegram.inlinequeryresult
telegram.inlinequeryresultarticle
telegram.inlinequeryresultaudio
telegram.inlinequeryresultcachedaudio
telegram.inlinequeryresultcacheddocument
telegram.inlinequeryresultcachedgif
telegram.inlinequeryresultcachedmpeg4gif
telegram.inlinequeryresultcachedphoto
telegram.inlinequeryresultcachedsticker
telegram.inlinequeryresultcachedvideo
telegram.inlinequeryresultcachedvoice
telegram.inlinequeryresultcontact
telegram.inlinequeryresultdocument
telegram.inlinequeryresultgame
telegram.inlinequeryresultgif
telegram.inlinequeryresultlocation
telegram.inlinequeryresultmpeg4gif
telegram.inlinequeryresultphoto
telegram.inlinequeryresultvenue
telegram.inlinequeryresultvideo
telegram.inlinequeryresultvoice
telegram.inputmessagecontent
telegram.inputtextmessagecontent
telegram.inputlocationmessagecontent
telegram.inputvenuemessagecontent
telegram.inputcontactmessagecontent
telegram.choseninlineresult
telegram.inlinequery
telegram.inlinequeryresult
telegram.inlinequeryresultarticle
telegram.inlinequeryresultaudio
telegram.inlinequeryresultcachedaudio
telegram.inlinequeryresultcacheddocument
telegram.inlinequeryresultcachedgif
telegram.inlinequeryresultcachedmpeg4gif
telegram.inlinequeryresultcachedphoto
telegram.inlinequeryresultcachedsticker
telegram.inlinequeryresultcachedvideo
telegram.inlinequeryresultcachedvoice
telegram.inlinequeryresultcontact
telegram.inlinequeryresultdocument
telegram.inlinequeryresultgame
telegram.inlinequeryresultgif
telegram.inlinequeryresultlocation
telegram.inlinequeryresultmpeg4gif
telegram.inlinequeryresultphoto
telegram.inlinequeryresultvenue
telegram.inlinequeryresultvideo
telegram.inlinequeryresultvoice
telegram.inputmessagecontent
telegram.inputtextmessagecontent
telegram.inputlocationmessagecontent
telegram.inputvenuemessagecontent
telegram.inputcontactmessagecontent
telegram.choseninlineresult
Payments
--------
.. toctree::
telegram.labeledprice
telegram.invoice
telegram.shippingaddress
telegram.orderinfo
telegram.shippingoption
telegram.successfulpayment
telegram.shippingquery
telegram.precheckoutquery
telegram.labeledprice
telegram.invoice
telegram.shippingaddress
telegram.orderinfo
telegram.shippingoption
telegram.successfulpayment
telegram.shippingquery
telegram.precheckoutquery
Games
-----
.. toctree::
telegram.game
telegram.animation
telegram.callbackgame
telegram.gamehighscore
telegram.game
telegram.callbackgame
telegram.gamehighscore
Passport
--------
Module contents
---------------
.. toctree::
.. automodule:: telegram
:members:
:undoc-members:
:show-inheritance:
:noindex:
telegram.passportelementerror
telegram.passportelementerrorfile
telegram.passportelementerrorreverseside
telegram.passportelementerrorfrontside
telegram.passportelementerrorfiles
telegram.passportelementerrordatafield
telegram.passportelementerrorfile
telegram.credentials
telegram.datacredentials
telegram.securedata
telegram.filecredentials
telegram.iddocumentdata
telegram.personaldetails
telegram.residentialaddress
telegram.passportdata
telegram.passportfile
telegram.encryptedpassportelement
telegram.encryptedcredentials
.. include:: telegram.utils.rst
+6
View File
@@ -0,0 +1,6 @@
telegram.SecureData
===================
.. autoclass:: telegram.SecureData
:members:
:show-inheritance:
+23 -2
View File
@@ -1,6 +1,6 @@
# Examples
The examples in this folder are small bots meant to show you how a bot that is written with `python-telegram-bot` looks like. Some bots focus on one specific aspect of the Telegram Bot API while others focus on one of the mechanics of this library. Except for the [`echobot.py`](#pure-api) example, they all use the high-level framework this library provides with the [`telegram.ext`](https://python-telegram-bot.readthedocs.io/en/latest/telegram.ext.html) submodule.
In this folder are small examples to show what a bot written with `python-telegram-bot` looks like. Some bots focus on one specific aspect of the Telegram Bot API while others focus on one of the mechanics of this library. Except for the [`echobot.py`](#pure-api) example, they all use the high-level framework this library provides with the [`telegram.ext`](https://python-telegram-bot.readthedocs.io/en/latest/telegram.ext.html) submodule.
All examples are licensed under the [CC0 License](https://github.com/python-telegram-bot/python-telegram-bot/blob/master/examples/LICENSE.txt) and are therefore fully dedicated to the public domain. You can use them as the base for your own bots without worrying about copyrights.
@@ -16,14 +16,35 @@ A common task for a bot is to ask information from the user. In v5.0 of this lib
### [`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!
### [`nestedconversationbot.py`](https://github.com/python-telegram-bot/python-telegram-bot/blob/master/examples/nestedconversationbot.py)
A even more complex example of a bot that uses the nested `ConversationHandler`s. While it's certainly not that complex that you couldn't built it without nested `ConversationHanldler`s, it gives a good impression on how to work with them. Of course, there is a [fancy state diagram](https://github.com/python-telegram-bot/python-telegram-bot/blob/master/examples/nestedconversationbot.png) for this example, too!
### [`persistentconversationbot.py`](https://github.com/python-telegram-bot/python-telegram-bot/blob/master/examples/persistentconversationbot.py)
A basic example of a bot store conversation state and user_data over multiple restarts.
### [`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.
### [`inlinekeyboard2.py`](https://github.com/python-telegram-bot/python-telegram-bot/blob/master/examples/inlinekeyboard2.py)
A more complex example about inline keyboards, callback queries and message editing. This example showcases how an interactive menu could be build using inline keyboards.
### [`deeplinking.py`](https://github.com/python-telegram-bot/python-telegram-bot/blob/master/examples/deeplinking.py)
A basic example on how to use deeplinking with inline keyboards.
### [`inlinebot.py`](https://github.com/python-telegram-bot/python-telegram-bot/blob/master/examples/inlinebot.py)
A basic example of an [inline bot](https://core.telegram.org/bots/inline). Don't forget to enable inline mode with [@BotFather](https://telegram.me/BotFather).
### [`pollbot.py`](https://github.com/python-telegram-bot/python-telegram-bot/blob/master/examples/pollbot.py)
This example sheds some light on polls, poll answers and the corresponding handlers.
### [`passportbot.py`](https://github.com/python-telegram-bot/python-telegram-bot/blob/master/examples/passportbot.py)
A basic example of a bot that can accept passports. Use in combination with [`passportbot.html`](https://github.com/python-telegram-bot/python-telegram-bot/blob/master/examples/passportbot.html). Don't forget to enable and configure payments with [@BotFather](https://telegram.me/BotFather). Check out this [guide](https://git.io/fAvYd) on Telegram passports in PTB.
### [`paymentbot.py`](https://github.com/python-telegram-bot/python-telegram-bot/blob/master/examples/paymentbot.py)
A basic example of a bot that can accept payments. Don't forget to enable and configure payments with [@BotFather](https://telegram.me/BotFather).
### [`errorhandlerbot.py`](https://github.com/python-telegram-bot/python-telegram-bot/blob/master/examples/errorhandlerbot.py)
A basic example on how to set up a costum error handler.
## Pure API
The [`echobot.py`](https://github.com/python-telegram-bot/python-telegram-bot/blob/master/examples/echobot.py) example uses only the pure, "bare-metal" API wrapper.
The [`echobot.py`](https://github.com/python-telegram-bot/python-telegram-bot/blob/master/examples/echobot.py) example uses only the pure, "bare-metal" API wrapper.
+19 -28
View File
@@ -1,11 +1,8 @@
#!/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.
@@ -17,12 +14,12 @@ Press Ctrl-C on the command line or send a signal to the process to stop the
bot.
"""
from telegram import (ReplyKeyboardMarkup, ReplyKeyboardRemove)
from telegram.ext import (Updater, CommandHandler, MessageHandler, Filters, RegexHandler,
ConversationHandler)
import logging
from telegram import (ReplyKeyboardMarkup, ReplyKeyboardRemove)
from telegram.ext import (Updater, CommandHandler, MessageHandler, Filters,
ConversationHandler)
# Enable logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO)
@@ -32,7 +29,7 @@ logger = logging.getLogger(__name__)
GENDER, PHOTO, LOCATION, BIO = range(4)
def start(bot, update):
def start(update, context):
reply_keyboard = [['Boy', 'Girl', 'Other']]
update.message.reply_text(
@@ -44,7 +41,7 @@ def start(bot, update):
return GENDER
def gender(bot, update):
def gender(update, context):
user = update.message.from_user
logger.info("Gender of %s: %s", user.first_name, update.message.text)
update.message.reply_text('I see! Please send me a photo of yourself, '
@@ -54,9 +51,9 @@ def gender(bot, update):
return PHOTO
def photo(bot, update):
def photo(update, context):
user = update.message.from_user
photo_file = bot.get_file(update.message.photo[-1].file_id)
photo_file = update.message.photo[-1].get_file()
photo_file.download('user_photo.jpg')
logger.info("Photo of %s: %s", user.first_name, 'user_photo.jpg')
update.message.reply_text('Gorgeous! Now, send me your location please, '
@@ -65,7 +62,7 @@ def photo(bot, update):
return LOCATION
def skip_photo(bot, update):
def skip_photo(update, context):
user = update.message.from_user
logger.info("User %s did not send a photo.", user.first_name)
update.message.reply_text('I bet you look great! Now, send me your location please, '
@@ -74,7 +71,7 @@ def skip_photo(bot, update):
return LOCATION
def location(bot, update):
def location(update, context):
user = update.message.from_user
user_location = update.message.location
logger.info("Location of %s: %f / %f", user.first_name, user_location.latitude,
@@ -85,7 +82,7 @@ def location(bot, update):
return BIO
def skip_location(bot, update):
def skip_location(update, context):
user = update.message.from_user
logger.info("User %s did not send a location.", user.first_name)
update.message.reply_text('You seem a bit paranoid! '
@@ -94,7 +91,7 @@ def skip_location(bot, update):
return BIO
def bio(bot, update):
def bio(update, context):
user = update.message.from_user
logger.info("Bio of %s: %s", user.first_name, update.message.text)
update.message.reply_text('Thank you! I hope we can talk again some day.')
@@ -102,7 +99,7 @@ def bio(bot, update):
return ConversationHandler.END
def cancel(bot, update):
def cancel(update, context):
user = update.message.from_user
logger.info("User %s canceled the conversation.", user.first_name)
update.message.reply_text('Bye! I hope we can talk again some day.',
@@ -111,14 +108,11 @@ def cancel(bot, update):
return ConversationHandler.END
def error(bot, update, error):
"""Log Errors caused by Updates."""
logger.warning('Update "%s" caused error "%s"', update, error)
def main():
# Create the EventHandler and pass it your bot's token.
updater = Updater("TOKEN")
# Create the Updater and pass it your bot's token.
# Make sure to set use_context=True to use the new context based callbacks
# Post version 12 this will no longer be necessary
updater = Updater("TOKEN", use_context=True)
# Get the dispatcher to register handlers
dp = updater.dispatcher
@@ -128,7 +122,7 @@ def main():
entry_points=[CommandHandler('start', start)],
states={
GENDER: [RegexHandler('^(Boy|Girl|Other)$', gender)],
GENDER: [MessageHandler(Filters.regex('^(Boy|Girl|Other)$'), gender)],
PHOTO: [MessageHandler(Filters.photo, photo),
CommandHandler('skip', skip_photo)],
@@ -144,9 +138,6 @@ def main():
dp.add_handler(conv_handler)
# log all errors
dp.add_error_handler(error)
# Start the Bot
updater.start_polling()
+27 -37
View File
@@ -1,11 +1,8 @@
#!/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.
@@ -17,12 +14,12 @@ 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
from telegram import ReplyKeyboardMarkup
from telegram.ext import (Updater, CommandHandler, MessageHandler, Filters,
ConversationHandler)
# Enable logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO)
@@ -46,7 +43,7 @@ def facts_to_str(user_data):
return "\n".join(facts).join(['\n', '\n'])
def start(bot, update):
def start(update, context):
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?",
@@ -55,37 +52,39 @@ def start(bot, update):
return CHOOSING
def regular_choice(bot, update, user_data):
def regular_choice(update, context):
text = update.message.text
user_data['choice'] = text
context.user_data['choice'] = text
update.message.reply_text(
'Your {}? Yes, I would love to hear about that!'.format(text.lower()))
return TYPING_REPLY
def custom_choice(bot, update):
def custom_choice(update, context):
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):
def received_information(update, context):
user_data = context.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:"
"{}"
"You can tell me more, or change your opinion on something.".format(
facts_to_str(user_data)), reply_markup=markup)
"{} You can tell me more, or change your opinion"
" on something.".format(facts_to_str(user_data)),
reply_markup=markup)
return CHOOSING
def done(bot, update, user_data):
def done(update, context):
user_data = context.user_data
if 'choice' in user_data:
del user_data['choice']
@@ -97,49 +96,40 @@ def done(bot, update, user_data):
return ConversationHandler.END
def error(bot, update, error):
"""Log Errors caused by Updates."""
logger.warning('Update "%s" caused error "%s"', update, error)
def main():
# Create the Updater and pass it your bot's token.
updater = Updater("TOKEN")
# Make sure to set use_context=True to use the new context based callbacks
# Post version 12 this will no longer be necessary
updater = Updater("TOKEN", use_context=True)
# Get the dispatcher to register handlers
dp = updater.dispatcher
# Add conversation handler with the states GENDER, PHOTO, LOCATION and BIO
# Add conversation handler with the states CHOOSING, TYPING_CHOICE and TYPING_REPLY
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),
CHOOSING: [MessageHandler(Filters.regex('^(Age|Favourite colour|Number of siblings)$'),
regular_choice),
MessageHandler(Filters.regex('^Something else...$'),
custom_choice)
],
TYPING_CHOICE: [MessageHandler(Filters.text,
regular_choice,
pass_user_data=True),
regular_choice)
],
TYPING_REPLY: [MessageHandler(Filters.text,
received_information,
pass_user_data=True),
received_information),
],
},
fallbacks=[RegexHandler('^Done$', done, pass_user_data=True)]
fallbacks=[MessageHandler(Filters.regex('^Done$'), done)]
)
dp.add_handler(conv_handler)
# log all errors
dp.add_error_handler(error)
# Start the Bot
updater.start_polling()
+111
View File
@@ -0,0 +1,111 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Bot that explains Telegram's "Deep Linking Parameters" functionality.
This program is dedicated to the public domain under the CC0 license.
This Bot uses the Updater class to handle the bot.
First, a few handler functions are defined. Then, those functions are passed to
the Dispatcher and registered at their respective places.
Then, the bot is started and runs until we press Ctrl-C on the command line.
Usage:
Deep Linking example. Send /start to get the link.
Press Ctrl-C on the command line or send a signal to the process to stop the
bot.
"""
import logging
from telegram import ParseMode, InlineKeyboardMarkup, InlineKeyboardButton
from telegram.ext import Updater, CommandHandler, Filters
# Enable logging
from telegram.utils import helpers
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO)
logger = logging.getLogger(__name__)
# Define constants that will allow us to reuse the deep-linking parameters.
CHECK_THIS_OUT = 'check-this-out'
USING_ENTITIES = 'using-entities-here'
SO_COOL = 'so-cool'
def start(update, context):
"""Send a deep-linked URL when the command /start is issued."""
bot = context.bot
url = helpers.create_deep_linked_url(bot.get_me().username, CHECK_THIS_OUT, group=True)
text = "Feel free to tell your friends about it:\n\n" + url
update.message.reply_text(text)
def deep_linked_level_1(update, context):
"""Reached through the CHECK_THIS_OUT payload"""
bot = context.bot
url = helpers.create_deep_linked_url(bot.get_me().username, SO_COOL)
text = "Awesome, you just accessed hidden functionality! " \
" Now let's get back to the private chat."
keyboard = InlineKeyboardMarkup.from_button(
InlineKeyboardButton(text='Continue here!', url=url)
)
update.message.reply_text(text, reply_markup=keyboard)
def deep_linked_level_2(update, context):
"""Reached through the SO_COOL payload"""
bot = context.bot
url = helpers.create_deep_linked_url(bot.get_me().username, USING_ENTITIES)
text = "You can also mask the deep-linked URLs as links: " \
"[▶️ CLICK HERE]({}).".format(url)
update.message.reply_text(text, parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True)
def deep_linked_level_3(update, context):
"""Reached through the USING_ENTITIES payload"""
payload = context.args
update.message.reply_text("Congratulations! This is as deep as it gets 👏🏻\n\n"
"The payload was: {}".format(payload))
def main():
"""Start the bot."""
# Create the Updater and pass it your bot's token.
updater = Updater("TOKEN", use_context=True)
# Get the dispatcher to register handlers
dp = updater.dispatcher
# More info on what deep linking actually is (read this first if it's unclear to you):
# https://core.telegram.org/bots#deep-linking
# Register a deep-linking handler
dp.add_handler(CommandHandler("start", deep_linked_level_1, Filters.regex(CHECK_THIS_OUT)))
# This one works with a textual link instead of an URL
dp.add_handler(CommandHandler("start", deep_linked_level_2, Filters.regex(SO_COOL)))
# We can also pass on the deep-linking payload
dp.add_handler(CommandHandler("start",
deep_linked_level_3,
Filters.regex(USING_ENTITIES),
pass_args=True))
# Make sure the deep-linking handlers occur *before* the normal /start handler.
dp.add_handler(CommandHandler("start", start))
# Start the Bot
updater.start_polling()
# Run the bot until you press Ctrl-C or the process receives SIGINT,
# SIGTERM or SIGABRT. This should be used most of the time, since
# start_polling() is non-blocking and will stop the bot gracefully.
updater.idle()
if __name__ == '__main__':
main()
+15 -22
View File
@@ -1,11 +1,9 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# This program is dedicated to the public domain under the CC0 license.
"""Simple Bot to reply to Telegram messages.
This program is dedicated to the public domain under the CC0 license.
This Bot uses the Updater class to handle the bot.
"""
Simple Bot to reply to Telegram messages.
First, a few handler functions are defined. Then, those functions are passed to
the Dispatcher and registered at their respective places.
@@ -17,9 +15,10 @@ Press Ctrl-C on the command line or send a signal to the process to stop the
bot.
"""
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
import logging
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
# Enable logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO)
@@ -27,46 +26,40 @@ logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s
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):
# Define a few command handlers. These usually take the two arguments update and
# context. Error handlers also receive the raised TelegramError object in error.
def start(update, context):
"""Send a message when the command /start is issued."""
update.message.reply_text('Hi!')
def help(bot, update):
def help_command(update, context):
"""Send a message when the command /help is issued."""
update.message.reply_text('Help!')
def echo(bot, update):
def echo(update, context):
"""Echo the user message."""
update.message.reply_text(update.message.text)
def error(bot, update, error):
"""Log Errors caused by Updates."""
logger.warning('Update "%s" caused error "%s"', update, error)
def main():
"""Start the bot."""
# Create the EventHandler and pass it your bot's token.
updater = Updater("TOKEN")
# Create the Updater and pass it your bot's token.
# Make sure to set use_context=True to use the new context based callbacks
# Post version 12 this will no longer be necessary
updater = Updater("TOKEN", use_context=True)
# Get the dispatcher to register handlers
dp = updater.dispatcher
# on different commands - answer in Telegram
dp.add_handler(CommandHandler("start", start))
dp.add_handler(CommandHandler("help", help))
dp.add_handler(CommandHandler("help", help_command))
# on noncommand i.e message - echo the message on Telegram
dp.add_handler(MessageHandler(Filters.text, echo))
# log all errors
dp.add_error_handler(error)
# Start the Bot
updater.start_polling()
+95
View File
@@ -0,0 +1,95 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# This program is dedicated to the public domain under the CC0 license.
"""
This is a very simple example on how one could implement a custom error handler
"""
import html
import json
import logging
import traceback
from telegram import Update, ParseMode
from telegram.ext import Updater, CallbackContext, CommandHandler
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO)
logger = logging.getLogger(__name__)
# The token you got from @botfather when you created the bot
BOT_TOKEN = "TOKEN"
# This can be your own ID, or one for a developer group/channel.
# You can use the /start command of this bot to see your chat id.
DEVELOPER_CHAT_ID = 123456789
def error_handler(update: Update, context: CallbackContext):
"""Log the error and send a telegram message to notify the developer."""
# Log the error before we do anything else, so we can see it even if something breaks.
logger.error(msg="Exception while handling an update:", exc_info=context.error)
# traceback.format_exception returns the usual python message about an exception, but as a
# list of strings rather than a single string, so we have to join them together.
tb_list = traceback.format_exception(None, context.error, context.error.__traceback__)
tb = ''.join(tb_list)
# Build the message with some markup and additional information about what happened.
# You might need to add some logic to deal with messages longer than the 4096 character limit.
message = (
'An exception was raised while handling an update\n'
'<pre>update = {}</pre>\n\n'
'<pre>context.chat_data = {}</pre>\n\n'
'<pre>context.user_data = {}</pre>\n\n'
'<pre>{}</pre>'
).format(
html.escape(json.dumps(update.to_dict(), indent=2, ensure_ascii=False)),
html.escape(str(context.chat_data)),
html.escape(str(context.user_data)),
html.escape(tb)
)
# Finally, send the message
context.bot.send_message(chat_id=DEVELOPER_CHAT_ID, text=message, parse_mode=ParseMode.HTML)
def bad_command(update: Update, context: CallbackContext):
"""Raise an error to trigger the error handler."""
context.bot.wrong_method_name()
def start(update: Update, context: CallbackContext):
update.effective_message.reply_html('Use /bad_command to cause an error.\n'
'Your chat id is <code>{}</code>.'
.format(update.effective_chat.id))
def main():
# Create the Updater and pass it your bot's token.
# Make sure to set use_context=True to use the new context based callbacks
# Post version 12 this will no longer be necessary
updater = Updater(BOT_TOKEN, use_context=True)
# Get the dispatcher to register handlers
dp = updater.dispatcher
# Register the commands...
dp.add_handler(CommandHandler('start', start))
dp.add_handler(CommandHandler('bad_command', bad_command))
# ...and the error handler
dp.add_error_handler(error_handler)
# Start the Bot
updater.start_polling()
# Run the bot until you press Ctrl-C or the process receives SIGINT,
# SIGTERM or SIGABRT. This should be used most of the time, since
# start_polling() is non-blocking and will stop the bot gracefully.
updater.idle()
if __name__ == '__main__':
main()
+13 -24
View File
@@ -1,12 +1,8 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# This program is dedicated to the public domain under the CC0 license.
"""Simple Bot to reply to Telegram messages.
This program is dedicated to the public domain under the CC0 license.
This Bot uses the Updater class to handle the bot.
"""
First, a few handler functions are defined. Then, those functions are passed to
the Dispatcher and registered at their respective places.
Then, the bot is started and runs until we press Ctrl-C on the command line.
@@ -16,14 +12,13 @@ Basic inline bot example. Applies different text transformations.
Press Ctrl-C on the command line or send a signal to the process to stop the
bot.
"""
import logging
from uuid import uuid4
from telegram.utils.helpers import escape_markdown
from telegram import InlineQueryResultArticle, ParseMode, \
InputTextMessageContent
from telegram.ext import Updater, InlineQueryHandler, CommandHandler
import logging
from telegram.utils.helpers import escape_markdown
# Enable logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
@@ -32,19 +27,19 @@ logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s
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):
# Define a few command handlers. These usually take the two arguments update and
# context. Error handlers also receive the raised TelegramError object in error.
def start(update, context):
"""Send a message when the command /start is issued."""
update.message.reply_text('Hi!')
def help(bot, update):
def help_command(update, context):
"""Send a message when the command /help is issued."""
update.message.reply_text('Help!')
def inlinequery(bot, update):
def inlinequery(update, context):
"""Handle the inline query."""
query = update.inline_query.query
results = [
@@ -69,28 +64,22 @@ def inlinequery(bot, update):
update.inline_query.answer(results)
def error(bot, update, error):
"""Log Errors caused by Updates."""
logger.warning('Update "%s" caused error "%s"', update, error)
def main():
# Create the Updater and pass it your bot's token.
updater = Updater("TOKEN")
# Make sure to set use_context=True to use the new context based callbacks
# Post version 12 this will no longer be necessary
updater = Updater("TOKEN", use_context=True)
# Get the dispatcher to register handlers
dp = updater.dispatcher
# on different commands - answer in Telegram
dp.add_handler(CommandHandler("start", start))
dp.add_handler(CommandHandler("help", help))
dp.add_handler(CommandHandler("help", help_command))
# on noncommand i.e message - echo the message on Telegram
dp.add_handler(InlineQueryHandler(inlinequery))
# log all errors
dp.add_error_handler(error)
# Start the Bot
updater.start_polling()
+16 -16
View File
@@ -1,10 +1,12 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Basic example for a bot that uses inline keyboards.
# This program is dedicated to the public domain under the CC0 license.
"""
Basic example for a bot that uses inline keyboards.
"""
import logging
from telegram import InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import Updater, CommandHandler, CallbackQueryHandler
@@ -13,7 +15,7 @@ logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s
logger = logging.getLogger(__name__)
def start(bot, update):
def start(update, context):
keyboard = [[InlineKeyboardButton("Option 1", callback_data='1'),
InlineKeyboardButton("Option 2", callback_data='2')],
@@ -24,31 +26,29 @@ def start(bot, update):
update.message.reply_text('Please choose:', reply_markup=reply_markup)
def button(bot, update):
def button(update, context):
query = update.callback_query
bot.edit_message_text(text="Selected option: {}".format(query.data),
chat_id=query.message.chat_id,
message_id=query.message.message_id)
# CallbackQueries need to be answered, even if no notification to the user is needed
# Some clients may have trouble otherwise. See https://core.telegram.org/bots/api#callbackquery
query.answer()
query.edit_message_text(text="Selected option: {}".format(query.data))
def help(bot, update):
def help_command(update, context):
update.message.reply_text("Use /start to test this bot.")
def error(bot, update, error):
"""Log Errors caused by Updates."""
logger.warning('Update "%s" caused error "%s"', update, error)
def main():
# Create the Updater and pass it your bot's token.
updater = Updater("TOKEN")
# Make sure to set use_context=True to use the new context based callbacks
# Post version 12 this will no longer be necessary
updater = Updater("TOKEN", use_context=True)
updater.dispatcher.add_handler(CommandHandler('start', start))
updater.dispatcher.add_handler(CallbackQueryHandler(button))
updater.dispatcher.add_handler(CommandHandler('help', help))
updater.dispatcher.add_error_handler(error)
updater.dispatcher.add_handler(CommandHandler('help', help_command))
# Start the Bot
updater.start_polling()
+192
View File
@@ -0,0 +1,192 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Simple inline keyboard bot with multiple CallbackQueryHandlers.
This Bot uses the Updater class to handle the bot.
First, a few callback functions are defined as callback query handler. 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 that uses inline keyboard that has multiple CallbackQueryHandlers arranged in a
ConversationHandler.
Send /start to initiate the conversation.
Press Ctrl-C on the command line to stop the bot.
"""
from telegram import InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import Updater, CommandHandler, CallbackQueryHandler, ConversationHandler
import logging
# Enable logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO)
logger = logging.getLogger(__name__)
# Stages
FIRST, SECOND = range(2)
# Callback data
ONE, TWO, THREE, FOUR = range(4)
def start(update, context):
"""Send message on `/start`."""
# Get user that sent /start and log his name
user = update.message.from_user
logger.info("User %s started the conversation.", user.first_name)
# Build InlineKeyboard where each button has a displayed text
# and a string as callback_data
# The keyboard is a list of button rows, where each row is in turn
# a list (hence `[[...]]`).
keyboard = [
[InlineKeyboardButton("1", callback_data=str(ONE)),
InlineKeyboardButton("2", callback_data=str(TWO))]
]
reply_markup = InlineKeyboardMarkup(keyboard)
# Send message with text and appended InlineKeyboard
update.message.reply_text(
"Start handler, Choose a route",
reply_markup=reply_markup
)
# Tell ConversationHandler that we're in state `FIRST` now
return FIRST
def start_over(update, context):
"""Prompt same text & keyboard as `start` does but not as new message"""
# Get CallbackQuery from Update
query = update.callback_query
# CallbackQueries need to be answered, even if no notification to the user is needed
# Some clients may have trouble otherwise. See https://core.telegram.org/bots/api#callbackquery
query.answer()
keyboard = [
[InlineKeyboardButton("1", callback_data=str(ONE)),
InlineKeyboardButton("2", callback_data=str(TWO))]
]
reply_markup = InlineKeyboardMarkup(keyboard)
# Instead of sending a new message, edit the message that
# originated the CallbackQuery. This gives the feeling of an
# interactive menu.
query.edit_message_text(
text="Start handler, Choose a route",
reply_markup=reply_markup
)
return FIRST
def one(update, context):
"""Show new choice of buttons"""
query = update.callback_query
query.answer()
keyboard = [
[InlineKeyboardButton("3", callback_data=str(THREE)),
InlineKeyboardButton("4", callback_data=str(FOUR))]
]
reply_markup = InlineKeyboardMarkup(keyboard)
query.edit_message_text(
text="First CallbackQueryHandler, Choose a route",
reply_markup=reply_markup
)
return FIRST
def two(update, context):
"""Show new choice of buttons"""
query = update.callback_query
query.answer()
keyboard = [
[InlineKeyboardButton("1", callback_data=str(ONE)),
InlineKeyboardButton("3", callback_data=str(THREE))]
]
reply_markup = InlineKeyboardMarkup(keyboard)
query.edit_message_text(
text="Second CallbackQueryHandler, Choose a route",
reply_markup=reply_markup
)
return FIRST
def three(update, context):
"""Show new choice of buttons"""
query = update.callback_query
query.answer()
keyboard = [
[InlineKeyboardButton("Yes, let's do it again!", callback_data=str(ONE)),
InlineKeyboardButton("Nah, I've had enough ...", callback_data=str(TWO))]
]
reply_markup = InlineKeyboardMarkup(keyboard)
query.edit_message_text(
text="Third CallbackQueryHandler. Do want to start over?",
reply_markup=reply_markup
)
# Transfer to conversation state `SECOND`
return SECOND
def four(update, context):
"""Show new choice of buttons"""
query = update.callback_query
query.answer()
keyboard = [
[InlineKeyboardButton("2", callback_data=str(TWO)),
InlineKeyboardButton("4", callback_data=str(FOUR))]
]
reply_markup = InlineKeyboardMarkup(keyboard)
query.edit_message_text(
text="Fourth CallbackQueryHandler, Choose a route",
reply_markup=reply_markup
)
return FIRST
def end(update, context):
"""Returns `ConversationHandler.END`, which tells the
ConversationHandler that the conversation is over"""
query = update.callback_query
query.answer()
query.edit_message_text(
text="See you next time!"
)
return ConversationHandler.END
def main():
# Create the Updater and pass it your bot's token.
updater = Updater("TOKEN", use_context=True)
# Get the dispatcher to register handlers
dp = updater.dispatcher
# Setup conversation handler with the states FIRST and SECOND
# Use the pattern parameter to pass CallbackQueries with specific
# data pattern to the corresponding handlers.
# ^ means "start of line/string"
# $ means "end of line/string"
# So ^ABC$ will only allow 'ABC'
conv_handler = ConversationHandler(
entry_points=[CommandHandler('start', start)],
states={
FIRST: [CallbackQueryHandler(one, pattern='^' + str(ONE) + '$'),
CallbackQueryHandler(two, pattern='^' + str(TWO) + '$'),
CallbackQueryHandler(three, pattern='^' + str(THREE) + '$'),
CallbackQueryHandler(four, pattern='^' + str(FOUR) + '$')],
SECOND: [CallbackQueryHandler(start_over, pattern='^' + str(ONE) + '$'),
CallbackQueryHandler(end, pattern='^' + str(TWO) + '$')]
},
fallbacks=[CommandHandler('start', start)]
)
# Add ConversationHandler to dispatcher that will be used for handling
# updates
dp.add_handler(conv_handler)
# Start the Bot
updater.start_polling()
# Run the bot until you press Ctrl-C or the process receives SIGINT,
# SIGTERM or SIGABRT. This should be used most of the time, since
# start_polling() is non-blocking and will stop the bot gracefully.
updater.idle()
if __name__ == '__main__':
main()
Binary file not shown.

After

Width:  |  Height:  |  Size: 492 KiB

+366
View File
@@ -0,0 +1,366 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# This program is dedicated to the public domain under the CC0 license.
"""
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 nested ConversationHandlers.
Send /start to initiate the conversation.
Press Ctrl-C on the command line or send a signal to the process to stop the
bot.
"""
import logging
from telegram import (InlineKeyboardMarkup, InlineKeyboardButton)
from telegram.ext import (Updater, CommandHandler, MessageHandler, Filters,
ConversationHandler, CallbackQueryHandler)
# Enable logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO)
logger = logging.getLogger(__name__)
# State definitions for top level conversation
SELECTING_ACTION, ADDING_MEMBER, ADDING_SELF, DESCRIBING_SELF = map(chr, range(4))
# State definitions for second level conversation
SELECTING_LEVEL, SELECTING_GENDER = map(chr, range(4, 6))
# State definitions for descriptions conversation
SELECTING_FEATURE, TYPING = map(chr, range(6, 8))
# Meta states
STOPPING, SHOWING = map(chr, range(8, 10))
# Shortcut for ConversationHandler.END
END = ConversationHandler.END
# Different constants for this example
(PARENTS, CHILDREN, SELF, GENDER, MALE, FEMALE, AGE, NAME, START_OVER, FEATURES,
CURRENT_FEATURE, CURRENT_LEVEL) = map(chr, range(10, 22))
# Helper
def _name_switcher(level):
if level == PARENTS:
return ('Father', 'Mother')
elif level == CHILDREN:
return ('Brother', 'Sister')
# Top level conversation callbacks
def start(update, context):
"""Select an action: Adding parent/child or show data."""
text = 'You may add a familiy member, yourself show the gathered data or end the ' \
'conversation. To abort, simply type /stop.'
buttons = [[
InlineKeyboardButton(text='Add family member', callback_data=str(ADDING_MEMBER)),
InlineKeyboardButton(text='Add yourself', callback_data=str(ADDING_SELF))
], [
InlineKeyboardButton(text='Show data', callback_data=str(SHOWING)),
InlineKeyboardButton(text='Done', callback_data=str(END))
]]
keyboard = InlineKeyboardMarkup(buttons)
# If we're starting over we don't need do send a new message
if context.user_data.get(START_OVER):
update.callback_query.answer()
update.callback_query.edit_message_text(text=text, reply_markup=keyboard)
else:
update.message.reply_text('Hi, I\'m FamiliyBot and here to help you gather information'
'about your family.')
update.message.reply_text(text=text, reply_markup=keyboard)
context.user_data[START_OVER] = False
return SELECTING_ACTION
def adding_self(update, context):
"""Add information about youself."""
context.user_data[CURRENT_LEVEL] = SELF
text = 'Okay, please tell me about yourself.'
button = InlineKeyboardButton(text='Add info', callback_data=str(MALE))
keyboard = InlineKeyboardMarkup.from_button(button)
update.callback_query.answer()
update.callback_query.edit_message_text(text=text, reply_markup=keyboard)
return DESCRIBING_SELF
def show_data(update, context):
"""Pretty print gathered data."""
def prettyprint(user_data, level):
people = user_data.get(level)
if not people:
return '\nNo information yet.'
text = ''
if level == SELF:
for person in user_data[level]:
text += '\nName: {}, Age: {}'.format(person.get(NAME, '-'), person.get(AGE, '-'))
else:
male, female = _name_switcher(level)
for person in user_data[level]:
gender = female if person[GENDER] == FEMALE else male
text += '\n{}: Name: {}, Age: {}'.format(gender, person.get(NAME, '-'),
person.get(AGE, '-'))
return text
ud = context.user_data
text = 'Yourself:' + prettyprint(ud, SELF)
text += '\n\nParents:' + prettyprint(ud, PARENTS)
text += '\n\nChildren:' + prettyprint(ud, CHILDREN)
buttons = [[
InlineKeyboardButton(text='Back', callback_data=str(END))
]]
keyboard = InlineKeyboardMarkup(buttons)
update.callback_query.answer()
update.callback_query.edit_message_text(text=text, reply_markup=keyboard)
ud[START_OVER] = True
return SHOWING
def stop(update, context):
"""End Conversation by command."""
update.message.reply_text('Okay, bye.')
return END
def end(update, context):
"""End conversation from InlineKeyboardButton."""
update.callback_query.answer()
text = 'See you around!'
update.callback_query.edit_message_text(text=text)
return END
# Second level conversation callbacks
def select_level(update, context):
"""Choose to add a parent or a child."""
text = 'You may add a parent or a child. Also you can show the gathered data or go back.'
buttons = [[
InlineKeyboardButton(text='Add parent', callback_data=str(PARENTS)),
InlineKeyboardButton(text='Add child', callback_data=str(CHILDREN))
], [
InlineKeyboardButton(text='Show data', callback_data=str(SHOWING)),
InlineKeyboardButton(text='Back', callback_data=str(END))
]]
keyboard = InlineKeyboardMarkup(buttons)
update.callback_query.answer()
update.callback_query.edit_message_text(text=text, reply_markup=keyboard)
return SELECTING_LEVEL
def select_gender(update, context):
"""Choose to add mother or father."""
level = update.callback_query.data
context.user_data[CURRENT_LEVEL] = level
text = 'Please choose, whom to add.'
male, female = _name_switcher(level)
buttons = [[
InlineKeyboardButton(text='Add ' + male, callback_data=str(MALE)),
InlineKeyboardButton(text='Add ' + female, callback_data=str(FEMALE))
], [
InlineKeyboardButton(text='Show data', callback_data=str(SHOWING)),
InlineKeyboardButton(text='Back', callback_data=str(END))
]]
keyboard = InlineKeyboardMarkup(buttons)
update.callback_query.answer()
update.callback_query.edit_message_text(text=text, reply_markup=keyboard)
return SELECTING_GENDER
def end_second_level(update, context):
"""Return to top level conversation."""
context.user_data[START_OVER] = True
start(update, context)
return END
# Third level callbacks
def select_feature(update, context):
"""Select a feature to update for the person."""
buttons = [[
InlineKeyboardButton(text='Name', callback_data=str(NAME)),
InlineKeyboardButton(text='Age', callback_data=str(AGE)),
InlineKeyboardButton(text='Done', callback_data=str(END)),
]]
keyboard = InlineKeyboardMarkup(buttons)
# If we collect features for a new person, clear the cache and save the gender
if not context.user_data.get(START_OVER):
context.user_data[FEATURES] = {GENDER: update.callback_query.data}
text = 'Please select a feature to update.'
update.callback_query.answer()
update.callback_query.edit_message_text(text=text, reply_markup=keyboard)
# But after we do that, we need to send a new message
else:
text = 'Got it! Please select a feature to update.'
update.message.reply_text(text=text, reply_markup=keyboard)
context.user_data[START_OVER] = False
return SELECTING_FEATURE
def ask_for_input(update, context):
"""Prompt user to input data for selected feature."""
context.user_data[CURRENT_FEATURE] = update.callback_query.data
text = 'Okay, tell me.'
update.callback_query.answer()
update.callback_query.edit_message_text(text=text)
return TYPING
def save_input(update, context):
"""Save input for feature and return to feature selection."""
ud = context.user_data
ud[FEATURES][ud[CURRENT_FEATURE]] = update.message.text
ud[START_OVER] = True
return select_feature(update, context)
def end_describing(update, context):
"""End gathering of features and return to parent conversation."""
ud = context.user_data
level = ud[CURRENT_LEVEL]
if not ud.get(level):
ud[level] = []
ud[level].append(ud[FEATURES])
# Print upper level menu
if level == SELF:
ud[START_OVER] = True
start(update, context)
else:
select_level(update, context)
return END
def stop_nested(update, context):
"""Completely end conversation from within nested conversation."""
update.message.reply_text('Okay, bye.')
return STOPPING
def main():
# Create the Updater and pass it your bot's token.
# Make sure to set use_context=True to use the new context based callbacks
# Post version 12 this will no longer be necessary
updater = Updater("TOKEN", use_context=True)
# Get the dispatcher to register handlers
dp = updater.dispatcher
# Set up third level ConversationHandler (collecting features)
description_conv = ConversationHandler(
entry_points=[CallbackQueryHandler(select_feature,
pattern='^' + str(MALE) + '$|^' + str(FEMALE) + '$')],
states={
SELECTING_FEATURE: [CallbackQueryHandler(ask_for_input,
pattern='^(?!' + str(END) + ').*$')],
TYPING: [MessageHandler(Filters.text, save_input)],
},
fallbacks=[
CallbackQueryHandler(end_describing, pattern='^' + str(END) + '$'),
CommandHandler('stop', stop_nested)
],
map_to_parent={
# Return to second level menu
END: SELECTING_LEVEL,
# End conversation alltogether
STOPPING: STOPPING,
}
)
# Set up second level ConversationHandler (adding a person)
add_member_conv = ConversationHandler(
entry_points=[CallbackQueryHandler(select_level,
pattern='^' + str(ADDING_MEMBER) + '$')],
states={
SELECTING_LEVEL: [CallbackQueryHandler(select_gender,
pattern='^{}$|^{}$'.format(str(PARENTS),
str(CHILDREN)))],
SELECTING_GENDER: [description_conv]
},
fallbacks=[
CallbackQueryHandler(show_data, pattern='^' + str(SHOWING) + '$'),
CallbackQueryHandler(end_second_level, pattern='^' + str(END) + '$'),
CommandHandler('stop', stop_nested)
],
map_to_parent={
# After showing data return to top level menu
SHOWING: SHOWING,
# Return to top level menu
END: SELECTING_ACTION,
# End conversation alltogether
STOPPING: END,
}
)
# Set up top level ConversationHandler (selecting action)
# Because the states of the third level conversation map to the ones of the econd level
# conversation, we need to make sure the top level conversation can also handle them
selection_handlers = [
add_member_conv,
CallbackQueryHandler(show_data, pattern='^' + str(SHOWING) + '$'),
CallbackQueryHandler(adding_self, pattern='^' + str(ADDING_SELF) + '$'),
CallbackQueryHandler(end, pattern='^' + str(END) + '$'),
]
conv_handler = ConversationHandler(
entry_points=[CommandHandler('start', start)],
states={
SHOWING: [CallbackQueryHandler(start, pattern='^' + str(END) + '$')],
SELECTING_ACTION: selection_handlers,
SELECTING_LEVEL: selection_handlers,
DESCRIBING_SELF: [description_conv],
STOPPING: [CommandHandler('start', start)],
},
fallbacks=[CommandHandler('stop', stop)],
)
dp.add_handler(conv_handler)
# Start the Bot
updater.start_polling()
# Run the bot until you press Ctrl-C or the process receives SIGINT,
# SIGTERM or SIGABRT. This should be used most of the time, since
# start_polling() is non-blocking and will stop the bot gracefully.
updater.idle()
if __name__ == '__main__':
main()
+29
View File
@@ -0,0 +1,29 @@
<!DOCTYPE html>
<html lang="en">
<head>
<title>Telegram passport test!</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!--- Needs file from https://github.com/TelegramMessenger/TGPassportJsSDK downloaded --->
<script src="telegram-passport.js"></script>
<script>
"use strict";
Telegram.Passport.createAuthButton('telegram_passport_auth', {
bot_id: BOT_ID, // YOUR BOT ID
scope: {data: [{type: 'id_document', selfie: true}, 'address_document', 'phone_number', 'email'], v: 1}, // WHAT DATA YOU WANT TO RECEIVE
public_key: '-----BEGIN PUBLIC KEY----- ...', // YOUR PUBLIC KEY
payload: 'thisisatest', // YOUR BOT WILL RECEIVE THIS DATA WITH THE REQUEST
callback_url: 'https://example.org' // TELEGRAM WILL SEND YOUR USER BACK TO THIS URL
});
</script>
</head>
<body>
<h1>Telegram passport test</h1>
<div id="telegram_passport_auth"></div>
</body>
</html>
+101
View File
@@ -0,0 +1,101 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# This program is dedicated to the public domain under the CC0 license.
"""
Simple Bot to print/download all incoming passport data
See https://telegram.org/blog/passport for info about what telegram passport is.
See https://git.io/fAvYd for how to use Telegram Passport properly with python-telegram-bot.
"""
import logging
from telegram.ext import Updater, MessageHandler, Filters
# Enable logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.DEBUG)
logger = logging.getLogger(__name__)
def msg(update, context):
# If we received any passport data
passport_data = update.message.passport_data
if passport_data:
# If our nonce doesn't match what we think, this Update did not originate from us
# Ideally you would randomize the nonce on the server
if passport_data.decrypted_credentials.nonce != 'thisisatest':
return
# Print the decrypted credential data
# For all elements
# Print their decrypted data
# Files will be downloaded to current directory
for data in passport_data.decrypted_data: # This is where the data gets decrypted
if data.type == 'phone_number':
print('Phone: ', data.phone_number)
elif data.type == 'email':
print('Email: ', data.email)
if data.type in ('personal_details', 'passport', 'driver_license', 'identity_card',
'internal_passport', 'address'):
print(data.type, data.data)
if data.type in ('utility_bill', 'bank_statement', 'rental_agreement',
'passport_registration', 'temporary_registration'):
print(data.type, len(data.files), 'files')
for file in data.files:
actual_file = file.get_file()
print(actual_file)
actual_file.download()
if data.type in ('passport', 'driver_license', 'identity_card',
'internal_passport'):
if data.front_side:
file = data.front_side.get_file()
print(data.type, file)
file.download()
if data.type in ('driver_license' and 'identity_card'):
if data.reverse_side:
file = data.reverse_side.get_file()
print(data.type, file)
file.download()
if data.type in ('passport', 'driver_license', 'identity_card',
'internal_passport'):
if data.selfie:
file = data.selfie.get_file()
print(data.type, file)
file.download()
if data.type in ('passport', 'driver_license', 'identity_card',
'internal_passport', 'utility_bill', 'bank_statement',
'rental_agreement', 'passport_registration',
'temporary_registration'):
print(data.type, len(data.translation), 'translation')
for file in data.translation:
actual_file = file.get_file()
print(actual_file)
actual_file.download()
def main():
"""Start the bot."""
# Create the Updater and pass it your token and private key
updater = Updater("TOKEN", private_key=open('private.key', 'rb').read())
# Get the dispatcher to register handlers
dp = updater.dispatcher
# On messages that include passport data call msg
dp.add_handler(MessageHandler(Filters.passport_data, msg))
# Start the Bot
updater.start_polling()
# Run the bot until you press Ctrl-C or the process receives SIGINT,
# SIGTERM or SIGABRT. This should be used most of the time, since
# start_polling() is non-blocking and will stop the bot gracefully.
updater.idle()
if __name__ == '__main__':
main()
+29 -37
View File
@@ -1,15 +1,16 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
"""Basic example for a bot that can receive payment from user.
# This program is dedicated to the public domain under the CC0 license.
This program is dedicated to the public domain under the CC0 license.
"""
Basic example for a bot that can receive payment from user.
"""
import logging
from telegram import (LabeledPrice, ShippingOption)
from telegram.ext import (Updater, CommandHandler, MessageHandler,
Filters, PreCheckoutQueryHandler, ShippingQueryHandler)
import logging
# Enable logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
@@ -18,18 +19,13 @@ logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s
logger = logging.getLogger(__name__)
def error(bot, update, error):
"""Log Errors caused by Updates."""
logger.warning('Update "%s" caused error "%s"', update, error)
def start_callback(bot, update):
def start_callback(update, context):
msg = "Use /shipping to get an invoice for shipping-payment, "
msg += "or /noshipping for an invoice without shipping."
update.message.reply_text(msg)
def start_with_shipping_callback(bot, update):
def start_with_shipping_callback(update, context):
chat_id = update.message.chat_id
title = "Payment Example"
description = "Payment Example using python-telegram-bot"
@@ -41,19 +37,19 @@ def start_with_shipping_callback(bot, update):
currency = "USD"
# price in dollars
price = 1
# price * 100 so as to include 2 d.p.
# price * 100 so as to include 2 decimal points
# check https://core.telegram.org/bots/payments#supported-currencies for more details
prices = [LabeledPrice("Test", price * 100)]
# optionally pass need_name=True, need_phone_number=True,
# need_email=True, need_shipping_address=True, is_flexible=True
bot.sendInvoice(chat_id, title, description, payload,
provider_token, start_parameter, currency, prices,
need_name=True, need_phone_number=True,
need_email=True, need_shipping_address=True, is_flexible=True)
context.bot.send_invoice(chat_id, title, description, payload,
provider_token, start_parameter, currency, prices,
need_name=True, need_phone_number=True,
need_email=True, need_shipping_address=True, is_flexible=True)
def start_without_shipping_callback(bot, update):
def start_without_shipping_callback(update, context):
chat_id = update.message.chat_id
title = "Payment Example"
description = "Payment Example using python-telegram-bot"
@@ -65,22 +61,21 @@ def start_without_shipping_callback(bot, update):
currency = "USD"
# price in dollars
price = 1
# price * 100 so as to include 2 d.p.
# price * 100 so as to include 2 decimal points
prices = [LabeledPrice("Test", price * 100)]
# optionally pass need_name=True, need_phone_number=True,
# need_email=True, need_shipping_address=True, is_flexible=True
bot.sendInvoice(chat_id, title, description, payload,
provider_token, start_parameter, currency, prices)
context.bot.send_invoice(chat_id, title, description, payload,
provider_token, start_parameter, currency, prices)
def shipping_callback(bot, update):
def shipping_callback(update, context):
query = update.shipping_query
# check the payload, is this from your bot?
if query.invoice_payload != 'Custom-Payload':
# answer False pre_checkout_query
bot.answer_shipping_query(shipping_query_id=query.id, ok=False,
error_message="Something went wrong...")
query.answer(ok=False, error_message="Something went wrong...")
return
else:
options = list()
@@ -89,31 +84,31 @@ def shipping_callback(bot, update):
# an array of LabeledPrice objects
price_list = [LabeledPrice('B1', 150), LabeledPrice('B2', 200)]
options.append(ShippingOption('2', 'Shipping Option B', price_list))
bot.answer_shipping_query(shipping_query_id=query.id, ok=True,
shipping_options=options)
query.answer(ok=True, shipping_options=options)
# after (optional) shipping, it's the pre-checkout
def precheckout_callback(bot, update):
def precheckout_callback(update, context):
query = update.pre_checkout_query
# check the payload, is this from your bot?
if query.invoice_payload != 'Custom-Payload':
# answer False pre_checkout_query
bot.answer_pre_checkout_query(pre_checkout_query_id=query.id, ok=False,
error_message="Something went wrong...")
query.answer(ok=False, error_message="Something went wrong...")
else:
bot.answer_pre_checkout_query(pre_checkout_query_id=query.id, ok=True)
query.answer(ok=True)
# finally, after contacting to the payment provider...
def successful_payment_callback(bot, update):
# do something after successful receive of payment?
# finally, after contacting the payment provider...
def successful_payment_callback(update, context):
# do something after successfully receiving payment?
update.message.reply_text("Thank you for your payment!")
def main():
# Create the EventHandler and pass it your bot's token.
updater = Updater(token="BOT_TOKEN")
# Create the Updater and pass it your bot's token.
# Make sure to set use_context=True to use the new context based callbacks
# Post version 12 this will no longer be necessary
updater = Updater("TOKEN", use_context=True)
# Get the dispatcher to register handlers
dp = updater.dispatcher
@@ -134,9 +129,6 @@ def main():
# Success! Notify your user!
dp.add_handler(MessageHandler(Filters.successful_payment, successful_payment_callback))
# log all errors
dp.add_error_handler(error)
# Start the Bot
updater.start_polling()
+158
View File
@@ -0,0 +1,158 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# This program is dedicated to the public domain under the CC0 license.
"""
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,
ConversationHandler, PicklePersistence)
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('{} - {}'.format(key, value))
return "\n".join(facts).join(['\n', '\n'])
def start(update, context):
reply_text = "Hi! My name is Doctor Botter."
if context.user_data:
reply_text += " You already told me your {}. Why don't you tell me something more " \
"about yourself? Or change anything I " \
"already know.".format(", ".join(context.user_data.keys()))
else:
reply_text += " I will hold a more complex conversation with you. Why don't you tell me " \
"something about yourself?"
update.message.reply_text(reply_text, reply_markup=markup)
return CHOOSING
def regular_choice(update, context):
text = update.message.text.lower()
context.user_data['choice'] = text
if context.user_data.get(text):
reply_text = 'Your {}, I already know the following ' \
'about that: {}'.format(text, context.user_data[text])
else:
reply_text = 'Your {}? Yes, I would love to hear about that!'.format(text)
update.message.reply_text(reply_text)
return TYPING_REPLY
def custom_choice(update, context):
update.message.reply_text('Alright, please send me the category first, '
'for example "Most impressive skill"')
return TYPING_CHOICE
def received_information(update, context):
text = update.message.text
category = context.user_data['choice']
context.user_data[category] = text.lower()
del context.user_data['choice']
update.message.reply_text("Neat! Just so you know, this is what you already told me:"
"{}"
"You can tell me more, or change your opinion on "
"something.".format(facts_to_str(context.user_data)),
reply_markup=markup)
return CHOOSING
def show_data(update, context):
update.message.reply_text("This is what you already told me:"
"{}".format(facts_to_str(context.user_data)))
def done(update, context):
if 'choice' in context.user_data:
del context.user_data['choice']
update.message.reply_text("I learned these facts about you:"
"{}"
"Until next time!".format(facts_to_str(context.user_data)))
return ConversationHandler.END
def main():
# Create the Updater and pass it your bot's token.
pp = PicklePersistence(filename='conversationbot')
updater = Updater("TOKEN", persistence=pp, use_context=True)
# Get the dispatcher to register handlers
dp = updater.dispatcher
# Add conversation handler with the states CHOOSING, TYPING_CHOICE and TYPING_REPLY
conv_handler = ConversationHandler(
entry_points=[CommandHandler('start', start)],
states={
CHOOSING: [MessageHandler(Filters.regex('^(Age|Favourite colour|Number of siblings)$'),
regular_choice),
MessageHandler(Filters.regex('^Something else...$'),
custom_choice),
],
TYPING_CHOICE: [MessageHandler(Filters.text,
regular_choice),
],
TYPING_REPLY: [MessageHandler(Filters.text,
received_information),
],
},
fallbacks=[MessageHandler(Filters.regex('^Done$'), done)],
name="my_conversation",
persistent=True
)
dp.add_handler(conv_handler)
show_data_handler = CommandHandler('show_data', show_data)
dp.add_handler(show_data_handler)
# Start the Bot
updater.start_polling()
# Run the bot until you press Ctrl-C or the process receives SIGINT,
# SIGTERM or SIGABRT. This should be used most of the time, since
# start_polling() is non-blocking and will stop the bot gracefully.
updater.idle()
if __name__ == '__main__':
main()
+147
View File
@@ -0,0 +1,147 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# This program is dedicated to the public domain under the CC0 license.
"""
Basic example for a bot that works with polls. Only 3 people are allowed to interact with each
poll/quiz the bot generates. The preview command generates a closed poll/quiz, excatly like the
one the user sends the bot
"""
import logging
from telegram import (Poll, ParseMode, KeyboardButton, KeyboardButtonPollType,
ReplyKeyboardMarkup, ReplyKeyboardRemove)
from telegram.ext import (Updater, CommandHandler, PollAnswerHandler, PollHandler, MessageHandler,
Filters)
from telegram.utils.helpers import mention_html
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO)
logger = logging.getLogger(__name__)
def start(update, context):
"""Inform user about what this bot can do"""
update.message.reply_text('Please select /poll to get a Poll, /quiz to get a Quiz or /preview'
' to generate a preview for your poll')
def poll(update, context):
"""Sends a predefined poll"""
questions = ["Good", "Really good", "Fantastic", "Great"]
message = context.bot.send_poll(update.effective_user.id, "How are you?", questions,
is_anonymous=False, allows_multiple_answers=True)
# Save some info about the poll the bot_data for later use in receive_poll_answer
payload = {message.poll.id: {"questions": questions, "message_id": message.message_id,
"chat_id": update.effective_chat.id, "answers": 0}}
context.bot_data.update(payload)
def receive_poll_answer(update, context):
"""Summarize a users poll vote"""
answer = update.poll_answer
poll_id = answer.poll_id
try:
questions = context.bot_data[poll_id]["questions"]
# this means this poll answer update is from an old poll, we can't do our answering then
except KeyError:
return
selected_options = answer.option_ids
answer_string = ""
for question_id in selected_options:
if question_id != selected_options[-1]:
answer_string += questions[question_id] + " and "
else:
answer_string += questions[question_id]
user_mention = mention_html(update.effective_user.id, update.effective_user.full_name)
context.bot.send_message(context.bot_data[poll_id]["chat_id"],
"{} feels {}!".format(user_mention, answer_string),
parse_mode=ParseMode.HTML)
context.bot_data[poll_id]["answers"] += 1
# Close poll after three participants voted
if context.bot_data[poll_id]["answers"] == 3:
context.bot.stop_poll(context.bot_data[poll_id]["chat_id"],
context.bot_data[poll_id]["message_id"])
def quiz(update, context):
"""Send a predefined poll"""
questions = ["1", "2", "4", "20"]
message = update.effective_message.reply_poll("How many eggs do you need for a cake?",
questions, type=Poll.QUIZ, correct_option_id=2)
# Save some info about the poll the bot_data for later use in receive_quiz_answer
payload = {message.poll.id: {"chat_id": update.effective_chat.id,
"message_id": message.message_id}}
context.bot_data.update(payload)
def receive_quiz_answer(update, context):
"""Close quiz after three participants took it"""
# the bot can receive closed poll updates we don't care about
if update.poll.is_closed:
return
if update.poll.total_voter_count == 3:
try:
quiz_data = context.bot_data[update.poll.id]
# this means this poll answer update is from an old poll, we can't stop it then
except KeyError:
return
context.bot.stop_poll(quiz_data["chat_id"], quiz_data["message_id"])
def preview(update, context):
"""Ask user to create a poll and display a preview of it"""
# using this without a type lets the user chooses what he wants (quiz or poll)
button = [[KeyboardButton("Press me!", request_poll=KeyboardButtonPollType())]]
message = "Press the button to let the bot generate a preview for your poll"
# using one_time_keyboard to hide the keyboard
update.effective_message.reply_text(message,
reply_markup=ReplyKeyboardMarkup(button,
one_time_keyboard=True))
def receive_poll(update, context):
"""On receiving polls, reply to it by a closed poll copying the received poll"""
actual_poll = update.effective_message.poll
# Only need to set the question and options, since all other parameters don't matter for
# a closed poll
update.effective_message.reply_poll(
question=actual_poll.question,
options=[o.text for o in actual_poll.options],
# with is_closed true, the poll/quiz is immediately closed
is_closed=True,
reply_markup=ReplyKeyboardRemove()
)
def help_handler(update, context):
"""Display a help message"""
update.message.reply_text("Use /quiz, /poll or /preview to test this "
"bot.")
def main():
# Create the Updater and pass it your bot's token.
# Make sure to set use_context=True to use the new context based callbacks
# Post version 12 this will no longer be necessary
updater = Updater("TOKEN", use_context=True)
dp = updater.dispatcher
dp.add_handler(CommandHandler('start', start))
dp.add_handler(CommandHandler('poll', poll))
dp.add_handler(PollAnswerHandler(receive_poll_answer))
dp.add_handler(CommandHandler('quiz', quiz))
dp.add_handler(PollHandler(receive_quiz_answer))
dp.add_handler(CommandHandler('preview', preview))
dp.add_handler(MessageHandler(Filters.poll, receive_poll))
dp.add_handler(CommandHandler('help', help_handler))
# Start the Bot
updater.start_polling()
# Run the bot until the user presses Ctrl-C or the process receives SIGINT,
# SIGTERM or SIGABRT
updater.idle()
if __name__ == '__main__':
main()
+27 -28
View File
@@ -1,11 +1,10 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Simple Bot to send timed Telegram messages.
# This program is dedicated to the public domain under the CC0 license.
"""
Simple Bot to send timed Telegram messages.
This Bot uses the Updater class to handle the bot and the JobQueue to send
timed messages.
@@ -19,9 +18,10 @@ Press Ctrl-C on the command line or send a signal to the process to stop the
bot.
"""
from telegram.ext import Updater, CommandHandler
import logging
from telegram.ext import Updater, CommandHandler
# Enable logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO)
@@ -29,30 +29,34 @@ logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s
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):
# Define a few command handlers. These usually take the two arguments update and
# context. Error handlers also receive the raised TelegramError object in error.
def start(update, context):
update.message.reply_text('Hi! Use /set <seconds> to set a timer')
def alarm(bot, job):
def alarm(context):
"""Send the alarm message."""
bot.send_message(job.context, text='Beep!')
job = context.job
context.bot.send_message(job.context, text='Beep!')
def set_timer(bot, update, args, job_queue, chat_data):
def set_timer(update, context):
"""Add a job to the queue."""
chat_id = update.message.chat_id
try:
# args[0] should contain the time for the timer in seconds
due = int(args[0])
due = int(context.args[0])
if due < 0:
update.message.reply_text('Sorry we can not go back to future!')
return
# Add job to queue
job = job_queue.run_once(alarm, due, context=chat_id)
chat_data['job'] = job
# Add job to queue and stop current one if there is a timer already
if 'job' in context.chat_data:
old_job = context.chat_data['job']
old_job.schedule_removal()
new_job = context.job_queue.run_once(alarm, due, context=chat_id)
context.chat_data['job'] = new_job
update.message.reply_text('Timer successfully set!')
@@ -60,27 +64,25 @@ def set_timer(bot, update, args, job_queue, chat_data):
update.message.reply_text('Usage: /set <seconds>')
def unset(bot, update, chat_data):
def unset(update, context):
"""Remove the job if the user changed their mind."""
if 'job' not in chat_data:
if 'job' not in context.chat_data:
update.message.reply_text('You have no active timer')
return
job = chat_data['job']
job = context.chat_data['job']
job.schedule_removal()
del chat_data['job']
del context.chat_data['job']
update.message.reply_text('Timer successfully unset!')
def error(bot, update, error):
"""Log Errors caused by Updates."""
logger.warning('Update "%s" caused error "%s"', update, error)
def main():
"""Run bot."""
updater = Updater("TOKEN")
# Create the Updater and pass it your bot's token.
# Make sure to set use_context=True to use the new context based callbacks
# Post version 12 this will no longer be necessary
updater = Updater("TOKEN", use_context=True)
# Get the dispatcher to register handlers
dp = updater.dispatcher
@@ -94,9 +96,6 @@ def main():
pass_chat_data=True))
dp.add_handler(CommandHandler("unset", unset, pass_chat_data=True))
# log all errors
dp.add_error_handler(error)
# Start the Bot
updater.start_polling()
+3 -2
View File
@@ -5,6 +5,7 @@ flaky
yapf
pre-commit
beautifulsoup4
pytest
pytest-catchlog
pytest==4.2.0
pytest-timeout
wheel
attrs==19.1.0
+3 -1
View File
@@ -1,2 +1,4 @@
future>=0.16.0
certifi
tornado>=5.1
cryptography
decorator>=4.4.0
+6 -1
View File
@@ -1,6 +1,9 @@
[wheel]
universal = 1
[metadata]
license_file = LICENSE.dual
[build_sphinx]
source-dir = docs/source
build-dir = docs/build
@@ -11,7 +14,8 @@ upload-dir = docs/build/html
[flake8]
max-line-length = 99
ignore = W503
ignore = W503, W605
exclude = setup.py, docs/source/conf.py
[yapf]
based_on_style = google
@@ -24,6 +28,7 @@ addopts = --no-success-flaky-report -rsxX
filterwarnings =
error
ignore::DeprecationWarning
ignore::telegram.utils.deprecate.TelegramDeprecationWarning
[coverage:run]
branch = True
+14 -5
View File
@@ -3,6 +3,8 @@
import codecs
import os
import sys
from setuptools import setup, find_packages
@@ -18,6 +20,14 @@ def requirements():
packages = find_packages(exclude=['tests*'])
requirements = requirements()
# Allow for a package install to not use the vendored urllib3
UPSTREAM_URLLIB3_FLAG = '--with-upstream-urllib3'
if UPSTREAM_URLLIB3_FLAG in sys.argv:
sys.argv.remove(UPSTREAM_URLLIB3_FLAG)
requirements.append('urllib3 >= 1.19.1')
packages = [x for x in packages if not x.startswith('telegram.vendor.ptb_urllib3')]
with codecs.open('README.rst', 'r', 'utf-8') as fd:
fn = os.path.join('telegram', 'version.py')
@@ -35,7 +45,7 @@ with codecs.open('README.rst', 'r', 'utf-8') as fd:
description="We have made you a wrapper you can't refuse",
long_description=fd.read(),
packages=packages,
install_requires=requirements(),
install_requires=requirements,
extras_require={
'json': 'ujson',
'socks': 'PySocks'
@@ -50,10 +60,9 @@ with codecs.open('README.rst', 'r', 'utf-8') as fd:
'Topic :: Communications :: Chat',
'Topic :: Internet',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6'
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
],)
+47 -12
View File
@@ -1,7 +1,7 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2018
# Copyright (C) 2015-2020
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
@@ -19,14 +19,17 @@
"""A library that provides a Python interface to the Telegram Bot API"""
from .base import TelegramObject
from .botcommand import BotCommand
from .user import User
from .files.chatphoto import ChatPhoto
from .chat import Chat
from .chatmember import ChatMember
from .chatpermissions import ChatPermissions
from .files.photosize import PhotoSize
from .files.audio import Audio
from .files.voice import Voice
from .files.document import Document
from .files.animation import Animation
from .files.sticker import Sticker, StickerSet, MaskPosition
from .files.video import Video
from .files.contact import Contact
@@ -34,8 +37,10 @@ from .files.location import Location
from .files.venue import Venue
from .files.videonote import VideoNote
from .chataction import ChatAction
from .dice import Dice
from .userprofilephotos import UserProfilePhotos
from .keyboardbutton import KeyboardButton
from .keyboardbuttonpolltype import KeyboardButtonPollType
from .replymarkup import ReplyMarkup
from .replykeyboardmarkup import ReplyKeyboardMarkup
from .replykeyboardremove import ReplyKeyboardRemove
@@ -45,18 +50,24 @@ from .files.inputfile import InputFile
from .files.file import File
from .parsemode import ParseMode
from .messageentity import MessageEntity
from .games.animation import Animation
from .games.game import Game
from .poll import Poll, PollOption, PollAnswer
from .loginurl import LoginUrl
from .games.callbackgame import CallbackGame
from .payment.shippingaddress import ShippingAddress
from .payment.orderinfo import OrderInfo
from .payment.successfulpayment import SuccessfulPayment
from .payment.invoice import Invoice
from .passport.credentials import EncryptedCredentials
from .passport.passportfile import PassportFile
from .passport.data import IdDocumentData, PersonalDetails, ResidentialAddress
from .passport.encryptedpassportelement import EncryptedPassportElement
from .passport.passportdata import PassportData
from .inline.inlinekeyboardbutton import InlineKeyboardButton
from .inline.inlinekeyboardmarkup import InlineKeyboardMarkup
from .message import Message
from .callbackquery import CallbackQuery
from .choseninlineresult import ChosenInlineResult
from .inline.inlinekeyboardbutton import InlineKeyboardButton
from .inline.inlinekeyboardmarkup import InlineKeyboardMarkup
from .inline.inputmessagecontent import InputMessageContent
from .inline.inlinequery import InlineQuery
from .inline.inlinequeryresult import InlineQueryResult
@@ -91,21 +102,35 @@ from .payment.shippingquery import ShippingQuery
from .webhookinfo import WebhookInfo
from .games.gamehighscore import GameHighScore
from .update import Update
from .files.inputmedia import (InputMedia, InputMediaVideo, InputMediaPhoto, InputMediaAnimation,
InputMediaAudio, InputMediaDocument)
from .bot import Bot
from .constants import (MAX_MESSAGE_LENGTH, MAX_CAPTION_LENGTH, SUPPORTED_WEBHOOK_PORTS,
MAX_FILESIZE_DOWNLOAD, MAX_FILESIZE_UPLOAD,
MAX_MESSAGES_PER_SECOND_PER_CHAT, MAX_MESSAGES_PER_SECOND,
MAX_MESSAGES_PER_MINUTE_PER_GROUP)
from .files.inputmedia import InputMedia
from .files.inputmediavideo import InputMediaVideo
from .files.inputmediaphoto import InputMediaPhoto
from .version import __version__ # flake8: noqa
from .passport.passportelementerrors import (PassportElementError,
PassportElementErrorDataField,
PassportElementErrorFile,
PassportElementErrorFiles,
PassportElementErrorFrontSide,
PassportElementErrorReverseSide,
PassportElementErrorSelfie,
PassportElementErrorTranslationFile,
PassportElementErrorTranslationFiles,
PassportElementErrorUnspecified)
from .passport.credentials import (Credentials,
DataCredentials,
SecureData,
FileCredentials,
TelegramDecryptionError)
from .version import __version__ # noqa: F401
__author__ = 'devs@python-telegram-bot.org'
__all__ = [
'Audio', 'Bot', 'Chat', 'ChatMember', 'ChatAction', 'ChosenInlineResult', 'CallbackQuery',
'Contact', 'Document', 'File', 'ForceReply', 'InlineKeyboardButton',
'Audio', 'Bot', 'Chat', 'ChatMember', 'ChatPermissions', 'ChatAction', 'ChosenInlineResult',
'CallbackQuery', 'Contact', 'Document', 'File', 'ForceReply', 'InlineKeyboardButton',
'InlineKeyboardMarkup', 'InlineQuery', 'InlineQueryResult', 'InlineQueryResult',
'InlineQueryResultArticle', 'InlineQueryResultAudio', 'InlineQueryResultCachedAudio',
'InlineQueryResultCachedDocument', 'InlineQueryResultCachedGif',
@@ -116,7 +141,8 @@ __all__ = [
'InlineQueryResultPhoto', 'InlineQueryResultVenue', 'InlineQueryResultVideo',
'InlineQueryResultVoice', 'InlineQueryResultGame', 'InputContactMessageContent', 'InputFile',
'InputLocationMessageContent', 'InputMessageContent', 'InputTextMessageContent',
'InputVenueMessageContent', 'KeyboardButton', 'Location', 'Message', 'MessageEntity',
'InputVenueMessageContent', 'Location', 'EncryptedCredentials',
'PassportFile', 'EncryptedPassportElement', 'PassportData', 'Message', 'MessageEntity',
'ParseMode', 'PhotoSize', 'ReplyKeyboardRemove', 'ReplyKeyboardMarkup', 'ReplyMarkup',
'Sticker', 'TelegramError', 'TelegramObject', 'Update', 'User', 'UserProfilePhotos', 'Venue',
'Video', 'Voice', 'MAX_MESSAGE_LENGTH', 'MAX_CAPTION_LENGTH', 'SUPPORTED_WEBHOOK_PORTS',
@@ -125,5 +151,14 @@ __all__ = [
'Game', 'GameHighScore', 'VideoNote', 'LabeledPrice', 'SuccessfulPayment', 'ShippingOption',
'ShippingAddress', 'PreCheckoutQuery', 'OrderInfo', 'Invoice', 'ShippingQuery', 'ChatPhoto',
'StickerSet', 'MaskPosition', 'CallbackGame', 'InputMedia', 'InputMediaPhoto',
'InputMediaVideo'
'InputMediaVideo', 'PassportElementError', 'PassportElementErrorFile',
'PassportElementErrorReverseSide', 'PassportElementErrorFrontSide',
'PassportElementErrorFiles', 'PassportElementErrorDataField', 'PassportElementErrorFile',
'Credentials', 'DataCredentials', 'SecureData', 'FileCredentials', 'IdDocumentData',
'PersonalDetails', 'ResidentialAddress', 'InputMediaVideo', 'InputMediaAnimation',
'InputMediaAudio', 'InputMediaDocument', 'TelegramDecryptionError',
'PassportElementErrorSelfie', 'PassportElementErrorTranslationFile',
'PassportElementErrorTranslationFiles', 'PassportElementErrorUnspecified', 'Poll',
'PollOption', 'PollAnswer', 'LoginUrl', 'KeyboardButton', 'KeyboardButtonPollType', 'Dice',
'BotCommand'
]
+17 -6
View File
@@ -1,7 +1,7 @@
# !/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2018
# Copyright (C) 2015-2020
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
@@ -17,18 +17,29 @@
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
import sys
import subprocess
import certifi
import future
from . import __version__ as telegram_ver
def _git_revision():
try:
output = subprocess.check_output(["git", "describe", "--long", "--tags"],
stderr=subprocess.STDOUT)
except (subprocess.SubprocessError, OSError):
return None
return output.decode().strip()
def print_ver_info():
print('python-telegram-bot {0}'.format(telegram_ver))
print('certifi {0}'.format(certifi.__version__))
print('future {0}'.format(future.__version__))
print('Python {0}'.format(sys.version.replace('\n', ' ')))
git_revision = _git_revision()
print('python-telegram-bot {}'.format(telegram_ver) + (' ({})'.format(git_revision)
if git_revision else ''))
print('certifi {}'.format(certifi.__version__))
print('Python {}'.format(sys.version.replace('\n', ' ')))
def main():
+5 -8
View File
@@ -1,7 +1,7 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2018
# Copyright (C) 2015-2020
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
@@ -23,13 +23,10 @@ try:
except ImportError:
import json
from abc import ABCMeta
class TelegramObject(object):
class TelegramObject:
"""Base class for most telegram objects."""
__metaclass__ = ABCMeta
_id_attrs = ()
def __str__(self):
@@ -60,7 +57,7 @@ class TelegramObject(object):
data = dict()
for key in iter(self.__dict__):
if key in ('bot', '_id_attrs'):
if key == 'bot' or key.startswith('_'):
continue
value = self.__dict__[key]
@@ -77,9 +74,9 @@ class TelegramObject(object):
def __eq__(self, other):
if isinstance(other, self.__class__):
return self._id_attrs == other._id_attrs
return super(TelegramObject, self).__eq__(other) # pylint: disable=no-member
return super().__eq__(other) # pylint: disable=no-member
def __hash__(self):
if self._id_attrs:
return hash((self.__class__, self._id_attrs)) # pylint: disable=no-member
return super(TelegramObject, self).__hash__()
return super().__hash__()
+1349 -436
View File
File diff suppressed because it is too large Load Diff
+46
View File
@@ -0,0 +1,46 @@
#!/usr/bin/env python
# pylint: disable=R0903
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2020
# 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 Bot Command."""
from telegram import TelegramObject
class BotCommand(TelegramObject):
"""
This object represents a bot command.
Attributes:
command (:obj:`str`): Text of the command.
description (:obj:`str`): Description of the command.
Args:
command (:obj:`str`): Text of the command, 1-32 characters. Can contain only lowercase
English letters, digits and underscores.
description (:obj:`str`): Description of the command, 3-256 characters.
"""
def __init__(self, command, description, **kwargs):
self.command = command
self.description = description
@classmethod
def de_json(cls, data, bot):
if not data:
return None
return cls(**data)
+43 -30
View File
@@ -1,7 +1,7 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2018
# Copyright (C) 2015-2020
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
@@ -36,30 +36,31 @@ class CallbackQuery(TelegramObject):
Attributes:
id (:obj:`str`): Unique identifier for this query.
from_user (:class:`telegram.User`): Sender.
chat_instance (:obj:`str`): Global identifier, uniquely corresponding to the chat to which
the message with the callback button was sent.
message (:class:`telegram.Message`): Optional. Message with the callback button that
originated the query.
data (:obj:`str`): Optional. Data associated with the callback button.
inline_message_id (:obj:`str`): Optional. Identifier of the message sent via the bot in
inline mode, that originated the query.
chat_instance (:obj:`str`): Optional. Global identifier, uniquely corresponding to the chat
to which the message with the callback button was sent.
data (:obj:`str`): Optional. Data associated with the callback button.
game_short_name (:obj:`str`): Optional. Short name of a Game to be returned.
bot (:class:`telegram.Bot`, optional): The Bot to use for instance methods.
Args:
id (:obj:`str`): Unique identifier for this query.
from_user (:class:`telegram.User`): Sender.
chat_instance (:obj:`str`): Global identifier, uniquely corresponding to the chat to which
the message with the callback button was sent. Useful for high scores in games.
message (:class:`telegram.Message`, optional): Message with the callback button that
originated the query. Note that message content and message date will not be available
if the message is too old.
inline_message_id (:obj:`str`, optional): Identifier of the message sent via the bot in
inline mode, that originated the query.
chat_instance (:obj:`str`, optional): Global identifier, uniquely corresponding to the chat
to which the message with the callback button was sent. Useful for high scores in
games.
data (:obj:`str`, optional): Data associated with the callback button. Be aware that a bad
client can send arbitrary data in this field.
inline_message_id (:obj:`str`, optional): Identifier of the message sent via the bot in
inline mode, that originated the query.
game_short_name (:obj:`str`, optional): Short name of a Game to be returned, serves as
the unique identifier for the game
bot (:class:`telegram.Bot`, optional): The Bot to use for instance methods.
Note:
After the user presses an inline button, Telegram clients will display a progress bar
@@ -98,10 +99,13 @@ class CallbackQuery(TelegramObject):
if not data:
return None
data = super(CallbackQuery, cls).de_json(data, bot)
data = super().de_json(data, bot)
data['from_user'] = User.de_json(data.get('from'), bot)
data['message'] = Message.de_json(data.get('message'), bot)
message = data.get('message')
if message:
message['default_quote'] = data.get('default_quote')
data['message'] = Message.de_json(message, bot)
return cls(bot=bot, **data)
@@ -116,16 +120,16 @@ class CallbackQuery(TelegramObject):
"""
return self.bot.answerCallbackQuery(self.id, *args, **kwargs)
def edit_message_text(self, *args, **kwargs):
def edit_message_text(self, text, *args, **kwargs):
"""Shortcut for either::
bot.edit_message_text(chat_id=update.callback_query.message.chat_id,
bot.edit_message_text(text, chat_id=update.callback_query.message.chat_id,
message_id=update.callback_query.message.message_id,
*args, **kwargs)
or::
bot.edit_message_text(inline_message_id=update.callback_query.inline_message_id,
bot.edit_message_text(text, inline_message_id=update.callback_query.inline_message_id,
*args, **kwargs)
Returns:
@@ -134,22 +138,24 @@ class CallbackQuery(TelegramObject):
"""
if self.inline_message_id:
return self.bot.edit_message_text(
inline_message_id=self.inline_message_id, *args, **kwargs)
return self.bot.edit_message_text(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)
return self.bot.edit_message_text(text, chat_id=self.message.chat_id,
message_id=self.message.message_id, *args, **kwargs)
def edit_message_caption(self, *args, **kwargs):
def edit_message_caption(self, caption, *args, **kwargs):
"""Shortcut for either::
bot.edit_message_caption(chat_id=update.callback_query.message.chat_id,
bot.edit_message_caption(caption=caption,
chat_id=update.callback_query.message.chat_id,
message_id=update.callback_query.message.message_id,
*args, **kwargs)
or::
bot.edit_message_caption(inline_message_id=update.callback_query.inline_message_id,
bot.edit_message_caption(caption=caption
inline_message_id=update.callback_query.inline_message_id,
*args, **kwargs)
Returns:
@@ -158,22 +164,26 @@ class CallbackQuery(TelegramObject):
"""
if self.inline_message_id:
return self.bot.edit_message_caption(
inline_message_id=self.inline_message_id, *args, **kwargs)
return self.bot.edit_message_caption(caption=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)
return self.bot.edit_message_caption(caption=caption, chat_id=self.message.chat_id,
message_id=self.message.message_id,
*args, **kwargs)
def edit_message_reply_markup(self, *args, **kwargs):
def edit_message_reply_markup(self, reply_markup, *args, **kwargs):
"""Shortcut for either::
bot.edit_message_replyMarkup(chat_id=update.callback_query.message.chat_id,
message_id=update.callback_query.message.message_id,
reply_markup=reply_markup,
*args, **kwargs)
or::
bot.edit_message_reply_markup(inline_message_id=update.callback_query.inline_message_id,
reply_markup=reply_markup,
*args, **kwargs)
Returns:
@@ -182,8 +192,11 @@ class CallbackQuery(TelegramObject):
"""
if self.inline_message_id:
return self.bot.edit_message_reply_markup(
inline_message_id=self.inline_message_id, *args, **kwargs)
return self.bot.edit_message_reply_markup(reply_markup=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)
return self.bot.edit_message_reply_markup(reply_markup=reply_markup,
chat_id=self.message.chat_id,
message_id=self.message.message_id,
*args, **kwargs)
+95 -25
View File
@@ -2,7 +2,7 @@
# pylint: disable=C0103,W0622
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2018
# Copyright (C) 2015-2020
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
@@ -20,6 +20,7 @@
"""This module contains an object that represents a Telegram Chat."""
from telegram import TelegramObject, ChatPhoto
from .chatpermissions import ChatPermissions
class Chat(TelegramObject):
@@ -32,12 +33,15 @@ class Chat(TelegramObject):
username (:obj:`str`): Optional. Username.
first_name (:obj:`str`): Optional. First name of the other party in a private chat.
last_name (:obj:`str`): Optional. Last name of the other party in a private chat.
all_members_are_administrators (:obj:`bool`): Optional.
photo (:class:`telegram.ChatPhoto`): Optional. Chat photo.
description (:obj:`str`): Optional. Description, for supergroups and channel chats.
description (:obj:`str`): Optional. Description, for groups, supergroups and channel chats.
invite_link (:obj:`str`): Optional. Chat invite link, for supergroups and channel chats.
pinned_message (:class:`telegram.Message`): Optional. Pinned message, for supergroups.
Returned only in get_chat.
permissions (:class:`telegram.ChatPermission`): Optional. Default chat member permissions,
for groups and supergroups. Returned only in getChat.
slow_mode_delay (:obj:`int`): Optional. For supergroups, the minimum allowed delay between
consecutive messages sent by each unpriviledged user. Returned only in getChat.
sticker_set_name (:obj:`str`): Optional. For supergroups, name of Group sticker set.
can_set_sticker_set (:obj:`bool`): Optional. ``True``, if the bot can change group the
sticker set.
@@ -54,15 +58,17 @@ class Chat(TelegramObject):
available.
first_name(:obj:`str`, optional): First name of the other party in a private chat.
last_name(:obj:`str`, optional): Last name of the other party in a private chat.
all_members_are_administrators (:obj:`bool`, optional): True if a group has `All Members
Are Admins` enabled.
photo (:class:`telegram.ChatPhoto`, optional): Chat photo. Returned only in getChat.
description (:obj:`str`, optional): Description, for supergroups and channel chats.
description (:obj:`str`, optional): Description, for groups, supergroups and channel chats.
Returned only in get_chat.
invite_link (:obj:`str`, optional): Chat invite link, for supergroups and channel chats.
Returned only in get_chat.
pinned_message (:class:`telegram.Message`, optional): Pinned message, for supergroups.
Returned only in get_chat.
permissions (:class:`telegram.ChatPermission`): Optional. Default chat member permissions,
for groups and supergroups. Returned only in getChat.
slow_mode_delay (:obj:`int`, optional): For supergroups, the minimum allowed delay between
consecutive messages sent by each unpriviledged user. Returned only in getChat.
bot (:class:`telegram.Bot`, optional): The Bot to use for instance methods.
sticker_set_name (:obj:`str`, optional): For supergroups, name of Group sticker set.
Returned only in get_chat.
@@ -88,14 +94,15 @@ class Chat(TelegramObject):
username=None,
first_name=None,
last_name=None,
all_members_are_administrators=None,
bot=None,
photo=None,
description=None,
invite_link=None,
pinned_message=None,
permissions=None,
sticker_set_name=None,
can_set_sticker_set=None,
slow_mode_delay=None,
**kwargs):
# Required
self.id = int(id)
@@ -105,17 +112,28 @@ class Chat(TelegramObject):
self.username = username
self.first_name = first_name
self.last_name = last_name
self.all_members_are_administrators = all_members_are_administrators
# TODO: Remove (also from tests), when Telegram drops this completely
self.all_members_are_administrators = kwargs.get('all_members_are_administrators')
self.photo = photo
self.description = description
self.invite_link = invite_link
self.pinned_message = pinned_message
self.permissions = permissions
self.slow_mode_delay = slow_mode_delay
self.sticker_set_name = sticker_set_name
self.can_set_sticker_set = can_set_sticker_set
self.bot = bot
self._id_attrs = (self.id,)
@property
def link(self):
""":obj:`str`: Convenience property. If the chat has a :attr:`username`, returns a t.me
link of the chat."""
if self.username:
return "https://t.me/{}".format(self.username)
return None
@classmethod
def de_json(cls, data, bot):
if not data:
@@ -123,7 +141,11 @@ class Chat(TelegramObject):
data['photo'] = ChatPhoto.de_json(data.get('photo'), bot)
from telegram import Message
data['pinned_message'] = Message.de_json(data.get('pinned_message'), bot)
pinned_message = data.get('pinned_message')
if pinned_message:
pinned_message['default_quote'] = data.get('default_quote')
data['pinned_message'] = Message.de_json(pinned_message, bot)
data['permissions'] = ChatPermissions.de_json(data.get('permissions'), bot)
return cls(bot=bot, **data)
@@ -213,10 +235,32 @@ class Chat(TelegramObject):
"""
return self.bot.unban_chat_member(self.id, *args, **kwargs)
def set_permissions(self, *args, **kwargs):
"""Shortcut for::
bot.set_chat_permissions(update.message.chat.id, *args, **kwargs)
Returns:
:obj:`bool`: If the action was sent successfully.
"""
return self.bot.set_chat_permissions(self.id, *args, **kwargs)
def set_administrator_custom_title(self, *args, **kwargs):
"""Shortcut for::
bot.set_chat_administrator_custom_title(update.message.chat.id, *args, **kwargs)
Returns:
:obj:`bool`: If the action was sent successfully.
"""
return self.bot.set_chat_administrator_custom_title(self.id, *args, **kwargs)
def send_message(self, *args, **kwargs):
"""Shortcut for::
bot.send_message(Chat.chat_id, *args, **kwargs)
bot.send_message(Chat.id, *args, **kwargs)
Where Chat is the current instance.
@@ -224,12 +268,12 @@ class Chat(TelegramObject):
:class:`telegram.Message`: On success, instance representing the message posted.
"""
return self.bot.send_message(chat_id=self.id, *args, **kwargs)
return self.bot.send_message(self.id, *args, **kwargs)
def send_photo(self, *args, **kwargs):
"""Shortcut for::
bot.send_photo(Chat.chat_id, *args, **kwargs)
bot.send_photo(Chat.id, *args, **kwargs)
Where Chat is the current instance.
@@ -237,12 +281,12 @@ class Chat(TelegramObject):
:class:`telegram.Message`: On success, instance representing the message posted.
"""
return self.bot.send_photo(chat_id=self.id, *args, **kwargs)
return self.bot.send_photo(self.id, *args, **kwargs)
def send_audio(self, *args, **kwargs):
"""Shortcut for::
bot.send_audio(Chat.chat_id, *args, **kwargs)
bot.send_audio(Chat.id, *args, **kwargs)
Where Chat is the current instance.
@@ -250,12 +294,12 @@ class Chat(TelegramObject):
:class:`telegram.Message`: On success, instance representing the message posted.
"""
return self.bot.send_audio(chat_id=self.id, *args, **kwargs)
return self.bot.send_audio(self.id, *args, **kwargs)
def send_document(self, *args, **kwargs):
"""Shortcut for::
bot.send_document(Chat.chat_id, *args, **kwargs)
bot.send_document(Chat.id, *args, **kwargs)
Where Chat is the current instance.
@@ -263,12 +307,25 @@ class Chat(TelegramObject):
:class:`telegram.Message`: On success, instance representing the message posted.
"""
return self.bot.send_document(chat_id=self.id, *args, **kwargs)
return self.bot.send_document(self.id, *args, **kwargs)
def send_animation(self, *args, **kwargs):
"""Shortcut for::
bot.send_animation(Chat.id, *args, **kwargs)
Where Chat is the current instance.
Returns:
:class:`telegram.Message`: On success, instance representing the message posted.
"""
return self.bot.send_animation(self.id, *args, **kwargs)
def send_sticker(self, *args, **kwargs):
"""Shortcut for::
bot.send_sticker(Chat.chat_id, *args, **kwargs)
bot.send_sticker(Chat.id, *args, **kwargs)
Where Chat is the current instance.
@@ -276,12 +333,12 @@ class Chat(TelegramObject):
:class:`telegram.Message`: On success, instance representing the message posted.
"""
return self.bot.send_sticker(chat_id=self.id, *args, **kwargs)
return self.bot.send_sticker(self.id, *args, **kwargs)
def send_video(self, *args, **kwargs):
"""Shortcut for::
bot.send_video(Chat.chat_id, *args, **kwargs)
bot.send_video(Chat.id, *args, **kwargs)
Where Chat is the current instance.
@@ -289,12 +346,12 @@ class Chat(TelegramObject):
:class:`telegram.Message`: On success, instance representing the message posted.
"""
return self.bot.send_video(chat_id=self.id, *args, **kwargs)
return self.bot.send_video(self.id, *args, **kwargs)
def send_video_note(self, *args, **kwargs):
"""Shortcut for::
bot.send_video_note(Chat.chat_id, *args, **kwargs)
bot.send_video_note(Chat.id, *args, **kwargs)
Where Chat is the current instance.
@@ -302,12 +359,12 @@ class Chat(TelegramObject):
:class:`telegram.Message`: On success, instance representing the message posted.
"""
return self.bot.send_video_note(chat_id=self.id, *args, **kwargs)
return self.bot.send_video_note(self.id, *args, **kwargs)
def send_voice(self, *args, **kwargs):
"""Shortcut for::
bot.send_voice(Chat.chat_id, *args, **kwargs)
bot.send_voice(Chat.id, *args, **kwargs)
Where Chat is the current instance.
@@ -315,4 +372,17 @@ class Chat(TelegramObject):
:class:`telegram.Message`: On success, instance representing the message posted.
"""
return self.bot.send_voice(chat_id=self.id, *args, **kwargs)
return self.bot.send_voice(self.id, *args, **kwargs)
def send_poll(self, *args, **kwargs):
"""Shortcut for::
bot.send_poll(Chat.id, *args, **kwargs)
Where Chat is the current instance.
Returns:
:class:`telegram.Message`: On success, instance representing the message posted.
"""
return self.bot.send_poll(self.id, *args, **kwargs)
+2 -2
View File
@@ -2,7 +2,7 @@
# pylint: disable=R0903
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2018
# Copyright (C) 2015-2020
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
@@ -20,7 +20,7 @@
"""This module contains an object that represents a Telegram ChatAction."""
class ChatAction(object):
class ChatAction:
"""Helper class to provide constants for different chatactions."""
FIND_LOCATION = 'find_location'
+29 -16
View File
@@ -1,7 +1,7 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2018
# Copyright (C) 2015-2020
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
@@ -28,28 +28,32 @@ class ChatMember(TelegramObject):
Attributes:
user (:class:`telegram.User`): Information about the user.
status (:obj:`str`): The member's status in the chat.
custom_title (:obj:`str`): Optional. Custom title for owner and administrators.
until_date (:class:`datetime.datetime`): Optional. Date when restrictions will be lifted
for this user.
can_be_edited (:obj:`bool`): Optional. If the bot is allowed to edit administrator
privileges of that user.
can_change_info (:obj:`bool`): Optional. If the administrator can change the chat title,
photo and other settings.
can_change_info (:obj:`bool`): Optional. If the user can change the chat title, photo and
other settings.
can_post_messages (:obj:`bool`): Optional. If the administrator can post in the channel.
can_edit_messages (:obj:`bool`): Optional. If the administrator can edit messages of other
users.
can_delete_messages (:obj:`bool`): Optional. If the administrator can delete messages of
other users.
can_invite_users (:obj:`bool`): Optional. If the administrator can invite new users to the
chat.
can_invite_users (:obj:`bool`): Optional. If the user can invite new users to the chat.
can_restrict_members (:obj:`bool`): Optional. If the administrator can restrict, ban or
unban chat members.
can_pin_messages (:obj:`bool`): Optional. If the administrator can pin messages.
can_pin_messages (:obj:`bool`): Optional. If the user can pin messages.
can_promote_members (:obj:`bool`): Optional. If the administrator can add new
administrators.
is_member (:obj:`bool`): Optional. Restricted only. True, if the user is a member of the
chat at the moment of the request.
can_send_messages (:obj:`bool`): Optional. If the user can send text messages, contacts,
locations and venues.
can_send_media_messages (:obj:`bool`): Optional. If the user can send media messages,
implies can_send_messages.
can_send_polls (:obj:`bool`): Optional. True, if the user is allowed to
send polls.
can_send_other_messages (:obj:`bool`): Optional. If the user can send animations, games,
stickers and use inline bots, implies can_send_media_messages.
can_add_web_page_previews (:obj:`bool`): Optional. If user may add web page previews to his
@@ -59,33 +63,39 @@ class ChatMember(TelegramObject):
user (:class:`telegram.User`): Information about the user.
status (:obj:`str`): The member's status in the chat. Can be 'creator', 'administrator',
'member', 'restricted', 'left' or 'kicked'.
custom_title (:obj:`str`, optional): Owner and administrators only.
Custom title for this user.
until_date (:class:`datetime.datetime`, optional): Restricted and kicked only. Date when
restrictions will be lifted for this user.
can_be_edited (:obj:`bool`, optional): Administrators only. True, if the bot is allowed to
edit administrator privileges of that user.
can_change_info (:obj:`bool`, optional): Administrators only. True, if the administrator
can change the chat title, photo and other settings.
can_change_info (:obj:`bool`, optional): Administrators and restricted only. True, if the
user can change the chat title, photo and other settings.
can_post_messages (:obj:`bool`, optional): Administrators only. True, if the administrator
can post in the channel, channels only.
can_edit_messages (:obj:`bool`, optional): Administrators only. True, if the administrator
can edit messages of other users, channels only.
can_delete_messages (:obj:`bool`, optional): Administrators only. True, if the
administrator can delete messages of other user.
can_invite_users (:obj:`bool`, optional): Administrators only. True, if the administrator
can invite new users to the chat.
can_invite_users (:obj:`bool`, optional): Administrators and restricted only. True, if the
user can invite new users to the chat.
can_restrict_members (:obj:`bool`, optional): Administrators only. True, if the
administrator can restrict, ban or unban chat members.
can_pin_messages (:obj:`bool`, optional): Administrators only. True, if the administrator
can pin messages, supergroups only.
can_pin_messages (:obj:`bool`, optional): Administrators and restricted only. True, if the
user can pin messages, supergroups only.
can_promote_members (:obj:`bool`, optional): Administrators only. True, if the
administrator can add new administrators with a subset of his own privileges or demote
administrators that he has promoted, directly or indirectly (promoted by administrators
that were appointed by the user).
is_member (:obj:`bool`, optional): Restricted only. True, if the user is a member of the
chat at the moment of the request.
can_send_messages (:obj:`bool`, optional): Restricted only. True, if the user can send text
messages, contacts, locations and venues.
can_send_media_messages (:obj:`bool`, optional): Restricted only. True, if the user can
send audios, documents, photos, videos, video notes and voice notes, implies
can_send_messages.
can_send_polls (:obj:`bool`, optional): Restricted only. True, if the user is allowed to
send polls.
can_send_other_messages (:obj:`bool`, optional): Restricted only. True, if the user can
send animations, games, stickers and use inline bots, implies can_send_media_messages.
can_add_web_page_previews (:obj:`bool`, optional): Restricted only. True, if user may add
@@ -110,11 +120,12 @@ class ChatMember(TelegramObject):
can_delete_messages=None, can_invite_users=None,
can_restrict_members=None, can_pin_messages=None,
can_promote_members=None, can_send_messages=None,
can_send_media_messages=None, can_send_other_messages=None,
can_add_web_page_previews=None, **kwargs):
can_send_media_messages=None, can_send_polls=None, can_send_other_messages=None,
can_add_web_page_previews=None, is_member=None, custom_title=None, **kwargs):
# Required
self.user = user
self.status = status
self.custom_title = custom_title
self.until_date = until_date
self.can_be_edited = can_be_edited
self.can_change_info = can_change_info
@@ -127,8 +138,10 @@ class ChatMember(TelegramObject):
self.can_promote_members = can_promote_members
self.can_send_messages = can_send_messages
self.can_send_media_messages = can_send_media_messages
self.can_send_polls = can_send_polls
self.can_send_other_messages = can_send_other_messages
self.can_add_web_page_previews = can_add_web_page_previews
self.is_member = is_member
self._id_attrs = (self.user, self.status)
@@ -137,7 +150,7 @@ class ChatMember(TelegramObject):
if not data:
return None
data = super(ChatMember, cls).de_json(data, bot)
data = super().de_json(data, bot)
data['user'] = User.de_json(data.get('user'), bot)
data['until_date'] = from_timestamp(data.get('until_date', None))
@@ -145,7 +158,7 @@ class ChatMember(TelegramObject):
return cls(**data)
def to_dict(self):
data = super(ChatMember, self).to_dict()
data = super().to_dict()
data['until_date'] = to_timestamp(self.until_date)
+92
View File
@@ -0,0 +1,92 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2020
# 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 ChatPermission."""
from telegram import TelegramObject
class ChatPermissions(TelegramObject):
"""Describes actions that a non-administrator user is allowed to take in a chat.
Note:
Though not stated explicitly in the offical docs, Telegram changes not only the permissions
that are set, but also sets all the others to :obj:`False`. However, since not documented,
this behaviour may change unbeknown to PTB.
Attributes:
can_send_messages (:obj:`bool`): Optional. True, if the user is allowed to send text
messages, contacts, locations and venues.
can_send_media_messages (:obj:`bool`): Optional. True, if the user is allowed to send
audios, documents, photos, videos, video notes and voice notes, implies
:attr:`can_send_messages`.
can_send_polls (:obj:`bool`): Optional. True, if the user is allowed to send polls, implies
:attr:`can_send_messages`.
can_send_other_messages (:obj:`bool`): Optional. True, if the user is allowed to send
animations, games, stickers and use inline bots, implies
:attr:`can_send_media_messages`.
can_add_web_page_previews (:obj:`bool`): Optional. True, if the user is allowed to add web
page previews to their messages, implies :attr:`can_send_media_messages`.
can_change_info (:obj:`bool`): Optional. True, if the user is allowed to change the chat
title, photo and other settings. Ignored in public supergroups.
can_invite_users (:obj:`bool`): Optional. True, if the user is allowed to invite new users
to the chat.
can_pin_messages (:obj:`bool`): Optional. True, if the user is allowed to pin messages.
Ignored in public supergroups.
Args:
can_send_messages (:obj:`bool`, optional): True, if the user is allowed to send text
messages, contacts, locations and venues.
can_send_media_messages (:obj:`bool`, optional): True, if the user is allowed to send
audios, documents, photos, videos, video notes and voice notes, implies
:attr:`can_send_messages`.
can_send_polls (:obj:`bool`, optional): True, if the user is allowed to send polls, implies
:attr:`can_send_messages`.
can_send_other_messages (:obj:`bool`, optional): True, if the user is allowed to send
animations, games, stickers and use inline bots, implies
:attr:`can_send_media_messages`.
can_add_web_page_previews (:obj:`bool`, optional): True, if the user is allowed to add web
page previews to their messages, implies :attr:`can_send_media_messages`.
can_change_info (:obj:`bool`, optional): True, if the user is allowed to change the chat
title, photo and other settings. Ignored in public supergroups.
can_invite_users (:obj:`bool`, optional): True, if the user is allowed to invite new users
to the chat.
can_pin_messages (:obj:`bool`, optional): True, if the user is allowed to pin messages.
Ignored in public supergroups.
"""
def __init__(self, can_send_messages=None, can_send_media_messages=None, can_send_polls=None,
can_send_other_messages=None, can_add_web_page_previews=None,
can_change_info=None, can_invite_users=None, can_pin_messages=None, **kwargs):
# Required
self.can_send_messages = can_send_messages
self.can_send_media_messages = can_send_media_messages
self.can_send_polls = can_send_polls
self.can_send_other_messages = can_send_other_messages
self.can_add_web_page_previews = can_add_web_page_previews
self.can_change_info = can_change_info
self.can_invite_users = can_invite_users
self.can_pin_messages = can_pin_messages
@classmethod
def de_json(cls, data, bot):
if not data:
return None
return cls(**data)

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