Skip to content

Beta #72

Merged
5hojib merged 22 commits intomainfrom
beta
Feb 14, 2026
Merged

Beta #72
5hojib merged 22 commits intomainfrom
beta

Conversation

@5hojib
Copy link
Member

@5hojib 5hojib commented Feb 14, 2026

Summary by Sourcery

Refresh documentation styling and MTProto schema integration, add automated schema update tooling, adjust business payment API naming, and tighten dependencies and CI branches.

New Features:

  • Introduce automated MTProto API schema fetch-and-update tooling with a scheduled GitHub Actions workflow.
  • Add categorized enum documentation pages, including a dedicated ButtonStyle enum page.
  • Expose new Str and Link types across public type packages and business refund_stars_payment aliasing.

Bug Fixes:

  • Correct various TL schema flag orders, field names, and removed/added constructors to match current API behavior.
  • Ensure error generation recreates destination packages cleanly and initializes init correctly.
  • Keep CI workflows targeting beta and main branches appropriately for docs, tests, and publishing.

Enhancements:

  • Modernize docs theme appearance with updated typography, code blocks, tables, scrollbars, and header styling.
  • Improve Sphinx configuration with preserved defaults, extra warning suppression, custom fonts, and additional theme features.
  • Refactor error compiler paths and template handling for more robust, path-safe generation.
  • Align TL schema (main_api.tl) with upstream Telegram Desktop definitions and layer metadata.
  • Update dev and docs dependencies to pinned minimum versions in pyproject.toml and lock files.
  • Fix minor docstring and reference issues in Chat type documentation and align business refund method naming.

Build:

  • Tighten core, dev, and docs dependency versions and regenerate associated lockfiles to reflect updated constraints.

CI:

  • Retarget docs and format/test workflows to run on the beta branch and adjust publish workflow to trigger from main.
  • Add scheduled workflow to periodically check MTProto API schema updates and open/update PRs automatically.

Deployment:

  • Automate MTProto schema updates through a dedicated workflow that compiles API and error modules and pushes update branches.

Documentation:

  • Restructure enums documentation index into logical categories and generate per-enum pages.
  • Create placeholder docs for decorators and support sections and wire new ButtonStyle enum documentation.
  • Visually refine documentation via custom CSS and Sphinx theme options.

Chores:

  • Introduce dev_tools/check_api_schema_updates.py utility for fetching, normalizing, and writing the latest MTProto schema.

5hojib and others added 22 commits February 10, 2026 18:40
Signed-off-by: 5hojib <yesiamshojib@gmail.com>
Signed-off-by: 5hojib <yesiamshojib@gmail.com>
Signed-off-by: 5hojib <yesiamshojib@gmail.com>
Signed-off-by: 5hojib <yesiamshojib@gmail.com>
Updates the requirements on [sphinx](https://github.com/sphinx-doc/sphinx) to permit the latest version.
- [Release notes](https://github.com/sphinx-doc/sphinx/releases)
- [Changelog](https://github.com/sphinx-doc/sphinx/blob/v8.1.3/CHANGES.rst)
- [Commits](sphinx-doc/sphinx@v0.1.61611...v8.1.3)

---
updated-dependencies:
- dependency-name: sphinx
  dependency-version: 8.1.3
  dependency-type: direct:development
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Signed-off-by: 5hojib <yesiamshojib@gmail.com>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
This commit updates top-level dependency constraints in `pyproject.toml` to their latest compatible versions and regenerates all lock files (`uv.lock`, `requirements.lock`, and `requirements-dev.lock`).

Key changes:
- Updated `pysocks`, `aiosqlite`, `pymediainfo`, `pymongo`, `ElectroCrypto`, and `anyio` minimum versions in `pyproject.toml`.
- Bumped `hatch` and `pytest` minimum versions in `dev` extra.
- Updated `sphinx` constraint to `<10.0.0` and added minimum versions for other documentation and development tools.
- Regenerated `uv.lock` with latest compatible versions.
- Re-exported `requirements.lock` and `requirements-dev.lock` with hashes using `uv export`, ensuring consistency across dependency management tools.
- Verified all tests pass in the updated environment.

Co-authored-by: google-labs-jules[bot] <161369871+google-labs-jules[bot]@users.noreply.github.com>
- Updated `compiler/docs/compiler.py` to support categorized Enums.
- Enhanced documentation visuals with modern fonts (Inter, JetBrains Mono) and theme features (instant navigation).
- Refined `docs/source/_static/css/custom.css` for a modern minimalist UI with backdrop-filter blurs and improved typography.
- Improved `docs/source/index.rst` layout for a better first impression.
- Fixed typo in enum filename: renamed `listerner_types.py` to `listener_types.py`.
- Regenerated all API and documentation files.

Co-authored-by: google-labs-jules[bot] <161369871+google-labs-jules[bot]@users.noreply.github.com>
- Fixed duplicate and missing decorators in `docs/source/api/decorators.rst`.
- Renamed `refund_star_payment` to `refund_stars_payment` and `RefundStarPayment` to `RefundStarsPayment` for consistency with Telegram's terminology, with backward compatibility aliases.
- Fixed a cut-off docstring in `pyrogram/types/user_and_chats/chat.py`.
- Exported `Str` and `Link` types in `pyrogram.types` to resolve Sphinx import failures.
- Removed a trailing transition in `docs/source/support.rst` that caused a docutils warning.
- Configured Sphinx to preserve default values and suppress lexing warnings for better documentation output.
- Verified that documentation now builds with zero warnings.

Co-authored-by: google-labs-jules[bot] <161369871+google-labs-jules[bot]@users.noreply.github.com>
Signed-off-by: 5hojib <yesiamshojib@gmail.com>
* perf: optimize TL object serialization with buffer passing

This change transitions the serialization process from a recursive "return bytes"
pattern to a "write to buffer" pattern. By passing a shared BytesIO buffer
through nested write calls, we avoid many redundant memory allocations and
byte-copying operations, which significantly improves performance for large
and deeply nested TL objects.

Key changes:
- Added optional `b: BytesIO` parameter to `TLObject.write`.
- Optimized Primitives (Int, Long, Bytes, String, Vector, Bool) to support
  writing directly to a buffer.
- Updated the API compiler and templates to generate optimized serialization
  logic for thousands of raw API classes.
- Updated manually implemented core objects (Message, GzipPacked, etc.).
- Pre-calculated Boolean byte constants.

Co-authored-by: 5hojib <107526130+5hojib@users.noreply.github.com>

* perf: refine TL object serialization and fix review issues

- Explicitly delegate String.write to Bytes.write.
- Use Int.write for Vector constructor ID instead of hardcoded literal.
- Ensure BytesIO is imported at runtime in all primitive files.
- Add missing write methods to Bool and Double primitives.
- Optimize Vector.write to use inner type's write method.
- Regenerate raw API with refined templates.

Co-authored-by: 5hojib <107526130+5hojib@users.noreply.github.com>

---------

Co-authored-by: google-labs-jules[bot] <161369871+google-labs-jules[bot]@users.noreply.github.com>
Signed-off-by: 5hojib <yesiamshojib@gmail.com>
Signed-off-by: 5hojib <yesiamshojib@gmail.com>
@sourcery-ai
Copy link
Contributor

sourcery-ai bot commented Feb 14, 2026

Reviewer's Guide

Refactors MTProto API schema handling and error compiler paths, introduces an automated schema update workflow and dev tool, updates dependencies and documentation styling/structure, and renames the business stars refund API while keeping it backward compatible.

Updated class diagram for business stars refund API

classDiagram
    class Client

    class RefundStarsPayment {
        +async refund_stars_payment(self, user_id, telegram_payment_charge_id) bool
        +refund_star_payment(self, user_id, telegram_payment_charge_id) bool
    }

    class TelegramBusiness {
    }

    class raw_functions_payments_RefundStarsCharge {
    }

    Client <|.. RefundStarsPayment : used_as_self
    TelegramBusiness <|-- RefundStarsPayment

    RefundStarsPayment ..> raw_functions_payments_RefundStarsCharge : uses
Loading

File-Level Changes

Change Details Files
Modernizes Sphinx docs styling and configuration, including typography, components, and warning handling.
  • Add custom blurred header, typography tweaks, rounded code blocks, enhanced tables, scrollbars, and badges in custom CSS
  • Configure Sphinx to preserve defaults, suppress highlighting warnings, and extend theme options with fonts and extra features
docs/source/_static/css/custom.css
docs/source/conf.py
Refactors error compiler to use robust Path-based paths and cleaner string manipulation for generating error classes.
  • Replace global string paths with Path-based constants resolved from the module location
  • Simplify camel/snake helpers and string transformations
  • Ensure destination directory recreation, init file creation, and template reading are done safely
  • Use Path.read_text/write_text for final placeholder replacement
compiler/errors/compiler.py
Realigns MTProto TL schema to upstream tdesktop API.tl and cleans up unused/changed constructors and functions.
  • Replace legacy header/primitive definitions with a fixed header pointing to upstream schema
  • Apply multiple constructor flag/field adjustments (e.g., chats, star gifts, keyboard buttons, requestPeer* types, transactions)
  • Remove deprecated types/functions and adjust IDs where needed (e.g., invokeWithApnsSecret)
  • Update layer comment from 224 to 222
compiler/api/source/main_api.tl
Improves docs generation for enums by grouping them into semantic categories.
  • Introduce ENUMS_CATEGORIES mapping for high-level enum groups
  • Generate enums index.rst grouped by category sections with autosummary and hidden toctrees instead of a single flat list
compiler/docs/compiler.py
Updates runtime and dev dependencies with minimum versions and refreshes lockfiles/uv metadata.
  • Add minimum versions for core dependencies and dev/doc extras
  • Bump Sphinx and theme constraints, and pin tornado and related tooling
  • Regenerate requirements.lock, requirements-dev.lock, and uv.lock to match new constraints
pyproject.toml
requirements.lock
requirements-dev.lock
uv.lock
Renames the business refund stars API for clarity while keeping backwards compatibility and updates exports and docs.
  • Rename RefundStarPayment class/method to RefundStarsPayment/refund_stars_payment and adjust docstring and example
  • Add alias method refund_star_payment pointing to refund_stars_payment and class alias RefundStarPayment
  • Update TelegramBusiness mixin import to use the new class name
pyrogram/methods/business/refund_stars_payment.py
pyrogram/methods/business/__init__.py
Tweaks public types and docstrings for correctness and adds new exported types.
  • Export new Str and Link types from types/init and per-subpackage in messages_and_media and user_and_chats
  • Fix Chat.join_requests_count docstring reference to Client.get_chat
pyrogram/types/__init__.py
pyrogram/types/messages_and_media/__init__.py
pyrogram/types/user_and_chats/__init__.py
pyrogram/types/user_and_chats/chat.py
Adjusts CI workflows to target the correct branches and decouple docs/tests from experimental branches.
  • Change docs and format/test workflows to trigger on beta instead of test
  • Change tag_and_publish workflow to trigger on main instead of dev
.github/workflows/docs_gen.yml
.github/workflows/format_and_test.yml
.github/workflows/tag_and_publish.yml
Adds an automated MTProto API schema update tool and scheduled GitHub workflow that opens/updates PRs on schema changes.
  • Introduce dev_tools/check_api_schema_updates.py to fetch upstream api.tl, normalize it, compute hashes, and update local main_api.tl
  • Add fetch_mtproto.yml workflow to periodically run the checker, compile API and errors, push changes to a dedicated branch, and create/update PRs
dev_tools/check_api_schema_updates.py
.github/workflows/fetch_mtproto.yml
Prepares documentation stubs for new enums and reorganized docs structure.
  • Add ButtonStyle enum doc stub and touch other RST index/support files to align with new structure
  • Align top-level docs index and support pages with the new style and enums grouping
docs/source/api/enums/ButtonStyle.rst
docs/source/api/decorators.rst
docs/source/api/enums/index.rst
docs/source/index.rst
docs/source/support.rst

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello @5hojib, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request focuses on updating the project's core API definitions to align with the latest Telegram schema, enhancing the user documentation for a more modern and organized experience, and streamlining the development workflow through dependency management migration and automation. These changes collectively improve the project's maintainability, clarity, and adherence to current standards.

Highlights

  • API Schema Update: The Telegram API schema has been updated from Layer 224 to Layer 222, involving extensive cleanup and removal of deprecated types and flags across various API definitions.
  • Documentation Overhaul: The project documentation has received a significant visual and structural overhaul, including modern styling, typography refinements, improved code blocks, categorized enum listings, and enhanced navigation features.
  • Dependency Management Migration: The project's dependency management has migrated from rye to uv, resulting in updated lockfiles and version constraints for both core and development dependencies.
  • Automated Schema Updates: A new development tool has been introduced to automate the process of checking for and applying updates to the Telegram API schema, ensuring the project stays current with upstream changes.
  • Codebase Refinements: Various code quality improvements were made, including refactoring path handling to use pathlib.Path, simplifying string manipulations, correcting typos in enum names and docstrings, and renaming RefundStarPayment to RefundStarsPayment for consistency.
Changelog
  • compiler/api/source/main_api.tl
    • Removed outdated comments and basic type definitions.
    • Updated API layer from 224 to 222.
    • Removed userStatusHidden and kicked flag from chat definition.
    • Modified messageActionStarGift and messageActionStarGiftUnique flags.
    • Removed several MessageAction types and inputMessagesFilterPhotoVideoDocuments.
    • Removed updateTranscribeAudio and updateBotSubscriptionExpire.
    • Removed webPageUrlPending and contacts.importCard.
    • Adjusted flag order and type references in KeyboardButton related types.
    • Removed can_save_credentials and password_missing flags from payments.paymentFormStars.
    • Removed channelAdminLogEventActionChangeTheme.
    • Removed title_missing flag from forumTopic.
    • Reordered flags in requestPeerTypeChat and requestPeerTypeBroadcast.
    • Removed revoked flag from exportedChatlistInvite and chatlists.editExportedInvite.
    • Removed subscription, paid_message, premium_gift flags from starsTransaction.
    • Removed can_upgrade flag from starGift.
    • Removed anonymous flag from groupCallDonor.
    • Reordered StarGiftAttributeRarity types and removed messages.messageEmpty, premiumGiftOption, messages.webViewResult.
    • Corrected invokeWithApnsSecret hash.
    • Removed several messages functions and moved payments.getCraftStarGifts and payments.craftStarGift to the payments section.
  • compiler/docs/compiler.py
    • Added enum categorization logic for improved documentation structure.
    • Modified enum documentation generation to group enums by category.
  • compiler/errors/compiler.py
    • Refactored path handling to use pathlib.Path for better maintainability.
    • Simplified string manipulation for class and method naming.
  • dev_tools/check_api_schema_updates.py
    • Added a new script to automate fetching, processing, and updating the Telegram API schema.
  • docs/source/_static/css/custom.css
    • Implemented a modern design for the documentation, including header blur, typography, code blocks, badges, links, tables, and scrollbars.
  • docs/source/api/decorators.rst
    • Added new decorator references for on_shipping_query and on_pre_checkout_query.
    • Removed a duplicate decorator reference.
  • docs/source/api/enums/ButtonStyle.rst
    • Added new documentation file for ButtonStyle enum.
  • docs/source/api/enums/index.rst
    • Updated enum index to display categorized lists of enums.
  • docs/source/conf.py
    • Configured Sphinx to preserve default values in autodoc and suppressed a highlighting warning.
    • Updated theme options for fonts and added new navigation/content features.
  • docs/source/index.rst
    • Updated the main documentation page with a refreshed visual style and simplified introductory text.
  • docs/source/support.rst
    • Removed a redundant horizontal rule.
  • pyproject.toml
    • Updated version constraints for core dependencies and development/documentation tools.
  • pyrogram/init.py
    • Incremented the project version to v0.3.222.
  • pyrogram/enums/init.py
    • Corrected a typo in an enum import.
  • pyrogram/enums/listener_types.py
    • Renamed the enum file from listerner_types.py to listener_types.py to fix a typo.
  • pyrogram/methods/business/init.py
    • Updated import and usage of RefundStarPayment to RefundStarsPayment.
  • pyrogram/methods/business/refund_stars_payment.py
    • Renamed the class and method to RefundStarsPayment for consistency and added a backward-compatible alias.
  • pyrogram/types/init.py
    • Exported new types Str and Link.
  • pyrogram/types/messages_and_media/init.py
    • Exported the new Str type.
  • pyrogram/types/messages_and_media/message.py
    • Defined the new Str type.
  • pyrogram/types/user_and_chats/init.py
    • Exported the new Link type.
  • pyrogram/types/user_and_chats/chat.py
    • Corrected a docstring reference for join_requests_count.
  • requirements-dev.lock
    • Updated development dependency versions and hashes, and migrated from rye to uv for lockfile generation.
  • requirements.lock
    • Updated production dependency versions and hashes, and migrated from rye to uv for lockfile generation.
  • uv.lock
    • Updated resolution markers for Python versions and refreshed package versions and hashes for alabaster, cryptography, docutils, filelock, platformdirs, roman-numerals, sphinx, and uv.
Ignored Files
  • Ignored by pattern: .github/workflows/** (4)
    • .github/workflows/docs_gen.yml
    • .github/workflows/fetch_mtproto.yml
    • .github/workflows/format_and_test.yml
    • .github/workflows/tag_and_publish.yml
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Contributor

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 3 issues, and left some high level feedback:

  • In compiler/errors/compiler.py, the files = [i.name for i in (ERRORS_HOME_PATH / "source").iterdir()] line will now include directories as well as files (unlike the previous is_file() filter), which can break the CSV reading loop; consider restoring an i.is_file() check there.
  • The new dev_tools/check_api_schema_updates.py uses requests.get without a timeout, which can cause the CI job to hang if the upstream endpoint is slow or unresponsive; adding an explicit timeout would make the workflow more robust.
  • The compiler/errors/compiler.py script no longer overrides HOME/DEST when run as __main__, so its behavior differs from the previous relative-path based execution; if you still rely on calling it from different working directories, you may want to document or reintroduce equivalent CLI/path handling.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- In `compiler/errors/compiler.py`, the `files = [i.name for i in (ERRORS_HOME_PATH / "source").iterdir()]` line will now include directories as well as files (unlike the previous `is_file()` filter), which can break the CSV reading loop; consider restoring an `i.is_file()` check there.
- The new `dev_tools/check_api_schema_updates.py` uses `requests.get` without a timeout, which can cause the CI job to hang if the upstream endpoint is slow or unresponsive; adding an explicit timeout would make the workflow more robust.
- The `compiler/errors/compiler.py` script no longer overrides `HOME`/`DEST` when run as `__main__`, so its behavior differs from the previous relative-path based execution; if you still rely on calling it from different working directories, you may want to document or reintroduce equivalent CLI/path handling.

## Individual Comments

### Comment 1
<location> `dev_tools/check_api_schema_updates.py:92` </location>
<code_context>
+    logger.info("Fetching latest API schema from Telegram repository")
+
+    try:
+        api_response = requests.get(API_SCHEMA_URL)
+        api_response.raise_for_status()
+
</code_context>

<issue_to_address>
**suggestion (bug_risk):** Add a timeout to the schema download to avoid hanging the script (and the workflow).

Since `requests.get` has no timeout, a slow or stalled GitHub response can hang this script and block the CI job. Please pass an explicit timeout (e.g. `timeout=10``30`) so the job fails fast with a clear error instead of hanging indefinitely.

Suggested implementation:

```python
import requests

SCHEMA_REQUEST_TIMEOUT = 20  # seconds

```

```python
        api_response = requests.get(API_SCHEMA_URL, timeout=SCHEMA_REQUEST_TIMEOUT)

```

If the surrounding code has specific error handling, you may also want to:
1. Add a dedicated `except requests.exceptions.Timeout` block to log a clearer message (e.g. "Timed out fetching latest API schema").
2. Ensure the script exits with a non-zero status code in the timeout case so CI fails appropriately.
</issue_to_address>

### Comment 2
<location> `docs/source/index.rst:39` </location>
<code_context>
-in the top left corner.
-
-Here below you can, instead, find a list of the most relevant pages for a quick access.
+Contents are organized into sections composed of self-contained topics which can be all accessed from the sidebar.
+Here below you can find a list of the most relevant pages for quick access.

</code_context>

<issue_to_address>
**suggestion (typo):** Consider reordering "can be all accessed" to the more natural "can all be accessed".

Also consider phrasing the full clause as: “which can all be accessed from the sidebar.”

```suggestion
Contents are organized into sections composed of self-contained topics which can all be accessed from the sidebar.
```
</issue_to_address>

### Comment 3
<location> `dev_tools/check_api_schema_updates.py:81` </location>
<code_context>
+    return hashlib.sha256(MAIN_API_PATH.read_bytes()).hexdigest()
+
+
+def get_latest_schema() -> SchemaData | None:
+    """
+    Fetch the latest API schema from Telegram's repository.
</code_context>

<issue_to_address>
**issue (complexity):** Consider refactoring `get_latest_schema` into small helper functions and simplifying the BASIC_TYPES filtering logic to make the flow clearer and easier to maintain.

You can keep all current behavior but reduce complexity by extracting a few small helpers and simplifying the BASIC_TYPES filtering.

### 1. Split `get_latest_schema` into focused helpers

Right now `get_latest_schema` is handling fetching, parsing, filtering, and assembling. Splitting this into small pure helpers makes each step easier to reason about and test.

For example:

```python
def fetch_raw_schema() -> str:
    api_response = requests.get(API_SCHEMA_URL)
    api_response.raise_for_status()
    return api_response.text


def extract_layer(raw: str) -> str:
    match = LAYER_RE.search(raw)
    return match.group(1) if match else "Unknown"


def split_types_and_functions(raw: str) -> tuple[str, str]:
    functions_idx = raw.find("---functions---")
    if functions_idx != -1:
        types_part = raw[:functions_idx].strip()
        functions_part = raw[functions_idx:]
    else:
        types_part = raw
        functions_part = ""
    return types_part, functions_part
```

Then the main function becomes mostly orchestration, which is much simpler to read:

```python
def get_latest_schema() -> SchemaData | None:
    logger.info("Fetching latest API schema from Telegram repository")

    try:
        api_content = fetch_raw_schema()
        layer_version = extract_layer(api_content)
        types_part, functions_part = split_types_and_functions(api_content)

        processed_types_content = filter_basic_types(types_part)
        schema_content = build_final_content(processed_types_content, functions_part)
        schema_hash = hashlib.sha256(schema_content.encode()).hexdigest()

        return {
            "content": schema_content,
            "hash": schema_hash,
            "layer": layer_version,
        }
    except requests.RequestException as e:
        logger.error("Error fetching schema: %s", e)
        return None
    except (ValueError, KeyError) as e:
        logger.error("Error processing schema: %s", e)
        return None
```

### 2. Simplify BASIC_TYPES filtering

You can precompute the prefixes once and move the intent into a named helper, making the logic clearer and cheaper per line:

```python
BASIC_TYPE_PREFIXES: set[str] = {
    bt.split("=")[0].strip() for bt in BASIC_TYPES
}


def is_basic_type_line(line: str) -> bool:
    stripped = line.strip()
    return any(stripped.startswith(prefix) for prefix in BASIC_TYPE_PREFIXES)
```

Then the loop becomes shorter and self‑describing:

```python
def filter_basic_types(types_part: str) -> str:
    processed_types: list[str] = []

    for line in types_part.split("\n"):
        line_stripped = line.strip()

        if not line_stripped:
            processed_types.append("")
            continue

        if not is_basic_type_line(line):
            processed_types.append(line)

    return "\n".join(processed_types).strip()
```

And the final content builder can be a small helper as well:

```python
def build_final_content(types: str, functions: str) -> str:
    if functions:
        return f"{SCHEMA_HEADER}\n{types}\n\n{functions}"
    return f"{SCHEMA_HEADER}\n{types}"
```

These changes keep all behavior (including whitespace handling and header injection) but make the control flow and responsibilities much clearer with minimal code movement.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

logger.info("Fetching latest API schema from Telegram repository")

try:
api_response = requests.get(API_SCHEMA_URL)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion (bug_risk): Add a timeout to the schema download to avoid hanging the script (and the workflow).

Since requests.get has no timeout, a slow or stalled GitHub response can hang this script and block the CI job. Please pass an explicit timeout (e.g. timeout=1030) so the job fails fast with a clear error instead of hanging indefinitely.

Suggested implementation:

import requests

SCHEMA_REQUEST_TIMEOUT = 20  # seconds
        api_response = requests.get(API_SCHEMA_URL, timeout=SCHEMA_REQUEST_TIMEOUT)

If the surrounding code has specific error handling, you may also want to:

  1. Add a dedicated except requests.exceptions.Timeout block to log a clearer message (e.g. "Timed out fetching latest API schema").
  2. Ensure the script exits with a non-zero status code in the timeout case so CI fails appropriately.

in the top left corner.

Here below you can, instead, find a list of the most relevant pages for a quick access.
Contents are organized into sections composed of self-contained topics which can be all accessed from the sidebar.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion (typo): Consider reordering "can be all accessed" to the more natural "can all be accessed".

Also consider phrasing the full clause as: “which can all be accessed from the sidebar.”

Suggested change
Contents are organized into sections composed of self-contained topics which can be all accessed from the sidebar.
Contents are organized into sections composed of self-contained topics which can all be accessed from the sidebar.

return hashlib.sha256(MAIN_API_PATH.read_bytes()).hexdigest()


def get_latest_schema() -> SchemaData | None:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (complexity): Consider refactoring get_latest_schema into small helper functions and simplifying the BASIC_TYPES filtering logic to make the flow clearer and easier to maintain.

You can keep all current behavior but reduce complexity by extracting a few small helpers and simplifying the BASIC_TYPES filtering.

1. Split get_latest_schema into focused helpers

Right now get_latest_schema is handling fetching, parsing, filtering, and assembling. Splitting this into small pure helpers makes each step easier to reason about and test.

For example:

def fetch_raw_schema() -> str:
    api_response = requests.get(API_SCHEMA_URL)
    api_response.raise_for_status()
    return api_response.text


def extract_layer(raw: str) -> str:
    match = LAYER_RE.search(raw)
    return match.group(1) if match else "Unknown"


def split_types_and_functions(raw: str) -> tuple[str, str]:
    functions_idx = raw.find("---functions---")
    if functions_idx != -1:
        types_part = raw[:functions_idx].strip()
        functions_part = raw[functions_idx:]
    else:
        types_part = raw
        functions_part = ""
    return types_part, functions_part

Then the main function becomes mostly orchestration, which is much simpler to read:

def get_latest_schema() -> SchemaData | None:
    logger.info("Fetching latest API schema from Telegram repository")

    try:
        api_content = fetch_raw_schema()
        layer_version = extract_layer(api_content)
        types_part, functions_part = split_types_and_functions(api_content)

        processed_types_content = filter_basic_types(types_part)
        schema_content = build_final_content(processed_types_content, functions_part)
        schema_hash = hashlib.sha256(schema_content.encode()).hexdigest()

        return {
            "content": schema_content,
            "hash": schema_hash,
            "layer": layer_version,
        }
    except requests.RequestException as e:
        logger.error("Error fetching schema: %s", e)
        return None
    except (ValueError, KeyError) as e:
        logger.error("Error processing schema: %s", e)
        return None

2. Simplify BASIC_TYPES filtering

You can precompute the prefixes once and move the intent into a named helper, making the logic clearer and cheaper per line:

BASIC_TYPE_PREFIXES: set[str] = {
    bt.split("=")[0].strip() for bt in BASIC_TYPES
}


def is_basic_type_line(line: str) -> bool:
    stripped = line.strip()
    return any(stripped.startswith(prefix) for prefix in BASIC_TYPE_PREFIXES)

Then the loop becomes shorter and self‑describing:

def filter_basic_types(types_part: str) -> str:
    processed_types: list[str] = []

    for line in types_part.split("\n"):
        line_stripped = line.strip()

        if not line_stripped:
            processed_types.append("")
            continue

        if not is_basic_type_line(line):
            processed_types.append(line)

    return "\n".join(processed_types).strip()

And the final content builder can be a small helper as well:

def build_final_content(types: str, functions: str) -> str:
    if functions:
        return f"{SCHEMA_HEADER}\n{types}\n\n{functions}"
    return f"{SCHEMA_HEADER}\n{types}"

These changes keep all behavior (including whitespace handling and header injection) but make the control flow and responsibilities much clearer with minimal code movement.

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces a wide range of improvements, including a major update to the MTProto schema, automated tooling for schema updates, significant documentation enhancements in styling, organization, and content, and dependency updates. The code quality is high, with good use of modern Python features and robust error handling in the new tooling. The renaming of APIs for consistency while maintaining backward compatibility is also well-handled. I have found one critical issue in the updated schema that needs to be addressed.

keyboardButtonSimpleWebView#e15c4370 flags:# style:flags.10?KeyboardButtonStyle text:string url:string = KeyboardButton;
keyboardButtonRequestPeer#5b0f15f5 flags:# style:flags.10?KeyboardButtonStyle text:string button_id:int peer_type:RequestPeerType max_quantity:int = KeyboardButton;
inputKeyboardButtonRequestPeer#c9662d05 flags:# name_requested:flags.0?true username_requested:flags.1?true photo_requested:flags.2?true text:string button_id:int peer_type:RequestPeerType max_quantity:int = KeyboardButton;
inputKeyboardButtonRequestPeer#2b78156 flags:# name_requested:flags.0?true username_requested:flags.1?true photo_requested:flags.2?true style:flags.10?KeyboardButtonStyle text:string button_id:int peer_type:RequestPeerType max_quantity:int = KeyboardButton;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

critical

The constructor ID #2b78156 for inputKeyboardButtonRequestPeer is only 7 characters long. It should be an 8-character hexadecimal value. It seems to be missing a leading zero and should be #02b78156. This will likely cause parsing failures.

inputKeyboardButtonRequestPeer#02b78156 flags:# name_requested:flags.0?true username_requested:flags.1?true photo_requested:flags.2?true style:flags.10?KeyboardButtonStyle text:string button_id:int peer_type:RequestPeerType max_quantity:int = KeyboardButton;

@5hojib 5hojib merged commit 50ca2ac into main Feb 14, 2026
1 check passed
@5hojib 5hojib deleted the beta branch February 14, 2026 12:31
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant