diff --git a/.github/workflows/chango.yml b/.github/workflows/chango.yml new file mode 100644 index 00000000000..d845f6bc019 --- /dev/null +++ b/.github/workflows/chango.yml @@ -0,0 +1,66 @@ +name: Chango +on: + pull_request: + types: + - opened + - reopened + - synchronize + +permissions: {} + +jobs: + create-chango-fragment: + permissions: + # Give the default GITHUB_TOKEN write permission to commit and push the + # added or changed files to the repository. + contents: write + name: Create chango Fragment + runs-on: ubuntu-latest + outputs: + IS_RELEASE_PR: ${{ steps.check_title.outputs.IS_RELEASE_PR }} + + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + # needed for commit and push step at the end + persist-credentials: true + - name: Check PR Title + id: check_title + run: | # zizmor: ignore[template-injection] + if [[ "$(echo "${{ github.event.pull_request.title }}" | tr '[:upper:]' '[:lower:]')" =~ ^bump\ version\ to\ .* ]]; then + echo "COMMIT_AND_PUSH=false" >> $GITHUB_OUTPUT + echo "IS_RELEASE_PR=true" >> $GITHUB_OUTPUT + else + echo "COMMIT_AND_PUSH=true" >> $GITHUB_OUTPUT + echo "IS_RELEASE_PR=false" >> $GITHUB_OUTPUT + fi + + # Create the new fragment + - uses: Bibo-Joshi/chango@9d6bd9d7612eca5fab2c5161687011be59baaf19 # v0.4.0 + with: + github-token: ${{ secrets.CHANGO_PAT }} + query-issue-types: true + commit-and-push: ${{ steps.check_title.outputs.COMMIT_AND_PUSH }} + + # Run `chango release` if applicable - needs some additional setup. + - name: Set up Python + if: steps.check_title.outputs.IS_RELEASE_PR == 'true' + uses: actions/setup-python@8d9ed9ac5c53483de85588cdf95a591a75ab9f55 # v5.5.0 + with: + python-version: "3.x" + + - name: Do Release + if: steps.check_title.outputs.IS_RELEASE_PR == 'true' + run: | + cd ./target-repo + git add changes/unreleased/* + pip install . -r docs/requirements-docs.txt + VERSION_TAG=$(python -c "from telegram import __version__; print(f'{__version__}')") + chango release --uid $VERSION_TAG + + - name: Commit & Push + if: steps.check_title.outputs.IS_RELEASE_PR == 'true' + uses: stefanzweifel/git-auto-commit-action@b863ae1933cb653a53c021fe36dbb774e1fb9403 # v5.2.0 + with: + commit_message: "Do chango Release" + repository: ./target-repo diff --git a/.github/workflows/chango_fragment.yml b/.github/workflows/chango_fragment.yml deleted file mode 100644 index 8a1cc25984c..00000000000 --- a/.github/workflows/chango_fragment.yml +++ /dev/null @@ -1,30 +0,0 @@ -name: Create Chango Fragment -on: - pull_request: - types: - - opened - - reopened - - synchronize - -permissions: {} - -jobs: - create-chango-fragment: - permissions: - # Give the default GITHUB_TOKEN write permission to commit and push the - # added or changed files to the repository. - contents: write - name: create-chango-fragment - runs-on: ubuntu-latest - steps: - - # Create the new fragment - - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - with: - persist-credentials: false - - uses: Bibo-Joshi/chango@9d6bd9d7612eca5fab2c5161687011be59baaf19 # v0.4.0 - with: - github-token: ${{ secrets.CHANGO_PAT }} - query-issue-types: true - - diff --git a/.github/workflows/docs-admonitions.yml b/.github/workflows/docs-admonitions.yml index 52dac4cef94..00b03ae4cca 100644 --- a/.github/workflows/docs-admonitions.yml +++ b/.github/workflows/docs-admonitions.yml @@ -28,7 +28,7 @@ jobs: with: persist-credentials: false - name: Set up Python ${{ matrix.python-version }} - uses: actions/setup-python@42375524e23c412d93fb67b49958b491fce71c38 # v5.4.0 + uses: actions/setup-python@8d9ed9ac5c53483de85588cdf95a591a75ab9f55 # v5.5.0 with: python-version: ${{ matrix.python-version }} cache: 'pip' diff --git a/.github/workflows/docs-linkcheck.yml b/.github/workflows/docs-linkcheck.yml index 1c6f56ab8bc..65453ad11f3 100644 --- a/.github/workflows/docs-linkcheck.yml +++ b/.github/workflows/docs-linkcheck.yml @@ -23,7 +23,7 @@ jobs: with: persist-credentials: false - name: Set up Python ${{ matrix.python-version }} - uses: actions/setup-python@42375524e23c412d93fb67b49958b491fce71c38 # v5.4.0 + uses: actions/setup-python@8d9ed9ac5c53483de85588cdf95a591a75ab9f55 # v5.5.0 with: python-version: ${{ matrix.python-version }} - name: Install dependencies @@ -31,11 +31,11 @@ jobs: python -W ignore -m pip install --upgrade pip 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 + run: sphinx-build docs/source docs/build/html --keep-going -j auto -b linkcheck - name: Upload linkcheck output # Run also if the previous steps failed if: always() - uses: actions/upload-artifact@6f51ac03b9356f520e9adb1b1b7802705f340c2b # v4.5.0 + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: name: linkcheck-output path: docs/build/html/output.* diff --git a/.github/workflows/gha_security.yml b/.github/workflows/gha_security.yml index aaa72e61cae..df0d0f10bb5 100644 --- a/.github/workflows/gha_security.yml +++ b/.github/workflows/gha_security.yml @@ -21,13 +21,13 @@ jobs: with: persist-credentials: false - name: Install the latest version of uv - uses: astral-sh/setup-uv@f94ec6bedd8674c4426838e6b50417d36b6ab231 # v5.3.1 + uses: astral-sh/setup-uv@0c5e2b8115b80b4c7c5ddf6ffdd634974642d182 # v5.4.1 - name: Run zizmor run: uvx zizmor --persona=pedantic --format sarif . > results.sarif env: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} - name: Upload SARIF file - uses: github/codeql-action/upload-sarif@b56ba49b26e50535fa1e7f7db0f4f7b4bf65d80d # v3.28.10 + uses: github/codeql-action/upload-sarif@28deaeda66b76a05916b6923827895f2b14ab387 # v3.28.16 with: sarif_file: results.sarif category: zizmor \ No newline at end of file diff --git a/.github/workflows/release_pypi.yml b/.github/workflows/release_pypi.yml index c59a4579561..a9e9e468010 100644 --- a/.github/workflows/release_pypi.yml +++ b/.github/workflows/release_pypi.yml @@ -21,7 +21,7 @@ jobs: with: persist-credentials: false - name: Set up Python - uses: actions/setup-python@42375524e23c412d93fb67b49958b491fce71c38 # v5.4.0 + uses: actions/setup-python@8d9ed9ac5c53483de85588cdf95a591a75ab9f55 # v5.5.0 with: python-version: "3.x" - name: Install pypa/build @@ -30,7 +30,7 @@ jobs: - name: Build a binary wheel and a source tarball run: python3 -m build - name: Store the distribution packages - uses: actions/upload-artifact@6f51ac03b9356f520e9adb1b1b7802705f340c2b # v4.5.0 + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: name: python-package-distributions path: dist/ @@ -55,7 +55,7 @@ jobs: steps: - name: Download all the dists - uses: actions/download-artifact@fa0a91b85d4f404e444e00e005971372dc801d16 # v4.1.8 + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 with: name: python-package-distributions path: dist/ @@ -74,7 +74,7 @@ jobs: steps: - name: Download all the dists - uses: actions/download-artifact@fa0a91b85d4f404e444e00e005971372dc801d16 # v4.1.8 + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 with: name: python-package-distributions path: dist/ @@ -92,7 +92,7 @@ jobs: ./dist/*.tar.gz ./dist/*.whl - name: Store the distribution packages and signatures - uses: actions/upload-artifact@6f51ac03b9356f520e9adb1b1b7802705f340c2b # v4.5.0 + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: name: python-package-distributions-and-signatures path: dist/ @@ -110,8 +110,11 @@ jobs: actions: read # for downloading artifacts steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + persist-credentials: false - name: Download all the dists - uses: actions/download-artifact@fa0a91b85d4f404e444e00e005971372dc801d16 # v4.1.8 + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 with: name: python-package-distributions-and-signatures path: dist/ @@ -150,6 +153,9 @@ jobs: permissions: {} steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + persist-credentials: false - name: Publish to Telegram Channel env: TAG: ${{ needs.build.outputs.TAG }} diff --git a/.github/workflows/release_test_pypi.yml b/.github/workflows/release_test_pypi.yml index ac8872ff509..a59baec5e67 100644 --- a/.github/workflows/release_test_pypi.yml +++ b/.github/workflows/release_test_pypi.yml @@ -21,7 +21,7 @@ jobs: with: persist-credentials: false - name: Set up Python - uses: actions/setup-python@42375524e23c412d93fb67b49958b491fce71c38 # v5.4.0 + uses: actions/setup-python@8d9ed9ac5c53483de85588cdf95a591a75ab9f55 # v5.5.0 with: python-version: "3.x" - name: Install pypa/build @@ -30,7 +30,7 @@ jobs: - name: Build a binary wheel and a source tarball run: python3 -m build - name: Store the distribution packages - uses: actions/upload-artifact@6f51ac03b9356f520e9adb1b1b7802705f340c2b # v4.5.0 + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: name: python-package-distributions path: dist/ @@ -55,7 +55,7 @@ jobs: steps: - name: Download all the dists - uses: actions/download-artifact@fa0a91b85d4f404e444e00e005971372dc801d16 # v4.1.8 + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 with: name: python-package-distributions path: dist/ @@ -76,7 +76,7 @@ jobs: steps: - name: Download all the dists - uses: actions/download-artifact@fa0a91b85d4f404e444e00e005971372dc801d16 # v4.1.8 + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 with: name: python-package-distributions path: dist/ @@ -94,7 +94,7 @@ jobs: ./dist/*.tar.gz ./dist/*.whl - name: Store the distribution packages and signatures - uses: actions/upload-artifact@6f51ac03b9356f520e9adb1b1b7802705f340c2b # v4.5.0 + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: name: python-package-distributions-and-signatures path: dist/ @@ -112,8 +112,11 @@ jobs: actions: read # for downloading artifacts steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + persist-credentials: false - name: Download all the dists - uses: actions/download-artifact@fa0a91b85d4f404e444e00e005971372dc801d16 # v4.1.8 + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 with: name: python-package-distributions-and-signatures path: dist/ diff --git a/.github/workflows/test_official.yml b/.github/workflows/test_official.yml index 6eae5e4bcf6..14224d0901a 100644 --- a/.github/workflows/test_official.yml +++ b/.github/workflows/test_official.yml @@ -27,7 +27,7 @@ jobs: with: persist-credentials: false - name: Set up Python ${{ matrix.python-version }} - uses: actions/setup-python@42375524e23c412d93fb67b49958b491fce71c38 # v5.4.0 + uses: actions/setup-python@8d9ed9ac5c53483de85588cdf95a591a75ab9f55 # v5.5.0 with: python-version: ${{ matrix.python-version }} - name: Install dependencies diff --git a/.github/workflows/unit_tests.yml b/.github/workflows/unit_tests.yml index fd914bf91b4..affb519fce2 100644 --- a/.github/workflows/unit_tests.yml +++ b/.github/workflows/unit_tests.yml @@ -30,7 +30,7 @@ jobs: with: persist-credentials: false - name: Set up Python ${{ matrix.python-version }} - uses: actions/setup-python@42375524e23c412d93fb67b49958b491fce71c38 # v5.4.0 + uses: actions/setup-python@8d9ed9ac5c53483de85588cdf95a591a75ab9f55 # v5.5.0 with: python-version: ${{ matrix.python-version }} cache: 'pip' @@ -92,14 +92,14 @@ jobs: .test_report_optionals_junit.xml - name: Submit coverage - uses: codecov/codecov-action@1e68e06f1dbfde0e4cefc87efeba9e4643565303 # v5.1.2 + uses: codecov/codecov-action@ad3126e916f78f00edff4ed0317cf185271ccc2d # v5.4.2 with: env_vars: OS,PYTHON name: ${{ matrix.os }}-${{ matrix.python-version }} fail_ci_if_error: true token: ${{ secrets.CODECOV_TOKEN }} - name: Upload test results to Codecov - uses: codecov/test-results-action@4e79e65778be1cecd5df25e14af1eafb6df80ea9 # v1.0.2 + uses: codecov/test-results-action@f2dba722c67b86c6caa034178c6e4d35335f6706 # v1.1.0 if: ${{ !cancelled() }} with: files: .test_report_no_optionals_junit.xml,.test_report_optionals_junit.xml diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 6b56f457ed3..a6002c846bf 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -7,7 +7,7 @@ ci: repos: - repo: https://github.com/astral-sh/ruff-pre-commit - rev: 'v0.8.6' + rev: 'v0.11.9' hooks: - id: ruff name: ruff @@ -18,18 +18,18 @@ repos: - cachetools>=5.3.3,<5.5.0 - aiolimiter~=1.1,<1.3 - repo: https://github.com/psf/black-pre-commit-mirror - rev: 24.10.0 + rev: 25.1.0 hooks: - id: black args: - --diff - --check - repo: https://github.com/PyCQA/flake8 - rev: 7.1.1 + rev: 7.2.0 hooks: - id: flake8 - repo: https://github.com/PyCQA/pylint - rev: v3.3.3 + rev: v3.3.6 hooks: - id: pylint files: ^(?!(tests|docs)).*\.py$ @@ -41,7 +41,7 @@ repos: - aiolimiter~=1.1,<1.3 - . # this basically does `pip install -e .` - repo: https://github.com/pre-commit/mirrors-mypy - rev: v1.14.1 + rev: v1.15.0 hooks: - id: mypy name: mypy-ptb @@ -74,7 +74,7 @@ repos: args: - --py39-plus - repo: https://github.com/pycqa/isort - rev: 5.13.2 + rev: 6.0.1 hooks: - id: isort name: isort diff --git a/AUTHORS.rst b/AUTHORS.rst index 98e5b686de1..61535397919 100644 --- a/AUTHORS.rst +++ b/AUTHORS.rst @@ -7,10 +7,8 @@ The current development team includes - `Hinrich Mahler `_ (maintainer) - `Poolitzer `_ (community liaison) -- `Shivam `_ - `Harshil `_ -- `Dmitry Kolomatskiy `_ -- `Aditya `_ +- `Abdelrahman `_ Emeritus maintainers include `Jannes Höke `_ (`@jh0ker `_ on Telegram), @@ -21,7 +19,7 @@ Contributors The following wonderful people contributed directly or indirectly to this project: -- `Abdelrahman `_ +- `Aditya `_ - `Abshar `_ - `Abubakar Alaya `_ - `Alateas `_ @@ -42,6 +40,7 @@ The following wonderful people contributed directly or indirectly to this projec - `daimajia `_ - `Daniel Reed `_ - `D David Livingston `_ +- `Dmitry Kolomatskiy `_ - `DonalDuck004 `_ - `Eana Hufwe `_ - `Ehsan Online `_ @@ -122,6 +121,7 @@ The following wonderful people contributed directly or indirectly to this projec - `Sam Mosleh `_ - `Sascha `_ - `Shelomentsev D `_ +- `Shivam `_ - `Shivam Saini `_ - `Siloé Garcez `_ - `Simon Schürrle `_ diff --git a/README.rst b/README.rst index d19a93d4d3f..d847fd3140c 100644 --- a/README.rst +++ b/README.rst @@ -19,7 +19,7 @@ :target: https://pypistats.org/packages/python-telegram-bot :alt: PyPi Package Monthly Download -.. image:: https://readthedocs.org/projects/python-telegram-bot/badge/?version=stable +.. image:: https://app.readthedocs.org/projects/python-telegram-bot/badge/?version=stable :target: https://docs.python-telegram-bot.org/en/stable/ :alt: Documentation Status diff --git a/changes/22.0_2025-03-15/4697.GzyGCEgj74G6bTEDbuFjUU.toml b/changes/22.0_2025-03-15/4697.GzyGCEgj74G6bTEDbuFjUU.toml index d1bdf38d738..abdb8f95575 100644 --- a/changes/22.0_2025-03-15/4697.GzyGCEgj74G6bTEDbuFjUU.toml +++ b/changes/22.0_2025-03-15/4697.GzyGCEgj74G6bTEDbuFjUU.toml @@ -1,5 +1,5 @@ internal = "Bump github/codeql-action from 3.28.8 to 3.28.10" [[pull_requests]] uid = "4697" -author_uid = "dependabot[bot]" +author_uid = "dependabot" closes_threads = [] diff --git a/changes/22.0_2025-03-15/4698.Fkzr3oU2qcFmFX28xfoja5.toml b/changes/22.0_2025-03-15/4698.Fkzr3oU2qcFmFX28xfoja5.toml index 6ba893a7200..93eb25aa5b5 100644 --- a/changes/22.0_2025-03-15/4698.Fkzr3oU2qcFmFX28xfoja5.toml +++ b/changes/22.0_2025-03-15/4698.Fkzr3oU2qcFmFX28xfoja5.toml @@ -1,5 +1,5 @@ internal = "Bump srvaroa/labeler from 1.12.0 to 1.13.0" [[pull_requests]] uid = "4698" -author_uid = "dependabot[bot]" +author_uid = "dependabot" closes_threads = [] diff --git a/changes/22.0_2025-03-15/4699.LYAYfKXX7C7wqT54kRPnVy.toml b/changes/22.0_2025-03-15/4699.LYAYfKXX7C7wqT54kRPnVy.toml index 23bfcbfd4c7..6d028a80509 100644 --- a/changes/22.0_2025-03-15/4699.LYAYfKXX7C7wqT54kRPnVy.toml +++ b/changes/22.0_2025-03-15/4699.LYAYfKXX7C7wqT54kRPnVy.toml @@ -1,5 +1,5 @@ internal = "Bump astral-sh/setup-uv from 5.2.2 to 5.3.1" [[pull_requests]] uid = "4699" -author_uid = "dependabot[bot]" +author_uid = "dependabot" closes_threads = [] diff --git a/changes/22.0_2025-03-15/4700.nm6R6YTnkmCo5evbykz4kz.toml b/changes/22.0_2025-03-15/4700.nm6R6YTnkmCo5evbykz4kz.toml index 6dc7d8a9e07..5f5355f6d2e 100644 --- a/changes/22.0_2025-03-15/4700.nm6R6YTnkmCo5evbykz4kz.toml +++ b/changes/22.0_2025-03-15/4700.nm6R6YTnkmCo5evbykz4kz.toml @@ -1,5 +1,5 @@ internal = "Bump Bibo-Joshi/chango from 0.3.1 to 0.3.2" [[pull_requests]] uid = "4700" -author_uid = "dependabot[bot]" +author_uid = "dependabot" closes_threads = [] diff --git a/changes/22.0_2025-03-15/4701.ah8Wi4SWc22EbgBc4KQeqH.toml b/changes/22.0_2025-03-15/4701.ah8Wi4SWc22EbgBc4KQeqH.toml index a402f0e8990..ac941f29246 100644 --- a/changes/22.0_2025-03-15/4701.ah8Wi4SWc22EbgBc4KQeqH.toml +++ b/changes/22.0_2025-03-15/4701.ah8Wi4SWc22EbgBc4KQeqH.toml @@ -1,5 +1,5 @@ internal = "Bump pypa/gh-action-pypi-publish from 1.12.3 to 1.12.4" [[pull_requests]] uid = "4701" -author_uid = "dependabot[bot]" +author_uid = "dependabot" closes_threads = [] diff --git a/changes/22.0_2025-03-15/4709.dbwPVaU8vSacVkMLhiMjyJ.toml b/changes/22.0_2025-03-15/4709.dbwPVaU8vSacVkMLhiMjyJ.toml index a697b214f38..5cc432cd401 100644 --- a/changes/22.0_2025-03-15/4709.dbwPVaU8vSacVkMLhiMjyJ.toml +++ b/changes/22.0_2025-03-15/4709.dbwPVaU8vSacVkMLhiMjyJ.toml @@ -1,5 +1,5 @@ internal = "Bump pytest from 8.3.4 to 8.3.5" [[pull_requests]] uid = "4709" -author_uid = "dependabot[bot]" +author_uid = "dependabot" closes_threads = [] diff --git a/changes/22.0_2025-03-15/4710.CSNixpvxJdLFaM6xSQ39Zf.toml b/changes/22.0_2025-03-15/4710.CSNixpvxJdLFaM6xSQ39Zf.toml index 2d7787a14a9..4219b05acba 100644 --- a/changes/22.0_2025-03-15/4710.CSNixpvxJdLFaM6xSQ39Zf.toml +++ b/changes/22.0_2025-03-15/4710.CSNixpvxJdLFaM6xSQ39Zf.toml @@ -1,5 +1,5 @@ internal = "Bump sphinx from 8.1.3 to 8.2.3" [[pull_requests]] uid = "4710" -author_uid = "dependabot[bot]" +author_uid = "dependabot" closes_threads = [] diff --git a/changes/config.py b/changes/config.py index d7557990bad..1fd95fa9767 100644 --- a/changes/config.py +++ b/changes/config.py @@ -2,9 +2,12 @@ # pylint: disable=import-error """Configuration for the chango changelog tool""" +import re from collections.abc import Collection +from pathlib import Path from typing import Optional +from chango import Version from chango.concrete import DirectoryChanGo, DirectoryVersionScanner, HeaderVersionHistory from chango.concrete.sections import GitHubSectionChangeNote, Section, SectionVersionNote @@ -70,7 +73,31 @@ def get_sections( return found or {"other"} -chango_instance = DirectoryChanGo( +class CustomChango(DirectoryChanGo): + """Custom ChanGo class for overriding release""" + + def release(self, version: Version) -> bool: + """replace "14.5" with version.uid except in the contrib guide + then call super + """ + root = Path(__file__).parent.parent / "telegram" + python_files = root.rglob("*.py") + pattern = re.compile(r"NEXT\.VERSION") + excluded_paths = {root / "docs/source/contribute.rst"} + for file_path in python_files: + if str(file_path) in excluded_paths: + continue + + content = file_path.read_text(encoding="utf-8") + modified = pattern.sub(version.uid, content) + + if content != modified: + file_path.write_text(modified, encoding="utf-8") + + return super().release(version) + + +chango_instance = CustomChango( change_note_type=ChangoSectionChangeNote, version_note_type=SectionVersionNote, version_history_type=HeaderVersionHistory, diff --git a/changes/unreleased/4692.dVZs28GuwTFnNJdWkvPbNv.toml b/changes/unreleased/4692.dVZs28GuwTFnNJdWkvPbNv.toml new file mode 100644 index 00000000000..aebbd7e67c1 --- /dev/null +++ b/changes/unreleased/4692.dVZs28GuwTFnNJdWkvPbNv.toml @@ -0,0 +1,5 @@ +breaking = "Drop backward compatibility for `user_id` in `send_gift` by updating the order of parameters. Please adapt your code accordingly or use keyword arguments." +[[pull_requests]] +uid = "4692" +author_uid = "Bibo-Joshi" +closes_threads = [] diff --git a/changes/unreleased/4733.BRLwsEuh76974FPJRuiBjf.toml b/changes/unreleased/4733.BRLwsEuh76974FPJRuiBjf.toml new file mode 100644 index 00000000000..579b6c3b37d --- /dev/null +++ b/changes/unreleased/4733.BRLwsEuh76974FPJRuiBjf.toml @@ -0,0 +1,5 @@ +bugfixes = "Ensure execution of ``Bot.shutdown`` even if ``Bot.get_me()`` fails in ``Bot.initialize()``" +[[pull_requests]] +uid = "4733" +author_uid = "Poolitzer" +closes_threads = [] diff --git a/changes/unreleased/4741.nVLBrFX4p8jTCBjMRqaYoQ.toml b/changes/unreleased/4741.nVLBrFX4p8jTCBjMRqaYoQ.toml new file mode 100644 index 00000000000..aacb5f2d501 --- /dev/null +++ b/changes/unreleased/4741.nVLBrFX4p8jTCBjMRqaYoQ.toml @@ -0,0 +1,5 @@ +internal = "Bump codecov/test-results-action from 1.0.2 to 1.1.0" +[[pull_requests]] +uid = "4741" +author_uid = "dependabot" +closes_threads = [] diff --git a/changes/unreleased/4742.oEA6MjYXMafdbu2akWT5tC.toml b/changes/unreleased/4742.oEA6MjYXMafdbu2akWT5tC.toml new file mode 100644 index 00000000000..97463ed483f --- /dev/null +++ b/changes/unreleased/4742.oEA6MjYXMafdbu2akWT5tC.toml @@ -0,0 +1,5 @@ +internal = "Bump actions/setup-python from 5.4.0 to 5.5.0" +[[pull_requests]] +uid = "4742" +author_uid = "dependabot" +closes_threads = [] diff --git a/changes/unreleased/4743.SpMm4vvAMjEreykTcGwzcF.toml b/changes/unreleased/4743.SpMm4vvAMjEreykTcGwzcF.toml new file mode 100644 index 00000000000..b6724ab2917 --- /dev/null +++ b/changes/unreleased/4743.SpMm4vvAMjEreykTcGwzcF.toml @@ -0,0 +1,5 @@ +internal = "Bump github/codeql-action from 3.28.10 to 3.28.13" +[[pull_requests]] +uid = "4743" +author_uid = "dependabot" +closes_threads = [] diff --git a/changes/unreleased/4744.a4tsF64kZPA2noP7HtTzTX.toml b/changes/unreleased/4744.a4tsF64kZPA2noP7HtTzTX.toml new file mode 100644 index 00000000000..cb5f24ea554 --- /dev/null +++ b/changes/unreleased/4744.a4tsF64kZPA2noP7HtTzTX.toml @@ -0,0 +1,5 @@ +internal = "Bump astral-sh/setup-uv from 5.3.1 to 5.4.1" +[[pull_requests]] +uid = "4744" +author_uid = "dependabot" +closes_threads = [] diff --git a/changes/unreleased/4745.emNmhxtvtTP9uLNQxpcVSj.toml b/changes/unreleased/4745.emNmhxtvtTP9uLNQxpcVSj.toml new file mode 100644 index 00000000000..cae16287a79 --- /dev/null +++ b/changes/unreleased/4745.emNmhxtvtTP9uLNQxpcVSj.toml @@ -0,0 +1,5 @@ +internal = "Bump actions/download-artifact from 4.1.8 to 4.2.1" +[[pull_requests]] +uid = "4745" +author_uid = "dependabot" +closes_threads = [] diff --git a/changes/unreleased/4746.gWnX3BCxbvujQ8B2QejtTK.toml b/changes/unreleased/4746.gWnX3BCxbvujQ8B2QejtTK.toml new file mode 100644 index 00000000000..c24204d45c4 --- /dev/null +++ b/changes/unreleased/4746.gWnX3BCxbvujQ8B2QejtTK.toml @@ -0,0 +1,5 @@ +internal = "Reenable ``test_official`` Blocked by Debug Remnant" +[[pull_requests]] +uid = "4746" +author_uid = "aelkheir" +closes_threads = [] diff --git a/changes/unreleased/4747.MLmApvpGdwN7J24j7fXsDU.toml b/changes/unreleased/4747.MLmApvpGdwN7J24j7fXsDU.toml new file mode 100644 index 00000000000..e6bb47332f9 --- /dev/null +++ b/changes/unreleased/4747.MLmApvpGdwN7J24j7fXsDU.toml @@ -0,0 +1,5 @@ +documentation = "Update ``AUTHORS.rst``, Adding `@aelkheir `_ to Active Development Team" +[[pull_requests]] +uid = "4747" +author_uid = "Bibo-Joshi" +closes_threads = [] diff --git a/changes/unreleased/4748.j3cKusZZKqTLbc542K4sqJ.toml b/changes/unreleased/4748.j3cKusZZKqTLbc542K4sqJ.toml new file mode 100644 index 00000000000..a719b9ecd07 --- /dev/null +++ b/changes/unreleased/4748.j3cKusZZKqTLbc542K4sqJ.toml @@ -0,0 +1,5 @@ +internal = "Bump `pre-commit` Hooks to Latest Versions" +[[pull_requests]] +uid = "4748" +author_uid = "pre-commit-ci" +closes_threads = [] diff --git a/changes/unreleased/4758.dSyCdBJWEJroH2GynR2VaJ.toml b/changes/unreleased/4758.dSyCdBJWEJroH2GynR2VaJ.toml new file mode 100644 index 00000000000..23ffc153339 --- /dev/null +++ b/changes/unreleased/4758.dSyCdBJWEJroH2GynR2VaJ.toml @@ -0,0 +1,5 @@ +internal = "Fine Tune ``chango`` and Release Workflows" +[[pull_requests]] +uid = "4758" +author_uid = "Bibo-Joshi" +closes_threads = ["4720"] diff --git a/changes/unreleased/4761.mmsngFA6b4ccdEzEpFTZS3.toml b/changes/unreleased/4761.mmsngFA6b4ccdEzEpFTZS3.toml new file mode 100644 index 00000000000..a47dcdcc3b1 --- /dev/null +++ b/changes/unreleased/4761.mmsngFA6b4ccdEzEpFTZS3.toml @@ -0,0 +1,6 @@ +bugfixes = "Fix Handling of ``Defaults`` for ``InputPaidMedia``" + +[[pull_requests]] +uid = "4761" +author_uid = "ngrogolev" +closes_threads = ["4753"] diff --git a/changes/unreleased/4762.PbcJGM8KPBMbKri3fdHKjh.toml b/changes/unreleased/4762.PbcJGM8KPBMbKri3fdHKjh.toml new file mode 100644 index 00000000000..0aeebe750b6 --- /dev/null +++ b/changes/unreleased/4762.PbcJGM8KPBMbKri3fdHKjh.toml @@ -0,0 +1,5 @@ +documentation = "Clarify Documentation and Type Hints of ``InputMedia`` and ``InputPaidMedia``. Note that the ``media`` parameter accepts only objects of type ``str`` and ``InputFile``. The respective subclasses of ``Input(Paid)Media`` each accept a broader range of input type for the ``media`` parameter." +[[pull_requests]] +uid = "4762" +author_uid = "Bibo-Joshi" +closes_threads = [] diff --git a/changes/unreleased/4775.kkLon84t7Vy5REKRe9LwPH.toml b/changes/unreleased/4775.kkLon84t7Vy5REKRe9LwPH.toml new file mode 100644 index 00000000000..b01e19eb5ec --- /dev/null +++ b/changes/unreleased/4775.kkLon84t7Vy5REKRe9LwPH.toml @@ -0,0 +1,5 @@ +internal = "Bump codecov/codecov-action from 5.1.2 to 5.4.2" +[[pull_requests]] +uid = "4775" +author_uid = "dependabot" +closes_threads = [] diff --git a/changes/unreleased/4776.g83DxRk4WVWCC8rCd6ocFC.toml b/changes/unreleased/4776.g83DxRk4WVWCC8rCd6ocFC.toml new file mode 100644 index 00000000000..2af8ebcd2d6 --- /dev/null +++ b/changes/unreleased/4776.g83DxRk4WVWCC8rCd6ocFC.toml @@ -0,0 +1,5 @@ +internal = "Bump actions/upload-artifact from 4.5.0 to 4.6.2" +[[pull_requests]] +uid = "4776" +author_uid = "dependabot" +closes_threads = [] diff --git a/changes/unreleased/4777.Lhgz8xFtQjgrKM2KvNfxwD.toml b/changes/unreleased/4777.Lhgz8xFtQjgrKM2KvNfxwD.toml new file mode 100644 index 00000000000..4b5e40bad26 --- /dev/null +++ b/changes/unreleased/4777.Lhgz8xFtQjgrKM2KvNfxwD.toml @@ -0,0 +1,5 @@ +internal = "Bump stefanzweifel/git-auto-commit-action from 5.1.0 to 5.2.0" +[[pull_requests]] +uid = "4777" +author_uid = "dependabot" +closes_threads = [] diff --git a/changes/unreleased/4778.CeUSPNLbGGsqP2Vo4xKkdp.toml b/changes/unreleased/4778.CeUSPNLbGGsqP2Vo4xKkdp.toml new file mode 100644 index 00000000000..c14276f7821 --- /dev/null +++ b/changes/unreleased/4778.CeUSPNLbGGsqP2Vo4xKkdp.toml @@ -0,0 +1,5 @@ +internal = "Bump github/codeql-action from 3.28.13 to 3.28.16" +[[pull_requests]] +uid = "4778" +author_uid = "dependabot" +closes_threads = [] diff --git a/changes/unreleased/4779.UqcbJVKYxwTtrBEGDgb3VS.toml b/changes/unreleased/4779.UqcbJVKYxwTtrBEGDgb3VS.toml new file mode 100644 index 00000000000..b6917ffef1b --- /dev/null +++ b/changes/unreleased/4779.UqcbJVKYxwTtrBEGDgb3VS.toml @@ -0,0 +1,5 @@ +internal = "Bump actions/download-artifact from 4.2.1 to 4.3.0" +[[pull_requests]] +uid = "4779" +author_uid = "dependabot" +closes_threads = [] diff --git a/docs/auxil/sphinx_hooks.py b/docs/auxil/sphinx_hooks.py index 53f3c4edea0..47fd9c9281c 100644 --- a/docs/auxil/sphinx_hooks.py +++ b/docs/auxil/sphinx_hooks.py @@ -15,12 +15,12 @@ # # You should have received a copy of the GNU Lesser Public License # along with this program. If not, see [http://www.gnu.org/licenses/]. -import collections.abc import contextlib import inspect import re import typing from pathlib import Path +from typing import TYPE_CHECKING from sphinx.application import Sphinx @@ -37,6 +37,10 @@ ) from docs.auxil.link_code import LINE_NUMBERS +if TYPE_CHECKING: + import collections.abc + + ADMONITION_INSERTER = AdmonitionInserter() # Some base classes are implementation detail @@ -128,7 +132,7 @@ def autodoc_process_docstring( insert_idx += len(effective_insert) ADMONITION_INSERTER.insert_admonitions( - obj=typing.cast(collections.abc.Callable, obj), + obj=typing.cast("collections.abc.Callable", obj), docstring_lines=lines, ) @@ -136,7 +140,7 @@ def autodoc_process_docstring( # (where applicable) if what == "class": ADMONITION_INSERTER.insert_admonitions( - obj=typing.cast(type, obj), # since "what" == class, we know it's not just object + obj=typing.cast("type", obj), # since "what" == class, we know it's not just object docstring_lines=lines, ) diff --git a/docs/source/conf.py b/docs/source/conf.py index fbb8b43168e..a0352d2c509 100644 --- a/docs/source/conf.py +++ b/docs/source/conf.py @@ -125,6 +125,8 @@ # The doc-fixes branch may not always exist - doesn't matter, we only link to it from the # contributing guide re.escape("https://docs.python-telegram-bot.org/en/doc-fixes"), + # Apparently has some human-verification check and gives 403 in the sphinx build + re.escape("https://stackoverflow.com/questions/tagged/python-telegram-bot"), ] linkcheck_allowed_redirects = { # Redirects to the default version are okay diff --git a/examples/arbitrarycallbackdatabot.py b/examples/arbitrarycallbackdatabot.py index e11620c1670..64971817bfb 100644 --- a/examples/arbitrarycallbackdatabot.py +++ b/examples/arbitrarycallbackdatabot.py @@ -69,7 +69,7 @@ async def list_button(update: Update, context: ContextTypes.DEFAULT_TYPE) -> Non # Get the data from the callback_data. # If you're using a type checker like MyPy, you'll have to use typing.cast # to make the checker get the expected type of the callback_data - number, number_list = cast(tuple[int, list[int]], query.data) + number, number_list = cast("tuple[int, list[int]]", query.data) # append the number to the list number_list.append(number) diff --git a/pyproject.toml b/pyproject.toml index f036d57a533..1ffe02f8efe 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -125,8 +125,7 @@ line-length = 99 show-fixes = true [tool.ruff.lint] -preview = true -explicit-preview-rules = true # TODO: Drop this when RUF022 and RUF023 are out of preview +typing-extensions = false 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", diff --git a/telegram/_bot.py b/telegram/_bot.py index cd868678611..49847efd3d4 100644 --- a/telegram/_bot.py +++ b/telegram/_bot.py @@ -829,13 +829,15 @@ async def initialize(self) -> None: return await asyncio.gather(self._request[0].initialize(), self._request[1].initialize()) + # this needs to be set before we call get_me, since this can trigger an error in the + # request backend, which would then NOT lead to a proper shutdown if this flag isn't set + self._initialized = True # Since the bot is to be initialized only once, we can also use it for # verifying the token passed and raising an exception if it's invalid. try: await self.get_me() except InvalidToken as exc: raise InvalidToken(f"The token `{self._token}` was rejected by the server.") from exc - self._initialized = True async def shutdown(self) -> None: """Stop & clear resources used by this class. Currently just calls @@ -3926,7 +3928,7 @@ async def get_file( api_kwargs=api_kwargs, ) - file_path = cast(dict, result).get("file_path") + file_path = cast("dict", result).get("file_path") if file_path and not is_local_file(file_path): result["file_path"] = f"{self._base_file_url}/{file_path}" @@ -4589,7 +4591,7 @@ async def get_updates( # waiting for the server to return and there's no way of knowing the connection had been # dropped in real time. result = cast( - list[JSONDict], + "list[JSONDict]", await self._post( "getUpdates", data, @@ -9843,13 +9845,13 @@ async def get_available_gifts( async def send_gift( self, - user_id: Optional[int] = None, - gift_id: Union[str, Gift] = None, # type: ignore + gift_id: Union[str, Gift], text: Optional[str] = None, text_parse_mode: ODVInput[str] = DEFAULT_NONE, text_entities: Optional[Sequence["MessageEntity"]] = None, pay_for_upgrade: Optional[bool] = None, chat_id: Optional[Union[str, int]] = None, + user_id: Optional[int] = None, *, read_timeout: ODVInput[float] = DEFAULT_NONE, write_timeout: ODVInput[float] = DEFAULT_NONE, @@ -9861,15 +9863,18 @@ async def send_gift( The gift can't be converted to Telegram Stars by the receiver. .. versionadded:: 21.8 + .. versionchanged:: NEXT.VERSION + Bot API 8.3 made :paramref:`user_id` optional. In version NEXT.VERSION, the methods + signature was changed accordingly. Args: + gift_id (:obj:`str` | :class:`~telegram.Gift`): Identifier of the gift or a + :class:`~telegram.Gift` object user_id (:obj:`int`, optional): Required if :paramref:`chat_id` is not specified. Unique identifier of the target user that will receive the gift. .. versionchanged:: 21.11 Now optional. - gift_id (:obj:`str` | :class:`~telegram.Gift`): Identifier of the gift or a - :class:`~telegram.Gift` object chat_id (:obj:`int` | :obj:`str`, optional): Required if :paramref:`user_id` is not specified. |chat_id_channel| It will receive the gift. @@ -9900,11 +9905,6 @@ async def send_gift( Raises: :class:`telegram.error.TelegramError` """ - # TODO: Remove when stability policy allows, tags: deprecated 21.11 - # also we should raise a deprecation warnung if anything is passed by - # position since it will be moved, not sure how - if gift_id is None: - raise TypeError("Missing required argument `gift_id`.") data: JSONDict = { "user_id": user_id, "gift_id": gift_id.id if isinstance(gift_id, Gift) else gift_id, diff --git a/telegram/_files/inputmedia.py b/telegram/_files/inputmedia.py index a36590f9746..017e1b423fe 100644 --- a/telegram/_files/inputmedia.py +++ b/telegram/_files/inputmedia.py @@ -51,13 +51,8 @@ class InputMedia(TelegramObject): Args: media_type (:obj:`str`): Type of media that the instance represents. - media (:obj:`str` | :term:`file object` | :class:`~telegram.InputFile` | :obj:`bytes` | \ - :class:`pathlib.Path` | :class:`telegram.Animation` | :class:`telegram.Audio` | \ - :class:`telegram.Document` | :class:`telegram.PhotoSize` | \ - :class:`telegram.Video`): File to send. + media (:obj:`str` | :class:`~telegram.InputFile`): File to send. |fileinputnopath| - Lastly you can pass an existing telegram media object of the corresponding type - to send. caption (:obj:`str`, optional): Caption of the media to be sent, 0-:tg-const:`telegram.constants.MessageLimit.CAPTION_LENGTH` characters after entities parsing. @@ -89,7 +84,7 @@ class InputMedia(TelegramObject): def __init__( self, media_type: str, - media: Union[str, InputFile, MediaType], + media: Union[str, InputFile], caption: Optional[str] = None, caption_entities: Optional[Sequence[MessageEntity]] = None, parse_mode: ODVInput[str] = DEFAULT_NONE, @@ -98,7 +93,7 @@ def __init__( ): super().__init__(api_kwargs=api_kwargs) self.type: str = enum.get_member(constants.InputMediaType, media_type, media_type) - self.media: Union[str, InputFile, Animation, Audio, Document, PhotoSize, Video] = media + self.media: Union[str, InputFile] = media self.caption: Optional[str] = caption self.caption_entities: tuple[MessageEntity, ...] = parse_sequence_arg(caption_entities) self.parse_mode: ODVInput[str] = parse_mode @@ -129,11 +124,8 @@ class InputPaidMedia(TelegramObject): Args: type (:obj:`str`): Type of media that the instance represents. - media (:obj:`str` | :term:`file object` | :class:`~telegram.InputFile` | :obj:`bytes` | \ - :class:`pathlib.Path` | :class:`telegram.PhotoSize` | :class:`telegram.Video`): File + media (:obj:`str` | :class:`~telegram.InputFile`): 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. @@ -150,13 +142,13 @@ class InputPaidMedia(TelegramObject): def __init__( self, type: str, # pylint: disable=redefined-builtin - media: Union[str, InputFile, PhotoSize, Video], + media: Union[str, InputFile], *, 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.media: Union[str, InputFile] = media self._freeze() diff --git a/telegram/_payment/stars/transactionpartner.py b/telegram/_payment/stars/transactionpartner.py index 4efe50cb7ee..811947581ee 100644 --- a/telegram/_payment/stars/transactionpartner.py +++ b/telegram/_payment/stars/transactionpartner.py @@ -56,7 +56,7 @@ class TransactionPartner(TelegramObject): .. versionadded:: 21.4 - ..versionchanged:: 21.11 + .. versionchanged:: 21.11 Added :class:`TransactionPartnerChat` Args: diff --git a/telegram/_telegramobject.py b/telegram/_telegramobject.py index 1b1b30ed092..ca0d20555eb 100644 --- a/telegram/_telegramobject.py +++ b/telegram/_telegramobject.py @@ -290,7 +290,7 @@ def __setstate__(self, state: dict[str, object]) -> None: self._bot = None # get api_kwargs first because we may need to add entries to it (see try-except below) - api_kwargs = cast(dict[str, object], state.pop("api_kwargs", {})) + api_kwargs = cast("dict[str, object]", state.pop("api_kwargs", {})) # get _frozen before the loop to avoid setting it to True in the loop frozen = state.pop("_frozen", False) diff --git a/telegram/_utils/files.py b/telegram/_utils/files.py index 8bce30d64c5..a750e1512e1 100644 --- a/telegram/_utils/files.py +++ b/telegram/_utils/files.py @@ -59,7 +59,7 @@ def load_file( try: contents = obj.read() # type: ignore[union-attr] except AttributeError: - return None, cast(Union[bytes, "InputFile", str, Path], obj) + return None, cast("Union[bytes, InputFile, str, Path]", obj) filename = guess_file_name(obj) @@ -151,7 +151,7 @@ def parse_file_input( # pylint: disable=too-many-return-statements if isinstance(file_input, bytes): return InputFile(file_input, filename=filename, attach=attach) if hasattr(file_input, "read"): - return InputFile(cast(IO, file_input), filename=filename, attach=attach) + return InputFile(cast("IO", file_input), filename=filename, attach=attach) if tg_type and isinstance(file_input, tg_type): return file_input.file_id # type: ignore[attr-defined] return file_input diff --git a/telegram/ext/_application.py b/telegram/ext/_application.py index 423e08b4f2f..e856fa85321 100644 --- a/telegram/ext/_application.py +++ b/telegram/ext/_application.py @@ -355,7 +355,7 @@ def __init__( self.__create_task_tasks: set[asyncio.Task] = set() # Used for awaiting tasks upon exit self.__stop_running_marker = asyncio.Event() - async def __aenter__(self: _AppType) -> _AppType: # noqa: PYI019 + async def __aenter__(self: _AppType) -> _AppType: """|async_context_manager| :meth:`initializes ` the App. Returns: diff --git a/telegram/ext/_baseupdateprocessor.py b/telegram/ext/_baseupdateprocessor.py index ea9649d1f68..c08afec0b41 100644 --- a/telegram/ext/_baseupdateprocessor.py +++ b/telegram/ext/_baseupdateprocessor.py @@ -74,7 +74,7 @@ def __init__(self, max_concurrent_updates: int): raise ValueError("`max_concurrent_updates` must be a positive integer!") self._semaphore = TrackedBoundedSemaphore(self.max_concurrent_updates) - async def __aenter__(self: _BUPT) -> _BUPT: # noqa: PYI019 + async def __aenter__(self: _BUPT) -> _BUPT: """|async_context_manager| :meth:`initializes ` the Processor. Returns: diff --git a/telegram/ext/_callbackdatacache.py b/telegram/ext/_callbackdatacache.py index 1052bd5a2a5..a24befd719d 100644 --- a/telegram/ext/_callbackdatacache.py +++ b/telegram/ext/_callbackdatacache.py @@ -347,7 +347,7 @@ def __process_message(self, message: Message) -> Optional[str]: for row in message.reply_markup.inline_keyboard: for button in row: if button.callback_data: - button_data = cast(str, button.callback_data) + button_data = cast("str", button.callback_data) keyboard_id, callback_data = self.__get_keyboard_uuid_and_button_data( button_data ) diff --git a/telegram/ext/_dictpersistence.py b/telegram/ext/_dictpersistence.py index da9749dfc85..758a8dd5436 100644 --- a/telegram/ext/_dictpersistence.py +++ b/telegram/ext/_dictpersistence.py @@ -145,7 +145,7 @@ def __init__( self._callback_data = None else: self._callback_data = cast( - CDCData, + "CDCData", ([(one, float(two), three) for one, two, three in data[0]], data[1]), ) self._callback_data_json = callback_data_json diff --git a/telegram/ext/_extbot.py b/telegram/ext/_extbot.py index f77cfbf631b..15b969fd85d 100644 --- a/telegram/ext/_extbot.py +++ b/telegram/ext/_extbot.py @@ -62,6 +62,7 @@ InlineKeyboardMarkup, InlineQueryResultsButton, InputMedia, + InputPaidMedia, InputPollOption, LinkPreviewOptions, Location, @@ -114,7 +115,6 @@ InputMediaDocument, InputMediaPhoto, InputMediaVideo, - InputPaidMedia, InputSticker, LabeledPrice, MessageEntity, @@ -253,7 +253,7 @@ def __init__( return if not isinstance(arbitrary_callback_data, bool): - maxsize = cast(int, arbitrary_callback_data) + maxsize = cast("int", arbitrary_callback_data) else: maxsize = 1024 @@ -466,7 +466,11 @@ def _insert_defaults(self, data: dict[str, object]) -> None: with copied_val._unfrozen(): copied_val.parse_mode = self.defaults.parse_mode data[key] = copied_val - elif key == "media" and isinstance(val, Sequence): + elif ( + key == "media" + and isinstance(val, Sequence) + and not isinstance(val[0], InputPaidMedia) + ): # Copy objects as not to edit them in-place copy_list = [copy(media) for media in val] for media in copy_list: @@ -4476,13 +4480,13 @@ async def get_available_gifts( async def send_gift( self, - user_id: Optional[int] = None, - gift_id: Union[str, Gift] = None, # type: ignore + gift_id: Union[str, Gift], text: Optional[str] = None, text_parse_mode: ODVInput[str] = DEFAULT_NONE, text_entities: Optional[Sequence["MessageEntity"]] = None, pay_for_upgrade: Optional[bool] = None, chat_id: Optional[Union[str, int]] = None, + user_id: Optional[int] = None, *, read_timeout: ODVInput[float] = DEFAULT_NONE, write_timeout: ODVInput[float] = DEFAULT_NONE, diff --git a/telegram/ext/_handlers/callbackqueryhandler.py b/telegram/ext/_handlers/callbackqueryhandler.py index b09f8249c35..27ddc5b2ec4 100644 --- a/telegram/ext/_handlers/callbackqueryhandler.py +++ b/telegram/ext/_handlers/callbackqueryhandler.py @@ -204,5 +204,5 @@ def collect_additional_context( :attr:`CallbackContext.matches` as list with one element. """ if self.pattern: - check_result = cast(Match, check_result) + check_result = cast("Match", check_result) context.matches = [check_result] diff --git a/telegram/ext/_handlers/choseninlineresulthandler.py b/telegram/ext/_handlers/choseninlineresulthandler.py index 3bc80ed144b..2faa0bc862c 100644 --- a/telegram/ext/_handlers/choseninlineresulthandler.py +++ b/telegram/ext/_handlers/choseninlineresulthandler.py @@ -118,5 +118,5 @@ def collect_additional_context( :attr:`telegram.ext.CallbackContext.matches`. """ if self.pattern: - check_result = cast(Match, check_result) + check_result = cast("Match", check_result) context.matches = [check_result] diff --git a/telegram/ext/_handlers/conversationhandler.py b/telegram/ext/_handlers/conversationhandler.py index 1bc5f0398de..dd824bf5601 100644 --- a/telegram/ext/_handlers/conversationhandler.py +++ b/telegram/ext/_handlers/conversationhandler.py @@ -599,7 +599,7 @@ async def _initialize_persistence( current_conversations = self._conversations self._conversations = cast( - TrackingDict[ConversationKey, object], + "TrackingDict[ConversationKey, object]", TrackingDict(), ) # In the conversation already processed updates @@ -924,7 +924,7 @@ async def _trigger_timeout(self, context: CCT) -> None: :obj:`True` is handled. """ job = cast("Job", context.job) - ctxt = cast(_ConversationTimeoutContext, job.data) + ctxt = cast("_ConversationTimeoutContext", job.data) _LOGGER.debug( "Conversation timeout was triggered for conversation %s!", ctxt.conversation_key diff --git a/telegram/ext/_handlers/inlinequeryhandler.py b/telegram/ext/_handlers/inlinequeryhandler.py index 31106ba33a6..0285d259c25 100644 --- a/telegram/ext/_handlers/inlinequeryhandler.py +++ b/telegram/ext/_handlers/inlinequeryhandler.py @@ -139,5 +139,5 @@ def collect_additional_context( :attr:`CallbackContext.matches` as list with one element. """ if self.pattern: - check_result = cast(Match, check_result) + check_result = cast("Match", check_result) context.matches = [check_result] diff --git a/telegram/ext/_picklepersistence.py b/telegram/ext/_picklepersistence.py index c2f4c01e383..1602eabed0e 100644 --- a/telegram/ext/_picklepersistence.py +++ b/telegram/ext/_picklepersistence.py @@ -237,7 +237,7 @@ def __init__( self.callback_data: Optional[CDCData] = None self.conversations: Optional[dict[str, dict[tuple[Union[int, str], ...], object]]] = None self.context_types: ContextTypes[Any, UD, CD, BD] = cast( - ContextTypes[Any, UD, CD, BD], context_types or ContextTypes() + "ContextTypes[Any, UD, CD, BD]", context_types or ContextTypes() ) def _load_singlefile(self) -> None: diff --git a/telegram/ext/_updater.py b/telegram/ext/_updater.py index a2a921672dd..95f7e225ed1 100644 --- a/telegram/ext/_updater.py +++ b/telegram/ext/_updater.py @@ -124,7 +124,7 @@ def __init__( self.__polling_task_stop_event: asyncio.Event = asyncio.Event() self.__polling_cleanup_cb: Optional[Callable[[], Coroutine[Any, Any, None]]] = None - async def __aenter__(self: _UpdaterType) -> _UpdaterType: # noqa: PYI019 + async def __aenter__(self: _UpdaterType) -> _UpdaterType: """ |async_context_manager| :meth:`initializes ` the Updater. diff --git a/telegram/ext/filters.py b/telegram/ext/filters.py index 8757fe3e7d8..a1e8030f7b4 100644 --- a/telegram/ext/filters.py +++ b/telegram/ext/filters.py @@ -1588,10 +1588,10 @@ class Language(MessageFilter): def __init__(self, lang: SCT[str]): if isinstance(lang, str): - lang = cast(str, lang) + lang = cast("str", lang) self.lang: Sequence[str] = [lang] else: - lang = cast(list[str], lang) + lang = cast("list[str]", lang) self.lang = lang super().__init__(name=f"filters.Language({self.lang})") diff --git a/tests/_files/test_inputmedia.py b/tests/_files/test_inputmedia.py index b362411cbd8..a077c309cc5 100644 --- a/tests/_files/test_inputmedia.py +++ b/tests/_files/test_inputmedia.py @@ -710,7 +710,6 @@ async def test_send_media_group_with_thumbs( self, offline_bot, chat_id, video_file, photo_file, monkeypatch ): async def make_assertion(method, url, request_data: RequestData, *args, **kwargs): - nonlocal input_video files = request_data.multipart_data video_check = files[input_video.media.attach_name] == input_video.media.field_tuple thumb_check = ( diff --git a/tests/auxil/bot_method_checks.py b/tests/auxil/bot_method_checks.py index ca7b041be5c..f7f43088681 100644 --- a/tests/auxil/bot_method_checks.py +++ b/tests/auxil/bot_method_checks.py @@ -35,6 +35,7 @@ InlineQueryResultArticle, InlineQueryResultCachedPhoto, InputMediaPhoto, + InputPaidMediaPhoto, InputTextMessageContent, LinkPreviewOptions, ReplyParameters, @@ -285,8 +286,13 @@ def build_kwargs( elif name in ["prices", "commands", "errors"]: kws[name] = [] elif name == "media": - media = InputMediaPhoto("media", parse_mode=manually_passed_value) - if "list" in str(param.annotation).lower(): + if "star_count" in signature.parameters: + media = InputPaidMediaPhoto("media") + else: + media = InputMediaPhoto("media", parse_mode=manually_passed_value) + + param_annotation = str(param.annotation).lower() + if "sequence" in param_annotation or "list" in param_annotation: kws[name] = [media] else: kws[name] = media @@ -351,9 +357,6 @@ def build_kwargs( allow_sending_without_reply=manually_passed_value, quote_parse_mode=manually_passed_value, ) - # TODO remove when gift_id isnt marked as optional anymore, tags: deprecated 21.11 - elif name == "gift_id": - kws[name] = "GIFT-ID" return kws @@ -510,7 +513,8 @@ def check_input_media(m: dict): ) media = data.pop("media", None) - if media: + paid_media = media and data.pop("star_count", None) + if media and not paid_media: if isinstance(media, dict) and isinstance(media.get("type", None), InputMediaType): check_input_media(media) else: @@ -617,7 +621,7 @@ async def check_defaults_handling( kwargs_need_default.remove("parse_mode") defaults_no_custom_defaults = Defaults() - kwargs = {kwarg: "custom_default" for kwarg in inspect.signature(Defaults).parameters} + kwargs = dict.fromkeys(inspect.signature(Defaults).parameters, "custom_default") kwargs["tzinfo"] = zoneinfo.ZoneInfo("America/New_York") kwargs["link_preview_options"] = LinkPreviewOptions( url="custom_default", show_above_text="custom_default" diff --git a/tests/ext/test_application.py b/tests/ext/test_application.py index 8de4c8ed0d0..fd96aa99e1f 100644 --- a/tests/ext/test_application.py +++ b/tests/ext/test_application.py @@ -16,8 +16,7 @@ # # You should have received a copy of the GNU Lesser Public License # along with this program. If not, see [http://www.gnu.org/licenses/]. -"""The integration of persistence into the application is tested in test_basepersistence. -""" +"""The integration of persistence into the application is tested in test_basepersistence.""" import asyncio import functools import inspect diff --git a/tests/ext/test_applicationbuilder.py b/tests/ext/test_applicationbuilder.py index 519b8b28194..15e85b6416e 100644 --- a/tests/ext/test_applicationbuilder.py +++ b/tests/ext/test_applicationbuilder.py @@ -426,7 +426,6 @@ def test_custom_socket_options(self, builder, monkeypatch, bot): httpx_request_init = HTTPXRequest.__init__ def init_transport(*args, **kwargs): - nonlocal httpx_request_kwargs # This is called once for request and once for get_updates_request, so we make # it a list httpx_request_kwargs.append(kwargs.copy()) diff --git a/tests/ext/test_conversationhandler.py b/tests/ext/test_conversationhandler.py index 7d8b7ddb946..e57c1faa373 100644 --- a/tests/ext/test_conversationhandler.py +++ b/tests/ext/test_conversationhandler.py @@ -1438,7 +1438,7 @@ async def test_conversation_handler_timeout_update_and_context(self, app, bot, u context = None async def start_callback(u, c): - nonlocal context, self + nonlocal context context = c return await self.start(u, c) @@ -1459,7 +1459,6 @@ async def start_callback(u, c): update = Update(update_id=0, message=message) async def timeout_callback(u, c): - nonlocal update, context assert u is update assert c is context diff --git a/tests/test_bot.py b/tests/test_bot.py index eefd07b568d..22ffc9accc7 100644 --- a/tests/test_bot.py +++ b/tests/test_bot.py @@ -402,6 +402,21 @@ async def shutdown(): assert self.test_flag == "stop" + async def test_shutdown_at_error_in_request_in_init(self, monkeypatch, offline_bot): + async def get_me_error(): + raise httpx.HTTPError("BadRequest wrong token sry :(") + + async def shutdown(*args): + self.test_flag = "stop" + + monkeypatch.setattr(offline_bot, "get_me", get_me_error) + monkeypatch.setattr(offline_bot, "shutdown", shutdown) + + async with offline_bot: + pass + + assert self.test_flag == "stop" + async def test_equality(self): async with ( make_bot(token=FALLBACKS[0]["token"]) as a, @@ -528,7 +543,7 @@ def test_api_kwargs_and_timeouts_present(self, bot_class, bot_method_name, bot_m if bot_method_name.replace("_", "").lower() != "getupdates" and bot_class is ExtBot: assert rate_arg in param_names, f"{bot_method} is missing the parameter `{rate_arg}`" - @bot_methods(ext_bot=False) + @bot_methods() async def test_defaults_handling( self, bot_class, diff --git a/tests/test_chat.py b/tests/test_chat.py index 5e01ad526a4..f53a0fdd2fe 100644 --- a/tests/test_chat.py +++ b/tests/test_chat.py @@ -1330,15 +1330,7 @@ async def make_assertion_channel(*_, **kwargs): and kwargs["text_entities"] == "text_entities" ) - # TODO discuss if better way exists - # tags: deprecated 21.11 - with pytest.raises( - Exception, - match="Default for argument gift_id does not match the default of the Bot method.", - ): - assert check_shortcut_signature( - Chat.send_gift, Bot.send_gift, ["user_id", "chat_id"], [] - ) + assert check_shortcut_signature(Chat.send_gift, Bot.send_gift, ["user_id", "chat_id"], []) assert await check_shortcut_call( chat.send_gift, chat.get_bot(), "send_gift", ["user_id", "chat_id"] ) diff --git a/tests/test_gifts.py b/tests/test_gifts.py index 5af1dc58cf1..3b3ef52cb39 100644 --- a/tests/test_gifts.py +++ b/tests/test_gifts.py @@ -135,40 +135,8 @@ def test_equality(self, gift): ], ids=["string", "Gift"], ) - async def test_send_gift(self, offline_bot, gift, monkeypatch): - # We can't send actual gifts, so we just check that the correct parameters are passed - text_entities = [ - MessageEntity(MessageEntity.TEXT_LINK, 0, 4, "url"), - MessageEntity(MessageEntity.BOLD, 5, 9), - ] - - async def make_assertion(url, request_data: RequestData, *args, **kwargs): - user_id = request_data.parameters["user_id"] == "user_id" - gift_id = request_data.parameters["gift_id"] == "gift_id" - text = request_data.parameters["text"] == "text" - text_parse_mode = request_data.parameters["text_parse_mode"] == "text_parse_mode" - tes = request_data.parameters["text_entities"] == [ - me.to_dict() for me in text_entities - ] - pay_for_upgrade = request_data.parameters["pay_for_upgrade"] is True - - return user_id and gift_id and text and text_parse_mode and tes and pay_for_upgrade - - monkeypatch.setattr(offline_bot.request, "post", make_assertion) - assert await offline_bot.send_gift( - "user_id", - gift, - "text", - text_parse_mode="text_parse_mode", - text_entities=text_entities, - pay_for_upgrade=True, - ) - @pytest.mark.parametrize("id_name", ["user_id", "chat_id"]) - async def test_send_gift_user_chat_id(self, offline_bot, gift, monkeypatch, id_name): - # Only here because we have to temporarily mark gift_id as optional. - # tags: deprecated 21.11 - + async def test_send_gift(self, offline_bot, gift, monkeypatch, id_name): # We can't send actual gifts, so we just check that the correct parameters are passed text_entities = [ MessageEntity(MessageEntity.TEXT_LINK, 0, 4, "url"), @@ -177,7 +145,7 @@ async def test_send_gift_user_chat_id(self, offline_bot, gift, monkeypatch, id_n async def make_assertion(url, request_data: RequestData, *args, **kwargs): received_id = request_data.parameters[id_name] == id_name - gift_id = request_data.parameters["gift_id"] == "some_id" + gift_id = request_data.parameters["gift_id"] == "gift_id" text = request_data.parameters["text"] == "text" text_parse_mode = request_data.parameters["text_parse_mode"] == "text_parse_mode" tes = request_data.parameters["text_entities"] == [ @@ -189,18 +157,14 @@ async def make_assertion(url, request_data: RequestData, *args, **kwargs): monkeypatch.setattr(offline_bot.request, "post", make_assertion) assert await offline_bot.send_gift( - gift_id=gift, - text="text", + gift, + "text", text_parse_mode="text_parse_mode", text_entities=text_entities, pay_for_upgrade=True, **{id_name: id_name}, ) - async def test_send_gift_without_gift_id(self, offline_bot): - with pytest.raises(TypeError, match="Missing required argument `gift_id`."): - await offline_bot.send_gift() - @pytest.mark.parametrize("default_bot", [{"parse_mode": "Markdown"}], indirect=True) @pytest.mark.parametrize( ("passed_value", "expected_value"), diff --git a/tests/test_official/exceptions.py b/tests/test_official/exceptions.py index fdc04adc553..d0d73fa4b7b 100644 --- a/tests/test_official/exceptions.py +++ b/tests/test_official/exceptions.py @@ -19,7 +19,7 @@ """This module contains exceptions to our API compared to the official API.""" import datetime as dtm -from telegram import Animation, Audio, Document, PhotoSize, Sticker, Video, VideoNote, Voice +from telegram import Animation, Audio, Document, Gift, PhotoSize, Sticker, Video, VideoNote, Voice from tests.test_official.helpers import _get_params_base IGNORED_OBJECTS = ("ResponseParameters",) @@ -47,8 +47,7 @@ class ParamTypeCheckingExceptions: "animation": Animation, "voice": Voice, "sticker": Sticker, - # TODO: Deprecated and will be corrected (and readded) in next major bot API release: - # "gift_id": Gift, + "gift_id": Gift, }, "(delete|set)_sticker.*": { "sticker$": Sticker, @@ -101,9 +100,6 @@ class ParamTypeCheckingExceptions: "EncryptedPassportElement": { "data": str, # actual: Union[IdDocumentData, PersonalDetails, ResidentialAddress] }, - # TODO: Deprecated and will be corrected (and removed) in next major PTB - # version: - "send_gift": {"gift_id": str}, # actual: Non optional } # param names ignored in the param type checking in classes for the `tg.Defaults` case. @@ -196,8 +192,6 @@ def ptb_ignored_params(object_name: str) -> set[str]: "send_venue": {"latitude", "longitude", "title", "address"}, "send_contact": {"phone_number", "first_name"}, # ----> - # here for backwards compatibility. Todo: remove on next bot api release - "send_gift": {"gift_id"}, } diff --git a/tests/test_official/test_official.py b/tests/test_official/test_official.py index 9b0a418a2bb..b699a2b2eea 100644 --- a/tests/test_official/test_official.py +++ b/tests/test_official/test_official.py @@ -138,11 +138,6 @@ def test_check_object(tg_class: TelegramClass) -> None: - No unexpected parameters """ obj = getattr(telegram, tg_class.class_name) - if tg_class.class_name not in ( - "PassportElementErrorFiles", - "PassportElementErrorTranslationFiles", - ): - return # Check arguments based on source. Makes sure to only check __init__'s signature & nothing else sig = inspect.signature(obj.__init__, follow_wrapped=True) diff --git a/tests/test_user.py b/tests/test_user.py index 815785bcb7f..b7ea5f8bd26 100644 --- a/tests/test_user.py +++ b/tests/test_user.py @@ -731,15 +731,7 @@ async def make_assertion(*_, **kwargs): and kwargs["text_entities"] == "text_entities" ) - # TODO discuss if better way exists - # tags: deprecated 21.11 - with pytest.raises( - Exception, - match="Default for argument gift_id does not match the default of the Bot method.", - ): - assert check_shortcut_signature( - user.send_gift, Bot.send_gift, ["user_id", "chat_id"], [] - ) + assert check_shortcut_signature(user.send_gift, Bot.send_gift, ["user_id", "chat_id"], []) assert await check_shortcut_call( user.send_gift, user.get_bot(), "send_gift", ["chat_id", "user_id"] )