Compare commits

...

32 Commits

Author SHA1 Message Date
Hinrich Mahler a769861b32 Bump version to v13.11 2022-05-26 15:15:40 +02:00
Bibo-Joshi 0a00a821cb Documentation Improvements (#3029)
Co-authored-by: Hinrich Mahler <22366557+Bibo-Joshi@users.noreply.github.com>

Co-authored-by: Sukka <isukkaw@gmail.com>
2022-05-26 11:10:45 +02:00
Poolitzer ef2a0527fe API 6.0 (#3027)
Co-authored-by: Harshil <37377066+harshil21@users.noreply.github.com>
2022-05-25 17:40:01 +02:00
Hinrich Mahler 92cb6f3ae8 Bump version to v13.11 2022-02-02 21:16:36 +01:00
Harshil a35ecf4065 API 5.7 (#2881) 2022-02-02 21:05:46 +01:00
Hinrich Mahler ade1529986 Bump version to v13.10 2022-01-03 08:36:27 +01:00
Harshil e6d9f3d057 Update Copyright to 2022 (#2836) 2022-01-03 08:15:18 +01:00
Harshil 98bf378c6e API 5.6 (#2835) 2022-01-03 08:13:33 +01:00
Poolitzer c4b413ef9e Update Documentation of BotCommand (#2820) 2021-12-17 16:12:34 +01:00
Hinrich Mahler a9dd2b1746 Bump version to v13.9 2021-12-11 15:44:21 +01:00
Bibo-Joshi cb95868c4a Api 5.5 (#2809)
Co-authored-by: poolitzer <github@poolitzer.eu>
Co-authored-by: Harshil <37377066+harshil21@users.noreply.github.com>
2021-12-11 15:21:56 +01:00
Bibo-Joshi 2f6c4075c8 Adjust Automated Locking of Inactive Closed Threads (#2775) 2021-11-10 21:16:59 +01:00
Hinrich Mahler c53dc7dae4 Bump version to v13.8.1 2021-11-08 20:09:23 +01:00
Bibo-Joshi 8b3ea5ce56 Add ChatJoinRequest(Handler) to Docs (#2771) 2021-11-08 19:56:57 +01:00
Hinrich Mahler 51a4a6664c Bump version to v13.8 2021-11-08 19:12:10 +01:00
Bibo-Joshi e4dc80f41d API 5.4 (#2767)
Co-authored-by: poolitzer <25934244+Poolitzer@users.noreply.github.com>
2021-11-08 19:02:20 +01:00
Abshar Mohammed Aslam bc7c422a11 Create Issue Template Forms (#2689) 2021-10-03 20:08:04 +02:00
Yan c3e3bb77e5 Fix camelCase Functions in ExtBot (#2659)
Co-authored-by: Bibo-Joshi <22366557+Bibo-Joshi@users.noreply.github.com>
2021-09-15 17:07:11 +02:00
DonalDuck004 a25c76e6a3 Fix Empty Captions not Being Passed by Bot.copy_message (#2651) 2021-09-09 07:50:04 +02:00
Mehdi 0c5085022c Fix Setting Thumbs When Uploading A Single File (#2583)
* Update request.py

If the media has a thumb, we also need to attach it to the data.

* Add test

* Editing syntax

* Debug test

* update request.py

* Update test_inputmedia.py

* Update test_inputmedia.py

* Update test_inputmedia.py

Fix test.

* Update AUTHORS.rst

Adding my name!

* Update AUTHORS.rst
2021-08-11 08:34:47 +02:00
Bibo-Joshi 1fdaaac809 Fix Bug in BasePersistence.insert/replace_bot for Objects with __dict__ not in __slots__ (#2603)
* More special cases with slots

* Fix failing tests
2021-07-24 17:17:25 +02:00
Hinrich Mahler bcec6f03cb Bump version to v13.7 2021-07-01 18:03:38 +02:00
Bibo-Joshi ed147813ab API 5.3 (#2572)
* BotCommandScopes

* pre-commit

* typo

Co-authored-by: Harshil <37377066+harshil21@users.noreply.github.com>

* rename kickChatMember & getChatMembersCount method

Signed-off-by: starry69 <starry369126@outlook.com>

* add `language_code` and `scope` to `get/set_my_commands`

and add `delete_my_commands()`

* add `input_field_placeholder` to replykeyboardmarkup.py and forcereply.py

also improved/fixed docs along the way

* showcase `input_field_placeholder` in conversationbot.py

* review 1

'i will not go away' has gone away 😢

* deprecate `Bot.commands` and make sure its only used for default scope

* review 2 (use constants for scope)

* Review

Signed-off-by: starry69 <starry369126@outlook.com>

* doc updates

* New ChatMember classes

Signed-off-by: starry69 <starry369126@outlook.com>

* Address review

Signed-off-by: starry69 <starry369126@outlook.com>

* add versionadded tags again

Signed-off-by: starry69 <starry369126@outlook.com>

* Improve tests & add a deprecation note to ChatMember

* test_official

* Documentation tweaks

* Bump bot api version number

* but bot

* Rename chat shortcuts

Signed-off-by: starry69 <starry369126@outlook.com>

* deepsource

Signed-off-by: starry69 <starry369126@outlook.com>

* add missing slot in botcommandscope & missing slot tests

Co-authored-by: Harshil <37377066+harshil21@users.noreply.github.com>
Co-authored-by: starry69 <starry369126@outlook.com>
Co-authored-by: Harshil <ilovebhagwan@gmail.com>
2021-07-01 17:45:19 +02:00
Bibo-Joshi 4315225642 Type Hinting Fixes (#2552)
* Fixe overload signatures for ContextTypes

* more fixing for contexttypes
2021-07-01 17:43:59 +02:00
Bibo-Joshi a75dffd4a8 Doc Fixes (#2551)
* Document ExtBot.insert_callbakc_data

* fix duplicate object descriptions

Fixed by removing `:undoc-members:` in the affected classes.
Closes https://github.com/sphinx-doc/sphinx/issues/9294

* fix incorrect shortcut docstrings in user.py

* fix object type in forcereply.py

* fix discuss bot link in loginurl.py

* document that message is None for (my)_chat_member

in `effective_message`

* numerous persistence rendering fixes

* move docstring from property setter to property

* Revert "fix object type in forcereply.py"

This reverts commit 012663e0c3.

* Document comparison of jobs

* Update min python version to 3.6.8

* remove old note from chat.py + some return msg fixes

* fix colon placement

Co-authored-by: Harshil <ilovebhagwan@gmail.com>
Co-authored-by: Harshil <37377066+harshil21@users.noreply.github.com>
2021-07-01 17:34:23 +02:00
Harshil fce2993d21 Improve Deprecation Warning for __slots__ (#2574)
* add stacklevel to `set_new_attribute_deprecated`

* detail warning message and change stacklevel
2021-06-29 18:10:08 +02:00
Harshil 9aec8deec6 Stabilize CI (#2575)
* attempt 'surely this one' on fixing test_idle and test_depr_warnings

* remove unused filterwarnings
2021-06-26 22:19:59 +02:00
Bibo-Joshi ec3026673b Fix Coverage Configuration (#2571)
* remove possibly malicious line from config

* exclude overload signatures from coverage
2021-06-25 09:02:46 +02:00
zeroone2numeral2 105f1ccdb5 Better Exception-Handling for BasePersistence.replace/insert_bot (#2564)
* Catch exceptions raised while copying __dict__/__slots__ in BasePersistence.replace/insert_bot()

Also updated the docstrings to reflect the changes in behavior with unexpected errors

* Tests: added to CustomClass immutable object that would trigger a setattr() exception

* Tests: added new uuid_ property to own CustomClass methods

* Updated AUTHORS.rst

* Revert "Tests: added new uuid_ property to own CustomClass methods"

This reverts commit 9e67463cf7.

* Revert "Tests: added to CustomClass immutable object that would trigger a setattr() exception"

This reverts commit 1c258304

* Removed unneeded Exception cast to string

f-string will perform the string-ification on their own

* Removed another unneeded Exception cast to string

* Added test to parse unparsable objects in __dict__ or __slots__

* Applied black and pylint style suggestions

All lint tests passed

* Fix typo

Co-authored-by: Harshil <37377066+harshil21@users.noreply.github.com>

Co-authored-by: Bibo-Joshi <hinrich.mahler@freenet.de>
Co-authored-by: Harshil <37377066+harshil21@users.noreply.github.com>
2021-06-20 22:14:05 +02:00
Bibo-Joshi 52ce03929b Fix Bug in BasePersistence.insert/replace_bot for Objects with __dict__ in their slots (#2561)
* Handle objects with __dict__ in __slots__

* Rework
2021-06-13 15:07:40 +02:00
Bibo-Joshi ac4768155f Remove Incorrect Warning About Defaults and ExtBot (#2553)
* Don't throw warning when passing defaults to ExtBot

* Review
2021-06-10 12:03:44 +02:00
Harshil d08172b4b0 Remove Deprecated pass_args from Deeplinking Example (#2550) 2021-06-07 09:05:17 +02:00
358 changed files with 7863 additions and 1129 deletions
+76
View File
@@ -0,0 +1,76 @@
name: Bug Report
description: Create a report to help us improve
title: "[BUG]"
labels: ["bug :bug:"]
body:
- type: markdown
attributes:
value: |
Thanks for reporting issues of python-telegram-bot!
Use this template to notify us if you found a bug.
To make it easier for us to help you please enter detailed information below.
Please note, we only support the latest version of python-telegram-bot and master branch. Please make sure to upgrade & recreate the issue on the latest version prior to opening an issue.
- type: textarea
id: steps-to-reproduce
attributes:
label: Steps to Reproduce
value: |
1.
2.
3.
validations:
required: true
- type: textarea
id: expected-behaviour
attributes:
label: Expected behaviour
description: Tell us what should happen
validations:
required: true
- type: textarea
id: actual-behaviour
attributes:
label: Actual behaviour
description: Tell us what happens instead
validations:
required: true
- type: markdown
attributes:
value: "### Configuration"
- type: input
id: operating-system
attributes:
label: Operating System
validations:
required: true
- type: textarea
id: versions
attributes:
label: Version of Python, python-telegram-bot & dependencies
description: Paste the output of `$ python -m telegram` here. This will be automatically formatted into code, so no need for backticks.
render: shell
validations:
required: true
- type: textarea
id: logs
attributes:
label: Relevant log output
description: Insert logs here (if necessary). This will be automatically formatted into code, so no need for backticks.
render: python
- type: textarea
id: additional-context
attributes:
label: Additional Context
description: You may provide any other additional context to the bug here.
-43
View File
@@ -1,43 +0,0 @@
---
name: Bug report
about: Create a report to help us improve
title: "[BUG]"
labels: 'bug :bug:'
assignees: ''
---
<!--
Thanks for reporting issues of python-telegram-bot!
Use this template to notify us if you found a bug.
To make it easier for us to help you please enter detailed information below.
Please note, we only support the latest version of python-telegram-bot and
master branch. Please make sure to upgrade & recreate the issue on the latest
version prior to opening an issue.
-->
### Steps to reproduce
1.
2.
3.
### Expected behaviour
Tell us what should happen
### Actual behaviour
Tell us what happens instead
### Configuration
**Operating System:**
**Version of Python, python-telegram-bot & dependencies:**
``$ python -m telegram``
### Logs
Insert logs here (if necessary)
@@ -0,0 +1,37 @@
name: Feature Request
description: Suggest an idea for this project
title: "[FEATURE]"
labels: ["enhancement"]
body:
- type: textarea
id: related-problem
attributes:
label: "What kind of feature are you missing? Where do you notice a shortcoming of PTB?"
description: "A clear and concise description of what the problem is."
placeholder: "Example: I want to do X, but there is no way to do it."
validations:
required: true
- type: textarea
id: solution
attributes:
label: "Describe the solution you'd like"
description: "A clear and concise description of what you want to happen."
placeholder: "Example: I think it would be nice if you would add feature Y so I can do X."
validations:
required: true
- type: textarea
id: alternatives
attributes:
label: "Describe alternatives you've considered"
description: "A clear and concise description of any alternative solutions or features you've considered."
placeholder: "Example: I considered Z to be able to do X, but that didn't work because..."
- type: textarea
id: additional-context
attributes:
label: "Additional context"
description: "Add any other context or screenshots about the feature request here."
placeholder: "Example: Here's a photo of my cat!"
-24
View File
@@ -1,24 +0,0 @@
---
name: Feature request
about: Suggest an idea for this project
title: "[FEATURE]"
labels: enhancement
assignees: ''
---
#### Is your feature request related to a problem? Please describe.
A clear and concise description of what the problem is.
Ex. *I want to do X, but there is no way to do it.*
#### Describe the solution you'd like
A clear and concise description of what you want to happen.
Ex. *I think it would be nice if you would add feature Y so it will make it easier.*
#### Describe alternatives you've considered
A clear and concise description of any alternative solutions or features you've considered.
Ex. *I considered Z, but that didn't work because...*
#### Additional context
Add any other context or screenshots about the feature request here.
Ex. *Here's a photo of my cat!*
-29
View File
@@ -1,29 +0,0 @@
---
name: Question
about: Get help with errors or general questions
title: "[QUESTION]"
labels: question
assignees: ''
---
<!--
Hey there, you have a question? We are happy to answer. Please make sure no similar question was opened already.
To make it easier for us to help you, please read this article https://git.io/JURJO and try to follow the template below as closely as possible.
Please mind that there is also a users' Telegram group at https://t.me/pythontelegrambotgroup for questions about the library. Questions asked there might be answered quicker than here. Moreover, GitHub Discussions at https://git.io/JG3rk offer a slightly better format to discuss usage questions.
-->
### Issue I am facing
Please describe the issue here in as much detail as possible
### Traceback to the issue
```
put it here
```
### Related part of your code
```python
put it here
```
+68
View File
@@ -0,0 +1,68 @@
name: Question
description: Get help with errors or general questions
title: "[QUESTION]"
labels: ["question"]
body:
- type: markdown
attributes:
value: |
Hey there, you have a question? We are happy to answer. Please make sure no similar question was opened already.
To make it easier for us to help you, please read this [article](https://github.com/python-telegram-bot/python-telegram-bot/wiki/Ask-Right).
Please mind that there is also a users' [Telegram group](https://t.me/pythontelegrambotgroup) for questions about the library. Questions asked there might be answered quicker than here. Moreover, [GitHub Discussions](https://github.com/python-telegram-bot/python-telegram-bot/discussions) offer a slightly better format to discuss usage questions.
- type: textarea
id: issue-faced
attributes:
label: "Issue I am facing"
description: "Please describe the issue here in as much detail as possible"
validations:
required: true
- type: textarea
id: traceback
attributes:
label: "Traceback to the issue"
description: "If you are facing a specific error message, please paste the traceback here. This will be automatically formatted into python code, so no need for backticks."
placeholder: |
Traceback (most recent call last):
File "/home/bot.py", line 1, in main
foo = bar()
...
telegram.error.BadRequest: Traceback not found
render: python
- type: textarea
id: related-code
attributes:
label: "Related part of your code"
description: "This will be automatically formatted into code (python), so no need for backticks."
placeholder: |
logging.basicConfig(
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO
)
logger = logging.getLogger(__name__)
render: python
- type: markdown
attributes:
value: "### Configuration"
- type: input
id: operating-system
attributes:
label: Operating System
validations:
required: true
- type: textarea
id: versions
attributes:
label: Version of Python, python-telegram-bot & dependencies
description: Paste the output of `$ python -m telegram` here. This will be automatically formatted into code, so no need for backticks.
render: shell
validations:
required: true
+1
View File
@@ -7,6 +7,7 @@ Hey! You're PRing? Cool! Please have a look at the below checklist. It's here to
- [ ] Added `.. versionadded:: version`, `.. versionchanged:: version` or `.. deprecated:: version` to the docstrings for user facing changes (for methods/class descriptions, arguments and attributes)
- [ ] Created new or adapted existing unit tests
- [ ] Added myself alphabetically to `AUTHORS.rst` (optional)
- [ ] Added new classes & modules to the docs
### If the PR contains API changes (otherwise, you can delete this passage)
+2 -2
View File
@@ -12,7 +12,7 @@ jobs:
- uses: dessant/lock-threads@v2.0.1
with:
github-token: ${{ github.token }}
issue-lock-inactive-days: '1'
issue-lock-inactive-days: '7'
issue-lock-reason: ''
pr-lock-inactive-days: '1'
pr-lock-inactive-days: '7'
pr-lock-reason: ''
+3 -25
View File
@@ -3,9 +3,11 @@ on:
pull_request:
branches:
- master
- v13.x
push:
branches:
- master
- v13.x
jobs:
pytest:
@@ -13,7 +15,7 @@ jobs:
runs-on: ${{matrix.os}}
strategy:
matrix:
python-version: [3.6, 3.7, 3.8, 3.9]
python-version: [3.7, 3.8, 3.9]
os: [ubuntu-latest, windows-latest, macos-latest]
fail-fast: False
steps:
@@ -94,27 +96,3 @@ jobs:
env:
TEST_OFFICIAL: "true"
shell: bash --noprofile --norc {0}
test_pre_commit:
name: test-pre-commit
runs-on: ${{matrix.os}}
strategy:
matrix:
python-version: [3.7]
os: [ubuntu-latest]
fail-fast: False
steps:
- uses: actions/checkout@v2
- name: Initialize vendored libs
run:
git submodule update --init --recursive
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v2
with:
python-version: ${{ matrix.python-version }}
- name: Install dependencies
run: |
python -W ignore -m pip install --upgrade pip
python -W ignore -m pip install -r requirements.txt
python -W ignore -m pip install -r requirements-dev.txt
- name: Run pre-commit tests
run: pre-commit run --all-files
+6 -1
View File
@@ -1,9 +1,14 @@
# Make sure that
# * the revs specified here match requirements-dev.txt
# * the additional_dependencies here match requirements.txt
ci:
# We currently only need this behavior on the v13.x branch were we have the vendored urllib
submodules: true
repos:
- repo: https://github.com/psf/black
rev: 20.8b1
rev: 22.3.0
hooks:
- id: black
args:
+4
View File
@@ -26,6 +26,7 @@ Contributors
The following wonderful people contributed directly or indirectly to this project:
- `Abshar <https://github.com/abxhr>`_
- `Alateas <https://github.com/alateas>`_
- `Ales Dokshanin <https://github.com/alesdokshanin>`_
- `Ambro17 <https://github.com/Ambro17>`_
@@ -39,6 +40,7 @@ The following wonderful people contributed directly or indirectly to this projec
- `daimajia <https://github.com/daimajia>`_
- `Daniel Reed <https://github.com/nmlorg>`_
- `D David Livingston <https://github.com/daviddl9>`_
- `DonalDuck004 <https://github.com/DonalDuck004>`_
- `Eana Hufwe <https://github.com/blueset>`_
- `Ehsan Online <https://github.com/ehsanonline>`_
- `Eli Gao <https://github.com/eligao>`_
@@ -84,6 +86,7 @@ The following wonderful people contributed directly or indirectly to this projec
- `Oleg Sushchenko <https://github.com/feuillemorte>`_
- `Or Bin <https://github.com/OrBin>`_
- `overquota <https://github.com/overquota>`_
- `Paradox <https://github.com/paradox70>`_
- `Patrick Hofmann <https://github.com/PH89>`_
- `Paul Larsen <https://github.com/PaulSonOfLars>`_
- `Pieter Schutz <https://github.com/eldinnie>`_
@@ -106,6 +109,7 @@ The following wonderful people contributed directly or indirectly to this projec
- `Vorobjev Simon <https://github.com/simonvorobjev>`_
- `Wagner Macedo <https://github.com/wagnerluis1982>`_
- `wjt <https://github.com/wjt>`_
- `zeroone2numeral2 <https://github.com/zeroone2numeral2>`_
- `zeshuaro <https://github.com/zeshuaro>`_
Please add yourself here alphabetically when you submit your first pull request.
+140 -2
View File
@@ -2,6 +2,144 @@
Changelog
=========
Version 13.12
=============
*Released 2022-05-26*
This is the technical changelog for version 13.12. More elaborate release notes can be found in the news channel `@pythontelegrambotchannel <https://t.me/pythontelegrambotchannel>`_.
**Major Changes:**
- Full Support for API 6.0 (`#3027`_)
**Minor Changes:**
- Documentation Improvements (`#3029`_)
.. _`#3027`: https://github.com/python-telegram-bot/python-telegram-bot/pull/3027
.. _`#3029`: https://github.com/python-telegram-bot/python-telegram-bot/pull/3029
Version 13.11
=============
*Released 2022-02-02*
This is the technical changelog for version 13.11. More elaborate release notes can be found in the news channel `@pythontelegrambotchannel <https://t.me/pythontelegrambotchannel>`_.
**Major Changes:**
- Full Support for Bot API 5.7 (`#2881`_)
.. _`#2881`: https://github.com/python-telegram-bot/python-telegram-bot/pull/2881
Version 13.10
=============
*Released 2022-01-03*
This is the technical changelog for version 13.10. More elaborate release notes can be found in the news channel `@pythontelegrambotchannel <https://t.me/pythontelegrambotchannel>`_.
**Major Changes:**
- Full Support for API 5.6 (`#2835`_)
**Minor Changes & Doc fixes:**
- Update Copyright to 2022 (`#2836`_)
- Update Documentation of ``BotCommand`` (`#2820`_)
.. _`#2835`: https://github.com/python-telegram-bot/python-telegram-bot/pull/2835
.. _`#2836`: https://github.com/python-telegram-bot/python-telegram-bot/pull/2836
.. _`#2820`: https://github.com/python-telegram-bot/python-telegram-bot/pull/2820
Version 13.9
============
*Released 2021-12-11*
This is the technical changelog for version 13.9. More elaborate release notes can be found in the news channel `@pythontelegrambotchannel <https://t.me/pythontelegrambotchannel>`_.
**Major Changes:**
- Full Support for Api 5.5 (`#2809`_)
**Minor Changes**
- Adjust Automated Locking of Inactive Issues (`#2775`_)
.. _`#2809`: https://github.com/python-telegram-bot/python-telegram-bot/pull/2809
.. _`#2775`: https://github.com/python-telegram-bot/python-telegram-bot/pull/2775
Version 13.8.1
==============
*Released 2021-11-08*
This is the technical changelog for version 13.8.1. More elaborate release notes can be found in the news channel `@pythontelegrambotchannel <https://t.me/pythontelegrambotchannel>`_.
**Doc fixes:**
- Add ``ChatJoinRequest(Handler)`` to Docs (`#2771`_)
.. _`#2771`: https://github.com/python-telegram-bot/python-telegram-bot/pull/2771
Version 13.8
============
*Released 2021-11-08*
This is the technical changelog for version 13.8. More elaborate release notes can be found in the news channel `@pythontelegrambotchannel <https://t.me/pythontelegrambotchannel>`_.
**Major Changes:**
- Full support for API 5.4 (`#2767`_)
**Minor changes, CI improvements, Doc fixes and Type hinting:**
- Create Issue Template Forms (`#2689`_)
- Fix ``camelCase`` Functions in ``ExtBot`` (`#2659`_)
- Fix Empty Captions not Being Passed by ``Bot.copy_message`` (`#2651`_)
- Fix Setting Thumbs When Uploading A Single File (`#2583`_)
- Fix Bug in ``BasePersistence.insert``/``replace_bot`` for Objects with ``__dict__`` not in ``__slots__`` (`#2603`_)
.. _`#2767`: https://github.com/python-telegram-bot/python-telegram-bot/pull/2767
.. _`#2689`: https://github.com/python-telegram-bot/python-telegram-bot/pull/2689
.. _`#2659`: https://github.com/python-telegram-bot/python-telegram-bot/pull/2659
.. _`#2651`: https://github.com/python-telegram-bot/python-telegram-bot/pull/2651
.. _`#2583`: https://github.com/python-telegram-bot/python-telegram-bot/pull/2583
.. _`#2603`: https://github.com/python-telegram-bot/python-telegram-bot/pull/2603
Version 13.7
============
*Released 2021-07-01*
This is the technical changelog for version 13.7. More elaborate release notes can be found in the news channel `@pythontelegrambotchannel <https://t.me/pythontelegrambotchannel>`_.
**Major Changes:**
- Full support for Bot API 5.3 (`#2572`_)
**Bug Fixes:**
- Fix Bug in ``BasePersistence.insert/replace_bot`` for Objects with ``__dict__`` in their slots (`#2561`_)
- Remove Incorrect Warning About ``Defaults`` and ``ExtBot`` (`#2553`_)
**Minor changes, CI improvements, Doc fixes and Type hinting:**
- Type Hinting Fixes (`#2552`_)
- Doc Fixes (`#2551`_)
- Improve Deprecation Warning for ``__slots__`` (`#2574`_)
- Stabilize CI (`#2575`_)
- Fix Coverage Configuration (`#2571`_)
- Better Exception-Handling for ``BasePersistence.replace/insert_bot`` (`#2564`_)
- Remove Deprecated ``pass_args`` from Deeplinking Example (`#2550`_)
.. _`#2572`: https://github.com/python-telegram-bot/python-telegram-bot/pull/2572
.. _`#2561`: https://github.com/python-telegram-bot/python-telegram-bot/pull/2561
.. _`#2553`: https://github.com/python-telegram-bot/python-telegram-bot/pull/2553
.. _`#2552`: https://github.com/python-telegram-bot/python-telegram-bot/pull/2552
.. _`#2551`: https://github.com/python-telegram-bot/python-telegram-bot/pull/2551
.. _`#2574`: https://github.com/python-telegram-bot/python-telegram-bot/pull/2574
.. _`#2575`: https://github.com/python-telegram-bot/python-telegram-bot/pull/2575
.. _`#2571`: https://github.com/python-telegram-bot/python-telegram-bot/pull/2571
.. _`#2564`: https://github.com/python-telegram-bot/python-telegram-bot/pull/2564
.. _`#2550`: https://github.com/python-telegram-bot/python-telegram-bot/pull/2550
Version 13.6
============
*Released 2021-06-06*
@@ -774,7 +912,7 @@ Expect minor releases soon (mainly complete Bot API 4.4 support)
- Error Handler now handles all types of exceptions (`#1485`_)
- Return UTC from from_timestamp() (`#1485`_)
**See the wiki page at https://git.io/fxJuV for a detailed guide on how to migrate from version 11 to version 12.**
**See the wiki page at https://github.com/python-telegram-bot/python-telegram-bot/wiki/Transition-guide-to-Version-12.0 for a detailed guide on how to migrate from version 11 to version 12.**
Context based callbacks (`#1100`_)
----------------------------------
@@ -979,7 +1117,7 @@ Non Bot API 4.0 changes:
.. _`#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
.. _`our telegram passport wiki page`: https://github.com/python-telegram-bot/python-telegram-bot/wiki/Telegram-Passport
Version 10.1.0
==============
+8 -7
View File
@@ -1,5 +1,5 @@
..
Make user to apply any changes to this file to README_RAW.rst as well!
Make sure to apply any changes to this file to README_RAW.rst as well!
.. image:: https://github.com/python-telegram-bot/logos/blob/master/logo-text/png/ptb-logo-text_768.png?raw=true
:align: center
@@ -20,7 +20,7 @@ We have a vibrant community of developers helping each other in our `Telegram gr
:target: https://pypi.org/project/python-telegram-bot/
:alt: Supported Python versions
.. image:: https://img.shields.io/badge/Bot%20API-5.2-blue?logo=telegram
.. image:: https://img.shields.io/badge/Bot%20API-6.0-blue?logo=telegram
:target: https://core.telegram.org/bots/api-changelog
:alt: Supported Bot API versions
@@ -87,19 +87,20 @@ Table of contents
- `License`_
============
Introduction
============
This library provides a pure Python interface for the
`Telegram Bot API <https://core.telegram.org/bots/api>`_.
It's compatible with Python versions 3.6.2+. PTB might also work on `PyPy <http://pypy.org/>`_, though there have been a lot of issues before. Hence, PyPy is not officially supported.
It's compatible with Python versions 3.7+. PTB might also work on `PyPy <http://pypy.org/>`_, though there have been a lot of issues before. Hence, PyPy is not officially supported.
In addition to the pure API implementation, this library features a number of high-level classes to
make the development of bots easy and straightforward. These classes are contained in the
``telegram.ext`` submodule.
A pure API implementation *without* ``telegram.ext`` is available as the standalone package ``python-telegram-bot-raw``. `See here for details. <https://github.com/python-telegram-bot/python-telegram-bot/blob/master/README_RAW.rst>`_
A pure API implementation *without* ``telegram.ext`` is available as the standalone package ``python-telegram-bot-raw``. `See here for details. <https://github.com/python-telegram-bot/python-telegram-bot/blob/v13.x/README_RAW.rst>`_
----
Note
@@ -111,7 +112,7 @@ Installing both ``python-telegram-bot`` and ``python-telegram-bot-raw`` in conju
Telegram API support
====================
All types and methods of the Telegram Bot API **5.2** are supported.
All types and methods of the Telegram Bot API **6.0** are supported.
==========
Installing
@@ -171,7 +172,7 @@ look at ``echobot.py``, it is the de facto base for most of the bots out there.
the code for these examples are released to the public domain, so you can start by grabbing the
code and building on top of it.
Visit `this page <https://github.com/python-telegram-bot/python-telegram-bot/blob/master/examples/README.md>`_ to discover the official examples or look at the examples on the `wiki <https://github.com/python-telegram-bot/python-telegram-bot/wiki/Examples>`_ to see other bots the community has built.
Visit `this page <https://github.com/python-telegram-bot/python-telegram-bot/blob/v13.x/examples/README.md>`_ to discover the official examples or look at the examples on the `wiki <https://github.com/python-telegram-bot/python-telegram-bot/wiki/Examples>`_ to see other bots the community has built.
-------
Logging
@@ -226,7 +227,7 @@ You can get help in several ways:
Contributing
============
Contributions of all sizes are welcome. Please review our `contribution guidelines <https://github.com/python-telegram-bot/python-telegram-bot/blob/master/.github/CONTRIBUTING.rst>`_ to get started. You can also help by `reporting bugs <https://github.com/python-telegram-bot/python-telegram-bot/issues/new>`_.
Contributions of all sizes are welcome. Please review our `contribution guidelines <https://github.com/python-telegram-bot/python-telegram-bot/blob/v13.x/.github/CONTRIBUTING.rst>`_ to get started. You can also help by `reporting bugs <https://github.com/python-telegram-bot/python-telegram-bot/issues/new>`_.
========
Donating
+5 -5
View File
@@ -1,5 +1,5 @@
..
Make user to apply any changes to this file to README.rst as well!
Make sure to apply any changes to this file to README.rst as well!
.. image:: https://github.com/python-telegram-bot/logos/blob/master/logo-text/png/ptb-raw-logo-text_768.png?raw=true
:align: center
@@ -20,7 +20,7 @@ We have a vibrant community of developers helping each other in our `Telegram gr
:target: https://pypi.org/project/python-telegram-bot-raw/
:alt: Supported Python versions
.. image:: https://img.shields.io/badge/Bot%20API-5.2-blue?logo=telegram
.. image:: https://img.shields.io/badge/Bot%20API-6.0-blue?logo=telegram
:target: https://core.telegram.org/bots/api-changelog
:alt: Supported Bot API versions
@@ -91,7 +91,7 @@ Introduction
This library provides a pure Python, lightweight interface for the
`Telegram Bot API <https://core.telegram.org/bots/api>`_.
It's compatible with Python versions 3.6.2+. PTB-Raw might also work on `PyPy <http://pypy.org/>`_, though there have been a lot of issues before. Hence, PyPy is not officially supported.
It's compatible with Python versions 3.7+. PTB-Raw might also work on `PyPy <http://pypy.org/>`_, though there have been a lot of issues before. Hence, PyPy is not officially supported.
``python-telegram-bot-raw`` is part of the `python-telegram-bot <https://python-telegram-bot.org>`_ ecosystem and provides the pure API functionality extracted from PTB. It therefore does *not* have independent release schedules, changelogs or documentation. Please consult the PTB resources.
@@ -105,7 +105,7 @@ Installing both ``python-telegram-bot`` and ``python-telegram-bot-raw`` in conju
Telegram API support
====================
All types and methods of the Telegram Bot API **5.2** are supported.
All types and methods of the Telegram Bot API **6.0** are supported.
==========
Installing
@@ -208,7 +208,7 @@ You can get help in several ways:
Contributing
============
Contributions of all sizes are welcome. Please review our `contribution guidelines <https://github.com/python-telegram-bot/python-telegram-bot/blob/master/.github/CONTRIBUTING.rst>`_ to get started. You can also help by `reporting bugs <https://github.com/python-telegram-bot/python-telegram-bot/issues/new>`_.
Contributions of all sizes are welcome. Please review our `contribution guidelines <https://github.com/python-telegram-bot/python-telegram-bot/blob/v13.x/.github/CONTRIBUTING.rst>`_ to get started. You can also help by `reporting bugs <https://github.com/python-telegram-bot/python-telegram-bot/issues/new>`_.
========
Donating
+1 -1
View File
@@ -2,7 +2,7 @@
/*
Generated by https://darkreader.org
Instructions: Install the extension on a Chromium-based browser
Then do this to export the CSS: https://git.io/JOM6t and drop it here
Then do this to export the CSS: https://github.com/darkreader/darkreader/issues/604#issuecomment-661107893 and drop it here
Some color values where manually changed - just search for "/*" in this file and insert them in the new css
*/
/* User-Agent Style */
+2 -2
View File
@@ -60,9 +60,9 @@ author = u'Leandro Toledo'
# built documents.
#
# The short X.Y version.
version = '13.6' # telegram.__version__[:3]
version = '13.12' # telegram.__version__[:3]
# The full version, including alpha/beta/rc tags.
release = '13.6' # telegram.__version__
release = '13.12' # telegram.__version__
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
+8
View File
@@ -0,0 +1,8 @@
:github_url: https://github.com/python-telegram-bot/python-telegram-bot/blob/master/telegram/botcommandscope.py
telegram.BotCommandScope
========================
.. autoclass:: telegram.BotCommandScope
:members:
:show-inheritance:
@@ -0,0 +1,8 @@
:github_url: https://github.com/python-telegram-bot/python-telegram-bot/blob/master/telegram/botcommandscope.py
telegram.BotCommandScopeAllChatAdministrators
=============================================
.. autoclass:: telegram.BotCommandScopeAllChatAdministrators
:members:
:show-inheritance:
@@ -0,0 +1,8 @@
:github_url: https://github.com/python-telegram-bot/python-telegram-bot/blob/master/telegram/botcommandscope.py
telegram.BotCommandScopeAllGroupChats
=======================================
.. autoclass:: telegram.BotCommandScopeAllGroupChats
:members:
:show-inheritance:
@@ -0,0 +1,8 @@
:github_url: https://github.com/python-telegram-bot/python-telegram-bot/blob/master/telegram/botcommandscope.py
telegram.BotCommandScopeAllPrivateChats
=======================================
.. autoclass:: telegram.BotCommandScopeAllPrivateChats
:members:
:show-inheritance:
@@ -0,0 +1,8 @@
:github_url: https://github.com/python-telegram-bot/python-telegram-bot/blob/master/telegram/botcommandscope.py
telegram.BotCommandScopeChat
============================
.. autoclass:: telegram.BotCommandScopeChat
:members:
:show-inheritance:
@@ -0,0 +1,8 @@
:github_url: https://github.com/python-telegram-bot/python-telegram-bot/blob/master/telegram/botcommandscope.py
telegram.BotCommandScopeChatAdministrators
==========================================
.. autoclass:: telegram.BotCommandScopeChatAdministrators
:members:
:show-inheritance:
@@ -0,0 +1,8 @@
:github_url: https://github.com/python-telegram-bot/python-telegram-bot/blob/master/telegram/botcommandscope.py
telegram.BotCommandScopeChatMember
==================================
.. autoclass:: telegram.BotCommandScopeChatMember
:members:
:show-inheritance:
@@ -0,0 +1,8 @@
:github_url: https://github.com/python-telegram-bot/python-telegram-bot/blob/master/telegram/botcommandscope.py
telegram.BotCommandScopeDefault
===============================
.. autoclass:: telegram.BotCommandScopeDefault
:members:
:show-inheritance:
@@ -0,0 +1,8 @@
:github_url: https://github.com/python-telegram-bot/python-telegram-bot/blob/master/telegram/chatadministratorrights.py
telegram.ChatAdministratorRights
================================
.. autoclass:: telegram.ChatAdministratorRights
:members:
:show-inheritance:
+8
View File
@@ -0,0 +1,8 @@
:github_url: https://github.com/python-telegram-bot/python-telegram-bot/blob/master/telegram/chatjoinrequest.py
telegram.ChatJoinRequest
========================
.. autoclass:: telegram.ChatJoinRequest
:members:
:show-inheritance:
@@ -0,0 +1,8 @@
:github_url: https://github.com/python-telegram-bot/python-telegram-bot/blob/master/telegram/chatmember.py
telegram.ChatMemberAdministrator
================================
.. autoclass:: telegram.ChatMemberAdministrator
:members:
:show-inheritance:
@@ -0,0 +1,8 @@
:github_url: https://github.com/python-telegram-bot/python-telegram-bot/blob/master/telegram/chatmember.py
telegram.ChatMemberBanned
=========================
.. autoclass:: telegram.ChatMemberBanned
:members:
:show-inheritance:
+8
View File
@@ -0,0 +1,8 @@
:github_url: https://github.com/python-telegram-bot/python-telegram-bot/blob/master/telegram/chatmember.py
telegram.ChatMemberLeft
=======================
.. autoclass:: telegram.ChatMemberLeft
:members:
:show-inheritance:
@@ -0,0 +1,8 @@
:github_url: https://github.com/python-telegram-bot/python-telegram-bot/blob/master/telegram/chatmember.py
telegram.ChatMemberMember
=========================
.. autoclass:: telegram.ChatMemberMember
:members:
:show-inheritance:
+9
View File
@@ -0,0 +1,9 @@
:github_url: https://github.com/python-telegram-bot/python-telegram-bot/blob/master/telegram/chatmember.py
telegram.ChatMemberOwner
========================
.. autoclass:: telegram.ChatMemberOwner
:members:
:show-inheritance:
@@ -0,0 +1,8 @@
:github_url: https://github.com/python-telegram-bot/python-telegram-bot/blob/master/telegram/chatmember.py
telegram.ChatMemberRestricted
=============================
.. autoclass:: telegram.ChatMemberRestricted
:members:
:show-inheritance:
@@ -0,0 +1,8 @@
:github_url: https://github.com/python-telegram-bot/python-telegram-bot/blob/master/telegram/ext/chatjoinrequesthandler.py
telegram.ext.ChatJoinRequestHandler
===================================
.. autoclass:: telegram.ext.ChatJoinRequestHandler
:members:
:show-inheritance:
+2
View File
@@ -5,3 +5,5 @@ telegram.ext.ExtBot
.. autoclass:: telegram.ext.ExtBot
:show-inheritance:
.. autofunction:: telegram.ext.ExtBot.insert_callback_data
-1
View File
@@ -5,5 +5,4 @@ telegram.ext.Handler
.. autoclass:: telegram.ext.Handler
:members:
:undoc-members:
:show-inheritance:
+2 -1
View File
@@ -22,8 +22,9 @@ Handlers
telegram.ext.handler
telegram.ext.callbackqueryhandler
telegram.ext.choseninlineresulthandler
telegram.ext.chatjoinrequesthandler
telegram.ext.chatmemberhandler
telegram.ext.choseninlineresulthandler
telegram.ext.commandhandler
telegram.ext.conversationhandler
telegram.ext.inlinequeryhandler
+8
View File
@@ -0,0 +1,8 @@
:github_url: https://github.com/python-telegram-bot/python-telegram-bot/blob/master/telegram/menubutton.py
telegram.MenuButton
===================
.. autoclass:: telegram.MenuButton
:members:
:show-inheritance:
@@ -0,0 +1,8 @@
:github_url: https://github.com/python-telegram-bot/python-telegram-bot/blob/master/telegram/menubutton.py
telegram.MenuButtonCommands
===========================
.. autoclass:: telegram.MenuButtonCommands
:members:
:show-inheritance:
@@ -0,0 +1,8 @@
:github_url: https://github.com/python-telegram-bot/python-telegram-bot/blob/master/telegram/menubutton.py
telegram.MenuButtonDefault
==========================
.. autoclass:: telegram.MenuButtonDefault
:members:
:show-inheritance:
@@ -0,0 +1,8 @@
:github_url: https://github.com/python-telegram-bot/python-telegram-bot/blob/master/telegram/menubutton.py
telegram.MenuButtonWebApp
=========================
.. autoclass:: telegram.MenuButtonWebApp
:members:
:show-inheritance:
+27
View File
@@ -7,12 +7,28 @@ telegram package
telegram.audio
telegram.bot
telegram.botcommand
telegram.botcommandscope
telegram.botcommandscopedefault
telegram.botcommandscopeallprivatechats
telegram.botcommandscopeallgroupchats
telegram.botcommandscopeallchatadministrators
telegram.botcommandscopechat
telegram.botcommandscopechatadministrators
telegram.botcommandscopechatmember
telegram.callbackquery
telegram.chat
telegram.chatadministratorrights
telegram.chataction
telegram.chatinvitelink
telegram.chatjoinrequest
telegram.chatlocation
telegram.chatmember
telegram.chatmemberowner
telegram.chatmemberadministrator
telegram.chatmembermember
telegram.chatmemberrestricted
telegram.chatmemberleft
telegram.chatmemberbanned
telegram.chatmemberupdated
telegram.chatpermissions
telegram.chatphoto
@@ -36,6 +52,10 @@ telegram package
telegram.keyboardbuttonpolltype
telegram.location
telegram.loginurl
telegram.menubutton
telegram.menubuttoncommands
telegram.menubuttondefault
telegram.menubuttonwebapp
telegram.message
telegram.messageautodeletetimerchanged
telegram.messageid
@@ -49,18 +69,25 @@ telegram package
telegram.replykeyboardremove
telegram.replykeyboardmarkup
telegram.replymarkup
telegram.sentwebappmessage
telegram.telegramobject
telegram.update
telegram.user
telegram.userprofilephotos
telegram.venue
telegram.video
telegram.videochatended
telegram.videochatparticipantsinvited
telegram.videochatscheduled
telegram.videochatstarted
telegram.videonote
telegram.voice
telegram.voicechatstarted
telegram.voicechatended
telegram.voicechatscheduled
telegram.voicechatparticipantsinvited
telegram.webappdata
telegram.webappinfo
telegram.webhookinfo
Stickers
@@ -0,0 +1,8 @@
:github_url: https://github.com/python-telegram-bot/python-telegram-bot/blob/master/telegram/sentwebappmessage.py
telegram.SentWebAppMessage
==========================
.. autoclass:: telegram.SentWebAppMessage
:members:
:show-inheritance:
-1
View File
@@ -5,5 +5,4 @@ telegram.Update
.. autoclass:: telegram.Update
:members:
:undoc-members:
:show-inheritance:
-1
View File
@@ -5,5 +5,4 @@ telegram.User
.. autoclass:: telegram.User
:members:
:undoc-members:
:show-inheritance:
+9
View File
@@ -0,0 +1,9 @@
:github_url: https://github.com/python-telegram-bot/python-telegram-bot/blob/master/telegram/videochatended.py
telegram.VideoChatEnded
=======================
.. autoclass:: telegram.VideoChatEnded
:members:
:show-inheritance:
@@ -0,0 +1,8 @@
:github_url: https://github.com/python-telegram-bot/python-telegram-bot/blob/master/telegram/videochatparticipantsinvited.py
telegram.VideoChatParticipantsInvited
=====================================
.. autoclass:: telegram.VideoChatParticipantsInvited
:members:
:show-inheritance:
@@ -0,0 +1,8 @@
:github_url: https://github.com/python-telegram-bot/python-telegram-bot/blob/master/telegram/videochatscheduled.py
telegram.VideoChatScheduled
===========================
.. autoclass:: telegram.VideoChatScheduled
:members:
:show-inheritance:
@@ -0,0 +1,8 @@
:github_url: https://github.com/python-telegram-bot/python-telegram-bot/blob/master/telegram/videochatstarted.py
telegram.VideoChatStarted
=========================
.. autoclass:: telegram.VideoChatStarted
:members:
:show-inheritance:
+2
View File
@@ -7,3 +7,5 @@ telegram.VoiceChatEnded
:members:
:show-inheritance:
.. versionchanged:: v13.12
Since Bot API 6.0, voice chat was renamed to video chat.
@@ -7,3 +7,5 @@ telegram.VoiceChatParticipantsInvited
:members:
:show-inheritance:
.. versionchanged:: v13.12
Since Bot API 6.0, voice chat was renamed to video chat.
@@ -7,3 +7,5 @@ telegram.VoiceChatScheduled
:members:
:show-inheritance:
.. versionchanged:: v13.12
Since Bot API 6.0, voice chat was renamed to video chat.
@@ -7,3 +7,5 @@ telegram.VoiceChatStarted
:members:
:show-inheritance:
.. versionchanged:: v13.12
Since Bot API 6.0, voice chat was renamed to video chat.
+8
View File
@@ -0,0 +1,8 @@
:github_url: https://github.com/python-telegram-bot/python-telegram-bot/blob/master/telegram/webappdata.py
telegram.WebAppData
===================
.. autoclass:: telegram.WebAppData
:members:
:show-inheritance:
+8
View File
@@ -0,0 +1,8 @@
:github_url: https://github.com/python-telegram-bot/python-telegram-bot/blob/master/telegram/webappinfo.py
telegram.WebAppInfo
===================
.. autoclass:: telegram.WebAppInfo
:members:
:show-inheritance:
+24 -24
View File
@@ -2,60 +2,60 @@
In this folder are small examples to show what a bot written with `python-telegram-bot` looks like. Some bots focus on one specific aspect of the Telegram Bot API while others focus on one of the mechanics of this library. Except for the [`rawapibot.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.
All examples are licensed under the [CC0 License](https://github.com/python-telegram-bot/python-telegram-bot/blob/v13.x/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.
Do note that we ignore one pythonic convention. Best practice would dictate, in many handler callbacks function signatures, to replace the argument `context` with an underscore, since `context` is an unused local variable in those callbacks. However, since these are examples and not having a name for that argument confuses beginners, we decided to have it present.
### [`echobot.py`](https://github.com/python-telegram-bot/python-telegram-bot/blob/master/examples/echobot.py)
### [`echobot.py`](https://github.com/python-telegram-bot/python-telegram-bot/blob/v13.x/examples/echobot.py)
This is probably the base for most of the bots made with `python-telegram-bot`. It simply replies to each text message with a message that contains the same text.
### [`timerbot.py`](https://github.com/python-telegram-bot/python-telegram-bot/blob/master/examples/timerbot.py)
### [`timerbot.py`](https://github.com/python-telegram-bot/python-telegram-bot/blob/v13.x/examples/timerbot.py)
This bot uses the [`JobQueue`](https://python-telegram-bot.readthedocs.io/en/latest/telegram.ext.jobqueue.html) class to send timed messages. The user sets a timer by using `/set` command with a specific time, for example `/set 30`. The bot then sets up a job to send a message to that user after 30 seconds. The user can also cancel the timer by sending `/unset`. To learn more about the `JobQueue`, read [this wiki article](https://github.com/python-telegram-bot/python-telegram-bot/wiki/Extensions-%E2%80%93-JobQueue).
### [`conversationbot.py`](https://github.com/python-telegram-bot/python-telegram-bot/blob/master/examples/conversationbot.py)
A common task for a bot is to ask information from the user. In v5.0 of this library, we introduced the [`ConversationHandler`](https://python-telegram-bot.readthedocs.io/en/latest/telegram.ext.conversationhandler.html) for that exact purpose. This example uses it to retrieve user-information in a conversation-like style. To get a better understanding, take a look at the [state diagram](https://github.com/python-telegram-bot/python-telegram-bot/blob/master/examples/conversationbot.png).
### [`conversationbot.py`](https://github.com/python-telegram-bot/python-telegram-bot/blob/v13.x/examples/conversationbot.py)
A common task for a bot is to ask information from the user. In v5.0 of this library, we introduced the [`ConversationHandler`](https://python-telegram-bot.readthedocs.io/en/latest/telegram.ext.conversationhandler.html) for that exact purpose. This example uses it to retrieve user-information in a conversation-like style. To get a better understanding, take a look at the [state diagram](https://github.com/python-telegram-bot/python-telegram-bot/blob/v13.x/examples/conversationbot.png).
### [`conversationbot2.py`](https://github.com/python-telegram-bot/python-telegram-bot/blob/master/examples/conversationbot2.py)
A more complex example of a bot that uses the `ConversationHandler`. It is also more confusing. Good thing there is a [fancy state diagram](https://github.com/python-telegram-bot/python-telegram-bot/blob/master/examples/conversationbot2.png) for this one, too!
### [`conversationbot2.py`](https://github.com/python-telegram-bot/python-telegram-bot/blob/v13.x/examples/conversationbot2.py)
A more complex example of a bot that uses the `ConversationHandler`. It is also more confusing. Good thing there is a [fancy state diagram](https://github.com/python-telegram-bot/python-telegram-bot/blob/v13.x/examples/conversationbot2.png) for this one, too!
### [`nestedconversationbot.py`](https://github.com/python-telegram-bot/python-telegram-bot/blob/master/examples/nestedconversationbot.py)
A even more complex example of a bot that uses the nested `ConversationHandler`s. While it's certainly not that complex that you couldn't built it without nested `ConversationHanldler`s, it gives a good impression on how to work with them. Of course, there is a [fancy state diagram](https://github.com/python-telegram-bot/python-telegram-bot/blob/master/examples/nestedconversationbot.png) for this example, too!
### [`nestedconversationbot.py`](https://github.com/python-telegram-bot/python-telegram-bot/blob/v13.x/examples/nestedconversationbot.py)
A even more complex example of a bot that uses the nested `ConversationHandler`s. While it's certainly not that complex that you couldn't built it without nested `ConversationHanldler`s, it gives a good impression on how to work with them. Of course, there is a [fancy state diagram](https://github.com/python-telegram-bot/python-telegram-bot/blob/v13.x/examples/nestedconversationbot.png) for this example, too!
### [`persistentconversationbot.py`](https://github.com/python-telegram-bot/python-telegram-bot/blob/master/examples/persistentconversationbot.py)
### [`persistentconversationbot.py`](https://github.com/python-telegram-bot/python-telegram-bot/blob/v13.x/examples/persistentconversationbot.py)
A basic example of a bot store conversation state and user_data over multiple restarts.
### [`inlinekeyboard.py`](https://github.com/python-telegram-bot/python-telegram-bot/blob/master/examples/inlinekeyboard.py)
This example sheds some light on inline keyboards, callback queries and message editing. A wikipedia site explaining this examples lives at https://git.io/JOmFw.
### [`inlinekeyboard.py`](https://github.com/python-telegram-bot/python-telegram-bot/blob/v13.x/examples/inlinekeyboard.py)
This example sheds some light on inline keyboards, callback queries and message editing. A wikipedia site explaining this examples lives at https://github.com/python-telegram-bot/python-telegram-bot/wiki/InlineKeyboard-Example.
### [`inlinekeyboard2.py`](https://github.com/python-telegram-bot/python-telegram-bot/blob/master/examples/inlinekeyboard2.py)
### [`inlinekeyboard2.py`](https://github.com/python-telegram-bot/python-telegram-bot/blob/v13.x/examples/inlinekeyboard2.py)
A more complex example about inline keyboards, callback queries and message editing. This example showcases how an interactive menu could be build using inline keyboards.
### [`deeplinking.py`](https://github.com/python-telegram-bot/python-telegram-bot/blob/master/examples/deeplinking.py)
### [`deeplinking.py`](https://github.com/python-telegram-bot/python-telegram-bot/blob/v13.x/examples/deeplinking.py)
A basic example on how to use deeplinking with inline keyboards.
### [`inlinebot.py`](https://github.com/python-telegram-bot/python-telegram-bot/blob/master/examples/inlinebot.py)
### [`inlinebot.py`](https://github.com/python-telegram-bot/python-telegram-bot/blob/v13.x/examples/inlinebot.py)
A basic example of an [inline bot](https://core.telegram.org/bots/inline). Don't forget to enable inline mode with [@BotFather](https://telegram.me/BotFather).
### [`pollbot.py`](https://github.com/python-telegram-bot/python-telegram-bot/blob/master/examples/pollbot.py)
### [`pollbot.py`](https://github.com/python-telegram-bot/python-telegram-bot/blob/v13.x/examples/pollbot.py)
This example sheds some light on polls, poll answers and the corresponding handlers.
### [`passportbot.py`](https://github.com/python-telegram-bot/python-telegram-bot/blob/master/examples/passportbot.py)
A basic example of a bot that can accept passports. Use in combination with [`passportbot.html`](https://github.com/python-telegram-bot/python-telegram-bot/blob/master/examples/passportbot.html). Don't forget to enable and configure payments with [@BotFather](https://telegram.me/BotFather). Check out this [guide](https://git.io/fAvYd) on Telegram passports in PTB.
### [`passportbot.py`](https://github.com/python-telegram-bot/python-telegram-bot/blob/v13.x/examples/passportbot.py)
A basic example of a bot that can accept passports. Use in combination with [`passportbot.html`](https://github.com/python-telegram-bot/python-telegram-bot/blob/v13.x/examples/passportbot.html). Don't forget to enable and configure payments with [@BotFather](https://telegram.me/BotFather). Check out this [guide](https://github.com/python-telegram-bot/python-telegram-bot/wiki/Telegram-Passport) on Telegram passports in PTB.
### [`paymentbot.py`](https://github.com/python-telegram-bot/python-telegram-bot/blob/master/examples/paymentbot.py)
### [`paymentbot.py`](https://github.com/python-telegram-bot/python-telegram-bot/blob/v13.x/examples/paymentbot.py)
A basic example of a bot that can accept payments. Don't forget to enable and configure payments with [@BotFather](https://telegram.me/BotFather).
### [`errorhandlerbot.py`](https://github.com/python-telegram-bot/python-telegram-bot/blob/master/examples/errorhandlerbot.py)
### [`errorhandlerbot.py`](https://github.com/python-telegram-bot/python-telegram-bot/blob/v13.x/examples/errorhandlerbot.py)
A basic example on how to set up a custom error handler.
### [`chatmemberbot.py`](https://github.com/python-telegram-bot/python-telegram-bot/blob/master/examples/chatmemberbot.py)
### [`chatmemberbot.py`](https://github.com/python-telegram-bot/python-telegram-bot/blob/v13.x/examples/chatmemberbot.py)
A basic example on how `(my_)chat_member` updates can be used.
### [`contexttypesbot.py`](https://github.com/python-telegram-bot/python-telegram-bot/blob/master/examples/contexttypesbot.py)
### [`contexttypesbot.py`](https://github.com/python-telegram-bot/python-telegram-bot/blob/v13.x/examples/contexttypesbot.py)
This example showcases how `telegram.ext.ContextTypes` can be used to customize the `context` argument of handler and job callbacks.
### [`arbitrarycallbackdatabot.py`](https://github.com/python-telegram-bot/python-telegram-bot/blob/master/examples/arbitrarycallbackdatabot.py)
### [`arbitrarycallbackdatabot.py`](https://github.com/python-telegram-bot/python-telegram-bot/blob/v13.x/examples/arbitrarycallbackdatabot.py)
This example showcases how PTBs "arbitrary callback data" feature can be used.
## Pure API
The [`rawapibot.py`](https://github.com/python-telegram-bot/python-telegram-bot/blob/master/examples/rawapibot.py) example uses only the pure, "bare-metal" API wrapper.
The [`rawapibot.py`](https://github.com/python-telegram-bot/python-telegram-bot/blob/v13.x/examples/rawapibot.py) example uses only the pure, "bare-metal" API wrapper.
+2 -1
View File
@@ -4,7 +4,8 @@
"""This example showcases how PTBs "arbitrary callback data" feature can be used.
For detailed info on arbitrary callback data, see the wiki page at https://git.io/JGBDI
For detailed info on arbitrary callback data, see the wiki page at
https://github.com/python-telegram-bot/python-telegram-bot/wiki/Arbitrary-callback_data
"""
import logging
from typing import List, Tuple, cast
+10 -18
View File
@@ -44,24 +44,16 @@ def extract_status_change(
return None
old_status, new_status = status_change
was_member = (
old_status
in [
ChatMember.MEMBER,
ChatMember.CREATOR,
ChatMember.ADMINISTRATOR,
]
or (old_status == ChatMember.RESTRICTED and old_is_member is True)
)
is_member = (
new_status
in [
ChatMember.MEMBER,
ChatMember.CREATOR,
ChatMember.ADMINISTRATOR,
]
or (new_status == ChatMember.RESTRICTED and new_is_member is True)
)
was_member = old_status in [
ChatMember.MEMBER,
ChatMember.CREATOR,
ChatMember.ADMINISTRATOR,
] or (old_status == ChatMember.RESTRICTED and old_is_member is True)
is_member = new_status in [
ChatMember.MEMBER,
ChatMember.CREATOR,
ChatMember.ADMINISTRATOR,
] or (new_status == ChatMember.RESTRICTED and new_is_member is True)
return was_member, is_member
+3 -1
View File
@@ -44,7 +44,9 @@ def start(update: Update, context: CallbackContext) -> int:
'Hi! My name is Professor Bot. I will hold a conversation with you. '
'Send /cancel to stop talking to me.\n\n'
'Are you a boy or a girl?',
reply_markup=ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True),
reply_markup=ReplyKeyboardMarkup(
reply_keyboard, one_time_keyboard=True, input_field_placeholder='Boy or Girl?'
),
)
return GENDER
+1 -1
View File
@@ -124,7 +124,7 @@ def main() -> None:
# We can also pass on the deep-linking payload
dispatcher.add_handler(
CommandHandler("start", deep_linked_level_3, Filters.regex(USING_ENTITIES), pass_args=True)
CommandHandler("start", deep_linked_level_3, Filters.regex(USING_ENTITIES))
)
# Possible with inline keyboard buttons as well
+1 -1
View File
@@ -4,7 +4,7 @@
"""
Basic example for a bot that uses inline keyboards. For an in-depth explanation, check out
https://git.io/JOmFw.
https://github.com/python-telegram-bot/python-telegram-bot/wiki/InlineKeyboard-Example.
"""
import logging
+2 -1
View File
@@ -7,7 +7,8 @@ Simple Bot to print/download all incoming passport data
See https://telegram.org/blog/passport for info about what telegram passport is.
See https://git.io/fAvYd for how to use Telegram Passport properly with python-telegram-bot.
See https://github.com/python-telegram-bot/python-telegram-bot/wiki/Telegram-Passport
for how to use Telegram Passport properly with python-telegram-bot.
"""
import logging
+1 -1
View File
@@ -3,7 +3,7 @@ cryptography!=3.4,!=3.4.1,!=3.4.2,!=3.4.3
pre-commit
# Make sure that the versions specified here match the pre-commit settings!
black==20.8b1
black==22.3.0
flake8==3.9.2
pylint==2.8.3
mypy==0.812
+3 -2
View File
@@ -43,8 +43,9 @@ omit =
[coverage:report]
exclude_lines =
pragma: no cover
@overload
if TYPE_CHECKING:
...
[mypy]
warn_unused_ignores = True
@@ -59,7 +60,7 @@ ignore_errors = True
# Disable strict optional for telegram objects with class methods
# We don't want to clutter the code with 'if self.bot is None: raise RuntimeError()'
[mypy-telegram.callbackquery,telegram.chat,telegram.message,telegram.user,telegram.files.*,telegram.inline.inlinequery,telegram.payment.precheckoutquery,telegram.payment.shippingquery,telegram.passport.passportdata,telegram.passport.credentials,telegram.passport.passportfile,telegram.ext.filters]
[mypy-telegram.callbackquery,telegram.chat,telegram.message,telegram.user,telegram.files.*,telegram.inline.inlinequery,telegram.payment.precheckoutquery,telegram.payment.shippingquery,telegram.passport.passportdata,telegram.passport.credentials,telegram.passport.passportfile,telegram.ext.filters,telegram.chatjoinrequest]
strict_optional = False
# type hinting for asyncio in webhookhandler is a bit tricky because it depends on the OS
+1 -2
View File
@@ -65,7 +65,7 @@ def get_setup_kwargs(raw=False):
author_email='devs@python-telegram-bot.org',
license='LGPLv3',
url='https://python-telegram-bot.org/',
# Keywords supported by PyPI can be found at https://git.io/JtLIZ
# Keywords supported by PyPI can be found at https://github.com/pypa/warehouse/blob/aafc5185e57e67d43487ce4faa95913dd4573e14/warehouse/templates/packaging/detail.html#L20-L58
project_urls={
"Documentation": "https://python-telegram-bot.readthedocs.io",
"Bug Tracker": "https://github.com/python-telegram-bot/python-telegram-bot/issues",
@@ -98,7 +98,6 @@ def get_setup_kwargs(raw=False):
'Topic :: Internet',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3.9',
+61 -4
View File
@@ -1,7 +1,7 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2021
# Copyright (C) 2015-2022
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
@@ -20,12 +20,28 @@
from .base import TelegramObject
from .botcommand import BotCommand
from .webappdata import WebAppData
from .webappinfo import WebAppInfo
from .sentwebappmessage import SentWebAppMessage
from .menubutton import MenuButton, MenuButtonCommands, MenuButtonDefault, MenuButtonWebApp
from .loginurl import LoginUrl
from .games.callbackgame import CallbackGame
from .user import User
from .files.chatphoto import ChatPhoto
from .chat import Chat
from .chatadministratorrights import ChatAdministratorRights
from .chatlocation import ChatLocation
from .chatinvitelink import ChatInviteLink
from .chatmember import ChatMember
from .chatjoinrequest import ChatJoinRequest
from .chatmember import (
ChatMember,
ChatMemberOwner,
ChatMemberAdministrator,
ChatMemberMember,
ChatMemberRestricted,
ChatMemberLeft,
ChatMemberBanned,
)
from .chatmemberupdated import ChatMemberUpdated
from .chatpermissions import ChatPermissions
from .files.photosize import PhotoSize
@@ -62,9 +78,13 @@ from .voicechat import (
VoiceChatParticipantsInvited,
VoiceChatScheduled,
)
from .loginurl import LoginUrl
from .videochat import (
VideoChatStarted,
VideoChatEnded,
VideoChatParticipantsInvited,
VideoChatScheduled,
)
from .proximityalerttriggered import ProximityAlertTriggered
from .games.callbackgame import CallbackGame
from .payment.shippingaddress import ShippingAddress
from .payment.orderinfo import OrderInfo
from .payment.successfulpayment import SuccessfulPayment
@@ -153,6 +173,16 @@ from .passport.credentials import (
FileCredentials,
TelegramDecryptionError,
)
from .botcommandscope import (
BotCommandScope,
BotCommandScopeDefault,
BotCommandScopeAllPrivateChats,
BotCommandScopeAllGroupChats,
BotCommandScopeAllChatAdministrators,
BotCommandScopeChat,
BotCommandScopeChatAdministrators,
BotCommandScopeChatMember,
)
from .bot import Bot
from .version import __version__, bot_api_version # noqa: F401
@@ -163,13 +193,29 @@ __all__ = ( # Keep this alphabetically ordered
'Audio',
'Bot',
'BotCommand',
'BotCommandScope',
'BotCommandScopeAllChatAdministrators',
'BotCommandScopeAllGroupChats',
'BotCommandScopeAllPrivateChats',
'BotCommandScopeChat',
'BotCommandScopeChatAdministrators',
'BotCommandScopeChatMember',
'BotCommandScopeDefault',
'CallbackGame',
'CallbackQuery',
'Chat',
'ChatAdministratorRights',
'ChatAction',
'ChatInviteLink',
'ChatJoinRequest',
'ChatLocation',
'ChatMember',
'ChatMemberOwner',
'ChatMemberAdministrator',
'ChatMemberMember',
'ChatMemberRestricted',
'ChatMemberLeft',
'ChatMemberBanned',
'ChatMemberUpdated',
'ChatPermissions',
'ChatPhoto',
@@ -238,6 +284,10 @@ __all__ = ( # Keep this alphabetically ordered
'MAX_MESSAGES_PER_SECOND_PER_CHAT',
'MAX_MESSAGE_LENGTH',
'MaskPosition',
'MenuButton',
'MenuButtonCommands',
'MenuButtonDefault',
'MenuButtonWebApp',
'Message',
'MessageAutoDeleteTimerChanged',
'MessageEntity',
@@ -270,6 +320,7 @@ __all__ = ( # Keep this alphabetically ordered
'SUPPORTED_WEBHOOK_PORTS',
'SecureData',
'SecureValue',
'SentWebAppMessage',
'ShippingAddress',
'ShippingOption',
'ShippingQuery',
@@ -284,11 +335,17 @@ __all__ = ( # Keep this alphabetically ordered
'UserProfilePhotos',
'Venue',
'Video',
'VideoChatEnded',
'VideoChatParticipantsInvited',
'VideoChatScheduled',
'VideoChatStarted',
'VideoNote',
'Voice',
'VoiceChatStarted',
'VoiceChatEnded',
'VoiceChatScheduled',
'VoiceChatParticipantsInvited',
'WebAppData',
'WebAppInfo',
'WebhookInfo',
)
+1 -1
View File
@@ -1,7 +1,7 @@
# !/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2021
# Copyright (C) 2015-2022
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
+1 -1
View File
@@ -1,7 +1,7 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2021
# Copyright (C) 2015-2022
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
+842 -52
View File
File diff suppressed because it is too large Load Diff
+2 -2
View File
@@ -2,7 +2,7 @@
# pylint: disable=R0903
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2021
# Copyright (C) 2015-2022
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
@@ -33,7 +33,7 @@ class BotCommand(TelegramObject):
Args:
command (:obj:`str`): Text of the command, 1-32 characters. Can contain only lowercase
English letters, digits and underscores.
description (:obj:`str`): Description of the command, 3-256 characters.
description (:obj:`str`): Description of the command, 1-256 characters.
Attributes:
command (:obj:`str`): Text of the command.
+263
View File
@@ -0,0 +1,263 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2022
# 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/].
# pylint: disable=W0622
"""This module contains objects representing Telegram bot command scopes."""
from typing import Any, Union, Optional, TYPE_CHECKING, Dict, Type
from telegram import TelegramObject, constants
from telegram.utils.types import JSONDict
if TYPE_CHECKING:
from telegram import Bot
class BotCommandScope(TelegramObject):
"""Base class for objects that represent the scope to which bot commands are applied.
Currently, the following 7 scopes are supported:
* :class:`telegram.BotCommandScopeDefault`
* :class:`telegram.BotCommandScopeAllPrivateChats`
* :class:`telegram.BotCommandScopeAllGroupChats`
* :class:`telegram.BotCommandScopeAllChatAdministrators`
* :class:`telegram.BotCommandScopeChat`
* :class:`telegram.BotCommandScopeChatAdministrators`
* :class:`telegram.BotCommandScopeChatMember`
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`type` is equal. For subclasses with additional attributes,
the notion of equality is overridden.
Note:
Please see the `official docs`_ on how Telegram determines which commands to display.
.. _`official docs`: https://core.telegram.org/bots/api#determining-list-of-commands
.. versionadded:: 13.7
Args:
type (:obj:`str`): Scope type.
Attributes:
type (:obj:`str`): Scope type.
"""
__slots__ = ('type', '_id_attrs')
DEFAULT = constants.BOT_COMMAND_SCOPE_DEFAULT
""":const:`telegram.constants.BOT_COMMAND_SCOPE_DEFAULT`"""
ALL_PRIVATE_CHATS = constants.BOT_COMMAND_SCOPE_ALL_PRIVATE_CHATS
""":const:`telegram.constants.BOT_COMMAND_SCOPE_ALL_PRIVATE_CHATS`"""
ALL_GROUP_CHATS = constants.BOT_COMMAND_SCOPE_ALL_GROUP_CHATS
""":const:`telegram.constants.BOT_COMMAND_SCOPE_ALL_GROUP_CHATS`"""
ALL_CHAT_ADMINISTRATORS = constants.BOT_COMMAND_SCOPE_ALL_CHAT_ADMINISTRATORS
""":const:`telegram.constants.BOT_COMMAND_SCOPE_ALL_CHAT_ADMINISTRATORS`"""
CHAT = constants.BOT_COMMAND_SCOPE_CHAT
""":const:`telegram.constants.BOT_COMMAND_SCOPE_CHAT`"""
CHAT_ADMINISTRATORS = constants.BOT_COMMAND_SCOPE_CHAT_ADMINISTRATORS
""":const:`telegram.constants.BOT_COMMAND_SCOPE_CHAT_ADMINISTRATORS`"""
CHAT_MEMBER = constants.BOT_COMMAND_SCOPE_CHAT_MEMBER
""":const:`telegram.constants.BOT_COMMAND_SCOPE_CHAT_MEMBER`"""
def __init__(self, type: str, **_kwargs: Any):
self.type = type
self._id_attrs = (self.type,)
@classmethod
def de_json(cls, data: Optional[JSONDict], bot: 'Bot') -> Optional['BotCommandScope']:
"""Converts JSON data to the appropriate :class:`BotCommandScope` object, i.e. takes
care of selecting the correct subclass.
Args:
data (Dict[:obj:`str`, ...]): The JSON data.
bot (:class:`telegram.Bot`): The bot associated with this object.
Returns:
The Telegram object.
"""
data = cls._parse_data(data)
if not data:
return None
_class_mapping: Dict[str, Type['BotCommandScope']] = {
cls.DEFAULT: BotCommandScopeDefault,
cls.ALL_PRIVATE_CHATS: BotCommandScopeAllPrivateChats,
cls.ALL_GROUP_CHATS: BotCommandScopeAllGroupChats,
cls.ALL_CHAT_ADMINISTRATORS: BotCommandScopeAllChatAdministrators,
cls.CHAT: BotCommandScopeChat,
cls.CHAT_ADMINISTRATORS: BotCommandScopeChatAdministrators,
cls.CHAT_MEMBER: BotCommandScopeChatMember,
}
if cls is BotCommandScope:
return _class_mapping.get(data['type'], cls)(**data, bot=bot)
return cls(**data)
class BotCommandScopeDefault(BotCommandScope):
"""Represents the default scope of bot commands. Default commands are used if no commands with
a `narrower scope`_ are specified for the user.
.. _`narrower scope`: https://core.telegram.org/bots/api#determining-list-of-commands
.. versionadded:: 13.7
Attributes:
type (:obj:`str`): Scope type :attr:`telegram.BotCommandScope.DEFAULT`.
"""
__slots__ = ()
def __init__(self, **_kwargs: Any):
super().__init__(type=BotCommandScope.DEFAULT)
class BotCommandScopeAllPrivateChats(BotCommandScope):
"""Represents the scope of bot commands, covering all private chats.
.. versionadded:: 13.7
Attributes:
type (:obj:`str`): Scope type :attr:`telegram.BotCommandScope.ALL_PRIVATE_CHATS`.
"""
__slots__ = ()
def __init__(self, **_kwargs: Any):
super().__init__(type=BotCommandScope.ALL_PRIVATE_CHATS)
class BotCommandScopeAllGroupChats(BotCommandScope):
"""Represents the scope of bot commands, covering all group and supergroup chats.
.. versionadded:: 13.7
Attributes:
type (:obj:`str`): Scope type :attr:`telegram.BotCommandScope.ALL_GROUP_CHATS`.
"""
__slots__ = ()
def __init__(self, **_kwargs: Any):
super().__init__(type=BotCommandScope.ALL_GROUP_CHATS)
class BotCommandScopeAllChatAdministrators(BotCommandScope):
"""Represents the scope of bot commands, covering all group and supergroup chat administrators.
.. versionadded:: 13.7
Attributes:
type (:obj:`str`): Scope type :attr:`telegram.BotCommandScope.ALL_CHAT_ADMINISTRATORS`.
"""
__slots__ = ()
def __init__(self, **_kwargs: Any):
super().__init__(type=BotCommandScope.ALL_CHAT_ADMINISTRATORS)
class BotCommandScopeChat(BotCommandScope):
"""Represents the scope of bot commands, covering a specific chat.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`type` and :attr:`chat_id` are equal.
.. versionadded:: 13.7
Args:
chat_id (:obj:`str` | :obj:`int`): Unique identifier for the target chat or username of the
target supergroup (in the format ``@supergroupusername``)
Attributes:
type (:obj:`str`): Scope type :attr:`telegram.BotCommandScope.CHAT`.
chat_id (:obj:`str` | :obj:`int`): Unique identifier for the target chat or username of the
target supergroup (in the format ``@supergroupusername``)
"""
__slots__ = ('chat_id',)
def __init__(self, chat_id: Union[str, int], **_kwargs: Any):
super().__init__(type=BotCommandScope.CHAT)
self.chat_id = (
chat_id if isinstance(chat_id, str) and chat_id.startswith('@') else int(chat_id)
)
self._id_attrs = (self.type, self.chat_id)
class BotCommandScopeChatAdministrators(BotCommandScope):
"""Represents the scope of bot commands, covering all administrators of a specific group or
supergroup chat.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`type` and :attr:`chat_id` are equal.
.. versionadded:: 13.7
Args:
chat_id (:obj:`str` | :obj:`int`): Unique identifier for the target chat or username of the
target supergroup (in the format ``@supergroupusername``)
Attributes:
type (:obj:`str`): Scope type :attr:`telegram.BotCommandScope.CHAT_ADMINISTRATORS`.
chat_id (:obj:`str` | :obj:`int`): Unique identifier for the target chat or username of the
target supergroup (in the format ``@supergroupusername``)
"""
__slots__ = ('chat_id',)
def __init__(self, chat_id: Union[str, int], **_kwargs: Any):
super().__init__(type=BotCommandScope.CHAT_ADMINISTRATORS)
self.chat_id = (
chat_id if isinstance(chat_id, str) and chat_id.startswith('@') else int(chat_id)
)
self._id_attrs = (self.type, self.chat_id)
class BotCommandScopeChatMember(BotCommandScope):
"""Represents the scope of bot commands, covering a specific member of a group or supergroup
chat.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`type`, :attr:`chat_id` and :attr:`user_id` are equal.
.. versionadded:: 13.7
Args:
chat_id (:obj:`str` | :obj:`int`): Unique identifier for the target chat or username of the
target supergroup (in the format ``@supergroupusername``)
user_id (:obj:`int`): Unique identifier of the target user.
Attributes:
type (:obj:`str`): Scope type :attr:`telegram.BotCommandScope.CHAT_MEMBER`.
chat_id (:obj:`str` | :obj:`int`): Unique identifier for the target chat or username of the
target supergroup (in the format ``@supergroupusername``)
user_id (:obj:`int`): Unique identifier of the target user.
"""
__slots__ = ('chat_id', 'user_id')
def __init__(self, chat_id: Union[str, int], user_id: int, **_kwargs: Any):
super().__init__(type=BotCommandScope.CHAT_MEMBER)
self.chat_id = (
chat_id if isinstance(chat_id, str) and chat_id.startswith('@') else int(chat_id)
)
self.user_id = int(user_id)
self._id_attrs = (self.type, self.chat_id, self.user_id)
+3 -1
View File
@@ -1,7 +1,7 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2021
# Copyright (C) 2015-2022
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
@@ -620,6 +620,7 @@ class CallbackQuery(TelegramObject):
reply_markup: ReplyMarkup = None,
timeout: ODVInput[float] = DEFAULT_NONE,
api_kwargs: JSONDict = None,
protect_content: bool = None,
) -> 'MessageId':
"""Shortcut for::
@@ -648,6 +649,7 @@ class CallbackQuery(TelegramObject):
reply_markup=reply_markup,
timeout=timeout,
api_kwargs=api_kwargs,
protect_content=protect_content,
)
MAX_ANSWER_TEXT_LENGTH: ClassVar[int] = constants.MAX_ANSWER_CALLBACK_QUERY_TEXT_LENGTH
+342 -23
View File
@@ -2,7 +2,7 @@
# pylint: disable=W0622
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2021
# Copyright (C) 2015-2022
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
@@ -18,11 +18,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 Chat."""
import warnings
from datetime import datetime
from typing import TYPE_CHECKING, List, Optional, ClassVar, Union, Tuple, Any
from telegram import ChatPhoto, TelegramObject, constants
from telegram import ChatPhoto, TelegramObject, constants, MenuButton
from telegram.utils.types import JSONDict, FileInput, ODVInput, DVInput
from telegram.utils.deprecate import TelegramDeprecationWarning
from .chatpermissions import ChatPermissions
from .chatlocation import ChatLocation
@@ -79,6 +81,11 @@ class Chat(TelegramObject):
Returned only in :meth:`telegram.Bot.get_chat`.
bio (:obj:`str`, optional): Bio of the other party in a private chat. Returned only in
:meth:`telegram.Bot.get_chat`.
has_private_forwards (:obj:`bool`, optional): :obj:`True`, if privacy settings of the other
party in the private chat allows to use ``tg://user?id=<user_id>`` links only in chats
with the user. Returned only in :meth:`telegram.Bot.get_chat`.
.. versionadded:: 13.9
description (:obj:`str`, optional): Description, for groups, supergroups and channel chats.
Returned only in :meth:`telegram.Bot.get_chat`.
invite_link (:obj:`str`, optional): Primary invite link, for groups, supergroups and
@@ -95,6 +102,10 @@ class Chat(TelegramObject):
:meth:`telegram.Bot.get_chat`.
.. versionadded:: 13.4
has_protected_content (:obj:`bool`, optional): :obj:`True`, if messages from the chat can't
be forwarded to other chats. Returned only in :meth:`telegram.Bot.get_chat`.
.. versionadded:: 13.9
bot (:class:`telegram.Bot`, optional): The Bot to use for instance methods.
sticker_set_name (:obj:`str`, optional): For supergroups, name of group sticker set.
Returned only in :meth:`telegram.Bot.get_chat`.
@@ -117,6 +128,11 @@ class Chat(TelegramObject):
photo (:class:`telegram.ChatPhoto`): Optional. Chat photo.
bio (:obj:`str`): Optional. Bio of the other party in a private chat. Returned only in
:meth:`telegram.Bot.get_chat`.
has_private_forwards (:obj:`bool`): Optional. :obj:`True`, if privacy settings of the other
party in the private chat allows to use ``tg://user?id=<user_id>`` links only in chats
with the user.
.. versionadded:: 13.9
description (:obj:`str`): Optional. Description, for groups, supergroups and channel chats.
invite_link (:obj:`str`): Optional. Primary invite link, for groups, supergroups and
channel. Returned only in :meth:`telegram.Bot.get_chat`.
@@ -132,6 +148,10 @@ class Chat(TelegramObject):
:meth:`telegram.Bot.get_chat`.
.. versionadded:: 13.4
has_protected_content (:obj:`bool`): Optional. :obj:`True`, if messages from the chat can't
be forwarded to other chats.
.. versionadded:: 13.9
sticker_set_name (:obj:`str`): Optional. For supergroups, name of Group sticker set.
can_set_sticker_set (:obj:`bool`): Optional. :obj:`True`, if the bot can change group the
sticker set.
@@ -164,6 +184,8 @@ class Chat(TelegramObject):
'linked_chat_id',
'all_members_are_administrators',
'message_auto_delete_time',
'has_protected_content',
'has_private_forwards',
'_id_attrs',
)
@@ -202,6 +224,8 @@ class Chat(TelegramObject):
linked_chat_id: int = None,
location: ChatLocation = None,
message_auto_delete_time: int = None,
has_private_forwards: bool = None,
has_protected_content: bool = None,
**_kwargs: Any,
):
# Required
@@ -216,6 +240,7 @@ class Chat(TelegramObject):
self.all_members_are_administrators = _kwargs.get('all_members_are_administrators')
self.photo = photo
self.bio = bio
self.has_private_forwards = has_private_forwards
self.description = description
self.invite_link = invite_link
self.pinned_message = pinned_message
@@ -224,6 +249,7 @@ class Chat(TelegramObject):
self.message_auto_delete_time = (
int(message_auto_delete_time) if message_auto_delete_time is not None else None
)
self.has_protected_content = has_protected_content
self.sticker_set_name = sticker_set_name
self.can_set_sticker_set = can_set_sticker_set
self.linked_chat_id = linked_chat_id
@@ -284,7 +310,7 @@ class Chat(TelegramObject):
For the documentation of the arguments, please see :meth:`telegram.Bot.leave_chat`.
Returns:
:obj:`bool` If the action was sent successfully.
:obj:`bool`: On success, :obj:`True` is returned.
"""
return self.bot.leave_chat(
@@ -318,19 +344,37 @@ class Chat(TelegramObject):
def get_members_count(
self, timeout: ODVInput[float] = DEFAULT_NONE, api_kwargs: JSONDict = None
) -> int:
"""
Deprecated, use :func:`~telegram.Chat.get_member_count` instead.
.. deprecated:: 13.7
"""
warnings.warn(
'`Chat.get_members_count` is deprecated. Use `Chat.get_member_count` instead.',
TelegramDeprecationWarning,
stacklevel=2,
)
return self.get_member_count(
timeout=timeout,
api_kwargs=api_kwargs,
)
def get_member_count(
self, timeout: ODVInput[float] = DEFAULT_NONE, api_kwargs: JSONDict = None
) -> int:
"""Shortcut for::
bot.get_chat_members_count(update.effective_chat.id, *args, **kwargs)
bot.get_chat_member_count(update.effective_chat.id, *args, **kwargs)
For the documentation of the arguments, please see
:meth:`telegram.Bot.get_chat_members_count`.
:meth:`telegram.Bot.get_chat_member_count`.
Returns:
:obj:`int`
"""
return self.bot.get_chat_members_count(
return self.bot.get_chat_member_count(
chat_id=self.id,
timeout=timeout,
api_kwargs=api_kwargs,
@@ -366,24 +410,45 @@ class Chat(TelegramObject):
until_date: Union[int, datetime] = None,
api_kwargs: JSONDict = None,
revoke_messages: bool = None,
) -> bool:
"""
Deprecated, use :func:`~telegram.Chat.ban_member` instead.
.. deprecated:: 13.7
"""
warnings.warn(
'`Chat.kick_member` is deprecated. Use `Chat.ban_member` instead.',
TelegramDeprecationWarning,
stacklevel=2,
)
return self.ban_member(
user_id=user_id,
timeout=timeout,
until_date=until_date,
api_kwargs=api_kwargs,
revoke_messages=revoke_messages,
)
def ban_member(
self,
user_id: Union[str, int],
timeout: ODVInput[float] = DEFAULT_NONE,
until_date: Union[int, datetime] = None,
api_kwargs: JSONDict = None,
revoke_messages: bool = None,
) -> bool:
"""Shortcut for::
bot.kick_chat_member(update.effective_chat.id, *args, **kwargs)
bot.ban_chat_member(update.effective_chat.id, *args, **kwargs)
For the documentation of the arguments, please see
:meth:`telegram.Bot.kick_chat_member`.
:meth:`telegram.Bot.ban_chat_member`.
Returns:
:obj:`bool`: If the action was sent successfully.
Note:
This method will only work if the `All Members Are Admins` setting is off in the
target group. Otherwise members may only be removed by the group's creator or by the
member that added them.
:obj:`bool`: On success, :obj:`True` is returned.
"""
return self.bot.kick_chat_member(
return self.bot.ban_chat_member(
chat_id=self.id,
user_id=user_id,
timeout=timeout,
@@ -392,6 +457,98 @@ class Chat(TelegramObject):
revoke_messages=revoke_messages,
)
def ban_sender_chat(
self,
sender_chat_id: int,
timeout: ODVInput[float] = DEFAULT_NONE,
api_kwargs: JSONDict = None,
) -> bool:
"""Shortcut for::
bot.ban_chat_sender_chat(chat_id=update.effective_chat.id, *args, **kwargs)
For the documentation of the arguments, please see
:meth:`telegram.Bot.ban_chat_sender_chat`.
.. versionadded:: 13.9
Returns:
:obj:`bool`: On success, :obj:`True` is returned.
"""
return self.bot.ban_chat_sender_chat(
chat_id=self.id, sender_chat_id=sender_chat_id, timeout=timeout, api_kwargs=api_kwargs
)
def ban_chat(
self,
chat_id: Union[str, int],
timeout: ODVInput[float] = DEFAULT_NONE,
api_kwargs: JSONDict = None,
) -> bool:
"""Shortcut for::
bot.ban_chat_sender_chat(sender_chat_id=update.effective_chat.id, *args, **kwargs)
For the documentation of the arguments, please see
:meth:`telegram.Bot.ban_chat_sender_chat`.
.. versionadded:: 13.9
Returns:
:obj:`bool`: On success, :obj:`True` is returned.
"""
return self.bot.ban_chat_sender_chat(
chat_id=chat_id, sender_chat_id=self.id, timeout=timeout, api_kwargs=api_kwargs
)
def unban_sender_chat(
self,
sender_chat_id: int,
timeout: ODVInput[float] = DEFAULT_NONE,
api_kwargs: JSONDict = None,
) -> bool:
"""Shortcut for::
bot.unban_chat_sender_chat(chat_id=update.effective_chat.id, *args, **kwargs)
For the documentation of the arguments, please see
:meth:`telegram.Bot.unban_chat_sender_chat`.
.. versionadded:: 13.9
Returns:
:obj:`bool`: On success, :obj:`True` is returned.
"""
return self.bot.unban_chat_sender_chat(
chat_id=self.id, sender_chat_id=sender_chat_id, timeout=timeout, api_kwargs=api_kwargs
)
def unban_chat(
self,
chat_id: Union[str, int],
timeout: ODVInput[float] = DEFAULT_NONE,
api_kwargs: JSONDict = None,
) -> bool:
"""Shortcut for::
bot.unban_chat_sender_chat(sender_chat_id=update.effective_chat.id, *args, **kwargs)
For the documentation of the arguments, please see
:meth:`telegram.Bot.unban_chat_sender_chat`.
.. versionadded:: 13.9
Returns:
:obj:`bool`: On success, :obj:`True` is returned.
"""
return self.bot.unban_chat_sender_chat(
chat_id=chat_id, sender_chat_id=self.id, timeout=timeout, api_kwargs=api_kwargs
)
def unban_member(
self,
user_id: Union[str, int],
@@ -406,7 +563,7 @@ class Chat(TelegramObject):
For the documentation of the arguments, please see :meth:`telegram.Bot.unban_chat_member`.
Returns:
:obj:`bool`: If the action was sent successfully.
:obj:`bool`: On success, :obj:`True` is returned.
"""
return self.bot.unban_chat_member(
@@ -433,6 +590,7 @@ class Chat(TelegramObject):
is_anonymous: bool = None,
can_manage_chat: bool = None,
can_manage_voice_chats: bool = None,
can_manage_video_chats: bool = None,
) -> bool:
"""Shortcut for::
@@ -443,8 +601,11 @@ class Chat(TelegramObject):
.. versionadded:: 13.2
..versionchanged:: 13.12
Since Bot API 6.0, voice chat was renamed to video chat.
Returns:
:obj:`bool`: If the action was sent successfully.
:obj:`bool`: On success, :obj:`True` is returned.
"""
return self.bot.promote_chat_member(
@@ -463,6 +624,7 @@ class Chat(TelegramObject):
is_anonymous=is_anonymous,
can_manage_chat=can_manage_chat,
can_manage_voice_chats=can_manage_voice_chats,
can_manage_video_chats=can_manage_video_chats,
)
def restrict_member(
@@ -483,7 +645,7 @@ class Chat(TelegramObject):
.. versionadded:: 13.2
Returns:
:obj:`bool`: If the action was sent successfully.
:obj:`bool`: On success, :obj:`True` is returned.
"""
return self.bot.restrict_chat_member(
@@ -509,7 +671,7 @@ class Chat(TelegramObject):
:meth:`telegram.Bot.set_chat_permissions`.
Returns:
:obj:`bool`: If the action was sent successfully.
:obj:`bool`: On success, :obj:`True` is returned.
"""
return self.bot.set_chat_permissions(
@@ -534,7 +696,7 @@ class Chat(TelegramObject):
:meth:`telegram.Bot.set_chat_administrator_custom_title`.
Returns:
:obj:`bool`: If the action was sent successfully.
:obj:`bool`: On success, :obj:`True` is returned.
"""
return self.bot.set_chat_administrator_custom_title(
@@ -635,6 +797,7 @@ class Chat(TelegramObject):
api_kwargs: JSONDict = None,
allow_sending_without_reply: ODVInput[bool] = DEFAULT_NONE,
entities: Union[List['MessageEntity'], Tuple['MessageEntity', ...]] = None,
protect_content: bool = None,
) -> 'Message':
"""Shortcut for::
@@ -658,6 +821,7 @@ class Chat(TelegramObject):
api_kwargs=api_kwargs,
allow_sending_without_reply=allow_sending_without_reply,
entities=entities,
protect_content=protect_content,
)
def send_media_group(
@@ -670,6 +834,7 @@ class Chat(TelegramObject):
timeout: DVInput[float] = DEFAULT_20,
api_kwargs: JSONDict = None,
allow_sending_without_reply: ODVInput[bool] = DEFAULT_NONE,
protect_content: bool = None,
) -> List['Message']:
"""Shortcut for::
@@ -678,7 +843,7 @@ class Chat(TelegramObject):
For the documentation of the arguments, please see :meth:`telegram.Bot.send_media_group`.
Returns:
List[:class:`telegram.Message`:] On success, instance representing the message posted.
List[:class:`telegram.Message`]: On success, instance representing the message posted.
"""
return self.bot.send_media_group(
@@ -689,6 +854,7 @@ class Chat(TelegramObject):
timeout=timeout,
api_kwargs=api_kwargs,
allow_sending_without_reply=allow_sending_without_reply,
protect_content=protect_content,
)
def send_chat_action(
@@ -730,6 +896,7 @@ class Chat(TelegramObject):
allow_sending_without_reply: ODVInput[bool] = DEFAULT_NONE,
caption_entities: Union[List['MessageEntity'], Tuple['MessageEntity', ...]] = None,
filename: str = None,
protect_content: bool = None,
) -> 'Message':
"""Shortcut for::
@@ -754,6 +921,7 @@ class Chat(TelegramObject):
allow_sending_without_reply=allow_sending_without_reply,
caption_entities=caption_entities,
filename=filename,
protect_content=protect_content,
)
def send_contact(
@@ -769,6 +937,7 @@ class Chat(TelegramObject):
vcard: str = None,
api_kwargs: JSONDict = None,
allow_sending_without_reply: ODVInput[bool] = DEFAULT_NONE,
protect_content: bool = None,
) -> 'Message':
"""Shortcut for::
@@ -793,6 +962,7 @@ class Chat(TelegramObject):
vcard=vcard,
api_kwargs=api_kwargs,
allow_sending_without_reply=allow_sending_without_reply,
protect_content=protect_content,
)
def send_audio(
@@ -812,6 +982,7 @@ class Chat(TelegramObject):
allow_sending_without_reply: ODVInput[bool] = DEFAULT_NONE,
caption_entities: Union[List['MessageEntity'], Tuple['MessageEntity', ...]] = None,
filename: str = None,
protect_content: bool = None,
) -> 'Message':
"""Shortcut for::
@@ -840,6 +1011,7 @@ class Chat(TelegramObject):
allow_sending_without_reply=allow_sending_without_reply,
caption_entities=caption_entities,
filename=filename,
protect_content=protect_content,
)
def send_document(
@@ -857,6 +1029,7 @@ class Chat(TelegramObject):
disable_content_type_detection: bool = None,
allow_sending_without_reply: ODVInput[bool] = DEFAULT_NONE,
caption_entities: Union[List['MessageEntity'], Tuple['MessageEntity', ...]] = None,
protect_content: bool = None,
) -> 'Message':
"""Shortcut for::
@@ -883,6 +1056,7 @@ class Chat(TelegramObject):
disable_content_type_detection=disable_content_type_detection,
allow_sending_without_reply=allow_sending_without_reply,
caption_entities=caption_entities,
protect_content=protect_content,
)
def send_dice(
@@ -894,6 +1068,7 @@ class Chat(TelegramObject):
emoji: str = None,
api_kwargs: JSONDict = None,
allow_sending_without_reply: ODVInput[bool] = DEFAULT_NONE,
protect_content: bool = None,
) -> 'Message':
"""Shortcut for::
@@ -914,6 +1089,7 @@ class Chat(TelegramObject):
emoji=emoji,
api_kwargs=api_kwargs,
allow_sending_without_reply=allow_sending_without_reply,
protect_content=protect_content,
)
def send_game(
@@ -925,6 +1101,7 @@ class Chat(TelegramObject):
timeout: ODVInput[float] = DEFAULT_NONE,
api_kwargs: JSONDict = None,
allow_sending_without_reply: ODVInput[bool] = DEFAULT_NONE,
protect_content: bool = None,
) -> 'Message':
"""Shortcut for::
@@ -945,6 +1122,7 @@ class Chat(TelegramObject):
timeout=timeout,
api_kwargs=api_kwargs,
allow_sending_without_reply=allow_sending_without_reply,
protect_content=protect_content,
)
def send_invoice(
@@ -976,6 +1154,7 @@ class Chat(TelegramObject):
allow_sending_without_reply: ODVInput[bool] = DEFAULT_NONE,
max_tip_amount: int = None,
suggested_tip_amounts: List[int] = None,
protect_content: bool = None,
) -> 'Message':
"""Shortcut for::
@@ -1024,6 +1203,7 @@ class Chat(TelegramObject):
allow_sending_without_reply=allow_sending_without_reply,
max_tip_amount=max_tip_amount,
suggested_tip_amounts=suggested_tip_amounts,
protect_content=protect_content,
)
def send_location(
@@ -1041,6 +1221,7 @@ class Chat(TelegramObject):
heading: int = None,
proximity_alert_radius: int = None,
allow_sending_without_reply: ODVInput[bool] = DEFAULT_NONE,
protect_content: bool = None,
) -> 'Message':
"""Shortcut for::
@@ -1067,6 +1248,7 @@ class Chat(TelegramObject):
heading=heading,
proximity_alert_radius=proximity_alert_radius,
allow_sending_without_reply=allow_sending_without_reply,
protect_content=protect_content,
)
def send_animation(
@@ -1086,6 +1268,7 @@ class Chat(TelegramObject):
allow_sending_without_reply: ODVInput[bool] = DEFAULT_NONE,
caption_entities: Union[List['MessageEntity'], Tuple['MessageEntity', ...]] = None,
filename: str = None,
protect_content: bool = None,
) -> 'Message':
"""Shortcut for::
@@ -1114,6 +1297,7 @@ class Chat(TelegramObject):
allow_sending_without_reply=allow_sending_without_reply,
caption_entities=caption_entities,
filename=filename,
protect_content=protect_content,
)
def send_sticker(
@@ -1125,6 +1309,7 @@ class Chat(TelegramObject):
timeout: DVInput[float] = DEFAULT_20,
api_kwargs: JSONDict = None,
allow_sending_without_reply: ODVInput[bool] = DEFAULT_NONE,
protect_content: bool = None,
) -> 'Message':
"""Shortcut for::
@@ -1145,6 +1330,7 @@ class Chat(TelegramObject):
timeout=timeout,
api_kwargs=api_kwargs,
allow_sending_without_reply=allow_sending_without_reply,
protect_content=protect_content,
)
def send_venue(
@@ -1164,6 +1350,7 @@ class Chat(TelegramObject):
google_place_id: str = None,
google_place_type: str = None,
allow_sending_without_reply: ODVInput[bool] = DEFAULT_NONE,
protect_content: bool = None,
) -> 'Message':
"""Shortcut for::
@@ -1192,6 +1379,7 @@ class Chat(TelegramObject):
google_place_id=google_place_id,
google_place_type=google_place_type,
allow_sending_without_reply=allow_sending_without_reply,
protect_content=protect_content,
)
def send_video(
@@ -1212,6 +1400,7 @@ class Chat(TelegramObject):
allow_sending_without_reply: ODVInput[bool] = DEFAULT_NONE,
caption_entities: Union[List['MessageEntity'], Tuple['MessageEntity', ...]] = None,
filename: str = None,
protect_content: bool = None,
) -> 'Message':
"""Shortcut for::
@@ -1241,6 +1430,7 @@ class Chat(TelegramObject):
allow_sending_without_reply=allow_sending_without_reply,
caption_entities=caption_entities,
filename=filename,
protect_content=protect_content,
)
def send_video_note(
@@ -1256,6 +1446,7 @@ class Chat(TelegramObject):
api_kwargs: JSONDict = None,
allow_sending_without_reply: ODVInput[bool] = DEFAULT_NONE,
filename: str = None,
protect_content: bool = None,
) -> 'Message':
"""Shortcut for::
@@ -1280,6 +1471,7 @@ class Chat(TelegramObject):
api_kwargs=api_kwargs,
allow_sending_without_reply=allow_sending_without_reply,
filename=filename,
protect_content=protect_content,
)
def send_voice(
@@ -1296,6 +1488,7 @@ class Chat(TelegramObject):
allow_sending_without_reply: ODVInput[bool] = DEFAULT_NONE,
caption_entities: Union[List['MessageEntity'], Tuple['MessageEntity', ...]] = None,
filename: str = None,
protect_content: bool = None,
) -> 'Message':
"""Shortcut for::
@@ -1321,6 +1514,7 @@ class Chat(TelegramObject):
allow_sending_without_reply=allow_sending_without_reply,
caption_entities=caption_entities,
filename=filename,
protect_content=protect_content,
)
def send_poll(
@@ -1344,6 +1538,7 @@ class Chat(TelegramObject):
api_kwargs: JSONDict = None,
allow_sending_without_reply: ODVInput[bool] = DEFAULT_NONE,
explanation_entities: Union[List['MessageEntity'], Tuple['MessageEntity', ...]] = None,
protect_content: bool = None,
) -> 'Message':
"""Shortcut for::
@@ -1375,6 +1570,7 @@ class Chat(TelegramObject):
api_kwargs=api_kwargs,
allow_sending_without_reply=allow_sending_without_reply,
explanation_entities=explanation_entities,
protect_content=protect_content,
)
def send_copy(
@@ -1390,6 +1586,7 @@ class Chat(TelegramObject):
reply_markup: 'ReplyMarkup' = None,
timeout: ODVInput[float] = DEFAULT_NONE,
api_kwargs: JSONDict = None,
protect_content: bool = None,
) -> 'MessageId':
"""Shortcut for::
@@ -1414,6 +1611,7 @@ class Chat(TelegramObject):
reply_markup=reply_markup,
timeout=timeout,
api_kwargs=api_kwargs,
protect_content=protect_content,
)
def copy_message(
@@ -1429,6 +1627,7 @@ class Chat(TelegramObject):
reply_markup: 'ReplyMarkup' = None,
timeout: ODVInput[float] = DEFAULT_NONE,
api_kwargs: JSONDict = None,
protect_content: bool = None,
) -> 'MessageId':
"""Shortcut for::
@@ -1453,6 +1652,7 @@ class Chat(TelegramObject):
reply_markup=reply_markup,
timeout=timeout,
api_kwargs=api_kwargs,
protect_content=protect_content,
)
def export_invite_link(
@@ -1483,6 +1683,8 @@ class Chat(TelegramObject):
member_limit: int = None,
timeout: ODVInput[float] = DEFAULT_NONE,
api_kwargs: JSONDict = None,
name: str = None,
creates_join_request: bool = None,
) -> 'ChatInviteLink':
"""Shortcut for::
@@ -1493,6 +1695,10 @@ class Chat(TelegramObject):
.. versionadded:: 13.4
.. versionchanged:: 13.8
Edited signature according to the changes of
:meth:`telegram.Bot.create_chat_invite_link`.
Returns:
:class:`telegram.ChatInviteLink`
@@ -1503,6 +1709,8 @@ class Chat(TelegramObject):
member_limit=member_limit,
timeout=timeout,
api_kwargs=api_kwargs,
name=name,
creates_join_request=creates_join_request,
)
def edit_invite_link(
@@ -1512,6 +1720,8 @@ class Chat(TelegramObject):
member_limit: int = None,
timeout: ODVInput[float] = DEFAULT_NONE,
api_kwargs: JSONDict = None,
name: str = None,
creates_join_request: bool = None,
) -> 'ChatInviteLink':
"""Shortcut for::
@@ -1522,6 +1732,9 @@ class Chat(TelegramObject):
.. versionadded:: 13.4
.. versionchanged:: 13.8
Edited signature according to the changes of :meth:`telegram.Bot.edit_chat_invite_link`.
Returns:
:class:`telegram.ChatInviteLink`
@@ -1533,6 +1746,8 @@ class Chat(TelegramObject):
member_limit=member_limit,
timeout=timeout,
api_kwargs=api_kwargs,
name=name,
creates_join_request=creates_join_request,
)
def revoke_invite_link(
@@ -1557,3 +1772,107 @@ class Chat(TelegramObject):
return self.bot.revoke_chat_invite_link(
chat_id=self.id, invite_link=invite_link, timeout=timeout, api_kwargs=api_kwargs
)
def approve_join_request(
self,
user_id: int,
timeout: ODVInput[float] = DEFAULT_NONE,
api_kwargs: JSONDict = None,
) -> bool:
"""Shortcut for::
bot.approve_chat_join_request(chat_id=update.effective_chat.id, *args, **kwargs)
For the documentation of the arguments, please see
:meth:`telegram.Bot.approve_chat_join_request`.
.. versionadded:: 13.8
Returns:
:obj:`bool`: On success, :obj:`True` is returned.
"""
return self.bot.approve_chat_join_request(
chat_id=self.id, user_id=user_id, timeout=timeout, api_kwargs=api_kwargs
)
def decline_join_request(
self,
user_id: int,
timeout: ODVInput[float] = DEFAULT_NONE,
api_kwargs: JSONDict = None,
) -> bool:
"""Shortcut for::
bot.decline_chat_join_request(chat_id=update.effective_chat.id, *args, **kwargs)
For the documentation of the arguments, please see
:meth:`telegram.Bot.decline_chat_join_request`.
.. versionadded:: 13.8
Returns:
:obj:`bool`: On success, :obj:`True` is returned.
"""
return self.bot.decline_chat_join_request(
chat_id=self.id, user_id=user_id, timeout=timeout, api_kwargs=api_kwargs
)
def set_menu_button(
self,
menu_button: MenuButton = None,
timeout: ODVInput[float] = DEFAULT_NONE,
api_kwargs: JSONDict = None,
) -> bool:
"""Shortcut for::
bot.set_chat_menu_button(chat_id=update.effective_chat.id, *args, **kwargs)
For the documentation of the arguments, please see
:meth:`telegram.Bot.set_chat_menu_button`.
Caution:
Can only work, if the chat is a private chat.
..seealso:: :meth:`get_menu_button`
.. versionadded:: 13.12
Returns:
:obj:`bool`: On success, :obj:`True` is returned.
"""
return self.bot.set_chat_menu_button(
chat_id=self.id,
menu_button=menu_button,
timeout=timeout,
api_kwargs=api_kwargs,
)
def get_menu_button(
self,
timeout: ODVInput[float] = DEFAULT_NONE,
api_kwargs: JSONDict = None,
) -> MenuButton:
"""Shortcut for::
bot.get_chat_menu_button(chat_id=update.effective_chat.id, *args, **kwargs)
For the documentation of the arguments, please see
:meth:`telegram.Bot.set_chat_menu_button`.
Caution:
Can only work, if the chat is a private chat.
..seealso:: :meth:`set_menu_button`
.. versionadded:: 13.12
Returns:
:class:`telegram.MenuButton`: On success, the current menu button is returned.
"""
return self.bot.get_chat_menu_button(
chat_id=self.id,
timeout=timeout,
api_kwargs=api_kwargs,
)
+5 -1
View File
@@ -2,7 +2,7 @@
# pylint: disable=R0903
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2021
# Copyright (C) 2015-2022
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
@@ -59,6 +59,10 @@ class ChatAction:
"""
UPLOAD_DOCUMENT: ClassVar[str] = constants.CHATACTION_UPLOAD_DOCUMENT
""":const:`telegram.constants.CHATACTION_UPLOAD_DOCUMENT`"""
CHOOSE_STICKER: ClassVar[str] = constants.CHATACTION_CHOOSE_STICKER
""":const:`telegram.constants.CHOOSE_STICKER`
.. versionadded:: 13.8"""
UPLOAD_PHOTO: ClassVar[str] = constants.CHATACTION_UPLOAD_PHOTO
""":const:`telegram.constants.CHATACTION_UPLOAD_PHOTO`"""
UPLOAD_VIDEO: ClassVar[str] = constants.CHATACTION_UPLOAD_VIDEO
+167
View File
@@ -0,0 +1,167 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2022
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the class which represents a Telegram ChatAdministratorRights."""
from typing import Any
from telegram import TelegramObject
class ChatAdministratorRights(TelegramObject):
"""Represents the rights of an administrator in a chat.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`is_anonymous`, :attr:`can_manage_chat`,
:attr:`can_delete_messages`, :attr:`can_manage_video_chats`, :attr:`can_restrict_members`,
:attr:`can_promote_members`, :attr:`can_change_info`, :attr:`can_invite_users`,
:attr:`can_post_messages`, :attr:`can_edit_messages`, :attr:`can_pin_messages` are equal.
.. seealso: :meth:`Bot.set_my_default_administrator_rights`,
:meth:`Bot.get_my_default_administrator_rights`
.. versionadded:: 13.12
Args:
is_anonymous (:obj:`bool`): :obj:`True`, if the user's presence in the chat is hidden.
can_manage_chat (:obj:`bool`): :obj:`True`, if the administrator can access the chat event
log, chat statistics, message statistics in channels, see channel members, see
anonymous administrators in supergroups and ignore slow mode. Implied by any other
administrator privilege.
can_delete_messages (:obj:`bool`): :obj:`True`, if the administrator can delete messages of
other users.
can_manage_video_chats (:obj:`bool`): :obj:`True`, if the administrator can manage video
chats.
can_restrict_members (:obj:`bool`): :obj:`True`, if the administrator can restrict, ban or
unban chat members.
can_promote_members (:obj:`bool`): :obj:`True`, if the administrator can add new
administrators with a subset of their own privileges or demote administrators that he
has promoted, directly or indirectly (promoted by administrators that were appointed by
the user.)
can_change_info (:obj:`bool`): :obj:`True`, if the user is allowed to change the chat title
, photo and other settings.
can_invite_users (:obj:`bool`): :obj:`True`, if the user is allowed to invite new users to
the chat.
can_post_messages (:obj:`bool`, optional): :obj:`True`, if the administrator can post
messages in the channel; channels only.
can_edit_messages (:obj:`bool`, optional): :obj:`True`, if the administrator can edit
messages of other users.
can_pin_messages (:obj:`bool`, optional): :obj:`True`, if the user is allowed to pin
messages; groups and supergroups only.
Attributes:
is_anonymous (:obj:`bool`): :obj:`True`, if the user's presence in the chat is hidden.
can_manage_chat (:obj:`bool`): :obj:`True`, if the administrator can access the chat event
log, chat statistics, message statistics in channels, see channel members, see
anonymous administrators in supergroups and ignore slow mode. Implied by any other
administrator privilege.
can_delete_messages (:obj:`bool`): :obj:`True`, if the administrator can delete messages of
other users.
can_manage_video_chats (:obj:`bool`): :obj:`True`, if the administrator can manage video
chats.
can_restrict_members (:obj:`bool`): :obj:`True`, if the administrator can restrict, ban or
unban chat members.
can_promote_members (:obj:`bool`): :obj:`True`, if the administrator can add new
administrators with a subset of their own privileges or demote administrators that he
has promoted, directly or indirectly (promoted by administrators that were appointed by
the user.)
can_change_info (:obj:`bool`): :obj:`True`, if the user is allowed to change the chat title
,photo and other settings.
can_invite_users (:obj:`bool`): :obj:`True`, if the user is allowed to invite new users to
the chat.
can_post_messages (:obj:`bool`): Optional. :obj:`True`, if the administrator can post
messages in the channel; channels only.
can_edit_messages (:obj:`bool`): Optional. :obj:`True`, if the administrator can edit
messages of other users.
can_pin_messages (:obj:`bool`): Optional. :obj:`True`, if the user is allowed to pin
messages; groups and supergroups only.
"""
__slots__ = (
'is_anonymous',
'can_manage_chat',
'can_delete_messages',
'can_manage_video_chats',
'can_restrict_members',
'can_promote_members',
'can_change_info',
'can_invite_users',
'can_post_messages',
'can_edit_messages',
'can_pin_messages',
'_id_attrs',
)
def __init__(
self,
is_anonymous: bool,
can_manage_chat: bool,
can_delete_messages: bool,
can_manage_video_chats: bool,
can_restrict_members: bool,
can_promote_members: bool,
can_change_info: bool,
can_invite_users: bool,
can_post_messages: bool = None,
can_edit_messages: bool = None,
can_pin_messages: bool = None,
**_kwargs: Any,
) -> None:
# Required
self.is_anonymous = is_anonymous
self.can_manage_chat = can_manage_chat
self.can_delete_messages = can_delete_messages
self.can_manage_video_chats = can_manage_video_chats
self.can_restrict_members = can_restrict_members
self.can_promote_members = can_promote_members
self.can_change_info = can_change_info
self.can_invite_users = can_invite_users
# Optionals
self.can_post_messages = can_post_messages
self.can_edit_messages = can_edit_messages
self.can_pin_messages = can_pin_messages
self._id_attrs = (
self.is_anonymous,
self.can_manage_chat,
self.can_delete_messages,
self.can_manage_video_chats,
self.can_restrict_members,
self.can_promote_members,
self.can_change_info,
self.can_invite_users,
self.can_post_messages,
self.can_edit_messages,
self.can_pin_messages,
)
@classmethod
def all_rights(cls) -> 'ChatAdministratorRights':
"""
This method returns the :class:`ChatAdministratorRights` object with all attributes set to
:obj:`True`. This is e.g. useful when changing the bot's default administrator rights with
:meth:`telegram.Bot.set_my_default_administrator_rights`.
"""
return cls(True, True, True, True, True, True, True, True, True, True, True)
@classmethod
def no_rights(cls) -> 'ChatAdministratorRights':
"""
This method returns the :class:`ChatAdministratorRights` object with all attributes set to
:obj:`False`.
"""
return cls(False, False, False, False, False, False, False, False, False, False, False)
+34 -2
View File
@@ -1,7 +1,7 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2021
# Copyright (C) 2015-2022
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
@@ -46,6 +46,17 @@ class ChatInviteLink(TelegramObject):
has been expired.
member_limit (:obj:`int`, optional): Maximum number of users that can be members of the
chat simultaneously after joining the chat via this invite link; 1-99999.
name (:obj:`str`, optional): Invite link name.
.. versionadded:: 13.8
creates_join_request (:obj:`bool`, optional): :obj:`True`, if users joining the chat via
the link need to be approved by chat administrators.
.. versionadded:: 13.8
pending_join_request_count (:obj:`int`, optional): Number of pending join requests
created using this link.
.. versionadded:: 13.8
Attributes:
invite_link (:obj:`str`): The invite link. If the link was created by another chat
@@ -57,6 +68,17 @@ class ChatInviteLink(TelegramObject):
has been expired.
member_limit (:obj:`int`): Optional. Maximum number of users that can be members
of the chat simultaneously after joining the chat via this invite link; 1-99999.
name (:obj:`str`): Optional. Invite link name.
.. versionadded:: 13.8
creates_join_request (:obj:`bool`): Optional. :obj:`True`, if users joining the chat via
the link need to be approved by chat administrators.
.. versionadded:: 13.8
pending_join_request_count (:obj:`int`): Optional. Number of pending join requests
created using this link.
.. versionadded:: 13.8
"""
@@ -67,6 +89,9 @@ class ChatInviteLink(TelegramObject):
'is_revoked',
'expire_date',
'member_limit',
'name',
'creates_join_request',
'pending_join_request_count',
'_id_attrs',
)
@@ -78,6 +103,9 @@ class ChatInviteLink(TelegramObject):
is_revoked: bool,
expire_date: datetime.datetime = None,
member_limit: int = None,
name: str = None,
creates_join_request: bool = None,
pending_join_request_count: int = None,
**_kwargs: Any,
):
# Required
@@ -89,7 +117,11 @@ class ChatInviteLink(TelegramObject):
# Optionals
self.expire_date = expire_date
self.member_limit = int(member_limit) if member_limit is not None else None
self.name = name
self.creates_join_request = creates_join_request
self.pending_join_request_count = (
int(pending_join_request_count) if pending_join_request_count is not None else None
)
self._id_attrs = (self.invite_link, self.creator, self.is_primary, self.is_revoked)
@classmethod
+159
View File
@@ -0,0 +1,159 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2022
# 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 ChatJoinRequest."""
import datetime
from typing import TYPE_CHECKING, Any, Optional
from telegram import TelegramObject, User, Chat, ChatInviteLink
from telegram.utils.helpers import from_timestamp, to_timestamp, DEFAULT_NONE
from telegram.utils.types import JSONDict, ODVInput
if TYPE_CHECKING:
from telegram import Bot
class ChatJoinRequest(TelegramObject):
"""This object represents a join request sent to a chat.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`chat`, :attr:`from_user` and :attr:`date` are equal.
Note:
Since Bot API 5.5, bots are allowed to contact users who sent a join request to a chat
where the bot is an administrator with the
:attr:`~telegram.ChatMemberAdministrator.can_invite_users` administrator right even if
the user never interacted with the bot before.
.. versionadded:: 13.8
Args:
chat (:class:`telegram.Chat`): Chat to which the request was sent.
from_user (:class:`telegram.User`): User that sent the join request.
date (:class:`datetime.datetime`): Date the request was sent.
bio (:obj:`str`, optional): Bio of the user.
invite_link (:class:`telegram.ChatInviteLink`, optional): Chat invite link that was used
by the user to send the join request.
bot (:class:`telegram.Bot`, optional): The Bot to use for instance methods.
Attributes:
chat (:class:`telegram.Chat`): Chat to which the request was sent.
from_user (:class:`telegram.User`): User that sent the join request.
date (:class:`datetime.datetime`): Date the request was sent.
bio (:obj:`str`): Optional. Bio of the user.
invite_link (:class:`telegram.ChatInviteLink`): Optional. Chat invite link that was used
by the user to send the join request.
"""
__slots__ = (
'chat',
'from_user',
'date',
'bio',
'invite_link',
'bot',
'_id_attrs',
)
def __init__(
self,
chat: Chat,
from_user: User,
date: datetime.datetime,
bio: str = None,
invite_link: ChatInviteLink = None,
bot: 'Bot' = None,
**_kwargs: Any,
):
# Required
self.chat = chat
self.from_user = from_user
self.date = date
# Optionals
self.bio = bio
self.invite_link = invite_link
self.bot = bot
self._id_attrs = (self.chat, self.from_user, self.date)
@classmethod
def de_json(cls, data: Optional[JSONDict], bot: 'Bot') -> Optional['ChatJoinRequest']:
"""See :meth:`telegram.TelegramObject.de_json`."""
data = cls._parse_data(data)
if not data:
return None
data['chat'] = Chat.de_json(data.get('chat'), bot)
data['from_user'] = User.de_json(data.get('from'), bot)
data['date'] = from_timestamp(data.get('date', None))
data['invite_link'] = ChatInviteLink.de_json(data.get('invite_link'), bot)
return cls(bot=bot, **data)
def to_dict(self) -> JSONDict:
"""See :meth:`telegram.TelegramObject.to_dict`."""
data = super().to_dict()
data['date'] = to_timestamp(self.date)
return data
def approve(
self,
timeout: ODVInput[float] = DEFAULT_NONE,
api_kwargs: JSONDict = None,
) -> bool:
"""Shortcut for::
bot.approve_chat_join_request(chat_id=update.effective_chat.id,
user_id=update.effective_user.id, *args, **kwargs)
For the documentation of the arguments, please see
:meth:`telegram.Bot.approve_chat_join_request`.
Returns:
:obj:`bool`: On success, :obj:`True` is returned.
"""
return self.bot.approve_chat_join_request(
chat_id=self.chat.id, user_id=self.from_user.id, timeout=timeout, api_kwargs=api_kwargs
)
def decline(
self,
timeout: ODVInput[float] = DEFAULT_NONE,
api_kwargs: JSONDict = None,
) -> bool:
"""Shortcut for::
bot.decline_chat_join_request(chat_id=update.effective_chat.id,
user_id=update.effective_user.id, *args, **kwargs)
For the documentation of the arguments, please see
:meth:`telegram.Bot.decline_chat_join_request`.
Returns:
:obj:`bool`: On success, :obj:`True` is returned.
"""
return self.bot.decline_chat_join_request(
chat_id=self.chat.id, user_id=self.from_user.id, timeout=timeout, api_kwargs=api_kwargs
)
+1 -1
View File
@@ -1,7 +1,7 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2021
# Copyright (C) 2015-2022
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
+503 -6
View File
@@ -1,7 +1,7 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2021
# Copyright (C) 2015-2022
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
@@ -18,7 +18,7 @@
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram ChatMember."""
import datetime
from typing import TYPE_CHECKING, Any, Optional, ClassVar
from typing import TYPE_CHECKING, Any, Optional, ClassVar, Dict, Type
from telegram import TelegramObject, User, constants
from telegram.utils.helpers import from_timestamp, to_timestamp
@@ -29,113 +29,239 @@ if TYPE_CHECKING:
class ChatMember(TelegramObject):
"""This object contains information about one member of a chat.
"""Base class for Telegram ChatMember Objects.
Currently, the following 6 types of chat members are supported:
* :class:`telegram.ChatMemberOwner`
* :class:`telegram.ChatMemberAdministrator`
* :class:`telegram.ChatMemberMember`
* :class:`telegram.ChatMemberRestricted`
* :class:`telegram.ChatMemberLeft`
* :class:`telegram.ChatMemberBanned`
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`user` and :attr:`status` are equal.
Note:
As of Bot API 5.3, :class:`ChatMember` is nothing but the base class for the subclasses
listed above and is no longer returned directly by :meth:`~telegram.Bot.get_chat`.
Therefore, most of the arguments and attributes were deprecated and you should no longer
use :class:`ChatMember` directly.
Args:
user (:class:`telegram.User`): Information about the user.
status (:obj:`str`): The member's status in the chat. Can be 'creator', 'administrator',
'member', 'restricted', 'left' or 'kicked'.
status (:obj:`str`): The member's status in the chat. Can be
:attr:`~telegram.ChatMember.ADMINISTRATOR`, :attr:`~telegram.ChatMember.CREATOR`,
:attr:`~telegram.ChatMember.KICKED`, :attr:`~telegram.ChatMember.LEFT`,
:attr:`~telegram.ChatMember.MEMBER` or :attr:`~telegram.ChatMember.RESTRICTED`.
custom_title (:obj:`str`, optional): Owner and administrators only.
Custom title for this user.
.. deprecated:: 13.7
is_anonymous (:obj:`bool`, optional): Owner and administrators only. :obj:`True`, if the
user's presence in the chat is hidden.
.. deprecated:: 13.7
until_date (:class:`datetime.datetime`, optional): Restricted and kicked only. Date when
restrictions will be lifted for this user.
.. deprecated:: 13.7
can_be_edited (:obj:`bool`, optional): Administrators only. :obj:`True`, if the bot is
allowed to edit administrator privileges of that user.
.. deprecated:: 13.7
can_manage_chat (:obj:`bool`, optional): Administrators only. :obj:`True`, if the
administrator can access the chat event log, chat statistics, message statistics in
channels, see channel members, see anonymous administrators in supergroups and ignore
slow mode. Implied by any other administrator privilege.
.. versionadded:: 13.4
.. deprecated:: 13.7
can_manage_voice_chats (:obj:`bool`, optional): Administrators only. :obj:`True`, if the
administrator can manage voice chats.
.. versionadded:: 13.4
.. deprecated:: 13.7
can_change_info (:obj:`bool`, optional): Administrators and restricted only. :obj:`True`,
if the user can change the chat title, photo and other settings.
.. deprecated:: 13.7
can_post_messages (:obj:`bool`, optional): Administrators only. :obj:`True`, if the
administrator can post in the channel, channels only.
.. deprecated:: 13.7
can_edit_messages (:obj:`bool`, optional): Administrators only. :obj:`True`, if the
administrator can edit messages of other users and can pin messages; channels only.
.. deprecated:: 13.7
can_delete_messages (:obj:`bool`, optional): Administrators only. :obj:`True`, if the
administrator can delete messages of other users.
.. deprecated:: 13.7
can_invite_users (:obj:`bool`, optional): Administrators and restricted only. :obj:`True`,
if the user can invite new users to the chat.
.. deprecated:: 13.7
can_restrict_members (:obj:`bool`, optional): Administrators only. :obj:`True`, if the
administrator can restrict, ban or unban chat members.
.. deprecated:: 13.7
can_pin_messages (:obj:`bool`, optional): Administrators and restricted only. :obj:`True`,
if the user can pin messages, groups and supergroups only.
.. deprecated:: 13.7
can_promote_members (:obj:`bool`, optional): Administrators only. :obj:`True`, if the
administrator can add new administrators with a subset of his own privileges or demote
administrators that he has promoted, directly or indirectly (promoted by administrators
that were appointed by the user).
.. deprecated:: 13.7
is_member (:obj:`bool`, optional): Restricted only. :obj:`True`, if the user is a member of
the chat at the moment of the request.
.. deprecated:: 13.7
can_send_messages (:obj:`bool`, optional): Restricted only. :obj:`True`, if the user can
send text messages, contacts, locations and venues.
.. deprecated:: 13.7
can_send_media_messages (:obj:`bool`, optional): Restricted only. :obj:`True`, if the user
can send audios, documents, photos, videos, video notes and voice notes.
.. deprecated:: 13.7
can_send_polls (:obj:`bool`, optional): Restricted only. :obj:`True`, if the user is
allowed to send polls.
.. deprecated:: 13.7
can_send_other_messages (:obj:`bool`, optional): Restricted only. :obj:`True`, if the user
can send animations, games, stickers and use inline bots.
.. deprecated:: 13.7
can_add_web_page_previews (:obj:`bool`, optional): Restricted only. :obj:`True`, if user
may add web page previews to his messages.
.. deprecated:: 13.7
Attributes:
user (:class:`telegram.User`): Information about the user.
status (:obj:`str`): The member's status in the chat.
custom_title (:obj:`str`): Optional. Custom title for owner and administrators.
.. deprecated:: 13.7
is_anonymous (:obj:`bool`): Optional. :obj:`True`, if the user's presence in the chat is
hidden.
.. deprecated:: 13.7
until_date (:class:`datetime.datetime`): Optional. Date when restrictions will be lifted
for this user.
.. deprecated:: 13.7
can_be_edited (:obj:`bool`): Optional. If the bot is allowed to edit administrator
privileges of that user.
.. deprecated:: 13.7
can_manage_chat (:obj:`bool`): Optional. If the administrator can access the chat event
log, chat statistics, message statistics in channels, see channel members, see
anonymous administrators in supergroups and ignore slow mode.
.. versionadded:: 13.4
.. deprecated:: 13.7
can_manage_voice_chats (:obj:`bool`): Optional. if the administrator can manage
voice chats.
.. versionadded:: 13.4
.. deprecated:: 13.7
can_change_info (:obj:`bool`): Optional. If the user can change the chat title, photo and
other settings.
.. deprecated:: 13.7
can_post_messages (:obj:`bool`): Optional. If the administrator can post in the channel.
.. deprecated:: 13.7
can_edit_messages (:obj:`bool`): Optional. If the administrator can edit messages of other
users.
.. deprecated:: 13.7
can_delete_messages (:obj:`bool`): Optional. If the administrator can delete messages of
other users.
.. deprecated:: 13.7
can_invite_users (:obj:`bool`): Optional. If the user can invite new users to the chat.
.. deprecated:: 13.7
can_restrict_members (:obj:`bool`): Optional. If the administrator can restrict, ban or
unban chat members.
.. deprecated:: 13.7
can_pin_messages (:obj:`bool`): Optional. If the user can pin messages.
.. deprecated:: 13.7
can_promote_members (:obj:`bool`): Optional. If the administrator can add new
administrators.
.. deprecated:: 13.7
is_member (:obj:`bool`): Optional. Restricted only. :obj:`True`, if the user is a member of
the chat at the moment of the request.
.. deprecated:: 13.7
can_send_messages (:obj:`bool`): Optional. If the user can send text messages, contacts,
locations and venues.
.. deprecated:: 13.7
can_send_media_messages (:obj:`bool`): Optional. If the user can send media messages,
implies can_send_messages.
.. deprecated:: 13.7
can_send_polls (:obj:`bool`): Optional. :obj:`True`, if the user is allowed to
send polls.
.. deprecated:: 13.7
can_send_other_messages (:obj:`bool`): Optional. If the user can send animations, games,
stickers and use inline bots, implies can_send_media_messages.
.. deprecated:: 13.7
can_add_web_page_previews (:obj:`bool`): Optional. If user may add web page previews to his
messages, implies can_send_media_messages
.. deprecated:: 13.7
"""
__slots__ = (
@@ -160,6 +286,7 @@ class ChatMember(TelegramObject):
'can_pin_messages',
'can_manage_chat',
'can_manage_voice_chats',
'can_manage_video_chats',
'until_date',
'_id_attrs',
)
@@ -201,8 +328,18 @@ class ChatMember(TelegramObject):
is_anonymous: bool = None,
can_manage_chat: bool = None,
can_manage_voice_chats: bool = None,
can_manage_video_chats: bool = None,
**_kwargs: Any,
):
# check before required to not waste resources if the error is raised
if can_manage_voice_chats is not None and can_manage_video_chats is not None:
# if they are the same it's fine...
if can_manage_voice_chats != can_manage_video_chats:
raise ValueError(
"Only supply one of `can_manage_video_chats`/`can_manage_voice_chats`,"
" not both."
)
# Required
self.user = user
self.status = status
@@ -227,7 +364,13 @@ class ChatMember(TelegramObject):
self.can_add_web_page_previews = can_add_web_page_previews
self.is_member = is_member
self.can_manage_chat = can_manage_chat
self.can_manage_voice_chats = can_manage_voice_chats
temp = (
can_manage_video_chats
if can_manage_video_chats is not None
else can_manage_voice_chats
)
self.can_manage_voice_chats = temp
self.can_manage_video_chats = temp
self._id_attrs = (self.user, self.status)
@@ -242,6 +385,17 @@ class ChatMember(TelegramObject):
data['user'] = User.de_json(data.get('user'), bot)
data['until_date'] = from_timestamp(data.get('until_date', None))
_class_mapping: Dict[str, Type['ChatMember']] = {
cls.CREATOR: ChatMemberOwner,
cls.ADMINISTRATOR: ChatMemberAdministrator,
cls.MEMBER: ChatMemberMember,
cls.RESTRICTED: ChatMemberRestricted,
cls.LEFT: ChatMemberLeft,
cls.KICKED: ChatMemberBanned,
}
if cls is ChatMember:
return _class_mapping.get(data['status'], cls)(**data, bot=bot)
return cls(**data)
def to_dict(self) -> JSONDict:
@@ -251,3 +405,346 @@ class ChatMember(TelegramObject):
data['until_date'] = to_timestamp(self.until_date)
return data
class ChatMemberOwner(ChatMember):
"""
Represents a chat member that owns the chat
and has all administrator privileges.
.. versionadded:: 13.7
Args:
user (:class:`telegram.User`): Information about the user.
custom_title (:obj:`str`, optional): Custom title for this user.
is_anonymous (:obj:`bool`, optional): :obj:`True`, if the
user's presence in the chat is hidden.
Attributes:
status (:obj:`str`): The member's status in the chat,
always :attr:`telegram.ChatMember.CREATOR`.
user (:class:`telegram.User`): Information about the user.
custom_title (:obj:`str`): Optional. Custom title for
this user.
is_anonymous (:obj:`bool`): Optional. :obj:`True`, if the user's
presence in the chat is hidden.
"""
__slots__ = ()
def __init__(
self,
user: User,
custom_title: str = None,
is_anonymous: bool = None,
**_kwargs: Any,
):
super().__init__(
status=ChatMember.CREATOR,
user=user,
custom_title=custom_title,
is_anonymous=is_anonymous,
)
class ChatMemberAdministrator(ChatMember):
"""
Represents a chat member that has some additional privileges.
.. versionadded:: 13.7
.. versionchanged:: 13.12
Since Bot API 6.0, voice chat was renamed to video chat.
Args:
user (:class:`telegram.User`): Information about the user.
can_be_edited (:obj:`bool`, optional): :obj:`True`, if the bot
is allowed to edit administrator privileges of that user.
custom_title (:obj:`str`, optional): Custom title for this user.
is_anonymous (:obj:`bool`, optional): :obj:`True`, if the user's
presence in the chat is hidden.
can_manage_chat (:obj:`bool`, optional): :obj:`True`, if the administrator
can access the chat event log, chat statistics, message statistics in
channels, see channel members, see anonymous administrators in supergroups
and ignore slow mode. Implied by any other administrator privilege.
can_post_messages (:obj:`bool`, optional): :obj:`True`, if the
administrator can post in the channel, channels only.
can_edit_messages (:obj:`bool`, optional): :obj:`True`, if the
administrator can edit messages of other users and can pin
messages; channels only.
can_delete_messages (:obj:`bool`, optional): :obj:`True`, if the
administrator can delete messages of other users.
can_manage_voice_chats (:obj:`bool`, optional): :obj:`True`, if the
administrator can manage voice chats.
.. deprecated:: 13.12
can_manage_video_chats (:obj:`bool`): :obj:`True`, if the
administrator can manage video chats.
.. versionadded:: 13.12
can_restrict_members (:obj:`bool`, optional): :obj:`True`, if the
administrator can restrict, ban or unban chat members.
can_promote_members (:obj:`bool`, optional): :obj:`True`, if the administrator
can add new administrators with a subset of his own privileges or demote
administrators that he has promoted, directly or indirectly (promoted by
administrators that were appointed by the user).
can_change_info (:obj:`bool`, optional): :obj:`True`, if the user can change
the chat title, photo and other settings.
can_invite_users (:obj:`bool`, optional): :obj:`True`, if the user can invite
new users to the chat.
can_pin_messages (:obj:`bool`, optional): :obj:`True`, if the user is allowed
to pin messages; groups and supergroups only.
Attributes:
status (:obj:`str`): The member's status in the chat,
always :attr:`telegram.ChatMember.ADMINISTRATOR`.
user (:class:`telegram.User`): Information about the user.
can_be_edited (:obj:`bool`): Optional. :obj:`True`, if the bot
is allowed to edit administrator privileges of that user.
custom_title (:obj:`str`): Optional. Custom title for this user.
is_anonymous (:obj:`bool`): Optional. :obj:`True`, if the user's
presence in the chat is hidden.
can_manage_chat (:obj:`bool`): Optional. :obj:`True`, if the administrator
can access the chat event log, chat statistics, message statistics in
channels, see channel members, see anonymous administrators in supergroups
and ignore slow mode. Implied by any other administrator privilege.
can_post_messages (:obj:`bool`): Optional. :obj:`True`, if the
administrator can post in the channel, channels only.
can_edit_messages (:obj:`bool`): Optional. :obj:`True`, if the
administrator can edit messages of other users and can pin
messages; channels only.
can_delete_messages (:obj:`bool`): Optional. :obj:`True`, if the
administrator can delete messages of other users.
can_manage_voice_chats (:obj:`bool`): Optional. :obj:`True`, if the
administrator can manage voice chats.
.. deprecated:: 13.12 contains the same value as :attr:`can_manage_video_chats`
for backwards compatibility.
can_manage_video_chats (:obj:`bool`): :obj:`True`, if the
administrator can manage video chats.
.. versionadded:: 13.12
can_restrict_members (:obj:`bool`): Optional. :obj:`True`, if the
administrator can restrict, ban or unban chat members.
can_promote_members (:obj:`bool`): Optional. :obj:`True`, if the administrator
can add new administrators with a subset of his own privileges or demote
administrators that he has promoted, directly or indirectly (promoted by
administrators that were appointed by the user).
can_change_info (:obj:`bool`): Optional. :obj:`True`, if the user can change
the chat title, photo and other settings.
can_invite_users (:obj:`bool`): Optional. :obj:`True`, if the user can invite
new users to the chat.
can_pin_messages (:obj:`bool`): Optional. :obj:`True`, if the user is allowed
to pin messages; groups and supergroups only.
"""
__slots__ = ()
def __init__(
self,
user: User,
can_be_edited: bool = None,
custom_title: str = None,
is_anonymous: bool = None,
can_manage_chat: bool = None,
can_post_messages: bool = None,
can_edit_messages: bool = None,
can_delete_messages: bool = None,
can_manage_voice_chats: bool = None,
can_restrict_members: bool = None,
can_promote_members: bool = None,
can_change_info: bool = None,
can_invite_users: bool = None,
can_pin_messages: bool = None,
can_manage_video_chats: bool = None,
**_kwargs: Any,
):
super().__init__(
status=ChatMember.ADMINISTRATOR,
user=user,
can_be_edited=can_be_edited,
custom_title=custom_title,
is_anonymous=is_anonymous,
can_manage_chat=can_manage_chat,
can_post_messages=can_post_messages,
can_edit_messages=can_edit_messages,
can_delete_messages=can_delete_messages,
can_manage_voice_chats=can_manage_voice_chats,
can_restrict_members=can_restrict_members,
can_promote_members=can_promote_members,
can_change_info=can_change_info,
can_invite_users=can_invite_users,
can_pin_messages=can_pin_messages,
can_manage_video_chats=can_manage_video_chats,
)
class ChatMemberMember(ChatMember):
"""
Represents a chat member that has no additional
privileges or restrictions.
.. versionadded:: 13.7
Args:
user (:class:`telegram.User`): Information about the user.
Attributes:
status (:obj:`str`): The member's status in the chat,
always :attr:`telegram.ChatMember.MEMBER`.
user (:class:`telegram.User`): Information about the user.
"""
__slots__ = ()
def __init__(self, user: User, **_kwargs: Any):
super().__init__(status=ChatMember.MEMBER, user=user)
class ChatMemberRestricted(ChatMember):
"""
Represents a chat member that is under certain restrictions
in the chat. Supergroups only.
.. versionadded:: 13.7
Args:
user (:class:`telegram.User`): Information about the user.
is_member (:obj:`bool`, optional): :obj:`True`, if the user is a
member of the chat at the moment of the request.
can_change_info (:obj:`bool`, optional): :obj:`True`, if the user can change
the chat title, photo and other settings.
can_invite_users (:obj:`bool`, optional): :obj:`True`, if the user can invite
new users to the chat.
can_pin_messages (:obj:`bool`, optional): :obj:`True`, if the user is allowed
to pin messages; groups and supergroups only.
can_send_messages (:obj:`bool`, optional): :obj:`True`, if the user is allowed
to send text messages, contacts, locations and venues.
can_send_media_messages (:obj:`bool`, optional): :obj:`True`, if the user is allowed
to send audios, documents, photos, videos, video notes and voice notes.
can_send_polls (:obj:`bool`, optional): :obj:`True`, if the user is allowed
to send polls.
can_send_other_messages (:obj:`bool`, optional): :obj:`True`, if the user is allowed
to send animations, games, stickers and use inline bots.
can_add_web_page_previews (:obj:`bool`, optional): :obj:`True`, if the user is
allowed to add web page previews to their messages.
until_date (:class:`datetime.datetime`, optional): Date when restrictions
will be lifted for this user.
Attributes:
status (:obj:`str`): The member's status in the chat,
always :attr:`telegram.ChatMember.RESTRICTED`.
user (:class:`telegram.User`): Information about the user.
is_member (:obj:`bool`): Optional. :obj:`True`, if the user is a
member of the chat at the moment of the request.
can_change_info (:obj:`bool`): Optional. :obj:`True`, if the user can change
the chat title, photo and other settings.
can_invite_users (:obj:`bool`): Optional. :obj:`True`, if the user can invite
new users to the chat.
can_pin_messages (:obj:`bool`): Optional. :obj:`True`, if the user is allowed
to pin messages; groups and supergroups only.
can_send_messages (:obj:`bool`): Optional. :obj:`True`, if the user is allowed
to send text messages, contacts, locations and venues.
can_send_media_messages (:obj:`bool`): Optional. :obj:`True`, if the user is allowed
to send audios, documents, photos, videos, video notes and voice notes.
can_send_polls (:obj:`bool`): Optional. :obj:`True`, if the user is allowed
to send polls.
can_send_other_messages (:obj:`bool`): Optional. :obj:`True`, if the user is allowed
to send animations, games, stickers and use inline bots.
can_add_web_page_previews (:obj:`bool`): Optional. :obj:`True`, if the user is
allowed to add web page previews to their messages.
until_date (:class:`datetime.datetime`): Optional. Date when restrictions
will be lifted for this user.
"""
__slots__ = ()
def __init__(
self,
user: User,
is_member: bool = None,
can_change_info: bool = None,
can_invite_users: bool = None,
can_pin_messages: bool = None,
can_send_messages: bool = None,
can_send_media_messages: bool = None,
can_send_polls: bool = None,
can_send_other_messages: bool = None,
can_add_web_page_previews: bool = None,
until_date: datetime.datetime = None,
**_kwargs: Any,
):
super().__init__(
status=ChatMember.RESTRICTED,
user=user,
is_member=is_member,
can_change_info=can_change_info,
can_invite_users=can_invite_users,
can_pin_messages=can_pin_messages,
can_send_messages=can_send_messages,
can_send_media_messages=can_send_media_messages,
can_send_polls=can_send_polls,
can_send_other_messages=can_send_other_messages,
can_add_web_page_previews=can_add_web_page_previews,
until_date=until_date,
)
class ChatMemberLeft(ChatMember):
"""
Represents a chat member that isn't currently a member of the chat,
but may join it themselves.
.. versionadded:: 13.7
Args:
user (:class:`telegram.User`): Information about the user.
Attributes:
status (:obj:`str`): The member's status in the chat,
always :attr:`telegram.ChatMember.LEFT`.
user (:class:`telegram.User`): Information about the user.
"""
__slots__ = ()
def __init__(self, user: User, **_kwargs: Any):
super().__init__(status=ChatMember.LEFT, user=user)
class ChatMemberBanned(ChatMember):
"""
Represents a chat member that was banned in the chat and
can't return to the chat or view chat messages.
.. versionadded:: 13.7
Args:
user (:class:`telegram.User`): Information about the user.
until_date (:class:`datetime.datetime`, optional): Date when restrictions
will be lifted for this user.
Attributes:
status (:obj:`str`): The member's status in the chat,
always :attr:`telegram.ChatMember.KICKED`.
user (:class:`telegram.User`): Information about the user.
until_date (:class:`datetime.datetime`): Optional. Date when restrictions
will be lifted for this user.
"""
__slots__ = ()
def __init__(
self,
user: User,
until_date: datetime.datetime = None,
**_kwargs: Any,
):
super().__init__(
status=ChatMember.KICKED,
user=user,
until_date=until_date,
)
+1 -1
View File
@@ -1,7 +1,7 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2021
# Copyright (C) 2015-2022
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
+1 -1
View File
@@ -1,7 +1,7 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2021
# Copyright (C) 2015-2022
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
+1 -1
View File
@@ -2,7 +2,7 @@
# pylint: disable=R0902,R0913
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2021
# Copyright (C) 2015-2022
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
+60 -3
View File
@@ -1,5 +1,5 @@
# python-telegram-bot - a Python interface to the Telegram Bot API
# Copyright (C) 2015-2021
# Copyright (C) 2015-2022
# by the python-telegram-bot contributors <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
@@ -21,7 +21,7 @@ The following constants were extracted from the
`Telegram Bots API <https://core.telegram.org/bots/api>`_.
Attributes:
BOT_API_VERSION (:obj:`str`): `5.2`. Telegram Bot API version supported by this
BOT_API_VERSION (:obj:`str`): `6.0`. Telegram Bot API version supported by this
version of `python-telegram-bot`. Also available as ``telegram.bot_api_version``.
.. versionadded:: 13.4
@@ -48,6 +48,10 @@ Attributes:
ANONYMOUS_ADMIN_ID (:obj:`int`): ``1087968824`` (User id in groups for anonymous admin)
SERVICE_CHAT_ID (:obj:`int`): ``777000`` (Telegram service chat, that also acts as sender of
channel posts forwarded to discussion groups)
FAKE_CHANNEL_ID (:obj:`int`): ``136817688`` (User id in groups when message is sent on behalf
of a channel).
.. versionadded:: 13.9
The following constants are related to specific classes and are also available
as attributes of those classes:
@@ -86,6 +90,9 @@ Attributes:
.. versionadded:: 13.5
CHATACTION_UPLOAD_DOCUMENT (:obj:`str`): ``'upload_document'``
CHATACTION_CHOOSE_STICKER (:obj:`str`): ``'choose_sticker'``
.. versionadded:: 13.8
CHATACTION_UPLOAD_PHOTO (:obj:`str`): ``'upload_photo'``
CHATACTION_UPLOAD_VIDEO (:obj:`str`): ``'upload_video'``
CHATACTION_UPLOAD_VIDEO_NOTE (:obj:`str`): ``'upload_video_note'``
@@ -134,6 +141,9 @@ Attributes:
MESSAGEENTITY_TEXT_MENTION (:obj:`str`): ``'text_mention'``
MESSAGEENTITY_UNDERLINE (:obj:`str`): ``'underline'``
MESSAGEENTITY_STRIKETHROUGH (:obj:`str`): ``'strikethrough'``
MESSAGEENTITY_SPOILER (:obj:`str`): ``'spoiler'``
.. versionadded:: 13.10
MESSAGEENTITY_ALL_TYPES (List[:obj:`str`]): List of all the types of message entity.
:class:`telegram.ParseMode`:
@@ -201,18 +211,48 @@ Attributes:
UPDATE_CHAT_MEMBER (:obj:`str`): ``'chat_member'``
.. versionadded:: 13.5
UPDATE_CHAT_JOIN_REQUEST (:obj:`str`): ``'chat_join_request'``
.. versionadded:: 13.8
UPDATE_ALL_TYPES (List[:obj:`str`]): List of all update types.
.. versionadded:: 13.5
.. versionchanged:: 13.8
:class:`telegram.BotCommandScope`:
Attributes:
BOT_COMMAND_SCOPE_DEFAULT (:obj:`str`): ``'default'``
..versionadded:: 13.7
BOT_COMMAND_SCOPE_ALL_PRIVATE_CHATS (:obj:`str`): ``'all_private_chats'``
..versionadded:: 13.7
BOT_COMMAND_SCOPE_ALL_GROUP_CHATS (:obj:`str`): ``'all_group_chats'``
..versionadded:: 13.7
BOT_COMMAND_SCOPE_ALL_CHAT_ADMINISTRATORS (:obj:`str`): ``'all_chat_administrators'``
..versionadded:: 13.7
BOT_COMMAND_SCOPE_CHAT (:obj:`str`): ``'chat'``
..versionadded:: 13.7
BOT_COMMAND_SCOPE_CHAT_ADMINISTRATORS (:obj:`str`): ``'chat_administrators'``
..versionadded:: 13.7
BOT_COMMAND_SCOPE_CHAT_MEMBER (:obj:`str`): ``'chat_member'``
..versionadded:: 13.7
"""
from typing import List
BOT_API_VERSION: str = '5.2'
BOT_API_VERSION: str = '6.0'
MAX_MESSAGE_LENGTH: int = 4096
MAX_CAPTION_LENGTH: int = 1024
ANONYMOUS_ADMIN_ID: int = 1087968824
SERVICE_CHAT_ID: int = 777000
FAKE_CHANNEL_ID: int = 136817688
# constants above this line are tested
@@ -242,6 +282,7 @@ CHATACTION_TYPING: str = 'typing'
CHATACTION_UPLOAD_AUDIO: str = 'upload_audio'
CHATACTION_UPLOAD_VOICE: str = 'upload_voice'
CHATACTION_UPLOAD_DOCUMENT: str = 'upload_document'
CHATACTION_CHOOSE_STICKER: str = 'choose_sticker'
CHATACTION_UPLOAD_PHOTO: str = 'upload_photo'
CHATACTION_UPLOAD_VIDEO: str = 'upload_video'
CHATACTION_UPLOAD_VIDEO_NOTE: str = 'upload_video_note'
@@ -283,6 +324,7 @@ MESSAGEENTITY_TEXT_LINK: str = 'text_link'
MESSAGEENTITY_TEXT_MENTION: str = 'text_mention'
MESSAGEENTITY_UNDERLINE: str = 'underline'
MESSAGEENTITY_STRIKETHROUGH: str = 'strikethrough'
MESSAGEENTITY_SPOILER: str = 'spoiler'
MESSAGEENTITY_ALL_TYPES: List[str] = [
MESSAGEENTITY_MENTION,
MESSAGEENTITY_HASHTAG,
@@ -299,6 +341,7 @@ MESSAGEENTITY_ALL_TYPES: List[str] = [
MESSAGEENTITY_TEXT_MENTION,
MESSAGEENTITY_UNDERLINE,
MESSAGEENTITY_STRIKETHROUGH,
MESSAGEENTITY_SPOILER,
]
PARSEMODE_MARKDOWN: str = 'Markdown'
@@ -328,6 +371,7 @@ UPDATE_POLL = 'poll'
UPDATE_POLL_ANSWER = 'poll_answer'
UPDATE_MY_CHAT_MEMBER = 'my_chat_member'
UPDATE_CHAT_MEMBER = 'chat_member'
UPDATE_CHAT_JOIN_REQUEST = 'chat_join_request'
UPDATE_ALL_TYPES = [
UPDATE_MESSAGE,
UPDATE_EDITED_MESSAGE,
@@ -342,4 +386,17 @@ UPDATE_ALL_TYPES = [
UPDATE_POLL_ANSWER,
UPDATE_MY_CHAT_MEMBER,
UPDATE_CHAT_MEMBER,
UPDATE_CHAT_JOIN_REQUEST,
]
BOT_COMMAND_SCOPE_DEFAULT = 'default'
BOT_COMMAND_SCOPE_ALL_PRIVATE_CHATS = 'all_private_chats'
BOT_COMMAND_SCOPE_ALL_GROUP_CHATS = 'all_group_chats'
BOT_COMMAND_SCOPE_ALL_CHAT_ADMINISTRATORS = 'all_chat_administrators'
BOT_COMMAND_SCOPE_CHAT = 'chat'
BOT_COMMAND_SCOPE_CHAT_ADMINISTRATORS = 'chat_administrators'
BOT_COMMAND_SCOPE_CHAT_MEMBER = 'chat_member'
MENU_BUTTON_COMMANDS = 'commands'
MENU_BUTTON_WEB_APP = 'web_app'
MENU_BUTTON_DEFAULT = 'default'
+4 -3
View File
@@ -2,7 +2,7 @@
# pylint: disable=R0903
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2021
# Copyright (C) 2015-2022
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
@@ -50,8 +50,9 @@ class Dice(TelegramObject):
Telegram.
If :attr:`emoji` is "🎰", each value corresponds to a unique combination of symbols, which
can be found at our `wiki <https://git.io/JkeC6>`_. However, this behaviour is undocumented
and might be changed by Telegram.
can be found at our `wiki <https://github.com/python-telegram-bot/python-telegram-bot/\
wiki/Code-snippets#map-a-slot-machine-dice-value-to-the-corresponding-symbols>`_.
However, this behaviour is undocumented and might be changed by Telegram.
Args:
value (:obj:`int`): Value of the dice. 1-6 for dice, darts and bowling balls, 1-5 for
+1 -1
View File
@@ -1,7 +1,7 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2021
# Copyright (C) 2015-2022
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
+3 -13
View File
@@ -1,7 +1,7 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2021
# Copyright (C) 2015-2022
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
@@ -16,7 +16,6 @@
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
# pylint: disable=C0413
"""Extensions over the Telegram Bot API to facilitate bot making"""
from .extbot import ExtBot
@@ -28,17 +27,6 @@ from .callbackcontext import CallbackContext
from .contexttypes import ContextTypes
from .dispatcher import Dispatcher, DispatcherHandlerStop, run_async
# https://bugs.python.org/issue41451, fixed on 3.7+, doesn't actually remove slots
# try-except is just here in case the __init__ is called twice (like in the tests)
# this block is also the reason for the pylint-ignore at the top of the file
try:
del Dispatcher.__slots__ # type: ignore[has-type]
except AttributeError as exc:
if str(exc) == '__slots__':
pass
else:
raise exc
from .jobqueue import JobQueue, Job
from .updater import Updater
from .callbackqueryhandler import CallbackQueryHandler
@@ -59,6 +47,7 @@ from .messagequeue import DelayQueue
from .pollanswerhandler import PollAnswerHandler
from .pollhandler import PollHandler
from .chatmemberhandler import ChatMemberHandler
from .chatjoinrequesthandler import ChatJoinRequestHandler
from .defaults import Defaults
from .callbackdatacache import CallbackDataCache, InvalidCallbackData
@@ -68,6 +57,7 @@ __all__ = (
'CallbackContext',
'CallbackDataCache',
'CallbackQueryHandler',
'ChatJoinRequestHandler',
'ChatMemberHandler',
'ChosenInlineResultHandler',
'CommandHandler',
+68 -40
View File
@@ -1,7 +1,7 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2021
# Copyright (C) 2015-2022
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
@@ -212,7 +212,8 @@ class BasePersistence(Generic[UD, CD, BD], ABC):
:attr:`REPLACED_BOT`. Currently, this handles objects of type ``list``, ``tuple``, ``set``,
``frozenset``, ``dict``, ``defaultdict`` and objects that have a ``__dict__`` or
``__slots__`` attribute, excluding classes and objects that can't be copied with
``copy.copy``.
``copy.copy``. If the parsing of an object fails, the object will be returned unchanged and
the error will be logged.
Args:
obj (:obj:`object`): The object
@@ -276,21 +277,34 @@ class BasePersistence(Generic[UD, CD, BD], ABC):
new_obj[cls._replace_bot(k, memo)] = cls._replace_bot(val, memo)
memo[obj_id] = new_obj
return new_obj
if hasattr(obj, '__dict__'):
for attr_name, attr in new_obj.__dict__.items():
setattr(new_obj, attr_name, cls._replace_bot(attr, memo))
memo[obj_id] = new_obj
return new_obj
if hasattr(obj, '__slots__'):
for attr_name in new_obj.__slots__:
setattr(
new_obj,
attr_name,
cls._replace_bot(cls._replace_bot(getattr(new_obj, attr_name), memo), memo),
)
memo[obj_id] = new_obj
return new_obj
try:
if hasattr(obj, '__slots__'):
for attr_name in new_obj.__slots__:
setattr(
new_obj,
attr_name,
cls._replace_bot(
cls._replace_bot(getattr(new_obj, attr_name), memo), memo
),
)
if '__dict__' in obj.__slots__:
# In this case, we have already covered the case that obj has __dict__
# Note that obj may have a __dict__ even if it's not in __slots__!
memo[obj_id] = new_obj
return new_obj
if hasattr(obj, '__dict__'):
for attr_name, attr in new_obj.__dict__.items():
setattr(new_obj, attr_name, cls._replace_bot(attr, memo))
memo[obj_id] = new_obj
return new_obj
except Exception as exception:
warnings.warn(
f'Parsing of an object failed with the following exception: {exception}. '
f'See the docs of BasePersistence.replace_bot for more information.',
RuntimeWarning,
)
memo[obj_id] = obj
return obj
def insert_bot(self, obj: object) -> object:
@@ -299,7 +313,8 @@ class BasePersistence(Generic[UD, CD, BD], ABC):
:attr:`bot`. Currently, this handles objects of type ``list``, ``tuple``, ``set``,
``frozenset``, ``dict``, ``defaultdict`` and objects that have a ``__dict__`` or
``__slots__`` attribute, excluding classes and objects that can't be copied with
``copy.copy``.
``copy.copy``. If the parsing of an object fails, the object will be returned unchanged and
the error will be logged.
Args:
obj (:obj:`object`): The object
@@ -364,21 +379,34 @@ class BasePersistence(Generic[UD, CD, BD], ABC):
new_obj[self._insert_bot(k, memo)] = self._insert_bot(val, memo)
memo[obj_id] = new_obj
return new_obj
if hasattr(obj, '__dict__'):
for attr_name, attr in new_obj.__dict__.items():
setattr(new_obj, attr_name, self._insert_bot(attr, memo))
memo[obj_id] = new_obj
return new_obj
if hasattr(obj, '__slots__'):
for attr_name in obj.__slots__:
setattr(
new_obj,
attr_name,
self._insert_bot(self._insert_bot(getattr(new_obj, attr_name), memo), memo),
)
memo[obj_id] = new_obj
return new_obj
try:
if hasattr(obj, '__slots__'):
for attr_name in obj.__slots__:
setattr(
new_obj,
attr_name,
self._insert_bot(
self._insert_bot(getattr(new_obj, attr_name), memo), memo
),
)
if '__dict__' in obj.__slots__:
# In this case, we have already covered the case that obj has __dict__
# Note that obj may have a __dict__ even if it's not in __slots__!
memo[obj_id] = new_obj
return new_obj
if hasattr(obj, '__dict__'):
for attr_name, attr in new_obj.__dict__.items():
setattr(new_obj, attr_name, self._insert_bot(attr, memo))
memo[obj_id] = new_obj
return new_obj
except Exception as exception:
warnings.warn(
f'Parsing of an object failed with the following exception: {exception}. '
f'See the docs of BasePersistence.insert_bot for more information.',
RuntimeWarning,
)
memo[obj_id] = obj
return obj
@abstractmethod
@@ -418,8 +446,8 @@ class BasePersistence(Generic[UD, CD, BD], ABC):
.. versionadded:: 13.6
Returns:
Optional[:class:`telegram.ext.utils.types.CDCData`]: The restored meta data or
:obj:`None`, if no data was stored.
Optional[:class:`telegram.ext.utils.types.CDCData`]: The restored meta data or
:obj:`None`, if no data was stored.
"""
raise NotImplementedError
@@ -441,8 +469,8 @@ class BasePersistence(Generic[UD, CD, BD], ABC):
def update_conversation(
self, name: str, key: Tuple[int, ...], new_state: Optional[object]
) -> None:
"""Will be called when a :attr:`telegram.ext.ConversationHandler.update_state`
is called. This allows the storage of the new state in the persistence.
"""Will be called when a :class:`telegram.ext.ConversationHandler` changes states.
This allows the storage of the new state in the persistence.
Args:
name (:obj:`str`): The handler's name.
@@ -458,7 +486,7 @@ class BasePersistence(Generic[UD, CD, BD], ABC):
Args:
user_id (:obj:`int`): The user the data might have been changed for.
data (:class:`telegram.ext.utils.types.UD`): The
:attr:`telegram.ext.dispatcher.user_data` ``[user_id]``.
:attr:`telegram.ext.Dispatcher.user_data` ``[user_id]``.
"""
@abstractmethod
@@ -469,7 +497,7 @@ class BasePersistence(Generic[UD, CD, BD], ABC):
Args:
chat_id (:obj:`int`): The chat the data might have been changed for.
data (:class:`telegram.ext.utils.types.CD`): The
:attr:`telegram.ext.dispatcher.chat_data` ``[chat_id]``.
:attr:`telegram.ext.Dispatcher.chat_data` ``[chat_id]``.
"""
@abstractmethod
@@ -479,7 +507,7 @@ class BasePersistence(Generic[UD, CD, BD], ABC):
Args:
data (:class:`telegram.ext.utils.types.BD`): The
:attr:`telegram.ext.dispatcher.bot_data`.
:attr:`telegram.ext.Dispatcher.bot_data`.
"""
def refresh_user_data(self, user_id: int, user_data: UD) -> None:
@@ -524,8 +552,8 @@ class BasePersistence(Generic[UD, CD, BD], ABC):
.. versionadded:: 13.6
Args:
data (:class:`telegram.ext.utils.types.CDCData`:): The relevant data to restore
:attr:`telegram.ext.dispatcher.bot.callback_data_cache`.
data (:class:`telegram.ext.utils.types.CDCData`): The relevant data to restore
:class:`telegram.ext.CallbackDataCache`.
"""
raise NotImplementedError
+10 -4
View File
@@ -1,7 +1,7 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2021
# Copyright (C) 2015-2022
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
@@ -139,7 +139,9 @@ class CallbackContext(Generic[UD, CD, BD]):
@bot_data.setter
def bot_data(self, value: object) -> NoReturn:
raise AttributeError(
"You can not assign a new value to bot_data, see https://git.io/Jt6ic"
"You can not assign a new value to bot_data, "
"see https://github.com/python-telegram-bot/python-telegram-bot/wiki/Storing-bot%2C"
"-user-and-chat-related-data "
)
@property
@@ -160,7 +162,9 @@ class CallbackContext(Generic[UD, CD, BD]):
@chat_data.setter
def chat_data(self, value: object) -> NoReturn:
raise AttributeError(
"You can not assign a new value to chat_data, see https://git.io/Jt6ic"
"You can not assign a new value to chat_data, "
"see https://github.com/python-telegram-bot/python-telegram-bot/wiki/Storing-bot%2C"
"-user-and-chat-related-data "
)
@property
@@ -175,7 +179,9 @@ class CallbackContext(Generic[UD, CD, BD]):
@user_data.setter
def user_data(self, value: object) -> NoReturn:
raise AttributeError(
"You can not assign a new value to user_data, see https://git.io/Jt6ic"
"You can not assign a new value to user_data, "
"see https://github.com/python-telegram-bot/python-telegram-bot/wiki/Storing-bot%2C"
"-user-and-chat-related-data "
)
def refresh_data(self) -> None:
+1 -20
View File
@@ -1,8 +1,7 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2021
# Copyright (C) 2015-2022
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
@@ -17,24 +16,6 @@
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2021
# 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 CallbackDataCache class."""
import logging
import time
+3 -2
View File
@@ -1,7 +1,7 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2021
# Copyright (C) 2015-2022
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
@@ -55,7 +55,8 @@ class CallbackQueryHandler(Handler[Update, CCT]):
user or in the same chat, it will be the same ``dict``.
Note that this is DEPRECATED, and you should use context based callbacks. See
https://git.io/fxJuV for more info.
https://github.com/python-telegram-bot/python-telegram-bot/wiki\
/Transition-guide-to-Version-12.0 for more info.
* If your bot allows arbitrary objects as ``callback_data``, it may happen that the
original ``callback_data`` for the incoming :class:`telegram.CallbackQuery`` can not be
found. This is the case when either a malicious client tempered with the
+101
View File
@@ -0,0 +1,101 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2022
# 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 ChatJoinRequestHandler class."""
from telegram import Update
from .handler import Handler
from .utils.types import CCT
class ChatJoinRequestHandler(Handler[Update, CCT]):
"""Handler class to handle Telegram updates that contain a chat join request.
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
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``.
Note that this is DEPRECATED, and you should use context based callbacks. See
https://github.com/python-telegram-bot/python-telegram-bot/wiki\
/Transition-guide-to-Version-12.0 for more info.
Warning:
When setting ``run_async`` to :obj:`True`, you cannot rely on adding custom
attributes to :class:`telegram.ext.CallbackContext`. See its docs for more info.
.. versionadded:: 13.8
Args:
callback (:obj:`callable`): The callback function for this handler. Will be called when
:attr:`check_update` has determined that an update should be processed by this handler.
Callback signature for context based API:
``def callback(update: Update, context: CallbackContext)``
The return value of the callback is usually ignored except for the special case of
:class:`telegram.ext.ConversationHandler`.
pass_update_queue (:obj:`bool`, optional): If set to :obj:`True`, a keyword argument called
``update_queue`` will be passed to the callback function. It will be the ``Queue``
instance used by the :class:`telegram.ext.Updater` and :class:`telegram.ext.Dispatcher`
that contains new updates which can be used to insert updates. Default is :obj:`False`.
DEPRECATED: Please switch to context based callbacks.
pass_job_queue (:obj:`bool`, optional): If set to :obj:`True`, a keyword argument called
``job_queue`` will be passed to the callback function. It will be a
:class:`telegram.ext.JobQueue` instance created by the :class:`telegram.ext.Updater`
which can be used to schedule new jobs. Default is :obj:`False`.
DEPRECATED: Please switch to context based callbacks.
pass_user_data (:obj:`bool`, optional): If set to :obj:`True`, a keyword argument called
``user_data`` will be passed to the callback function. Default is :obj:`False`.
DEPRECATED: Please switch to context based callbacks.
pass_chat_data (:obj:`bool`, optional): If set to :obj:`True`, a keyword argument called
``chat_data`` will be passed to the callback function. Default is :obj:`False`.
DEPRECATED: Please switch to context based callbacks.
run_async (:obj:`bool`): Determines whether the callback will run asynchronously.
Defaults to :obj:`False`.
Attributes:
callback (:obj:`callable`): The callback function for this handler.
pass_update_queue (:obj:`bool`): Determines whether ``update_queue`` will be
passed to the callback function.
pass_job_queue (:obj:`bool`): Determines whether ``job_queue`` will be passed to
the callback function.
pass_user_data (:obj:`bool`): Determines whether ``user_data`` will be passed to
the callback function.
pass_chat_data (:obj:`bool`): Determines whether ``chat_data`` will be passed to
the callback function.
run_async (:obj:`bool`): Determines whether the callback will run asynchronously.
"""
__slots__ = ()
def check_update(self, update: object) -> bool:
"""Determines whether an update should be passed to this handlers :attr:`callback`.
Args:
update (:class:`telegram.Update` | :obj:`object`): Incoming update.
Returns:
:obj:`bool`
"""
return isinstance(update, Update) and bool(update.chat_join_request)
+3 -2
View File
@@ -1,7 +1,7 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2019-2021
# Copyright (C) 2015-2022
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
@@ -39,7 +39,8 @@ class ChatMemberHandler(Handler[Update, CCT]):
or in the same chat, it will be the same ``dict``.
Note that this is DEPRECATED, and you should use context based callbacks. See
https://git.io/fxJuV for more info.
https://github.com/python-telegram-bot/python-telegram-bot/wiki\
/Transition-guide-to-Version-12.0 for more info.
Warning:
When setting ``run_async`` to :obj:`True`, you cannot rely on adding custom
+3 -2
View File
@@ -1,7 +1,7 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2021
# Copyright (C) 2015-2022
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
@@ -42,7 +42,8 @@ class ChosenInlineResultHandler(Handler[Update, CCT]):
or in the same chat, it will be the same ``dict``.
Note that this is DEPRECATED, and you should use context based callbacks. See
https://git.io/fxJuV for more info.
https://github.com/python-telegram-bot/python-telegram-bot/wiki\
/Transition-guide-to-Version-12.0 for more info.
Warning:
When setting ``run_async`` to :obj:`True`, you cannot rely on adding custom
+8 -4
View File
@@ -1,7 +1,7 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2021
# Copyright (C) 2015-2022
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
@@ -55,7 +55,8 @@ class CommandHandler(Handler[Update, CCT]):
user or in the same chat, it will be the same :obj:`dict`.
Note that this is DEPRECATED, and you should use context based callbacks. See
https://git.io/fxJuV for more info.
https://github.com/python-telegram-bot/python-telegram-bot/wiki\
/Transition-guide-to-Version-12.0 for more info.
Warning:
When setting ``run_async`` to :obj:`True`, you cannot rely on adding custom
@@ -169,7 +170,9 @@ class CommandHandler(Handler[Update, CCT]):
if allow_edited is not None:
warnings.warn(
'allow_edited is deprecated. See https://git.io/fxJuV for more info',
'allow_edited is deprecated. See '
'https://github.com/python-telegram-bot/python-telegram-bot/wiki/Transition'
'-guide-to-Version-12.0 for more info',
TelegramDeprecationWarning,
stacklevel=2,
)
@@ -288,7 +291,8 @@ class PrefixHandler(CommandHandler):
user or in the same chat, it will be the same :obj:`dict`.
Note that this is DEPRECATED, and you should use context based callbacks. See
https://git.io/fxJuV for more info.
https://github.com/python-telegram-bot/python-telegram-bot/wiki\
/Transition-guide-to-Version-12.0 for more info.
Warning:
When setting ``run_async`` to :obj:`True`, you cannot rely on adding custom
+38 -29
View File
@@ -1,7 +1,7 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2020
# Copyright (C) 2015-2022
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
@@ -50,9 +50,12 @@ class ContextTypes(Generic[CCT, UD, CD, BD]):
__slots__ = ('_context', '_bot_data', '_chat_data', '_user_data')
# overload signatures generated with
# https://gist.github.com/Bibo-Joshi/399382cda537fb01bd86b13c3d03a956
@overload
def __init__(
self: 'ContextTypes[CallbackContext, Dict, Dict, Dict]',
self: 'ContextTypes[CallbackContext[Dict, Dict, Dict], Dict, Dict, Dict]',
):
...
@@ -61,20 +64,26 @@ class ContextTypes(Generic[CCT, UD, CD, BD]):
...
@overload
def __init__(self: 'ContextTypes[CallbackContext, UD, Dict, Dict]', bot_data: Type[UD]):
...
@overload
def __init__(self: 'ContextTypes[CallbackContext, Dict, CD, Dict]', chat_data: Type[CD]):
...
@overload
def __init__(self: 'ContextTypes[CallbackContext, Dict, Dict, BD]', user_data: Type[BD]):
def __init__(
self: 'ContextTypes[CallbackContext[UD, Dict, Dict], UD, Dict, Dict]', user_data: Type[UD]
):
...
@overload
def __init__(
self: 'ContextTypes[CCT, UD, Dict, Dict]', context: Type[CCT], bot_data: Type[UD]
self: 'ContextTypes[CallbackContext[Dict, CD, Dict], Dict, CD, Dict]', chat_data: Type[CD]
):
...
@overload
def __init__(
self: 'ContextTypes[CallbackContext[Dict, Dict, BD], Dict, Dict, BD]', bot_data: Type[BD]
):
...
@overload
def __init__(
self: 'ContextTypes[CCT, UD, Dict, Dict]', context: Type[CCT], user_data: Type[UD]
):
...
@@ -86,31 +95,31 @@ class ContextTypes(Generic[CCT, UD, CD, BD]):
@overload
def __init__(
self: 'ContextTypes[CCT, Dict, Dict, BD]', context: Type[CCT], user_data: Type[BD]
self: 'ContextTypes[CCT, Dict, Dict, BD]', context: Type[CCT], bot_data: Type[BD]
):
...
@overload
def __init__(
self: 'ContextTypes[CallbackContext, UD, CD, Dict]',
bot_data: Type[UD],
self: 'ContextTypes[CallbackContext[UD, CD, Dict], UD, CD, Dict]',
user_data: Type[UD],
chat_data: Type[CD],
):
...
@overload
def __init__(
self: 'ContextTypes[CallbackContext, UD, Dict, BD]',
bot_data: Type[UD],
user_data: Type[BD],
self: 'ContextTypes[CallbackContext[UD, Dict, BD], UD, Dict, BD]',
user_data: Type[UD],
bot_data: Type[BD],
):
...
@overload
def __init__(
self: 'ContextTypes[CallbackContext, Dict, CD, BD]',
self: 'ContextTypes[CallbackContext[Dict, CD, BD], Dict, CD, BD]',
chat_data: Type[CD],
user_data: Type[BD],
bot_data: Type[BD],
):
...
@@ -118,7 +127,7 @@ class ContextTypes(Generic[CCT, UD, CD, BD]):
def __init__(
self: 'ContextTypes[CCT, UD, CD, Dict]',
context: Type[CCT],
bot_data: Type[UD],
user_data: Type[UD],
chat_data: Type[CD],
):
...
@@ -127,8 +136,8 @@ class ContextTypes(Generic[CCT, UD, CD, BD]):
def __init__(
self: 'ContextTypes[CCT, UD, Dict, BD]',
context: Type[CCT],
bot_data: Type[UD],
user_data: Type[BD],
user_data: Type[UD],
bot_data: Type[BD],
):
...
@@ -137,16 +146,16 @@ class ContextTypes(Generic[CCT, UD, CD, BD]):
self: 'ContextTypes[CCT, Dict, CD, BD]',
context: Type[CCT],
chat_data: Type[CD],
user_data: Type[BD],
bot_data: Type[BD],
):
...
@overload
def __init__(
self: 'ContextTypes[CallbackContext, UD, CD, BD]',
bot_data: Type[UD],
self: 'ContextTypes[CallbackContext[UD, CD, BD], UD, CD, BD]',
user_data: Type[UD],
chat_data: Type[CD],
user_data: Type[BD],
bot_data: Type[BD],
):
...
@@ -154,9 +163,9 @@ class ContextTypes(Generic[CCT, UD, CD, BD]):
def __init__(
self: 'ContextTypes[CCT, UD, CD, BD]',
context: Type[CCT],
bot_data: Type[UD],
user_data: Type[UD],
chat_data: Type[CD],
user_data: Type[BD],
bot_data: Type[BD],
):
...
+5 -4
View File
@@ -1,7 +1,7 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2021
# Copyright (C) 2015-2022
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
@@ -79,7 +79,8 @@ class ConversationHandler(Handler[Update, CCT]):
Finally, ``ConversationHandler``, does *not* handle (edited) channel posts.
.. _`FAQ`: https://git.io/JtcyU
.. _`FAQ`: https://github.com/python-telegram-bot/python-telegram-bot/wiki\
/Frequently-Asked-Questions#what-do-the-per_-settings-in-conversationhandler-do
The first collection, a ``list`` named :attr:`entry_points`, is used to initiate the
conversation, for example with a :class:`telegram.ext.CommandHandler` or
@@ -119,7 +120,7 @@ class ConversationHandler(Handler[Update, CCT]):
:attr:`END` to end the *parent* conversation from within the nested one. For an example on
nested :class:`ConversationHandler` s, see our `examples`_.
.. _`examples`: https://github.com/python-telegram-bot/python-telegram-bot/blob/master/examples
.. _`examples`: https://github.com/python-telegram-bot/python-telegram-bot/blob/v13.x/examples
Args:
entry_points (List[:class:`telegram.ext.Handler`]): A list of ``Handler`` objects that can
@@ -350,11 +351,11 @@ class ConversationHandler(Handler[Update, CCT]):
@property
def allow_reentry(self) -> bool:
""":obj:`bool`: Determines if a user can restart a conversation with an entry point."""
return self._allow_reentry
@allow_reentry.setter
def allow_reentry(self, value: object) -> NoReturn:
""":obj:`bool`: Determines if a user can restart a conversation with an entry point."""
raise ValueError('You can not assign a new value to allow_reentry after initialization.')
@property
+1 -1
View File
@@ -1,7 +1,7 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2020-2021
# Copyright (C) 2015-2022
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
+7 -7
View File
@@ -1,7 +1,7 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2021
# Copyright (C) 2015-2022
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
@@ -294,7 +294,7 @@ class DictPersistence(BasePersistence):
Returns:
Optional[:class:`telegram.ext.utils.types.CDCData`]: The restored meta data or
:obj:`None`, if no data was stored.
:obj:`None`, if no data was stored.
"""
if self.callback_data is None:
self._callback_data = None
@@ -334,7 +334,7 @@ class DictPersistence(BasePersistence):
Args:
user_id (:obj:`int`): The user the data might have been changed for.
data (:obj:`dict`): The :attr:`telegram.ext.dispatcher.user_data` ``[user_id]``.
data (:obj:`dict`): The :attr:`telegram.ext.Dispatcher.user_data` ``[user_id]``.
"""
if self._user_data is None:
self._user_data = defaultdict(dict)
@@ -348,7 +348,7 @@ class DictPersistence(BasePersistence):
Args:
chat_id (:obj:`int`): The chat the data might have been changed for.
data (:obj:`dict`): The :attr:`telegram.ext.dispatcher.chat_data` ``[chat_id]``.
data (:obj:`dict`): The :attr:`telegram.ext.Dispatcher.chat_data` ``[chat_id]``.
"""
if self._chat_data is None:
self._chat_data = defaultdict(dict)
@@ -361,7 +361,7 @@ class DictPersistence(BasePersistence):
"""Will update the bot_data (if changed).
Args:
data (:obj:`dict`): The :attr:`telegram.ext.dispatcher.bot_data`.
data (:obj:`dict`): The :attr:`telegram.ext.Dispatcher.bot_data`.
"""
if self._bot_data == data:
return
@@ -374,8 +374,8 @@ class DictPersistence(BasePersistence):
.. versionadded:: 13.6
Args:
data (:class:`telegram.ext.utils.types.CDCData`:): The relevant data to restore
:attr:`telegram.ext.dispatcher.bot.callback_data_cache`.
data (:class:`telegram.ext.utils.types.CDCData`): The relevant data to restore
:class:`telegram.ext.CallbackDataCache`.
"""
if self._callback_data == data:
return
+7 -4
View File
@@ -1,7 +1,7 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2021
# Copyright (C) 2015-2022
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
@@ -241,7 +241,9 @@ class Dispatcher(Generic[CCT, UD, CD, BD]):
if not use_context:
warnings.warn(
'Old Handler API is deprecated - see https://git.io/fxJuV for details',
'Old Handler API is deprecated - see '
'https://github.com/python-telegram-bot/python-telegram-bot/wiki/Transition'
'-guide-to-Version-12.0 for details',
TelegramDeprecationWarning,
stacklevel=3,
)
@@ -356,7 +358,7 @@ class Dispatcher(Generic[CCT, UD, CD, BD]):
raise RuntimeError(f'{cls.__name__} not initialized or multiple instances exist')
def _pooled(self) -> None:
thr_name = current_thread().getName()
thr_name = current_thread().name
while 1:
promise = self.__async_queue.get()
@@ -763,7 +765,8 @@ class Dispatcher(Generic[CCT, UD, CD, BD]):
asynchronously using :meth:`run_async`. Defaults to :obj:`False`.
Note:
See https://git.io/fxJuV for more info about switching to context based API.
See https://github.com/python-telegram-bot/python-telegram-bot/wiki\
/Transition-guide-to-Version-12.0 for more info about switching to context based API.
"""
if callback in self.error_handlers:
self.logger.debug('The callback is already registered as an error handler. Ignoring.')
+20 -3
View File
@@ -2,7 +2,7 @@
# pylint: disable=E0611,E0213,E1102,C0103,E1101,R0913,R0904
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2021
# Copyright (C) 2015-2022
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
@@ -62,7 +62,9 @@ class ExtBot(telegram.bot.Bot):
arbitrary_callback_data (:obj:`bool` | :obj:`int`, optional): Whether to
allow arbitrary objects as callback data for :class:`telegram.InlineKeyboardButton`.
Pass an integer to specify the maximum number of objects cached in memory. For more
details, please see our `wiki <https://git.io/JGBDI>`_. Defaults to :obj:`False`.
details, please see our `wiki <https://github.com/python-telegram-bot/\
python-telegram-bot/wiki/Arbitrary-callback_data>`_.
Defaults to :obj:`False`.
Attributes:
arbitrary_callback_data (:obj:`bool` | :obj:`int`): Whether this bot instance
@@ -101,8 +103,9 @@ class ExtBot(telegram.bot.Bot):
request=request,
private_key=private_key,
private_key_password=private_key_password,
defaults=defaults,
)
# We don't pass this to super().__init__ to avoid the deprecation warning
self.defaults = defaults
# set up callback_data
if not isinstance(arbitrary_callback_data, bool):
@@ -192,6 +195,7 @@ class ExtBot(telegram.bot.Bot):
allow_sending_without_reply: ODVInput[bool] = DEFAULT_NONE,
timeout: ODVInput[float] = DEFAULT_NONE,
api_kwargs: JSONDict = None,
protect_content: bool = None,
) -> Union[bool, Message]:
# We override this method to call self._replace_keyboard and self._insert_callback_data.
# This covers most methods that have a reply_markup
@@ -204,6 +208,7 @@ class ExtBot(telegram.bot.Bot):
allow_sending_without_reply=allow_sending_without_reply,
timeout=timeout,
api_kwargs=api_kwargs,
protect_content=protect_content,
)
if isinstance(result, Message):
self._insert_callback_data(result)
@@ -298,6 +303,7 @@ class ExtBot(telegram.bot.Bot):
reply_markup: ReplyMarkup = None,
timeout: ODVInput[float] = DEFAULT_NONE,
api_kwargs: JSONDict = None,
protect_content: bool = None,
) -> MessageId:
# We override this method to call self._replace_keyboard
return super().copy_message(
@@ -313,6 +319,7 @@ class ExtBot(telegram.bot.Bot):
reply_markup=self._replace_keyboard(reply_markup),
timeout=timeout,
api_kwargs=api_kwargs,
protect_content=protect_content,
)
def get_chat(
@@ -324,3 +331,13 @@ class ExtBot(telegram.bot.Bot):
# We override this method to call self._insert_callback_data
result = super().get_chat(chat_id=chat_id, timeout=timeout, api_kwargs=api_kwargs)
return self._insert_callback_data(result)
# updated camelCase aliases
getChat = get_chat
"""Alias for :meth:`get_chat`"""
copyMessage = copy_message
"""Alias for :meth:`copy_message`"""
getUpdates = get_updates
"""Alias for :meth:`get_updates`"""
stopPoll = stop_poll
"""Alias for :meth:`stop_poll`"""
+109 -5
View File
@@ -1,7 +1,7 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2021
# Copyright (C) 2015-2022
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
@@ -1182,6 +1182,56 @@ officedocument.wordprocessingml.document")``.
voice_chat_participants_invited = _VoiceChatParticipantsInvited()
"""Messages that contain :attr:`telegram.Message.voice_chat_participants_invited`."""
class _VideoChatScheduled(MessageFilter):
__slots__ = ()
name = 'Filters.status_update.video_chat_scheduled'
def filter(self, message: Message) -> bool:
return bool(message.video_chat_scheduled)
video_chat_scheduled = _VideoChatScheduled()
"""Messages that contain :attr:`telegram.Message.video_chat_scheduled`."""
class _VideoChatStarted(MessageFilter):
__slots__ = ()
name = 'Filters.status_update.video_chat_started'
def filter(self, message: Message) -> bool:
return bool(message.video_chat_started)
video_chat_started = _VideoChatStarted()
"""Messages that contain :attr:`telegram.Message.video_chat_started`."""
class _VideoChatEnded(MessageFilter):
__slots__ = ()
name = 'Filters.status_update.video_chat_ended'
def filter(self, message: Message) -> bool:
return bool(message.video_chat_ended)
video_chat_ended = _VideoChatEnded()
"""Messages that contain :attr:`telegram.Message.voice_chat_ended`."""
class _VideoChatParticipantsInvited(MessageFilter):
__slots__ = ()
name = 'Filters.status_update.video_chat_participants_invited'
def filter(self, message: Message) -> bool:
return bool(message.video_chat_participants_invited)
video_chat_participants_invited = _VideoChatParticipantsInvited()
"""Messages that contain :attr:`telegram.Message.video_chat_participants_invited`."""
class _WebAppData(MessageFilter):
__slots__ = ()
name = 'Filters.status_update.web_app_data'
def filter(self, message: Message) -> bool:
return bool(message.web_app_data)
web_app_data = _WebAppData()
"""Messages that contain :attr:`telegram.Message.web_app_data`."""
name = 'Filters.status_update'
def filter(self, message: Update) -> bool:
@@ -1201,6 +1251,11 @@ officedocument.wordprocessingml.document")``.
or self.voice_chat_started(message)
or self.voice_chat_ended(message)
or self.voice_chat_participants_invited(message)
or self.video_chat_scheduled(message)
or self.video_chat_started(message)
or self.video_chat_ended(message)
or self.video_chat_participants_invited(message)
or self.web_app_data(message)
)
status_update = _StatusUpdate()
@@ -1242,18 +1297,38 @@ officedocument.wordprocessingml.document")``.
:attr:`telegram.Message.voice_chat_scheduled`.
.. versionadded:: 13.5
.. deprecated:: 13.12
voice_chat_started: Messages that contain
:attr:`telegram.Message.voice_chat_started`.
.. versionadded:: 13.4
.. deprecated:: 13.12
voice_chat_ended: Messages that contain
:attr:`telegram.Message.voice_chat_ended`.
.. versionadded:: 13.4
.. deprecated:: 13.12
voice_chat_participants_invited: Messages that contain
:attr:`telegram.Message.voice_chat_participants_invited`.
.. versionadded:: 13.4
.. deprecated:: 13.12
video_chat_scheduled: Messages that contain
:attr:`telegram.Message.video_chat_scheduled`.
.. versionadded:: 13.12
video_chat_started: Messages that contain
:attr:`telegram.Message.video_chat_started`.
.. versionadded:: 13.12
video_chat_ended: Messages that contain
:attr:`telegram.Message.video_chat_ended`.
.. versionadded:: 13.12
video_chat_participants_invited: Messages that contain
:attr:`telegram.Message.video_chat_participants_invited`.
.. versionadded:: 13.12
"""
@@ -1965,16 +2040,16 @@ officedocument.wordprocessingml.document")``.
class sender_chat(_ChatUserBaseFilter):
# pylint: disable=W0235
"""Filters messages to allow only those which are from a specified sender chats chat ID or
"""Filters messages to allow only those which are from a specified sender chat's chat ID or
username.
Examples:
* To filter for messages forwarded to a discussion group from a channel with ID
* To filter for messages sent to a group by a channel with ID
``-1234``, use ``MessageHandler(Filters.sender_chat(-1234), callback_method)``.
* To filter for messages of anonymous admins in a super group with username
``@anonymous``, use
``MessageHandler(Filters.sender_chat(username='anonymous'), callback_method)``.
* To filter for messages forwarded to a discussion group from *any* channel, use
* To filter for messages sent to a group by *any* channel, use
``MessageHandler(Filters.sender_chat.channel, callback_method)``.
* To filter for messages of anonymous admins in *any* super group, use
``MessageHandler(Filters.sender_chat.super_group, callback_method)``.
@@ -1983,7 +2058,10 @@ officedocument.wordprocessingml.document")``.
Remember, ``sender_chat`` is also set for messages in a channel as the channel itself,
so when your bot is an admin in a channel and the linked discussion group, you would
receive the message twice (once from inside the channel, once inside the discussion
group).
group). Since v13.9, the field :attr:`telegram.Message.is_automatic_forward` will be
:obj:`True` for the discussion group message.
.. seealso:: :attr:`Filters.is_automatic_forward`
Warning:
:attr:`chat_ids` will return a *copy* of the saved chat ids as :class:`frozenset`. This
@@ -2089,6 +2167,32 @@ officedocument.wordprocessingml.document")``.
super_group = _SuperGroup()
channel = _Channel()
class _IsAutomaticForward(MessageFilter):
__slots__ = ()
name = 'Filters.is_automatic_forward'
def filter(self, message: Message) -> bool:
return bool(message.is_automatic_forward)
is_automatic_forward = _IsAutomaticForward()
"""Messages that contain :attr:`telegram.Message.is_automatic_forward`.
.. versionadded:: 13.9
"""
class _HasProtectedContent(MessageFilter):
__slots__ = ()
name = 'Filters.has_protected_content'
def filter(self, message: Message) -> bool:
return bool(message.has_protected_content)
has_protected_content = _HasProtectedContent()
"""Messages that contain :attr:`telegram.Message.has_protected_content`.
.. versionadded:: 13.9
"""
class _Invoice(MessageFilter):
__slots__ = ()
name = 'Filters.invoice'

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