Compare commits

..

35 Commits

Author SHA1 Message Date
Bibo-Joshi 2ac4e009d0 Bump version to v21.4 (#4371) 2024-07-12 17:40:42 +02:00
Bibo-Joshi efe1392e73 Automate PyPI Releases (#4364) 2024-07-12 16:44:41 +02:00
Bibo-Joshi 0a673e8f7e Documentation Improvements (#4303)
Co-authored-by: poolitzer <github@poolitzer.eu>
2024-07-12 16:33:42 +02:00
Bibo-Joshi 86c8cae40d Restructure Readme (#4362) 2024-07-10 20:36:47 +02:00
Bibo-Joshi f737702544 Use a Composite Action for Testing Type Completeness (#4367) 2024-07-10 17:33:04 +02:00
Bibo-Joshi 06f1da576e Stabilize Some Concurrency Usages in Test Suite (#4360) 2024-07-10 17:11:22 +02:00
Bibo-Joshi 7a470d57c8 Add a Test Case for MenuButton (#4363) 2024-07-10 17:10:33 +02:00
Poolitzer 1714bfd8f6 Deprecate Inclusion of successful_payment in Message.effective_attachment (#4365) 2024-07-09 23:33:57 +02:00
Poolitzer 71e4015e22 API 7.7 (#4356)
Co-authored-by: Harshil <37377066+harshil21@users.noreply.github.com>
Co-authored-by: Bibo-Joshi <22366557+Bibo-Joshi@users.noreply.github.com>
2024-07-09 10:35:18 +02:00
Harshil 52237cf00c Add filters.PAID_MEDIA (#4357) 2024-07-07 22:23:31 +02:00
Harshil dba7866aab API 7.6 (#4333, #4341, #4342, #4334, #4335, #4344, #4348, #4351)
Co-authored-by: Bibo-Joshi <22366557+Bibo-Joshi@users.noreply.github.com>
2024-07-07 13:08:52 +02:00
Bibo-Joshi 98bed6f01a Log Received Data on Deserialization Errors (#4304) 2024-07-06 16:09:04 +02:00
Antares 42d7c8c477 Add MessageEntity.adjust_message_entities_to_utf_16 Utility Function (#4323)
Co-authored-by: Bibo-Joshi <22366557+Bibo-Joshi@users.noreply.github.com>
Co-authored-by: Harshil <37377066+harshil21@users.noreply.github.com>
2024-07-06 16:08:29 +02:00
Poolitzer 8018e5ff3f Extend SuccessfulPayment Test (#4349) 2024-07-05 23:03:54 +02:00
Harshil c39839b026 Small Fixes for test_stars.py (#4347) 2024-07-05 18:44:41 +02:00
Harshil 4213c12c5b Use Python 3.13 Beta 3 in Test Suite (#4336)
Co-authored-by: Hinrich Mahler <22366557+Bibo-Joshi@users.noreply.github.com>
2024-07-03 19:04:45 +02:00
pre-commit-ci[bot] 97226b1ae3 Bump pre-commit Hooks to Latest Versions (#4337)
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Hinrich Mahler <22366557+Bibo-Joshi@users.noreply.github.com>
2024-07-03 18:29:09 +02:00
Harshil 146ec54a00 API 7.5 (#4312, #4311, #4315, #4328, #4316)
Co-authored-by: Bibo-Joshi <22366557+Bibo-Joshi@users.noreply.github.com>
2024-07-01 21:45:37 +02:00
Bibo-Joshi df8aae0a38 Fix Link-Check Workflow (#4332) 2024-07-01 20:43:54 +02:00
Bibo-Joshi 4ccc80f9c1 Make Argument bot of TelegramObject.de_json Optional (#4320) 2024-07-01 19:59:54 +02:00
Harshil cfc75bb08b Bump ruff and Add New Rules (#4329) 2024-06-30 18:22:12 +02:00
Palaptin 51ef571a07 Add Lower Bound for flaky Dependency (#4322) 2024-06-23 20:15:37 +02:00
Harshil 9ce0f49882 Add Support for Python 3.13 Beta (#4253)
Co-authored-by: Bibo-Joshi <22366557+Bibo-Joshi@users.noreply.github.com>
2024-06-18 22:25:02 +02:00
dependabot[bot] 5b1e7399a4 Bump pytest from 8.2.1 to 8.2.2 (#4294)
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Bibo-Joshi <22366557+Bibo-Joshi@users.noreply.github.com>
2024-06-18 22:20:47 +02:00
Harshil a83046e1ec Add mise-en-place to .gitignore (#4300) 2024-06-17 19:32:47 +02:00
Bibo-Joshi 44e8292838 Drop python-telegram-bot-raw And Switch to pyproject.toml Based Packaging (#4288) 2024-06-15 10:29:19 +02:00
Hinrich Mahler a9f6afd015 Bump version to v21.3 2024-06-07 16:52:22 +02:00
Bibo-Joshi 78c945d485 Documentation Improvements (#4264) 2024-06-07 16:13:55 +02:00
Trijeet Modak 9e70ac8b7a Add Parameter chat_id to ChatMemberHandler (#4290) 2024-06-06 17:31:45 +02:00
Harshil cf728496e4 API 7.4 (#4276, #4278, #4279, #4280, #4286, #4283, #4285)
Co-authored-by: Bibo-Joshi <22366557+Bibo-Joshi@users.noreply.github.com>
2024-06-03 19:39:31 +02:00
dependabot[bot] 078d775250 Bump pytest from 8.2.0 to 8.2.1 (#4272)
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-06-03 19:25:54 +02:00
Bibo-Joshi 57298aa076 Deprecate python-telegram-bot-raw (#4270) 2024-06-01 21:19:38 +02:00
Bibo-Joshi 2c299bb109 Add setuptools to requirements-dev.txt (#4282) 2024-05-30 21:02:41 +02:00
Harshil c1c5438f37 Remove Functionality Deprecated in Bot API 7.3 (#4266) 2024-05-29 19:59:23 +02:00
Bibo-Joshi 6ba7a097f4 Update Settings for pre-commit.ci (#4265) 2024-05-22 17:43:45 +02:00
187 changed files with 6176 additions and 2428 deletions
+4 -9
View File
@@ -26,7 +26,7 @@ Setting things up
.. code-block:: bash
$ pip install -r requirements-all.txt
$ pip install -r requirements-dev-all.txt
5. Install pre-commit hooks:
@@ -194,7 +194,7 @@ Feel free to copy (parts of) the checklist to the PR description to remind you o
- Added or updated documentation for the changed class(es) and/or method(s)
- Added the new method(s) to ``_extbot.py``
- Added or updated ``bot_methods.rst``
- Updated the Bot API version number in all places: ``README.rst`` and ``README_RAW.rst`` (including the badge), as well as ``telegram.constants.BOT_API_VERSION_INFO``
- Updated the Bot API version number in all places: ``README.rst`` (including the badge) and ``telegram.constants.BOT_API_VERSION_INFO``
- Added logic for arbitrary callback data in :class:`telegram.ext.ExtBot` for new methods that either accept a ``reply_markup`` in some form or have a return type that is/contains :class:`~telegram.Message`
Documenting
@@ -210,13 +210,8 @@ doc strings don't have a separate documentation site they generate, instead, the
User facing documentation
-------------------------
We use `sphinx`_ to generate static HTML docs. To build them, first make sure you're running Python 3.9 or above and have the required dependencies:
.. code-block:: bash
$ pip install -r docs/requirements-docs.txt
then run the following from the PTB root directory:
We use `sphinx`_ to generate static HTML docs. To build them, first make sure you're running Python 3.9 or above and have the required dependencies installed as explained above.
Then, run the following from the PTB root directory:
.. code-block:: bash
+1 -1
View File
@@ -22,6 +22,6 @@ jobs:
- name: Install dependencies
run: |
python -W ignore -m pip install --upgrade pip
python -W ignore -m pip install -r requirements-all.txt
python -W ignore -m pip install -r requirements-dev-all.txt
- name: Check Links
run: sphinx-build docs/source docs/build/html -W --keep-going -j auto -b linkcheck
+1 -1
View File
@@ -28,7 +28,7 @@ jobs:
- name: Install dependencies
run: |
python -W ignore -m pip install --upgrade pip
python -W ignore -m pip install -r requirements-all.txt
python -W ignore -m pip install -r requirements-dev-all.txt
- name: Test autogeneration of admonitions
run: pytest -v --tb=short tests/docs/admonition_inserter.py
- name: Build docs
@@ -1,19 +0,0 @@
name: Warning maintainers
on:
pull_request_target:
paths:
- requirements.txt
- requirements-opts.txt
- .pre-commit-config.yaml
permissions:
pull-requests: write
jobs:
job:
runs-on: ubuntu-latest
name: about pre-commit and dependency change
steps:
- name: running the check
uses: Poolitzer/notifier-action@master
with:
notify-message: Hey! Looks like you edited the (optional) requirements or the pre-commit hooks. I'm just a friendly reminder to keep the additional dependencies for the hooks in sync with the requirements :)
repo-token: ${{ secrets.GITHUB_TOKEN }}
-18
View File
@@ -1,18 +0,0 @@
name: Warning maintainers
on:
pull_request_target:
paths:
- README.rst
- README_RAW.rst
permissions:
pull-requests: write
jobs:
job:
runs-on: ubuntu-latest
name: about readme change
steps:
- name: running the check
uses: Poolitzer/notifier-action@master
with:
notify-message: Hey! Looks like you edited README.rst or README_RAW.rst. I'm just a friendly reminder to apply relevant changes to both of those files :)
repo-token: ${{ secrets.GITHUB_TOKEN }}
+204
View File
@@ -0,0 +1,204 @@
name: Publish to PyPI
on:
# Run on any tag
push:
tags:
- '**'
# manually trigger the workflow - for testing only
workflow_dispatch:
jobs:
build:
name: Build Distribution
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: "3.x"
- name: Install pypa/build
run: >-
python3 -m pip install build --user
- name: Build a binary wheel and a source tarball
run: python3 -m build
- name: Store the distribution packages
uses: actions/upload-artifact@v4
with:
name: python-package-distributions
path: dist/
publish-to-pypi:
name: Publish to PyPI
# only publish to PyPI on tag pushes
if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags')
needs:
- build
runs-on: ubuntu-latest
environment:
name: release_pypi
url: https://pypi.org/p/python-telegram-bot
permissions:
id-token: write # IMPORTANT: mandatory for trusted publishing
steps:
- name: Download all the dists
uses: actions/download-artifact@v4
with:
name: python-package-distributions
path: dist/
- name: Publish to PyPI
uses: pypa/gh-action-pypi-publish@release/v1
publish-to-test-pypi:
name: Publish to Test PyPI
needs:
- build
runs-on: ubuntu-latest
environment:
name: release_test_pypi
url: https://test.pypi.org/p/python-telegram-bot
permissions:
id-token: write # IMPORTANT: mandatory for trusted publishing
steps:
- name: Download all the dists
uses: actions/download-artifact@v4
with:
name: python-package-distributions
path: dist/
- name: Publish to Test PyPI
uses: pypa/gh-action-pypi-publish@release/v1
with:
repository-url: https://test.pypi.org/legacy/
compute-signatures:
name: Compute SHA1 Sums and Sign with Sigstore
runs-on: ubuntu-latest
needs:
- publish-to-pypi
- publish-to-test-pypi
# run if either of the publishing jobs ran successfully
# see also:
# https://github.com/actions/runner/issues/491#issuecomment-850884422
if: |
always() && (
(needs.publish-to-pypi.result == 'success') ||
(needs.publish-to-test-pypi.result == 'success')
)
permissions:
id-token: write # IMPORTANT: mandatory for sigstore
steps:
- name: Download all the dists
uses: actions/download-artifact@v4
with:
name: python-package-distributions
path: dist/
- name: Compute SHA1 Sums
run: |
# Compute SHA1 sum of the distribution packages and save it to a file with the same name,
# but with .sha1 extension
for file in dist/*; do
sha1sum $file > $file.sha1
done
- name: Sign the dists with Sigstore
uses: sigstore/gh-action-sigstore-python@v2.1.1
with:
inputs: >-
./dist/*.tar.gz
./dist/*.whl
- name: Store the distribution packages and signatures
uses: actions/upload-artifact@v4
with:
name: python-package-distributions-and-signatures
path: dist/
github-release:
name: Upload to GitHub Release
needs:
- publish-to-pypi
- compute-signatures
if: |
always() && (
(needs.publish-to-pypi.result == 'success') &&
(needs.compute-signatures.result == 'success')
)
runs-on: ubuntu-latest
permissions:
contents: write # IMPORTANT: mandatory for making GitHub Releases
steps:
- name: Download all the dists
uses: actions/download-artifact@v4
with:
name: python-package-distributions-and-signatures
path: dist/
- name: Create GitHub Release
env:
GITHUB_TOKEN: ${{ github.token }}
# Create a GitHub Release for this tag. The description can be changed later, as for now
# we don't define it through this workflow.
run: >-
gh release create
'${{ github.ref_name }}'
--repo '${{ github.repository }}'
--generate-notes
- name: Upload artifact signatures to GitHub Release
env:
GITHUB_TOKEN: ${{ github.token }}
# Upload to GitHub Release using the `gh` CLI.
# `dist/` contains the built packages, and the
# sigstore-produced signatures and certificates.
run: >-
gh release upload
'${{ github.ref_name }}' dist/**
--repo '${{ github.repository }}'
github-test-release:
name: Upload to GitHub Release Draft
needs:
- publish-to-test-pypi
- compute-signatures
if: |
always() && (
(needs.publish-to-test-pypi.result == 'success') &&
(needs.compute-signatures.result == 'success')
)
runs-on: ubuntu-latest
permissions:
contents: write # IMPORTANT: mandatory for making GitHub Releases
steps:
- name: Download all the dists
uses: actions/download-artifact@v4
with:
name: python-package-distributions-and-signatures
path: dist/
- name: Create GitHub Release
env:
GITHUB_TOKEN: ${{ github.token }}
# Create a GitHub Release *draft*. The description can be changed later, as for now
# we don't define it through this workflow.
run: >-
gh release create
'${{ github.ref_name }}'
--repo '${{ github.repository }}'
--generate-notes
--draft
- name: Upload artifact signatures to GitHub Release
env:
GITHUB_TOKEN: ${{ github.token }}
# Upload to GitHub Release using the `gh` CLI.
# `dist/` contains the built packages, and the
# sigstore-produced signatures and certificates.
run: >-
gh release upload
'${{ github.ref_name }}' dist/**
--repo '${{ github.repository }}'
+2 -3
View File
@@ -29,9 +29,8 @@ jobs:
- 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-opts.txt
python -W ignore -m pip install -r requirements-dev.txt
python -W ignore -m pip install .[all]
python -W ignore -m pip install -r requirements-unit-tests.txt
- name: Compare to official api
run: |
pytest -v tests/test_official/test_official.py --junit-xml=.test_report_official.xml
+6 -64
View File
@@ -3,8 +3,8 @@ on:
pull_request:
paths:
- telegram/**
- requirements.txt
- requirements-opts.txt
- pyproject.toml
- .github/workflows/type_completeness.yml
push:
branches:
- master
@@ -14,66 +14,8 @@ jobs:
name: test-type-completeness
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: git fetch --depth=1 # https://github.com/actions/checkout/issues/329#issuecomment-674881489
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v5
- uses: Bibo-Joshi/pyright-type-completeness@1.0.0
with:
python-version: 3.9
cache: 'pip'
cache-dependency-path: '**/requirements*.txt'
- name: Install Pyright
run: |
python -W ignore -m pip install pyright~=1.1.316
- name: Get PR Completeness
# Must run before base completeness, as base completeness will checkout the base branch
# And we can't go back to the PR branch after that in case the PR is coming from a fork
run: |
pip install . -U
pyright --verifytypes telegram --ignoreexternal --outputjson > pr.json || true
pyright --verifytypes telegram --ignoreexternal > pr.readable || true
- name: Get Base Completeness
run: |
git checkout ${{ github.base_ref }}
pip install . -U
pyright --verifytypes telegram --ignoreexternal --outputjson > base.json || true
- name: Compare Completeness
uses: jannekem/run-python-script-action@v1
with:
script: |
import json
import os
from pathlib import Path
base = float(
json.load(open("base.json", "rb"))["typeCompleteness"]["completenessScore"]
)
pr = float(
json.load(open("pr.json", "rb"))["typeCompleteness"]["completenessScore"]
)
base_text = f"This PR changes type completeness from {round(base, 3)} to {round(pr, 3)}."
if base == 0:
text = f"Something is broken in the workflow. Reported type completeness is 0. 💥"
set_summary(text)
print(Path("pr.readable").read_text(encoding="utf-8"))
error(text)
exit(1)
if pr < (base - 0.001):
text = f"{base_text} ❌"
set_summary(text)
print(Path("pr.readable").read_text(encoding="utf-8"))
error(text)
exit(1)
elif pr > (base + 0.001):
text = f"{base_text} ✨"
set_summary(text)
if pr < 1:
print(Path("pr.readable").read_text(encoding="utf-8"))
print(text)
else:
text = f"{base_text} This is less than 0.1 percentage points. ✅"
set_summary(text)
print(Path("pr.readable").read_text(encoding="utf-8"))
print(text)
package-name: telegram
python-version: 3.12
pyright-version: ~=1.1.367
+7 -7
View File
@@ -4,9 +4,9 @@ on:
paths:
- telegram/**
- tests/**
- requirements.txt
- requirements-opts.txt
- requirements-dev.txt
- .github/workflows/unit_tests.yml
- pyproject.toml
- requirements-unit-tests.txt
push:
branches:
- master
@@ -20,7 +20,7 @@ jobs:
runs-on: ${{matrix.os}}
strategy:
matrix:
python-version: ['3.8', '3.9', '3.10', '3.11', '3.12']
python-version: ['3.8', '3.9', '3.10', '3.11', '3.12', '3.13.0-beta.3']
os: [ubuntu-latest, windows-latest, macos-latest]
fail-fast: False
steps:
@@ -35,8 +35,8 @@ jobs:
run: |
python -W ignore -m pip install --upgrade pip
python -W ignore -m pip install -U pytest-cov
python -W ignore -m pip install -r requirements.txt
python -W ignore -m pip install -r requirements-dev.txt
python -W ignore -m pip install .
python -W ignore -m pip install -r requirements-unit-tests.txt
python -W ignore -m pip install pytest-xdist[psutil]
- name: Test with pytest
@@ -65,7 +65,7 @@ jobs:
# Test the rest
export TEST_WITH_OPT_DEPS='true'
pip install -r requirements-opts.txt
pip install .[all]
# `-n auto --dist loadfile` uses pytest-xdist to run each test file on a different CPU
# worker. Increasing number of workers has little effect on test duration, but it seems
# to increase flakyness, specially on python 3.7 with --dist=loadgroup.
+3
View File
@@ -92,3 +92,6 @@ telegram.jpg
# virtual env
venv*
# environment manager:
.mise.toml
+8 -7
View File
@@ -1,12 +1,13 @@
# Make sure that the additional_dependencies here match requirements(-opts).txt
# Make sure that the additional_dependencies here match pyproject.toml
ci:
autofix_prs: false
autoupdate_schedule: monthly
autoupdate_schedule: quarterly
autoupdate_commit_msg: 'Bump `pre-commit` Hooks to Latest Versions'
repos:
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: 'v0.4.3'
rev: 'v0.5.0'
hooks:
- id: ruff
name: ruff
@@ -24,11 +25,11 @@ repos:
- --diff
- --check
- repo: https://github.com/PyCQA/flake8
rev: 7.0.0
rev: 7.1.0
hooks:
- id: flake8
- repo: https://github.com/PyCQA/pylint
rev: v3.1.0
rev: v3.2.4
hooks:
- id: pylint
files: ^(?!(tests|docs)).*\.py$
@@ -40,7 +41,7 @@ repos:
- aiolimiter~=1.1.0
- . # this basically does `pip install -e .`
- repo: https://github.com/pre-commit/mirrors-mypy
rev: v1.10.0
rev: v1.10.1
hooks:
- id: mypy
name: mypy-ptb
@@ -67,7 +68,7 @@ repos:
- cachetools~=5.3.3
- . # this basically does `pip install -e .`
- repo: https://github.com/asottile/pyupgrade
rev: v3.15.2
rev: v3.16.0
hooks:
- id: pyupgrade
args:
+86
View File
@@ -4,6 +4,92 @@
Changelog
=========
Version 21.4
============
*Released 2024-07-12*
This is the technical changelog for version 21.4. More elaborate release notes can be found in the news channel `@pythontelegrambotchannel <https://t.me/pythontelegrambotchannel>`_.
Major Changes
-------------
- Full Support for Bot API 7.5 (:pr:`4328`, :pr:`4316`, :pr:`4315`, :pr:`4312` closes :issue:`4310`, :pr:`4311`)
- Full Support for Bot API 7.6 (:pr:`4333` closes :issue:`4331`, :pr:`4344`, :pr:`4341`, :pr:`4334`, :pr:`4335`, :pr:`4351`, :pr:`4342`, :pr:`4348`)
- Full Support for Bot API 7.7 (:pr:`4356` closes :issue:`4355`)
- Drop ``python-telegram-bot-raw`` And Switch to ``pyproject.toml`` Based Packaging (:pr:`4288` closes :issue:`4129` and :issue:`4296`)
- Deprecate Inclusion of ``successful_payment`` in ``Message.effective_attachment`` (:pr:`4365` closes :issue:`4350`)
New Features
------------
- Add Support for Python 3.13 Beta (:pr:`4253`)
- Add ``filters.PAID_MEDIA`` (:pr:`4357`)
- Log Received Data on Deserialization Errors (:pr:`4304`)
- Add ``MessageEntity.adjust_message_entities_to_utf_16`` Utility Function (:pr:`4323` by `Antares0982 <https://github.com/Antares0982>`_ closes :issue:`4319`)
- Make Argument ``bot`` of ``TelegramObject.de_json`` Optional (:pr:`4320`)
Documentation Improvements
--------------------------
- Documentation Improvements (:pr:`4303` closes :issue:`4301`)
- Restructure Readme (:pr:`4362`)
- Fix Link-Check Workflow (:pr:`4332`)
Internal Changes
----------------
- Automate PyPI Releases (:pr:`4364` closes :issue:`4318`)
- Add ``mise-en-place`` to ``.gitignore`` (:pr:`4300`)
- Use a Composite Action for Testing Type Completeness (:pr:`4367`)
- Stabilize Some Concurrency Usages in Test Suite (:pr:`4360`)
- Add a Test Case for ``MenuButton`` (:pr:`4363`)
- Extend ``SuccessfulPayment`` Test (:pr:`4349`)
- Small Fixes for ``test_stars.py`` (:pr:`4347`)
- Use Python 3.13 Beta 3 in Test Suite (:pr:`4336`)
Dependency Updates
------------------
- Bump ``ruff`` and Add New Rules (:pr:`4329`)
- Bump ``pre-commit`` Hooks to Latest Versions (:pr:`4337`)
- Add Lower Bound for ``flaky`` Dependency (:pr:`4322` by `Palaptin <https://github.com/Palaptin>`_)
- Bump ``pytest`` from 8.2.1 to 8.2.2 (:pr:`4294`)
Version 21.3
============
*Released 2024-06-07*
This is the technical changelog for version 21.3. More elaborate release notes can be found in the news channel `@pythontelegrambotchannel <https://t.me/pythontelegrambotchannel>`_.
Major Changes
-------------
- Full Support for Bot API 7.4 (:pr:`4286`, :pr:`4276` closes :issue:`4275`, :pr:`4285`, :pr:`4283`, :pr:`4280`, :pr:`4278`, :pr:`4279`)
- Deprecate ``python-telegram-bot-raw`` (:pr:`4270`)
- Remove Functionality Deprecated in Bot API 7.3 (:pr:`4266` closes :issue:`4244`)
New Features
------------
- Add Parameter ``chat_id`` to ``ChatMemberHandler`` (:pr:`4290` by `uniquetrij <https://github.com/uniquetrij>`_ closes :issue:`4287`)
Documentation Improvements
--------------------------
- Documentation Improvements (:pr:`4264` closes :issue:`4240`)
Internal Changes
----------------
- Add ``setuptools`` to ``requirements-dev.txt`` (:pr:`4282`)
- Update Settings for pre-commit.ci (:pr:`4265`)
Dependency Updates
------------------
- Bump ``pytest`` from 8.2.0 to 8.2.1 (:pr:`4272`)
Version 21.2
============
-1
View File
@@ -1 +0,0 @@
include LICENSE LICENSE.lesser requirements.txt requirements-opts.txt README_RAW.rst telegram/py.typed
+45 -30
View File
@@ -1,6 +1,3 @@
..
Make sure to apply any changes to this file to README_RAW.rst as well!
.. image:: https://raw.githubusercontent.com/python-telegram-bot/logos/master/logo-text/png/ptb-logo-text_768.png
:align: center
:target: https://python-telegram-bot.org
@@ -14,7 +11,7 @@
:target: https://pypi.org/project/python-telegram-bot/
:alt: Supported Python versions
.. image:: https://img.shields.io/badge/Bot%20API-7.3-blue?logo=telegram
.. image:: https://img.shields.io/badge/Bot%20API-7.7-blue?logo=telegram
:target: https://core.telegram.org/bots/api-changelog
:alt: Supported Bot API version
@@ -69,30 +66,36 @@ We have a vibrant community of developers helping each other in our `Telegram gr
*Stay tuned for library updates and new releases on our* `Telegram Channel <https://telegram.me/pythontelegrambotchannel>`_.
Introduction
============
------------
This library provides a pure Python, asynchronous interface for the
`Telegram Bot API <https://core.telegram.org/bots/api>`_.
It's compatible with Python versions **3.8+**.
In addition to the pure API implementation, this library features a number of high-level classes to
In addition to the pure API implementation, this library features several convenience methods and shortcuts as well as 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>`_
Note
----
Installing both ``python-telegram-bot`` and ``python-telegram-bot-raw`` in conjunction will result in undesired side-effects, so only install *one* of both.
After installing_ the library, be sure to check out the section on `working with PTB`_.
Telegram API support
====================
~~~~~~~~~~~~~~~~~~~~
All types and methods of the Telegram Bot API **7.3** are supported.
All types and methods of the Telegram Bot API **7.7** are natively supported by this library.
In addition, Bot API functionality not yet natively included can still be used as described `in our wiki <https://github.com/python-telegram-bot/python-telegram-bot/wiki/Bot-API-Forward-Compatibility>`_.
Notable Features
~~~~~~~~~~~~~~~~
- `Fully asynchronous <https://github.com/python-telegram-bot/python-telegram-bot/wiki/Concurrency>`_
- Convenient shortcut methods, e.g. `Message.reply_text <https://docs.python-telegram-bot.org/en/stable/telegram.message.html#telegram.Message.reply_text>`_
- `Fully annotated with static type hints <https://github.com/python-telegram-bot/python-telegram-bot/wiki/Type-Checking>`_
- `Customizable and extendable interface <https://github.com/python-telegram-bot/python-telegram-bot/wiki/Architecture>`_
- Seamless integration with `webhooks <https://github.com/python-telegram-bot/python-telegram-bot/wiki/Webhooks>`_ and `polling <https://docs.python-telegram-bot.org/en/stable/telegram.ext.application.html#telegram.ext.Application.run_polling>`_
- `Comprehensive documentation and examples <#working-with-ptb>`_
Installing
==========
----------
You can install or upgrade ``python-telegram-bot`` via
@@ -108,22 +111,27 @@ You can also install ``python-telegram-bot`` from source, though this is usually
$ git clone https://github.com/python-telegram-bot/python-telegram-bot
$ cd python-telegram-bot
$ python setup.py install
$ pip install build
$ python -m build
Verifying Releases
------------------
~~~~~~~~~~~~~~~~~~
We sign all the releases with a GPG key.
The signatures are uploaded to both the `GitHub releases page <https://github.com/python-telegram-bot/python-telegram-bot/releases>`_ and the `PyPI project <https://pypi.org/project/python-telegram-bot/>`_ and end with a suffix ``.asc``.
To enable you to verify that a release file that you downloaded was indeed provided by the ``python-telegram-bot`` team, we have taken the following measures.
Starting with v21.4, all releases are signed via `sigstore <https://sigstore.dev>`_.
The corresponding signature files are uploaded to the `GitHub releases page`_.
To verify the signature, please install the `sigstore Python client <https://pypi.org/project/sigstore/>`_ and follow the instructions for `verifying signatures from GitHub Actions <https://github.com/sigstore/sigstore-python#signatures-from-github-actions>`_. As input for the ``--repository`` parameter, please use the value ``python-telegram-bot/python-telegram-bot``.
Earlier releases are signed with a GPG key.
The signatures are uploaded to both the `GitHub releases page`_ and the `PyPI project <https://pypi.org/project/python-telegram-bot/>`_ and end with a suffix ``.asc``.
Please find the public keys `here <https://github.com/python-telegram-bot/python-telegram-bot/tree/master/public_keys>`_.
The keys are named in the format ``<first_version>-<last_version>.gpg`` or ``<first_version>-current.gpg`` if the key is currently being used for new releases.
The keys are named in the format ``<first_version>-<last_version>.gpg``.
In addition, the GitHub release page also contains the sha1 hashes of the release files in the files with the suffix ``.sha1``.
This allows you to verify that a release file that you downloaded was indeed provided by the ``python-telegram-bot`` team.
Dependencies & Their Versions
-----------------------------
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
``python-telegram-bot`` tries to use as few 3rd party dependencies as possible.
However, for some features using a 3rd party library is more sane than implementing the functionality again.
@@ -159,14 +167,19 @@ Additionally, two shortcuts are provided:
* ``pip install "python-telegram-bot[all]"`` installs all optional dependencies.
* ``pip install "python-telegram-bot[ext]"`` installs all optional dependencies that are related to ``telegram.ext``, i.e. ``[rate-limiter, webhooks, callback-data, job-queue]``.
Working with PTB
----------------
Once you have installed the library, you can begin working with it - so let's get started!
Quick Start
===========
~~~~~~~~~~~
Our Wiki contains an `Introduction to the API <https://github.com/python-telegram-bot/python-telegram-bot/wiki/Introduction-to-the-API>`_ explaining how the pure Bot API can be accessed via ``python-telegram-bot``.
Moreover, the `Tutorial: Your first Bot <https://github.com/python-telegram-bot/python-telegram-bot/wiki/Extensions---Your-first-Bot>`_ gives an introduction on how chatbots can be easily programmed with the help of the ``telegram.ext`` module.
Resources
=========
~~~~~~~~~
- The `package documentation <https://docs.python-telegram-bot.org/>`_ is the technical reference for ``python-telegram-bot``.
It contains descriptions of all available classes, modules, methods and arguments as well as the `changelog <https://docs.python-telegram-bot.org/changelog.html>`_.
@@ -177,7 +190,7 @@ Resources
- The `official Telegram Bot API documentation <https://core.telegram.org/bots/api>`_ is of course always worth a read.
Getting help
============
~~~~~~~~~~~~
If the resources mentioned above don't answer your questions or simply overwhelm you, there are several ways of getting help.
@@ -188,7 +201,7 @@ If the resources mentioned above don't answer your questions or simply overwhelm
3. You can even ask for help on Stack Overflow using the `python-telegram-bot tag <https://stackoverflow.com/questions/tagged/python-telegram-bot>`_.
Concurrency
===========
~~~~~~~~~~~
Since v20.0, ``python-telegram-bot`` is built on top of Pythons ``asyncio`` module.
Because ``asyncio`` is in general single-threaded, ``python-telegram-bot`` does currently not aim to be thread-safe.
@@ -201,20 +214,22 @@ Noteworthy parts of ``python-telegram-bots`` API that are likely to cause issues
* all classes in the ``telegram.ext.filters`` module that allow to add/remove allowed users/chats at runtime
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 or feature requests <https://github.com/python-telegram-bot/python-telegram-bot/issues/new/choose>`_.
Donating
========
--------
Occasionally we are asked if we accept donations to support the development.
While we appreciate the thought, maintaining PTB is our hobby, and we have almost no running costs for it. We therefore have nothing set up to accept donations.
If you still want to donate, we kindly ask you to donate to another open source project/initiative of your choice instead.
License
=======
-------
You may copy, distribute and modify the software provided that modifications are described and licensed for free under `LGPL-3 <https://www.gnu.org/licenses/lgpl-3.0.html>`_.
Derivatives works (including modifications or anything statically linked to the library) can only be redistributed under LGPL-3, but applications that use the library don't have to be.
.. _`GitHub releases page`: https://github.com/python-telegram-bot/python-telegram-bot/releases>
-206
View File
@@ -1,206 +0,0 @@
..
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
:target: https://python-telegram-bot.org
:alt: python-telegram-bot-raw Logo
.. image:: https://img.shields.io/pypi/v/python-telegram-bot-raw.svg
:target: https://pypi.org/project/python-telegram-bot-raw/
:alt: PyPi Package Version
.. image:: https://img.shields.io/pypi/pyversions/python-telegram-bot-raw.svg
:target: https://pypi.org/project/python-telegram-bot-raw/
:alt: Supported Python versions
.. image:: https://img.shields.io/badge/Bot%20API-7.3-blue?logo=telegram
:target: https://core.telegram.org/bots/api-changelog
:alt: Supported Bot API version
.. image:: https://img.shields.io/pypi/dm/python-telegram-bot-raw
:target: https://pypistats.org/packages/python-telegram-bot-raw
:alt: PyPi Package Monthly Download
.. image:: https://readthedocs.org/projects/python-telegram-bot/badge/?version=stable
:target: https://docs.python-telegram-bot.org/
:alt: Documentation Status
.. image:: https://img.shields.io/pypi/l/python-telegram-bot-raw.svg
:target: https://www.gnu.org/licenses/lgpl-3.0.html
:alt: LGPLv3 License
.. image:: https://github.com/python-telegram-bot/python-telegram-bot/actions/workflows/unit_tests.yml/badge.svg?branch=master
:target: https://github.com/python-telegram-bot/python-telegram-bot/
:alt: Github Actions workflow
.. image:: https://codecov.io/gh/python-telegram-bot/python-telegram-bot/branch/master/graph/badge.svg
:target: https://app.codecov.io/gh/python-telegram-bot/python-telegram-bot
:alt: Code coverage
.. image:: https://isitmaintained.com/badge/resolution/python-telegram-bot/python-telegram-bot.svg
:target: https://isitmaintained.com/project/python-telegram-bot/python-telegram-bot
:alt: Median time to resolve an issue
.. image:: https://api.codacy.com/project/badge/Grade/99d901eaa09b44b4819aec05c330c968
:target: https://app.codacy.com/gh/python-telegram-bot/python-telegram-bot/dashboard
:alt: Code quality: Codacy
.. image:: https://results.pre-commit.ci/badge/github/python-telegram-bot/python-telegram-bot/master.svg
:target: https://results.pre-commit.ci/latest/github/python-telegram-bot/python-telegram-bot/master
:alt: pre-commit.ci status
.. image:: https://img.shields.io/badge/code%20style-black-000000.svg
:target: https://github.com/psf/black
:alt: Code Style: Black
.. image:: https://img.shields.io/badge/Telegram-Channel-blue.svg?logo=telegram
:target: https://t.me/pythontelegrambotchannel
:alt: Telegram Channel
.. image:: https://img.shields.io/badge/Telegram-Group-blue.svg?logo=telegram
:target: https://telegram.me/pythontelegrambotgroup
:alt: Telegram Group
We have made you a wrapper you can't refuse
We have a vibrant community of developers helping each other in our `Telegram group <https://telegram.me/pythontelegrambotgroup>`_. Join us!
*Stay tuned for library updates and new releases on our* `Telegram Channel <https://telegram.me/pythontelegrambotchannel>`_.
Introduction
============
This library provides a pure Python, asynchronous interface for the
`Telegram Bot API <https://core.telegram.org/bots/api>`_.
It's compatible with Python versions **3.8+**.
``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.
Note
----
Installing both ``python-telegram-bot`` and ``python-telegram-bot-raw`` in conjunction will result in undesired side-effects, so only install *one* of both.
Telegram API support
====================
All types and methods of the Telegram Bot API **7.3** are supported.
Installing
==========
You can install or upgrade ``python-telegram-bot`` via
.. code:: shell
$ pip install python-telegram-bot-raw --upgrade
To install a pre-release, use the ``--pre`` `flag <https://pip.pypa.io/en/stable/cli/pip_install/#cmdoption-pre>`_ in addition.
You can also install ``python-telegram-bot-raw`` from source, though this is usually not necessary.
.. code:: shell
$ git clone https://github.com/python-telegram-bot/python-telegram-bot
$ cd python-telegram-bot
$ python setup_raw.py install
Note
----
Installing the ``.tar.gz`` archive available on PyPi directly via ``pip`` will *not* work as expected, as ``pip`` does not recognize that it should use ``setup_raw.py`` instead of ``setup.py``.
Verifying Releases
------------------
We sign all the releases with a GPG key.
The signatures are uploaded to both the `GitHub releases page <https://github.com/python-telegram-bot/python-telegram-bot/releases>`_ and the `PyPI project <https://pypi.org/project/python-telegram-bot/>`_ and end with a suffix ``.asc``.
Please find the public keys `here <https://github.com/python-telegram-bot/python-telegram-bot/tree/master/public_keys>`_.
The keys are named in the format ``<first_version>-<last_version>.gpg`` or ``<first_version>-current.gpg`` if the key is currently being used for new releases.
In addition, the GitHub release page also contains the sha1 hashes of the release files in the files with the suffix ``.sha1``.
This allows you to verify that a release file that you downloaded was indeed provided by the ``python-telegram-bot`` team.
Dependencies & Their Versions
-----------------------------
``python-telegram-bot`` tries to use as few 3rd party dependencies as possible.
However, for some features using a 3rd party library is more sane than implementing the functionality again.
As these features are *optional*, the corresponding 3rd party dependencies are not installed by default.
Instead, they are listed as optional dependencies.
This allows to avoid unnecessary dependency conflicts for users who don't need the optional features.
The only required dependency is `httpx ~= 0.27 <https://www.python-httpx.org>`_ for
``telegram.request.HTTPXRequest``, the default networking backend.
``python-telegram-bot`` is most useful when used along with additional libraries.
To minimize dependency conflicts, we try to be liberal in terms of version requirements on the (optional) dependencies.
On the other hand, we have to ensure stability of ``python-telegram-bot``, which is why we do apply version bounds.
If you encounter dependency conflicts due to these bounds, feel free to reach out.
Optional Dependencies
#####################
PTB can be installed with optional dependencies:
* ``pip install "python-telegram-bot-raw[passport]"`` installs the `cryptography>=39.0.1 <https://cryptography.io/en/stable>`_ library. Use this, if you want to use Telegram Passport related functionality.
* ``pip install "python-telegram-bot-raw[socks]"`` installs `httpx[socks] <https://www.python-httpx.org/#dependencies>`_. Use this, if you want to work behind a Socks5 server.
* ``pip install "python-telegram-bot-raw[http2]"`` installs `httpx[http2] <https://www.python-httpx.org/#dependencies>`_. Use this, if you want to use HTTP/2.
To install multiple optional dependencies, separate them by commas, e.g. ``pip install "python-telegram-bot-raw[passport,socks]"``.
Additionally, the shortcut ``pip install "python-telegram-bot-raw[all]"`` installs all optional dependencies.
Quick Start
===========
Our Wiki contains an `Introduction to the API <https://github.com/python-telegram-bot/python-telegram-bot/wiki/Introduction-to-the-API>`_ explaining how the pure Bot API can be accessed via ``python-telegram-bot``.
Resources
=========
- The `package documentation <https://docs.python-telegram-bot.org/>`_ is the technical reference for ``python-telegram-bot``.
It contains descriptions of all available classes, modules, methods and arguments as well as the `changelog <https://docs.python-telegram-bot.org/changelog.html>`_.
- The `wiki <https://github.com/python-telegram-bot/python-telegram-bot/wiki/>`_ is home to number of more elaborate introductions of the different features of ``python-telegram-bot`` and other useful resources that go beyond the technical documentation.
- Our `examples section <https://docs.python-telegram-bot.org/examples.html>`_ contains several examples that showcase the different features of both the Bot API and ``python-telegram-bot``.
Even if it is not your approach for learning, please take a look at ``echobot.py``. It is the de facto base for most of the bots out there.
The code for these examples is released to the public domain, so you can start by grabbing the code and building on top of it.
- The `official Telegram Bot API documentation <https://core.telegram.org/bots/api>`_ is of course always worth a read.
Getting help
============
If the resources mentioned above don't answer your questions or simply overwhelm you, there are several ways of getting help.
1. We have a vibrant community of developers helping each other in our `Telegram group <https://telegram.me/pythontelegrambotgroup>`_. Join us! Asking a question here is often the quickest way to get a pointer in the right direction.
2. Ask questions by opening `a discussion <https://github.com/python-telegram-bot/python-telegram-bot/discussions/new>`_.
3. You can even ask for help on Stack Overflow using the `python-telegram-bot tag <https://stackoverflow.com/questions/tagged/python-telegram-bot>`_.
Concurrency
===========
Since v20.0, ``python-telegram-bot`` is built on top of Pythons ``asyncio`` module.
Because ``asyncio`` is in general single-threaded, ``python-telegram-bot`` does currently not aim to be thread-safe.
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 or feature requests <https://github.com/python-telegram-bot/python-telegram-bot/issues/new/choose>`_.
Donating
========
Occasionally we are asked if we accept donations to support the development.
While we appreciate the thought, maintaining PTB is our hobby, and we have almost no running costs for it. We therefore have nothing set up to accept donations.
If you still want to donate, we kindly ask you to donate to another open source project/initiative of your choice instead.
License
=======
You may copy, distribute and modify the software provided that modifications are described and licensed for free under `LGPL-3 <https://www.gnu.org/licenses/lgpl-3.0.html>`_.
Derivatives works (including modifications or anything statically linked to the library) can only be redistributed under LGPL-3, but applications that use the library don't have to be.
+1
View File
@@ -46,6 +46,7 @@ PRIVATE_BASE_CLASSES = {
"_BaseThumbedMedium": "TelegramObject",
"_BaseMedium": "TelegramObject",
"_CredentialsBase": "TelegramObject",
"_ChatBase": "TelegramObject",
}
+1 -1
View File
@@ -4,4 +4,4 @@ furo-sphinx-search @ git+https://github.com/harshil21/furo-sphinx-search@v0.2.0.
sphinx-paramlinks==0.6.0
sphinxcontrib-mermaid==0.9.2
sphinx-copybutton==0.5.2
sphinx-inline-tabs==2023.4.21
sphinx-inline-tabs==2023.4.21
+6 -2
View File
@@ -20,9 +20,13 @@ author = "Leandro Toledo"
# built documents.
#
# The short X.Y version.
version = "21.2" # telegram.__version__[:3]
# Import needs to be below the sys.path.insert above
import telegram # noqa: E402
version = telegram.__version__
# The full version, including alpha/beta/rc tags.
release = "21.2" # telegram.__version__
release = telegram.__version__
# If your documentation needs a minimal Sphinx version, state it here.
needs_sphinx = "6.1.3"
+6
View File
@@ -33,6 +33,8 @@
- Used for sending media grouped together
* - :meth:`~telegram.Bot.send_message`
- Used for sending text messages
* - :meth:`~telegram.Bot.send_paid_media`
- Used for sending paid media to channels
* - :meth:`~telegram.Bot.send_photo`
- Used for sending photos
* - :meth:`~telegram.Bot.send_poll`
@@ -369,6 +371,10 @@
- Used for getting basic info about a file
* - :meth:`~telegram.Bot.get_me`
- Used for getting basic information about the bot
* - :meth:`~telegram.Bot.get_star_transactions`
- Used for obtaining the bot's Telegram Stars transactions
* - :meth:`~telegram.Bot.refund_star_payment`
- Used for refunding a payment in Telegram Stars
.. raw:: html
+12
View File
@@ -3,6 +3,18 @@
You can adapt this file completely to your liking, but it should at least
contain the root `toctree` directive.
.. raw:: html
<div style="display: none">
Hidden Headline
===============
This is just here to get furo to display the right sidebar.
.. raw:: html
</div>
.. include:: ../../README.rst
.. The toctrees are hidden such that they don't render on the start page but still include the contents into the documentation.
+8
View File
@@ -88,6 +88,9 @@ Available Types
telegram.inputmediadocument
telegram.inputmediaphoto
telegram.inputmediavideo
telegram.inputpaidmedia
telegram.inputpaidmediaphoto
telegram.inputpaidmediavideo
telegram.inputpolloption
telegram.inputsticker
telegram.keyboardbutton
@@ -113,6 +116,11 @@ Available Types
telegram.messageoriginuser
telegram.messagereactioncountupdated
telegram.messagereactionupdated
telegram.paidmedia
telegram.paidmediainfo
telegram.paidmediaphoto
telegram.paidmediapreview
telegram.paidmediavideo
telegram.photosize
telegram.poll
telegram.pollanswer
+2
View File
@@ -1,6 +1,8 @@
Chat
====
.. Also lists methods of _ChatBase, but not the ones of TelegramObject
.. autoclass:: telegram.Chat
:members:
:show-inheritance:
:inherited-members: TelegramObject
+3 -1
View File
@@ -1,6 +1,8 @@
ChatFullInfo
============
.. Also lists methods of _ChatBase, but not the ones of TelegramObject
.. autoclass:: telegram.ChatFullInfo
:members:
:show-inheritance:
:show-inheritance:
:inherited-members: TelegramObject
+6
View File
@@ -0,0 +1,6 @@
InputPaidMedia
==============
.. autoclass:: telegram.InputPaidMedia
:members:
:show-inheritance:
@@ -0,0 +1,6 @@
InputPaidMediaPhoto
===================
.. autoclass:: telegram.InputPaidMediaPhoto
:members:
:show-inheritance:
@@ -0,0 +1,6 @@
InputPaidMediaVideo
===================
.. autoclass:: telegram.InputPaidMediaVideo
:members:
:show-inheritance:
+6
View File
@@ -0,0 +1,6 @@
PaidMedia
=========
.. autoclass:: telegram.PaidMedia
:members:
:show-inheritance:
+6
View File
@@ -0,0 +1,6 @@
PaidMediaInfo
=============
.. autoclass:: telegram.PaidMediaInfo
:members:
:show-inheritance:
+6
View File
@@ -0,0 +1,6 @@
PaidMediaPhoto
==============
.. autoclass:: telegram.PaidMediaPhoto
:members:
:show-inheritance:
@@ -0,0 +1,6 @@
PaidMediaPreview
================
.. autoclass:: telegram.PaidMediaPreview
:members:
:show-inheritance:
+6
View File
@@ -0,0 +1,6 @@
PaidMediaVideo
==============
.. autoclass:: telegram.PaidMediaVideo
:members:
:show-inheritance:
+12
View File
@@ -8,7 +8,19 @@ Payments
telegram.labeledprice
telegram.orderinfo
telegram.precheckoutquery
telegram.refundedpayment
telegram.revenuewithdrawalstate
telegram.revenuewithdrawalstatefailed
telegram.revenuewithdrawalstatepending
telegram.revenuewithdrawalstatesucceeded
telegram.shippingaddress
telegram.shippingoption
telegram.shippingquery
telegram.startransaction
telegram.startransactions
telegram.successfulpayment
telegram.transactionpartner
telegram.transactionpartnerfragment
telegram.transactionpartnerother
telegram.transactionpartnertelegramads
telegram.transactionpartneruser
+1 -1
View File
@@ -1,6 +1,6 @@
PhotoSize
=========
.. Also lists methods of _BaseThumbedMedium, but not the ones of TelegramObject
.. Also lists methods of _BaseMedium, but not the ones of TelegramObject
.. autoclass:: telegram.PhotoSize
:members:
+6
View File
@@ -0,0 +1,6 @@
RefundedPayment
===============
.. autoclass:: telegram.RefundedPayment
:members:
:show-inheritance:
@@ -0,0 +1,7 @@
RevenueWithdrawalState
======================
.. autoclass:: telegram.RevenueWithdrawalState
:members:
:show-inheritance:
:inherited-members: TelegramObject
@@ -0,0 +1,7 @@
RevenueWithdrawalStateFailed
=============================
.. autoclass:: telegram.RevenueWithdrawalStateFailed
:members:
:show-inheritance:
:inherited-members: TelegramObject
@@ -0,0 +1,7 @@
RevenueWithdrawalStatePending
=============================
.. autoclass:: telegram.RevenueWithdrawalStatePending
:members:
:show-inheritance:
:inherited-members: TelegramObject
@@ -0,0 +1,7 @@
RevenueWithdrawalStateSucceeded
===============================
.. autoclass:: telegram.RevenueWithdrawalStateSucceeded
:members:
:show-inheritance:
:inherited-members: TelegramObject
+7
View File
@@ -0,0 +1,7 @@
StarTransaction
===============
.. autoclass:: telegram.StarTransaction
:members:
:show-inheritance:
:inherited-members: TelegramObject
@@ -0,0 +1,8 @@
StarTransactions
================
.. autoclass:: telegram.StarTransactions
:members:
:show-inheritance:
:inherited-members: TelegramObject
@@ -0,0 +1,7 @@
TransactionPartner
==================
.. autoclass:: telegram.TransactionPartner
:members:
:show-inheritance:
:inherited-members: TelegramObject
@@ -0,0 +1,7 @@
TransactionPartnerFragment
==========================
.. autoclass:: telegram.TransactionPartnerFragment
:members:
:show-inheritance:
:inherited-members: TelegramObject
@@ -0,0 +1,7 @@
TransactionPartnerOther
=======================
.. autoclass:: telegram.TransactionPartnerOther
:members:
:show-inheritance:
:inherited-members: TelegramObject
@@ -0,0 +1,7 @@
TransactionPartnerTelegramAds
=============================
.. autoclass:: telegram.TransactionPartnerTelegramAds
:members:
:show-inheritance:
:inherited-members: TelegramObject
@@ -0,0 +1,7 @@
TransactionPartnerUser
======================
.. autoclass:: telegram.TransactionPartnerUser
:members:
:show-inheritance:
:inherited-members: TelegramObject
+10
View File
@@ -16,6 +16,8 @@
.. |editreplymarkup| replace:: It is currently only possible to edit messages without :attr:`telegram.Message.reply_markup` or with inline keyboards.
.. |bcid_edit_time| replace:: Note that business messages that were not sent by the bot and do not contain an inline keyboard can only be edited within *48 hours* from the time they were sent.
.. |toapikwargsbase| replace:: These arguments are also considered by :meth:`~telegram.TelegramObject.to_dict` and :meth:`~telegram.TelegramObject.to_json`, i.e. when passing objects to Telegram. Passing them to Telegram is however not guaranteed to work for all kinds of objects, e.g. this will fail for objects that can not directly be JSON serialized.
.. |toapikwargsarg| replace:: Arbitrary keyword arguments. Can be used to store data for which there are no dedicated attributes. |toapikwargsbase|
@@ -81,3 +83,11 @@
.. |non_optional_story_argument| replace:: As of this version, this argument is now required. In accordance with our `stability policy <https://docs.python-telegram-bot.org/en/stable/stability_policy.html>`__, the signature will be kept as optional for now, though they are mandatory and an error will be raised if you don't pass it.
.. |business_id_str| replace:: Unique identifier of the business connection on behalf of which the message will be sent.
.. |business_id_str_edit| replace:: Unique identifier of the business connection on behalf of which the message to be edited was sent
.. |message_effect_id| replace:: Unique identifier of the message effect to be added to the message; for private chats only.
.. |show_cap_above_med| replace:: :obj:`True`, if the caption must be shown above the message media.
.. |tg_stars| replace:: `Telegram Stars <https://t.me/BotNews/90>`__
+10 -10
View File
@@ -47,9 +47,9 @@ async def msg(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
# Files will be downloaded to current directory
for data in passport_data.decrypted_data: # This is where the data gets decrypted
if data.type == "phone_number":
print("Phone: ", data.phone_number)
logger.info("Phone: %s", data.phone_number)
elif data.type == "email":
print("Email: ", data.email)
logger.info("Email: %s", data.email)
if data.type in (
"personal_details",
"passport",
@@ -58,7 +58,7 @@ async def msg(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"internal_passport",
"address",
):
print(data.type, data.data)
logger.info(data.type, data.data)
if data.type in (
"utility_bill",
"bank_statement",
@@ -66,28 +66,28 @@ async def msg(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"passport_registration",
"temporary_registration",
):
print(data.type, len(data.files), "files")
logger.info(data.type, len(data.files), "files")
for file in data.files:
actual_file = await file.get_file()
print(actual_file)
logger.info(actual_file)
await actual_file.download_to_drive()
if (
data.type in ("passport", "driver_license", "identity_card", "internal_passport")
and data.front_side
):
front_file = await data.front_side.get_file()
print(data.type, front_file)
logger.info(data.type, front_file)
await front_file.download_to_drive()
if data.type in ("driver_license" and "identity_card") and data.reverse_side:
reverse_file = await data.reverse_side.get_file()
print(data.type, reverse_file)
logger.info(data.type, reverse_file)
await reverse_file.download_to_drive()
if (
data.type in ("passport", "driver_license", "identity_card", "internal_passport")
and data.selfie
):
selfie_file = await data.selfie.get_file()
print(data.type, selfie_file)
logger.info(data.type, selfie_file)
await selfie_file.download_to_drive()
if data.translation and data.type in (
"passport",
@@ -100,10 +100,10 @@ async def msg(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"passport_registration",
"temporary_registration",
):
print(data.type, len(data.translation), "translation")
logger.info(data.type, len(data.translation), "translation")
for file in data.translation:
actual_file = await file.get_file()
print(actual_file)
logger.info(actual_file)
await actual_file.download_to_drive()
+113 -6
View File
@@ -1,7 +1,116 @@
# PACKAGING
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
[project]
dynamic = ["version"]
name = "python-telegram-bot"
description = "We have made you a wrapper you can't refuse"
readme = "README.rst"
requires-python = ">=3.8"
license = "LGPL-3.0-only"
license-files = { paths = ["LICENSE", "LICENSE.dual", "LICENSE.lesser"] }
authors = [
{ name = "Leandro Toledo", email = "devs@python-telegram-bot.org" }
]
keywords = [
"python",
"telegram",
"bot",
"api",
"wrapper",
]
classifiers = [
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)",
"Operating System :: OS Independent",
"Topic :: Software Development :: Libraries :: Python Modules",
"Topic :: Communications :: Chat",
"Topic :: Internet",
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
"Programming Language :: Python :: 3.13",
]
dependencies = [
"httpx ~= 0.27",
]
[project.urls]
"Homepage" = "https://python-telegram-bot.org"
"Documentation" = "https://docs.python-telegram-bot.org"
"Bug Tracker" = "https://github.com/python-telegram-bot/python-telegram-bot/issues"
"Source Code" = "https://github.com/python-telegram-bot/python-telegram-bot"
"News" = "https://t.me/pythontelegrambotchannel"
"Changelog" = "https://docs.python-telegram-bot.org/en/stable/changelog.html"
"Support" = "https://t.me/pythontelegrambotgroup"
[project.optional-dependencies]
# Make sure to install those as additional_dependencies in the
# pre-commit hooks for pylint & mypy
# Also update the readme accordingly
#
# When dependencies release new versions and tests succeed, we should try to expand the allowed
# versions and only increase the lower bound if necessary
#
# When adding new groups, make sure to update `ext` and `all` accordingly
# Optional dependencies for production
all = [
"python-telegram-bot[ext,http2,passport,socks]",
]
callback-data = [
# Cachetools doesn't have a strict stability policy. Let's be cautious for now.
"cachetools~=5.3.3",
]
ext = [
"python-telegram-bot[callback-data,job-queue,rate-limiter,webhooks]",
]
http2 = [
"httpx[http2]",
]
job-queue = [
# APS doesn't have a strict stability policy. Let's be cautious for now.
"APScheduler~=3.10.4",
# pytz is required by APS and just needs the lower bound due to #2120
"pytz>=2018.6",
]
passport = [
"cryptography!=3.4,!=3.4.1,!=3.4.2,!=3.4.3,>=39.0.1",
# cffi is a dependency of cryptography and added support for python 3.13 in 1.17.0rc1
"cffi >= 1.17.0rc1; python_version > '3.12'"
]
rate-limiter = [
"aiolimiter~=1.1.0",
]
socks = [
"httpx[socks]",
]
webhooks = [
# tornado is rather stable, but let's not allow the next major release without prior testing
"tornado~=6.4",
]
# HATCH
[tool.hatch.version]
# dynamically evaluates the `__version__` variable in that file
source = "code"
path = "telegram/_version.py"
search-paths = ["telegram"]
[tool.hatch.build]
packages = ["telegram"]
# BLACK:
[tool.black]
line-length = 99
target-version = ['py38', 'py39', 'py310', 'py311']
# ISORT:
[tool.isort] # black config
@@ -11,22 +120,20 @@ line_length = 99
# RUFF:
[tool.ruff]
line-length = 99
target-version = "py38"
show-fixes = true
[tool.ruff.lint]
preview = true
explicit-preview-rules = true
explicit-preview-rules = true # TODO: Drop this when RUF022 and RUF023 are out of preview
ignore = ["PLR2004", "PLR0911", "PLR0912", "PLR0913", "PLR0915", "PERF203"]
select = ["E", "F", "I", "PL", "UP", "RUF", "PTH", "C4", "B", "PIE", "SIM", "RET", "RSE",
"G", "ISC", "PT", "ASYNC", "TCH", "SLOT", "PERF", "PYI", "FLY", "AIR", "RUF022",
"RUF023", "Q", "INP", "W", "YTT", "DTZ", "ARG"]
# Add "FURB" after it's out of preview
"RUF023", "Q", "INP", "W", "YTT", "DTZ", "ARG", "T20", "FURB"]
# Add "A (flake8-builtins)" after we drop pylint
[tool.ruff.lint.per-file-ignores]
"tests/*.py" = ["B018"]
"tests/**.py" = ["RUF012", "ASYNC101", "DTZ", "ARG"]
"tests/**.py" = ["RUF012", "ASYNC230", "DTZ", "ARG", "T201"]
"docs/**.py" = ["INP001", "ARG"]
"examples/**.py" = ["ARG"]
-4
View File
@@ -1,4 +0,0 @@
-r requirements.txt
-r requirements-dev.txt
-r requirements-opts.txt
-r docs/requirements-docs.txt
+5
View File
@@ -0,0 +1,5 @@
-e .[all]
# needed for pre-commit hooks in the git commit command
pre-commit
-r requirements-unit-tests.txt
-r docs/requirements-docs.txt
-10
View File
@@ -1,10 +0,0 @@
pre-commit # needed for pre-commit hooks in the git commit command
# For the test suite
pytest==8.2.0
pytest-asyncio==0.21.2 # needed because pytest doesn't come with native support for coroutines as tests
pytest-xdist==3.6.1 # xdist runs tests in parallel
flaky # Used for flaky tests (flaky decorator)
beautifulsoup4 # used in test_official for parsing tg docs
wheel # required for building the wheels for releases
-27
View File
@@ -1,27 +0,0 @@
# Format:
# package_name==version # req-1, req-2, req-3!ext
# `pip install ptb-raw[req-1/2]` will install `package_name`
# `pip install ptb[req-1/2/3]` will also install `package_name`
# Make sure to install those as additional_dependencies in the
# pre-commit hooks for pylint & mypy
# Also update the readme accordingly
# When dependencies release new versions and tests succeed, we should try to expand the allowed
# versions and only increase the lower bound if necessary
httpx[socks] # socks
httpx[http2] # http2
cryptography!=3.4,!=3.4.1,!=3.4.2,!=3.4.3,>=39.0.1 # passport
aiolimiter~=1.1.0 # rate-limiter!ext
# tornado is rather stable, but let's not allow the next mayor release without prior testing
tornado~=6.4 # webhooks!ext
# Cachetools and APS don't have a strict stability policy.
# Let's be cautious for now.
cachetools~=5.3.3 # callback-data!ext
APScheduler~=3.10.4 # job-queue!ext
# pytz is required by APS and just needs the lower bound due to #2120
pytz>=2018.6 # job-queue!ext
+19
View File
@@ -0,0 +1,19 @@
-e .
# required for building the wheels for releases
build
# For the test suite
pytest==8.2.2
# needed because pytest doesn't come with native support for coroutines as tests
pytest-asyncio==0.21.2
# xdist runs tests in parallel
pytest-xdist==3.6.1
# Used for flaky tests (flaky decorator)
flaky>=3.8.1
# used in test_official for parsing tg docs
beautifulsoup4
-10
View File
@@ -1,10 +0,0 @@
# Make sure to install those as additional_dependencies in the
# pre-commit hooks for pylint & mypy
# Also update the readme accordingly
# When dependencies release new versions and tests succeed, we should try to expand the allowed
# versions and only increase the lower bound if necessary
# httpx has no stable release yet, but we've had no stability problems since v20.0a0 either
# Since there have been requests to relax the bound a bit, we allow versions < 1.0.0
httpx ~= 0.27
+1 -4
View File
@@ -1,8 +1,5 @@
[metadata]
license_files = LICENSE, LICENSE.dual, LICENSE.lesser
[flake8]
max-line-length = 99
ignore = W503, W605
extend-ignore = E203, E704
exclude = setup.py, setup_raw.py docs/source/conf.py
exclude = docs/source/conf.py
-131
View File
@@ -1,131 +0,0 @@
#!/usr/bin/env python
"""The setup and build script for the python-telegram-bot library."""
import subprocess
import sys
from collections import defaultdict
from pathlib import Path
from typing import Any, Dict, List, Tuple
from setuptools import find_packages, setup
def get_requirements() -> List[str]:
"""Build the requirements list for this project"""
requirements_list = []
with Path("requirements.txt").open(encoding="utf-8") as reqs:
for install in reqs:
if install.startswith("#"):
continue
requirements_list.append(install.strip())
return requirements_list
def get_packages_requirements(raw: bool = False) -> Tuple[List[str], List[str]]:
"""Build the package & requirements list for this project"""
reqs = get_requirements()
exclude = ["tests*", "docs*"]
if raw:
exclude.append("telegram.ext*")
packs = find_packages(exclude=exclude)
return packs, reqs
def get_optional_requirements(raw: bool = False) -> Dict[str, List[str]]:
"""Build the optional dependencies"""
requirements = defaultdict(list)
with Path("requirements-opts.txt").open(encoding="utf-8") as reqs:
for line in reqs:
effective_line = line.strip()
if not effective_line or effective_line.startswith("#"):
continue
dependency, names = effective_line.split("#")
dependency = dependency.strip()
for name in names.split(","):
effective_name = name.strip()
if effective_name.endswith("!ext"):
if raw:
continue
effective_name = effective_name[:-4]
requirements["ext"].append(dependency)
requirements[effective_name].append(dependency)
requirements["all"].append(dependency)
return requirements
def get_setup_kwargs(raw: bool = False) -> Dict[str, Any]:
"""Builds a dictionary of kwargs for the setup function"""
packages, requirements = get_packages_requirements(raw=raw)
raw_ext = "-raw" if raw else ""
readme = Path(f'README{"_RAW" if raw else ""}.rst')
version_file = Path("telegram/_version.py").read_text(encoding="utf-8")
first_part = version_file.split("# SETUP.PY MARKER")[0]
exec(first_part) # pylint: disable=exec-used
return {
"script_name": f"setup{raw_ext}.py",
"name": f"python-telegram-bot{raw_ext}",
"version": locals()["__version__"],
"author": "Leandro Toledo",
"author_email": "devs@python-telegram-bot.org",
"license": "LGPLv3",
"url": "https://python-telegram-bot.org/",
# 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://docs.python-telegram-bot.org",
"Bug Tracker": "https://github.com/python-telegram-bot/python-telegram-bot/issues",
"Source Code": "https://github.com/python-telegram-bot/python-telegram-bot",
"News": "https://t.me/pythontelegrambotchannel",
"Changelog": "https://docs.python-telegram-bot.org/en/stable/changelog.html",
},
"download_url": f"https://pypi.org/project/python-telegram-bot{raw_ext}/",
"keywords": "python telegram bot api wrapper",
"description": "We have made you a wrapper you can't refuse",
"long_description": readme.read_text(encoding="utf-8"),
"long_description_content_type": "text/x-rst",
"packages": packages,
"install_requires": requirements,
"extras_require": get_optional_requirements(raw=raw),
"include_package_data": True,
"classifiers": [
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)",
"Operating System :: OS Independent",
"Topic :: Software Development :: Libraries :: Python Modules",
"Topic :: Communications :: Chat",
"Topic :: Internet",
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
],
"python_requires": ">=3.8",
}
def main() -> None:
# If we're building, build ptb-raw as well
if set(sys.argv[1:]) in [{"bdist_wheel"}, {"sdist"}, {"sdist", "bdist_wheel"}]:
args = ["python", "setup_raw.py"]
args.extend(sys.argv[1:])
subprocess.run(args, check=True, capture_output=True)
setup(**get_setup_kwargs(raw=False))
if __name__ == "__main__":
main()
-8
View File
@@ -1,8 +0,0 @@
#!/usr/bin/env python
"""The setup and build script for the python-telegram-bot-raw library."""
from setuptools import setup
from setup import get_setup_kwargs
setup(**get_setup_kwargs(raw=True))
+40 -3
View File
@@ -142,6 +142,9 @@ __all__ = (
"InputMediaPhoto",
"InputMediaVideo",
"InputMessageContent",
"InputPaidMedia",
"InputPaidMediaPhoto",
"InputPaidMediaVideo",
"InputPollOption",
"InputSticker",
"InputTextMessageContent",
@@ -173,6 +176,11 @@ __all__ = (
"MessageReactionCountUpdated",
"MessageReactionUpdated",
"OrderInfo",
"PaidMedia",
"PaidMediaInfo",
"PaidMediaPhoto",
"PaidMediaPreview",
"PaidMediaVideo",
"PassportData",
"PassportElementError",
"PassportElementErrorDataField",
@@ -196,10 +204,15 @@ __all__ = (
"ReactionType",
"ReactionTypeCustomEmoji",
"ReactionTypeEmoji",
"RefundedPayment",
"ReplyKeyboardMarkup",
"ReplyKeyboardRemove",
"ReplyParameters",
"ResidentialAddress",
"RevenueWithdrawalState",
"RevenueWithdrawalStateFailed",
"RevenueWithdrawalStatePending",
"RevenueWithdrawalStateSucceeded",
"SecureData",
"SecureValue",
"SentWebAppMessage",
@@ -207,6 +220,8 @@ __all__ = (
"ShippingAddress",
"ShippingOption",
"ShippingQuery",
"StarTransaction",
"StarTransactions",
"Sticker",
"StickerSet",
"Story",
@@ -214,6 +229,11 @@ __all__ = (
"SwitchInlineQueryChosenChat",
"TelegramObject",
"TextQuote",
"TransactionPartner",
"TransactionPartnerFragment",
"TransactionPartnerOther",
"TransactionPartnerTelegramAds",
"TransactionPartnerUser",
"Update",
"User",
"UserChatBoosts",
@@ -242,7 +262,6 @@ __all__ = (
"warnings",
)
from . import _version, constants, error, helpers, request, warnings
from ._birthdate import Birthdate
from ._bot import Bot
@@ -324,6 +343,9 @@ from ._files.inputmedia import (
InputMediaDocument,
InputMediaPhoto,
InputMediaVideo,
InputPaidMedia,
InputPaidMediaPhoto,
InputPaidMediaVideo,
)
from ._files.inputsticker import InputSticker
from ._files.location import Location
@@ -396,6 +418,7 @@ from ._messageorigin import (
MessageOriginUser,
)
from ._messagereactionupdated import MessageReactionCountUpdated, MessageReactionUpdated
from ._paidmedia import PaidMedia, PaidMediaInfo, PaidMediaPhoto, PaidMediaPreview, PaidMediaVideo
from ._passport.credentials import (
Credentials,
DataCredentials,
@@ -424,9 +447,23 @@ from ._payment.invoice import Invoice
from ._payment.labeledprice import LabeledPrice
from ._payment.orderinfo import OrderInfo
from ._payment.precheckoutquery import PreCheckoutQuery
from ._payment.refundedpayment import RefundedPayment
from ._payment.shippingaddress import ShippingAddress
from ._payment.shippingoption import ShippingOption
from ._payment.shippingquery import ShippingQuery
from ._payment.stars import (
RevenueWithdrawalState,
RevenueWithdrawalStateFailed,
RevenueWithdrawalStatePending,
RevenueWithdrawalStateSucceeded,
StarTransaction,
StarTransactions,
TransactionPartner,
TransactionPartnerFragment,
TransactionPartnerOther,
TransactionPartnerTelegramAds,
TransactionPartnerUser,
)
from ._payment.successfulpayment import SuccessfulPayment
from ._poll import InputPollOption, Poll, PollAnswer, PollOption
from ._proximityalerttriggered import ProximityAlertTriggered
@@ -470,8 +507,8 @@ __version_info__: _version.Version = _version.__version_info__
#:
#: .. versionchanged:: 20.0
#: This constant was previously named ``bot_api_version``.
__bot_api_version__: str = _version.__bot_api_version__
__bot_api_version__: str = constants.BOT_API_VERSION
#: :class:`typing.NamedTuple`: Shortcut for :const:`telegram.constants.BOT_API_VERSION_INFO`.
#:
#: .. versionadded:: 20.0
__bot_api_version_info__: constants._BotAPIVersion = _version.__bot_api_version_info__
__bot_api_version_info__: constants._BotAPIVersion = constants.BOT_API_VERSION_INFO
+1
View File
@@ -17,6 +17,7 @@
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
# pylint: disable=missing-module-docstring
# ruff: noqa: T201
import subprocess
import sys
from typing import Optional
+424 -56
View File
File diff suppressed because it is too large Load Diff
+8 -2
View File
@@ -84,13 +84,19 @@ class BotCommandScope(TelegramObject):
self._freeze()
@classmethod
def de_json(cls, data: Optional[JSONDict], bot: "Bot") -> Optional["BotCommandScope"]:
def de_json(
cls, data: Optional[JSONDict], bot: Optional["Bot"] = None
) -> 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.
bot (:class:`telegram.Bot`, optional): The bot associated with this object. Defaults to
:obj:`None`, in which case shortcut methods will not be available.
.. versionchanged:: 21.4
:paramref:`bot` is now optional and defaults to :obj:`None`
Returns:
The Telegram object.
+15 -5
View File
@@ -106,7 +106,9 @@ class BusinessConnection(TelegramObject):
self._freeze()
@classmethod
def de_json(cls, data: Optional[JSONDict], bot: "Bot") -> Optional["BusinessConnection"]:
def de_json(
cls, data: Optional[JSONDict], bot: Optional["Bot"] = None
) -> Optional["BusinessConnection"]:
"""See :meth:`telegram.TelegramObject.de_json`."""
data = cls._parse_data(data)
@@ -175,7 +177,9 @@ class BusinessMessagesDeleted(TelegramObject):
self._freeze()
@classmethod
def de_json(cls, data: Optional[JSONDict], bot: "Bot") -> Optional["BusinessMessagesDeleted"]:
def de_json(
cls, data: Optional[JSONDict], bot: Optional["Bot"] = None
) -> Optional["BusinessMessagesDeleted"]:
"""See :meth:`telegram.TelegramObject.de_json`."""
data = cls._parse_data(data)
@@ -232,7 +236,9 @@ class BusinessIntro(TelegramObject):
self._freeze()
@classmethod
def de_json(cls, data: Optional[JSONDict], bot: "Bot") -> Optional["BusinessIntro"]:
def de_json(
cls, data: Optional[JSONDict], bot: Optional["Bot"] = None
) -> Optional["BusinessIntro"]:
"""See :meth:`telegram.TelegramObject.de_json`."""
data = cls._parse_data(data)
@@ -284,7 +290,9 @@ class BusinessLocation(TelegramObject):
self._freeze()
@classmethod
def de_json(cls, data: Optional[JSONDict], bot: "Bot") -> Optional["BusinessLocation"]:
def de_json(
cls, data: Optional[JSONDict], bot: Optional["Bot"] = None
) -> Optional["BusinessLocation"]:
"""See :meth:`telegram.TelegramObject.de_json`."""
data = cls._parse_data(data)
@@ -431,7 +439,9 @@ class BusinessOpeningHours(TelegramObject):
self._freeze()
@classmethod
def de_json(cls, data: Optional[JSONDict], bot: "Bot") -> Optional["BusinessOpeningHours"]:
def de_json(
cls, data: Optional[JSONDict], bot: Optional["Bot"] = None
) -> Optional["BusinessOpeningHours"]:
"""See :meth:`telegram.TelegramObject.de_json`."""
data = cls._parse_data(data)
+21 -2
View File
@@ -93,7 +93,7 @@ class CallbackQuery(TelegramObject):
with the callback button that originated the query.
.. versionchanged:: 20.8
Objects maybe be of type :class:`telegram.MaybeInaccessibleMessage` since Bot API
Objects may be of type :class:`telegram.MaybeInaccessibleMessage` since Bot API
7.0.
data (:obj:`str` | :obj:`object`): Optional. Data associated with the callback button.
Be aware that the message, which originated the query, can contain no callback buttons
@@ -148,7 +148,9 @@ class CallbackQuery(TelegramObject):
self._freeze()
@classmethod
def de_json(cls, data: Optional[JSONDict], bot: "Bot") -> Optional["CallbackQuery"]:
def de_json(
cls, data: Optional[JSONDict], bot: Optional["Bot"] = None
) -> Optional["CallbackQuery"]:
"""See :meth:`telegram.TelegramObject.de_json`."""
data = cls._parse_data(data)
@@ -260,6 +262,8 @@ class CallbackQuery(TelegramObject):
entities=entities,
chat_id=None,
message_id=None,
# inline messages can not be sent on behalf of a bcid
business_connection_id=None,
)
return await self._get_message().edit_text(
text=text,
@@ -281,6 +285,7 @@ class CallbackQuery(TelegramObject):
reply_markup: Optional["InlineKeyboardMarkup"] = None,
parse_mode: ODVInput[str] = DEFAULT_NONE,
caption_entities: Optional[Sequence["MessageEntity"]] = None,
show_caption_above_media: Optional[bool] = None,
*,
read_timeout: ODVInput[float] = DEFAULT_NONE,
write_timeout: ODVInput[float] = DEFAULT_NONE,
@@ -326,6 +331,9 @@ class CallbackQuery(TelegramObject):
caption_entities=caption_entities,
chat_id=None,
message_id=None,
show_caption_above_media=show_caption_above_media,
# inline messages can not be sent on behalf of a bcid
business_connection_id=None,
)
return await self._get_message().edit_caption(
caption=caption,
@@ -337,6 +345,7 @@ class CallbackQuery(TelegramObject):
parse_mode=parse_mode,
api_kwargs=api_kwargs,
caption_entities=caption_entities,
show_caption_above_media=show_caption_above_media,
)
async def edit_message_reply_markup(
@@ -385,6 +394,8 @@ class CallbackQuery(TelegramObject):
api_kwargs=api_kwargs,
chat_id=None,
message_id=None,
# inline messages can not be sent on behalf of a bcid
business_connection_id=None,
)
return await self._get_message().edit_reply_markup(
reply_markup=reply_markup,
@@ -442,6 +453,8 @@ class CallbackQuery(TelegramObject):
api_kwargs=api_kwargs,
chat_id=None,
message_id=None,
# inline messages can not be sent on behalf of a bcid
business_connection_id=None,
)
return await self._get_message().edit_media(
media=media,
@@ -513,6 +526,8 @@ class CallbackQuery(TelegramObject):
live_period=live_period,
chat_id=None,
message_id=None,
# inline messages can not be sent on behalf of a bcid
business_connection_id=None,
)
return await self._get_message().edit_live_location(
latitude=latitude,
@@ -576,6 +591,8 @@ class CallbackQuery(TelegramObject):
api_kwargs=api_kwargs,
chat_id=None,
message_id=None,
# inline messages can not be sent on behalf of a bcid
business_connection_id=None,
)
return await self._get_message().stop_live_location(
reply_markup=reply_markup,
@@ -815,6 +832,7 @@ class CallbackQuery(TelegramObject):
protect_content: ODVInput[bool] = DEFAULT_NONE,
message_thread_id: Optional[int] = None,
reply_parameters: Optional["ReplyParameters"] = None,
show_caption_above_media: Optional[bool] = None,
*,
allow_sending_without_reply: ODVInput[bool] = DEFAULT_NONE,
reply_to_message_id: Optional[int] = None,
@@ -861,6 +879,7 @@ class CallbackQuery(TelegramObject):
protect_content=protect_content,
message_thread_id=message_thread_id,
reply_parameters=reply_parameters,
show_caption_above_media=show_caption_above_media,
)
MAX_ANSWER_TEXT_LENGTH: Final[int] = (
+212 -918
View File
File diff suppressed because it is too large Load Diff
+9 -3
View File
@@ -78,7 +78,9 @@ class BackgroundFill(TelegramObject):
self._freeze()
@classmethod
def de_json(cls, data: Optional[JSONDict], bot: "Bot") -> Optional["BackgroundFill"]:
def de_json(
cls, data: Optional[JSONDict], bot: Optional["Bot"] = None
) -> Optional["BackgroundFill"]:
"""See :meth:`telegram.TelegramObject.de_json`."""
data = cls._parse_data(data)
@@ -267,7 +269,9 @@ class BackgroundType(TelegramObject):
self._freeze()
@classmethod
def de_json(cls, data: Optional[JSONDict], bot: "Bot") -> Optional["BackgroundType"]:
def de_json(
cls, data: Optional[JSONDict], bot: Optional["Bot"] = None
) -> Optional["BackgroundType"]:
"""See :meth:`telegram.TelegramObject.de_json`."""
data = cls._parse_data(data)
@@ -528,7 +532,9 @@ class ChatBackground(TelegramObject):
self._freeze()
@classmethod
def de_json(cls, data: Optional[JSONDict], bot: "Bot") -> Optional["ChatBackground"]:
def de_json(
cls, data: Optional[JSONDict], bot: Optional["Bot"] = None
) -> Optional["ChatBackground"]:
"""See :meth:`telegram.TelegramObject.de_json`."""
data = cls._parse_data(data)
+15 -5
View File
@@ -110,7 +110,9 @@ class ChatBoostSource(TelegramObject):
self._freeze()
@classmethod
def de_json(cls, data: Optional[JSONDict], bot: "Bot") -> Optional["ChatBoostSource"]:
def de_json(
cls, data: Optional[JSONDict], bot: Optional["Bot"] = None
) -> Optional["ChatBoostSource"]:
"""See :meth:`telegram.TelegramObject.de_json`."""
data = cls._parse_data(data)
@@ -275,7 +277,9 @@ class ChatBoost(TelegramObject):
self._freeze()
@classmethod
def de_json(cls, data: Optional[JSONDict], bot: "Bot") -> Optional["ChatBoost"]:
def de_json(
cls, data: Optional[JSONDict], bot: Optional["Bot"] = None
) -> Optional["ChatBoost"]:
"""See :meth:`telegram.TelegramObject.de_json`."""
data = cls._parse_data(data)
@@ -325,7 +329,9 @@ class ChatBoostUpdated(TelegramObject):
self._freeze()
@classmethod
def de_json(cls, data: Optional[JSONDict], bot: "Bot") -> Optional["ChatBoostUpdated"]:
def de_json(
cls, data: Optional[JSONDict], bot: Optional["Bot"] = None
) -> Optional["ChatBoostUpdated"]:
"""See :meth:`telegram.TelegramObject.de_json`."""
data = cls._parse_data(data)
@@ -382,7 +388,9 @@ class ChatBoostRemoved(TelegramObject):
self._freeze()
@classmethod
def de_json(cls, data: Optional[JSONDict], bot: "Bot") -> Optional["ChatBoostRemoved"]:
def de_json(
cls, data: Optional[JSONDict], bot: Optional["Bot"] = None
) -> Optional["ChatBoostRemoved"]:
"""See :meth:`telegram.TelegramObject.de_json`."""
data = cls._parse_data(data)
@@ -429,7 +437,9 @@ class UserChatBoosts(TelegramObject):
self._freeze()
@classmethod
def de_json(cls, data: Optional[JSONDict], bot: "Bot") -> Optional["UserChatBoosts"]:
def de_json(
cls, data: Optional[JSONDict], bot: Optional["Bot"] = None
) -> Optional["UserChatBoosts"]:
"""See :meth:`telegram.TelegramObject.de_json`."""
data = cls._parse_data(data)
+434 -51
View File
@@ -19,58 +19,391 @@
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Telegram ChatFullInfo."""
from datetime import datetime
from typing import TYPE_CHECKING, Optional, Sequence
from typing import TYPE_CHECKING, Optional, Sequence, Tuple
from telegram._birthdate import Birthdate
from telegram._chat import Chat
from telegram._chat import Chat, _ChatBase
from telegram._chatlocation import ChatLocation
from telegram._chatpermissions import ChatPermissions
from telegram._files.chatphoto import ChatPhoto
from telegram._reaction import ReactionType
from telegram._utils.argumentparsing import parse_sequence_arg
from telegram._utils.datetime import extract_tzinfo_from_defaults, from_timestamp
from telegram._utils.types import JSONDict
if TYPE_CHECKING:
from telegram import BusinessIntro, BusinessLocation, BusinessOpeningHours, Message
from telegram import Bot, BusinessIntro, BusinessLocation, BusinessOpeningHours, Message
class ChatFullInfo(Chat):
class ChatFullInfo(_ChatBase):
"""
This object contains full information about a chat.
Objects of this class are comparable in terms of equality. Two objects of this class are
considered equal, if their :attr:`~telegram.Chat.id` is equal.
Caution:
This class is a subclass of :class:`telegram.Chat` and inherits all attributes and methods
for backwards compatibility. In the future, this class will *NOT* inherit from
:class:`telegram.Chat`.
.. seealso::
All arguments and attributes can be found in :class:`telegram.Chat`.
.. versionadded:: 21.2
.. versionchanged:: 21.3
Explicit support for all shortcut methods known from :class:`telegram.Chat` on this
object. Previously those were only available because this class inherited from
:class:`telegram.Chat`.
Args:
id (:obj:`int`): Unique identifier for this chat.
type (:obj:`str`): Type of chat, can be either :attr:`PRIVATE`, :attr:`GROUP`,
:attr:`SUPERGROUP` or :attr:`CHANNEL`.
accent_color_id (:obj:`int`, optional): Identifier of the
:class:`accent color <telegram.constants.AccentColor>` for the chat name and
backgrounds of the chat photo, reply header, and link preview. See `accent colors`_
for more details.
.. versionadded:: 20.8
max_reaction_count (:obj:`int`): The maximum number of reactions that can be set on a
message in the chat.
.. versionadded:: 21.2
title (:obj:`str`, optional): Title, for supergroups, channels and group chats.
username (:obj:`str`, optional): Username, for private chats, supergroups and channels if
available.
first_name (:obj:`str`, optional): First name of the other party in a private chat.
last_name (:obj:`str`, optional): Last name of the other party in a private chat.
is_forum (:obj:`bool`, optional): :obj:`True`, if the supergroup chat is a forum
(has topics_ enabled).
.. versionadded:: 20.0
photo (:class:`telegram.ChatPhoto`, optional): Chat photo.
active_usernames (Sequence[:obj:`str`], optional): If set, the list of all `active chat
usernames <https://telegram.org/blog/topics-in-groups-collectible-usernames\
#collectible-usernames>`_; for private chats, supergroups and channels.
.. versionadded:: 20.0
birthdate (:obj:`telegram.Birthdate`, optional): For private chats,
the date of birth of the user.
.. versionadded:: 21.1
business_intro (:class:`telegram.BusinessIntro`, optional): For private chats with
business accounts, the intro of the business.
.. versionadded:: 21.1
business_location (:class:`telegram.BusinessLocation`, optional): For private chats with
business accounts, the location of the business.
.. versionadded:: 21.1
business_opening_hours (:class:`telegram.BusinessOpeningHours`, optional): For private
chats with business accounts, the opening hours of the business.
.. versionadded:: 21.1
personal_chat (:obj:`telegram.Chat`, optional): For private chats, the personal channel of
the user.
.. versionadded:: 21.1
available_reactions (Sequence[:class:`telegram.ReactionType`], optional): List of available
reactions allowed in the chat. If omitted, then all of
:const:`telegram.constants.ReactionEmoji` are allowed.
.. versionadded:: 20.8
background_custom_emoji_id (:obj:`str`, optional): Custom emoji identifier of emoji chosen
by the chat for the reply header and link preview background.
.. versionadded:: 20.8
profile_accent_color_id (:obj:`int`, optional): Identifier of the
:class:`accent color <telegram.constants.ProfileAccentColor>` for the chat's profile
background. See profile `accent colors`_ for more details.
.. versionadded:: 20.8
profile_background_custom_emoji_id (:obj:`str`, optional): Custom emoji identifier of
the emoji chosen by the chat for its profile background.
.. versionadded:: 20.8
emoji_status_custom_emoji_id (:obj:`str`, optional): Custom emoji identifier of emoji
status of the chat or the other party in a private chat.
.. versionadded:: 20.0
emoji_status_expiration_date (:class:`datetime.datetime`, optional): Expiration date of
emoji status of the chat or the other party in a private chat, as a datetime object,
if any.
|datetime_localization|
.. versionadded:: 20.5
bio (:obj:`str`, optional): Bio of the other party in a private 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
has_restricted_voice_and_video_messages (:obj:`bool`, optional): :obj:`True`, if the
privacy settings of the other party restrict sending voice and video note messages
in the private chat.
.. versionadded:: 20.0
join_to_send_messages (:obj:`bool`, optional): :obj:`True`, if users need to join the
supergroup before they can send messages.
.. versionadded:: 20.0
join_by_request (:obj:`bool`, optional): :obj:`True`, if all users directly joining the
supergroup without using an invite link need to be approved by supergroup
administrators.
.. versionadded:: 20.0
description (:obj:`str`, optional): Description, for groups, supergroups and channel chats.
invite_link (:obj:`str`, optional): Primary invite link, for groups, supergroups and
channel.
pinned_message (:class:`telegram.Message`, optional): The most recent pinned message
(by sending date).
permissions (:class:`telegram.ChatPermissions`): Optional. Default chat member permissions,
for groups and supergroups.
slow_mode_delay (:obj:`int`, optional): For supergroups, the minimum allowed delay between
consecutive messages sent by each unprivileged user.
unrestrict_boost_count (:obj:`int`, optional): For supergroups, the minimum number of
boosts that a non-administrator user needs to add in order to ignore slow mode and chat
permissions.
.. versionadded:: 21.0
message_auto_delete_time (:obj:`int`, optional): The time after which all messages sent to
the chat will be automatically deleted; in seconds.
.. versionadded:: 13.4
has_aggressive_anti_spam_enabled (:obj:`bool`, optional): :obj:`True`, if aggressive
anti-spam checks are enabled in the supergroup. The field is only available to chat
administrators.
.. versionadded:: 20.0
has_hidden_members (:obj:`bool`, optional): :obj:`True`, if non-administrators can only
get the list of bots and administrators in the chat.
.. versionadded:: 20.0
has_protected_content (:obj:`bool`, optional): :obj:`True`, if messages from the chat can't
be forwarded to other chats.
.. versionadded:: 13.9
has_visible_history (:obj:`bool`, optional): :obj:`True`, if new chat members will have
access to old messages; available only to chat administrators.
.. versionadded:: 20.8
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.
custom_emoji_sticker_set_name (:obj:`str`, optional): For supergroups, the name of the
group's custom emoji sticker set. Custom emoji from this set can be used by all users
and bots in the group.
.. versionadded:: 21.0
linked_chat_id (:obj:`int`, optional): Unique identifier for the linked chat, i.e. the
discussion group identifier for a channel and vice versa; for supergroups and channel
chats.
location (:class:`telegram.ChatLocation`, optional): For supergroups, the location to which
the supergroup is connected.
can_send_paid_media (:obj:`bool`, optional): :obj:`True`, if paid media messages can be
sent or forwarded to the channel chat. The field is available only for channel chats.
.. versionadded:: 21.4
Attributes:
id (:obj:`int`): Unique identifier for this chat.
type (:obj:`str`): Type of chat, can be either :attr:`PRIVATE`, :attr:`GROUP`,
:attr:`SUPERGROUP` or :attr:`CHANNEL`.
accent_color_id (:obj:`int`): Optional. Identifier of the
:class:`accent color <telegram.constants.AccentColor>` for the chat name and
backgrounds of the chat photo, reply header, and link preview. See `accent colors`_
for more details.
.. versionadded:: 20.8
max_reaction_count (:obj:`int`): The maximum number of reactions that can be set on a
message in the chat.
.. versionadded:: 21.2
title (:obj:`str`, optional): Title, for supergroups, channels and group chats.
username (:obj:`str`, optional): Username, for private chats, supergroups and channels if
available.
first_name (:obj:`str`, optional): First name of the other party in a private chat.
last_name (:obj:`str`, optional): Last name of the other party in a private chat.
is_forum (:obj:`bool`, optional): :obj:`True`, if the supergroup chat is a forum
(has topics_ enabled).
.. versionadded:: 20.0
photo (:class:`telegram.ChatPhoto`): Optional. Chat photo.
active_usernames (Tuple[:obj:`str`]): Optional. If set, the list of all `active chat
usernames <https://telegram.org/blog/topics-in-groups-collectible-usernames\
#collectible-usernames>`_; for private chats, supergroups and channels.
This list is empty if the chat has no active usernames or this chat instance was not
obtained via :meth:`~telegram.Bot.get_chat`.
.. versionadded:: 20.0
birthdate (:obj:`telegram.Birthdate`): Optional. For private chats,
the date of birth of the user.
.. versionadded:: 21.1
business_intro (:class:`telegram.BusinessIntro`): Optional. For private chats with
business accounts, the intro of the business.
.. versionadded:: 21.1
business_location (:class:`telegram.BusinessLocation`): Optional. For private chats with
business accounts, the location of the business.
.. versionadded:: 21.1
business_opening_hours (:class:`telegram.BusinessOpeningHours`): Optional. For private
chats with business accounts, the opening hours of the business.
.. versionadded:: 21.1
personal_chat (:obj:`telegram.Chat`): Optional. For private chats, the personal channel of
the user.
.. versionadded:: 21.1
available_reactions (Tuple[:class:`telegram.ReactionType`]): Optional. List of available
reactions allowed in the chat. If omitted, then all of
:const:`telegram.constants.ReactionEmoji` are allowed.
.. versionadded:: 20.8
background_custom_emoji_id (:obj:`str`): Optional. Custom emoji identifier of emoji chosen
by the chat for the reply header and link preview background.
.. versionadded:: 20.8
profile_accent_color_id (:obj:`int`): Optional. Identifier of the
:class:`accent color <telegram.constants.ProfileAccentColor>` for the chat's profile
background. See profile `accent colors`_ for more details.
.. versionadded:: 20.8
profile_background_custom_emoji_id (:obj:`str`): Optional. Custom emoji identifier of
the emoji chosen by the chat for its profile background.
.. versionadded:: 20.8
emoji_status_custom_emoji_id (:obj:`str`): Optional. Custom emoji identifier of emoji
status of the chat or the other party in a private chat.
.. versionadded:: 20.0
emoji_status_expiration_date (:class:`datetime.datetime`): Optional. Expiration date of
emoji status of the chat or the other party in a private chat, as a datetime object,
if any.
|datetime_localization|
.. versionadded:: 20.5
bio (:obj:`str`): Optional. Bio of the other party in a private 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
has_restricted_voice_and_video_messages (:obj:`bool`): Optional. :obj:`True`, if the
privacy settings of the other party restrict sending voice and video note messages
in the private chat.
.. versionadded:: 20.0
join_to_send_messages (:obj:`bool`): Optional. :obj:`True`, if users need to join
the supergroup before they can send messages.
.. versionadded:: 20.0
join_by_request (:obj:`bool`): Optional. :obj:`True`, if all users directly joining the
supergroup without using an invite link need to be approved by supergroup
administrators.
.. versionadded:: 20.0
description (:obj:`str`): Optional. Description, for groups, supergroups and channel chats.
invite_link (:obj:`str`): Optional. Primary invite link, for groups, supergroups and
channel.
pinned_message (:class:`telegram.Message`): Optional. The most recent pinned message
(by sending date).
permissions (:class:`telegram.ChatPermissions`): Optional. Default chat member permissions,
for groups and supergroups.
slow_mode_delay (:obj:`int`): Optional. For supergroups, the minimum allowed delay between
consecutive messages sent by each unprivileged user.
unrestrict_boost_count (:obj:`int`): Optional. For supergroups, the minimum number of
boosts that a non-administrator user needs to add in order to ignore slow mode and chat
permissions.
.. versionadded:: 21.0
message_auto_delete_time (:obj:`int`): Optional. The time after which all messages sent to
the chat will be automatically deleted; in seconds.
.. versionadded:: 13.4
has_aggressive_anti_spam_enabled (:obj:`bool`): Optional. :obj:`True`, if aggressive
anti-spam checks are enabled in the supergroup. The field is only available to chat
administrators.
.. versionadded:: 20.0
has_hidden_members (:obj:`bool`): Optional. :obj:`True`, if non-administrators can only
get the list of bots and administrators in the chat.
.. versionadded:: 20.0
has_protected_content (:obj:`bool`): Optional. :obj:`True`, if messages from the chat can't
be forwarded to other chats.
.. versionadded:: 13.9
has_visible_history (:obj:`bool`): Optional. :obj:`True`, if new chat members will have
access to old messages; available only to chat administrators.
.. versionadded:: 20.8
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.
custom_emoji_sticker_set_name (:obj:`str`): Optional. For supergroups, the name of the
group's custom emoji sticker set. Custom emoji from this set can be used by all users
and bots in the group.
.. versionadded:: 21.0
linked_chat_id (:obj:`int`): Optional. Unique identifier for the linked chat, i.e. the
discussion group identifier for a channel and vice versa; for supergroups and channel
chats.
location (:class:`telegram.ChatLocation`): Optional. For supergroups, the location to which
the supergroup is connected.
can_send_paid_media (:obj:`bool`): Optional. :obj:`True`, if paid media messages can be
sent or forwarded to the channel chat. The field is available only for channel chats.
.. versionadded:: 21.4
.. _accent colors: https://core.telegram.org/bots/api#accent-colors
.. _topics: https://telegram.org/blog/topics-in-groups-collectible-usernames#topics-in-groups
"""
__slots__ = ("max_reaction_count",)
__slots__ = (
"accent_color_id",
"active_usernames",
"available_reactions",
"background_custom_emoji_id",
"bio",
"birthdate",
"business_intro",
"business_location",
"business_opening_hours",
"can_send_paid_media",
"can_set_sticker_set",
"custom_emoji_sticker_set_name",
"description",
"emoji_status_custom_emoji_id",
"emoji_status_expiration_date",
"has_aggressive_anti_spam_enabled",
"has_hidden_members",
"has_private_forwards",
"has_protected_content",
"has_restricted_voice_and_video_messages",
"has_visible_history",
"invite_link",
"join_by_request",
"join_to_send_messages",
"linked_chat_id",
"location",
"max_reaction_count",
"message_auto_delete_time",
"permissions",
"personal_chat",
"photo",
"pinned_message",
"profile_accent_color_id",
"profile_background_custom_emoji_id",
"slow_mode_delay",
"sticker_set_name",
"unrestrict_boost_count",
)
def __init__(
self,
id: int,
type: str,
accent_color_id: int, # API 7.3 made this argument required
max_reaction_count: int, # NEW arg in api 7.3 and is required
accent_color_id: int,
max_reaction_count: int,
title: Optional[str] = None,
username: Optional[str] = None,
first_name: Optional[str] = None,
@@ -110,6 +443,7 @@ class ChatFullInfo(Chat):
custom_emoji_sticker_set_name: Optional[str] = None,
linked_chat_id: Optional[int] = None,
location: Optional[ChatLocation] = None,
can_send_paid_media: Optional[bool] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
@@ -120,47 +454,96 @@ class ChatFullInfo(Chat):
username=username,
first_name=first_name,
last_name=last_name,
photo=photo,
description=description,
invite_link=invite_link,
pinned_message=pinned_message,
permissions=permissions,
sticker_set_name=sticker_set_name,
can_set_sticker_set=can_set_sticker_set,
slow_mode_delay=slow_mode_delay,
bio=bio,
linked_chat_id=linked_chat_id,
location=location,
message_auto_delete_time=message_auto_delete_time,
has_private_forwards=has_private_forwards,
has_protected_content=has_protected_content,
join_to_send_messages=join_to_send_messages,
join_by_request=join_by_request,
has_restricted_voice_and_video_messages=has_restricted_voice_and_video_messages,
is_forum=is_forum,
active_usernames=active_usernames,
emoji_status_custom_emoji_id=emoji_status_custom_emoji_id,
emoji_status_expiration_date=emoji_status_expiration_date,
has_aggressive_anti_spam_enabled=has_aggressive_anti_spam_enabled,
has_hidden_members=has_hidden_members,
available_reactions=available_reactions,
accent_color_id=accent_color_id,
background_custom_emoji_id=background_custom_emoji_id,
profile_accent_color_id=profile_accent_color_id,
profile_background_custom_emoji_id=profile_background_custom_emoji_id,
has_visible_history=has_visible_history,
unrestrict_boost_count=unrestrict_boost_count,
custom_emoji_sticker_set_name=custom_emoji_sticker_set_name,
birthdate=birthdate,
personal_chat=personal_chat,
business_intro=business_intro,
business_location=business_location,
business_opening_hours=business_opening_hours,
api_kwargs=api_kwargs,
)
# Required and unique to this class-
with self._unfrozen():
self.max_reaction_count: int = max_reaction_count
self.photo: Optional[ChatPhoto] = photo
self.bio: Optional[str] = bio
self.has_private_forwards: Optional[bool] = has_private_forwards
self.description: Optional[str] = description
self.invite_link: Optional[str] = invite_link
self.pinned_message: Optional[Message] = pinned_message
self.permissions: Optional[ChatPermissions] = permissions
self.slow_mode_delay: Optional[int] = slow_mode_delay
self.message_auto_delete_time: Optional[int] = (
int(message_auto_delete_time) if message_auto_delete_time is not None else None
)
self.has_protected_content: Optional[bool] = has_protected_content
self.has_visible_history: Optional[bool] = has_visible_history
self.sticker_set_name: Optional[str] = sticker_set_name
self.can_set_sticker_set: Optional[bool] = can_set_sticker_set
self.linked_chat_id: Optional[int] = linked_chat_id
self.location: Optional[ChatLocation] = location
self.join_to_send_messages: Optional[bool] = join_to_send_messages
self.join_by_request: Optional[bool] = join_by_request
self.has_restricted_voice_and_video_messages: Optional[bool] = (
has_restricted_voice_and_video_messages
)
self.active_usernames: Tuple[str, ...] = parse_sequence_arg(active_usernames)
self.emoji_status_custom_emoji_id: Optional[str] = emoji_status_custom_emoji_id
self.emoji_status_expiration_date: Optional[datetime] = emoji_status_expiration_date
self.has_aggressive_anti_spam_enabled: Optional[bool] = (
has_aggressive_anti_spam_enabled
)
self.has_hidden_members: Optional[bool] = has_hidden_members
self.available_reactions: Optional[Tuple[ReactionType, ...]] = parse_sequence_arg(
available_reactions
)
self.accent_color_id: Optional[int] = accent_color_id
self.background_custom_emoji_id: Optional[str] = background_custom_emoji_id
self.profile_accent_color_id: Optional[int] = profile_accent_color_id
self.profile_background_custom_emoji_id: Optional[str] = (
profile_background_custom_emoji_id
)
self.unrestrict_boost_count: Optional[int] = unrestrict_boost_count
self.custom_emoji_sticker_set_name: Optional[str] = custom_emoji_sticker_set_name
self.birthdate: Optional[Birthdate] = birthdate
self.personal_chat: Optional[Chat] = personal_chat
self.business_intro: Optional[BusinessIntro] = business_intro
self.business_location: Optional[BusinessLocation] = business_location
self.business_opening_hours: Optional[BusinessOpeningHours] = business_opening_hours
self.can_send_paid_media: Optional[bool] = can_send_paid_media
self._freeze()
@classmethod
def de_json(
cls, data: Optional[JSONDict], bot: Optional["Bot"] = None
) -> Optional["ChatFullInfo"]:
"""See :meth:`telegram.TelegramObject.de_json`."""
data = cls._parse_data(data)
if not data:
return None
# Get the local timezone from the bot if it has defaults
loc_tzinfo = extract_tzinfo_from_defaults(bot)
data["emoji_status_expiration_date"] = from_timestamp(
data.get("emoji_status_expiration_date"), tzinfo=loc_tzinfo
)
data["photo"] = ChatPhoto.de_json(data.get("photo"), bot)
from telegram import ( # pylint: disable=import-outside-toplevel
BusinessIntro,
BusinessLocation,
BusinessOpeningHours,
Message,
)
data["pinned_message"] = Message.de_json(data.get("pinned_message"), bot)
data["permissions"] = ChatPermissions.de_json(data.get("permissions"), bot)
data["location"] = ChatLocation.de_json(data.get("location"), bot)
data["available_reactions"] = ReactionType.de_list(data.get("available_reactions"), bot)
data["birthdate"] = Birthdate.de_json(data.get("birthdate"), bot)
data["personal_chat"] = Chat.de_json(data.get("personal_chat"), bot)
data["business_intro"] = BusinessIntro.de_json(data.get("business_intro"), bot)
data["business_location"] = BusinessLocation.de_json(data.get("business_location"), bot)
data["business_opening_hours"] = BusinessOpeningHours.de_json(
data.get("business_opening_hours"), bot
)
return super().de_json(data=data, bot=bot)
+3 -1
View File
@@ -151,7 +151,9 @@ class ChatInviteLink(TelegramObject):
self._freeze()
@classmethod
def de_json(cls, data: Optional[JSONDict], bot: "Bot") -> Optional["ChatInviteLink"]:
def de_json(
cls, data: Optional[JSONDict], bot: Optional["Bot"] = None
) -> Optional["ChatInviteLink"]:
"""See :meth:`telegram.TelegramObject.de_json`."""
data = cls._parse_data(data)
+3 -1
View File
@@ -129,7 +129,9 @@ class ChatJoinRequest(TelegramObject):
self._freeze()
@classmethod
def de_json(cls, data: Optional[JSONDict], bot: "Bot") -> Optional["ChatJoinRequest"]:
def de_json(
cls, data: Optional[JSONDict], bot: Optional["Bot"] = None
) -> Optional["ChatJoinRequest"]:
"""See :meth:`telegram.TelegramObject.de_json`."""
data = cls._parse_data(data)
+3 -1
View File
@@ -68,7 +68,9 @@ class ChatLocation(TelegramObject):
self._freeze()
@classmethod
def de_json(cls, data: Optional[JSONDict], bot: "Bot") -> Optional["ChatLocation"]:
def de_json(
cls, data: Optional[JSONDict], bot: Optional["Bot"] = None
) -> Optional["ChatLocation"]:
"""See :meth:`telegram.TelegramObject.de_json`."""
data = cls._parse_data(data)
+3 -1
View File
@@ -104,7 +104,9 @@ class ChatMember(TelegramObject):
self._freeze()
@classmethod
def de_json(cls, data: Optional[JSONDict], bot: "Bot") -> Optional["ChatMember"]:
def de_json(
cls, data: Optional[JSONDict], bot: Optional["Bot"] = None
) -> Optional["ChatMember"]:
"""See :meth:`telegram.TelegramObject.de_json`."""
data = cls._parse_data(data)
+3 -1
View File
@@ -141,7 +141,9 @@ class ChatMemberUpdated(TelegramObject):
self._freeze()
@classmethod
def de_json(cls, data: Optional[JSONDict], bot: "Bot") -> Optional["ChatMemberUpdated"]:
def de_json(
cls, data: Optional[JSONDict], bot: Optional["Bot"] = None
) -> Optional["ChatMemberUpdated"]:
"""See :meth:`telegram.TelegramObject.de_json`."""
data = cls._parse_data(data)
+3 -1
View File
@@ -231,7 +231,9 @@ class ChatPermissions(TelegramObject):
return cls(*(14 * (False,)))
@classmethod
def de_json(cls, data: Optional[JSONDict], bot: "Bot") -> Optional["ChatPermissions"]:
def de_json(
cls, data: Optional[JSONDict], bot: Optional["Bot"] = None
) -> Optional["ChatPermissions"]:
"""See :meth:`telegram.TelegramObject.de_json`."""
data = cls._parse_data(data)
+3 -1
View File
@@ -92,7 +92,9 @@ class ChosenInlineResult(TelegramObject):
self._freeze()
@classmethod
def de_json(cls, data: Optional[JSONDict], bot: "Bot") -> Optional["ChosenInlineResult"]:
def de_json(
cls, data: Optional[JSONDict], bot: Optional["Bot"] = None
) -> Optional["ChosenInlineResult"]:
"""See :meth:`telegram.TelegramObject.de_json`."""
data = cls._parse_data(data)
+3 -3
View File
@@ -44,7 +44,7 @@ class _BaseThumbedMedium(_BaseMedium):
is supposed to be the same over time and for different bots.
Can't be used to download or reuse the file.
file_size (:obj:`int`, optional): File size.
thumbnail (:class:`telegram.PhotoSize`, optional): Thumbnail as defined by sender.
thumbnail (:class:`telegram.PhotoSize`, optional): Thumbnail as defined by the sender.
.. versionadded:: 20.2
@@ -54,7 +54,7 @@ class _BaseThumbedMedium(_BaseMedium):
is supposed to be the same over time and for different bots.
Can't be used to download or reuse the file.
file_size (:obj:`int`): Optional. File size.
thumbnail (:class:`telegram.PhotoSize`): Optional. Thumbnail as defined by sender.
thumbnail (:class:`telegram.PhotoSize`): Optional. Thumbnail as defined by the sender.
.. versionadded:: 20.2
@@ -82,7 +82,7 @@ class _BaseThumbedMedium(_BaseMedium):
@classmethod
def de_json(
cls: Type[ThumbedMT_co], data: Optional[JSONDict], bot: "Bot"
cls: Type[ThumbedMT_co], data: Optional[JSONDict], bot: Optional["Bot"] = None
) -> Optional[ThumbedMT_co]:
"""See :meth:`telegram.TelegramObject.de_json`."""
data = cls._parse_data(data)
+10 -10
View File
@@ -39,11 +39,11 @@ class Animation(_BaseThumbedMedium):
file_unique_id (:obj:`str`): Unique identifier for this file, which
is supposed to be the same over time and for different bots.
Can't be used to download or reuse the file.
width (:obj:`int`): Video width as defined by sender.
height (:obj:`int`): Video height as defined by sender.
duration (:obj:`int`): Duration of the video in seconds as defined by sender.
file_name (:obj:`str`, optional): Original animation filename as defined by sender.
mime_type (:obj:`str`, optional): MIME type of the file as defined by sender.
width (:obj:`int`): Video width as defined by the sender.
height (:obj:`int`): Video height as defined by the sender.
duration (:obj:`int`): Duration of the video in seconds as defined by the sender.
file_name (:obj:`str`, optional): Original animation filename as defined by the sender.
mime_type (:obj:`str`, optional): MIME type of the file as defined by the sender.
file_size (:obj:`int`, optional): File size in bytes.
thumbnail (:class:`telegram.PhotoSize`, optional): Animation thumbnail as defined by
sender.
@@ -56,11 +56,11 @@ class Animation(_BaseThumbedMedium):
file_unique_id (:obj:`str`): Unique identifier for this file, which
is supposed to be the same over time and for different bots.
Can't be used to download or reuse the file.
width (:obj:`int`): Video width as defined by sender.
height (:obj:`int`): Video height as defined by sender.
duration (:obj:`int`): Duration of the video in seconds as defined by sender.
file_name (:obj:`str`): Optional. Original animation filename as defined by sender.
mime_type (:obj:`str`): Optional. MIME type of the file as defined by sender.
width (:obj:`int`): Video width as defined by the sender.
height (:obj:`int`): Video height as defined by the sender.
duration (:obj:`int`): Duration of the video in seconds as defined by the sender.
file_name (:obj:`str`): Optional. Original animation filename as defined by the sender.
mime_type (:obj:`str`): Optional. MIME type of the file as defined by the sender.
file_size (:obj:`int`): Optional. File size in bytes.
thumbnail (:class:`telegram.PhotoSize`): Optional. Animation thumbnail as defined by
sender.
+12 -12
View File
@@ -39,12 +39,12 @@ class Audio(_BaseThumbedMedium):
or reuse the file.
file_unique_id (:obj:`str`): Unique identifier for this file, which is supposed to be
the same over time and for different bots. Can't be used to download or reuse the file.
duration (:obj:`int`): Duration of the audio in seconds as defined by sender.
performer (:obj:`str`, optional): Performer of the audio as defined by sender or by audio
tags.
title (:obj:`str`, optional): Title of the audio as defined by sender or by audio tags.
file_name (:obj:`str`, optional): Original filename as defined by sender.
mime_type (:obj:`str`, optional): MIME type of the file as defined by sender.
duration (:obj:`int`): Duration of the audio in seconds as defined by the sender.
performer (:obj:`str`, optional): Performer of the audio as defined by the sender or by
audio tags.
title (:obj:`str`, optional): Title of the audio as defined by the sender or by audio tags.
file_name (:obj:`str`, optional): Original filename as defined by the sender.
mime_type (:obj:`str`, optional): MIME type of the file as defined by the sender.
file_size (:obj:`int`, optional): File size in bytes.
thumbnail (:class:`telegram.PhotoSize`, optional): Thumbnail of the album cover to
which the music file belongs.
@@ -56,12 +56,12 @@ class Audio(_BaseThumbedMedium):
or reuse the file.
file_unique_id (:obj:`str`): Unique identifier for this file, which is supposed to be
the same over time and for different bots. Can't be used to download or reuse the file.
duration (:obj:`int`): Duration of the audio in seconds as defined by sender.
performer (:obj:`str`): Optional. Performer of the audio as defined by sender or by audio
tags.
title (:obj:`str`): Optional. Title of the audio as defined by sender or by audio tags.
file_name (:obj:`str`): Optional. Original filename as defined by sender.
mime_type (:obj:`str`): Optional. MIME type of the file as defined by sender.
duration (:obj:`int`): Duration of the audio in seconds as defined by the sender.
performer (:obj:`str`): Optional. Performer of the audio as defined by the sender or by
audio tags.
title (:obj:`str`): Optional. Title of the audio as defined by the sender or by audio tags.
file_name (:obj:`str`): Optional. Original filename as defined by the sender.
mime_type (:obj:`str`): Optional. MIME type of the file as defined by the sender.
file_size (:obj:`int`): Optional. File size in bytes.
thumbnail (:class:`telegram.PhotoSize`): Optional. Thumbnail of the album cover to
which the music file belongs.
+8 -6
View File
@@ -39,10 +39,11 @@ class Document(_BaseThumbedMedium):
or reuse the file.
file_unique_id (:obj:`str`): Unique identifier for this file, which is supposed to be
the same over time and for different bots. Can't be used to download or reuse the file.
file_name (:obj:`str`, optional): Original filename as defined by sender.
mime_type (:obj:`str`, optional): MIME type of the file as defined by sender.
file_name (:obj:`str`, optional): Original filename as defined by the sender.
mime_type (:obj:`str`, optional): MIME type of the file as defined by the sender.
file_size (:obj:`int`, optional): File size in bytes.
thumbnail (:class:`telegram.PhotoSize`, optional): Document thumbnail as defined by sender.
thumbnail (:class:`telegram.PhotoSize`, optional): Document thumbnail as defined by the
sender.
.. versionadded:: 20.2
@@ -51,10 +52,11 @@ class Document(_BaseThumbedMedium):
or reuse the file.
file_unique_id (:obj:`str`): Unique identifier for this file, which is supposed to be
the same over time and for different bots. Can't be used to download or reuse the file.
file_name (:obj:`str`): Optional. Original filename as defined by sender.
mime_type (:obj:`str`): Optional. MIME type of the file as defined by sender.
file_name (:obj:`str`): Optional. Original filename as defined by the sender.
mime_type (:obj:`str`): Optional. MIME type of the file as defined by the sender.
file_size (:obj:`int`): Optional. File size in bytes.
thumbnail (:class:`telegram.PhotoSize`): Optional. Document thumbnail as defined by sender.
thumbnail (:class:`telegram.PhotoSize`): Optional. Document thumbnail as defined by the
sender.
.. versionadded:: 20.2
+196 -12
View File
@@ -17,7 +17,7 @@
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""Base class for Telegram InputMedia Objects."""
from typing import Optional, Sequence, Tuple, Union
from typing import Final, Optional, Sequence, Tuple, Union
from telegram import constants
from telegram._files.animation import Animation
@@ -115,13 +115,162 @@ class InputMedia(TelegramObject):
)
class InputPaidMedia(TelegramObject):
"""
Base class for Telegram InputPaidMedia Objects. Currently, it can be one of:
* :class:`telegram.InputMediaPhoto`
* :class:`telegram.InputMediaVideo`
.. seealso:: :wiki:`Working with Files and Media <Working-with-Files-and-Media>`
.. versionadded:: 21.4
Args:
type (:obj:`str`): Type of media that the instance represents.
media (:obj:`str` | :term:`file object` | :obj:`bytes` | :class:`pathlib.Path` | \
:class:`telegram.PhotoSize` | :class:`telegram.Video`): File to send. |fileinputnopath|
Lastly you can pass an existing telegram media object of the corresponding type
to send.
Attributes:
type (:obj:`str`): Type of the input media.
media (:obj:`str` | :class:`telegram.InputFile`): Media to send.
"""
PHOTO: Final[str] = constants.InputPaidMediaType.PHOTO
""":const:`telegram.constants.InputPaidMediaType.PHOTO`"""
VIDEO: Final[str] = constants.InputPaidMediaType.VIDEO
""":const:`telegram.constants.InputPaidMediaType.VIDEO`"""
__slots__ = ("media", "type")
def __init__(
self,
type: str, # pylint: disable=redefined-builtin
media: Union[str, InputFile, PhotoSize, Video],
*,
api_kwargs: Optional[JSONDict] = None,
):
super().__init__(api_kwargs=api_kwargs)
self.type: str = enum.get_member(constants.InputPaidMediaType, type, type)
self.media: Union[str, InputFile, PhotoSize, Video] = media
self._freeze()
class InputPaidMediaPhoto(InputPaidMedia):
"""The paid media to send is a photo.
.. seealso:: :wiki:`Working with Files and Media <Working-with-Files-and-Media>`
.. versionadded:: 21.4
Args:
media (:obj:`str` | :term:`file object` | :obj:`bytes` | :class:`pathlib.Path` | \
:class:`telegram.PhotoSize`): File to send. |fileinputnopath|
Lastly you can pass an existing :class:`telegram.PhotoSize` object to send.
Attributes:
type (:obj:`str`): Type of the media, always
:tg-const:`telegram.constants.InputPaidMediaType.PHOTO`.
media (:obj:`str` | :class:`telegram.InputFile`): Photo to send.
"""
__slots__ = ()
def __init__(
self,
media: Union[FileInput, PhotoSize],
*,
api_kwargs: Optional[JSONDict] = None,
):
media = parse_file_input(media, PhotoSize, attach=True, local_mode=True)
super().__init__(type=InputPaidMedia.PHOTO, media=media, api_kwargs=api_kwargs)
self._freeze()
class InputPaidMediaVideo(InputPaidMedia):
"""
The paid media to send is a video.
.. seealso:: :wiki:`Working with Files and Media <Working-with-Files-and-Media>`
.. versionadded:: 21.4
Note:
* When using a :class:`telegram.Video` for the :attr:`media` attribute, it will take the
width, height and duration from that video, unless otherwise specified with the optional
arguments.
* :paramref:`thumbnail` will be ignored for small video files, for which Telegram can
easily generate thumbnails. However, this behaviour is undocumented and might be
changed by Telegram.
Args:
media (:obj:`str` | :term:`file object` | :obj:`bytes` | :class:`pathlib.Path` | \
:class:`telegram.Video`): File to send. |fileinputnopath|
Lastly you can pass an existing :class:`telegram.Video` object to send.
thumbnail (:term:`file object` | :obj:`bytes` | :class:`pathlib.Path` | :obj:`str`, \
optional): |thumbdocstringnopath|
width (:obj:`int`, optional): Video width.
height (:obj:`int`, optional): Video height.
duration (:obj:`int`, optional): Video duration in seconds.
supports_streaming (:obj:`bool`, optional): Pass :obj:`True`, if the uploaded video is
suitable for streaming.
Attributes:
type (:obj:`str`): Type of the media, always
:tg-const:`telegram.constants.InputPaidMediaType.VIDEO`.
media (:obj:`str` | :class:`telegram.InputFile`): Video to send.
thumbnail (:class:`telegram.InputFile`): Optional. |thumbdocstringbase|
width (:obj:`int`): Optional. Video width.
height (:obj:`int`): Optional. Video height.
duration (:obj:`int`): Optional. Video duration in seconds.
supports_streaming (:obj:`bool`): Optional. :obj:`True`, if the uploaded video is
suitable for streaming.
"""
__slots__ = ("duration", "height", "supports_streaming", "thumbnail", "width")
def __init__(
self,
media: Union[FileInput, Video],
thumbnail: Optional[FileInput] = None,
width: Optional[int] = None,
height: Optional[int] = None,
duration: Optional[int] = None,
supports_streaming: Optional[bool] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
if isinstance(media, Video):
width = width if width is not None else media.width
height = height if height is not None else media.height
duration = duration if duration is not None else media.duration
media = media.file_id
else:
# We use local_mode=True because we don't have access to the actual setting and want
# things to work in local mode.
media = parse_file_input(media, attach=True, local_mode=True)
super().__init__(type=InputPaidMedia.VIDEO, media=media, api_kwargs=api_kwargs)
with self._unfrozen():
self.thumbnail: Optional[Union[str, InputFile]] = InputMedia._parse_thumbnail_input(
thumbnail
)
self.width: Optional[int] = width
self.height: Optional[int] = height
self.duration: Optional[int] = duration
self.supports_streaming: Optional[bool] = supports_streaming
class InputMediaAnimation(InputMedia):
"""Represents an animation file (GIF or H.264/MPEG-4 AVC video without sound) to be sent.
Note:
When using a :class:`telegram.Animation` for the :attr:`media` attribute, it will take the
width, height and duration from that video, unless otherwise specified with the optional
arguments.
width, height and duration from that animation, unless otherwise specified with the
optional arguments.
.. seealso:: :wiki:`Working with Files and Media <Working-with-Files-and-Media>`
@@ -160,6 +309,9 @@ class InputMediaAnimation(InputMedia):
optional): |thumbdocstringnopath|
.. versionadded:: 20.2
show_caption_above_media (:obj:`bool`, optional): Pass |show_cap_above_med|
.. versionadded:: 21.3
Attributes:
type (:obj:`str`): :tg-const:`telegram.constants.InputMediaType.ANIMATION`.
@@ -184,9 +336,19 @@ class InputMediaAnimation(InputMedia):
thumbnail (:class:`telegram.InputFile`): Optional. |thumbdocstringbase|
.. versionadded:: 20.2
show_caption_above_media (:obj:`bool`): Optional. |show_cap_above_med|
.. versionadded:: 21.3
"""
__slots__ = ("duration", "has_spoiler", "height", "thumbnail", "width")
__slots__ = (
"duration",
"has_spoiler",
"height",
"show_caption_above_media",
"thumbnail",
"width",
)
def __init__(
self,
@@ -200,6 +362,7 @@ class InputMediaAnimation(InputMedia):
filename: Optional[str] = None,
has_spoiler: Optional[bool] = None,
thumbnail: Optional[FileInput] = None,
show_caption_above_media: Optional[bool] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
@@ -229,6 +392,7 @@ class InputMediaAnimation(InputMedia):
self.height: Optional[int] = height
self.duration: Optional[int] = duration
self.has_spoiler: Optional[bool] = has_spoiler
self.show_caption_above_media: Optional[bool] = show_caption_above_media
class InputMediaPhoto(InputMedia):
@@ -260,6 +424,9 @@ class InputMediaPhoto(InputMedia):
with a spoiler animation.
.. versionadded:: 20.0
show_caption_above_media (:obj:`bool`, optional): Pass |show_cap_above_med|
.. versionadded:: 21.3
Attributes:
type (:obj:`str`): :tg-const:`telegram.constants.InputMediaType.PHOTO`.
@@ -278,9 +445,15 @@ class InputMediaPhoto(InputMedia):
spoiler animation.
.. versionadded:: 20.0
show_caption_above_media (:obj:`bool`): Optional. |show_cap_above_med|
.. versionadded:: 21.3
"""
__slots__ = ("has_spoiler",)
__slots__ = (
"has_spoiler",
"show_caption_above_media",
)
def __init__(
self,
@@ -290,6 +463,7 @@ class InputMediaPhoto(InputMedia):
caption_entities: Optional[Sequence[MessageEntity]] = None,
filename: Optional[str] = None,
has_spoiler: Optional[bool] = None,
show_caption_above_media: Optional[bool] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
@@ -307,6 +481,7 @@ class InputMediaPhoto(InputMedia):
with self._unfrozen():
self.has_spoiler: Optional[bool] = has_spoiler
self.show_caption_above_media: Optional[bool] = show_caption_above_media
class InputMediaVideo(InputMedia):
@@ -359,6 +534,9 @@ class InputMediaVideo(InputMedia):
optional): |thumbdocstringnopath|
.. versionadded:: 20.2
show_caption_above_media (:obj:`bool`, optional): Pass |show_cap_above_med|
.. versionadded:: 21.3
Attributes:
type (:obj:`str`): :tg-const:`telegram.constants.InputMediaType.VIDEO`.
@@ -385,12 +563,16 @@ class InputMediaVideo(InputMedia):
thumbnail (:class:`telegram.InputFile`): Optional. |thumbdocstringbase|
.. versionadded:: 20.2
show_caption_above_media (:obj:`bool`): Optional. |show_cap_above_med|
.. versionadded:: 21.3
"""
__slots__ = (
"duration",
"has_spoiler",
"height",
"show_caption_above_media",
"supports_streaming",
"thumbnail",
"width",
@@ -409,6 +591,7 @@ class InputMediaVideo(InputMedia):
filename: Optional[str] = None,
has_spoiler: Optional[bool] = None,
thumbnail: Optional[FileInput] = None,
show_caption_above_media: Optional[bool] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
@@ -439,6 +622,7 @@ class InputMediaVideo(InputMedia):
)
self.supports_streaming: Optional[bool] = supports_streaming
self.has_spoiler: Optional[bool] = has_spoiler
self.show_caption_above_media: Optional[bool] = show_caption_above_media
class InputMediaAudio(InputMedia):
@@ -475,10 +659,10 @@ class InputMediaAudio(InputMedia):
.. versionchanged:: 20.0
|sequenceclassargs|
duration (:obj:`int`, optional): Duration of the audio in seconds as defined by sender.
performer (:obj:`str`, optional): Performer of the audio as defined by sender or by audio
tags.
title (:obj:`str`, optional): Title of the audio as defined by sender or by audio tags.
duration (:obj:`int`, optional): Duration of the audio in seconds as defined by the sender.
performer (:obj:`str`, optional): Performer of the audio as defined by the sender or by
audio tags.
title (:obj:`str`, optional): Title of the audio as defined by the sender or by audio tags.
thumbnail (:term:`file object` | :obj:`bytes` | :class:`pathlib.Path` | :obj:`str`, \
optional): |thumbdocstringnopath|
@@ -498,9 +682,9 @@ class InputMediaAudio(InputMedia):
* |tupleclassattrs|
* |alwaystuple|
duration (:obj:`int`): Optional. Duration of the audio in seconds.
performer (:obj:`str`): Optional. Performer of the audio as defined by sender or by audio
tags.
title (:obj:`str`): Optional. Title of the audio as defined by sender or by audio tags.
performer (:obj:`str`): Optional. Performer of the audio as defined by the sender or by
audio tags.
title (:obj:`str`): Optional. Title of the audio as defined by the sender or by audio tags.
thumbnail (:class:`telegram.InputFile`): Optional. |thumbdocstringbase|
.. versionadded:: 20.2
+4 -4
View File
@@ -32,8 +32,8 @@ class Location(TelegramObject):
considered equal, if their :attr:`longitude` and :attr:`latitude` are equal.
Args:
longitude (:obj:`float`): Longitude as defined by sender.
latitude (:obj:`float`): Latitude as defined by sender.
longitude (:obj:`float`): Longitude as defined by the sender.
latitude (:obj:`float`): Latitude as defined by the sender.
horizontal_accuracy (:obj:`float`, optional): The radius of uncertainty for the location,
measured in meters; 0-:tg-const:`telegram.Location.HORIZONTAL_ACCURACY`.
live_period (:obj:`int`, optional): Time relative to the message sending date, during which
@@ -45,8 +45,8 @@ class Location(TelegramObject):
approaching another chat member, in meters. For sent live locations only.
Attributes:
longitude (:obj:`float`): Longitude as defined by sender.
latitude (:obj:`float`): Latitude as defined by sender.
longitude (:obj:`float`): Longitude as defined by the sender.
latitude (:obj:`float`): Latitude as defined by the sender.
horizontal_accuracy (:obj:`float`): Optional. The radius of uncertainty for the location,
measured in meters; 0-:tg-const:`telegram.Location.HORIZONTAL_ACCURACY`.
live_period (:obj:`int`): Optional. Time relative to the message sending date, during which
+4 -2
View File
@@ -193,7 +193,7 @@ class Sticker(_BaseThumbedMedium):
""":const:`telegram.constants.StickerType.CUSTOM_EMOJI`"""
@classmethod
def de_json(cls, data: Optional[JSONDict], bot: "Bot") -> Optional["Sticker"]:
def de_json(cls, data: Optional[JSONDict], bot: Optional["Bot"] = None) -> Optional["Sticker"]:
"""See :meth:`telegram.TelegramObject.de_json`."""
data = cls._parse_data(data)
@@ -305,7 +305,9 @@ class StickerSet(TelegramObject):
self._freeze()
@classmethod
def de_json(cls, data: Optional[JSONDict], bot: "Bot") -> Optional["StickerSet"]:
def de_json(
cls, data: Optional[JSONDict], bot: Optional["Bot"] = None
) -> Optional["StickerSet"]:
"""See :meth:`telegram.TelegramObject.de_json`."""
if not data:
return None
+1 -1
View File
@@ -103,7 +103,7 @@ class Venue(TelegramObject):
self._freeze()
@classmethod
def de_json(cls, data: Optional[JSONDict], bot: "Bot") -> Optional["Venue"]:
def de_json(cls, data: Optional[JSONDict], bot: Optional["Bot"] = None) -> Optional["Venue"]:
"""See :meth:`telegram.TelegramObject.de_json`."""
data = cls._parse_data(data)
+10 -10
View File
@@ -39,11 +39,11 @@ class Video(_BaseThumbedMedium):
file_unique_id (:obj:`str`): Unique identifier for this file, which
is supposed to be the same over time and for different bots.
Can't be used to download or reuse the file.
width (:obj:`int`): Video width as defined by sender.
height (:obj:`int`): Video height as defined by sender.
duration (:obj:`int`): Duration of the video in seconds as defined by sender.
file_name (:obj:`str`, optional): Original filename as defined by sender.
mime_type (:obj:`str`, optional): MIME type of a file as defined by sender.
width (:obj:`int`): Video width as defined by the sender.
height (:obj:`int`): Video height as defined by the sender.
duration (:obj:`int`): Duration of the video in seconds as defined by the sender.
file_name (:obj:`str`, optional): Original filename as defined by the sender.
mime_type (:obj:`str`, optional): MIME type of a file as defined by the sender.
file_size (:obj:`int`, optional): File size in bytes.
thumbnail (:class:`telegram.PhotoSize`, optional): Video thumbnail.
@@ -55,11 +55,11 @@ class Video(_BaseThumbedMedium):
file_unique_id (:obj:`str`): Unique identifier for this file, which
is supposed to be the same over time and for different bots.
Can't be used to download or reuse the file.
width (:obj:`int`): Video width as defined by sender.
height (:obj:`int`): Video height as defined by sender.
duration (:obj:`int`): Duration of the video in seconds as defined by sender.
file_name (:obj:`str`): Optional. Original filename as defined by sender.
mime_type (:obj:`str`): Optional. MIME type of a file as defined by sender.
width (:obj:`int`): Video width as defined by the sender.
height (:obj:`int`): Video height as defined by the sender.
duration (:obj:`int`): Duration of the video in seconds as defined by the sender.
file_name (:obj:`str`): Optional. Original filename as defined by the sender.
mime_type (:obj:`str`): Optional. MIME type of a file as defined by the sender.
file_size (:obj:`int`): Optional. File size in bytes.
thumbnail (:class:`telegram.PhotoSize`): Optional. Video thumbnail.
+2 -2
View File
@@ -42,7 +42,7 @@ class VideoNote(_BaseThumbedMedium):
Can't be used to download or reuse the file.
length (:obj:`int`): Video width and height (diameter of the video message) as defined
by sender.
duration (:obj:`int`): Duration of the video in seconds as defined by sender.
duration (:obj:`int`): Duration of the video in seconds as defined by the sender.
file_size (:obj:`int`, optional): File size in bytes.
thumbnail (:class:`telegram.PhotoSize`, optional): Video thumbnail.
@@ -56,7 +56,7 @@ class VideoNote(_BaseThumbedMedium):
Can't be used to download or reuse the file.
length (:obj:`int`): Video width and height (diameter of the video message) as defined
by sender.
duration (:obj:`int`): Duration of the video in seconds as defined by sender.
duration (:obj:`int`): Duration of the video in seconds as defined by the sender.
file_size (:obj:`int`): Optional. File size in bytes.
thumbnail (:class:`telegram.PhotoSize`): Optional. Video thumbnail.
+4 -4
View File
@@ -35,8 +35,8 @@ class Voice(_BaseMedium):
file_unique_id (:obj:`str`): Unique identifier for this file, which
is supposed to be the same over time and for different bots.
Can't be used to download or reuse the file.
duration (:obj:`int`): Duration of the audio in seconds as defined by sender.
mime_type (:obj:`str`, optional): MIME type of the file as defined by sender.
duration (:obj:`int`): Duration of the audio in seconds as defined by the sender.
mime_type (:obj:`str`, optional): MIME type of the file as defined by the sender.
file_size (:obj:`int`, optional): File size in bytes.
Attributes:
@@ -45,8 +45,8 @@ class Voice(_BaseMedium):
file_unique_id (:obj:`str`): Unique identifier for this file, which
is supposed to be the same over time and for different bots.
Can't be used to download or reuse the file.
duration (:obj:`int`): Duration of the audio in seconds as defined by sender.
mime_type (:obj:`str`): Optional. MIME type of the file as defined by sender.
duration (:obj:`int`): Duration of the audio in seconds as defined by the sender.
mime_type (:obj:`str`): Optional. MIME type of the file as defined by the sender.
file_size (:obj:`int`): Optional. File size in bytes.
"""
+1 -1
View File
@@ -122,7 +122,7 @@ class Game(TelegramObject):
self._freeze()
@classmethod
def de_json(cls, data: Optional[JSONDict], bot: "Bot") -> Optional["Game"]:
def de_json(cls, data: Optional[JSONDict], bot: Optional["Bot"] = None) -> Optional["Game"]:
"""See :meth:`telegram.TelegramObject.de_json`."""
data = cls._parse_data(data)
+3 -1
View File
@@ -61,7 +61,9 @@ class GameHighScore(TelegramObject):
self._freeze()
@classmethod
def de_json(cls, data: Optional[JSONDict], bot: "Bot") -> Optional["GameHighScore"]:
def de_json(
cls, data: Optional[JSONDict], bot: Optional["Bot"] = None
) -> Optional["GameHighScore"]:
"""See :meth:`telegram.TelegramObject.de_json`."""
data = cls._parse_data(data)
+10 -4
View File
@@ -123,7 +123,9 @@ class Giveaway(TelegramObject):
self._freeze()
@classmethod
def de_json(cls, data: Optional[JSONDict], bot: "Bot") -> Optional["Giveaway"]:
def de_json(
cls, data: Optional[JSONDict], bot: Optional["Bot"] = None
) -> Optional["Giveaway"]:
"""See :obj:`telegram.TelegramObject.de_json`."""
data = cls._parse_data(data)
@@ -257,7 +259,9 @@ class GiveawayWinners(TelegramObject):
self._freeze()
@classmethod
def de_json(cls, data: Optional[JSONDict], bot: "Bot") -> Optional["GiveawayWinners"]:
def de_json(
cls, data: Optional[JSONDict], bot: Optional["Bot"] = None
) -> Optional["GiveawayWinners"]:
"""See :obj:`telegram.TelegramObject.de_json`."""
data = cls._parse_data(data)
@@ -313,7 +317,7 @@ class GiveawayCompleted(TelegramObject):
self.winner_count: int = winner_count
self.unclaimed_prize_count: Optional[int] = unclaimed_prize_count
self.giveaway_message: Optional["Message"] = giveaway_message
self.giveaway_message: Optional[Message] = giveaway_message
self._id_attrs = (
self.winner_count,
@@ -323,7 +327,9 @@ class GiveawayCompleted(TelegramObject):
self._freeze()
@classmethod
def de_json(cls, data: Optional[JSONDict], bot: "Bot") -> Optional["GiveawayCompleted"]:
def de_json(
cls, data: Optional[JSONDict], bot: Optional["Bot"] = None
) -> Optional["GiveawayCompleted"]:
"""See :obj:`telegram.TelegramObject.de_json`."""
data = cls._parse_data(data)
+42 -23
View File
@@ -41,11 +41,12 @@ class InlineKeyboardButton(TelegramObject):
:attr:`web_app` and :attr:`pay` are equal.
Note:
* You must use exactly one of the optional fields. Mind that :attr:`callback_game` is not
* Exactly one of the optional fields must be used to specify type of the button.
* Mind that :attr:`callback_game` is not
working as expected. Putting a game short name in it might, but is not guaranteed to
work.
* If your bot allows for arbitrary callback data, in keyboards returned in a response
from telegram, :attr:`callback_data` maybe be an instance of
from telegram, :attr:`callback_data` may be an instance of
:class:`telegram.ext.InvalidCallbackData`. This will be the case, if the data
associated with the button was already deleted.
@@ -88,10 +89,9 @@ class InlineKeyboardButton(TelegramObject):
Caution:
Only ``HTTPS`` links are allowed after Bot API 6.1.
callback_data (:obj:`str` | :obj:`object`, optional): Data to be sent in a callback query
to the bot when button is pressed, UTF-8
to the bot when the button is pressed, UTF-8
:tg-const:`telegram.InlineKeyboardButton.MIN_CALLBACK_DATA`-
:tg-const:`telegram.InlineKeyboardButton.MAX_CALLBACK_DATA` bytes.
Not supported for messages sent on behalf of a Telegram Business account.
If the bot instance allows arbitrary callback data, anything can be passed.
Tip:
@@ -119,15 +119,24 @@ class InlineKeyboardButton(TelegramObject):
This is similar to the new parameter :paramref:`switch_inline_query_chosen_chat`,
but gives no control over which chats can be selected.
switch_inline_query_current_chat (:obj:`str`, optional): If set, pressing the button will
prompt the user to select one of their chats of the specified type, open that chat and
insert the bot's username and the specified inline query in the input field. Not
supported for messages sent on behalf of a Telegram Business account.
insert the bot's username and the specified inline query in the current chat's input
field. May be empty, in which case only the bot's username will be inserted.
This offers a quick way for the user to open your bot in inline mode in the same chat
- good for selecting something from multiple options. Not supported in channels and for
messages sent on behalf of a Telegram Business account.
callback_game (:class:`telegram.CallbackGame`, optional): Description of the game that will
be launched when the user presses the button. This type of button **must** always be
the **first** button in the first row.
pay (:obj:`bool`, optional): Specify :obj:`True`, to send a Pay button. This type of button
**must** always be the **first** button in the first row and can only be used in
invoice messages.
be launched when the user presses the button
Note:
This type of button **must** always be the first button in the first row.
pay (:obj:`bool`, optional): Specify :obj:`True`, to send a Pay button.
Substrings ```` and ``XTR`` in the buttons's text will be replaced with a
Telegram Star icon.
Note:
This type of button **must** always be the first button in the first row and can
only be used in invoice messages.
switch_inline_query_chosen_chat (:obj:`telegram.SwitchInlineQueryChosenChat`, optional):
If set, pressing the button will prompt the user to select one of their chats of the
specified type, open that chat and insert the bot's username and the specified inline
@@ -158,10 +167,9 @@ class InlineKeyboardButton(TelegramObject):
Caution:
Only ``HTTPS`` links are allowed after Bot API 6.1.
callback_data (:obj:`str` | :obj:`object`): Optional. Data to be sent in a callback query
to the bot when button is pressed, UTF-8
to the bot when the button is pressed, UTF-8
:tg-const:`telegram.InlineKeyboardButton.MIN_CALLBACK_DATA`-
:tg-const:`telegram.InlineKeyboardButton.MAX_CALLBACK_DATA` bytes.
Not supported for messages sent on behalf of a Telegram Business account.
web_app (:obj:`telegram.WebAppInfo`): Optional. Description of the `Web App
<https://core.telegram.org/bots/webapps>`_ that will be launched when the user presses
the button. The Web App will be able to send an arbitrary message on behalf of the user
@@ -182,15 +190,24 @@ class InlineKeyboardButton(TelegramObject):
This is similar to the new parameter :paramref:`switch_inline_query_chosen_chat`,
but gives no control over which chats can be selected.
switch_inline_query_current_chat (:obj:`str`): Optional. If set, pressing the button will
prompt the user to select one of their chats of the specified type, open that chat and
insert the bot's username and the specified inline query in the input field. Not
supported for messages sent on behalf of a Telegram Business account.
insert the bot's username and the specified inline query in the current chat's input
field. May be empty, in which case only the bot's username will be inserted.
This offers a quick way for the user to open your bot in inline mode in the same chat
- good for selecting something from multiple options. Not supported in channels and for
messages sent on behalf of a Telegram Business account.
callback_game (:class:`telegram.CallbackGame`): Optional. Description of the game that will
be launched when the user presses the button. This type of button **must** always be
the **first** button in the first row.
pay (:obj:`bool`): Optional. Specify :obj:`True`, to send a Pay button. This type of button
**must** always be the **first** button in the first row and can only be used in
invoice messages.
be launched when the user presses the button.
Note:
This type of button **must** always be the first button in the first row.
pay (:obj:`bool`): Optional. Specify :obj:`True`, to send a Pay button.
Substrings ```` and ``XTR`` in the buttons's text will be replaced with a
Telegram Star icon.
Note:
This type of button **must** always be the first button in the first row and can
only be used in invoice messages.
switch_inline_query_chosen_chat (:obj:`telegram.SwitchInlineQueryChosenChat`): Optional.
If set, pressing the button will prompt the user to select one of their chats of the
specified type, open that chat and insert the bot's username and the specified inline
@@ -271,7 +288,9 @@ class InlineKeyboardButton(TelegramObject):
)
@classmethod
def de_json(cls, data: Optional[JSONDict], bot: "Bot") -> Optional["InlineKeyboardButton"]:
def de_json(
cls, data: Optional[JSONDict], bot: Optional["Bot"] = None
) -> Optional["InlineKeyboardButton"]:
"""See :meth:`telegram.TelegramObject.de_json`."""
data = cls._parse_data(data)
+4 -2
View File
@@ -42,7 +42,7 @@ class InlineKeyboardMarkup(TelegramObject):
An inline keyboard on a message
.. seealso::
An another kind of keyboard would be the :class:`telegram.ReplyKeyboardMarkup`.
Another kind of keyboard would be the :class:`telegram.ReplyKeyboardMarkup`.
Examples:
* :any:`Inline Keyboard 1 <examples.inlinekeyboard>`
@@ -90,7 +90,9 @@ class InlineKeyboardMarkup(TelegramObject):
self._freeze()
@classmethod
def de_json(cls, data: Optional[JSONDict], bot: "Bot") -> Optional["InlineKeyboardMarkup"]:
def de_json(
cls, data: Optional[JSONDict], bot: Optional["Bot"] = None
) -> Optional["InlineKeyboardMarkup"]:
"""See :meth:`telegram.TelegramObject.de_json`."""
if not data:
return None
+3 -1
View File
@@ -125,7 +125,9 @@ class InlineQuery(TelegramObject):
self._freeze()
@classmethod
def de_json(cls, data: Optional[JSONDict], bot: "Bot") -> Optional["InlineQuery"]:
def de_json(
cls, data: Optional[JSONDict], bot: Optional["Bot"] = None
) -> Optional["InlineQuery"]:
"""See :meth:`telegram.TelegramObject.de_json`."""
data = cls._parse_data(data)
@@ -59,6 +59,9 @@ class InlineQueryResultCachedGif(InlineQueryResult):
to the message.
input_message_content (:class:`telegram.InputMessageContent`, optional): Content of the
message to be sent instead of the gif.
show_caption_above_media (:obj:`bool`, optional): Pass |show_cap_above_med|
.. versionadded:: 21.3
Attributes:
type (:obj:`str`): :tg-const:`telegram.constants.InlineQueryResultType.GIF`.
@@ -81,6 +84,9 @@ class InlineQueryResultCachedGif(InlineQueryResult):
to the message.
input_message_content (:class:`telegram.InputMessageContent`): Optional. Content of the
message to be sent instead of the gif.
show_caption_above_media (:obj:`bool`): Optional. |show_cap_above_med|
.. versionadded:: 21.3
"""
@@ -91,6 +97,7 @@ class InlineQueryResultCachedGif(InlineQueryResult):
"input_message_content",
"parse_mode",
"reply_markup",
"show_caption_above_media",
"title",
)
@@ -104,6 +111,7 @@ class InlineQueryResultCachedGif(InlineQueryResult):
input_message_content: Optional["InputMessageContent"] = None,
parse_mode: ODVInput[str] = DEFAULT_NONE,
caption_entities: Optional[Sequence[MessageEntity]] = None,
show_caption_above_media: Optional[bool] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
@@ -119,3 +127,4 @@ class InlineQueryResultCachedGif(InlineQueryResult):
self.caption_entities: Tuple[MessageEntity, ...] = parse_sequence_arg(caption_entities)
self.reply_markup: Optional[InlineKeyboardMarkup] = reply_markup
self.input_message_content: Optional[InputMessageContent] = input_message_content
self.show_caption_above_media: Optional[bool] = show_caption_above_media
@@ -59,6 +59,9 @@ class InlineQueryResultCachedMpeg4Gif(InlineQueryResult):
to the message.
input_message_content (:class:`telegram.InputMessageContent`, optional): Content of the
message to be sent instead of the MPEG-4 file.
show_caption_above_media (:obj:`bool`, optional): Pass |show_cap_above_med|
.. versionadded:: 21.3
Attributes:
type (:obj:`str`): :tg-const:`telegram.constants.InlineQueryResultType.MPEG4GIF`.
@@ -81,6 +84,9 @@ class InlineQueryResultCachedMpeg4Gif(InlineQueryResult):
to the message.
input_message_content (:class:`telegram.InputMessageContent`): Optional. Content of the
message to be sent instead of the MPEG-4 file.
show_caption_above_media (:obj:`bool`): Optional. |show_cap_above_med|
.. versionadded:: 21.3
"""
@@ -91,6 +97,7 @@ class InlineQueryResultCachedMpeg4Gif(InlineQueryResult):
"mpeg4_file_id",
"parse_mode",
"reply_markup",
"show_caption_above_media",
"title",
)
@@ -104,6 +111,7 @@ class InlineQueryResultCachedMpeg4Gif(InlineQueryResult):
input_message_content: Optional["InputMessageContent"] = None,
parse_mode: ODVInput[str] = DEFAULT_NONE,
caption_entities: Optional[Sequence[MessageEntity]] = None,
show_caption_above_media: Optional[bool] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
@@ -119,3 +127,4 @@ class InlineQueryResultCachedMpeg4Gif(InlineQueryResult):
self.caption_entities: Tuple[MessageEntity, ...] = parse_sequence_arg(caption_entities)
self.reply_markup: Optional[InlineKeyboardMarkup] = reply_markup
self.input_message_content: Optional[InputMessageContent] = input_message_content
self.show_caption_above_media: Optional[bool] = show_caption_above_media
@@ -60,6 +60,9 @@ class InlineQueryResultCachedPhoto(InlineQueryResult):
to the message.
input_message_content (:class:`telegram.InputMessageContent`, optional): Content of the
message to be sent instead of the photo.
show_caption_above_media (:obj:`bool`, optional): Pass |show_cap_above_med|
.. versionadded:: 21.3
Attributes:
type (:obj:`str`): :tg-const:`telegram.constants.InlineQueryResultType.PHOTO`.
@@ -83,6 +86,9 @@ class InlineQueryResultCachedPhoto(InlineQueryResult):
to the message.
input_message_content (:class:`telegram.InputMessageContent`): Optional. Content of the
message to be sent instead of the photo.
show_caption_above_media (:obj:`bool`): Optional. |show_cap_above_med|
.. versionadded:: 21.3
"""
@@ -94,6 +100,7 @@ class InlineQueryResultCachedPhoto(InlineQueryResult):
"parse_mode",
"photo_file_id",
"reply_markup",
"show_caption_above_media",
"title",
)
@@ -108,6 +115,7 @@ class InlineQueryResultCachedPhoto(InlineQueryResult):
input_message_content: Optional["InputMessageContent"] = None,
parse_mode: ODVInput[str] = DEFAULT_NONE,
caption_entities: Optional[Sequence[MessageEntity]] = None,
show_caption_above_media: Optional[bool] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
@@ -124,3 +132,4 @@ class InlineQueryResultCachedPhoto(InlineQueryResult):
self.caption_entities: Tuple[MessageEntity, ...] = parse_sequence_arg(caption_entities)
self.reply_markup: Optional[InlineKeyboardMarkup] = reply_markup
self.input_message_content: Optional[InputMessageContent] = input_message_content
self.show_caption_above_media: Optional[bool] = show_caption_above_media
@@ -56,6 +56,9 @@ class InlineQueryResultCachedVideo(InlineQueryResult):
to the message.
input_message_content (:class:`telegram.InputMessageContent`, optional): Content of the
message to be sent instead of the video.
show_caption_above_media (:obj:`bool`, optional): Pass |show_cap_above_med|
.. versionadded:: 21.3
Attributes:
type (:obj:`str`): :tg-const:`telegram.constants.InlineQueryResultType.VIDEO`.
@@ -79,6 +82,9 @@ class InlineQueryResultCachedVideo(InlineQueryResult):
to the message.
input_message_content (:class:`telegram.InputMessageContent`): Optional. Content of the
message to be sent instead of the video.
show_caption_above_media (:obj:`bool`): Optional. |show_cap_above_med|
.. versionadded:: 21.3
"""
@@ -89,6 +95,7 @@ class InlineQueryResultCachedVideo(InlineQueryResult):
"input_message_content",
"parse_mode",
"reply_markup",
"show_caption_above_media",
"title",
"video_file_id",
)
@@ -104,6 +111,7 @@ class InlineQueryResultCachedVideo(InlineQueryResult):
input_message_content: Optional["InputMessageContent"] = None,
parse_mode: ODVInput[str] = DEFAULT_NONE,
caption_entities: Optional[Sequence[MessageEntity]] = None,
show_caption_above_media: Optional[bool] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
@@ -120,3 +128,4 @@ class InlineQueryResultCachedVideo(InlineQueryResult):
self.caption_entities: Tuple[MessageEntity, ...] = parse_sequence_arg(caption_entities)
self.reply_markup: Optional[InlineKeyboardMarkup] = reply_markup
self.input_message_content: Optional[InputMessageContent] = input_message_content
self.show_caption_above_media: Optional[bool] = show_caption_above_media
+9
View File
@@ -78,6 +78,9 @@ class InlineQueryResultGif(InlineQueryResult):
to the message.
input_message_content (:class:`telegram.InputMessageContent`, optional): Content of the
message to be sent instead of the GIF animation.
show_caption_above_media (:obj:`bool`, optional): Pass |show_cap_above_med|
.. versionadded:: 21.3
Raises:
:class:`ValueError`: If neither :paramref:`thumbnail_url` nor :paramref:`thumb_url` is
@@ -115,6 +118,9 @@ class InlineQueryResultGif(InlineQueryResult):
to the message.
input_message_content (:class:`telegram.InputMessageContent`): Optional. Content of the
message to be sent instead of the GIF animation.
show_caption_above_media (:obj:`bool`): Optional. |show_cap_above_med|
.. versionadded:: 21.3
"""
@@ -128,6 +134,7 @@ class InlineQueryResultGif(InlineQueryResult):
"input_message_content",
"parse_mode",
"reply_markup",
"show_caption_above_media",
"thumbnail_mime_type",
"thumbnail_url",
"title",
@@ -148,6 +155,7 @@ class InlineQueryResultGif(InlineQueryResult):
parse_mode: ODVInput[str] = DEFAULT_NONE,
caption_entities: Optional[Sequence[MessageEntity]] = None,
thumbnail_mime_type: Optional[str] = None,
show_caption_above_media: Optional[bool] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
@@ -168,3 +176,4 @@ class InlineQueryResultGif(InlineQueryResult):
self.reply_markup: Optional[InlineKeyboardMarkup] = reply_markup
self.input_message_content: Optional[InputMessageContent] = input_message_content
self.thumbnail_mime_type: Optional[str] = thumbnail_mime_type
self.show_caption_above_media: Optional[bool] = show_caption_above_media
@@ -80,7 +80,9 @@ class InlineQueryResultMpeg4Gif(InlineQueryResult):
to the message.
input_message_content (:class:`telegram.InputMessageContent`, optional): Content of the
message to be sent instead of the video animation.
show_caption_above_media (:obj:`bool`, optional): Pass |show_cap_above_med|
.. versionadded:: 21.3
Raises:
:class:`ValueError`: If neither :paramref:`thumbnail_url` nor :paramref:`thumb_url` is
supplied or if both are supplied and are not equal.
@@ -118,7 +120,9 @@ class InlineQueryResultMpeg4Gif(InlineQueryResult):
to the message.
input_message_content (:class:`telegram.InputMessageContent`): Optional. Content of the
message to be sent instead of the video animation.
show_caption_above_media (:obj:`bool`): Optional. |show_cap_above_med|
.. versionadded:: 21.3
"""
__slots__ = (
@@ -131,6 +135,7 @@ class InlineQueryResultMpeg4Gif(InlineQueryResult):
"mpeg4_width",
"parse_mode",
"reply_markup",
"show_caption_above_media",
"thumbnail_mime_type",
"thumbnail_url",
"title",
@@ -151,6 +156,7 @@ class InlineQueryResultMpeg4Gif(InlineQueryResult):
parse_mode: ODVInput[str] = DEFAULT_NONE,
caption_entities: Optional[Sequence[MessageEntity]] = None,
thumbnail_mime_type: Optional[str] = None,
show_caption_above_media: Optional[bool] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
@@ -171,3 +177,4 @@ class InlineQueryResultMpeg4Gif(InlineQueryResult):
self.reply_markup: Optional[InlineKeyboardMarkup] = reply_markup
self.input_message_content: Optional[InputMessageContent] = input_message_content
self.thumbnail_mime_type: Optional[str] = thumbnail_mime_type
self.show_caption_above_media: Optional[bool] = show_caption_above_media
@@ -74,6 +74,9 @@ class InlineQueryResultPhoto(InlineQueryResult):
to the message.
input_message_content (:class:`telegram.InputMessageContent`, optional): Content of the
message to be sent instead of the photo.
show_caption_above_media (:obj:`bool`, optional): Pass |show_cap_above_med|
.. versionadded:: 21.3
Raises:
:class:`ValueError`: If neither :paramref:`thumbnail_url` nor :paramref:`thumb_url` is
@@ -105,6 +108,9 @@ class InlineQueryResultPhoto(InlineQueryResult):
to the message.
input_message_content (:class:`telegram.InputMessageContent`): Optional. Content of the
message to be sent instead of the photo.
show_caption_above_media (:obj:`bool`): Optional. |show_cap_above_med|
.. versionadded:: 21.3
"""
@@ -118,6 +124,7 @@ class InlineQueryResultPhoto(InlineQueryResult):
"photo_url",
"photo_width",
"reply_markup",
"show_caption_above_media",
"thumbnail_url",
"title",
)
@@ -136,6 +143,7 @@ class InlineQueryResultPhoto(InlineQueryResult):
input_message_content: Optional["InputMessageContent"] = None,
parse_mode: ODVInput[str] = DEFAULT_NONE,
caption_entities: Optional[Sequence[MessageEntity]] = None,
show_caption_above_media: Optional[bool] = None,
*,
api_kwargs: Optional[JSONDict] = None,
):
@@ -155,3 +163,4 @@ class InlineQueryResultPhoto(InlineQueryResult):
self.caption_entities: Tuple[MessageEntity, ...] = parse_sequence_arg(caption_entities)
self.reply_markup: Optional[InlineKeyboardMarkup] = reply_markup
self.input_message_content: Optional[InputMessageContent] = input_message_content
self.show_caption_above_media: Optional[bool] = show_caption_above_media
+3 -1
View File
@@ -97,7 +97,9 @@ class InlineQueryResultsButton(TelegramObject):
self._freeze()
@classmethod
def de_json(cls, data: Optional[JSONDict], bot: "Bot") -> Optional["InlineQueryResultsButton"]:
def de_json(
cls, data: Optional[JSONDict], bot: Optional["Bot"] = None
) -> Optional["InlineQueryResultsButton"]:
"""See :meth:`telegram.TelegramObject.de_json`."""
if not data:
return None

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