mirror of
https://github.com/python-telegram-bot/python-telegram-bot.git
synced 2026-06-28 04:05:01 +00:00
Compare commits
48 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 259a1faedc | |||
| 09bdb88822 | |||
| 937be3d2e8 | |||
| aa3ebb1180 | |||
| 4473d620de | |||
| 4689a80c2e | |||
| 353410242f | |||
| 8acff56145 | |||
| d4b5bd40a5 | |||
| d2059ed184 | |||
| f8a17cddcb | |||
| 9e2357bc33 | |||
| 42daf96d20 | |||
| 87afd98e02 | |||
| 247577b2e2 | |||
| 94abf16a7f | |||
| 3d8abc184a | |||
| efbd951b74 | |||
| 3ff4cc4445 | |||
| 32afc007aa | |||
| c758c19ef4 | |||
| 3bef2fa752 | |||
| b4cabecca2 | |||
| 0a8abccc78 | |||
| 5ff34fc0ba | |||
| 78fee3c1dc | |||
| 38d6f4d9f2 | |||
| 1ec12343f0 | |||
| b5196f00b2 | |||
| 39c679e519 | |||
| 7a6d2be101 | |||
| ef74c525b2 | |||
| 6d453b7fa2 | |||
| 716f52684f | |||
| 42497367c1 | |||
| b77b329dd6 | |||
| 5efd5e2586 | |||
| cbfb7df643 | |||
| 712baf0c07 | |||
| 59659eaf5e | |||
| 3ccf40e8cc | |||
| 38e3b91a87 | |||
| e182046376 | |||
| 1530ed20e5 | |||
| 2b221da9b9 | |||
| d9f77d6ee1 | |||
| 698a91427a | |||
| 5956aae235 |
@@ -5,5 +5,6 @@ formats:
|
||||
|
||||
python:
|
||||
setup_py_install: true
|
||||
version: 3
|
||||
|
||||
requirements_file: docs/requirements-docs.txt
|
||||
|
||||
+3
-1
@@ -4,6 +4,7 @@ python:
|
||||
- "3.4"
|
||||
- "3.5"
|
||||
- "3.6"
|
||||
- "3.7-dev"
|
||||
- "pypy-5.7.1"
|
||||
|
||||
dist: trusty
|
||||
@@ -23,7 +24,8 @@ before_cache:
|
||||
|
||||
install:
|
||||
- pip install -U codecov pytest-cov
|
||||
- pip install -U wheel
|
||||
- echo $TRAVIS_PYTHON_VERSION
|
||||
- if [[ $TRAVIS_PYTHON_VERSION == '3.7'* ]]; then pip install -U git+https://github.com/yaml/pyyaml.git; fi
|
||||
- pip install -U -r requirements.txt
|
||||
- pip install -U -r requirements-dev.txt
|
||||
- if [[ $TRAVIS_PYTHON_VERSION != 'pypy'* ]]; then pip install ujson; fi
|
||||
|
||||
+7
-3
@@ -3,8 +3,8 @@ Credits
|
||||
|
||||
``python-telegram-bot`` was originally created by
|
||||
`Leandro Toledo <https://github.com/leandrotoledo>`_ and is now maintained by
|
||||
`Jannes Höke <https://github.com/jh0ker>`_ (`@jh0ker <https://t.me/jh0ker>`_ on Telegram) and
|
||||
`Noam Meltzer <https://github.com/tsnoam>`_.
|
||||
`Jannes Höke <https://github.com/jh0ker>`_ (`@jh0ker <https://t.me/jh0ker>`_ on Telegram),
|
||||
`Noam Meltzer <https://github.com/tsnoam>`_, `Pieter Schutz <https://github.com/eldinnie>`_ and `Jasmin Bom <https://github.com/jsmnbom>`_.
|
||||
|
||||
We're vendoring urllib3 as part of ``python-telegram-bot`` which is distributed under the MIT
|
||||
license. For more info, full credits & license terms, the sources can be found here:
|
||||
@@ -24,6 +24,7 @@ The following wonderful people contributed directly or indirectly to this projec
|
||||
- `daimajia <https://github.com/daimajia>`_
|
||||
- `Daniel Reed <https://github.com/nmlorg>`_
|
||||
- `Eli Gao <https://github.com/eligao>`_
|
||||
- `Emilio Molinari <https://github.com/xates>`_
|
||||
- `ErgoZ Riftbit Vaper <https://github.com/ergoz>`_
|
||||
- `Eugene Lisitsky <https://github.com/lisitsky>`_
|
||||
- `Eugenio Panadero <https://github.com/azogue>`_
|
||||
@@ -31,7 +32,7 @@ The following wonderful people contributed directly or indirectly to this projec
|
||||
- `franciscod <https://github.com/franciscod>`_
|
||||
- `Hugo Damer <https://github.com/HakimusGIT>`_
|
||||
- `ihoru <https://github.com/ihoru>`_
|
||||
- `Jacob Bom <https://github.com/bomjacob>`_
|
||||
- `Jasmin Bom <https://github.com/jsmnbom>`_
|
||||
- `JASON0916 <https://github.com/JASON0916>`_
|
||||
- `jeffffc <https://github.com/jeffffc>`_
|
||||
- `Jelle Besseling <https://github.com/pingiun>`_
|
||||
@@ -52,6 +53,7 @@ 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>`_
|
||||
@@ -62,8 +64,10 @@ The following wonderful people contributed directly or indirectly to this projec
|
||||
- `Simon Schürrle <https://github.com/SitiSchu>`_
|
||||
- `sooyhwang <https://github.com/sooyhwang>`_
|
||||
- `thodnev <https://github.com/thodnev>`_
|
||||
- `Trainer Jono <https://github.com/Tr-Jono>`_
|
||||
- `Valentijn <https://github.com/Faalentijn>`_
|
||||
- `voider1 <https://github.com/voider1>`_
|
||||
- `Wagner Macedo <https://github.com/wagnerluis1982>`_
|
||||
- `wjt <https://github.com/wjt>`_
|
||||
|
||||
Please add yourself here alphabetically when you submit your first pull request.
|
||||
|
||||
+142
@@ -1,6 +1,148 @@
|
||||
=======
|
||||
Changes
|
||||
=======
|
||||
|
||||
**2018-09-01**
|
||||
*Released 11.1.0*
|
||||
|
||||
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
|
||||
|
||||
**2018-08-29**
|
||||
*Released 11.0.0*
|
||||
|
||||
Fully support Bot API version 4.0!
|
||||
(also some bugfixes :))
|
||||
|
||||
Telegram Passport (`#1174`_):
|
||||
|
||||
- Add full support for telegram passport.
|
||||
- New types: PassportData, PassportFile, EncryptedPassportElement, EncryptedCredentials, PassportElementError, PassportElementErrorDataField, PassportElementErrorFrontSide, PassportElementErrorReverseSide, PassportElementErrorSelfie, PassportElementErrorFile and PassportElementErrorFiles.
|
||||
- New bot method: set_passport_data_errors
|
||||
- New filter: Filters.passport_data
|
||||
- Field passport_data field on Message
|
||||
- PassportData can be easily decrypted.
|
||||
- PassportFiles are automatically decrypted if originating from decrypted PassportData.
|
||||
- See new passportbot.py example for details on how to use, or go to `our telegram passport wiki page`_ for more info
|
||||
- NOTE: Passport decryption requires new dependency `cryptography`.
|
||||
|
||||
Inputfile rework (`#1184`_):
|
||||
|
||||
- Change how Inputfile is handled internally
|
||||
- This allows support for specifying the thumbnails of photos and videos using the thumb= argument in the different send\_ methods.
|
||||
- Also allows Bot.send_media_group to actually finally send more than one media.
|
||||
- Add thumb to Audio, Video and Videonote
|
||||
- Add Bot.edit_message_media together with InputMediaAnimation, InputMediaAudio, and inputMediaDocument.
|
||||
|
||||
Other Bot API 4.0 changes:
|
||||
|
||||
- Add forusquare_type to Venue, InlineQueryResultVenue, InputVenueMessageContent, and Bot.send_venue. (`#1170`_)
|
||||
- Add vCard support by adding vcard field to Contact, InlineQueryResultContact, InputContactMessageContent, and Bot.send_contact. (`#1166`_)
|
||||
- Support new message entities: CASHTAG and PHONE_NUMBER. (`#1179`_)
|
||||
- Cashtag seems to be things like `$USD` and `$GBP`, but it seems telegram doesn't currently send them to bots.
|
||||
- Phone number also seems to have limited support for now
|
||||
- Add Bot.send_animation, add width, height, and duration to Animation, and add Filters.animation. (`#1172`_)
|
||||
|
||||
Non Bot API 4.0 changes:
|
||||
|
||||
- Minor integer comparison fix (`#1147`_)
|
||||
- Fix Filters.regex failing on non-text message (`#1158`_)
|
||||
- Fix ProcessLookupError if process finishes before we kill it (`#1126`_)
|
||||
- Add t.me links for User, Chat and Message if available and update User.mention_* (`#1092`_)
|
||||
- Fix mention_markdown/html on py2 (`#1112`_)
|
||||
|
||||
.. _`#1092`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1092
|
||||
.. _`#1112`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1112
|
||||
.. _`#1126`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1126
|
||||
.. _`#1147`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1147
|
||||
.. _`#1158`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1158
|
||||
.. _`#1166`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1166
|
||||
.. _`#1170`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1170
|
||||
.. _`#1174`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1174
|
||||
.. _`#1172`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1172
|
||||
.. _`#1179`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1179
|
||||
.. _`#1184`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1184
|
||||
.. _`our telegram passport wiki page`: https://git.io/fAvYd
|
||||
|
||||
**2018-05-02**
|
||||
*Released 10.1.0*
|
||||
|
||||
Fixes changing previous behaviour:
|
||||
|
||||
- Add urllib3 fix for socks5h support (`#1085`_)
|
||||
- Fix send_sticker() timeout=20 (`#1088`_)
|
||||
|
||||
Fixes:
|
||||
|
||||
- Add a caption_entity filter for filtering caption entities (`#1068`_)
|
||||
- Inputfile encode filenames (`#1086`_)
|
||||
- InputFile: Fix proper naming of file when reading from subprocess.PIPE (`#1079`_)
|
||||
- Remove pytest-catchlog from requirements (`#1099`_)
|
||||
- Documentation fixes (`#1061`_, `#1078`_, `#1081`_, `#1096`_)
|
||||
|
||||
.. _`#1061`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1061
|
||||
.. _`#1068`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1068
|
||||
.. _`#1078`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1078
|
||||
.. _`#1079`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1079
|
||||
.. _`#1081`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1081
|
||||
.. _`#1085`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1085
|
||||
.. _`#1086`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1086
|
||||
.. _`#1088`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1088
|
||||
.. _`#1096`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1096
|
||||
.. _`#1099`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1099
|
||||
|
||||
**2018-04-17**
|
||||
*Released 10.0.2*
|
||||
|
||||
Important fix:
|
||||
|
||||
- Handle utf8 decoding errors (`#1076`_)
|
||||
|
||||
New features:
|
||||
|
||||
- Added Filter.regex (`#1028`_)
|
||||
- Filters for Category and file types (`#1046`_)
|
||||
- Added video note filter (`#1067`_)
|
||||
|
||||
Fixes:
|
||||
|
||||
- Fix in telegram.Message (`#1042`_)
|
||||
- Make chat_id a positional argument inside shortcut methods of Chat and User classes (`#1050`_)
|
||||
- Make Bot.full_name return a unicode object. (`#1063`_)
|
||||
- CommandHandler faster check (`#1074`_)
|
||||
- Correct documentation of Dispatcher.add_handler (`#1071`_)
|
||||
- Various small fixes to documentation.
|
||||
|
||||
.. _`#1028`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1028
|
||||
.. _`#1042`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1042
|
||||
.. _`#1046`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1046
|
||||
.. _`#1050`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1050
|
||||
.. _`#1067`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1067
|
||||
.. _`#1063`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1063
|
||||
.. _`#1074`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1074
|
||||
.. _`#1076`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1076
|
||||
.. _`#1071`: https://github.com/python-telegram-bot/python-telegram-bot/pull/1071
|
||||
|
||||
**2018-03-05**
|
||||
*Released 10.0.1*
|
||||
|
||||
Fixes:
|
||||
|
||||
- Fix conversationhandler timeout (PR `#1032`_)
|
||||
- Add missing docs utils (PR `#912`_)
|
||||
|
||||
.. _`#1032`: https://github.com/python-telegram-bot/python-telegram-bot/pull/826
|
||||
.. _`#912`: https://github.com/python-telegram-bot/python-telegram-bot/pull/826
|
||||
|
||||
**2018-03-02**
|
||||
*Released 10.0.0*
|
||||
|
||||
|
||||
+792
@@ -0,0 +1,792 @@
|
||||
NOTICE: You can find here the GPLv3 license and after the Lesser GPLv3 license.
|
||||
You may choose either license.
|
||||
|
||||
|
||||
GNU LESSER GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. [http://fsf.org/]
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
|
||||
This version of the GNU Lesser General Public License incorporates
|
||||
the terms and conditions of version 3 of the GNU General Public
|
||||
License, supplemented by the additional permissions listed below.
|
||||
|
||||
0. Additional Definitions.
|
||||
|
||||
As used herein, "this License" refers to version 3 of the GNU Lesser
|
||||
General Public License, and the "GNU GPL" refers to version 3 of the GNU
|
||||
General Public License.
|
||||
|
||||
"The Library" refers to a covered work governed by this License,
|
||||
other than an Application or a Combined Work as defined below.
|
||||
|
||||
An "Application" is any work that makes use of an interface provided
|
||||
by the Library, but which is not otherwise based on the Library.
|
||||
Defining a subclass of a class defined by the Library is deemed a mode
|
||||
of using an interface provided by the Library.
|
||||
|
||||
A "Combined Work" is a work produced by combining or linking an
|
||||
Application with the Library. The particular version of the Library
|
||||
with which the Combined Work was made is also called the "Linked
|
||||
Version".
|
||||
|
||||
The "Minimal Corresponding Source" for a Combined Work means the
|
||||
Corresponding Source for the Combined Work, excluding any source code
|
||||
for portions of the Combined Work that, considered in isolation, are
|
||||
based on the Application, and not on the Linked Version.
|
||||
|
||||
The "Corresponding Application Code" for a Combined Work means the
|
||||
object code and/or source code for the Application, including any data
|
||||
and utility programs needed for reproducing the Combined Work from the
|
||||
Application, but excluding the System Libraries of the Combined Work.
|
||||
|
||||
1. Exception to Section 3 of the GNU GPL.
|
||||
|
||||
You may convey a covered work under sections 3 and 4 of this License
|
||||
without being bound by section 3 of the GNU GPL.
|
||||
|
||||
2. Conveying Modified Versions.
|
||||
|
||||
If you modify a copy of the Library, and, in your modifications, a
|
||||
facility refers to a function or data to be supplied by an Application
|
||||
that uses the facility (other than as an argument passed when the
|
||||
facility is invoked), then you may convey a copy of the modified
|
||||
version:
|
||||
|
||||
a) under this License, provided that you make a good faith effort to
|
||||
ensure that, in the event an Application does not supply the
|
||||
function or data, the facility still operates, and performs
|
||||
whatever part of its purpose remains meaningful, or
|
||||
|
||||
b) under the GNU GPL, with none of the additional permissions of
|
||||
this License applicable to that copy.
|
||||
|
||||
3. Object Code Incorporating Material from Library Header Files.
|
||||
|
||||
The object code form of an Application may incorporate material from
|
||||
a header file that is part of the Library. You may convey such object
|
||||
code under terms of your choice, provided that, if the incorporated
|
||||
material is not limited to numerical parameters, data structure
|
||||
layouts and accessors, or small macros, inline functions and templates
|
||||
(ten or fewer lines in length), you do both of the following:
|
||||
|
||||
a) Give prominent notice with each copy of the object code that the
|
||||
Library is used in it and that the Library and its use are
|
||||
covered by this License.
|
||||
|
||||
b) Accompany the object code with a copy of the GNU GPL and this license
|
||||
document.
|
||||
|
||||
4. Combined Works.
|
||||
|
||||
You may convey a Combined Work under terms of your choice that,
|
||||
taken together, effectively do not restrict modification of the
|
||||
portions of the Library contained in the Combined Work and reverse
|
||||
engineering for debugging such modifications, if you also do each of
|
||||
the following:
|
||||
|
||||
a) Give prominent notice with each copy of the Combined Work that
|
||||
the Library is used in it and that the Library and its use are
|
||||
covered by this License.
|
||||
|
||||
b) Accompany the Combined Work with a copy of the GNU GPL and this license
|
||||
document.
|
||||
|
||||
c) For a Combined Work that displays copyright notices during
|
||||
execution, include the copyright notice for the Library among
|
||||
these notices, as well as a reference directing the user to the
|
||||
copies of the GNU GPL and this license document.
|
||||
|
||||
d) Do one of the following:
|
||||
|
||||
0) Convey the Minimal Corresponding Source under the terms of this
|
||||
License, and the Corresponding Application Code in a form
|
||||
suitable for, and under terms that permit, the user to
|
||||
recombine or relink the Application with a modified version of
|
||||
the Linked Version to produce a modified Combined Work, in the
|
||||
manner specified by section 6 of the GNU GPL for conveying
|
||||
Corresponding Source.
|
||||
|
||||
1) Use a suitable shared library mechanism for linking with the
|
||||
Library. A suitable mechanism is one that (a) uses at run time
|
||||
a copy of the Library already present on the user's computer
|
||||
system, and (b) will operate properly with a modified version
|
||||
of the Library that is interface-compatible with the Linked
|
||||
Version.
|
||||
|
||||
e) Provide Installation Information, but only if you would otherwise
|
||||
be required to provide such information under section 6 of the
|
||||
GNU GPL, and only to the extent that such information is
|
||||
necessary to install and execute a modified version of the
|
||||
Combined Work produced by recombining or relinking the
|
||||
Application with a modified version of the Linked Version. (If
|
||||
you use option 4d0, the Installation Information must accompany
|
||||
the Minimal Corresponding Source and Corresponding Application
|
||||
Code. If you use option 4d1, you must provide the Installation
|
||||
Information in the manner specified by section 6 of the GNU GPL
|
||||
for conveying Corresponding Source.)
|
||||
|
||||
5. Combined Libraries.
|
||||
|
||||
You may place library facilities that are a work based on the
|
||||
Library side by side in a single library together with other library
|
||||
facilities that are not Applications and are not covered by this
|
||||
License, and convey such a combined library under terms of your
|
||||
choice, if you do both of the following:
|
||||
|
||||
a) Accompany the combined library with a copy of the same work based
|
||||
on the Library, uncombined with any other library facilities,
|
||||
conveyed under the terms of this License.
|
||||
|
||||
b) Give prominent notice with the combined library that part of it
|
||||
is a work based on the Library, and explaining where to find the
|
||||
accompanying uncombined form of the same work.
|
||||
|
||||
6. Revised Versions of the GNU Lesser General Public License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions
|
||||
of the GNU Lesser General Public License from time to time. Such new
|
||||
versions will be similar in spirit to the present version, but may
|
||||
differ in detail to address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Library as you received it specifies that a certain numbered version
|
||||
of the GNU Lesser General Public License "or any later version"
|
||||
applies to it, you have the option of following the terms and
|
||||
conditions either of that published version or of any later version
|
||||
published by the Free Software Foundation. If the Library as you
|
||||
received it does not specify a version number of the GNU Lesser
|
||||
General Public License, you may choose any version of the GNU Lesser
|
||||
General Public License ever published by the Free Software Foundation.
|
||||
|
||||
If the Library as you received it specifies that a proxy can decide
|
||||
whether future versions of the GNU Lesser General Public License shall
|
||||
apply, that proxy's public statement of acceptance of any version is
|
||||
permanent authorization for you to choose that version for the
|
||||
Library.
|
||||
|
||||
|
||||
|
||||
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. [http://fsf.org/]
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
+8
-6
@@ -5,15 +5,17 @@
|
||||
|
||||
We have made you a wrapper you can't refuse
|
||||
|
||||
We have a vibrant community of developers helping each other in our `Telegram group <https://telegram.me/pythontelegrambotgroup>`_. Join us!
|
||||
|
||||
*Stay tuned for library updates and new releases on our* `Telegram Channel <https://telegram.me/pythontelegrambotchannel>`_.
|
||||
|
||||
.. image:: https://img.shields.io/pypi/v/python-telegram-bot.svg
|
||||
:target: https://pypi.python.org/pypi/python-telegram-bot
|
||||
:target: https://pypi.org/project/python-telegram-bot/
|
||||
:alt: PyPi Package Version
|
||||
|
||||
.. image:: https://img.shields.io/pypi/pyversions/python-telegram-bot.svg
|
||||
:target: https://pypi.python.org/pypi/python-telegram-bot
|
||||
:alt: Supported python versions
|
||||
:target: https://pypi.org/project/python-telegram-bot/
|
||||
:alt: Supported Python versions
|
||||
|
||||
.. image:: https://www.cpu.re/static/python-telegram-bot/downloads.svg
|
||||
:target: https://www.cpu.re/static/python-telegram-bot/downloads-by-python-version.txt
|
||||
@@ -31,8 +33,8 @@ We have made you a wrapper you can't refuse
|
||||
:target: https://travis-ci.org/python-telegram-bot/python-telegram-bot
|
||||
:alt: Travis CI Status
|
||||
|
||||
.. image:: https://img.shields.io/appveyor/ci/Eldinnie/python-telegram-bot/master.svg?logo=appveyor
|
||||
:target: https://ci.appveyor.com/project/Eldinnie/python-telegram-bot
|
||||
.. image:: https://img.shields.io/appveyor/ci/python-telegram-bot/python-telegram-bot/master.svg?logo=appveyor
|
||||
:target: https://ci.appveyor.com/project/python-telegram-bot/python-telegram-bot
|
||||
:alt: AppVeyor CI Status
|
||||
|
||||
|
||||
@@ -93,7 +95,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.1** are supported.
|
||||
|
||||
==========
|
||||
Installing
|
||||
|
||||
@@ -26,7 +26,6 @@ install:
|
||||
- "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"
|
||||
|
||||
|
||||
+3
-11
@@ -58,9 +58,9 @@ author = u'Leandro Toledo'
|
||||
# built documents.
|
||||
#
|
||||
# The short X.Y version.
|
||||
version = '10.0' # telegram.__version__[:3]
|
||||
version = '11.1' # telegram.__version__[:3]
|
||||
# The full version, including alpha/beta/rc tags.
|
||||
release = '10.0.0' # telegram.__version__
|
||||
release = '11.1.0' # telegram.__version__
|
||||
|
||||
# The language for content autogenerated by Sphinx. Refer to documentation
|
||||
# for a list of supported languages.
|
||||
@@ -291,17 +291,9 @@ texinfo_documents = [
|
||||
|
||||
# -- script stuff --------------------------------------------------------
|
||||
|
||||
import inspect
|
||||
|
||||
|
||||
def autodoc_skip_member(app, what, name, obj, skip, options):
|
||||
try:
|
||||
if inspect.getmodule(obj).__name__.startswith('telegram') and inspect.isfunction(obj):
|
||||
if name.lower() != name:
|
||||
return True
|
||||
except AttributeError:
|
||||
pass
|
||||
# Return None so napoleon can handle it
|
||||
pass
|
||||
|
||||
|
||||
def setup(app):
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
telegram.Credentials
|
||||
====================
|
||||
|
||||
.. autoclass:: telegram.Credentials
|
||||
:members:
|
||||
:show-inheritance:
|
||||
@@ -0,0 +1,6 @@
|
||||
telegram.DataCredentials
|
||||
========================
|
||||
|
||||
.. autoclass:: telegram.DataCredentials
|
||||
:members:
|
||||
:show-inheritance:
|
||||
@@ -0,0 +1,6 @@
|
||||
telegram.EncryptedCredentials
|
||||
=============================
|
||||
|
||||
.. autoclass:: telegram.EncryptedCredentials
|
||||
:members:
|
||||
:show-inheritance:
|
||||
@@ -0,0 +1,6 @@
|
||||
telegram.EncryptedPassportElement
|
||||
=================================
|
||||
|
||||
.. autoclass:: telegram.EncryptedPassportElement
|
||||
:members:
|
||||
:show-inheritance:
|
||||
@@ -0,0 +1,6 @@
|
||||
telegram.FileCredentials
|
||||
========================
|
||||
|
||||
.. autoclass:: telegram.FileCredentials
|
||||
:members:
|
||||
:show-inheritance:
|
||||
@@ -0,0 +1,6 @@
|
||||
telegram.IdDocumentData
|
||||
=======================
|
||||
|
||||
.. autoclass:: telegram.IdDocumentData
|
||||
:members:
|
||||
:show-inheritance:
|
||||
@@ -0,0 +1,6 @@
|
||||
telegram.InputMediaAnimation
|
||||
============================
|
||||
|
||||
.. autoclass:: telegram.InputMediaAnimation
|
||||
:members:
|
||||
:show-inheritance:
|
||||
@@ -0,0 +1,6 @@
|
||||
telegram.InputMediaAudio
|
||||
========================
|
||||
|
||||
.. autoclass:: telegram.InputMediaAudio
|
||||
:members:
|
||||
:show-inheritance:
|
||||
@@ -0,0 +1,6 @@
|
||||
telegram.InputMediaDocument
|
||||
===========================
|
||||
|
||||
.. autoclass:: telegram.InputMediaDocument
|
||||
:members:
|
||||
:show-inheritance:
|
||||
@@ -0,0 +1,6 @@
|
||||
telegram.PassportData
|
||||
=====================
|
||||
|
||||
.. autoclass:: telegram.PassportData
|
||||
:members:
|
||||
:show-inheritance:
|
||||
@@ -0,0 +1,6 @@
|
||||
telegram.PassportElementError
|
||||
=============================
|
||||
|
||||
.. autoclass:: telegram.PassportElementError
|
||||
:members:
|
||||
:show-inheritance:
|
||||
@@ -0,0 +1,6 @@
|
||||
telegram.PassportElementErrorDataField
|
||||
======================================
|
||||
|
||||
.. autoclass:: telegram.PassportElementErrorDataField
|
||||
:members:
|
||||
:show-inheritance:
|
||||
@@ -0,0 +1,6 @@
|
||||
telegram.PassportElementErrorFile
|
||||
=================================
|
||||
|
||||
.. autoclass:: telegram.PassportElementErrorFile
|
||||
:members:
|
||||
:show-inheritance:
|
||||
@@ -0,0 +1,6 @@
|
||||
telegram.PassportElementErrorFiles
|
||||
==================================
|
||||
|
||||
.. autoclass:: telegram.PassportElementErrorFiles
|
||||
:members:
|
||||
:show-inheritance:
|
||||
@@ -0,0 +1,6 @@
|
||||
telegram.PassportElementErrorFrontSide
|
||||
======================================
|
||||
|
||||
.. autoclass:: telegram.PassportElementErrorFrontSide
|
||||
:members:
|
||||
:show-inheritance:
|
||||
@@ -0,0 +1,6 @@
|
||||
telegram.PassportElementErrorReverseSide
|
||||
========================================
|
||||
|
||||
.. autoclass:: telegram.PassportElementErrorReverseSide
|
||||
:members:
|
||||
:show-inheritance:
|
||||
@@ -0,0 +1,6 @@
|
||||
telegram.PassportFile
|
||||
=====================
|
||||
|
||||
.. autoclass:: telegram.PassportFile
|
||||
:members:
|
||||
:show-inheritance:
|
||||
@@ -0,0 +1,6 @@
|
||||
telegram.PersonalDetails
|
||||
========================
|
||||
|
||||
.. autoclass:: telegram.PersonalDetails
|
||||
:members:
|
||||
:show-inheritance:
|
||||
@@ -0,0 +1,6 @@
|
||||
telegram.ResidentialAddress
|
||||
===========================
|
||||
|
||||
.. autoclass:: telegram.ResidentialAddress
|
||||
:members:
|
||||
:show-inheritance:
|
||||
@@ -3,8 +3,9 @@ telegram package
|
||||
|
||||
.. toctree::
|
||||
|
||||
telegram.utils.helpers
|
||||
telegram.ext
|
||||
telegram.utils
|
||||
telegram.animation
|
||||
telegram.audio
|
||||
telegram.bot
|
||||
telegram.callbackquery
|
||||
@@ -22,6 +23,9 @@ telegram package
|
||||
telegram.inlinekeyboardmarkup
|
||||
telegram.inputfile
|
||||
telegram.inputmedia
|
||||
telegram.inputmediaanimation
|
||||
telegram.inputmediaaudio
|
||||
telegram.inputmediadocument
|
||||
telegram.inputmediaphoto
|
||||
telegram.inputmediavideo
|
||||
telegram.keyboardbutton
|
||||
@@ -106,10 +110,33 @@ Games
|
||||
.. toctree::
|
||||
|
||||
telegram.game
|
||||
telegram.animation
|
||||
telegram.callbackgame
|
||||
telegram.gamehighscore
|
||||
|
||||
Passport
|
||||
--------
|
||||
|
||||
.. toctree::
|
||||
|
||||
telegram.passportelementerror
|
||||
telegram.passportelementerrorfile
|
||||
telegram.passportelementerrorreverseside
|
||||
telegram.passportelementerrorfrontside
|
||||
telegram.passportelementerrorfiles
|
||||
telegram.passportelementerrordatafield
|
||||
telegram.passportelementerrorfile
|
||||
telegram.credentials
|
||||
telegram.datacredentials
|
||||
telegram.securedata
|
||||
telegram.filecredentials
|
||||
telegram.iddocumentdata
|
||||
telegram.personaldetails
|
||||
telegram.residentialaddress
|
||||
telegram.passportdata
|
||||
telegram.passportfile
|
||||
telegram.encryptedpassportelement
|
||||
telegram.encryptedcredentials
|
||||
|
||||
|
||||
Module contents
|
||||
---------------
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
telegram.SecureData
|
||||
===================
|
||||
|
||||
.. autoclass:: telegram.SecureData
|
||||
:members:
|
||||
:show-inheritance:
|
||||
@@ -0,0 +1,6 @@
|
||||
telegram.utils.promise.Promise
|
||||
==============================
|
||||
|
||||
.. autoclass:: telegram.utils.promise.Promise
|
||||
:members:
|
||||
:show-inheritance:
|
||||
@@ -0,0 +1,6 @@
|
||||
telegram.utils.request.Request
|
||||
==============================
|
||||
|
||||
.. autoclass:: telegram.utils.request.Request
|
||||
:members:
|
||||
:show-inheritance:
|
||||
@@ -0,0 +1,8 @@
|
||||
telegram.utils package
|
||||
======================
|
||||
|
||||
.. toctree::
|
||||
|
||||
telegram.utils.helpers
|
||||
telegram.utils.promise
|
||||
telegram.utils.request
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
# Examples
|
||||
|
||||
The examples in this folder are small bots meant to show you how a bot that is written with `python-telegram-bot` looks like. Some bots focus on one specific aspect of the Telegram Bot API while others focus on one of the mechanics of this library. Except for the [`echobot.py`](#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 there are small examples to show what a bot written with `python-telegram-bot` looks like. Some bots focus on one specific aspect of the Telegram Bot API while others focus on one of the mechanics of this library. Except for the [`echobot.py`](#pure-api) example, they all use the high-level framework this library provides with the [`telegram.ext`](https://python-telegram-bot.readthedocs.io/en/latest/telegram.ext.html) submodule.
|
||||
|
||||
All examples are licensed under the [CC0 License](https://github.com/python-telegram-bot/python-telegram-bot/blob/master/examples/LICENSE.txt) and are therefore fully dedicated to the public domain. You can use them as the base for your own bots without worrying about copyrights.
|
||||
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<title>Telegram passport test!</title>
|
||||
<meta charset="utf-8">
|
||||
<meta http-equiv="X-UA-Compatible" content="IE=edge">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
|
||||
<!--- Needs file from https://github.com/TelegramMessenger/TGPassportJsSDK downloaded --->
|
||||
<script src="telegram-passport.js"></script>
|
||||
<script>
|
||||
"use strict";
|
||||
|
||||
Telegram.Passport.createAuthButton('telegram_passport_auth', {
|
||||
bot_id: BOT_ID, // YOUR BOT ID
|
||||
scope: {data: [{type: 'id_document', selfie: true}, 'address_document', 'phone_number', 'email'], v: 1}, // WHAT DATA YOU WANT TO RECEIVE
|
||||
public_key: '-----BEGIN PUBLIC KEY----- ...', // YOUR PUBLIC KEY
|
||||
payload: 'thisisatest', // YOUR BOT WILL RECEIVE THIS DATA WITH THE REQUEST
|
||||
callback_url: 'https://example.org' // TELEGRAM WILL SEND YOUR USER BACK TO THIS URL
|
||||
});
|
||||
|
||||
</script>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Telegram passport test</h1>
|
||||
|
||||
<div id="telegram_passport_auth"></div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,108 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
#
|
||||
# Simple Bot to print/download all incoming passport data
|
||||
# This program is dedicated to the public domain under the CC0 license.
|
||||
"""
|
||||
See https://telegram.org/blog/passport for info about what telegram passport is.
|
||||
|
||||
See https://git.io/fAvYd for how to use Telegram Passport properly with python-telegram-bot.
|
||||
|
||||
"""
|
||||
import logging
|
||||
|
||||
from telegram.ext import Updater, MessageHandler, Filters
|
||||
|
||||
# Enable logging
|
||||
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
|
||||
level=logging.DEBUG)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def msg(bot, update):
|
||||
# If we received any passport data
|
||||
passport_data = update.message.passport_data
|
||||
if passport_data:
|
||||
# If our 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 error(bot, update, error):
|
||||
"""Log Errors caused by Updates."""
|
||||
logger.warning('Update "%s" caused error "%s"', update, error)
|
||||
|
||||
|
||||
def main():
|
||||
"""Start the bot."""
|
||||
# Create the Updater and pass it your token and private key
|
||||
updater = Updater("TOKEN", private_key=open('private.key', 'rb').read())
|
||||
|
||||
# Get the dispatcher to register handlers
|
||||
dp = updater.dispatcher
|
||||
|
||||
# On messages that include passport data call msg
|
||||
dp.add_handler(MessageHandler(Filters.passport_data, msg))
|
||||
|
||||
# log all errors
|
||||
dp.add_error_handler(error)
|
||||
|
||||
# Start the Bot
|
||||
updater.start_polling()
|
||||
|
||||
# Run the bot until you press Ctrl-C or the process receives SIGINT,
|
||||
# SIGTERM or SIGABRT. This should be used most of the time, since
|
||||
# start_polling() is non-blocking and will stop the bot gracefully.
|
||||
updater.idle()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -6,5 +6,5 @@ yapf
|
||||
pre-commit
|
||||
beautifulsoup4
|
||||
pytest
|
||||
pytest-catchlog
|
||||
pytest-timeout
|
||||
wheel
|
||||
|
||||
@@ -1,2 +1,3 @@
|
||||
future>=0.16.0
|
||||
certifi
|
||||
cryptography
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
[wheel]
|
||||
universal = 1
|
||||
|
||||
[metadata]
|
||||
license_file = LICENSE.dual
|
||||
|
||||
[build_sphinx]
|
||||
source-dir = docs/source
|
||||
build-dir = docs/build
|
||||
|
||||
+34
-7
@@ -1,4 +1,4 @@
|
||||
#!/usr/bin/env python
|
||||
''#!/usr/bin/env python
|
||||
#
|
||||
# A library that provides a Python interface to the Telegram Bot API
|
||||
# Copyright (C) 2015-2018
|
||||
@@ -27,6 +27,7 @@ from .files.photosize import PhotoSize
|
||||
from .files.audio import Audio
|
||||
from .files.voice import Voice
|
||||
from .files.document import Document
|
||||
from .files.animation import Animation
|
||||
from .files.sticker import Sticker, StickerSet, MaskPosition
|
||||
from .files.video import Video
|
||||
from .files.contact import Contact
|
||||
@@ -45,13 +46,17 @@ from .files.inputfile import InputFile
|
||||
from .files.file import File
|
||||
from .parsemode import ParseMode
|
||||
from .messageentity import MessageEntity
|
||||
from .games.animation import Animation
|
||||
from .games.game import Game
|
||||
from .games.callbackgame import CallbackGame
|
||||
from .payment.shippingaddress import ShippingAddress
|
||||
from .payment.orderinfo import OrderInfo
|
||||
from .payment.successfulpayment import SuccessfulPayment
|
||||
from .payment.invoice import Invoice
|
||||
from .passport.credentials import EncryptedCredentials
|
||||
from .passport.passportfile import PassportFile
|
||||
from .passport.data import IdDocumentData, PersonalDetails, ResidentialAddress
|
||||
from .passport.encryptedpassportelement import EncryptedPassportElement
|
||||
from .passport.passportdata import PassportData
|
||||
from .message import Message
|
||||
from .callbackquery import CallbackQuery
|
||||
from .choseninlineresult import ChosenInlineResult
|
||||
@@ -91,14 +96,28 @@ 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 .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__ # flake8: noqa
|
||||
|
||||
__author__ = 'devs@python-telegram-bot.org'
|
||||
@@ -116,7 +135,8 @@ __all__ = [
|
||||
'InlineQueryResultPhoto', 'InlineQueryResultVenue', 'InlineQueryResultVideo',
|
||||
'InlineQueryResultVoice', 'InlineQueryResultGame', 'InputContactMessageContent', 'InputFile',
|
||||
'InputLocationMessageContent', 'InputMessageContent', 'InputTextMessageContent',
|
||||
'InputVenueMessageContent', 'KeyboardButton', 'Location', 'Message', 'MessageEntity',
|
||||
'InputVenueMessageContent', 'KeyboardButton', 'Location', 'EncryptedCredentials',
|
||||
'PassportFile', 'EncryptedPassportElement', 'PassportData', 'Message', 'MessageEntity',
|
||||
'ParseMode', 'PhotoSize', 'ReplyKeyboardRemove', 'ReplyKeyboardMarkup', 'ReplyMarkup',
|
||||
'Sticker', 'TelegramError', 'TelegramObject', 'Update', 'User', 'UserProfilePhotos', 'Venue',
|
||||
'Video', 'Voice', 'MAX_MESSAGE_LENGTH', 'MAX_CAPTION_LENGTH', 'SUPPORTED_WEBHOOK_PORTS',
|
||||
@@ -125,5 +145,12 @@ __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'
|
||||
]
|
||||
|
||||
+6
-1
@@ -60,7 +60,12 @@ class TelegramObject(object):
|
||||
data = dict()
|
||||
|
||||
for key in iter(self.__dict__):
|
||||
if key in ('bot', '_id_attrs'):
|
||||
if key in ('bot',
|
||||
'_id_attrs',
|
||||
'_credentials',
|
||||
'_decrypted_credentials',
|
||||
'_decrypted_data',
|
||||
'_decrypted_secret'):
|
||||
continue
|
||||
|
||||
value = self.__dict__[key]
|
||||
|
||||
+396
-72
@@ -21,17 +21,22 @@
|
||||
"""This module contains an object that represents a Telegram Bot."""
|
||||
|
||||
import functools
|
||||
import json
|
||||
try:
|
||||
import ujson as json
|
||||
except ImportError:
|
||||
import json
|
||||
import logging
|
||||
import warnings
|
||||
from datetime import datetime
|
||||
|
||||
from cryptography.hazmat.backends import default_backend
|
||||
from cryptography.hazmat.primitives import serialization
|
||||
from future.utils import string_types
|
||||
|
||||
from telegram import (User, Message, Update, Chat, ChatMember, UserProfilePhotos, File,
|
||||
ReplyMarkup, TelegramObject, WebhookInfo, GameHighScore, StickerSet,
|
||||
PhotoSize, Audio, Document, Sticker, Video, Voice, VideoNote, Location,
|
||||
Venue, Contact)
|
||||
PhotoSize, Audio, Document, Sticker, Video, Animation, Voice, VideoNote,
|
||||
Location, Venue, Contact, InputFile)
|
||||
from telegram.error import InvalidToken, TelegramError
|
||||
from telegram.utils.helpers import to_timestamp
|
||||
from telegram.utils.request import Request
|
||||
@@ -101,10 +106,13 @@ class Bot(TelegramObject):
|
||||
base_file_url (:obj:`str`, optional): Telegram Bot API file URL.
|
||||
request (:obj:`telegram.utils.request.Request`, optional): Pre initialized
|
||||
:obj:`telegram.utils.request.Request`.
|
||||
private_key (:obj:`bytes`, optional): Private key for decryption of telegram passport data.
|
||||
private_key_password (:obj:`bytes`, optional): Password for above private key.
|
||||
|
||||
"""
|
||||
|
||||
def __init__(self, token, base_url=None, base_file_url=None, request=None):
|
||||
def __init__(self, token, base_url=None, base_file_url=None, request=None, private_key=None,
|
||||
private_key_password=None):
|
||||
self.token = self._validate_token(token)
|
||||
|
||||
if base_url is None:
|
||||
@@ -119,6 +127,11 @@ class Bot(TelegramObject):
|
||||
self._request = request or Request()
|
||||
self.logger = logging.getLogger(__name__)
|
||||
|
||||
if private_key:
|
||||
self.private_key = serialization.load_pem_private_key(private_key,
|
||||
password=private_key_password,
|
||||
backend=default_backend())
|
||||
|
||||
@property
|
||||
def request(self):
|
||||
return self._request
|
||||
@@ -381,6 +394,8 @@ class Bot(TelegramObject):
|
||||
|
||||
if isinstance(photo, PhotoSize):
|
||||
photo = photo.file_id
|
||||
elif InputFile.is_file(photo):
|
||||
photo = InputFile(photo)
|
||||
|
||||
data = {'chat_id': chat_id, 'photo': photo}
|
||||
|
||||
@@ -405,6 +420,7 @@ class Bot(TelegramObject):
|
||||
reply_markup=None,
|
||||
timeout=20,
|
||||
parse_mode=None,
|
||||
thumb=None,
|
||||
**kwargs):
|
||||
"""
|
||||
Use this method to send audio files, if you want Telegram clients to display them in the
|
||||
@@ -440,6 +456,10 @@ class Bot(TelegramObject):
|
||||
reply_markup (:class:`telegram.ReplyMarkup`, optional): Additional interface options. A
|
||||
JSON-serialized object for an inline keyboard, custom reply keyboard, instructions
|
||||
to remove reply keyboard or to force a reply from the user.
|
||||
thumb (`filelike object`, optional): Thumbnail of the
|
||||
file sent. The thumbnail should be in JPEG format and less than 200 kB in size.
|
||||
A thumbnail's width and height should not exceed 90. Ignored if the file is not
|
||||
is passed as a string or file_id.
|
||||
timeout (:obj:`int` | :obj:`float`, optional): Send file timeout (default: 20 seconds).
|
||||
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
|
||||
|
||||
@@ -454,6 +474,8 @@ class Bot(TelegramObject):
|
||||
|
||||
if isinstance(audio, Audio):
|
||||
audio = audio.file_id
|
||||
elif InputFile.is_file(audio):
|
||||
audio = InputFile(audio)
|
||||
|
||||
data = {'chat_id': chat_id, 'audio': audio}
|
||||
|
||||
@@ -467,6 +489,10 @@ class Bot(TelegramObject):
|
||||
data['caption'] = caption
|
||||
if parse_mode:
|
||||
data['parse_mode'] = parse_mode
|
||||
if thumb:
|
||||
if InputFile.is_file(thumb):
|
||||
thumb = InputFile(thumb, attach=True)
|
||||
data['thumb'] = thumb
|
||||
|
||||
return url, data
|
||||
|
||||
@@ -482,6 +508,7 @@ class Bot(TelegramObject):
|
||||
reply_markup=None,
|
||||
timeout=20,
|
||||
parse_mode=None,
|
||||
thumb=None,
|
||||
**kwargs):
|
||||
"""Use this method to send general files.
|
||||
|
||||
@@ -511,6 +538,10 @@ class Bot(TelegramObject):
|
||||
reply_markup (:class:`telegram.ReplyMarkup`, optional): Additional interface options. A
|
||||
JSON-serialized object for an inline keyboard, custom reply keyboard, instructions
|
||||
to remove reply keyboard or to force a reply from the user.
|
||||
thumb (`filelike object`, optional): Thumbnail of the
|
||||
file sent. The thumbnail should be in JPEG format and less than 200 kB in size.
|
||||
A thumbnail's width and height should not exceed 90. Ignored if the file is not
|
||||
is passed as a string or file_id.
|
||||
timeout (:obj:`int` | :obj:`float`, optional): Send file timeout (default: 20 seconds).
|
||||
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
|
||||
|
||||
@@ -525,15 +556,19 @@ class Bot(TelegramObject):
|
||||
|
||||
if isinstance(document, Document):
|
||||
document = document.file_id
|
||||
elif InputFile.is_file(document):
|
||||
document = InputFile(document, filename=filename)
|
||||
|
||||
data = {'chat_id': chat_id, 'document': document}
|
||||
|
||||
if filename:
|
||||
data['filename'] = filename
|
||||
if caption:
|
||||
data['caption'] = caption
|
||||
if parse_mode:
|
||||
data['parse_mode'] = parse_mode
|
||||
if thumb:
|
||||
if InputFile.is_file(thumb):
|
||||
thumb = InputFile(thumb, attach=True)
|
||||
data['thumb'] = thumb
|
||||
|
||||
return url, data
|
||||
|
||||
@@ -545,7 +580,7 @@ class Bot(TelegramObject):
|
||||
disable_notification=False,
|
||||
reply_to_message_id=None,
|
||||
reply_markup=None,
|
||||
timeout=None,
|
||||
timeout=20,
|
||||
**kwargs):
|
||||
"""Use this method to send .webp stickers.
|
||||
|
||||
@@ -582,6 +617,8 @@ class Bot(TelegramObject):
|
||||
|
||||
if isinstance(sticker, Sticker):
|
||||
sticker = sticker.file_id
|
||||
elif InputFile.is_file(sticker):
|
||||
sticker = InputFile(sticker)
|
||||
|
||||
data = {'chat_id': chat_id, 'sticker': sticker}
|
||||
|
||||
@@ -602,6 +639,7 @@ class Bot(TelegramObject):
|
||||
height=None,
|
||||
parse_mode=None,
|
||||
supports_streaming=None,
|
||||
thumb=None,
|
||||
**kwargs):
|
||||
"""
|
||||
Use this method to send video files, Telegram clients support mp4 videos
|
||||
@@ -636,6 +674,10 @@ class Bot(TelegramObject):
|
||||
reply_markup (:class:`telegram.ReplyMarkup`, optional): Additional interface options. A
|
||||
JSON-serialized object for an inline keyboard, custom reply keyboard, instructions
|
||||
to remove reply keyboard or to force a reply from the user.
|
||||
thumb (`filelike object`, optional): Thumbnail of the
|
||||
file sent. The thumbnail should be in JPEG format and less than 200 kB in size.
|
||||
A thumbnail's width and height should not exceed 90. Ignored if the file is not
|
||||
is passed as a string or file_id.
|
||||
timeout (:obj:`int` | :obj:`float`, optional): Send file timeout (default: 20 seconds).
|
||||
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
|
||||
|
||||
@@ -650,6 +692,8 @@ class Bot(TelegramObject):
|
||||
|
||||
if isinstance(video, Video):
|
||||
video = video.file_id
|
||||
elif InputFile.is_file(video):
|
||||
video = InputFile(video)
|
||||
|
||||
data = {'chat_id': chat_id, 'video': video}
|
||||
|
||||
@@ -665,6 +709,162 @@ class Bot(TelegramObject):
|
||||
data['width'] = width
|
||||
if height:
|
||||
data['height'] = height
|
||||
if thumb:
|
||||
if InputFile.is_file(thumb):
|
||||
thumb = InputFile(thumb, attach=True)
|
||||
data['thumb'] = thumb
|
||||
|
||||
return url, data
|
||||
|
||||
@log
|
||||
@message
|
||||
def send_video_note(self,
|
||||
chat_id,
|
||||
video_note,
|
||||
duration=None,
|
||||
length=None,
|
||||
disable_notification=False,
|
||||
reply_to_message_id=None,
|
||||
reply_markup=None,
|
||||
timeout=20,
|
||||
thumb=None,
|
||||
**kwargs):
|
||||
"""Use this method to send video messages.
|
||||
|
||||
Note:
|
||||
The video_note argument can be either a file_id or a file from disk
|
||||
``open(filename, 'rb')``
|
||||
|
||||
Args:
|
||||
chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username
|
||||
of the target channel (in the format @channelusername).
|
||||
video_note (:obj:`str` | `filelike object` | :class:`telegram.VideoNote`): Video note
|
||||
to send. Pass a file_id as String to send a video note that exists on the Telegram
|
||||
servers (recommended) or upload a new video using multipart/form-data. Or you can
|
||||
pass an existing :class:`telegram.VideoNote` object to send. Sending video notes by
|
||||
a URL is currently unsupported.
|
||||
duration (:obj:`int`, optional): Duration of sent video in seconds.
|
||||
length (:obj:`int`, optional): Video width and height
|
||||
disable_notification (:obj:`bool`, optional): Sends the message silently. Users will
|
||||
receive a notification with no sound.
|
||||
reply_to_message_id (:obj:`int`, optional): If the message is a reply, ID of the
|
||||
original message.
|
||||
reply_markup (:class:`telegram.ReplyMarkup`, optional): Additional interface options. A
|
||||
JSON-serialized object for an inline keyboard, custom reply keyboard,
|
||||
instructions to remove reply keyboard or to force a reply from the user.
|
||||
thumb (`filelike object`, optional): Thumbnail of the
|
||||
file sent. The thumbnail should be in JPEG format and less than 200 kB in size.
|
||||
A thumbnail's width and height should not exceed 90. Ignored if the file is not
|
||||
is passed as a string or file_id.
|
||||
timeout (:obj:`int` | :obj:`float`, optional): Send file timeout (default: 20 seconds).
|
||||
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
|
||||
|
||||
Returns:
|
||||
:class:`telegram.Message`: On success, the sent Message is returned.
|
||||
|
||||
Raises:
|
||||
:class:`telegram.TelegramError`
|
||||
|
||||
"""
|
||||
url = '{0}/sendVideoNote'.format(self.base_url)
|
||||
|
||||
if isinstance(video_note, VideoNote):
|
||||
video_note = video_note.file_id
|
||||
elif InputFile.is_file(video_note):
|
||||
video_note = InputFile(video_note)
|
||||
|
||||
data = {'chat_id': chat_id, 'video_note': video_note}
|
||||
|
||||
if duration is not None:
|
||||
data['duration'] = duration
|
||||
if length is not None:
|
||||
data['length'] = length
|
||||
if thumb:
|
||||
if InputFile.is_file(thumb):
|
||||
thumb = InputFile(thumb, attach=True)
|
||||
data['thumb'] = thumb
|
||||
|
||||
return url, data
|
||||
|
||||
@log
|
||||
@message
|
||||
def send_animation(self,
|
||||
chat_id,
|
||||
animation,
|
||||
duration=None,
|
||||
width=None,
|
||||
height=None,
|
||||
thumb=None,
|
||||
caption=None,
|
||||
parse_mode=None,
|
||||
disable_notification=False,
|
||||
reply_to_message_id=None,
|
||||
reply_markup=None,
|
||||
timeout=20,
|
||||
**kwargs):
|
||||
"""
|
||||
Use this method to send animation files (GIF or H.264/MPEG-4 AVC video without sound).
|
||||
|
||||
Args:
|
||||
chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username
|
||||
of the target channel (in the format @channelusername).
|
||||
animation (:obj:`str` | `filelike object` | :class:`telegram.Animation`): Animation to
|
||||
send. Pass a file_id as String to send an animation that exists on the Telegram
|
||||
servers (recommended), pass an HTTP URL as a String for Telegram to get an
|
||||
animation from the Internet, or upload a new animation using multipart/form-data.
|
||||
Lastly you can pass an existing :class:`telegram.Animation` object to send.
|
||||
duration (:obj:`int`, optional): Duration of sent animation in seconds.
|
||||
width (:obj:`int`, optional): Animation width.
|
||||
height (:obj:`int`, optional): Animation height.
|
||||
thumb (`filelike object`, optional): Thumbnail of the
|
||||
file sent. The thumbnail should be in JPEG format and less than 200 kB in size.
|
||||
A thumbnail's width and height should not exceed 90. Ignored if the file is not
|
||||
is passed as a string or file_id.
|
||||
caption (:obj:`str`, optional): Animation caption (may also be used when resending
|
||||
animations by file_id), 0-200 characters.
|
||||
parse_mode (:obj:`str`, optional): Send Markdown or HTML, if you want Telegram apps to
|
||||
show bold, italic, fixed-width text or inline URLs in the media caption. See the
|
||||
constants in :class:`telegram.ParseMode` for the available modes.
|
||||
disable_notification (:obj:`bool`, optional): Sends the message silently. Users will
|
||||
receive a notification with no sound.
|
||||
reply_to_message_id (:obj:`int`, optional): If the message is a reply, ID of the
|
||||
original message.
|
||||
reply_markup (:class:`telegram.ReplyMarkup`, optional): Additional interface options. A
|
||||
JSON-serialized object for an inline keyboard, custom reply keyboard, instructions
|
||||
to remove reply keyboard or to force a reply from the user.
|
||||
timeout (:obj:`int` | :obj:`float`, optional): Send file timeout (default: 20 seconds).
|
||||
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
|
||||
|
||||
Returns:
|
||||
:class:`telegram.Message`: On success, the sent Message is returned.
|
||||
|
||||
Raises:
|
||||
:class:`telegram.TelegramError`
|
||||
|
||||
"""
|
||||
url = '{0}/sendAnimation'.format(self.base_url)
|
||||
|
||||
if isinstance(animation, Animation):
|
||||
animation = animation.file_id
|
||||
elif InputFile.is_file(animation):
|
||||
animation = InputFile(animation)
|
||||
|
||||
data = {'chat_id': chat_id, 'animation': animation}
|
||||
|
||||
if duration:
|
||||
data['duration'] = duration
|
||||
if width:
|
||||
data['width'] = width
|
||||
if height:
|
||||
data['height'] = height
|
||||
if thumb:
|
||||
if InputFile.is_file(thumb):
|
||||
thumb = InputFile(thumb, attach=True)
|
||||
data['thumb'] = thumb
|
||||
if caption:
|
||||
data['caption'] = caption
|
||||
if parse_mode:
|
||||
data['parse_mode'] = parse_mode
|
||||
|
||||
return url, data
|
||||
|
||||
@@ -724,6 +924,8 @@ class Bot(TelegramObject):
|
||||
|
||||
if isinstance(voice, Voice):
|
||||
voice = voice.file_id
|
||||
elif InputFile.is_file(voice):
|
||||
voice = InputFile(voice)
|
||||
|
||||
data = {'chat_id': chat_id, 'voice': voice}
|
||||
|
||||
@@ -736,65 +938,6 @@ class Bot(TelegramObject):
|
||||
|
||||
return url, data
|
||||
|
||||
@log
|
||||
@message
|
||||
def send_video_note(self,
|
||||
chat_id,
|
||||
video_note,
|
||||
duration=None,
|
||||
length=None,
|
||||
disable_notification=False,
|
||||
reply_to_message_id=None,
|
||||
reply_markup=None,
|
||||
timeout=20,
|
||||
**kwargs):
|
||||
"""Use this method to send video messages.
|
||||
|
||||
Note:
|
||||
The video_note argument can be either a file_id or a file from disk
|
||||
``open(filename, 'rb')``
|
||||
|
||||
Args:
|
||||
chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username
|
||||
of the target channel (in the format @channelusername).
|
||||
video_note (:obj:`str` | `filelike object` | :class:`telegram.VideoNote`): Video note
|
||||
to send. Pass a file_id as String to send a video note that exists on the Telegram
|
||||
servers (recommended) or upload a new video using multipart/form-data. Or you can
|
||||
pass an existing :class:`telegram.VideoNote` object to send. Sending video notes by
|
||||
a URL is currently unsupported.
|
||||
duration (:obj:`int`, optional): Duration of sent video in seconds.
|
||||
length (:obj:`int`, optional): Video width and height
|
||||
disable_notification (:obj:`bool`, optional): Sends the message silently. Users will
|
||||
receive a notification with no sound.
|
||||
reply_to_message_id (:obj:`int`, optional): If the message is a reply, ID of the
|
||||
original message.
|
||||
reply_markup (:class:`telegram.ReplyMarkup`, optional): Additional interface options. A
|
||||
JSON-serialized object for an inline keyboard, custom reply keyboard,
|
||||
instructions to remove reply keyboard or to force a reply from the user.
|
||||
timeout (:obj:`int` | :obj:`float`, optional): Send file timeout (default: 20 seconds).
|
||||
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
|
||||
|
||||
Returns:
|
||||
:class:`telegram.Message`: On success, the sent Message is returned.
|
||||
|
||||
Raises:
|
||||
:class:`telegram.TelegramError`
|
||||
|
||||
"""
|
||||
url = '{0}/sendVideoNote'.format(self.base_url)
|
||||
|
||||
if isinstance(video_note, VideoNote):
|
||||
video_note = video_note.file_id
|
||||
|
||||
data = {'chat_id': chat_id, 'video_note': video_note}
|
||||
|
||||
if duration is not None:
|
||||
data['duration'] = duration
|
||||
if length is not None:
|
||||
data['length'] = length
|
||||
|
||||
return url, data
|
||||
|
||||
@log
|
||||
def send_media_group(self,
|
||||
chat_id,
|
||||
@@ -823,12 +966,9 @@ class Bot(TelegramObject):
|
||||
Raises:
|
||||
:class:`telegram.TelegramError`
|
||||
"""
|
||||
# TODO: Make InputMediaPhoto, InputMediaVideo and send_media_group work with new files
|
||||
|
||||
url = '{0}/sendMediaGroup'.format(self.base_url)
|
||||
|
||||
media = [med.to_dict() for med in media]
|
||||
|
||||
data = {'chat_id': chat_id, 'media': media}
|
||||
|
||||
if reply_to_message_id:
|
||||
@@ -1025,12 +1165,14 @@ class Bot(TelegramObject):
|
||||
reply_markup=None,
|
||||
timeout=None,
|
||||
venue=None,
|
||||
foursquare_type=None,
|
||||
**kwargs):
|
||||
"""Use this method to send information about a venue.
|
||||
|
||||
Note:
|
||||
you can either supply :obj:`venue`, or :obj:`latitude`, :obj:`longitude`,
|
||||
:obj:`title` and :obj:`address` and optionally :obj:`foursquare_id`.
|
||||
:obj:`title` and :obj:`address` and optionally :obj:`foursquare_id` and optionally
|
||||
:obj:`foursquare_type`.
|
||||
|
||||
Args:
|
||||
chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username
|
||||
@@ -1040,6 +1182,9 @@ class Bot(TelegramObject):
|
||||
title (:obj:`str`, optional): Name of the venue.
|
||||
address (:obj:`str`, optional): Address of the venue.
|
||||
foursquare_id (:obj:`str`, optional): Foursquare identifier of the venue.
|
||||
foursquare_type (:obj:`str`, optional): Foursquare type of the venue, if known.
|
||||
(For example, "arts_entertainment/default", "arts_entertainment/aquarium" or
|
||||
"food/icecream".)
|
||||
venue (:class:`telegram.Venue`, optional): The venue to send.
|
||||
disable_notification (:obj:`bool`, optional): Sends the message silently. Users will
|
||||
receive a notification with no sound.
|
||||
@@ -1072,6 +1217,7 @@ class Bot(TelegramObject):
|
||||
address = venue.address
|
||||
title = venue.title
|
||||
foursquare_id = venue.foursquare_id
|
||||
foursquare_type = venue.foursquare_type
|
||||
|
||||
data = {
|
||||
'chat_id': chat_id,
|
||||
@@ -1083,6 +1229,8 @@ class Bot(TelegramObject):
|
||||
|
||||
if foursquare_id:
|
||||
data['foursquare_id'] = foursquare_id
|
||||
if foursquare_type:
|
||||
data['foursquare_type'] = foursquare_type
|
||||
|
||||
return url, data
|
||||
|
||||
@@ -1098,12 +1246,13 @@ class Bot(TelegramObject):
|
||||
reply_markup=None,
|
||||
timeout=None,
|
||||
contact=None,
|
||||
vcard=None,
|
||||
**kwargs):
|
||||
"""Use this method to send phone contacts.
|
||||
|
||||
Note:
|
||||
You can either supply :obj:`contact` or :obj:`phone_number` and :obj:`first_name`
|
||||
with optionally :obj:`last_name`.
|
||||
with optionally :obj:`last_name` and optionally :obj:`vcard`.
|
||||
|
||||
Args:
|
||||
chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username
|
||||
@@ -1111,6 +1260,8 @@ class Bot(TelegramObject):
|
||||
phone_number (:obj:`str`, optional): Contact's phone number.
|
||||
first_name (:obj:`str`, optional): Contact's first name.
|
||||
last_name (:obj:`str`, optional): Contact's last name.
|
||||
vcard (:obj:`str`, optional): Additional data about the contact in the form of a vCard,
|
||||
0-2048 bytes.
|
||||
contact (:class:`telegram.Contact`, optional): The contact to send.
|
||||
disable_notification (:obj:`bool`, optional): Sends the message silently. Users will
|
||||
receive a notification with no sound.
|
||||
@@ -1141,11 +1292,14 @@ class Bot(TelegramObject):
|
||||
phone_number = contact.phone_number
|
||||
first_name = contact.first_name
|
||||
last_name = contact.last_name
|
||||
vcard = contact.vcard
|
||||
|
||||
data = {'chat_id': chat_id, 'phone_number': phone_number, 'first_name': first_name}
|
||||
|
||||
if last_name:
|
||||
data['last_name'] = last_name
|
||||
if vcard:
|
||||
data['vcard'] = vcard
|
||||
|
||||
return url, data
|
||||
|
||||
@@ -1648,6 +1802,59 @@ class Bot(TelegramObject):
|
||||
|
||||
return url, data
|
||||
|
||||
@log
|
||||
@message
|
||||
def edit_message_media(self,
|
||||
chat_id=None,
|
||||
message_id=None,
|
||||
inline_message_id=None,
|
||||
media=None,
|
||||
reply_markup=None,
|
||||
timeout=None,
|
||||
**kwargs):
|
||||
"""Use this method to edit audio, document, photo, or video messages. If a message is a
|
||||
part of a message album, then it can be edited only to a photo or a video. Otherwise,
|
||||
message type can be changed arbitrarily. When inline message is edited, new file can't be
|
||||
uploaded. Use previously uploaded file via its file_id or specify a URL. On success, if the
|
||||
edited message was sent by the bot, the edited Message is returned, otherwise True is
|
||||
returned.
|
||||
|
||||
Args:
|
||||
chat_id (:obj:`int` | :obj:`str`, optional): Unique identifier for the target chat or
|
||||
username of the target`channel (in the format @channelusername).
|
||||
message_id (:obj:`int`, optional): Required if inline_message_id is not specified.
|
||||
Identifier of the sent message.
|
||||
inline_message_id (:obj:`str`, optional): Required if chat_id and message_id are not
|
||||
specified. Identifier of the inline message.
|
||||
media (:class:`telegram.InputMedia`): An object for a new media content
|
||||
of the message.
|
||||
reply_markup (:class:`telegram.ReplyMarkup`, optional): Additional interface options. A
|
||||
JSON-serialized object for an inline keyboard, custom reply keyboard, instructions
|
||||
to remove reply keyboard or to force a reply from the user.
|
||||
timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as
|
||||
the read timeout from the server (instead of the one specified during creation of
|
||||
the connection pool).
|
||||
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
|
||||
"""
|
||||
|
||||
if inline_message_id is None and (chat_id is None or message_id is None):
|
||||
raise ValueError(
|
||||
'edit_message_caption: Both chat_id and message_id are required when '
|
||||
'inline_message_id is not specified')
|
||||
|
||||
url = '{0}/editMessageMedia'.format(self.base_url)
|
||||
|
||||
data = {'media': media}
|
||||
|
||||
if chat_id:
|
||||
data['chat_id'] = chat_id
|
||||
if message_id:
|
||||
data['message_id'] = message_id
|
||||
if inline_message_id:
|
||||
data['inline_message_id'] = inline_message_id
|
||||
|
||||
return url, data
|
||||
|
||||
@log
|
||||
@message
|
||||
def edit_message_reply_markup(self,
|
||||
@@ -1851,6 +2058,8 @@ class Bot(TelegramObject):
|
||||
if url is not None:
|
||||
data['url'] = url
|
||||
if certificate:
|
||||
if InputFile.is_file(certificate):
|
||||
certificate = InputFile(certificate)
|
||||
data['certificate'] = certificate
|
||||
if max_connections is not None:
|
||||
data['max_connections'] = max_connections
|
||||
@@ -2639,7 +2848,7 @@ class Bot(TelegramObject):
|
||||
Args:
|
||||
chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username
|
||||
of the target`channel (in the format @channelusername).
|
||||
photo (`telegram.InputFile`): New chat photo.
|
||||
photo (`filelike object`): New chat photo.
|
||||
timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as
|
||||
the read timeout from the server (instead of the one specified during creation of
|
||||
the connection pool).
|
||||
@@ -2658,6 +2867,9 @@ class Bot(TelegramObject):
|
||||
"""
|
||||
url = '{0}/setChatPhoto'.format(self.base_url)
|
||||
|
||||
if InputFile.is_file(photo):
|
||||
photo = InputFile(photo)
|
||||
|
||||
data = {'chat_id': chat_id, 'photo': photo}
|
||||
data.update(kwargs)
|
||||
|
||||
@@ -2892,6 +3104,9 @@ class Bot(TelegramObject):
|
||||
"""
|
||||
url = '{0}/uploadStickerFile'.format(self.base_url)
|
||||
|
||||
if InputFile.is_file(png_sticker):
|
||||
png_sticker = InputFile(png_sticker)
|
||||
|
||||
data = {'user_id': user_id, 'png_sticker': png_sticker}
|
||||
data.update(kwargs)
|
||||
|
||||
@@ -2943,6 +3158,9 @@ class Bot(TelegramObject):
|
||||
"""
|
||||
url = '{0}/createNewStickerSet'.format(self.base_url)
|
||||
|
||||
if InputFile.is_file(png_sticker):
|
||||
png_sticker = InputFile(png_sticker)
|
||||
|
||||
data = {'user_id': user_id, 'name': name, 'title': title, 'png_sticker': png_sticker,
|
||||
'emojis': emojis}
|
||||
|
||||
@@ -2991,6 +3209,9 @@ class Bot(TelegramObject):
|
||||
"""
|
||||
url = '{0}/addStickerToSet'.format(self.base_url)
|
||||
|
||||
if InputFile.is_file(png_sticker):
|
||||
png_sticker = InputFile(png_sticker)
|
||||
|
||||
data = {'user_id': user_id, 'name': name, 'png_sticker': png_sticker, 'emojis': emojis}
|
||||
|
||||
if mask_position is not None:
|
||||
@@ -3056,6 +3277,44 @@ class Bot(TelegramObject):
|
||||
|
||||
return result
|
||||
|
||||
@log
|
||||
def set_passport_data_errors(self, user_id, errors, timeout=None, **kwargs):
|
||||
"""
|
||||
Informs a user that some of the Telegram Passport elements they provided contains errors.
|
||||
The user will not be able to re-submit their Passport to you until the errors are fixed
|
||||
(the contents of the field for which you returned the error must change). Returns True
|
||||
on success.
|
||||
|
||||
Use this if the data submitted by the user doesn't satisfy the standards your service
|
||||
requires for any reason. For example, if a birthday date seems invalid, a submitted
|
||||
document is blurry, a scan shows evidence of tampering, etc. Supply some details in the
|
||||
error message to make sure the user knows how to correct the issues.
|
||||
|
||||
Args:
|
||||
user_id (:obj:`int`): User identifier
|
||||
errors (List[:class:`PassportElementError`]): A JSON-serialized array describing the
|
||||
errors.
|
||||
timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as
|
||||
the read timeout from the server (instead of the one specified during
|
||||
creation of the connection pool).
|
||||
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
|
||||
|
||||
Returns:
|
||||
:obj:`bool`: On success, ``True`` is returned.
|
||||
|
||||
Raises:
|
||||
:class:`telegram.TelegramError`
|
||||
|
||||
"""
|
||||
url_ = '{0}/setPassportDataErrors'.format(self.base_url)
|
||||
|
||||
data = {'user_id': user_id, 'errors': [error.to_dict() for error in errors]}
|
||||
data.update(kwargs)
|
||||
|
||||
result = self._request.post(url_, data, timeout=timeout)
|
||||
|
||||
return result
|
||||
|
||||
def to_dict(self):
|
||||
data = {'id': self.id, 'username': self.username, 'first_name': self.username}
|
||||
|
||||
@@ -3070,61 +3329,126 @@ class Bot(TelegramObject):
|
||||
|
||||
# camelCase aliases
|
||||
getMe = get_me
|
||||
"""Alias for :attr:`get_me`"""
|
||||
sendMessage = send_message
|
||||
"""Alias for :attr:`send_message`"""
|
||||
deleteMessage = delete_message
|
||||
"""Alias for :attr:`delete_message`"""
|
||||
forwardMessage = forward_message
|
||||
"""Alias for :attr:`forward_message`"""
|
||||
sendPhoto = send_photo
|
||||
"""Alias for :attr:`send_photo`"""
|
||||
sendAudio = send_audio
|
||||
"""Alias for :attr:`send_audio`"""
|
||||
sendDocument = send_document
|
||||
"""Alias for :attr:`send_document`"""
|
||||
sendSticker = send_sticker
|
||||
"""Alias for :attr:`send_sticker`"""
|
||||
sendVideo = send_video
|
||||
"""Alias for :attr:`send_video`"""
|
||||
sendAnimation = send_animation
|
||||
"""Alias for :attr:`send_animation`"""
|
||||
sendVoice = send_voice
|
||||
"""Alias for :attr:`send_voice`"""
|
||||
sendVideoNote = send_video_note
|
||||
"""Alias for :attr:`send_video_note`"""
|
||||
sendMediaGroup = send_media_group
|
||||
"""Alias for :attr:`send_media_group`"""
|
||||
sendLocation = send_location
|
||||
"""Alias for :attr:`send_location`"""
|
||||
editMessageLiveLocation = edit_message_live_location
|
||||
"""Alias for :attr:`edit_message_live_location`"""
|
||||
stopMessageLiveLocation = stop_message_live_location
|
||||
"""Alias for :attr:`stop_message_live_location`"""
|
||||
sendVenue = send_venue
|
||||
"""Alias for :attr:`send_venue`"""
|
||||
sendContact = send_contact
|
||||
"""Alias for :attr:`send_contact`"""
|
||||
sendGame = send_game
|
||||
"""Alias for :attr:`send_game`"""
|
||||
sendChatAction = send_chat_action
|
||||
"""Alias for :attr:`send_chat_action`"""
|
||||
answerInlineQuery = answer_inline_query
|
||||
"""Alias for :attr:`answer_inline_query`"""
|
||||
getUserProfilePhotos = get_user_profile_photos
|
||||
"""Alias for :attr:`get_user_profile_photos`"""
|
||||
getFile = get_file
|
||||
"""Alias for :attr:`get_file`"""
|
||||
kickChatMember = kick_chat_member
|
||||
"""Alias for :attr:`kick_chat_member`"""
|
||||
unbanChatMember = unban_chat_member
|
||||
"""Alias for :attr:`unban_chat_member`"""
|
||||
answerCallbackQuery = answer_callback_query
|
||||
"""Alias for :attr:`answer_callback_query`"""
|
||||
editMessageText = edit_message_text
|
||||
"""Alias for :attr:`edit_message_text`"""
|
||||
editMessageCaption = edit_message_caption
|
||||
"""Alias for :attr:`edit_message_caption`"""
|
||||
editMessageMedia = edit_message_media
|
||||
"""Alias for :attr:`edit_message_media`"""
|
||||
editMessageReplyMarkup = edit_message_reply_markup
|
||||
"""Alias for :attr:`edit_message_reply_markup`"""
|
||||
getUpdates = get_updates
|
||||
"""Alias for :attr:`get_updates`"""
|
||||
setWebhook = set_webhook
|
||||
"""Alias for :attr:`set_webhook`"""
|
||||
deleteWebhook = delete_webhook
|
||||
"""Alias for :attr:`delete_webhook`"""
|
||||
leaveChat = leave_chat
|
||||
"""Alias for :attr:`leave_chat`"""
|
||||
getChat = get_chat
|
||||
"""Alias for :attr:`get_chat`"""
|
||||
getChatAdministrators = get_chat_administrators
|
||||
"""Alias for :attr:`get_chat_administrators`"""
|
||||
getChatMember = get_chat_member
|
||||
"""Alias for :attr:`get_chat_member`"""
|
||||
setChatStickerSet = set_chat_sticker_set
|
||||
"""Alias for :attr:`set_chat_sticker_set`"""
|
||||
deleteChatStickerSet = delete_chat_sticker_set
|
||||
"""Alias for :attr:`delete_chat_sticker_set`"""
|
||||
getChatMembersCount = get_chat_members_count
|
||||
"""Alias for :attr:`get_chat_members_count`"""
|
||||
getWebhookInfo = get_webhook_info
|
||||
"""Alias for :attr:`get_webhook_info`"""
|
||||
setGameScore = set_game_score
|
||||
"""Alias for :attr:`set_game_score`"""
|
||||
getGameHighScores = get_game_high_scores
|
||||
"""Alias for :attr:`get_game_high_scores`"""
|
||||
sendInvoice = send_invoice
|
||||
"""Alias for :attr:`send_invoice`"""
|
||||
answerShippingQuery = answer_shipping_query
|
||||
"""Alias for :attr:`answer_shipping_query`"""
|
||||
answerPreCheckoutQuery = answer_pre_checkout_query
|
||||
"""Alias for :attr:`answer_pre_checkout_query`"""
|
||||
restrictChatMember = restrict_chat_member
|
||||
"""Alias for :attr:`restrict_chat_member`"""
|
||||
promoteChatMember = promote_chat_member
|
||||
"""Alias for :attr:`promote_chat_member`"""
|
||||
exportChatInviteLink = export_chat_invite_link
|
||||
"""Alias for :attr:`export_chat_invite_link`"""
|
||||
setChatPhoto = set_chat_photo
|
||||
"""Alias for :attr:`set_chat_photo`"""
|
||||
deleteChatPhoto = delete_chat_photo
|
||||
"""Alias for :attr:`delete_chat_photo`"""
|
||||
setChatTitle = set_chat_title
|
||||
"""Alias for :attr:`set_chat_title`"""
|
||||
setChatDescription = set_chat_description
|
||||
"""Alias for :attr:`set_chat_description`"""
|
||||
pinChatMessage = pin_chat_message
|
||||
"""Alias for :attr:`pin_chat_message`"""
|
||||
unpinChatMessage = unpin_chat_message
|
||||
"""Alias for :attr:`unpin_chat_message`"""
|
||||
getStickerSet = get_sticker_set
|
||||
"""Alias for :attr:`get_sticker_set`"""
|
||||
uploadStickerFile = upload_sticker_file
|
||||
"""Alias for :attr:`upload_sticker_file`"""
|
||||
createNewStickerSet = create_new_sticker_set
|
||||
"""Alias for :attr:`create_new_sticker_set`"""
|
||||
addStickerToSet = add_sticker_to_set
|
||||
"""Alias for :attr:`add_sticker_to_set`"""
|
||||
setStickerPositionInSet = set_sticker_position_in_set
|
||||
"""Alias for :attr:`set_sticker_position_in_set`"""
|
||||
deleteStickerFromSet = delete_sticker_from_set
|
||||
"""Alias for :attr:`delete_sticker_from_set`"""
|
||||
setPassportDataErrors = set_passport_data_errors
|
||||
"""Alias for :attr:`set_passport_data_errors`"""
|
||||
|
||||
+37
-16
@@ -116,6 +116,14 @@ class Chat(TelegramObject):
|
||||
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:
|
||||
@@ -216,7 +224,7 @@ class Chat(TelegramObject):
|
||||
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 +232,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 +245,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 +258,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 +271,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 +297,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 +310,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 +323,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 +336,4 @@ 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)
|
||||
|
||||
@@ -50,7 +50,7 @@ class CallbackQueryHandler(Handler):
|
||||
|
||||
Note:
|
||||
:attr:`pass_user_data` and :attr:`pass_chat_data` determine whether a ``dict`` you
|
||||
can use to keep any data in will be sent to the :attr:`callback` function.. Related to
|
||||
can use to keep any data in will be sent to the :attr:`callback` function. Related to
|
||||
either the user or the chat that the update was sent in. For each update from the same user
|
||||
or in the same chat, it will be the same ``dict``.
|
||||
|
||||
|
||||
@@ -39,7 +39,7 @@ class ChosenInlineResultHandler(Handler):
|
||||
|
||||
Note:
|
||||
:attr:`pass_user_data` and :attr:`pass_chat_data` determine whether a ``dict`` you
|
||||
can use to keep any data in will be sent to the :attr:`callback` function.. Related to
|
||||
can use to keep any data in will be sent to the :attr:`callback` function. Related to
|
||||
either the user or the chat that the update was sent in. For each update from the same user
|
||||
or in the same chat, it will be the same ``dict``.
|
||||
|
||||
|
||||
@@ -52,7 +52,7 @@ class CommandHandler(Handler):
|
||||
|
||||
Note:
|
||||
:attr:`pass_user_data` and :attr:`pass_chat_data` determine whether a ``dict`` you
|
||||
can use to keep any data in will be sent to the :attr:`callback` function.. Related to
|
||||
can use to keep any data in will be sent to the :attr:`callback` function. Related to
|
||||
either the user or the chat that the update was sent in. For each update from the same user
|
||||
or in the same chat, it will be the same ``dict``.
|
||||
|
||||
@@ -140,6 +140,10 @@ class CommandHandler(Handler):
|
||||
command.append(
|
||||
message.bot.username) # in case the command was sent without a username
|
||||
|
||||
if not (command[0].lower() in self.command
|
||||
and command[1].lower() == message.bot.username.lower()):
|
||||
return False
|
||||
|
||||
if self.filters is None:
|
||||
res = True
|
||||
elif isinstance(self.filters, list):
|
||||
@@ -147,8 +151,7 @@ class CommandHandler(Handler):
|
||||
else:
|
||||
res = self.filters(message)
|
||||
|
||||
return res and (command[0].lower() in self.command
|
||||
and command[1].lower() == message.bot.username.lower())
|
||||
return res
|
||||
|
||||
return False
|
||||
|
||||
|
||||
@@ -303,11 +303,10 @@ class ConversationHandler(Handler):
|
||||
|
||||
"""
|
||||
new_state = self.current_handler.handle_update(update, dispatcher)
|
||||
timeout_job = self.timeout_jobs.get(self.current_conversation)
|
||||
timeout_job = self.timeout_jobs.pop(self.current_conversation, None)
|
||||
|
||||
if timeout_job is not None or new_state == self.END:
|
||||
if timeout_job is not None:
|
||||
timeout_job.schedule_removal()
|
||||
del self.timeout_jobs[self.current_conversation]
|
||||
if self.conversation_timeout and new_state != self.END:
|
||||
self.timeout_jobs[self.current_conversation] = dispatcher.job_queue.run_once(
|
||||
self._trigger_timeout, self.conversation_timeout,
|
||||
@@ -330,4 +329,5 @@ class ConversationHandler(Handler):
|
||||
self.conversations[key] = new_state
|
||||
|
||||
def _trigger_timeout(self, bot, job):
|
||||
del self.timeout_jobs[job.context]
|
||||
self.update_state(self.END, job.context)
|
||||
|
||||
@@ -143,7 +143,7 @@ class Dispatcher(object):
|
||||
|
||||
"""
|
||||
if cls.__singleton is not None:
|
||||
return cls.__singleton()
|
||||
return cls.__singleton() # pylint: disable=not-callable
|
||||
else:
|
||||
raise RuntimeError('{} not initialized or multiple instances exist'.format(
|
||||
cls.__name__))
|
||||
@@ -308,7 +308,7 @@ class Dispatcher(object):
|
||||
A handler must be an instance of a subclass of :class:`telegram.ext.Handler`. All handlers
|
||||
are organized in groups with a numeric value. The default group is 0. All groups will be
|
||||
evaluated for handling an update, but only 0 or 1 handler per group will be used. If
|
||||
:class:`telegram.DispatcherHandlerStop` is raised from one of the handlers, no further
|
||||
:class:`telegram.ext.DispatcherHandlerStop` is raised from one of the handlers, no further
|
||||
handlers (regardless of the group) will be called.
|
||||
|
||||
The priority/order of handlers is determined as follows:
|
||||
@@ -385,4 +385,4 @@ class Dispatcher(object):
|
||||
|
||||
else:
|
||||
self.logger.exception(
|
||||
'No error handlers are registered, logging exception...', exc_info=error)
|
||||
'No error handlers are registered, logging exception.', exc_info=error)
|
||||
|
||||
+153
-1
@@ -17,6 +17,8 @@
|
||||
# You should have received a copy of the GNU Lesser Public License
|
||||
# along with this program. If not, see [http://www.gnu.org/licenses/].
|
||||
"""This module contains the Filters for use with the MessageHandler class."""
|
||||
|
||||
import re
|
||||
from telegram import Chat
|
||||
from future.utils import string_types
|
||||
|
||||
@@ -171,6 +173,35 @@ class Filters(object):
|
||||
command = _Command()
|
||||
""":obj:`Filter`: Messages starting with ``/``."""
|
||||
|
||||
class regex(BaseFilter):
|
||||
"""
|
||||
Filters updates by searching for an occurence of ``pattern`` in the message text.
|
||||
The ``re.search`` function is used to determine whether an update should be filtered.
|
||||
Refer to the documentation of the ``re`` module for more information.
|
||||
|
||||
Note: Does not allow passing groups or a groupdict like the ``RegexHandler`` yet,
|
||||
but this will probably be implemented in a future update, gradually phasing out the
|
||||
RegexHandler (see https://github.com/python-telegram-bot/python-telegram-bot/issues/835).
|
||||
|
||||
Examples:
|
||||
Example ``CommandHandler("start", deep_linked_callback, Filters.regex('parameter'))``
|
||||
|
||||
Args:
|
||||
pattern (:obj:`str` | :obj:`Pattern`): The regex pattern.
|
||||
"""
|
||||
|
||||
def __init__(self, pattern):
|
||||
self.pattern = re.compile(pattern)
|
||||
self.name = 'Filters.regex({})'.format(self.pattern)
|
||||
|
||||
# TODO: Once the callback revamp (#1026) is done, the regex filter should be able to pass
|
||||
# the matched groups and groupdict to the context object.
|
||||
|
||||
def filter(self, message):
|
||||
if message.text:
|
||||
return bool(self.pattern.search(message.text))
|
||||
return False
|
||||
|
||||
class _Reply(BaseFilter):
|
||||
name = 'Filters.reply'
|
||||
|
||||
@@ -192,12 +223,94 @@ class Filters(object):
|
||||
class _Document(BaseFilter):
|
||||
name = 'Filters.document'
|
||||
|
||||
class category(BaseFilter):
|
||||
"""This Filter filters documents by their category in the mime-type attribute
|
||||
|
||||
Note:
|
||||
This Filter only filters by the mime_type of the document,
|
||||
it doesn't check the validity of the document.
|
||||
The user can manipulate the mime-type of a message and
|
||||
send media with wrong types that don't fit to this handler.
|
||||
|
||||
Examples:
|
||||
Filters.documents.category('audio/') returnes `True` for all types
|
||||
of audio sent as file, for example 'audio/mpeg' or 'audio/x-wav'
|
||||
"""
|
||||
|
||||
def __init__(self, category):
|
||||
"""Initialize the category you want to filter
|
||||
|
||||
Args:
|
||||
category (str, optional): category of the media you want to filter"""
|
||||
self.category = category
|
||||
self.name = "Filters.document.category('{}')".format(self.category)
|
||||
|
||||
def filter(self, message):
|
||||
if message.document:
|
||||
return message.document.mime_type.startswith(self.category)
|
||||
|
||||
application = category('application/')
|
||||
audio = category('audio/')
|
||||
image = category('image/')
|
||||
video = category('video/')
|
||||
text = category('text/')
|
||||
|
||||
class mime_type(BaseFilter):
|
||||
"""This Filter filters documents by their mime-type attribute
|
||||
|
||||
Note:
|
||||
This Filter only filters by the mime_type of the document,
|
||||
it doesn't check the validity of document.
|
||||
The user can manipulate the mime-type of a message and
|
||||
send media with wrong types that don't fit to this handler.
|
||||
|
||||
Examples:
|
||||
Filters.documents.mime_type('audio/mpeg') filters all audio in mp3 format.
|
||||
"""
|
||||
|
||||
def __init__(self, mimetype):
|
||||
"""Initialize the category you want to filter
|
||||
|
||||
Args:
|
||||
filetype (str, optional): mime_type of the media you want to filter"""
|
||||
self.mimetype = mimetype
|
||||
self.name = "Filters.document.mime_type('{}')".format(self.mimetype)
|
||||
|
||||
def filter(self, message):
|
||||
if message.document:
|
||||
return message.document.mime_type == self.mimetype
|
||||
|
||||
apk = mime_type('application/vnd.android.package-archive')
|
||||
doc = mime_type('application/msword')
|
||||
docx = mime_type('application/vnd.openxmlformats-officedocument.wordprocessingml.document')
|
||||
exe = mime_type('application/x-ms-dos-executable')
|
||||
gif = mime_type('video/mp4')
|
||||
jpg = mime_type('image/jpeg')
|
||||
mp3 = mime_type('audio/mpeg')
|
||||
pdf = mime_type('application/pdf')
|
||||
py = mime_type('text/x-python')
|
||||
svg = mime_type('image/svg+xml')
|
||||
txt = mime_type('text/plain')
|
||||
targz = mime_type('application/x-compressed-tar')
|
||||
wav = mime_type('audio/x-wav')
|
||||
xml = mime_type('application/xml')
|
||||
zip = mime_type('application/zip')
|
||||
|
||||
def filter(self, message):
|
||||
return bool(message.document)
|
||||
|
||||
document = _Document()
|
||||
""":obj:`Filter`: Messages that contain :class:`telegram.Document`."""
|
||||
|
||||
class _Animation(BaseFilter):
|
||||
name = 'Filters.animation'
|
||||
|
||||
def filter(self, message):
|
||||
return bool(message.animation)
|
||||
|
||||
animation = _Animation()
|
||||
""":obj:`Filter`: Messages that contain :class:`telegram.Animation`."""
|
||||
|
||||
class _Photo(BaseFilter):
|
||||
name = 'Filters.photo'
|
||||
|
||||
@@ -234,6 +347,15 @@ class Filters(object):
|
||||
voice = _Voice()
|
||||
""":obj:`Filter`: Messages that contain :class:`telegram.Voice`."""
|
||||
|
||||
class _VideoNote(BaseFilter):
|
||||
name = 'Filters.video_note'
|
||||
|
||||
def filter(self, message):
|
||||
return bool(message.video_note)
|
||||
|
||||
video_note = _VideoNote()
|
||||
""":obj:`Filter`: Messages that contain :class:`telegram.VideoNote`."""
|
||||
|
||||
class _Contact(BaseFilter):
|
||||
name = 'Filters.contact'
|
||||
|
||||
@@ -430,7 +552,28 @@ class Filters(object):
|
||||
self.name = 'Filters.entity({})'.format(self.entity_type)
|
||||
|
||||
def filter(self, message):
|
||||
return any([entity.type == self.entity_type for entity in message.entities])
|
||||
return any(entity.type == self.entity_type for entity in message.entities)
|
||||
|
||||
class caption_entity(BaseFilter):
|
||||
"""
|
||||
Filters media messages to only allow those which have a :class:`telegram.MessageEntity`
|
||||
where their `type` matches `entity_type`.
|
||||
|
||||
Examples:
|
||||
Example ``MessageHandler(Filters.caption_entity("hashtag"), callback_method)``
|
||||
|
||||
Args:
|
||||
entity_type: Caption Entity type to check for. All types can be found as constants
|
||||
in :class:`telegram.MessageEntity`.
|
||||
|
||||
"""
|
||||
|
||||
def __init__(self, entity_type):
|
||||
self.entity_type = entity_type
|
||||
self.name = 'Filters.caption_entity({})'.format(self.entity_type)
|
||||
|
||||
def filter(self, message):
|
||||
return any(entity.type == self.entity_type for entity in message.caption_entities)
|
||||
|
||||
class _Private(BaseFilter):
|
||||
name = 'Filters.private'
|
||||
@@ -543,6 +686,15 @@ class Filters(object):
|
||||
successful_payment = _SuccessfulPayment()
|
||||
""":obj:`Filter`: Messages that confirm a :class:`telegram.SuccessfulPayment`."""
|
||||
|
||||
class _PassportData(BaseFilter):
|
||||
name = 'Filters.passport_data'
|
||||
|
||||
def filter(self, message):
|
||||
return bool(message.passport_data)
|
||||
|
||||
passport_data = _PassportData()
|
||||
""":obj:`Filter`: Messages that contain a :class:`telegram.PassportData`"""
|
||||
|
||||
class language(BaseFilter):
|
||||
"""Filters messages to only allow those which are from users with a certain language code.
|
||||
|
||||
|
||||
@@ -35,7 +35,7 @@ class Handler(object):
|
||||
|
||||
Note:
|
||||
:attr:`pass_user_data` and :attr:`pass_chat_data` determine whether a ``dict`` you
|
||||
can use to keep any data in will be sent to the :attr:`callback` function.. Related to
|
||||
can use to keep any data in will be sent to the :attr:`callback` function. Related to
|
||||
either the user or the chat that the update was sent in. For each update from the same user
|
||||
or in the same chat, it will be the same ``dict``.
|
||||
|
||||
|
||||
@@ -50,7 +50,7 @@ class InlineQueryHandler(Handler):
|
||||
|
||||
Note:
|
||||
:attr:`pass_user_data` and :attr:`pass_chat_data` determine whether a ``dict`` you
|
||||
can use to keep any data in will be sent to the :attr:`callback` function.. Related to
|
||||
can use to keep any data in will be sent to the :attr:`callback` function. Related to
|
||||
either the user or the chat that the update was sent in. For each update from the same user
|
||||
or in the same chat, it will be the same ``dict``.
|
||||
|
||||
|
||||
@@ -50,7 +50,7 @@ class MessageHandler(Handler):
|
||||
|
||||
Note:
|
||||
:attr:`pass_user_data` and :attr:`pass_chat_data` determine whether a ``dict`` you
|
||||
can use to keep any data in will be sent to the :attr:`callback` function.. Related to
|
||||
can use to keep any data in will be sent to the :attr:`callback` function. Related to
|
||||
either the user or the chat that the update was sent in. For each update from the same user
|
||||
or in the same chat, it will be the same ``dict``.
|
||||
|
||||
|
||||
@@ -38,7 +38,7 @@ class PreCheckoutQueryHandler(Handler):
|
||||
|
||||
Note:
|
||||
:attr:`pass_user_data` and :attr:`pass_chat_data` determine whether a ``dict`` you
|
||||
can use to keep any data in will be sent to the :attr:`callback` function.. Related to
|
||||
can use to keep any data in will be sent to the :attr:`callback` function. Related to
|
||||
either the user or the chat that the update was sent in. For each update from the same user
|
||||
or in the same chat, it will be the same ``dict``.
|
||||
|
||||
|
||||
@@ -53,7 +53,7 @@ class RegexHandler(Handler):
|
||||
|
||||
Note:
|
||||
:attr:`pass_user_data` and :attr:`pass_chat_data` determine whether a ``dict`` you
|
||||
can use to keep any data in will be sent to the :attr:`callback` function.. Related to
|
||||
can use to keep any data in will be sent to the :attr:`callback` function. Related to
|
||||
either the user or the chat that the update was sent in. For each update from the same user
|
||||
or in the same chat, it will be the same ``dict``.
|
||||
|
||||
|
||||
@@ -38,7 +38,7 @@ class ShippingQueryHandler(Handler):
|
||||
|
||||
Note:
|
||||
:attr:`pass_user_data` and :attr:`pass_chat_data` determine whether a ``dict`` you
|
||||
can use to keep any data in will be sent to the :attr:`callback` function.. Related to
|
||||
can use to keep any data in will be sent to the :attr:`callback` function. Related to
|
||||
either the user or the chat that the update was sent in. For each update from the same user
|
||||
or in the same chat, it will be the same ``dict``.
|
||||
|
||||
|
||||
@@ -66,6 +66,8 @@ class Updater(object):
|
||||
bot (:class:`telegram.Bot`, optional): A pre-initialized bot instance. If a pre-initialized
|
||||
bot is used, it is the user's responsibility to create it using a `Request`
|
||||
instance with a large enough connection pool.
|
||||
private_key (:obj:`bytes`, optional): Private key for decryption of telegram passport data.
|
||||
private_key_password (:obj:`bytes`, optional): Password for above private key.
|
||||
user_sig_handler (:obj:`function`, optional): Takes ``signum, frame`` as positional
|
||||
arguments. This will be called when a signal is received, defaults are (SIGINT,
|
||||
SIGTERM, SIGABRT) setable with :attr:`idle`.
|
||||
@@ -89,6 +91,8 @@ class Updater(object):
|
||||
base_url=None,
|
||||
workers=4,
|
||||
bot=None,
|
||||
private_key=None,
|
||||
private_key_password=None,
|
||||
user_sig_handler=None,
|
||||
request_kwargs=None):
|
||||
|
||||
@@ -96,6 +100,8 @@ class Updater(object):
|
||||
raise ValueError('`token` or `bot` must be passed')
|
||||
if (token is not None) and (bot is not None):
|
||||
raise ValueError('`token` and `bot` are mutually exclusive')
|
||||
if (private_key is not None) and (bot is not None):
|
||||
raise ValueError('`bot` and `private_key` are mutually exclusive')
|
||||
|
||||
self.logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -119,7 +125,8 @@ class Updater(object):
|
||||
if 'con_pool_size' not in request_kwargs:
|
||||
request_kwargs['con_pool_size'] = con_pool_size
|
||||
self._request = Request(**request_kwargs)
|
||||
self.bot = Bot(token, base_url, request=self._request)
|
||||
self.bot = Bot(token, base_url, request=self._request, private_key=private_key,
|
||||
private_key_password=private_key_password)
|
||||
self.user_sig_handler = user_sig_handler
|
||||
self.update_queue = Queue()
|
||||
self.job_queue = JobQueue(self.bot)
|
||||
@@ -381,7 +388,7 @@ class Updater(object):
|
||||
stderr=subprocess.STDOUT)
|
||||
except OSError:
|
||||
exit_code = 0
|
||||
if exit_code is 0:
|
||||
if exit_code == 0:
|
||||
try:
|
||||
self.httpd.socket = ssl.wrap_socket(
|
||||
self.httpd.socket, certfile=cert, keyfile=key, server_side=True)
|
||||
|
||||
@@ -26,6 +26,9 @@ class Animation(TelegramObject):
|
||||
|
||||
Attributes:
|
||||
file_id (:obj:`str`): Unique file identifier.
|
||||
width (:obj:`int`): Video width as defined by sender.
|
||||
height (:obj:`int`): Video height as defined by sender.
|
||||
duration (:obj:`int`): Duration of the video in seconds as defined by sender.
|
||||
thumb (:class:`telegram.PhotoSize`): Optional. Animation thumbnail as defined
|
||||
by sender.
|
||||
file_name (:obj:`str`): Optional. Original animation filename as defined by sender.
|
||||
@@ -34,6 +37,9 @@ class Animation(TelegramObject):
|
||||
|
||||
Args:
|
||||
file_id (:obj:`str`): Unique file identifier.
|
||||
width (:obj:`int`): Video width as defined by sender.
|
||||
height (:obj:`int`): Video height as defined by sender.
|
||||
duration (:obj:`int`): Duration of the video in seconds as defined by sender.
|
||||
thumb (:class:`telegram.PhotoSize`, optional): Animation thumbnail as defined by sender.
|
||||
file_name (:obj:`str`, optional): Original animation filename as defined by sender.
|
||||
mime_type (:obj:`str`, optional): MIME type of the file as defined by sender.
|
||||
@@ -43,12 +49,19 @@ class Animation(TelegramObject):
|
||||
|
||||
def __init__(self,
|
||||
file_id,
|
||||
width,
|
||||
height,
|
||||
duration,
|
||||
thumb=None,
|
||||
file_name=None,
|
||||
mime_type=None,
|
||||
file_size=None,
|
||||
**kwargs):
|
||||
self.file_id = file_id
|
||||
# Required
|
||||
self.file_id = str(file_id)
|
||||
self.width = int(width)
|
||||
self.height = int(height)
|
||||
self.duration = duration
|
||||
self.thumb = thumb
|
||||
self.file_name = file_name
|
||||
self.mime_type = mime_type
|
||||
@@ -18,7 +18,7 @@
|
||||
# along with this program. If not, see [http://www.gnu.org/licenses/].
|
||||
"""This module contains an object that represents a Telegram Audio."""
|
||||
|
||||
from telegram import TelegramObject
|
||||
from telegram import TelegramObject, PhotoSize
|
||||
|
||||
|
||||
class Audio(TelegramObject):
|
||||
@@ -32,6 +32,8 @@ class Audio(TelegramObject):
|
||||
title (:obj:`str`): Optional. Title of the audio as defined by sender or by audio tags.
|
||||
mime_type (:obj:`str`): Optional. MIME type of the file as defined by sender.
|
||||
file_size (:obj:`int`): Optional. File size.
|
||||
thumb (:class:`telegram.PhotoSize`): Optional. Thumbnail of the album cover to
|
||||
which the music file belongs
|
||||
bot (:class:`telegram.Bot`): Optional. The Bot to use for instance methods.
|
||||
|
||||
Args:
|
||||
@@ -42,6 +44,8 @@ class Audio(TelegramObject):
|
||||
title (:obj:`str`, optional): Title of the audio as defined by sender or by audio tags.
|
||||
mime_type (:obj:`str`, optional): MIME type of the file as defined by sender.
|
||||
file_size (:obj:`int`, optional): File size.
|
||||
thumb (:class:`telegram.PhotoSize`, optional): Thumbnail of the album cover to
|
||||
which the music file belongs
|
||||
bot (:class:`telegram.Bot`, optional): The Bot to use for instance methods.
|
||||
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
|
||||
|
||||
@@ -54,6 +58,7 @@ class Audio(TelegramObject):
|
||||
title=None,
|
||||
mime_type=None,
|
||||
file_size=None,
|
||||
thumb=None,
|
||||
bot=None,
|
||||
**kwargs):
|
||||
# Required
|
||||
@@ -64,6 +69,7 @@ class Audio(TelegramObject):
|
||||
self.title = title
|
||||
self.mime_type = mime_type
|
||||
self.file_size = file_size
|
||||
self.thumb = thumb
|
||||
self.bot = bot
|
||||
|
||||
self._id_attrs = (self.file_id,)
|
||||
@@ -73,6 +79,8 @@ class Audio(TelegramObject):
|
||||
if not data:
|
||||
return None
|
||||
|
||||
data['thumb'] = PhotoSize.de_json(data.get('thumb'), bot)
|
||||
|
||||
return cls(bot=bot, **data)
|
||||
|
||||
def get_file(self, timeout=None, **kwargs):
|
||||
|
||||
@@ -29,23 +29,27 @@ class Contact(TelegramObject):
|
||||
first_name (:obj:`str`): Contact's first name.
|
||||
last_name (:obj:`str`): Optional. Contact's last name.
|
||||
user_id (:obj:`int`): Optional. Contact's user identifier in Telegram.
|
||||
vcard (:obj:`str`): Optional. Additional data about the contact in the form of a vCard.
|
||||
|
||||
Args:
|
||||
phone_number (:obj:`str`): Contact's phone number.
|
||||
first_name (:obj:`str`): Contact's first name.
|
||||
last_name (:obj:`str`, optional): Contact's last name.
|
||||
user_id (:obj:`int`, optional): Contact's user identifier in Telegram.
|
||||
vcard (:obj:`str`, optional): Additional data about the contact in the form of a vCard.
|
||||
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
|
||||
|
||||
"""
|
||||
|
||||
def __init__(self, phone_number, first_name, last_name=None, user_id=None, **kwargs):
|
||||
def __init__(self, phone_number, first_name, last_name=None, user_id=None, vcard=None,
|
||||
**kwargs):
|
||||
# Required
|
||||
self.phone_number = str(phone_number)
|
||||
self.first_name = first_name
|
||||
# Optionals
|
||||
self.last_name = last_name
|
||||
self.user_id = user_id
|
||||
self.vcard = vcard
|
||||
|
||||
self._id_attrs = (self.phone_number,)
|
||||
|
||||
|
||||
+21
-1
@@ -17,11 +17,13 @@
|
||||
# You should have received a copy of the GNU Lesser Public License
|
||||
# along with this program. If not, see [http://www.gnu.org/licenses/].
|
||||
"""This module contains an object that represents a Telegram File."""
|
||||
from base64 import b64decode
|
||||
from os.path import basename
|
||||
|
||||
from future.backports.urllib import parse as urllib_parse
|
||||
|
||||
from telegram import TelegramObject
|
||||
from telegram.passport.credentials import decrypt
|
||||
|
||||
|
||||
class File(TelegramObject):
|
||||
@@ -45,6 +47,10 @@ class File(TelegramObject):
|
||||
bot (:obj:`telegram.Bot`, optional): Bot to use with shortcut method.
|
||||
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
|
||||
|
||||
Note:
|
||||
If you obtain an instance of this class from :attr:`telegram.PassportFile.get_file`,
|
||||
then it will automatically be decrypted as it downloads when you call :attr:`download()`.
|
||||
|
||||
"""
|
||||
|
||||
def __init__(self, file_id, bot=None, file_size=None, file_path=None, **kwargs):
|
||||
@@ -56,6 +62,7 @@ class File(TelegramObject):
|
||||
self.file_path = file_path
|
||||
|
||||
self.bot = bot
|
||||
self._credentials = None
|
||||
|
||||
self._id_attrs = (self.file_id,)
|
||||
|
||||
@@ -100,6 +107,10 @@ class File(TelegramObject):
|
||||
|
||||
if out:
|
||||
buf = self.bot.request.retrieve(url)
|
||||
if self._credentials:
|
||||
buf = decrypt(b64decode(self._credentials.secret),
|
||||
b64decode(self._credentials.hash),
|
||||
buf)
|
||||
out.write(buf)
|
||||
return out
|
||||
else:
|
||||
@@ -108,7 +119,13 @@ class File(TelegramObject):
|
||||
else:
|
||||
filename = basename(self.file_path)
|
||||
|
||||
self.bot.request.download(url, filename, timeout=timeout)
|
||||
buf = self.bot.request.retrieve(url, timeout=timeout)
|
||||
if self._credentials:
|
||||
buf = decrypt(b64decode(self._credentials.secret),
|
||||
b64decode(self._credentials.hash),
|
||||
buf)
|
||||
with open(filename, 'wb') as fobj:
|
||||
fobj.write(buf)
|
||||
return filename
|
||||
|
||||
def _get_encoded_url(self):
|
||||
@@ -133,3 +150,6 @@ class File(TelegramObject):
|
||||
|
||||
buf.extend(self.bot.request.retrieve(self._get_encoded_url()))
|
||||
return buf
|
||||
|
||||
def set_credentials(self, credentials):
|
||||
self._credentials = credentials
|
||||
|
||||
+40
-111
@@ -19,126 +19,68 @@
|
||||
# along with this program. If not, see [http://www.gnu.org/licenses/].
|
||||
"""This module contains an object that represents a Telegram InputFile."""
|
||||
|
||||
try:
|
||||
# python 3
|
||||
from email.generator import _make_boundary as choose_boundary
|
||||
except ImportError:
|
||||
# python 2
|
||||
from mimetools import choose_boundary
|
||||
|
||||
import imghdr
|
||||
import mimetypes
|
||||
import os
|
||||
import sys
|
||||
from uuid import uuid4
|
||||
|
||||
from telegram import TelegramError
|
||||
|
||||
DEFAULT_MIME_TYPE = 'application/octet-stream'
|
||||
USER_AGENT = 'Python Telegram Bot (https://github.com/python-telegram-bot/python-telegram-bot)'
|
||||
FILE_TYPES = ('audio', 'document', 'photo', 'sticker', 'video', 'voice', 'certificate',
|
||||
'video_note', 'png_sticker')
|
||||
|
||||
|
||||
class InputFile(object):
|
||||
"""This object represents a Telegram InputFile.
|
||||
|
||||
Attributes:
|
||||
data (:obj:`dict`): Data containing an inputfile.
|
||||
input_file_content (:obj:`bytes`): The binaray content of the file to send.
|
||||
filename (:obj:`str`): Optional, Filename for the file to be sent.
|
||||
attach (:obj:`str`): Optional, attach id for sending multiple files.
|
||||
|
||||
Args:
|
||||
data (:obj:`dict`): Data containing an inputfile.
|
||||
obj (:obj:`File handler`): An open file descriptor.
|
||||
filename (:obj:`str`, optional): Filename for this InputFile.
|
||||
attach (:obj:`bool`, optional): Whether this should be send as one file or is part of a
|
||||
collection of files.
|
||||
|
||||
Raises:
|
||||
TelegramError
|
||||
|
||||
"""
|
||||
|
||||
def __init__(self, data):
|
||||
self.data = data
|
||||
self.boundary = choose_boundary()
|
||||
def __init__(self, obj, filename=None, attach=None):
|
||||
self.filename = None
|
||||
self.input_file_content = obj.read()
|
||||
self.attach = 'attached' + uuid4().hex if attach else None
|
||||
|
||||
for t in FILE_TYPES:
|
||||
if t in data:
|
||||
self.input_name = t
|
||||
self.input_file = data.pop(t)
|
||||
break
|
||||
else:
|
||||
raise TelegramError('Unknown inputfile type')
|
||||
if filename:
|
||||
self.filename = filename
|
||||
elif (hasattr(obj, 'name') and
|
||||
not isinstance(obj.name, int) and # py3
|
||||
obj.name != '<fdopen>'): # py2
|
||||
# on py2.7, pylint fails to understand this properly
|
||||
# pylint: disable=E1101
|
||||
self.filename = os.path.basename(obj.name)
|
||||
|
||||
if hasattr(self.input_file, 'read'):
|
||||
self.filename = None
|
||||
self.input_file_content = self.input_file.read()
|
||||
if 'filename' in data:
|
||||
self.filename = self.data.pop('filename')
|
||||
elif hasattr(self.input_file, 'name'):
|
||||
# on py2.7, pylint fails to understand this properly
|
||||
# pylint: disable=E1101
|
||||
self.filename = os.path.basename(self.input_file.name)
|
||||
try:
|
||||
self.mimetype = self.is_image(self.input_file_content)
|
||||
except TelegramError:
|
||||
if self.filename:
|
||||
self.mimetype = mimetypes.guess_type(
|
||||
self.filename)[0] or DEFAULT_MIME_TYPE
|
||||
else:
|
||||
self.mimetype = DEFAULT_MIME_TYPE
|
||||
if not self.filename or '.' not in self.filename:
|
||||
self.filename = self.mimetype.replace('/', '.')
|
||||
|
||||
try:
|
||||
self.mimetype = self.is_image(self.input_file_content)
|
||||
if not self.filename or '.' not in self.filename:
|
||||
self.filename = self.mimetype.replace('/', '.')
|
||||
except TelegramError:
|
||||
if self.filename:
|
||||
self.mimetype = mimetypes.guess_type(
|
||||
self.filename)[0] or DEFAULT_MIME_TYPE
|
||||
else:
|
||||
self.mimetype = DEFAULT_MIME_TYPE
|
||||
if sys.version_info < (3,):
|
||||
if isinstance(self.filename, unicode): # flake8: noqa pylint: disable=E0602
|
||||
self.filename = self.filename.encode('utf-8', 'replace')
|
||||
|
||||
@property
|
||||
def headers(self):
|
||||
""":obj:`dict`: Headers."""
|
||||
|
||||
return {'User-agent': USER_AGENT, 'Content-type': self.content_type}
|
||||
|
||||
@property
|
||||
def content_type(self):
|
||||
""":obj:`str`: Content type"""
|
||||
return 'multipart/form-data; boundary=%s' % self.boundary
|
||||
|
||||
def to_form(self):
|
||||
"""Transform the inputfile to multipart/form data.
|
||||
|
||||
Returns:
|
||||
:obj:`str`
|
||||
|
||||
"""
|
||||
form = []
|
||||
form_boundary = '--' + self.boundary
|
||||
|
||||
# Add data fields
|
||||
for name in iter(self.data):
|
||||
value = self.data[name]
|
||||
form.extend([
|
||||
form_boundary, 'Content-Disposition: form-data; name="%s"' % name, '', str(value)
|
||||
])
|
||||
|
||||
# Add input_file to upload
|
||||
form.extend([
|
||||
form_boundary, 'Content-Disposition: form-data; name="%s"; filename="%s"' %
|
||||
(self.input_name,
|
||||
self.filename), 'Content-Type: %s' % self.mimetype, '', self.input_file_content
|
||||
])
|
||||
|
||||
form.append('--' + self.boundary + '--')
|
||||
form.append('')
|
||||
|
||||
return self._parse(form)
|
||||
|
||||
@staticmethod
|
||||
def _parse(form):
|
||||
if sys.version_info > (3,):
|
||||
# on Python 3 form needs to be byte encoded
|
||||
encoded_form = []
|
||||
for item in form:
|
||||
try:
|
||||
encoded_form.append(item.encode())
|
||||
except AttributeError:
|
||||
encoded_form.append(item)
|
||||
|
||||
return b'\r\n'.join(encoded_form)
|
||||
return '\r\n'.join(form)
|
||||
def field_tuple(self):
|
||||
return self.filename, self.input_file_content, self.mimetype
|
||||
|
||||
@staticmethod
|
||||
def is_image(stream):
|
||||
@@ -158,22 +100,9 @@ class InputFile(object):
|
||||
raise TelegramError('Could not parse file content')
|
||||
|
||||
@staticmethod
|
||||
def is_inputfile(data):
|
||||
"""Check if the request is a file request.
|
||||
def is_file(obj):
|
||||
return hasattr(obj, 'read')
|
||||
|
||||
Args:
|
||||
data (Dict[:obj:`str`, :obj:`str`]): A dict of (str, str) key/value pairs.
|
||||
|
||||
Returns:
|
||||
:obj:`bool`
|
||||
|
||||
"""
|
||||
if data:
|
||||
file_type = [i for i in iter(data) if i in FILE_TYPES]
|
||||
|
||||
if file_type:
|
||||
file_content = data[file_type[0]]
|
||||
|
||||
return hasattr(file_content, 'read')
|
||||
|
||||
return False
|
||||
def to_dict(self):
|
||||
if self.attach:
|
||||
return 'attach://' + self.attach
|
||||
|
||||
@@ -18,14 +18,334 @@
|
||||
# along with this program. If not, see [http://www.gnu.org/licenses/].
|
||||
"""Base class for Telegram InputMedia Objects."""
|
||||
|
||||
from telegram import TelegramObject
|
||||
from telegram import TelegramObject, InputFile, PhotoSize, Animation, Video, Audio, Document
|
||||
|
||||
|
||||
class InputMedia(TelegramObject):
|
||||
"""Base class for Telegram InputMedia Objects.
|
||||
|
||||
See :class:`telegram.InputMediaPhoto` and :class:`telegram.InputMediaVideo` for
|
||||
detailed use.
|
||||
See :class:`telegram.InputMediaAnimation`, :class:`telegram.InputMediaAudio`,
|
||||
:class:`telegram.InputMediaDocument`, :class:`telegram.InputMediaPhoto` and
|
||||
:class:`telegram.InputMediaVideo` for detailed use.
|
||||
|
||||
"""
|
||||
pass
|
||||
|
||||
|
||||
class InputMediaAnimation(InputMedia):
|
||||
"""Represents an animation file (GIF or H.264/MPEG-4 AVC video without sound) to be sent.
|
||||
|
||||
Attributes:
|
||||
type (:obj:`str`): ``animation``.
|
||||
media (:obj:`str`): File to send. Pass a file_id to send a file that exists on the Telegram
|
||||
servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet.
|
||||
Lastly you can pass an existing :class:`telegram.Animation` object to send.
|
||||
thumb (`filelike object`): Optional. Thumbnail of the
|
||||
file sent. The thumbnail should be in JPEG format and less than 200 kB in size.
|
||||
A thumbnail's width and height should not exceed 90. Ignored if the file is not
|
||||
is passed as a string or file_id.
|
||||
caption (:obj:`str`): Optional. Caption of the animation to be sent, 0-200 characters.
|
||||
parse_mode (:obj:`str`): Optional. Send Markdown or HTML, if you want Telegram apps to show
|
||||
bold, italic, fixed-width text or inline URLs in the media caption. See the constants
|
||||
in :class:`telegram.ParseMode` for the available modes.
|
||||
width (:obj:`int`): Optional. Animation width.
|
||||
height (:obj:`int`): Optional. Animation height.
|
||||
duration (:obj:`int`): Optional. Animation duration.
|
||||
|
||||
|
||||
Args:
|
||||
media (:obj:`str`): File to send. Pass a file_id to send a file that exists on the Telegram
|
||||
servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet.
|
||||
Lastly you can pass an existing :class:`telegram.Animation` object to send.
|
||||
thumb (`filelike object`, optional): Thumbnail of the
|
||||
file sent. The thumbnail should be in JPEG format and less than 200 kB in size.
|
||||
A thumbnail's width and height should not exceed 90. Ignored if the file is not
|
||||
is passed as a string or file_id.
|
||||
caption (:obj:`str`, optional): Caption of the animation to be sent, 0-200 characters.
|
||||
parse_mode (:obj:`str`, optional): Send Markdown or HTML, if you want Telegram apps to show
|
||||
bold, italic, fixed-width text or inline URLs in the media caption. See the constants
|
||||
in :class:`telegram.ParseMode` for the available modes.
|
||||
width (:obj:`int`, optional): Animation width.
|
||||
height (:obj:`int`, optional): Animation height.
|
||||
duration (:obj:`int`, optional): Animation duration.
|
||||
|
||||
Note:
|
||||
When using a :class:`telegram.Animation` for the :attr:`media` attribute. It will take the
|
||||
width, height and duration from that video, unless otherwise specified with the optional
|
||||
arguments.
|
||||
"""
|
||||
|
||||
def __init__(self, media, thumb=None, caption=None, parse_mode=None, width=None, height=None,
|
||||
duration=None):
|
||||
self.type = 'animation'
|
||||
|
||||
if isinstance(media, Animation):
|
||||
self.media = media.file_id
|
||||
self.width = media.width
|
||||
self.height = media.height
|
||||
self.duration = media.duration
|
||||
elif InputFile.is_file(media):
|
||||
self.media = InputFile(media, attach=True)
|
||||
else:
|
||||
self.media = media
|
||||
|
||||
if thumb:
|
||||
self.thumb = thumb
|
||||
if InputFile.is_file(self.thumb):
|
||||
self.thumb = InputFile(self.thumb, attach=True)
|
||||
|
||||
if caption:
|
||||
self.caption = caption
|
||||
if parse_mode:
|
||||
self.parse_mode = parse_mode
|
||||
if width:
|
||||
self.width = width
|
||||
if height:
|
||||
self.height = height
|
||||
if duration:
|
||||
self.duration = duration
|
||||
|
||||
|
||||
class InputMediaPhoto(InputMedia):
|
||||
"""Represents a photo to be sent.
|
||||
|
||||
Attributes:
|
||||
type (:obj:`str`): ``photo``.
|
||||
media (:obj:`str`): File to send. Pass a file_id to send a file that exists on the
|
||||
Telegram servers (recommended), pass an HTTP URL for Telegram to get a file from the
|
||||
Internet. Lastly you can pass an existing :class:`telegram.PhotoSize` object to send.
|
||||
caption (:obj:`str`): Optional. Caption of the photo to be sent, 0-200 characters.
|
||||
parse_mode (:obj:`str`): Optional. Send Markdown or HTML, if you want Telegram apps to show
|
||||
bold, italic, fixed-width text or inline URLs in the media caption. See the constants
|
||||
in :class:`telegram.ParseMode` for the available modes.
|
||||
|
||||
Args:
|
||||
media (:obj:`str`): File to send. Pass a file_id to send a file that exists on the
|
||||
Telegram servers (recommended), pass an HTTP URL for Telegram to get a file from the
|
||||
Internet. Lastly you can pass an existing :class:`telegram.PhotoSize` object to send.
|
||||
caption (:obj:`str`, optional ): Caption of the photo to be sent, 0-200 characters.
|
||||
parse_mode (:obj:`str`, optional): Send Markdown or HTML, if you want Telegram apps to show
|
||||
bold, italic, fixed-width text or inline URLs in the media caption. See the constants
|
||||
in :class:`telegram.ParseMode` for the available modes.
|
||||
"""
|
||||
|
||||
def __init__(self, media, caption=None, parse_mode=None):
|
||||
self.type = 'photo'
|
||||
|
||||
if isinstance(media, PhotoSize):
|
||||
self.media = media.file_id
|
||||
elif InputFile.is_file(media):
|
||||
self.media = InputFile(media, attach=True)
|
||||
else:
|
||||
self.media = media
|
||||
|
||||
if caption:
|
||||
self.caption = caption
|
||||
if parse_mode:
|
||||
self.parse_mode = parse_mode
|
||||
|
||||
|
||||
class InputMediaVideo(InputMedia):
|
||||
"""Represents a video to be sent.
|
||||
|
||||
Attributes:
|
||||
type (:obj:`str`): ``video``.
|
||||
media (:obj:`str`): File to send. Pass a file_id to send a file that exists on the Telegram
|
||||
servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet.
|
||||
Lastly you can pass an existing :class:`telegram.Video` object to send.
|
||||
caption (:obj:`str`): Optional. Caption of the video to be sent, 0-200 characters.
|
||||
parse_mode (:obj:`str`): Optional. Send Markdown or HTML, if you want Telegram apps to show
|
||||
bold, italic, fixed-width text or inline URLs in the media caption. See the constants
|
||||
in :class:`telegram.ParseMode` for the available modes.
|
||||
width (:obj:`int`): Optional. Video width.
|
||||
height (:obj:`int`): Optional. Video height.
|
||||
duration (:obj:`int`): Optional. Video duration.
|
||||
supports_streaming (:obj:`bool`): Optional. Pass True, if the uploaded video is suitable
|
||||
for streaming.
|
||||
thumb (`filelike object`): Optional. Thumbnail of the
|
||||
file sent. The thumbnail should be in JPEG format and less than 200 kB in size.
|
||||
A thumbnail's width and height should not exceed 90. Ignored if the file is not
|
||||
is passed as a string or file_id.
|
||||
|
||||
Args:
|
||||
media (:obj:`str`): File to send. Pass a file_id to send a file that exists on the Telegram
|
||||
servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet.
|
||||
Lastly you can pass an existing :class:`telegram.Video` object to send.
|
||||
caption (:obj:`str`, optional): Caption of the video to be sent, 0-200 characters.
|
||||
parse_mode (:obj:`str`, optional): Send Markdown or HTML, if you want Telegram apps to show
|
||||
bold, italic, fixed-width text or inline URLs in the media caption. See the constants
|
||||
in :class:`telegram.ParseMode` for the available modes.
|
||||
width (:obj:`int`, optional): Video width.
|
||||
height (:obj:`int`, optional): Video height.
|
||||
duration (:obj:`int`, optional): Video duration.
|
||||
supports_streaming (:obj:`bool`, optional): Pass True, if the uploaded video is suitable
|
||||
for streaming.
|
||||
thumb (`filelike object`, optional): Thumbnail of the
|
||||
file sent. The thumbnail should be in JPEG format and less than 200 kB in size.
|
||||
A thumbnail's width and height should not exceed 90. Ignored if the file is not
|
||||
is passed as a string or file_id.
|
||||
|
||||
Note:
|
||||
When using a :class:`telegram.Video` for the :attr:`media` attribute. It will take the
|
||||
width, height and duration from that video, unless otherwise specified with the optional
|
||||
arguments.
|
||||
"""
|
||||
|
||||
def __init__(self, media, caption=None, width=None, height=None, duration=None,
|
||||
supports_streaming=None, parse_mode=None, thumb=None):
|
||||
self.type = 'video'
|
||||
|
||||
if isinstance(media, Video):
|
||||
self.media = media.file_id
|
||||
self.width = media.width
|
||||
self.height = media.height
|
||||
self.duration = media.duration
|
||||
elif InputFile.is_file(media):
|
||||
self.media = InputFile(media, attach=True)
|
||||
else:
|
||||
self.media = media
|
||||
|
||||
if thumb:
|
||||
self.thumb = thumb
|
||||
if InputFile.is_file(self.thumb):
|
||||
self.thumb = InputFile(self.thumb, attach=True)
|
||||
|
||||
if caption:
|
||||
self.caption = caption
|
||||
if parse_mode:
|
||||
self.parse_mode = parse_mode
|
||||
if width:
|
||||
self.width = width
|
||||
if height:
|
||||
self.height = height
|
||||
if duration:
|
||||
self.duration = duration
|
||||
if supports_streaming:
|
||||
self.supports_streaming = supports_streaming
|
||||
|
||||
|
||||
class InputMediaAudio(InputMedia):
|
||||
"""Represents an audio file to be treated as music to be sent.
|
||||
|
||||
Attributes:
|
||||
type (:obj:`str`): ``audio``.
|
||||
media (:obj:`str`): File to send. Pass a file_id to send a file that exists on the Telegram
|
||||
servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet.
|
||||
Lastly you can pass an existing :class:`telegram.Audio` object to send.
|
||||
caption (:obj:`str`): Optional. Caption of the audio to be sent, 0-200 characters.
|
||||
parse_mode (:obj:`str`): Optional. Send Markdown or HTML, if you want Telegram apps to show
|
||||
bold, italic, fixed-width text or inline URLs in the media caption. See the constants
|
||||
in :class:`telegram.ParseMode` for the available modes.
|
||||
duration (:obj:`int`): Duration of the audio in seconds.
|
||||
performer (:obj:`str`): Optional. Performer of the audio as defined by sender or by audio
|
||||
tags.
|
||||
title (:obj:`str`): Optional. Title of the audio as defined by sender or by audio tags.
|
||||
thumb (`filelike object`): Optional. Thumbnail of the
|
||||
file sent. The thumbnail should be in JPEG format and less than 200 kB in size.
|
||||
A thumbnail's width and height should not exceed 90. Ignored if the file is not
|
||||
is passed as a string or file_id.
|
||||
|
||||
Args:
|
||||
media (:obj:`str`): File to send. Pass a file_id to send a file that exists on the Telegram
|
||||
servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet.
|
||||
Lastly you can pass an existing :class:`telegram.Document` object to send.
|
||||
caption (:obj:`str`, optional): Caption of the audio to be sent, 0-200 characters.
|
||||
parse_mode (:obj:`str`, optional): Send Markdown or HTML, if you want Telegram apps to show
|
||||
bold, italic, fixed-width text or inline URLs in the media caption. See the constants
|
||||
in :class:`telegram.ParseMode` for the available modes.
|
||||
duration (:obj:`int`): Duration of the audio in seconds as defined by sender.
|
||||
performer (:obj:`str`, optional): Performer of the audio as defined by sender or by audio
|
||||
tags.
|
||||
title (:obj:`str`, optional): Title of the audio as defined by sender or by audio tags.
|
||||
thumb (`filelike object`, optional): Thumbnail of the
|
||||
file sent. The thumbnail should be in JPEG format and less than 200 kB in size.
|
||||
A thumbnail's width and height should not exceed 90. Ignored if the file is not
|
||||
is passed as a string or file_id.
|
||||
|
||||
Note:
|
||||
When using a :class:`telegram.Audio` for the :attr:`media` attribute. It will take the
|
||||
duration, performer and title from that video, unless otherwise specified with the
|
||||
optional arguments.
|
||||
"""
|
||||
|
||||
def __init__(self, media, thumb=None, caption=None, parse_mode=None,
|
||||
duration=None, performer=None, title=None):
|
||||
self.type = 'audio'
|
||||
|
||||
if isinstance(media, Audio):
|
||||
self.media = media.file_id
|
||||
self.duration = media.duration
|
||||
self.performer = media.performer
|
||||
self.title = media.title
|
||||
elif InputFile.is_file(media):
|
||||
self.media = InputFile(media, attach=True)
|
||||
else:
|
||||
self.media = media
|
||||
|
||||
if thumb:
|
||||
self.thumb = thumb
|
||||
if InputFile.is_file(self.thumb):
|
||||
self.thumb = InputFile(self.thumb, attach=True)
|
||||
|
||||
if caption:
|
||||
self.caption = caption
|
||||
if parse_mode:
|
||||
self.parse_mode = parse_mode
|
||||
if duration:
|
||||
self.duration = duration
|
||||
if performer:
|
||||
self.performer = performer
|
||||
if title:
|
||||
self.title = title
|
||||
|
||||
|
||||
class InputMediaDocument(InputMedia):
|
||||
"""Represents a general file to be sent.
|
||||
|
||||
Attributes:
|
||||
type (:obj:`str`): ``document``.
|
||||
media (:obj:`str`): File to send. Pass a file_id to send a file that exists on the Telegram
|
||||
servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet.
|
||||
Lastly you can pass an existing :class:`telegram.Document` object to send.
|
||||
caption (:obj:`str`): Optional. Caption of the document to be sent, 0-200 characters.
|
||||
parse_mode (:obj:`str`): Optional. Send Markdown or HTML, if you want Telegram apps to show
|
||||
bold, italic, fixed-width text or inline URLs in the media caption. See the constants
|
||||
in :class:`telegram.ParseMode` for the available modes.
|
||||
thumb (`filelike object`): Optional. Thumbnail of the
|
||||
file sent. The thumbnail should be in JPEG format and less than 200 kB in size.
|
||||
A thumbnail's width and height should not exceed 90. Ignored if the file is not
|
||||
is passed as a string or file_id.
|
||||
|
||||
Args:
|
||||
media (:obj:`str`): File to send. Pass a file_id to send a file that exists on the Telegram
|
||||
servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet.
|
||||
Lastly you can pass an existing :class:`telegram.Document` object to send.
|
||||
caption (:obj:`str`, optional): Caption of the document to be sent, 0-200 characters.
|
||||
parse_mode (:obj:`str`, optional): Send Markdown or HTML, if you want Telegram apps to show
|
||||
bold, italic, fixed-width text or inline URLs in the media caption. See the constants
|
||||
in :class:`telegram.ParseMode` for the available modes.
|
||||
thumb (`filelike object`, optional): Thumbnail of the
|
||||
file sent. The thumbnail should be in JPEG format and less than 200 kB in size.
|
||||
A thumbnail's width and height should not exceed 90. Ignored if the file is not
|
||||
is passed as a string or file_id.
|
||||
"""
|
||||
|
||||
def __init__(self, media, thumb=None, caption=None, parse_mode=None):
|
||||
self.type = 'document'
|
||||
|
||||
if isinstance(media, Document):
|
||||
self.media = media.file_id
|
||||
elif InputFile.is_file(media):
|
||||
self.media = InputFile(media, attach=True)
|
||||
else:
|
||||
self.media = media
|
||||
|
||||
if thumb:
|
||||
self.thumb = thumb
|
||||
if InputFile.is_file(self.thumb):
|
||||
self.thumb = InputFile(self.thumb, attach=True)
|
||||
|
||||
if caption:
|
||||
self.caption = caption
|
||||
if parse_mode:
|
||||
self.parse_mode = parse_mode
|
||||
|
||||
@@ -1,65 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
#
|
||||
# A library that provides a Python interface to the Telegram Bot API
|
||||
# Copyright (C) 2015-2018
|
||||
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Lesser Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Lesser Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Lesser Public License
|
||||
# along with this program. If not, see [http://www.gnu.org/licenses/].
|
||||
"""This module contains an object that represents a Telegram InputMediaPhoto."""
|
||||
from telegram import InputMedia, PhotoSize
|
||||
|
||||
|
||||
class InputMediaPhoto(InputMedia):
|
||||
"""Represents a photo to be sent.
|
||||
|
||||
Attributes:
|
||||
type (:obj:`str`): ``photo``.
|
||||
media (:obj:`str`): File to send. Pass a file_id to send a file that exists on the
|
||||
Telegram servers (recommended), pass an HTTP URL for Telegram to get a file from the
|
||||
Internet. Lastly you can pass an existing :class:`telegram.PhotoSize` object to send.
|
||||
caption (:obj:`str`): Optional. Caption of the photo to be sent, 0-200 characters.
|
||||
parse_mode (:obj:`str`): Optional. Send Markdown or HTML, if you want Telegram apps to show
|
||||
bold, italic, fixed-width text or inline URLs in the media caption.. See the constants
|
||||
in :class:`telegram.ParseMode` for the available modes.
|
||||
|
||||
Args:
|
||||
media (:obj:`str`): File to send. Pass a file_id to send a file that exists on the
|
||||
Telegram servers (recommended), pass an HTTP URL for Telegram to get a file from the
|
||||
Internet. Lastly you can pass an existing :class:`telegram.PhotoSize` object to send.
|
||||
caption (:obj:`str`, optional ): Caption of the photo to be sent, 0-200 characters.
|
||||
parse_mode (:obj:`str`, optional): Send Markdown or HTML, if you want Telegram apps to show
|
||||
bold, italic, fixed-width text or inline URLs in the media caption.. See the constants
|
||||
in :class:`telegram.ParseMode` for the available modes.
|
||||
|
||||
Note:
|
||||
At the moment using a new file is not yet supported.
|
||||
"""
|
||||
|
||||
# TODO: Make InputMediaPhoto, InputMediaVideo and send_media_group work with new files
|
||||
|
||||
def __init__(self, media, caption=None, parse_mode=None):
|
||||
self.type = 'photo'
|
||||
|
||||
if isinstance(media, PhotoSize):
|
||||
self.media = media.file_id
|
||||
elif hasattr(media, 'read'):
|
||||
raise ValueError(
|
||||
'Sending files is not supported (yet). Use file_id, url or PhotoSize')
|
||||
else:
|
||||
self.media = media
|
||||
|
||||
if caption:
|
||||
self.caption = caption
|
||||
if parse_mode:
|
||||
self.parse_mode = parse_mode
|
||||
@@ -1,89 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
#
|
||||
# A library that provides a Python interface to the Telegram Bot API
|
||||
# Copyright (C) 2015-2018
|
||||
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Lesser Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Lesser Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Lesser Public License
|
||||
# along with this program. If not, see [http://www.gnu.org/licenses/].
|
||||
"""This module contains an object that represents a Telegram InputMediaPhoto."""
|
||||
from telegram import InputMedia, Video
|
||||
|
||||
|
||||
class InputMediaVideo(InputMedia):
|
||||
"""Represents a video to be sent.
|
||||
|
||||
Attributes:
|
||||
type (:obj:`str`): ``video``.
|
||||
media (:obj:`str`): File to send. Pass a file_id to send a file that exists on the Telegram
|
||||
servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet.
|
||||
Lastly you can pass an existing :class:`telegram.Video` object to send.
|
||||
caption (:obj:`str`): Optional. Caption of the video to be sent, 0-200 characters.
|
||||
parse_mode (:obj:`str`): Optional. Send Markdown or HTML, if you want Telegram apps to show
|
||||
bold, italic, fixed-width text or inline URLs in the media caption.. See the constants
|
||||
in :class:`telegram.ParseMode` for the available modes.
|
||||
width (:obj:`int`): Optional. Video width.
|
||||
height (:obj:`int`): Optional. Video height.
|
||||
duration (:obj:`int`): Optional. Video duration.
|
||||
supports_streaming (:obj:`bool`): Optional. Pass True, if the uploaded video is suitable
|
||||
for streaming.
|
||||
|
||||
Args:
|
||||
media (:obj:`str`): File to send. Pass a file_id to send a file that exists on the Telegram
|
||||
servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet.
|
||||
Lastly you can pass an existing :class:`telegram.Video` object to send.
|
||||
caption (:obj:`str`, optional): Caption of the video to be sent, 0-200 characters.
|
||||
parse_mode (:obj:`str`, optional): Send Markdown or HTML, if you want Telegram apps to show
|
||||
bold, italic, fixed-width text or inline URLs in the media caption.. See the constants
|
||||
in :class:`telegram.ParseMode` for the available modes.
|
||||
width (:obj:`int`, optional): Video width.
|
||||
height (:obj:`int`, optional): Video height.
|
||||
duration (:obj:`int`, optional): Video duration.
|
||||
supports_streaming (:obj:`bool`, optional): Pass True, if the uploaded video is suitable
|
||||
for streaming.
|
||||
|
||||
Note:
|
||||
When using a :class:`telegram.Video` for the :attr:`media` attribute. It will take the
|
||||
width, height and duration from that video, unless otherwise specified with the optional
|
||||
arguments.
|
||||
At the moment using a new file is not yet supported.
|
||||
"""
|
||||
|
||||
# TODO: Make InputMediaPhoto, InputMediaVideo and send_media_group work with new files
|
||||
|
||||
def __init__(self, media, caption=None, width=None, height=None, duration=None,
|
||||
supports_streaming=None, parse_mode=None):
|
||||
self.type = 'video'
|
||||
|
||||
if isinstance(media, Video):
|
||||
self.media = media.file_id
|
||||
self.width = media.width
|
||||
self.height = media.height
|
||||
self.duration = media.duration
|
||||
elif hasattr(media, 'read'):
|
||||
raise ValueError('Sending files is not supported (yet). Use file_id, url or Video')
|
||||
else:
|
||||
self.media = media
|
||||
|
||||
if caption:
|
||||
self.caption = caption
|
||||
if parse_mode:
|
||||
self.parse_mode = parse_mode
|
||||
if width:
|
||||
self.width = width
|
||||
if height:
|
||||
self.height = height
|
||||
if duration:
|
||||
self.duration = duration
|
||||
if supports_streaming:
|
||||
self.supports_streaming = supports_streaming
|
||||
@@ -29,23 +29,29 @@ class Venue(TelegramObject):
|
||||
title (:obj:`str`): Name of the venue.
|
||||
address (:obj:`str`): Address of the venue.
|
||||
foursquare_id (:obj:`str`): Optional. Foursquare identifier of the venue.
|
||||
foursquare_type (:obj:`str`): Optional. Foursquare type of the venue. (For example,
|
||||
"arts_entertainment/default", "arts_entertainment/aquarium" or "food/icecream".)
|
||||
|
||||
Args:
|
||||
location (:class:`telegram.Location`): Venue location.
|
||||
title (:obj:`str`): Name of the venue.
|
||||
address (:obj:`str`): Address of the venue.
|
||||
foursquare_id (:obj:`str`, optional): Foursquare identifier of the venue.
|
||||
foursquare_type (:obj:`str`, optional): Foursquare type of the venue. (For example,
|
||||
"arts_entertainment/default", "arts_entertainment/aquarium" or "food/icecream".)
|
||||
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
|
||||
|
||||
"""
|
||||
|
||||
def __init__(self, location, title, address, foursquare_id=None, **kwargs):
|
||||
def __init__(self, location, title, address, foursquare_id=None, foursquare_type=None,
|
||||
**kwargs):
|
||||
# Required
|
||||
self.location = location
|
||||
self.title = title
|
||||
self.address = address
|
||||
# Optionals
|
||||
self.foursquare_id = foursquare_id
|
||||
self.foursquare_type = foursquare_type
|
||||
|
||||
self._id_attrs = (self.location, self.title)
|
||||
|
||||
|
||||
@@ -36,7 +36,7 @@ class InlineQueryResultAudio(InlineQueryResult):
|
||||
audio_duration (:obj:`str`): Optional. Performer.
|
||||
caption (:obj:`str`): Optional. Audio duration in seconds.
|
||||
parse_mode (:obj:`str`): Optional. Send Markdown or HTML, if you want Telegram apps to show
|
||||
bold, italic, fixed-width text or inline URLs in the media caption.. See the constants
|
||||
bold, italic, fixed-width text or inline URLs in the media caption. See the constants
|
||||
in :class:`telegram.ParseMode` for the available modes.
|
||||
reply_markup (:class:`telegram.InlineKeyboardMarkup`): Optional. Inline keyboard attached
|
||||
to the message.
|
||||
@@ -51,7 +51,7 @@ class InlineQueryResultAudio(InlineQueryResult):
|
||||
audio_duration (:obj:`str`, optional): Performer.
|
||||
caption (:obj:`str`, optional): Audio duration in seconds.
|
||||
parse_mode (:obj:`str`, optional): Send Markdown or HTML, if you want Telegram apps to show
|
||||
bold, italic, fixed-width text or inline URLs in the media caption.. See the constants
|
||||
bold, italic, fixed-width text or inline URLs in the media caption. See the constants
|
||||
in :class:`telegram.ParseMode` for the available modes.
|
||||
reply_markup (:class:`telegram.InlineKeyboardMarkup`, optional): Inline keyboard attached
|
||||
to the message.
|
||||
|
||||
@@ -33,7 +33,7 @@ class InlineQueryResultCachedAudio(InlineQueryResult):
|
||||
audio_file_id (:obj:`str`): A valid file identifier for the audio file.
|
||||
caption (:obj:`str`): Optional. Caption, 0-200 characters
|
||||
parse_mode (:obj:`str`): Optional. Send Markdown or HTML, if you want Telegram apps to show
|
||||
bold, italic, fixed-width text or inline URLs in the media caption.. See the constants
|
||||
bold, italic, fixed-width text or inline URLs in the media caption. See the constants
|
||||
in :class:`telegram.ParseMode` for the available modes.
|
||||
reply_markup (:class:`telegram.InlineKeyboardMarkup`): Optional. Inline keyboard attached
|
||||
to the message.
|
||||
@@ -45,7 +45,7 @@ class InlineQueryResultCachedAudio(InlineQueryResult):
|
||||
audio_file_id (:obj:`str`): A valid file identifier for the audio file.
|
||||
caption (:obj:`str`, optional): Caption, 0-200 characters
|
||||
parse_mode (:obj:`str`, optional): Send Markdown or HTML, if you want Telegram apps to show
|
||||
bold, italic, fixed-width text or inline URLs in the media caption.. See the constants
|
||||
bold, italic, fixed-width text or inline URLs in the media caption. See the constants
|
||||
in :class:`telegram.ParseMode` for the available modes.
|
||||
reply_markup (:class:`telegram.InlineKeyboardMarkup`, optional): Inline keyboard attached
|
||||
to the message.
|
||||
|
||||
@@ -35,7 +35,7 @@ class InlineQueryResultCachedGif(InlineQueryResult):
|
||||
title (:obj:`str`): Optional. Title for the result.
|
||||
caption (:obj:`str`): Optional. Caption, 0-200 characters
|
||||
parse_mode (:obj:`str`): Optional. Send Markdown or HTML, if you want Telegram apps to show
|
||||
bold, italic, fixed-width text or inline URLs in the media caption.. See the constants
|
||||
bold, italic, fixed-width text or inline URLs in the media caption. See the constants
|
||||
in :class:`telegram.ParseMode` for the available modes.
|
||||
reply_markup (:class:`telegram.InlineKeyboardMarkup`): Optional. Inline keyboard attached
|
||||
to the message.
|
||||
@@ -48,7 +48,7 @@ class InlineQueryResultCachedGif(InlineQueryResult):
|
||||
title (:obj:`str`, optional): Title for the result.caption (:obj:`str`, optional):
|
||||
caption (:obj:`str`, optional): Caption, 0-200 characters
|
||||
parse_mode (:obj:`str`, optional): Send Markdown or HTML, if you want Telegram apps to show
|
||||
bold, italic, fixed-width text or inline URLs in the media caption.. See the constants
|
||||
bold, italic, fixed-width text or inline URLs in the media caption. See the constants
|
||||
in :class:`telegram.ParseMode` for the available modes.
|
||||
reply_markup (:class:`telegram.InlineKeyboardMarkup`, optional): Inline keyboard attached
|
||||
to the message.
|
||||
|
||||
@@ -35,7 +35,7 @@ class InlineQueryResultCachedMpeg4Gif(InlineQueryResult):
|
||||
title (:obj:`str`): Optional. Title for the result.
|
||||
caption (:obj:`str`): Optional. Caption, 0-200 characters
|
||||
parse_mode (:obj:`str`): Send Markdown or HTML, if you want Telegram apps to show
|
||||
bold, italic, fixed-width text or inline URLs in the media caption.. See the constants
|
||||
bold, italic, fixed-width text or inline URLs in the media caption. See the constants
|
||||
in :class:`telegram.ParseMode` for the available modes.
|
||||
reply_markup (:class:`telegram.InlineKeyboardMarkup`): Optional. Inline keyboard attached
|
||||
to the message.
|
||||
@@ -48,7 +48,7 @@ class InlineQueryResultCachedMpeg4Gif(InlineQueryResult):
|
||||
title (:obj:`str`, optional): Title for the result.
|
||||
caption (:obj:`str`, optional): Caption, 0-200 characters
|
||||
parse_mode (:obj:`str`, optional): Send Markdown or HTML, if you want Telegram apps to show
|
||||
bold, italic, fixed-width text or inline URLs in the media caption.. See the constants
|
||||
bold, italic, fixed-width text or inline URLs in the media caption. See the constants
|
||||
in :class:`telegram.ParseMode` for the available modes.
|
||||
reply_markup (:class:`telegram.InlineKeyboardMarkup`, optional): Inline keyboard attached
|
||||
to the message.
|
||||
|
||||
@@ -36,7 +36,7 @@ class InlineQueryResultCachedPhoto(InlineQueryResult):
|
||||
description (:obj:`str`): Optional. Short description of the result.
|
||||
caption (:obj:`str`): Optional. Caption, 0-200 characters
|
||||
parse_mode (:obj:`str`): Optional. Send Markdown or HTML, if you want Telegram apps to show
|
||||
bold, italic, fixed-width text or inline URLs in the media caption.. See the constants
|
||||
bold, italic, fixed-width text or inline URLs in the media caption. See the constants
|
||||
in :class:`telegram.ParseMode` for the available modes.
|
||||
reply_markup (:class:`telegram.InlineKeyboardMarkup`): Optional. Inline keyboard attached
|
||||
to the message.
|
||||
@@ -50,7 +50,7 @@ class InlineQueryResultCachedPhoto(InlineQueryResult):
|
||||
description (:obj:`str`, optional): Short description of the result.
|
||||
caption (:obj:`str`, optional): Caption, 0-200 characters
|
||||
parse_mode (:obj:`str`, optional): Send Markdown or HTML, if you want Telegram apps to show
|
||||
bold, italic, fixed-width text or inline URLs in the media caption.. See the constants
|
||||
bold, italic, fixed-width text or inline URLs in the media caption. See the constants
|
||||
in :class:`telegram.ParseMode` for the available modes.
|
||||
reply_markup (:class:`telegram.InlineKeyboardMarkup`, optional): Inline keyboard attached
|
||||
to the message.
|
||||
|
||||
@@ -36,7 +36,7 @@ class InlineQueryResultCachedVideo(InlineQueryResult):
|
||||
description (:obj:`str`): Optional. Short description of the result.
|
||||
caption (:obj:`str`): Optional. Caption, 0-200 characters.
|
||||
parse_mode (:obj:`str`): Optional. Send Markdown or HTML, if you want Telegram apps to show
|
||||
bold, italic, fixed-width text or inline URLs in the media caption.. See the constants
|
||||
bold, italic, fixed-width text or inline URLs in the media caption. See the constants
|
||||
in :class:`telegram.ParseMode` for the available modes.
|
||||
reply_markup (:class:`telegram.InlineKeyboardMarkup`): Optional. Inline keyboard attached
|
||||
to the message.
|
||||
@@ -50,7 +50,7 @@ class InlineQueryResultCachedVideo(InlineQueryResult):
|
||||
description (:obj:`str`, optional): Short description of the result.
|
||||
caption (:obj:`str`, optional): Caption, 0-200 characters.
|
||||
parse_mode (:obj:`str`, optional): Send Markdown or HTML, if you want Telegram apps to show
|
||||
bold, italic, fixed-width text or inline URLs in the media caption.. See the constants
|
||||
bold, italic, fixed-width text or inline URLs in the media caption. See the constants
|
||||
in :class:`telegram.ParseMode` for the available modes.
|
||||
reply_markup (:class:`telegram.InlineKeyboardMarkup`, optional): Inline keyboard attached
|
||||
to the message.
|
||||
|
||||
@@ -34,7 +34,7 @@ class InlineQueryResultCachedVoice(InlineQueryResult):
|
||||
title (:obj:`str`): Voice message title.
|
||||
caption (:obj:`str`): Optional. Caption, 0-200 characters.
|
||||
parse_mode (:obj:`str`): Optional. Send Markdown or HTML, if you want Telegram apps to show
|
||||
bold, italic, fixed-width text or inline URLs in the media caption.. See the constants
|
||||
bold, italic, fixed-width text or inline URLs in the media caption. See the constants
|
||||
in :class:`telegram.ParseMode` for the available modes.
|
||||
reply_markup (:class:`telegram.InlineKeyboardMarkup`): Optional. Inline keyboard attached
|
||||
to the message.
|
||||
@@ -47,7 +47,7 @@ class InlineQueryResultCachedVoice(InlineQueryResult):
|
||||
title (:obj:`str`): Voice message title.
|
||||
caption (:obj:`str`, optional): Caption, 0-200 characters.
|
||||
parse_mode (:obj:`str`, optional): Send Markdown or HTML, if you want Telegram apps to show
|
||||
bold, italic, fixed-width text or inline URLs in the media caption.. See the constants
|
||||
bold, italic, fixed-width text or inline URLs in the media caption. See the constants
|
||||
in :class:`telegram.ParseMode` for the available modes.
|
||||
reply_markup (:class:`telegram.InlineKeyboardMarkup`, optional): Inline keyboard attached
|
||||
to the message.
|
||||
|
||||
@@ -33,6 +33,8 @@ class InlineQueryResultContact(InlineQueryResult):
|
||||
phone_number (:obj:`str`): Contact's phone number.
|
||||
first_name (:obj:`str`): Contact's first name.
|
||||
last_name (:obj:`str`): Optional. Contact's last name.
|
||||
vcard (:obj:`str`): Optional. Additional data about the contact in the form of a vCard,
|
||||
0-2048 bytes.
|
||||
reply_markup (:class:`telegram.InlineKeyboardMarkup`): Optional. Inline keyboard attached
|
||||
to the message.
|
||||
input_message_content (:class:`telegram.InputMessageContent`): Optional. Content of the
|
||||
@@ -46,6 +48,8 @@ class InlineQueryResultContact(InlineQueryResult):
|
||||
phone_number (:obj:`str`): Contact's phone number.
|
||||
first_name (:obj:`str`): Contact's first name.
|
||||
last_name (:obj:`str`, optional): Contact's last name.
|
||||
vcard (:obj:`str`, optional): Additional data about the contact in the form of a vCard,
|
||||
0-2048 bytes.
|
||||
reply_markup (:class:`telegram.InlineKeyboardMarkup`, optional): Inline keyboard attached
|
||||
to the message.
|
||||
input_message_content (:class:`telegram.InputMessageContent`, optional): Content of the
|
||||
@@ -67,6 +71,7 @@ class InlineQueryResultContact(InlineQueryResult):
|
||||
thumb_url=None,
|
||||
thumb_width=None,
|
||||
thumb_height=None,
|
||||
vcard=None,
|
||||
**kwargs):
|
||||
# Required
|
||||
super(InlineQueryResultContact, self).__init__('contact', id)
|
||||
@@ -76,6 +81,8 @@ class InlineQueryResultContact(InlineQueryResult):
|
||||
# Optionals
|
||||
if last_name:
|
||||
self.last_name = last_name
|
||||
if vcard:
|
||||
self.vcard = vcard
|
||||
if reply_markup:
|
||||
self.reply_markup = reply_markup
|
||||
if input_message_content:
|
||||
|
||||
@@ -34,7 +34,7 @@ class InlineQueryResultDocument(InlineQueryResult):
|
||||
title (:obj:`str`): Title for the result.
|
||||
caption (:obj:`str`): Optional. Caption, 0-200 characters
|
||||
parse_mode (:obj:`str`): Optional. Send Markdown or HTML, if you want Telegram apps to show
|
||||
bold, italic, fixed-width text or inline URLs in the media caption.. See the constants
|
||||
bold, italic, fixed-width text or inline URLs in the media caption. See the constants
|
||||
in :class:`telegram.ParseMode` for the available modes.
|
||||
document_url (:obj:`str`): A valid URL for the file.
|
||||
mime_type (:obj:`str`): Mime type of the content of the file, either "application/pdf"
|
||||
@@ -53,7 +53,7 @@ class InlineQueryResultDocument(InlineQueryResult):
|
||||
title (:obj:`str`): Title for the result.
|
||||
caption (:obj:`str`, optional): Caption, 0-200 characters
|
||||
parse_mode (:obj:`str`, optional): Send Markdown or HTML, if you want Telegram apps to show
|
||||
bold, italic, fixed-width text or inline URLs in the media caption.. See the constants
|
||||
bold, italic, fixed-width text or inline URLs in the media caption. See the constants
|
||||
in :class:`telegram.ParseMode` for the available modes.
|
||||
document_url (:obj:`str`): A valid URL for the file.
|
||||
mime_type (:obj:`str`): Mime type of the content of the file, either "application/pdf"
|
||||
|
||||
@@ -38,7 +38,7 @@ class InlineQueryResultGif(InlineQueryResult):
|
||||
title (:obj:`str`): Optional. Title for the result.
|
||||
caption (:obj:`str`): Optional. Caption, 0-200 characters
|
||||
parse_mode (:obj:`str`): Optional. Send Markdown or HTML, if you want Telegram apps to show
|
||||
bold, italic, fixed-width text or inline URLs in the media caption.. See the constants
|
||||
bold, italic, fixed-width text or inline URLs in the media caption. See the constants
|
||||
in :class:`telegram.ParseMode` for the available modes.
|
||||
reply_markup (:class:`telegram.InlineKeyboardMarkup`): Optional. Inline keyboard attached
|
||||
to the message.
|
||||
@@ -55,7 +55,7 @@ class InlineQueryResultGif(InlineQueryResult):
|
||||
title (:obj:`str`, optional): Title for the result.caption (:obj:`str`, optional):
|
||||
caption (:obj:`str`, optional): Caption, 0-200 characters
|
||||
parse_mode (:obj:`str`, optional): Send Markdown or HTML, if you want Telegram apps to show
|
||||
bold, italic, fixed-width text or inline URLs in the media caption.. See the constants
|
||||
bold, italic, fixed-width text or inline URLs in the media caption. See the constants
|
||||
in :class:`telegram.ParseMode` for the available modes.
|
||||
reply_markup (:class:`telegram.InlineKeyboardMarkup`, optional): Inline keyboard attached
|
||||
to the message.
|
||||
|
||||
@@ -39,7 +39,7 @@ class InlineQueryResultMpeg4Gif(InlineQueryResult):
|
||||
title (:obj:`str`): Optional. Title for the result.
|
||||
caption (:obj:`str`): Optional. Caption, 0-200 characters
|
||||
parse_mode (:obj:`str`): Optional. Send Markdown or HTML, if you want Telegram apps to show
|
||||
bold, italic, fixed-width text or inline URLs in the media caption.. See the constants
|
||||
bold, italic, fixed-width text or inline URLs in the media caption. See the constants
|
||||
in :class:`telegram.ParseMode` for the available modes.
|
||||
reply_markup (:class:`telegram.InlineKeyboardMarkup`): Optional. Inline keyboard attached
|
||||
to the message.
|
||||
@@ -56,7 +56,7 @@ class InlineQueryResultMpeg4Gif(InlineQueryResult):
|
||||
title (:obj:`str`, optional): Title for the result.
|
||||
caption (:obj:`str`, optional): Caption, 0-200 characters
|
||||
parse_mode (:obj:`str`, optional): Send Markdown or HTML, if you want Telegram apps to show
|
||||
bold, italic, fixed-width text or inline URLs in the media caption.. See the constants
|
||||
bold, italic, fixed-width text or inline URLs in the media caption. See the constants
|
||||
in :class:`telegram.ParseMode` for the available modes.
|
||||
reply_markup (:class:`telegram.InlineKeyboardMarkup`, optional): Inline keyboard attached
|
||||
to the message.
|
||||
|
||||
@@ -39,7 +39,7 @@ class InlineQueryResultPhoto(InlineQueryResult):
|
||||
description (:obj:`str`): Optional. Short description of the result.
|
||||
caption (:obj:`str`): Optional. Caption, 0-200 characters
|
||||
parse_mode (:obj:`str`): Optional. Send Markdown or HTML, if you want Telegram apps to show
|
||||
bold, italic, fixed-width text or inline URLs in the media caption.. See the constants
|
||||
bold, italic, fixed-width text or inline URLs in the media caption. See the constants
|
||||
in :class:`telegram.ParseMode` for the available modes.
|
||||
reply_markup (:class:`telegram.InlineKeyboardMarkup`): Optional. Inline keyboard attached
|
||||
to the message.
|
||||
@@ -57,7 +57,7 @@ class InlineQueryResultPhoto(InlineQueryResult):
|
||||
description (:obj:`str`, optional): Short description of the result.
|
||||
caption (:obj:`str`, optional): Caption, 0-200 characters
|
||||
parse_mode (:obj:`str`, optional): Send Markdown or HTML, if you want Telegram apps to show
|
||||
bold, italic, fixed-width text or inline URLs in the media caption.. See the constants
|
||||
bold, italic, fixed-width text or inline URLs in the media caption. See the constants
|
||||
in :class:`telegram.ParseMode` for the available modes.
|
||||
reply_markup (:class:`telegram.InlineKeyboardMarkup`, optional): Inline keyboard attached
|
||||
to the message.
|
||||
|
||||
@@ -35,6 +35,9 @@ class InlineQueryResultVenue(InlineQueryResult):
|
||||
title (:obj:`str`): Title of the venue.
|
||||
address (:obj:`str`): Address of the venue.
|
||||
foursquare_id (:obj:`str`): Optional. Foursquare identifier of the venue if known.
|
||||
foursquare_type (:obj:`str`): Optional. Foursquare type of the venue, if known.
|
||||
(For example, "arts_entertainment/default", "arts_entertainment/aquarium" or
|
||||
"food/icecream".)
|
||||
reply_markup (:class:`telegram.InlineKeyboardMarkup`): Optional. Inline keyboard attached
|
||||
to the message.
|
||||
input_message_content (:class:`telegram.InputMessageContent`): Optional. Content of the
|
||||
@@ -50,6 +53,9 @@ class InlineQueryResultVenue(InlineQueryResult):
|
||||
title (:obj:`str`): Title of the venue.
|
||||
address (:obj:`str`): Address of the venue.
|
||||
foursquare_id (:obj:`str`, optional): Foursquare identifier of the venue if known.
|
||||
foursquare_type (:obj:`str`, optional): Foursquare type of the venue, if known.
|
||||
(For example, "arts_entertainment/default", "arts_entertainment/aquarium" or
|
||||
"food/icecream".)
|
||||
reply_markup (:class:`telegram.InlineKeyboardMarkup`, optional): Inline keyboard attached
|
||||
to the message.
|
||||
input_message_content (:class:`telegram.InputMessageContent`, optional): Content of the
|
||||
@@ -68,6 +74,7 @@ class InlineQueryResultVenue(InlineQueryResult):
|
||||
title,
|
||||
address,
|
||||
foursquare_id=None,
|
||||
foursquare_type=None,
|
||||
reply_markup=None,
|
||||
input_message_content=None,
|
||||
thumb_url=None,
|
||||
@@ -85,6 +92,8 @@ class InlineQueryResultVenue(InlineQueryResult):
|
||||
# Optional
|
||||
if foursquare_id:
|
||||
self.foursquare_id = foursquare_id
|
||||
if foursquare_type:
|
||||
self.foursquare_type = foursquare_type
|
||||
if reply_markup:
|
||||
self.reply_markup = reply_markup
|
||||
if input_message_content:
|
||||
|
||||
@@ -37,7 +37,7 @@ class InlineQueryResultVideo(InlineQueryResult):
|
||||
title (:obj:`str`): Title for the result.
|
||||
caption (:obj:`str`): Optional. Caption, 0-200 characters
|
||||
parse_mode (:obj:`str`): Optional. Send Markdown or HTML, if you want Telegram apps to show
|
||||
bold, italic, fixed-width text or inline URLs in the media caption.. See the constants
|
||||
bold, italic, fixed-width text or inline URLs in the media caption. See the constants
|
||||
in :class:`telegram.ParseMode` for the available modes.
|
||||
video_width (:obj:`int`): Optional. Video width.
|
||||
video_height (:obj:`int`): Optional. Video height.
|
||||
@@ -56,7 +56,7 @@ class InlineQueryResultVideo(InlineQueryResult):
|
||||
title (:obj:`str`): Title for the result.
|
||||
caption (:obj:`str`, optional): Caption, 0-200 characters.
|
||||
parse_mode (:obj:`str`, optional): Send Markdown or HTML, if you want Telegram apps to show
|
||||
bold, italic, fixed-width text or inline URLs in the media caption.. See the constants
|
||||
bold, italic, fixed-width text or inline URLs in the media caption. See the constants
|
||||
in :class:`telegram.ParseMode` for the available modes.
|
||||
video_width (:obj:`int`, optional): Video width.
|
||||
video_height (:obj:`int`, optional): Video height.
|
||||
|
||||
@@ -28,18 +28,23 @@ class InputContactMessageContent(InputMessageContent):
|
||||
phone_number (:obj:`str`): Contact's phone number.
|
||||
first_name (:obj:`str`): Contact's first name.
|
||||
last_name (:obj:`str`): Optional. Contact's last name.
|
||||
vcard (:obj:`str`): Optional. Additional data about the contact in the form of a vCard,
|
||||
0-2048 bytes.
|
||||
|
||||
Args:
|
||||
phone_number (:obj:`str`): Contact's phone number.
|
||||
first_name (:obj:`str`): Contact's first name.
|
||||
last_name (:obj:`str`, optional): Contact's last name.
|
||||
vcard (:obj:`str`, optional): Additional data about the contact in the form of a vCard,
|
||||
0-2048 bytes.
|
||||
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
|
||||
|
||||
"""
|
||||
|
||||
def __init__(self, phone_number, first_name, last_name=None, **kwargs):
|
||||
def __init__(self, phone_number, first_name, last_name=None, vcard=None, **kwargs):
|
||||
# Required
|
||||
self.phone_number = phone_number
|
||||
self.first_name = first_name
|
||||
# Optionals
|
||||
self.last_name = last_name
|
||||
self.vcard = vcard
|
||||
|
||||
@@ -30,6 +30,9 @@ class InputVenueMessageContent(InputMessageContent):
|
||||
title (:obj:`str`): Name of the venue.
|
||||
address (:obj:`str`): Address of the venue.
|
||||
foursquare_id (:obj:`str`): Optional. Foursquare identifier of the venue, if known.
|
||||
foursquare_type (:obj:`str`): Optional. Foursquare type of the venue, if known.
|
||||
(For example, "arts_entertainment/default", "arts_entertainment/aquarium" or
|
||||
"food/icecream".)
|
||||
|
||||
Args:
|
||||
latitude (:obj:`float`): Latitude of the location in degrees.
|
||||
@@ -37,11 +40,15 @@ class InputVenueMessageContent(InputMessageContent):
|
||||
title (:obj:`str`): Name of the venue.
|
||||
address (:obj:`str`): Address of the venue.
|
||||
foursquare_id (:obj:`str`, optional): Foursquare identifier of the venue, if known.
|
||||
foursquare_type (:obj:`str`, optional): Foursquare type of the venue, if known.
|
||||
(For example, "arts_entertainment/default", "arts_entertainment/aquarium" or
|
||||
"food/icecream".)
|
||||
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
|
||||
|
||||
"""
|
||||
|
||||
def __init__(self, latitude, longitude, title, address, foursquare_id=None, **kwargs):
|
||||
def __init__(self, latitude, longitude, title, address, foursquare_id=None,
|
||||
foursquare_type=None, **kwargs):
|
||||
# Required
|
||||
self.latitude = latitude
|
||||
self.longitude = longitude
|
||||
@@ -49,3 +56,4 @@ class InputVenueMessageContent(InputMessageContent):
|
||||
self.address = address
|
||||
# Optionals
|
||||
self.foursquare_id = foursquare_id
|
||||
self.foursquare_type = foursquare_type
|
||||
|
||||
+74
-7
@@ -21,9 +21,9 @@
|
||||
import sys
|
||||
from html import escape
|
||||
|
||||
from telegram import (Audio, Contact, Document, Chat, Location, PhotoSize, Sticker, TelegramObject,
|
||||
User, Video, Voice, Venue, MessageEntity, Game, Invoice, SuccessfulPayment,
|
||||
VideoNote)
|
||||
from telegram import (Animation, Audio, Contact, Document, Chat, Location, PhotoSize, Sticker,
|
||||
TelegramObject, User, Video, Voice, Venue, MessageEntity, Game, Invoice,
|
||||
SuccessfulPayment, VideoNote, PassportData)
|
||||
from telegram import ParseMode
|
||||
from telegram.utils.helpers import escape_markdown, to_timestamp, from_timestamp
|
||||
|
||||
@@ -62,6 +62,9 @@ class Message(TelegramObject):
|
||||
to use properly.
|
||||
audio (:class:`telegram.Audio`): Optional. Information about the file.
|
||||
document (:class:`telegram.Document`): Optional. Information about the file.
|
||||
animation (:class:`telegram.Animation`) Optional. Information about the file.
|
||||
For backward compatibility, when this field is set, the document field will also be
|
||||
set.
|
||||
game (:class:`telegram.Game`): Optional. Information about the game.
|
||||
photo (List[:class:`telegram.PhotoSize`]): Optional. Available sizes of the photo.
|
||||
sticker (:class:`telegram.Sticker`): Optional. Information about the sticker.
|
||||
@@ -97,6 +100,7 @@ class Message(TelegramObject):
|
||||
forwarded from channels.
|
||||
author_signature (:obj:`str`): Optional. Signature of the post author for messages
|
||||
in channels.
|
||||
passport_data (:class:`telegram.PassportData`): Optional. Telegram Passport data
|
||||
bot (:class:`telegram.Bot`): Optional. The Bot to use for instance methods.
|
||||
|
||||
Args:
|
||||
@@ -134,6 +138,9 @@ class Message(TelegramObject):
|
||||
about the file.
|
||||
document (:class:`telegram.Document`, optional): Message is a general file, information
|
||||
about the file.
|
||||
animation (:class:`telegram.Animation`, optional): Message is an animation, information
|
||||
about the animation. For backward compatibility, when this field is set, the document
|
||||
field will also be set.
|
||||
game (:class:`telegram.Game`, optional): Message is a game, information about the game.
|
||||
photo (List[:class:`telegram.PhotoSize`], optional): Message is a photo, available
|
||||
sizes of the photo.
|
||||
@@ -192,17 +199,18 @@ class Message(TelegramObject):
|
||||
forwarded from channels.
|
||||
author_signature (:obj:`str`, optional): Signature of the post author for messages
|
||||
in channels.
|
||||
passport_data (:class:`telegram.PassportData`, optional): Telegram Passport data
|
||||
"""
|
||||
|
||||
_effective_attachment = _UNDEFINED
|
||||
|
||||
ATTACHMENT_TYPES = ['audio', 'game', 'document', 'photo', 'sticker', 'video', 'voice',
|
||||
'video_note', 'contact', 'location', 'venue', 'invoice',
|
||||
ATTACHMENT_TYPES = ['audio', 'game', 'animation', 'document', 'photo', 'sticker', 'video',
|
||||
'voice', 'video_note', 'contact', 'location', 'venue', 'invoice',
|
||||
'successful_payment']
|
||||
MESSAGE_TYPES = ['text', 'new_chat_members', 'new_chat_title', 'new_chat_photo',
|
||||
'delete_chat_photo', 'group_chat_created', 'supergroup_chat_created',
|
||||
'channel_chat_created', 'migrate_to_chat_id', 'migrate_from_chat_id',
|
||||
'pinned_message'] + ATTACHMENT_TYPES
|
||||
'pinned_message', 'passport_data'] + ATTACHMENT_TYPES
|
||||
|
||||
def __init__(self,
|
||||
message_id,
|
||||
@@ -247,6 +255,8 @@ class Message(TelegramObject):
|
||||
author_signature=None,
|
||||
media_group_id=None,
|
||||
connected_website=None,
|
||||
animation=None,
|
||||
passport_data=None,
|
||||
bot=None,
|
||||
**kwargs):
|
||||
# Required
|
||||
@@ -293,6 +303,8 @@ class Message(TelegramObject):
|
||||
self.forward_signature = forward_signature
|
||||
self.author_signature = author_signature
|
||||
self.media_group_id = media_group_id
|
||||
self.animation = animation
|
||||
self.passport_data = passport_data
|
||||
|
||||
self.bot = bot
|
||||
|
||||
@@ -303,6 +315,14 @@ class Message(TelegramObject):
|
||||
""":obj:`int`: Shortcut for :attr:`telegram.Chat.id` for :attr:`chat`."""
|
||||
return self.chat.id
|
||||
|
||||
@property
|
||||
def link(self):
|
||||
""":obj:`str`: Convenience property. If the chat of the message is a supergroup or a
|
||||
channel and has a :attr:`Chat.username`, returns a t.me link of the message."""
|
||||
if self.chat.type in (Chat.SUPERGROUP, Chat.CHANNEL) and self.chat.username:
|
||||
return "https://t.me/{}/{}".format(self.chat.username, self.message_id)
|
||||
return None
|
||||
|
||||
@classmethod
|
||||
def de_json(cls, data, bot):
|
||||
if not data:
|
||||
@@ -322,6 +342,7 @@ class Message(TelegramObject):
|
||||
data['edit_date'] = from_timestamp(data.get('edit_date'))
|
||||
data['audio'] = Audio.de_json(data.get('audio'), bot)
|
||||
data['document'] = Document.de_json(data.get('document'), bot)
|
||||
data['animation'] = Animation.de_json(data.get('animation'), bot)
|
||||
data['game'] = Game.de_json(data.get('game'), bot)
|
||||
data['photo'] = PhotoSize.de_list(data.get('photo'), bot)
|
||||
data['sticker'] = Sticker.de_json(data.get('sticker'), bot)
|
||||
@@ -337,6 +358,7 @@ class Message(TelegramObject):
|
||||
data['pinned_message'] = Message.de_json(data.get('pinned_message'), bot)
|
||||
data['invoice'] = Invoice.de_json(data.get('invoice'), bot)
|
||||
data['successful_payment'] = SuccessfulPayment.de_json(data.get('successful_payment'), bot)
|
||||
data['passport_data'] = PassportData.de_json(data.get('passport_data'), bot)
|
||||
|
||||
return cls(bot=bot, **data)
|
||||
|
||||
@@ -346,6 +368,7 @@ class Message(TelegramObject):
|
||||
:class:`telegram.Audio`
|
||||
or :class:`telegram.Contact`
|
||||
or :class:`telegram.Document`
|
||||
or :class:`telegram.Animation`
|
||||
or :class:`telegram.Game`
|
||||
or :class:`telegram.Invoice`
|
||||
or :class:`telegram.Location`
|
||||
@@ -543,6 +566,23 @@ class Message(TelegramObject):
|
||||
self._quote(kwargs)
|
||||
return self.bot.send_document(self.chat_id, *args, **kwargs)
|
||||
|
||||
def reply_animation(self, *args, **kwargs):
|
||||
"""Shortcut for::
|
||||
|
||||
bot.send_animation(update.message.chat_id, *args, **kwargs)
|
||||
|
||||
Keyword Args:
|
||||
quote (:obj:`bool`, optional): If set to ``True``, the photo is sent as an actual reply
|
||||
to this message. If ``reply_to_message_id`` is passed in ``kwargs``, this parameter
|
||||
will be ignored. Default: ``True`` in group chats and ``False`` in private chats.
|
||||
|
||||
Returns:
|
||||
:class:`telegram.Message`: On success, instance representing the message posted.
|
||||
|
||||
"""
|
||||
self._quote(kwargs)
|
||||
return self.bot.send_animation(self.chat_id, *args, **kwargs)
|
||||
|
||||
def reply_sticker(self, *args, **kwargs):
|
||||
"""Shortcut for::
|
||||
|
||||
@@ -691,7 +731,7 @@ class Message(TelegramObject):
|
||||
Note:
|
||||
You can only edit messages that the bot sent itself,
|
||||
therefore this method can only be used on the
|
||||
return value of the ``bot.send_*`` family of methods..
|
||||
return value of the ``bot.send_*`` family of methods.
|
||||
|
||||
Returns:
|
||||
:class:`telegram.Message`: On success, instance representing the edited message.
|
||||
@@ -720,6 +760,27 @@ class Message(TelegramObject):
|
||||
return self.bot.edit_message_caption(
|
||||
chat_id=self.chat_id, message_id=self.message_id, *args, **kwargs)
|
||||
|
||||
def edit_media(self, media, *args, **kwargs):
|
||||
"""Shortcut for::
|
||||
|
||||
bot.edit_message_media(chat_id=message.chat_id,
|
||||
message_id=message.message_id,
|
||||
*args,
|
||||
**kwargs)
|
||||
|
||||
Note:
|
||||
You can only edit messages that the bot sent itself,
|
||||
therefore this method can only be used on the
|
||||
return value of the ``bot.send_*`` family of methods.
|
||||
|
||||
Returns:
|
||||
:class:`telegram.Message`: On success, instance representing the edited
|
||||
message.
|
||||
|
||||
"""
|
||||
return self.bot.edit_message_media(
|
||||
chat_id=self.chat_id, message_id=self.message_id, media=media, *args, **kwargs)
|
||||
|
||||
def edit_reply_markup(self, *args, **kwargs):
|
||||
"""Shortcut for::
|
||||
|
||||
@@ -868,6 +929,9 @@ class Message(TelegramObject):
|
||||
|
||||
@staticmethod
|
||||
def _parse_html(message_text, entities, urled=False):
|
||||
if message_text is None:
|
||||
return None
|
||||
|
||||
if not sys.maxunicode == 0xffff:
|
||||
message_text = message_text.encode('utf-16-le')
|
||||
|
||||
@@ -962,6 +1026,9 @@ class Message(TelegramObject):
|
||||
|
||||
@staticmethod
|
||||
def _parse_markdown(message_text, entities, urled=False):
|
||||
if message_text is None:
|
||||
return None
|
||||
|
||||
if not sys.maxunicode == 0xffff:
|
||||
message_text = message_text.encode('utf-16-le')
|
||||
|
||||
|
||||
@@ -81,6 +81,10 @@ class MessageEntity(TelegramObject):
|
||||
""":obj:`str`: 'mention'"""
|
||||
HASHTAG = 'hashtag'
|
||||
""":obj:`str`: 'hashtag'"""
|
||||
CASHTAG = 'cashtag'
|
||||
""":obj:`str`: 'cashtag'"""
|
||||
PHONE_NUMBER = 'phone_number'
|
||||
""":obj:`str`: 'phone_number'"""
|
||||
BOT_COMMAND = 'bot_command'
|
||||
""":obj:`str`: 'bot_command'"""
|
||||
URL = 'url'
|
||||
@@ -100,6 +104,7 @@ class MessageEntity(TelegramObject):
|
||||
TEXT_MENTION = 'text_mention'
|
||||
""":obj:`str`: 'text_mention'"""
|
||||
ALL_TYPES = [
|
||||
MENTION, HASHTAG, BOT_COMMAND, URL, EMAIL, BOLD, ITALIC, CODE, PRE, TEXT_LINK, TEXT_MENTION
|
||||
MENTION, HASHTAG, CASHTAG, PHONE_NUMBER, BOT_COMMAND, URL,
|
||||
EMAIL, BOLD, ITALIC, CODE, PRE, TEXT_LINK, TEXT_MENTION
|
||||
]
|
||||
"""List[:obj:`str`]: List of all the types."""
|
||||
|
||||
@@ -0,0 +1,439 @@
|
||||
#!/usr/bin/env python
|
||||
#
|
||||
# A library that provides a Python interface to the Telegram Bot API
|
||||
# Copyright (C) 2015-2018
|
||||
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Lesser Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Lesser Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Lesser Public License
|
||||
# along with this program. If not, see [http://www.gnu.org/licenses/].
|
||||
try:
|
||||
import ujson as json
|
||||
except ImportError:
|
||||
import json
|
||||
from base64 import b64decode
|
||||
|
||||
from cryptography.hazmat.backends import default_backend
|
||||
from cryptography.hazmat.primitives.asymmetric.padding import OAEP, MGF1
|
||||
from cryptography.hazmat.primitives.ciphers import Cipher
|
||||
from cryptography.hazmat.primitives.ciphers.algorithms import AES
|
||||
from cryptography.hazmat.primitives.ciphers.modes import CBC
|
||||
from cryptography.hazmat.primitives.hashes import SHA512, SHA256, Hash, SHA1
|
||||
from future.utils import bord
|
||||
|
||||
from telegram import TelegramObject, TelegramError
|
||||
|
||||
|
||||
class TelegramDecryptionError(TelegramError):
|
||||
"""
|
||||
Something went wrong with decryption.
|
||||
"""
|
||||
|
||||
def __init__(self, message):
|
||||
super(TelegramDecryptionError, self).__init__("TelegramDecryptionError: "
|
||||
"{}".format(message))
|
||||
|
||||
|
||||
def decrypt(secret, hash, data):
|
||||
"""
|
||||
Decrypt per telegram docs at https://core.telegram.org/passport.
|
||||
|
||||
Args:
|
||||
secret (:obj:`str` or :obj:`bytes`): The encryption secret, either as bytes or as a
|
||||
base64 encoded string.
|
||||
hash (:obj:`str` or :obj:`bytes`): The hash, either as bytes or as a
|
||||
base64 encoded string.
|
||||
data (:obj:`str` or :obj:`bytes`): The data to decrypt, either as bytes or as a
|
||||
base64 encoded string.
|
||||
file (:obj:`bool`): Force data to be treated as raw data, instead of trying to
|
||||
b64decode it.
|
||||
|
||||
Raises:
|
||||
:class:`TelegramDecryptionError`: Given hash does not match hash of decrypted data.
|
||||
|
||||
Returns:
|
||||
:obj:`bytes`: The decrypted data as bytes.
|
||||
|
||||
"""
|
||||
# Make a SHA512 hash of secret + update
|
||||
digest = Hash(SHA512(), backend=default_backend())
|
||||
digest.update(secret + hash)
|
||||
secret_hash_hash = digest.finalize()
|
||||
# First 32 chars is our key, next 16 is the initialisation vector
|
||||
key, iv = secret_hash_hash[:32], secret_hash_hash[32:32 + 16]
|
||||
# Init a AES-CBC cipher and decrypt the data
|
||||
cipher = Cipher(AES(key), CBC(iv), backend=default_backend())
|
||||
decryptor = cipher.decryptor()
|
||||
data = decryptor.update(data) + decryptor.finalize()
|
||||
# Calculate SHA256 hash of the decrypted data
|
||||
digest = Hash(SHA256(), backend=default_backend())
|
||||
digest.update(data)
|
||||
data_hash = digest.finalize()
|
||||
# If the newly calculated hash did not match the one telegram gave us
|
||||
if data_hash != hash:
|
||||
# Raise a error that is caught inside telegram.PassportData and transformed into a warning
|
||||
raise TelegramDecryptionError("Hashes are not equal! {} != {}".format(data_hash, hash))
|
||||
# Return data without padding
|
||||
return data[bord(data[0]):]
|
||||
|
||||
|
||||
def decrypt_json(secret, hash, data):
|
||||
"""Decrypts data using secret and hash and then decodes utf-8 string and loads json"""
|
||||
return json.loads(decrypt(secret, hash, data).decode('utf-8'))
|
||||
|
||||
|
||||
class EncryptedCredentials(TelegramObject):
|
||||
"""Contains data required for decrypting and authenticating EncryptedPassportElement. See the
|
||||
Telegram Passport Documentation for a complete description of the data decryption and
|
||||
authentication processes.
|
||||
|
||||
Attributes:
|
||||
data (:class:`telegram.Credentials` or :obj:`str`): Decrypted data with unique user's
|
||||
nonce, data hashes and secrets used for EncryptedPassportElement decryption and
|
||||
authentication or base64 encrypted data.
|
||||
hash (:obj:`str`): Base64-encoded data hash for data authentication.
|
||||
secret (:obj:`str`): Decrypted or encrypted secret used for decryption.
|
||||
|
||||
Args:
|
||||
data (:class:`telegram.Credentials` or :obj:`str`): Decrypted data with unique user's
|
||||
nonce, data hashes and secrets used for EncryptedPassportElement decryption and
|
||||
authentication or base64 encrypted data.
|
||||
hash (:obj:`str`): Base64-encoded data hash for data authentication.
|
||||
secret (:obj:`str`): Decrypted or encrypted secret used for decryption.
|
||||
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
|
||||
|
||||
Note:
|
||||
This object is decrypted only when originating from
|
||||
:obj:`telegram.PassportData.decrypted_credentials`.
|
||||
|
||||
"""
|
||||
|
||||
def __init__(self, data, hash, secret, bot=None, **kwargs):
|
||||
# Required
|
||||
self.data = data
|
||||
self.hash = hash
|
||||
self.secret = secret
|
||||
|
||||
self._id_attrs = (self.data, self.hash, self.secret)
|
||||
|
||||
self.bot = bot
|
||||
self._decrypted_secret = None
|
||||
self._decrypted_data = None
|
||||
|
||||
@classmethod
|
||||
def de_json(cls, data, bot):
|
||||
if not data:
|
||||
return None
|
||||
|
||||
data = super(EncryptedCredentials, cls).de_json(data, bot)
|
||||
|
||||
return cls(bot=bot, **data)
|
||||
|
||||
@property
|
||||
def decrypted_secret(self):
|
||||
"""
|
||||
:obj:`str`: Lazily decrypt and return secret.
|
||||
|
||||
Raises:
|
||||
telegram.TelegramDecryptionError: Decryption failed. Usually due to bad
|
||||
private/public key but can also suggest malformed/tampered data.
|
||||
"""
|
||||
if self._decrypted_secret is None:
|
||||
# Try decrypting according to step 1 at
|
||||
# https://core.telegram.org/passport#decrypting-data
|
||||
# We make sure to base64 decode the secret first.
|
||||
# Telegram says to use OAEP padding so we do that. The Mask Generation Function
|
||||
# is the default for OAEP, the algorithm is the default for PHP which is what
|
||||
# Telegram's backend servers run.
|
||||
try:
|
||||
self._decrypted_secret = self.bot.private_key.decrypt(b64decode(self.secret), OAEP(
|
||||
mgf=MGF1(algorithm=SHA1()),
|
||||
algorithm=SHA1(),
|
||||
label=None
|
||||
))
|
||||
except ValueError as e:
|
||||
# If decryption fails raise exception
|
||||
raise TelegramDecryptionError(e)
|
||||
return self._decrypted_secret
|
||||
|
||||
@property
|
||||
def decrypted_data(self):
|
||||
"""
|
||||
:class:`telegram.Credentials`: Lazily decrypt and return credentials data. This object
|
||||
also contains the user specified nonce as
|
||||
`decrypted_data.nonce`.
|
||||
|
||||
Raises:
|
||||
telegram.TelegramDecryptionError: Decryption failed. Usually due to bad
|
||||
private/public key but can also suggest malformed/tampered data.
|
||||
"""
|
||||
if self._decrypted_data is None:
|
||||
self._decrypted_data = Credentials.de_json(decrypt_json(self.decrypted_secret,
|
||||
b64decode(self.hash),
|
||||
b64decode(self.data)),
|
||||
self.bot)
|
||||
return self._decrypted_data
|
||||
|
||||
|
||||
class Credentials(TelegramObject):
|
||||
"""
|
||||
Attributes:
|
||||
secure_data (:class:`telegram.SecureData`): Credentials for encrypted data
|
||||
nonce (:obj:`str`): Bot-specified nonce
|
||||
"""
|
||||
|
||||
def __init__(self, secure_data, nonce, bot=None, **kwargs):
|
||||
# Required
|
||||
self.secure_data = secure_data
|
||||
self.nonce = nonce
|
||||
|
||||
self.bot = bot
|
||||
|
||||
@classmethod
|
||||
def de_json(cls, data, bot):
|
||||
if not data:
|
||||
return None
|
||||
|
||||
data['secure_data'] = SecureData.de_json(data.get('secure_data'), bot=bot)
|
||||
|
||||
return cls(bot=bot, **data)
|
||||
|
||||
|
||||
class SecureData(TelegramObject):
|
||||
"""
|
||||
This object represents the credentials that were used to decrypt the encrypted data.
|
||||
All fields are optional and depend on fields that were requested.
|
||||
|
||||
Attributes:
|
||||
personal_details (:class:`telegram.SecureValue`, optional): Credentials for encrypted
|
||||
personal details.
|
||||
passport (:class:`telegram.SecureValue`, optional): Credentials for encrypted passport.
|
||||
internal_passport (:class:`telegram.SecureValue`, optional): Credentials for encrypted
|
||||
internal passport.
|
||||
driver_license (:class:`telegram.SecureValue`, optional): Credentials for encrypted
|
||||
driver license.
|
||||
identity_card (:class:`telegram.SecureValue`, optional): Credentials for encrypted ID card
|
||||
address (:class:`telegram.SecureValue`, optional): Credentials for encrypted
|
||||
residential address.
|
||||
utility_bill (:class:`telegram.SecureValue`, optional): Credentials for encrypted
|
||||
utility bill.
|
||||
bank_statement (:class:`telegram.SecureValue`, optional): Credentials for encrypted
|
||||
bank statement.
|
||||
rental_agreement (:class:`telegram.SecureValue`, optional): Credentials for encrypted
|
||||
rental agreement.
|
||||
passport_registration (:class:`telegram.SecureValue`, optional): Credentials for encrypted
|
||||
registration from internal passport.
|
||||
temporary_registration (:class:`telegram.SecureValue`, optional): Credentials for encrypted
|
||||
temporary registration.
|
||||
"""
|
||||
|
||||
def __init__(self,
|
||||
personal_details=None,
|
||||
passport=None,
|
||||
internal_passport=None,
|
||||
driver_license=None,
|
||||
identity_card=None,
|
||||
address=None,
|
||||
utility_bill=None,
|
||||
bank_statement=None,
|
||||
rental_agreement=None,
|
||||
passport_registration=None,
|
||||
temporary_registration=None,
|
||||
bot=None,
|
||||
**kwargs):
|
||||
# Optionals
|
||||
self.temporary_registration = temporary_registration
|
||||
self.passport_registration = passport_registration
|
||||
self.rental_agreement = rental_agreement
|
||||
self.bank_statement = bank_statement
|
||||
self.utility_bill = utility_bill
|
||||
self.address = address
|
||||
self.identity_card = identity_card
|
||||
self.driver_license = driver_license
|
||||
self.internal_passport = internal_passport
|
||||
self.passport = passport
|
||||
self.personal_details = personal_details
|
||||
|
||||
self.bot = bot
|
||||
|
||||
@classmethod
|
||||
def de_json(cls, data, bot):
|
||||
if not data:
|
||||
return None
|
||||
|
||||
data['temporary_registration'] = SecureValue.de_json(data.get('temporary_registration'),
|
||||
bot=bot)
|
||||
data['passport_registration'] = SecureValue.de_json(data.get('passport_registration'),
|
||||
bot=bot)
|
||||
data['rental_agreement'] = SecureValue.de_json(data.get('rental_agreement'), bot=bot)
|
||||
data['bank_statement'] = SecureValue.de_json(data.get('bank_statement'), bot=bot)
|
||||
data['utility_bill'] = SecureValue.de_json(data.get('utility_bill'), bot=bot)
|
||||
data['address'] = SecureValue.de_json(data.get('address'), bot=bot)
|
||||
data['identity_card'] = SecureValue.de_json(data.get('identity_card'), bot=bot)
|
||||
data['driver_license'] = SecureValue.de_json(data.get('driver_license'), bot=bot)
|
||||
data['internal_passport'] = SecureValue.de_json(data.get('internal_passport'), bot=bot)
|
||||
data['passport'] = SecureValue.de_json(data.get('passport'), bot=bot)
|
||||
data['personal_details'] = SecureValue.de_json(data.get('personal_details'), bot=bot)
|
||||
|
||||
return cls(bot=bot, **data)
|
||||
|
||||
|
||||
class SecureValue(TelegramObject):
|
||||
"""
|
||||
This object represents the credentials that were used to decrypt the encrypted value.
|
||||
All fields are optional and depend on the type of field.
|
||||
|
||||
Attributes:
|
||||
data (:class:`telegram.DataCredentials`, optional): Credentials for encrypted Telegram
|
||||
Passport data. Available for "personal_details", "passport", "driver_license",
|
||||
"identity_card", "identity_passport" and "address" types.
|
||||
front_side (:class:`telegram.FileCredentials`, optional): Credentials for encrypted
|
||||
document's front side. Available for "passport", "driver_license", "identity_card"
|
||||
and "internal_passport".
|
||||
reverse_side (:class:`telegram.FileCredentials`, optional): Credentials for encrypted
|
||||
document's reverse side. Available for "driver_license" and "identity_card".
|
||||
selfie (:class:`telegram.FileCredentials`, optional): Credentials for encrypted selfie
|
||||
of the user with a document. Can be available for "passport", "driver_license",
|
||||
"identity_card" and "internal_passport".
|
||||
translation (List[:class:`telegram.FileCredentials`], optional): Credentials for an
|
||||
encrypted translation of the document. Available for "passport", "driver_license",
|
||||
"identity_card", "internal_passport", "utility_bill", "bank_statement",
|
||||
"rental_agreement", "passport_registration" and "temporary_registration".
|
||||
files (List[:class:`telegram.FileCredentials`], optional): Credentials for encrypted
|
||||
files. Available for "utility_bill", "bank_statement", "rental_agreement",
|
||||
"passport_registration" and "temporary_registration" types.
|
||||
|
||||
"""
|
||||
|
||||
def __init__(self,
|
||||
data=None,
|
||||
front_side=None,
|
||||
reverse_side=None,
|
||||
selfie=None,
|
||||
files=None,
|
||||
translation=None,
|
||||
bot=None,
|
||||
**kwargs):
|
||||
self.data = data
|
||||
self.front_side = front_side
|
||||
self.reverse_side = reverse_side
|
||||
self.selfie = selfie
|
||||
self.files = files
|
||||
self.translation = translation
|
||||
|
||||
self.bot = bot
|
||||
|
||||
@classmethod
|
||||
def de_json(cls, data, bot):
|
||||
if not data:
|
||||
return None
|
||||
|
||||
data['data'] = DataCredentials.de_json(data.get('data'), bot=bot)
|
||||
data['front_side'] = FileCredentials.de_json(data.get('front_side'), bot=bot)
|
||||
data['reverse_side'] = FileCredentials.de_json(data.get('reverse_side'), bot=bot)
|
||||
data['selfie'] = FileCredentials.de_json(data.get('selfie'), bot=bot)
|
||||
data['files'] = FileCredentials.de_list(data.get('files'), bot=bot)
|
||||
data['translation'] = FileCredentials.de_list(data.get('translation'), bot=bot)
|
||||
|
||||
return cls(bot=bot, **data)
|
||||
|
||||
def to_dict(self):
|
||||
data = super(SecureValue, self).to_dict()
|
||||
|
||||
data['files'] = [p.to_dict() for p in self.files]
|
||||
data['translation'] = [p.to_dict() for p in self.translation]
|
||||
|
||||
return data
|
||||
|
||||
|
||||
class _CredentialsBase(TelegramObject):
|
||||
"""Base class for DataCredentials and FileCredentials."""
|
||||
|
||||
def __init__(self, hash, secret, bot=None, **kwargs):
|
||||
self.hash = hash
|
||||
self.secret = secret
|
||||
|
||||
# Aliases just be be sure
|
||||
self.file_hash = self.hash
|
||||
self.data_hash = self.hash
|
||||
|
||||
self.bot = bot
|
||||
|
||||
@classmethod
|
||||
def de_json(cls, data, bot):
|
||||
if not data:
|
||||
return None
|
||||
|
||||
return cls(bot=bot, **data)
|
||||
|
||||
@classmethod
|
||||
def de_list(cls, data, bot):
|
||||
if not data:
|
||||
return []
|
||||
|
||||
credentials = list()
|
||||
for c in data:
|
||||
credentials.append(cls.de_json(c, bot=bot))
|
||||
|
||||
return credentials
|
||||
|
||||
|
||||
class DataCredentials(_CredentialsBase):
|
||||
"""
|
||||
These credentials can be used to decrypt encrypted data from the data field in
|
||||
EncryptedPassportData.
|
||||
|
||||
Args:
|
||||
data_hash (:obj:`str`): Checksum of encrypted data
|
||||
secret (:obj:`str`): Secret of encrypted data
|
||||
|
||||
Attributes:
|
||||
hash (:obj:`str`): Checksum of encrypted data
|
||||
secret (:obj:`str`): Secret of encrypted data
|
||||
"""
|
||||
|
||||
def __init__(self, data_hash, secret, **kwargs):
|
||||
super(DataCredentials, self).__init__(data_hash, secret, **kwargs)
|
||||
|
||||
def to_dict(self):
|
||||
data = super(DataCredentials, self).to_dict()
|
||||
|
||||
del data['file_hash']
|
||||
del data['hash']
|
||||
|
||||
return data
|
||||
|
||||
|
||||
class FileCredentials(_CredentialsBase):
|
||||
"""
|
||||
These credentials can be used to decrypt encrypted files from the front_side,
|
||||
reverse_side, selfie and files fields in EncryptedPassportData.
|
||||
|
||||
Args:
|
||||
file_hash (:obj:`str`): Checksum of encrypted file
|
||||
secret (:obj:`str`): Secret of encrypted file
|
||||
|
||||
Attributes:
|
||||
hash (:obj:`str`): Checksum of encrypted file
|
||||
secret (:obj:`str`): Secret of encrypted file
|
||||
"""
|
||||
|
||||
def __init__(self, file_hash, secret, **kwargs):
|
||||
super(FileCredentials, self).__init__(file_hash, secret, **kwargs)
|
||||
|
||||
def to_dict(self):
|
||||
data = super(FileCredentials, self).to_dict()
|
||||
|
||||
del data['data_hash']
|
||||
del data['hash']
|
||||
|
||||
return data
|
||||
@@ -0,0 +1,119 @@
|
||||
#!/usr/bin/env python
|
||||
#
|
||||
# A library that provides a Python interface to the Telegram Bot API
|
||||
# Copyright (C) 2015-2017
|
||||
# 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/].
|
||||
from telegram import TelegramObject
|
||||
|
||||
|
||||
class PersonalDetails(TelegramObject):
|
||||
"""
|
||||
This object represents personal details.
|
||||
|
||||
Attributes:
|
||||
first_name (:obj:`str`): First Name.
|
||||
middle_name (:obj:`str`): Optional. First Name.
|
||||
last_name (:obj:`str`): Last Name.
|
||||
birth_date (:obj:`str`): Date of birth in DD.MM.YYYY format.
|
||||
gender (:obj:`str`): Gender, male or female.
|
||||
country_code (:obj:`str`): Citizenship (ISO 3166-1 alpha-2 country code).
|
||||
residence_country_code (:obj:`str`): Country of residence (ISO 3166-1 alpha-2 country
|
||||
code).
|
||||
first_name (:obj:`str`): First Name in the language of the user's country of residence.
|
||||
middle_name (:obj:`str`): Optional. Middle Name in the language of the user's country of
|
||||
residence.
|
||||
last_name (:obj:`str`): Last Name in the language of the user's country of residence.
|
||||
"""
|
||||
|
||||
def __init__(self, first_name, last_name, birth_date, gender, country_code,
|
||||
residence_country_code, first_name_native, last_name_native, middle_name=None,
|
||||
middle_name_native=None, bot=None, **kwargs):
|
||||
# Required
|
||||
self.first_name = first_name
|
||||
self.last_name = last_name
|
||||
self.middle_name = middle_name
|
||||
self.birth_date = birth_date
|
||||
self.gender = gender
|
||||
self.country_code = country_code
|
||||
self.residence_country_code = residence_country_code
|
||||
self.first_name_native = first_name_native
|
||||
self.last_name_native = last_name_native
|
||||
self.middle_name_native = middle_name_native
|
||||
|
||||
self.bot = bot
|
||||
|
||||
@classmethod
|
||||
def de_json(cls, data, bot):
|
||||
if not data:
|
||||
return None
|
||||
|
||||
return cls(bot=bot, **data)
|
||||
|
||||
|
||||
class ResidentialAddress(TelegramObject):
|
||||
"""
|
||||
This object represents a residential address.
|
||||
|
||||
Attributes:
|
||||
street_line1 (:obj:`str`): First line for the address.
|
||||
street_line2 (:obj:`str`): Optional. Second line for the address.
|
||||
city (:obj:`str`): City.
|
||||
state (:obj:`str`): Optional. State.
|
||||
country_code (:obj:`str`): ISO 3166-1 alpha-2 country code.
|
||||
post_code (:obj:`str`): Address post code.
|
||||
"""
|
||||
|
||||
def __init__(self, street_line1, street_line2, city, state, country_code,
|
||||
post_code, bot=None, **kwargs):
|
||||
# Required
|
||||
self.street_line1 = street_line1
|
||||
self.street_line2 = street_line2
|
||||
self.city = city
|
||||
self.state = state
|
||||
self.country_code = country_code
|
||||
self.post_code = post_code
|
||||
|
||||
self.bot = bot
|
||||
|
||||
@classmethod
|
||||
def de_json(cls, data, bot):
|
||||
if not data:
|
||||
return None
|
||||
|
||||
return cls(bot=bot, **data)
|
||||
|
||||
|
||||
class IdDocumentData(TelegramObject):
|
||||
"""
|
||||
This object represents the data of an identity document.
|
||||
|
||||
Attributes:
|
||||
document_no (:obj:`str`): Document number.
|
||||
expiry_date (:obj:`str`): Optional. Date of expiry, in DD.MM.YYYY format.
|
||||
"""
|
||||
|
||||
def __init__(self, document_no, expiry_date, bot=None, **kwargs):
|
||||
self.document_no = document_no
|
||||
self.expiry_date = expiry_date
|
||||
|
||||
self.bot = bot
|
||||
|
||||
@classmethod
|
||||
def de_json(cls, data, bot):
|
||||
if not data:
|
||||
return None
|
||||
|
||||
return cls(bot=bot, **data)
|
||||
@@ -0,0 +1,207 @@
|
||||
#!/usr/bin/env python
|
||||
# flake8: noqa: E501
|
||||
# A library that provides a Python interface to the Telegram Bot API
|
||||
# Copyright (C) 2015-2018
|
||||
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Lesser Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Lesser Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Lesser Public License
|
||||
# along with this program. If not, see [http://www.gnu.org/licenses/].
|
||||
"""This module contains an object that represents a Telegram EncryptedPassportElement."""
|
||||
from base64 import b64decode
|
||||
|
||||
from telegram import (TelegramObject, PassportFile, PersonalDetails, IdDocumentData,
|
||||
ResidentialAddress)
|
||||
from telegram.passport.credentials import decrypt_json
|
||||
|
||||
|
||||
class EncryptedPassportElement(TelegramObject):
|
||||
"""
|
||||
Contains information about documents or other Telegram Passport elements shared with the bot
|
||||
by the user. The data has been automatically decrypted by python-telegram-bot.
|
||||
|
||||
Attributes:
|
||||
type (:obj:`str`): Element type. One of "personal_details", "passport", "driver_license",
|
||||
"identity_card", "internal_passport", "address", "utility_bill", "bank_statement",
|
||||
"rental_agreement", "passport_registration", "temporary_registration", "phone_number",
|
||||
"email".
|
||||
data (:class:`telegram.PersonalDetails` or :class:`telegram.IdDocument` or :class:`telegram.ResidentialAddress` or :obj:`str`):
|
||||
Optional. Decrypted or encrypted data, available for "personal_details", "passport",
|
||||
"driver_license", "identity_card", "identity_passport" and "address" types.
|
||||
phone_number (:obj:`str`): Optional. User's verified phone number, available only for
|
||||
"phone_number" type.
|
||||
email (:obj:`str`): Optional. User's verified email address, available only for "email"
|
||||
type.
|
||||
files (List[:class:`telegram.PassportFile`]): Optional. Array of encrypted/decrypted files
|
||||
with documents provided by the user, available for "utility_bill", "bank_statement",
|
||||
"rental_agreement", "passport_registration" and "temporary_registration" types.
|
||||
front_side (:class:`telegram.PassportFile`): Optional. Encrypted/decrypted file with the
|
||||
front side of the document, provided by the user. Available for "passport",
|
||||
"driver_license", "identity_card" and "internal_passport".
|
||||
reverse_side (:class:`telegram.PassportFile`): Optional. Encrypted/decrypted file with the
|
||||
reverse side of the document, provided by the user. Available for "driver_license" and
|
||||
"identity_card".
|
||||
selfie (:class:`telegram.PassportFile`): Optional. Encrypted/decrypted file with the
|
||||
selfie of the user holding a document, provided by the user; available for "passport",
|
||||
"driver_license", "identity_card" and "internal_passport".
|
||||
translation (List[:class:`telegram.PassportFile`]): Optional. Array of encrypted/decrypted
|
||||
files with translated versions of documents provided by the user. Available if
|
||||
requested for "passport", "driver_license", "identity_card", "internal_passport",
|
||||
"utility_bill", "bank_statement", "rental_agreement", "passport_registration" and
|
||||
"temporary_registration" types.
|
||||
hash (:obj:`str`): Base64-encoded element hash for using in
|
||||
:class:`telegram.PassportElementErrorUnspecified`.
|
||||
bot (:class:`telegram.Bot`): Optional. The Bot to use for instance methods.
|
||||
|
||||
Args:
|
||||
type (:obj:`str`): Element type. One of "personal_details", "passport", "driver_license",
|
||||
"identity_card", "internal_passport", "address", "utility_bill", "bank_statement",
|
||||
"rental_agreement", "passport_registration", "temporary_registration", "phone_number",
|
||||
"email".
|
||||
data (:class:`telegram.PersonalDetails` or :class:`telegram.IdDocument` or :class:`telegram.ResidentialAddress` or :obj:`str`, optional):
|
||||
Decrypted or encrypted data, available for "personal_details", "passport",
|
||||
"driver_license", "identity_card", "identity_passport" and "address" types.
|
||||
phone_number (:obj:`str`, optional): User's verified phone number, available only for
|
||||
"phone_number" type.
|
||||
email (:obj:`str`, optional): User's verified email address, available only for "email"
|
||||
type.
|
||||
files (List[:class:`telegram.PassportFile`], optional): Array of encrypted/decrypted files
|
||||
with documents provided by the user, available for "utility_bill", "bank_statement",
|
||||
"rental_agreement", "passport_registration" and "temporary_registration" types.
|
||||
front_side (:class:`telegram.PassportFile`, optional): Encrypted/decrypted file with the
|
||||
front side of the document, provided by the user. Available for "passport",
|
||||
"driver_license", "identity_card" and "internal_passport".
|
||||
reverse_side (:class:`telegram.PassportFile`, optional): Encrypted/decrypted file with the
|
||||
reverse side of the document, provided by the user. Available for "driver_license" and
|
||||
"identity_card".
|
||||
selfie (:class:`telegram.PassportFile`, optional): Encrypted/decrypted file with the
|
||||
selfie of the user holding a document, provided by the user; available for "passport",
|
||||
"driver_license", "identity_card" and "internal_passport".
|
||||
translation (List[:class:`telegram.PassportFile`], optional): Array of encrypted/decrypted
|
||||
files with translated versions of documents provided by the user. Available if
|
||||
requested for "passport", "driver_license", "identity_card", "internal_passport",
|
||||
"utility_bill", "bank_statement", "rental_agreement", "passport_registration" and
|
||||
"temporary_registration" types.
|
||||
hash (:obj:`str`): Base64-encoded element hash for using in
|
||||
:class:`telegram.PassportElementErrorUnspecified`.
|
||||
bot (:class:`telegram.Bot`, optional): The Bot to use for instance methods.
|
||||
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
|
||||
|
||||
Note:
|
||||
This object is decrypted only when originating from
|
||||
:obj:`telegram.PassportData.decrypted_data`.
|
||||
"""
|
||||
|
||||
def __init__(self,
|
||||
type,
|
||||
data=None,
|
||||
phone_number=None,
|
||||
email=None,
|
||||
files=None,
|
||||
front_side=None,
|
||||
reverse_side=None,
|
||||
selfie=None,
|
||||
translation=None,
|
||||
hash=None,
|
||||
bot=None,
|
||||
credentials=None,
|
||||
**kwargs):
|
||||
# Required
|
||||
self.type = type
|
||||
# Optionals
|
||||
self.data = data
|
||||
self.phone_number = phone_number
|
||||
self.email = email
|
||||
self.files = files
|
||||
self.front_side = front_side
|
||||
self.reverse_side = reverse_side
|
||||
self.selfie = selfie
|
||||
self.translation = translation
|
||||
self.hash = hash
|
||||
|
||||
self._id_attrs = (self.type, self.data, self.phone_number, self.email, self.files,
|
||||
self.front_side, self.reverse_side, self.selfie)
|
||||
|
||||
self.bot = bot
|
||||
|
||||
@classmethod
|
||||
def de_json(cls, data, bot):
|
||||
if not data:
|
||||
return None
|
||||
|
||||
data = super(EncryptedPassportElement, cls).de_json(data, bot)
|
||||
|
||||
data['files'] = PassportFile.de_list(data.get('files'), bot) or None
|
||||
data['front_side'] = PassportFile.de_json(data.get('front_side'), bot)
|
||||
data['reverse_side'] = PassportFile.de_json(data.get('reverse_side'), bot)
|
||||
data['selfie'] = PassportFile.de_json(data.get('selfie'), bot)
|
||||
data['translation'] = PassportFile.de_list(data.get('translation'), bot) or None
|
||||
|
||||
return cls(bot=bot, **data)
|
||||
|
||||
@classmethod
|
||||
def de_json_decrypted(cls, data, bot, credentials):
|
||||
if not data:
|
||||
return None
|
||||
|
||||
data = super(EncryptedPassportElement, cls).de_json(data, bot)
|
||||
|
||||
if data['type'] not in ('phone_number', 'email'):
|
||||
secure_data = getattr(credentials.secure_data, data['type'])
|
||||
|
||||
if secure_data.data is not None:
|
||||
# If not already decrypted
|
||||
if not isinstance(data['data'], dict):
|
||||
data['data'] = decrypt_json(b64decode(secure_data.data.secret),
|
||||
b64decode(secure_data.data.hash),
|
||||
b64decode(data['data']))
|
||||
if data['type'] == 'personal_details':
|
||||
data['data'] = PersonalDetails.de_json(data['data'], bot=bot)
|
||||
elif data['type'] in ('passport', 'internal_passport',
|
||||
'driver_license', 'identity_card'):
|
||||
data['data'] = IdDocumentData.de_json(data['data'], bot=bot)
|
||||
elif data['type'] == 'address':
|
||||
data['data'] = ResidentialAddress.de_json(data['data'], bot=bot)
|
||||
|
||||
data['files'] = PassportFile.de_list_decrypted(data.get('files'), bot,
|
||||
secure_data.files) or None
|
||||
data['front_side'] = PassportFile.de_json_decrypted(data.get('front_side'), bot,
|
||||
secure_data.front_side)
|
||||
data['reverse_side'] = PassportFile.de_json_decrypted(data.get('reverse_side'), bot,
|
||||
secure_data.reverse_side)
|
||||
data['selfie'] = PassportFile.de_json_decrypted(data.get('selfie'), bot,
|
||||
secure_data.selfie)
|
||||
data['translation'] = PassportFile.de_list_decrypted(data.get('translation'), bot,
|
||||
secure_data.translation) or None
|
||||
|
||||
return cls(bot=bot, **data)
|
||||
|
||||
@classmethod
|
||||
def de_list(cls, data, bot):
|
||||
if not data:
|
||||
return []
|
||||
|
||||
encrypted_passport_elements = list()
|
||||
for element in data:
|
||||
encrypted_passport_elements.append(cls.de_json(element, bot))
|
||||
|
||||
return encrypted_passport_elements
|
||||
|
||||
def to_dict(self):
|
||||
data = super(EncryptedPassportElement, self).to_dict()
|
||||
|
||||
if self.files:
|
||||
data['files'] = [p.to_dict() for p in self.files]
|
||||
if self.translation:
|
||||
data['translation'] = [p.to_dict() for p in self.translation]
|
||||
|
||||
return data
|
||||
@@ -0,0 +1,105 @@
|
||||
#!/usr/bin/env python
|
||||
#
|
||||
# A library that provides a Python interface to the Telegram Bot API
|
||||
# Copyright (C) 2015-2018
|
||||
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Lesser Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Lesser Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Lesser Public License
|
||||
# along with this program. If not, see [http://www.gnu.org/licenses/].
|
||||
"""Contains information about Telegram Passport data shared with the bot by the user."""
|
||||
|
||||
from telegram import EncryptedCredentials, EncryptedPassportElement, TelegramObject
|
||||
|
||||
|
||||
class PassportData(TelegramObject):
|
||||
"""Contains information about Telegram Passport data shared with the bot by the user.
|
||||
|
||||
Attributes:
|
||||
data (List[:class:`telegram.EncryptedPassportElement`]): Array with encrypted information
|
||||
about documents and other Telegram Passport elements that was shared with the bot.
|
||||
credentials (:class:`telegram.EncryptedCredentials`): Encrypted credentials.
|
||||
bot (:class:`telegram.Bot`, optional): The Bot to use for instance methods.
|
||||
|
||||
Args:
|
||||
data (List[:class:`telegram.EncryptedPassportElement`]): Array with encrypted information
|
||||
about documents and other Telegram Passport elements that was shared with the bot.
|
||||
credentials (:obj:`str`): Encrypted credentials.
|
||||
bot (:class:`telegram.Bot`, optional): The Bot to use for instance methods.
|
||||
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
|
||||
|
||||
Note:
|
||||
To be able to decrypt this object, you must pass your private_key to either
|
||||
:class:`telegram.Updater` or :class:`telegram.Bot`. Decrypted data is then found in
|
||||
:attr:`decrypted_data` and the payload can be found in :attr:`decrypted_credentials`'s
|
||||
attribute :attr:`telegram.Credentials.payload`.
|
||||
|
||||
"""
|
||||
|
||||
def __init__(self, data, credentials, bot=None, **kwargs):
|
||||
self.data = data
|
||||
self.credentials = credentials
|
||||
|
||||
self.bot = bot
|
||||
self._decrypted_data = None
|
||||
self._id_attrs = tuple([x.type for x in data] + [credentials.hash])
|
||||
|
||||
@classmethod
|
||||
def de_json(cls, data, bot):
|
||||
if not data:
|
||||
return None
|
||||
|
||||
data = super(PassportData, cls).de_json(data, bot)
|
||||
|
||||
data['data'] = EncryptedPassportElement.de_list(data.get('data'), bot)
|
||||
data['credentials'] = EncryptedCredentials.de_json(data.get('credentials'), bot)
|
||||
|
||||
return cls(bot=bot, **data)
|
||||
|
||||
def to_dict(self):
|
||||
data = super(PassportData, self).to_dict()
|
||||
|
||||
data['data'] = [e.to_dict() for e in self.data]
|
||||
|
||||
return data
|
||||
|
||||
@property
|
||||
def decrypted_data(self):
|
||||
"""
|
||||
List[:class:`telegram.EncryptedPassportElement`]: Lazily decrypt and return information
|
||||
about documents and other Telegram Passport elements which were shared with the bot.
|
||||
|
||||
Raises:
|
||||
telegram.TelegramDecryptionError: Decryption failed. Usually due to bad
|
||||
private/public key but can also suggest malformed/tampered data.
|
||||
"""
|
||||
if self._decrypted_data is None:
|
||||
self._decrypted_data = [
|
||||
EncryptedPassportElement.de_json_decrypted(element.to_dict(),
|
||||
self.bot,
|
||||
self.decrypted_credentials)
|
||||
for element in self.data
|
||||
]
|
||||
return self._decrypted_data
|
||||
|
||||
@property
|
||||
def decrypted_credentials(self):
|
||||
"""
|
||||
:class:`telegram.Credentials`: Lazily decrypt and return credentials that were used
|
||||
to decrypt the data. This object also contains the user specified payload as
|
||||
`decrypted_data.payload`.
|
||||
|
||||
Raises:
|
||||
telegram.TelegramDecryptionError: Decryption failed. Usually due to bad
|
||||
private/public key but can also suggest malformed/tampered data.
|
||||
"""
|
||||
return self.credentials.decrypted_data
|
||||
@@ -0,0 +1,357 @@
|
||||
#!/usr/bin/env python
|
||||
#
|
||||
# A library that provides a Python interface to the Telegram Bot API
|
||||
# Copyright (C) 2015-2018
|
||||
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Lesser Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Lesser Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Lesser Public License
|
||||
# along with this program. If not, see [http://www.gnu.org/licenses/].
|
||||
"""This module contains the classes that represent Telegram PassportElementError."""
|
||||
|
||||
from telegram import TelegramObject
|
||||
|
||||
|
||||
class PassportElementError(TelegramObject):
|
||||
"""Baseclass for the PassportElementError* classes.
|
||||
|
||||
Attributes:
|
||||
source (:obj:`str`): Error source.
|
||||
type (:obj:`str`): The section of the user's Telegram Passport which has the error.
|
||||
message (:obj:`str`): Error message
|
||||
|
||||
Args:
|
||||
source (:obj:`str`): Error source.
|
||||
type (:obj:`str`): The section of the user's Telegram Passport which has the error.
|
||||
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
|
||||
|
||||
"""
|
||||
|
||||
def __init__(self, source, type, message, **kwargs):
|
||||
# Required
|
||||
self.source = str(source)
|
||||
self.type = str(type)
|
||||
self.message = str(message)
|
||||
|
||||
self._id_attrs = (self.source, self.type)
|
||||
|
||||
|
||||
class PassportElementErrorDataField(PassportElementError):
|
||||
"""
|
||||
Represents an issue in one of the data fields that was provided by the user. The error is
|
||||
considered resolved when the field's value changes.
|
||||
|
||||
Attributes:
|
||||
type (:obj:`str`): The section of the user's Telegram Passport which has the error, one of
|
||||
"personal_details", "passport", "driver_license", "identity_card", "internal_passport",
|
||||
"address".
|
||||
field_name (:obj:`str`): Name of the data field which has the error.
|
||||
data_hash (:obj:`str`): Base64-encoded data hash.
|
||||
message (:obj:`str`): Error message.
|
||||
|
||||
Args:
|
||||
type (:obj:`str`): The section of the user's Telegram Passport which has the error, one of
|
||||
"personal_details", "passport", "driver_license", "identity_card", "internal_passport",
|
||||
"address".
|
||||
field_name (:obj:`str`): Name of the data field which has the error.
|
||||
data_hash (:obj:`str`): Base64-encoded data hash.
|
||||
message (:obj:`str`): Error message.
|
||||
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
|
||||
|
||||
"""
|
||||
|
||||
def __init__(self,
|
||||
type,
|
||||
field_name,
|
||||
data_hash,
|
||||
message,
|
||||
**kwargs):
|
||||
# Required
|
||||
super(PassportElementErrorDataField, self).__init__('data', type, message)
|
||||
self.field_name = field_name
|
||||
self.data_hash = data_hash
|
||||
|
||||
self._id_attrs = (self.source, self.type, self.field_name, self.data_hash, self.message)
|
||||
|
||||
|
||||
class PassportElementErrorFile(PassportElementError):
|
||||
"""
|
||||
Represents an issue with a document scan. The error is considered resolved when the file with
|
||||
the document scan changes.
|
||||
|
||||
Attributes:
|
||||
type (:obj:`str`): The section of the user's Telegram Passport which has the issue, one of
|
||||
"utility_bill", "bank_statement", "rental_agreement", "passport_registration",
|
||||
"temporary_registration".
|
||||
file_hash (:obj:`str`): Base64-encoded file hash.
|
||||
message (:obj:`str`): Error message.
|
||||
|
||||
Args:
|
||||
type (:obj:`str`): The section of the user's Telegram Passport which has the issue, one of
|
||||
"utility_bill", "bank_statement", "rental_agreement", "passport_registration",
|
||||
"temporary_registration".
|
||||
file_hash (:obj:`str`): Base64-encoded file hash.
|
||||
message (:obj:`str`): Error message.
|
||||
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
|
||||
|
||||
"""
|
||||
|
||||
def __init__(self,
|
||||
type,
|
||||
file_hash,
|
||||
message,
|
||||
**kwargs):
|
||||
# Required
|
||||
super(PassportElementErrorFile, self).__init__('file', type, message)
|
||||
self.file_hash = file_hash
|
||||
|
||||
self._id_attrs = (self.source, self.type, self.file_hash, self.message)
|
||||
|
||||
|
||||
class PassportElementErrorFiles(PassportElementError):
|
||||
"""
|
||||
Represents an issue with a list of scans. The error is considered resolved when the file with
|
||||
the document scan changes.
|
||||
|
||||
Attributes:
|
||||
type (:obj:`str`): The section of the user's Telegram Passport which has the issue, one of
|
||||
"utility_bill", "bank_statement", "rental_agreement", "passport_registration",
|
||||
"temporary_registration".
|
||||
file_hash (:obj:`str`): Base64-encoded file hash.
|
||||
message (:obj:`str`): Error message.
|
||||
|
||||
Args:
|
||||
type (:obj:`str`): The section of the user's Telegram Passport which has the issue, one of
|
||||
"utility_bill", "bank_statement", "rental_agreement", "passport_registration",
|
||||
"temporary_registration".
|
||||
file_hashes (List[:obj:`str`]): List of base64-encoded file hashes.
|
||||
message (:obj:`str`): Error message.
|
||||
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
|
||||
|
||||
"""
|
||||
|
||||
def __init__(self,
|
||||
type,
|
||||
file_hashes,
|
||||
message,
|
||||
**kwargs):
|
||||
# Required
|
||||
super(PassportElementErrorFiles, self).__init__('files', type, message)
|
||||
self.file_hashes = file_hashes
|
||||
|
||||
self._id_attrs = ((self.source, self.type, self.message) +
|
||||
tuple([file_hash for file_hash in file_hashes]))
|
||||
|
||||
|
||||
class PassportElementErrorFrontSide(PassportElementError):
|
||||
"""
|
||||
Represents an issue with the front side of a document. The error is considered resolved when
|
||||
the file with the front side of the document changes.
|
||||
|
||||
Attributes:
|
||||
type (:obj:`str`): The section of the user's Telegram Passport which has the issue, one of
|
||||
"passport", "driver_license", "identity_card", "internal_passport".
|
||||
file_hash (:obj:`str`): Base64-encoded hash of the file with the front side of the
|
||||
document.
|
||||
message (:obj:`str`): Error message.
|
||||
|
||||
Args:
|
||||
type (:obj:`str`): The section of the user's Telegram Passport which has the issue, one of
|
||||
"passport", "driver_license", "identity_card", "internal_passport".
|
||||
file_hash (:obj:`str`): Base64-encoded hash of the file with the front side of the
|
||||
document.
|
||||
message (:obj:`str`): Error message.
|
||||
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
|
||||
|
||||
"""
|
||||
|
||||
def __init__(self,
|
||||
type,
|
||||
file_hash,
|
||||
message,
|
||||
**kwargs):
|
||||
# Required
|
||||
super(PassportElementErrorFrontSide, self).__init__('front_side', type, message)
|
||||
self.file_hash = file_hash
|
||||
|
||||
self._id_attrs = (self.source, self.type, self.file_hash, self.message)
|
||||
|
||||
|
||||
class PassportElementErrorReverseSide(PassportElementError):
|
||||
"""
|
||||
Represents an issue with the front side of a document. The error is considered resolved when
|
||||
the file with the reverse side of the document changes.
|
||||
|
||||
Attributes:
|
||||
type (:obj:`str`): The section of the user's Telegram Passport which has the issue, one of
|
||||
"passport", "driver_license", "identity_card", "internal_passport".
|
||||
file_hash (:obj:`str`): Base64-encoded hash of the file with the reverse side of the
|
||||
document.
|
||||
message (:obj:`str`): Error message.
|
||||
|
||||
Args:
|
||||
type (:obj:`str`): The section of the user's Telegram Passport which has the issue, one of
|
||||
"driver_license", "identity_card".
|
||||
file_hash (:obj:`str`): Base64-encoded hash of the file with the reverse side of the
|
||||
document.
|
||||
message (:obj:`str`): Error message.
|
||||
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
|
||||
|
||||
"""
|
||||
|
||||
def __init__(self,
|
||||
type,
|
||||
file_hash,
|
||||
message,
|
||||
**kwargs):
|
||||
# Required
|
||||
super(PassportElementErrorReverseSide, self).__init__('reverse_side', type, message)
|
||||
self.file_hash = file_hash
|
||||
|
||||
self._id_attrs = (self.source, self.type, self.file_hash, self.message)
|
||||
|
||||
|
||||
class PassportElementErrorSelfie(PassportElementError):
|
||||
"""
|
||||
Represents an issue with the selfie with a document. The error is considered resolved when
|
||||
the file with the selfie changes.
|
||||
|
||||
Attributes:
|
||||
type (:obj:`str`): The section of the user's Telegram Passport which has the issue, one of
|
||||
"passport", "driver_license", "identity_card", "internal_passport".
|
||||
file_hash (:obj:`str`): Base64-encoded hash of the file with the selfie.
|
||||
message (:obj:`str`): Error message.
|
||||
|
||||
Args:
|
||||
type (:obj:`str`): The section of the user's Telegram Passport which has the issue, one of
|
||||
"passport", "driver_license", "identity_card", "internal_passport".
|
||||
file_hash (:obj:`str`): Base64-encoded hash of the file with the selfie.
|
||||
message (:obj:`str`): Error message.
|
||||
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
|
||||
|
||||
"""
|
||||
|
||||
def __init__(self,
|
||||
type,
|
||||
file_hash,
|
||||
message,
|
||||
**kwargs):
|
||||
# Required
|
||||
super(PassportElementErrorSelfie, self).__init__('selfie', type, message)
|
||||
self.file_hash = file_hash
|
||||
|
||||
self._id_attrs = (self.source, self.type, self.file_hash, self.message)
|
||||
|
||||
|
||||
class PassportElementErrorTranslationFile(PassportElementError):
|
||||
"""
|
||||
Represents an issue with one of the files that constitute the translation of a document.
|
||||
The error is considered resolved when the file changes.
|
||||
|
||||
Attributes:
|
||||
type (:obj:`str`): Type of element of the user's Telegram Passport which has the issue,
|
||||
one of "passport", "driver_license", "identity_card", "internal_passport",
|
||||
"utility_bill", "bank_statement", "rental_agreement", "passport_registration",
|
||||
"temporary_registration".
|
||||
file_hash (:obj:`str`): Base64-encoded hash of the file.
|
||||
message (:obj:`str`): Error message.
|
||||
|
||||
Args:
|
||||
type (:obj:`str`): Type of element of the user's Telegram Passport which has the issue,
|
||||
one of "passport", "driver_license", "identity_card", "internal_passport",
|
||||
"utility_bill", "bank_statement", "rental_agreement", "passport_registration",
|
||||
"temporary_registration".
|
||||
file_hash (:obj:`str`): Base64-encoded hash of the file.
|
||||
message (:obj:`str`): Error message.
|
||||
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
|
||||
|
||||
"""
|
||||
|
||||
def __init__(self,
|
||||
type,
|
||||
file_hash,
|
||||
message,
|
||||
**kwargs):
|
||||
# Required
|
||||
super(PassportElementErrorTranslationFile, self).__init__('translation_file',
|
||||
type, message)
|
||||
self.file_hash = file_hash
|
||||
|
||||
self._id_attrs = (self.source, self.type, self.file_hash, self.message)
|
||||
|
||||
|
||||
class PassportElementErrorTranslationFiles(PassportElementError):
|
||||
"""
|
||||
Represents an issue with the translated version of a document. The error is considered
|
||||
resolved when a file with the document translation change.
|
||||
|
||||
Attributes:
|
||||
type (:obj:`str`): Type of element of the user's Telegram Passport which has the issue,
|
||||
one of "passport", "driver_license", "identity_card", "internal_passport",
|
||||
"utility_bill", "bank_statement", "rental_agreement", "passport_registration",
|
||||
"temporary_registration"
|
||||
file_hash (:obj:`str`): Base64-encoded file hash.
|
||||
message (:obj:`str`): Error message.
|
||||
|
||||
Args:
|
||||
type (:obj:`str`): Type of element of the user's Telegram Passport which has the issue,
|
||||
one of "passport", "driver_license", "identity_card", "internal_passport",
|
||||
"utility_bill", "bank_statement", "rental_agreement", "passport_registration",
|
||||
"temporary_registration"
|
||||
file_hashes (List[:obj:`str`]): List of base64-encoded file hashes.
|
||||
message (:obj:`str`): Error message.
|
||||
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
|
||||
|
||||
"""
|
||||
|
||||
def __init__(self,
|
||||
type,
|
||||
file_hashes,
|
||||
message,
|
||||
**kwargs):
|
||||
# Required
|
||||
super(PassportElementErrorTranslationFiles, self).__init__('translation_files',
|
||||
type, message)
|
||||
self.file_hashes = file_hashes
|
||||
|
||||
self._id_attrs = ((self.source, self.type, self.message) +
|
||||
tuple([file_hash for file_hash in file_hashes]))
|
||||
|
||||
|
||||
class PassportElementErrorUnspecified(PassportElementError):
|
||||
"""
|
||||
Represents an issue in an unspecified place. The error is considered resolved when new
|
||||
data is added.
|
||||
|
||||
Attributes:
|
||||
type (:obj:`str`): Type of element of the user's Telegram Passport which has the issue.
|
||||
element_hash (:obj:`str`): Base64-encoded element hash.
|
||||
message (:obj:`str`): Error message.
|
||||
|
||||
Args:
|
||||
type (:obj:`str`): Type of element of the user's Telegram Passport which has the issue.
|
||||
element_hash (:obj:`str`): Base64-encoded element hash.
|
||||
message (:obj:`str`): Error message.
|
||||
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
|
||||
|
||||
"""
|
||||
|
||||
def __init__(self,
|
||||
type,
|
||||
element_hash,
|
||||
message,
|
||||
**kwargs):
|
||||
# Required
|
||||
super(PassportElementErrorUnspecified, self).__init__('unspecified', type, message)
|
||||
self.element_hash = element_hash
|
||||
|
||||
self._id_attrs = (self.source, self.type, self.element_hash, self.message)
|
||||
@@ -0,0 +1,111 @@
|
||||
#!/usr/bin/env python
|
||||
#
|
||||
# A library that provides a Python interface to the Telegram Bot API
|
||||
# Copyright (C) 2015-2018
|
||||
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Lesser Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU Lesser Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Lesser Public License
|
||||
# along with this program. If not, see [http://www.gnu.org/licenses/].
|
||||
"""This module contains an object that represents a Encrypted PassportFile."""
|
||||
|
||||
from telegram import TelegramObject
|
||||
|
||||
|
||||
class PassportFile(TelegramObject):
|
||||
"""
|
||||
This object represents a file uploaded to Telegram Passport. Currently all Telegram Passport
|
||||
files are in JPEG format when decrypted and don't exceed 10MB.
|
||||
|
||||
Attributes:
|
||||
file_id (:obj:`str`): Unique identifier for this file.
|
||||
file_size (:obj:`int`): File size.
|
||||
file_date (:obj:`int`): Unix time when the file was uploaded.
|
||||
bot (:class:`telegram.Bot`): Optional. The Bot to use for instance methods.
|
||||
|
||||
Args:
|
||||
file_id (:obj:`str`): Unique identifier for this file.
|
||||
file_size (:obj:`int`): File size.
|
||||
file_date (:obj:`int`): Unix time when the file was uploaded.
|
||||
bot (:class:`telegram.Bot`, optional): The Bot to use for instance methods.
|
||||
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
|
||||
|
||||
"""
|
||||
|
||||
def __init__(self, file_id, file_date, file_size=None, bot=None, credentials=None, **kwargs):
|
||||
# Required
|
||||
self.file_id = file_id
|
||||
self.file_size = file_size
|
||||
self.file_date = file_date
|
||||
# Optionals
|
||||
self.bot = bot
|
||||
self._credentials = credentials
|
||||
|
||||
self._id_attrs = (self.file_id,)
|
||||
|
||||
@classmethod
|
||||
def de_json(cls, data, bot):
|
||||
if not data:
|
||||
return None
|
||||
|
||||
data = super(PassportFile, cls).de_json(data, bot)
|
||||
|
||||
return cls(bot=bot, **data)
|
||||
|
||||
@classmethod
|
||||
def de_json_decrypted(cls, data, bot, credentials):
|
||||
if not data:
|
||||
return None
|
||||
|
||||
data = super(PassportFile, cls).de_json(data, bot)
|
||||
|
||||
data['credentials'] = credentials
|
||||
|
||||
return cls(bot=bot, **data)
|
||||
|
||||
@classmethod
|
||||
def de_list(cls, data, bot):
|
||||
if not data:
|
||||
return []
|
||||
|
||||
return [cls.de_json(passport_file, bot) for passport_file in data]
|
||||
|
||||
@classmethod
|
||||
def de_list_decrypted(cls, data, bot, credentials):
|
||||
if not data:
|
||||
return []
|
||||
|
||||
return [cls.de_json_decrypted(passport_file, bot, credentials[i])
|
||||
for i, passport_file in enumerate(data)]
|
||||
|
||||
def get_file(self, timeout=None, **kwargs):
|
||||
"""
|
||||
Wrapper over :attr:`telegram.Bot.get_file`. Will automatically assign the correct
|
||||
credentials to the returned :class:`telegram.File` if originating from
|
||||
:obj:`telegram.PassportData.decrypted_data`.
|
||||
|
||||
Args:
|
||||
timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as
|
||||
the read timeout from the server (instead of the one specified during creation of
|
||||
the connection pool).
|
||||
**kwargs (:obj:`dict`): Arbitrary keyword arguments.
|
||||
|
||||
Returns:
|
||||
:class:`telegram.File`
|
||||
|
||||
Raises:
|
||||
:class:`telegram.TelegramError`
|
||||
|
||||
"""
|
||||
file = self.bot.get_file(self.file_id, timeout=timeout, **kwargs)
|
||||
file.set_credentials(self._credentials)
|
||||
return file
|
||||
+51
-34
@@ -71,26 +71,30 @@ class User(TelegramObject):
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
"""
|
||||
:obj:`str`: Convenience property. If available, returns the user's :attr:`username`
|
||||
prefixed with "@". If :attr:`username` is not available, returns :attr:`full_name`.
|
||||
|
||||
"""
|
||||
""":obj:`str`: Convenience property. If available, returns the user's :attr:`username`
|
||||
prefixed with "@". If :attr:`username` is not available, returns :attr:`full_name`."""
|
||||
if self.username:
|
||||
return '@{}'.format(self.username)
|
||||
return self.full_name
|
||||
|
||||
@property
|
||||
def full_name(self):
|
||||
"""
|
||||
:obj:`str`: Convenience property. The user's :attr:`first_name`, followed by (if available)
|
||||
:attr:`last_name`.
|
||||
""":obj:`str`: Convenience property. The user's :attr:`first_name`, followed by (if
|
||||
available) :attr:`last_name`."""
|
||||
|
||||
"""
|
||||
if self.last_name:
|
||||
return '{} {}'.format(self.first_name, self.last_name)
|
||||
return u'{} {}'.format(self.first_name, self.last_name)
|
||||
return self.first_name
|
||||
|
||||
@property
|
||||
def link(self):
|
||||
""":obj:`str`: Convenience property. If :attr:`username` is available, returns a t.me link
|
||||
of the user."""
|
||||
|
||||
if self.username:
|
||||
return "https://t.me/{}".format(self.username)
|
||||
return None
|
||||
|
||||
@classmethod
|
||||
def de_json(cls, data, bot):
|
||||
if not data:
|
||||
@@ -124,33 +128,33 @@ class User(TelegramObject):
|
||||
def mention_markdown(self, name=None):
|
||||
"""
|
||||
Args:
|
||||
name (:obj:`str`): If provided, will overwrite the user's name.
|
||||
name (:obj:`str`): The name used as a link for the user. Defaults to :attr:`full_name`.
|
||||
|
||||
Returns:
|
||||
:obj:`str`: The inline mention for the user as markdown.
|
||||
|
||||
"""
|
||||
if not name:
|
||||
return util_mention_markdown(self.id, self.name)
|
||||
else:
|
||||
if name:
|
||||
return util_mention_markdown(self.id, name)
|
||||
return util_mention_markdown(self.id, self.full_name)
|
||||
|
||||
def mention_html(self, name=None):
|
||||
"""
|
||||
Args:
|
||||
name (:obj:`str`): If provided, will overwrite the user's name.
|
||||
name (:obj:`str`): The name used as a link for the user. Defaults to :attr:`full_name`.
|
||||
|
||||
Returns:
|
||||
:obj:`str`: The inline mention for the user as HTML.
|
||||
|
||||
"""
|
||||
if not name:
|
||||
return util_mention_html(self.id, self.name)
|
||||
else:
|
||||
if name:
|
||||
return util_mention_html(self.id, name)
|
||||
return util_mention_html(self.id, self.full_name)
|
||||
|
||||
def send_message(self, *args, **kwargs):
|
||||
"""Shortcut for::
|
||||
|
||||
bot.send_message(User.chat_id, *args, **kwargs)
|
||||
bot.send_message(User.id, *args, **kwargs)
|
||||
|
||||
Where User is the current instance.
|
||||
|
||||
@@ -158,12 +162,12 @@ class User(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(User.chat_id, *args, **kwargs)
|
||||
bot.send_photo(User.id, *args, **kwargs)
|
||||
|
||||
Where User is the current instance.
|
||||
|
||||
@@ -171,12 +175,12 @@ class User(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(User.chat_id, *args, **kwargs)
|
||||
bot.send_audio(User.id, *args, **kwargs)
|
||||
|
||||
Where User is the current instance.
|
||||
|
||||
@@ -184,12 +188,12 @@ class User(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(User.chat_id, *args, **kwargs)
|
||||
bot.send_document(User.id, *args, **kwargs)
|
||||
|
||||
Where User is the current instance.
|
||||
|
||||
@@ -197,12 +201,25 @@ class User(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(User.id, *args, **kwargs)
|
||||
|
||||
Where User 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(User.chat_id, *args, **kwargs)
|
||||
bot.send_sticker(User.id, *args, **kwargs)
|
||||
|
||||
Where User is the current instance.
|
||||
|
||||
@@ -210,12 +227,12 @@ class User(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(User.chat_id, *args, **kwargs)
|
||||
bot.send_video(User.id, *args, **kwargs)
|
||||
|
||||
Where User is the current instance.
|
||||
|
||||
@@ -223,12 +240,12 @@ class User(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(User.chat_id, *args, **kwargs)
|
||||
bot.send_video_note(User.id, *args, **kwargs)
|
||||
|
||||
Where User is the current instance.
|
||||
|
||||
@@ -236,12 +253,12 @@ class User(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(User.chat_id, *args, **kwargs)
|
||||
bot.send_voice(User.id, *args, **kwargs)
|
||||
|
||||
Where User is the current instance.
|
||||
|
||||
@@ -249,4 +266,4 @@ class User(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)
|
||||
|
||||
@@ -94,7 +94,7 @@ def mention_html(user_id, name):
|
||||
:obj:`str`: The inline mention for the user as html.
|
||||
"""
|
||||
if isinstance(user_id, int):
|
||||
return '<a href="tg://user?id={}">{}</a>'.format(user_id, escape(name))
|
||||
return u'<a href="tg://user?id={}">{}</a>'.format(user_id, escape(name))
|
||||
|
||||
|
||||
def mention_markdown(user_id, name):
|
||||
@@ -107,7 +107,7 @@ def mention_markdown(user_id, name):
|
||||
:obj:`str`: The inline mention for the user as markdown.
|
||||
"""
|
||||
if isinstance(user_id, int):
|
||||
return '[{}](tg://user?id={})'.format(escape_markdown(name), user_id)
|
||||
return u'[{}](tg://user?id={})'.format(escape_markdown(name), user_id)
|
||||
|
||||
|
||||
def effective_message_type(entity):
|
||||
|
||||
@@ -27,7 +27,20 @@ logger.addHandler(logging.NullHandler())
|
||||
|
||||
|
||||
class Promise(object):
|
||||
"""A simple Promise implementation for the run_async decorator."""
|
||||
"""A simple Promise implementation for use with the run_async decorator, DelayQueue etc.
|
||||
|
||||
Args:
|
||||
pooled_function (:obj:`callable`): The callable that will be called concurrently.
|
||||
args (:obj:`list` | :obj:`tuple`): Positional arguments for :attr:`pooled_function`.
|
||||
kwargs (:obj:`dict`): Keyword arguments for :attr:`pooled_function`.
|
||||
|
||||
Attributes:
|
||||
pooled_function (:obj:`callable`): The callable that will be called concurrently.
|
||||
args (:obj:`list` | :obj:`tuple`): Positional arguments for :attr:`pooled_function`.
|
||||
kwargs (:obj:`dict`): Keyword arguments for :attr:`pooled_function`.
|
||||
done (:obj:`threading.Event`): Is set when the result is available.
|
||||
|
||||
"""
|
||||
|
||||
def __init__(self, pooled_function, args, kwargs):
|
||||
self.pooled_function = pooled_function
|
||||
@@ -38,6 +51,8 @@ class Promise(object):
|
||||
self._exception = None
|
||||
|
||||
def run(self):
|
||||
"""Calls the :attr:`pooled_function` callable."""
|
||||
|
||||
try:
|
||||
self._result = self.pooled_function(*self.args, **self.kwargs)
|
||||
|
||||
@@ -52,6 +67,19 @@ class Promise(object):
|
||||
self.run()
|
||||
|
||||
def result(self, timeout=None):
|
||||
"""Return the result of the ``Promise``.
|
||||
|
||||
Args:
|
||||
timeout (:obj:`float`, optional): Maximum time in seconds to wait for the result to be
|
||||
calculated. ``None`` means indefinite. Default is ``None``.
|
||||
|
||||
Returns:
|
||||
Returns the return value of :attr:`pooled_function` or ``None`` if the ``timeout``
|
||||
expires.
|
||||
|
||||
Raises:
|
||||
Any exception raised by :attr:`pooled_function`.
|
||||
"""
|
||||
self.done.wait(timeout=timeout)
|
||||
if self._exception is not None:
|
||||
raise self._exception # pylint: disable=raising-bad-type
|
||||
@@ -59,4 +87,6 @@ class Promise(object):
|
||||
|
||||
@property
|
||||
def exception(self):
|
||||
"""The exception raised by :attr:`pooled_function` or ``None`` if no exception has been
|
||||
raised (yet)."""
|
||||
return self._exception
|
||||
|
||||
+55
-17
@@ -17,11 +17,12 @@
|
||||
# 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 methods to make POST and GET requests."""
|
||||
import logging
|
||||
import os
|
||||
import socket
|
||||
import sys
|
||||
import logging
|
||||
import warnings
|
||||
from builtins import str # For PY2
|
||||
|
||||
try:
|
||||
import ujson as json
|
||||
@@ -40,12 +41,14 @@ except ImportError: # pragma: no cover
|
||||
"how to properly install.")
|
||||
raise
|
||||
|
||||
from telegram import (InputFile, TelegramError)
|
||||
from telegram import (InputFile, TelegramError, InputMedia)
|
||||
from telegram.error import (Unauthorized, NetworkError, TimedOut, BadRequest, ChatMigrated,
|
||||
RetryAfter, InvalidToken)
|
||||
|
||||
logging.getLogger('urllib3').setLevel(logging.WARNING)
|
||||
|
||||
USER_AGENT = 'Python Telegram Bot (https://github.com/python-telegram-bot/python-telegram-bot)'
|
||||
|
||||
|
||||
class Request(object):
|
||||
"""
|
||||
@@ -83,9 +86,12 @@ class Request(object):
|
||||
|
||||
# TODO: Support other platforms like mac and windows.
|
||||
if 'linux' in sys.platform:
|
||||
sockopts.append((socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, 120))
|
||||
sockopts.append((socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, 30))
|
||||
sockopts.append((socket.IPPROTO_TCP, socket.TCP_KEEPCNT, 8))
|
||||
sockopts.append((socket.IPPROTO_TCP,
|
||||
socket.TCP_KEEPIDLE, 120)) # pylint: disable=no-member
|
||||
sockopts.append((socket.IPPROTO_TCP,
|
||||
socket.TCP_KEEPINTVL, 30)) # pylint: disable=no-member
|
||||
sockopts.append((socket.IPPROTO_TCP,
|
||||
socket.TCP_KEEPCNT, 8)) # pylint: disable=no-member
|
||||
|
||||
self._con_pool_size = con_pool_size
|
||||
|
||||
@@ -145,9 +151,14 @@ class Request(object):
|
||||
dict: A JSON parsed as Python dict with results - on error this dict will be empty.
|
||||
|
||||
"""
|
||||
decoded_s = json_data.decode('utf-8')
|
||||
|
||||
try:
|
||||
decoded_s = json_data.decode('utf-8')
|
||||
data = json.loads(decoded_s)
|
||||
except UnicodeDecodeError:
|
||||
logging.getLogger(__name__).debug(
|
||||
'Logging raw invalid UTF-8 response:\n%r', json_data)
|
||||
raise TelegramError('Server response could not be decoded using UTF-8')
|
||||
except ValueError:
|
||||
raise TelegramError('Invalid server response')
|
||||
|
||||
@@ -185,6 +196,8 @@ class Request(object):
|
||||
if 'headers' not in kwargs:
|
||||
kwargs['headers'] = {}
|
||||
kwargs['headers']['connection'] = 'keep-alive'
|
||||
# Also set our user agent
|
||||
kwargs['headers']['user-agent'] = USER_AGENT
|
||||
|
||||
try:
|
||||
resp = self._con_pool.request(*args, **kwargs)
|
||||
@@ -242,6 +255,7 @@ class Request(object):
|
||||
|
||||
def post(self, url, data, timeout=None):
|
||||
"""Request an URL.
|
||||
|
||||
Args:
|
||||
url (:obj:`str`): The web location we want to retrieve.
|
||||
data (dict[str, str|int]): A dict of key/value pairs. Note: On py2.7 value is unicode.
|
||||
@@ -258,18 +272,41 @@ class Request(object):
|
||||
if timeout is not None:
|
||||
urlopen_kwargs['timeout'] = Timeout(read=timeout, connect=self._connect_timeout)
|
||||
|
||||
if InputFile.is_inputfile(data):
|
||||
data = InputFile(data)
|
||||
result = self._request_wrapper(
|
||||
'POST', url, body=data.to_form(), headers=data.headers, **urlopen_kwargs)
|
||||
# Are we uploading files?
|
||||
files = False
|
||||
|
||||
for key, val in data.copy().items():
|
||||
if isinstance(val, InputFile):
|
||||
# Convert the InputFile to urllib3 field format
|
||||
data[key] = val.field_tuple
|
||||
files = True
|
||||
elif isinstance(val, (float, int)):
|
||||
# Urllib3 doesn't like floats it seems
|
||||
data[key] = str(val)
|
||||
elif key == 'media':
|
||||
# One media or multiple
|
||||
if isinstance(val, InputMedia):
|
||||
# Attach and set val to attached name
|
||||
data[key] = val.to_json()
|
||||
if isinstance(val.media, InputFile):
|
||||
data[val.media.attach] = val.media.field_tuple
|
||||
else:
|
||||
# Attach and set val to attached name for all
|
||||
media = []
|
||||
for m in val:
|
||||
media.append(m.to_dict())
|
||||
if isinstance(m.media, InputFile):
|
||||
data[m.media.attach] = m.media.field_tuple
|
||||
data[key] = json.dumps(media)
|
||||
files = True
|
||||
|
||||
# Use multipart upload if we're uploading files, otherwise use JSON
|
||||
if files:
|
||||
result = self._request_wrapper('POST', url, fields=data, **urlopen_kwargs)
|
||||
else:
|
||||
data = json.dumps(data)
|
||||
result = self._request_wrapper(
|
||||
'POST',
|
||||
url,
|
||||
body=data.encode(),
|
||||
headers={'Content-Type': 'application/json'},
|
||||
**urlopen_kwargs)
|
||||
result = self._request_wrapper('POST', url,
|
||||
body=json.dumps(data).encode('utf-8'),
|
||||
headers={'Content-Type': 'application/json'})
|
||||
|
||||
return self._parse(result)
|
||||
|
||||
@@ -291,6 +328,7 @@ class Request(object):
|
||||
|
||||
def download(self, url, filename, timeout=None):
|
||||
"""Download a file by its URL.
|
||||
|
||||
Args:
|
||||
url (str): The web location we want to retrieve.
|
||||
timeout (:obj:`int` | :obj:`float`): If this value is specified, use it as the read
|
||||
|
||||
Vendored
+1
-1
Submodule telegram/vendor/ptb_urllib3 updated: 06d04e451f...2c6446aa6c
+1
-1
@@ -17,4 +17,4 @@
|
||||
# You should have received a copy of the GNU Lesser Public License
|
||||
# along with this program. If not, see [http://www.gnu.org/licenses/].
|
||||
|
||||
__version__ = '10.0.0'
|
||||
__version__ = '11.1.0'
|
||||
|
||||
+28
-2
@@ -26,7 +26,7 @@ from time import sleep
|
||||
import pytest
|
||||
|
||||
from telegram import Bot
|
||||
from telegram.ext import Dispatcher, JobQueue
|
||||
from telegram.ext import Dispatcher, JobQueue, Updater
|
||||
from tests.bots import get_bot
|
||||
|
||||
TRAVIS = os.getenv('TRAVIS', False)
|
||||
@@ -34,6 +34,10 @@ TRAVIS = os.getenv('TRAVIS', False)
|
||||
if TRAVIS:
|
||||
pytest_plugins = ['tests.travis_fold']
|
||||
|
||||
# THIS KEY IS OBVIOUSLY COMPROMISED
|
||||
# DO NOT USE IN PRODUCTION!
|
||||
PRIVATE_KEY = b"-----BEGIN RSA PRIVATE KEY-----\r\nMIIEowIBAAKCAQEA0AvEbNaOnfIL3GjB8VI4M5IaWe+GcK8eSPHkLkXREIsaddum\r\nwPBm/+w8lFYdnY+O06OEJrsaDtwGdU//8cbGJ/H/9cJH3dh0tNbfszP7nTrQD+88\r\nydlcYHzClaG8G+oTe9uEZSVdDXj5IUqR0y6rDXXb9tC9l+oSz+ShYg6+C4grAb3E\r\nSTv5khZ9Zsi/JEPWStqNdpoNuRh7qEYc3t4B/a5BH7bsQENyJSc8AWrfv+drPAEe\r\njQ8xm1ygzWvJp8yZPwOIYuL+obtANcoVT2G2150Wy6qLC0bD88Bm40GqLbSazueC\r\nRHZRug0B9rMUKvKc4FhG4AlNzBCaKgIcCWEqKwIDAQABAoIBACcIjin9d3Sa3S7V\r\nWM32JyVF3DvTfN3XfU8iUzV7U+ZOswA53eeFM04A/Ly4C4ZsUNfUbg72O8Vd8rg/\r\n8j1ilfsYpHVvphwxaHQlfIMa1bKCPlc/A6C7b2GLBtccKTbzjARJA2YWxIaqk9Nz\r\nMjj1IJK98i80qt29xRnMQ5sqOO3gn2SxTErvNchtBiwOH8NirqERXig8VCY6fr3n\r\nz7ZImPU3G/4qpD0+9ULrt9x/VkjqVvNdK1l7CyAuve3D7ha3jPMfVHFtVH5gqbyp\r\nKotyIHAyD+Ex3FQ1JV+H7DkP0cPctQiss7OiO9Zd9C1G2OrfQz9el7ewAPqOmZtC\r\nKjB3hUECgYEA/4MfKa1cvaCqzd3yUprp1JhvssVkhM1HyucIxB5xmBcVLX2/Kdhn\r\nhiDApZXARK0O9IRpFF6QVeMEX7TzFwB6dfkyIePsGxputA5SPbtBlHOvjZa8omMl\r\nEYfNa8x/mJkvSEpzvkWPascuHJWv1cEypqphu/70DxubWB5UKo/8o6cCgYEA0HFy\r\ncgwPMB//nltHGrmaQZPFT7/Qgl9ErZT3G9S8teWY4o4CXnkdU75tBoKAaJnpSfX3\r\nq8VuRerF45AFhqCKhlG4l51oW7TUH50qE3GM+4ivaH5YZB3biwQ9Wqw+QyNLAh/Q\r\nnS4/Wwb8qC9QuyEgcCju5lsCaPEXZiZqtPVxZd0CgYEAshBG31yZjO0zG1TZUwfy\r\nfN3euc8mRgZpSdXIHiS5NSyg7Zr8ZcUSID8jAkJiQ3n3OiAsuq1MGQ6kNa582kLT\r\nFPQdI9Ea8ahyDbkNR0gAY9xbM2kg/Gnro1PorH9PTKE0ekSodKk1UUyNrg4DBAwn\r\nqE6E3ebHXt/2WmqIbUD653ECgYBQCC8EAQNX3AFegPd1GGxU33Lz4tchJ4kMCNU0\r\nN2NZh9VCr3nTYjdTbxsXU8YP44CCKFG2/zAO4kymyiaFAWEOn5P7irGF/JExrjt4\r\nibGy5lFLEq/HiPtBjhgsl1O0nXlwUFzd7OLghXc+8CPUJaz5w42unqT3PBJa40c3\r\nQcIPdQKBgBnSb7BcDAAQ/Qx9juo/RKpvhyeqlnp0GzPSQjvtWi9dQRIu9Pe7luHc\r\nm1Img1EO1OyE3dis/rLaDsAa2AKu1Yx6h85EmNjavBqP9wqmFa0NIQQH8fvzKY3/\r\nP8IHY6009aoamLqYaexvrkHVq7fFKiI6k8myMJ6qblVNFv14+KXU\r\n-----END RSA PRIVATE KEY-----" # noqa: E501
|
||||
|
||||
|
||||
@pytest.fixture(scope='session')
|
||||
def bot_info():
|
||||
@@ -42,7 +46,7 @@ def bot_info():
|
||||
|
||||
@pytest.fixture(scope='session')
|
||||
def bot(bot_info):
|
||||
return Bot(bot_info['token'])
|
||||
return Bot(bot_info['token'], private_key=PRIVATE_KEY)
|
||||
|
||||
|
||||
@pytest.fixture(scope='session')
|
||||
@@ -105,6 +109,28 @@ def dp(_dp):
|
||||
Dispatcher._Dispatcher__singleton_semaphore.release()
|
||||
|
||||
|
||||
@pytest.fixture(scope='function')
|
||||
def updater(bot):
|
||||
up = Updater(bot=bot, workers=2)
|
||||
yield up
|
||||
if up.running:
|
||||
up.stop()
|
||||
|
||||
|
||||
@pytest.fixture(scope='function')
|
||||
def thumb_file():
|
||||
f = open(u'tests/data/thumb.jpg', 'rb')
|
||||
yield f
|
||||
f.close()
|
||||
|
||||
|
||||
@pytest.fixture(scope='class')
|
||||
def class_thumb_file():
|
||||
f = open(u'tests/data/thumb.jpg', 'rb')
|
||||
yield f
|
||||
f.close()
|
||||
|
||||
|
||||
def pytest_configure(config):
|
||||
if sys.version_info >= (3,):
|
||||
config.addinivalue_line('filterwarnings', 'ignore::ResourceWarning')
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 2.7 KiB |
+69
-18
@@ -18,58 +18,109 @@
|
||||
# along with this program. If not, see [http://www.gnu.org/licenses/].
|
||||
|
||||
import pytest
|
||||
from flaky import flaky
|
||||
|
||||
from telegram import PhotoSize, Animation, Voice
|
||||
|
||||
|
||||
@pytest.fixture(scope='class')
|
||||
def thumb():
|
||||
return PhotoSize(height=50, file_size=1613, file_id='AAQEABPQUWQZAAT7gZuQAAH0bd93VwACAg',
|
||||
width=90)
|
||||
@pytest.fixture(scope='function')
|
||||
def animation_file():
|
||||
f = open('tests/data/game.gif', 'rb')
|
||||
yield f
|
||||
f.close()
|
||||
|
||||
|
||||
@pytest.fixture(scope='class')
|
||||
def animation(thumb, bot):
|
||||
return Animation(TestAnimation.animation_file_id, thumb=thumb.to_dict(),
|
||||
file_name=TestAnimation.file_name, mime_type=TestAnimation.mime_type,
|
||||
file_size=TestAnimation.file_size, bot=bot)
|
||||
def animation(bot, chat_id):
|
||||
with open('tests/data/game.gif', 'rb') as f:
|
||||
return bot.send_animation(chat_id, animation=f, timeout=50,
|
||||
thumb=open('tests/data/thumb.jpg', 'rb')).animation
|
||||
|
||||
|
||||
class TestAnimation(object):
|
||||
animation_file_id = 'CgADBAADFQEAAny4rAUgukhiTv2TWwI'
|
||||
animation_file_id = 'CgADAQADngIAAuyVeEez0xRovKi9VAI'
|
||||
width = 320
|
||||
height = 180
|
||||
duration = 1
|
||||
file_name = 'game.gif.mp4'
|
||||
mime_type = 'video/mp4'
|
||||
file_size = 4008
|
||||
file_size = 4135
|
||||
caption = "Test *animation*"
|
||||
|
||||
def test_de_json(self, bot, thumb):
|
||||
def test_creation(self, animation):
|
||||
assert isinstance(animation, Animation)
|
||||
assert isinstance(animation.file_id, str)
|
||||
assert animation.file_id is not ''
|
||||
|
||||
def test_expected_values(self, animation):
|
||||
assert animation.file_size == self.file_size
|
||||
assert animation.mime_type == self.mime_type
|
||||
assert animation.file_name == self.file_name
|
||||
assert isinstance(animation.thumb, PhotoSize)
|
||||
|
||||
@flaky(3, 1)
|
||||
@pytest.mark.timeout(10)
|
||||
def test_send_all_args(self, bot, chat_id, animation_file, animation, thumb_file):
|
||||
message = bot.send_animation(chat_id, animation_file, duration=self.duration,
|
||||
width=self.width, height=self.height, caption=self.caption,
|
||||
parse_mode='Markdown', disable_notification=False,
|
||||
filename=self.file_name, thumb=thumb_file)
|
||||
|
||||
assert isinstance(message.animation, Animation)
|
||||
assert isinstance(message.animation.file_id, str)
|
||||
assert message.animation.file_id != ''
|
||||
assert message.animation.file_name == animation.file_name
|
||||
assert message.animation.mime_type == animation.mime_type
|
||||
assert message.animation.file_size == animation.file_size
|
||||
assert message.animation.thumb.width == 50
|
||||
assert message.animation.thumb.height == 50
|
||||
|
||||
@flaky(3, 1)
|
||||
def test_resend(self, bot, chat_id, animation):
|
||||
message = bot.send_animation(chat_id, animation.file_id)
|
||||
|
||||
assert isinstance(message.animation, Animation)
|
||||
assert isinstance(message.animation.file_id, str)
|
||||
assert message.animation.file_id != ''
|
||||
assert message.animation.file_name == animation.file_name
|
||||
assert message.animation.mime_type == animation.mime_type
|
||||
assert message.animation.file_size == animation.file_size
|
||||
|
||||
def test_de_json(self, bot, animation):
|
||||
json_dict = {
|
||||
'file_id': self.animation_file_id,
|
||||
'thumb': thumb.to_dict(),
|
||||
'width': self.width,
|
||||
'height': self.height,
|
||||
'duration': self.duration,
|
||||
'thumb': animation.thumb.to_dict(),
|
||||
'file_name': self.file_name,
|
||||
'mime_type': self.mime_type,
|
||||
'file_size': self.file_size
|
||||
}
|
||||
animation = Animation.de_json(json_dict, bot)
|
||||
assert animation.file_id == self.animation_file_id
|
||||
assert animation.thumb == thumb
|
||||
assert animation.thumb == animation.thumb
|
||||
assert animation.file_name == self.file_name
|
||||
assert animation.mime_type == self.mime_type
|
||||
assert animation.file_size == self.file_size
|
||||
|
||||
def test_to_dict(self, animation, thumb):
|
||||
def test_to_dict(self, animation):
|
||||
animation_dict = animation.to_dict()
|
||||
|
||||
assert isinstance(animation_dict, dict)
|
||||
assert animation_dict['file_id'] == animation.file_id
|
||||
assert animation_dict['thumb'] == thumb.to_dict()
|
||||
assert animation_dict['width'] == animation.width
|
||||
assert animation_dict['height'] == animation.height
|
||||
assert animation_dict['duration'] == animation.duration
|
||||
assert animation_dict['thumb'] == animation.thumb.to_dict()
|
||||
assert animation_dict['file_name'] == animation.file_name
|
||||
assert animation_dict['mime_type'] == animation.mime_type
|
||||
assert animation_dict['file_size'] == animation.file_size
|
||||
|
||||
def test_equality(self):
|
||||
a = Animation(self.animation_file_id)
|
||||
b = Animation(self.animation_file_id)
|
||||
d = Animation('')
|
||||
a = Animation(self.animation_file_id, self.height, self.width, self.duration)
|
||||
b = Animation(self.animation_file_id, self.height, self.width, self.duration)
|
||||
d = Animation('', 0, 0, 0)
|
||||
e = Voice(self.animation_file_id, 0)
|
||||
|
||||
assert a == b
|
||||
|
||||
+17
-5
@@ -34,7 +34,8 @@ def audio_file():
|
||||
@pytest.fixture(scope='class')
|
||||
def audio(bot, chat_id):
|
||||
with open('tests/data/telegram.mp3', 'rb') as f:
|
||||
return bot.send_audio(chat_id, audio=f, timeout=50).audio
|
||||
return bot.send_audio(chat_id, audio=f, timeout=50,
|
||||
thumb=open('tests/data/thumb.jpg', 'rb')).audio
|
||||
|
||||
|
||||
class TestAudio(object):
|
||||
@@ -47,6 +48,9 @@ class TestAudio(object):
|
||||
audio_file_url = 'https://goo.gl/3En24v'
|
||||
mime_type = 'audio/mpeg'
|
||||
file_size = 122920
|
||||
thumb_file_size = 2744
|
||||
thumb_width = 50
|
||||
thumb_height = 50
|
||||
|
||||
def test_creation(self, audio):
|
||||
# Make sure file has been uploaded.
|
||||
@@ -60,14 +64,17 @@ class TestAudio(object):
|
||||
assert audio.title is None
|
||||
assert audio.mime_type == self.mime_type
|
||||
assert audio.file_size == self.file_size
|
||||
assert audio.thumb.file_size == self.thumb_file_size
|
||||
assert audio.thumb.width == self.thumb_width
|
||||
assert audio.thumb.height == self.thumb_height
|
||||
|
||||
@flaky(3, 1)
|
||||
@pytest.mark.timeout(10)
|
||||
def test_send_all_args(self, bot, chat_id, audio_file):
|
||||
def test_send_all_args(self, bot, chat_id, audio_file, thumb_file):
|
||||
message = bot.send_audio(chat_id, audio=audio_file, caption=self.caption,
|
||||
duration=self.duration, performer=self.performer,
|
||||
title=self.title, disable_notification=False,
|
||||
parse_mode='Markdown')
|
||||
parse_mode='Markdown', thumb=thumb_file)
|
||||
|
||||
assert message.caption == self.caption.replace('*', '')
|
||||
|
||||
@@ -79,6 +86,9 @@ class TestAudio(object):
|
||||
assert message.audio.title == self.title
|
||||
assert message.audio.mime_type == self.mime_type
|
||||
assert message.audio.file_size == self.file_size
|
||||
assert message.audio.thumb.file_size == self.thumb_file_size
|
||||
assert message.audio.thumb.width == self.thumb_width
|
||||
assert message.audio.thumb.height == self.thumb_height
|
||||
|
||||
@flaky(3, 1)
|
||||
@pytest.mark.timeout(10)
|
||||
@@ -122,14 +132,15 @@ class TestAudio(object):
|
||||
message = bot.send_audio(audio=audio, chat_id=chat_id)
|
||||
assert message
|
||||
|
||||
def test_de_json(self, bot):
|
||||
def test_de_json(self, bot, audio):
|
||||
json_dict = {'file_id': 'not a file id',
|
||||
'duration': self.duration,
|
||||
'performer': self.performer,
|
||||
'title': self.title,
|
||||
'caption': self.caption,
|
||||
'mime_type': self.mime_type,
|
||||
'file_size': self.file_size}
|
||||
'file_size': self.file_size,
|
||||
'thumb': audio.thumb.to_dict()}
|
||||
json_audio = Audio.de_json(json_dict, bot)
|
||||
|
||||
assert json_audio.file_id == 'not a file id'
|
||||
@@ -138,6 +149,7 @@ class TestAudio(object):
|
||||
assert json_audio.title == self.title
|
||||
assert json_audio.mime_type == self.mime_type
|
||||
assert json_audio.file_size == self.file_size
|
||||
assert json_audio.thumb == audio.thumb
|
||||
|
||||
def test_to_dict(self, audio):
|
||||
audio_dict = audio.to_dict()
|
||||
|
||||
+11
-3
@@ -104,8 +104,9 @@ class TestBot(object):
|
||||
# Considering that the first message is old enough
|
||||
bot.delete_message(chat_id=chat_id, message_id=1)
|
||||
|
||||
# send_photo, send_audio, send_document, send_sticker, send_video, send_voice, send_video_note
|
||||
# and send_media_group are tested in their respective test modules. No need to duplicate here.
|
||||
# send_photo, send_audio, send_document, send_sticker, send_video, send_voice, send_video_note,
|
||||
# send_media_group and send_animation are tested in their respective test modules. No need to
|
||||
# duplicate here.
|
||||
|
||||
@flaky(3, 1)
|
||||
@pytest.mark.timeout(10)
|
||||
@@ -114,14 +115,19 @@ class TestBot(object):
|
||||
latitude = -23.691288
|
||||
title = 'title'
|
||||
address = 'address'
|
||||
foursquare_id = 'foursquare id'
|
||||
foursquare_type = 'foursquare type'
|
||||
message = bot.send_venue(chat_id=chat_id, title=title, address=address, latitude=latitude,
|
||||
longitude=longitude)
|
||||
longitude=longitude, foursquare_id=foursquare_id,
|
||||
foursquare_type=foursquare_type)
|
||||
|
||||
assert message.venue
|
||||
assert message.venue.title == title
|
||||
assert message.venue.address == address
|
||||
assert message.venue.location.latitude == latitude
|
||||
assert message.venue.location.longitude == longitude
|
||||
assert message.venue.foursquare_id == foursquare_id
|
||||
assert message.venue.foursquare_type == foursquare_type
|
||||
|
||||
@flaky(3, 1)
|
||||
@pytest.mark.timeout(10)
|
||||
@@ -258,6 +264,8 @@ class TestBot(object):
|
||||
|
||||
assert message.caption == 'new_caption'
|
||||
|
||||
# edit_message_media is tested in test_inputmedia
|
||||
|
||||
@flaky(3, 1)
|
||||
@pytest.mark.timeout(10)
|
||||
def test_edit_message_caption_with_parse_mode(self, bot, media_message):
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user