### Setup Development Environment Source: https://github.com/icodecraft/telegram-init-data/blob/main/README.md Clone the repository, set up a virtual environment, install dependencies, and run tests and code formatting tools. ```bash # Clone the repository git clone https://github.com/telegram-init-data/telegram-init-data-python.git cd telegram-init-data-python # Create virtual environment python -m venv venv source venv/bin/activate # On Windows: venv\Scripts\activate # Install in development mode pip install -e .[dev] # Run tests pytest # Format code black telegram_init_data tests isort telegram_init_data tests # Type checking mypy telegram_init_data ``` -------------------------------- ### Install telegram-init-data Source: https://github.com/icodecraft/telegram-init-data/blob/main/_autodocs/README.md Install the core library or with FastAPI support using pip. ```bash # Core library only pip install telegram-init-data # With FastAPI support pip install telegram-init-data[fastapi] ``` -------------------------------- ### Install Development Dependencies Source: https://github.com/icodecraft/telegram-init-data/blob/main/README.md Install the necessary development dependencies for the project, including testing tools. ```bash pip install -e .[dev] ``` -------------------------------- ### Install telegram-init-data Source: https://github.com/icodecraft/telegram-init-data/blob/main/README.md Install the library using pip. For FastAPI integration, use the optional dependency. ```bash pip install telegram-init-data ``` ```bash pip install telegram-init-data[fastapi] ``` -------------------------------- ### Complete FastAPI Application Example Source: https://github.com/icodecraft/telegram-init-data/blob/main/_autodocs/MANIFEST.md A full example demonstrating how to integrate Telegram Init Data authentication into a FastAPI application, including protected and optional routes. ```python from fastapi import FastAPI, Depends, Request from typing import Optional from telegram_init_data.fastapi import TelegramInitDataAuth, create_init_data_dependency, create_optional_init_data_dependency, get_telegram_auth app = FastAPI() BOT_TOKEN = "YOUR_BOT_TOKEN" BOT_ID = "YOUR_BOT_ID" # --- Authentication Dependencies --- # Required authentication using TelegramInitDataAuth class auth_handler_required = TelegramInitDataAuth(bot_token=BOT_TOKEN) # Required authentication using dependency factory InitDataDependency = create_init_data_dependency(bot_token=BOT_TOKEN) # Optional authentication using dependency factory OptionalInitDataDependency = create_optional_init_data_dependency(bot_token=BOT_TOKEN) # Utility function for custom auth types (e.g., header) header_auth_dependency = get_telegram_auth(bot_token=BOT_TOKEN, auth_type="header") # --- Routes --- @app.get("/protected_class") async def protected_route_class( user_data: dict = Depends(auth_handler_required) ): return {"message": f"Hello, {user_data.get('user', {}).get('first_name', 'User')} (via class)!"} @app.get("/protected_factory") async def protected_route_factory( user_data: dict = Depends(InitDataDependency) ): return {"message": f"Hello, {user_data.get('user', {}).get('first_name', 'User')} (via factory)!"} @app.get("/optional_auth") async def optional_auth_route( user_data: Optional[dict] = Depends(OptionalInitDataDependency) ): if user_data: return {"message": f"Welcome, {user_data.get('user', {}).get('first_name', 'User')} (optional auth)!"} else: return {"message": "No valid init data provided."} @app.get("/custom_header_auth") async def custom_header_auth_route( user_data: dict = Depends(header_auth_dependency) ): return {"message": f"Hello, {user_data.get('user', {}).get('first_name', 'User')} (via custom header)!"} @app.get("/") async def root(): return {"message": "Welcome to the Telegram Init Data FastAPI example!"} # To run this example: # 1. Save as main.py # 2. Run: uvicorn main:app --reload ``` -------------------------------- ### Complete InitData Example Source: https://github.com/icodecraft/telegram-init-data/blob/main/_autodocs/README.md A comprehensive example of the initialization data structure received from Telegram. This includes query details, user, chat, authentication, and hashing information. ```python init_data = { "query_id": "AAHdF6IQAAAAAN0XohDhrOrc", "user": {...}, "receiver": {...}, "chat": {...}, "chat_type": "group", "chat_instance": "123456789", "start_param": "referral_code", "can_send_after": 1662771648, "auth_date": 1662771648, "hash": "c501b71e775f74ce10e377dea85a7ea24ecd640b223ea86dfe453e0eaed2e2b2", "signature": "..." # Only for 3rd party } ``` -------------------------------- ### Install Package With FastAPI Support Source: https://github.com/icodecraft/telegram-init-data/blob/main/_autodocs/module-imports.md Installs the telegram-init-data package along with FastAPI support. Use this command if your project utilizes FastAPI. ```bash # Install with FastAPI support pip install telegram-init-data[fastapi] ``` -------------------------------- ### Import Patterns Example Source: https://github.com/icodecraft/telegram-init-data/blob/main/_autodocs/MANIFEST.md Illustrates different patterns for importing library components. This helps users choose the most suitable import strategy for their project. ```python # Pattern 1: Import specific functions from telegram_init_data.validate import validate_init_data from telegram_init_data.types import User # Pattern 2: Import the whole module import telegram_init_data # Pattern 3: Import with an alias import telegram_init_data as tid # Pattern 4: Selective import from submodules from telegram_init_data.exceptions import InvalidDataError ``` -------------------------------- ### Importing Main Package Entry Point Source: https://github.com/icodecraft/telegram-init-data/blob/main/_autodocs/MANIFEST.md Shows how to import the main package entry point for accessing various functionalities. This is the standard way to start using the library. ```python import telegram_init_data # Example usage: # validated_data = telegram_init_data.validate(init_data, bot_token) # is_valid = telegram_init_data.is_valid(init_data, bot_token) # parsed_data = telegram_init_data.parse(init_data) ``` -------------------------------- ### TelegramInitDataAuth Header Example Source: https://github.com/icodecraft/telegram-init-data/blob/main/_autodocs/fastapi-integration.md Example of the Authorization header using the 'tma' scheme for Telegram Init Data authentication. ```http Authorization: tma query_id=...&hash=... ``` -------------------------------- ### FastAPI Integration Options Source: https://github.com/icodecraft/telegram-init-data/blob/main/_autodocs/README.md Example of configuring TelegramInitDataAuth for FastAPI, including bot token and validation options. ```python auth = TelegramInitDataAuth( bot_token="YOUR_BOT_TOKEN", header_name="Authorization", scheme_name="tma", auto_error=True, validate_options={"expires_in": 1800} ) ``` -------------------------------- ### Install Package Without FastAPI Source: https://github.com/icodecraft/telegram-init-data/blob/main/_autodocs/module-imports.md Installs the core telegram-init-data package without any optional dependencies. Use this command when FastAPI is not required for your project. ```bash # Install without FastAPI pip install telegram-init-data ``` -------------------------------- ### Environment Variable Configuration Example Source: https://github.com/icodecraft/telegram-init-data/blob/main/_autodocs/MANIFEST.md Illustrates how to use environment variables for configuring the bot token in FastAPI integrations. This promotes secure handling of sensitive credentials. ```python import os from fastapi import FastAPI, Depends from telegram_init_data.fastapi import create_init_data_dependency app = FastAPI() # Load bot token from environment variable BOT_TOKEN = os.environ.get("TELEGRAM_BOT_TOKEN") if not BOT_TOKEN: raise EnvironmentError("TELEGRAM_BOT_TOKEN environment variable not set.") # Use the environment variable to configure the dependency InitDataDependency = create_init_data_dependency(bot_token=BOT_TOKEN) @app.get("/env_protected") async def env_protected_route(user_data: dict = Depends(InitDataDependency)): return {"message": f"Hello, {user_data.get('user', {}).get('first_name')}, authenticated via env var!"} # To run this example: # 1. Set the environment variable: export TELEGRAM_BOT_TOKEN="YOUR_BOT_TOKEN" # 2. Save as main.py # 3. Run: uvicorn main:app --reload ``` -------------------------------- ### TelegramInitDataBearer Header Example Source: https://github.com/icodecraft/telegram-init-data/blob/main/_autodocs/fastapi-integration.md Example of the Authorization header using the 'Bearer' scheme for Telegram Init Data authentication. ```http Authorization: Bearer query_id=...&hash=... ``` -------------------------------- ### Signing and Validating Test Data Source: https://github.com/icodecraft/telegram-init-data/blob/main/_autodocs/api-overview.md This example shows how to create signed init data for testing purposes using the `sign` function, and then validate and parse it with `validate` and `parse`. This is useful for unit tests. ```python from telegram_init_data import sign, validate, parse from datetime import datetime # Create test data test_data = { "user": {"id": 123, "first_name": "Test"}, } # Sign it signed = sign(test_data, "BOT_TOKEN", datetime.now()) # Use in tests validate(signed, "BOT_TOKEN") # Passes parsed = parse(signed) # Works ``` -------------------------------- ### Complete FastAPI Application with Telegram Init Data Authentication Source: https://github.com/icodecraft/telegram-init-data/blob/main/_autodocs/fastapi-integration.md This snippet shows a full FastAPI application setup that utilizes multiple authentication methods provided by the `python-telegram-init-data` library. It includes examples for header, bearer, custom header, and optional authentication schemes, along with a custom exception handler for `TelegramInitDataError`. ```python from fastapi import FastAPI, Depends, HTTPException from fastapi.responses import JSONResponse from typing import Optional from datetime import datetime from telegram_init_data import ( TelegramInitDataAuth, TelegramInitDataBearer, create_init_data_dependency, create_optional_init_data_dependency, get_telegram_auth, InitData, TelegramInitDataError ) app = FastAPI( title="Telegram Mini App API", description="Example with multiple auth schemes" ) BOT_TOKEN = "YOUR_BOT_TOKEN" VALIDATE_OPTIONS = {"expires_in": 1800} # 30 minutes # Authentication schemes auth_header = TelegramInitDataAuth( bot_token=BOT_TOKEN, scheme_name="tma", validate_options=VALIDATE_OPTIONS ) auth_bearer = TelegramInitDataBearer( bot_token=BOT_TOKEN, validate_options=VALIDATE_OPTIONS ) auth_custom = create_init_data_dependency( bot_token=BOT_TOKEN, header_name="X-Telegram-Init-Data", validate_options=VALIDATE_OPTIONS ) auth_optional = create_optional_init_data_dependency( bot_token=BOT_TOKEN, header_name="X-Telegram-Init-Data" ) # Routes @app.get("/") async def root(): return {"message": "Telegram Mini App API"} @app.get("/me/header") async def get_user_header(init_data: InitData = Depends(auth_header)): """Requires: Authorization: tma """ user = init_data["user"] return { "method": "header", "user": { "id": user["id"], "name": user["first_name"], "username": user.get("username") } } @app.get("/me/bearer") async def get_user_bearer(init_data: InitData = Depends(auth_bearer)): """Requires: Authorization: Bearer """ user = init_data["user"] return { "method": "bearer", "user": { "id": user["id"], "name": user["first_name"] } } @app.get("/me/custom") async def get_user_custom(init_data: InitData = Depends(auth_custom)): """Requires: X-Telegram-Init-Data: """ user = init_data["user"] return { "method": "custom", "user": { "id": user["id"], "name": user["first_name"] } } @app.get("/content") async def get_content(init_data: Optional[InitData] = Depends(auth_optional)): """X-Telegram-Init-Data header is optional""" if init_data: user = init_data["user"] return { "type": "authenticated", "content": "Personalized content", "user_id": user["id"] } return { "type": "public", "content": "Public content" } @app.exception_handler(TelegramInitDataError) async def telegram_error_handler(request, exc): return JSONResponse( status_code=401, content={"error": str(exc), "type": type(exc).__name__} ) if __name__ == "__main__": import uvicorn uvicorn.run(app, host="0.0.0.0", port=8000) ``` -------------------------------- ### Graceful Handling of Optional FastAPI Import Source: https://github.com/icodecraft/telegram-init-data/blob/main/_autodocs/module-imports.md Demonstrates how to import FastAPI-related components while gracefully handling the case where FastAPI is not installed. This allows the code to function even without the optional dependency. ```python # This works with or without fastapi installed try: from telegram_init_data import TelegramInitDataAuth has_fastapi = True except ImportError: has_fastapi = False TelegramInitDataAuth = None ``` -------------------------------- ### Custom X-Telegram-Data Header Example Source: https://github.com/icodecraft/telegram-init-data/blob/main/_autodocs/fastapi-integration.md Example of a custom User-defined header 'X-Telegram-Data' for passing Telegram Init Data. ```http X-Telegram-Data: query_id=...&hash=... ``` -------------------------------- ### Create FastAPI Dependencies with Different Validation Options Source: https://github.com/icodecraft/telegram-init-data/blob/main/_autodocs/fastapi-integration.md This example demonstrates creating multiple FastAPI dependencies using `create_init_data_dependency` with distinct validation options, such as different expiration times for sensitive and less sensitive endpoints. Replace 'YOUR_BOT_TOKEN' with your actual bot token. ```python from fastapi import FastAPI, Depends from telegram_init_data import create_init_data_dependency, InitData app = FastAPI() # Different expiration for different endpoints strict_auth = create_init_data_dependency( bot_token="YOUR_BOT_TOKEN", header_name="X-Auth", validate_options={"expires_in": 300} # 5 minutes ) lenient_auth = create_init_data_dependency( bot_token="YOUR_BOT_TOKEN", header_name="X-Auth", validate_options={"expires_in": 3600} # 1 hour ) @app.post("/sensitive") async def sensitive_operation(init_data: InitData = Depends(strict_auth)): return {"status": "success"} @app.get("/less-sensitive") async def less_sensitive_operation(init_data: InitData = Depends(lenient_auth)): return {"status": "success"} ``` -------------------------------- ### Sign and Validate Telegram Init Data Source: https://github.com/icodecraft/telegram-init-data/blob/main/_autodocs/core-functions.md This example demonstrates how to sign data using `sign()` and then immediately validate it using `validate()`. This is useful for ensuring the signing process works correctly within your application. ```python from telegram_init_data import sign, validate from datetime import datetime bot_token = "123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11" test_data = { "user": { "id": 12345, "first_name": "Alice" } } # Sign the data signed = sign(test_data, bot_token, datetime.now()) # Validate the signed data (should succeed) try: validate(signed, bot_token) print("✅ Signed data validated successfully") except Exception as e: print(f"❌ Validation failed: {e}") ``` -------------------------------- ### Testing with Signed Data Source: https://github.com/icodecraft/telegram-init-data/blob/main/_autodocs/api-overview.md Provides an example of how to sign test data and use it with `validate` and `parse` functions for testing purposes. ```APIDOC ## Testing with Signed Data ### Description Demonstrates signing arbitrary data to simulate Telegram Init Data for testing validation and parsing logic. ### Method N/A (Testing utility) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from telegram_init_data import sign, validate, parse from datetime import datetime # Create test data test_data = { "user": {"id": 123, "first_name": "Test"}, } # Sign it bot_token = "BOT_TOKEN" signed_data = sign(test_data, bot_token, datetime.now()) # Use in tests validate(signed_data, bot_token) # Should pass parsed_data = parse(signed_data) # Should work ``` ### Response #### Success Response - **validate()**: Returns True if signature is valid. - **parse()**: Returns the parsed InitData object. #### Response Example ```json { "user": { "id": 123, "first_name": "Test" } } ``` ``` -------------------------------- ### Create Test Data with sign() Source: https://github.com/icodecraft/telegram-init-data/blob/main/_autodocs/core-functions.md Use this snippet to generate signed init data for testing purposes. Ensure you have the `telegram_init_data` library installed and provide your bot token and test data. ```python from telegram_init_data import sign from datetime import datetime bot_token = "123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11" test_data = { "query_id": "test_query_123", "user": { "id": 279058397, "first_name": "John", "last_name": "Doe", "username": "johndoe", "language_code": "en" }, "auth_date": datetime.now() } signed_data = sign(test_data, bot_token, datetime.now()) print(f"Signed data: {signed_data}") # Returns: "auth_date=1234567890&query_id=test_query_123&user=%7B%22id%22%3A279058397%7D&hash=abc123def456..." ``` -------------------------------- ### Run Project Tests Source: https://github.com/icodecraft/telegram-init-data/blob/main/README.md Execute all project tests using pytest. Ensure development dependencies are installed first. ```bash pytest ``` -------------------------------- ### FastAPI Integration with Bearer Token Header Source: https://github.com/icodecraft/telegram-init-data/blob/main/_autodocs/api-overview.md This example shows how to authenticate requests using the 'Authorization: Bearer ' header in FastAPI. Ensure your bot token is correctly configured. ```python from fastapi import FastAPI, Depends from telegram_init_data import TelegramInitDataBearer, InitData app = FastAPI() auth = TelegramInitDataBearer(bot_token="YOUR_TOKEN") @app.get("/data") async def get_data(init_data: InitData = Depends(auth)): return init_data ``` -------------------------------- ### User Object Example Source: https://github.com/icodecraft/telegram-init-data/blob/main/_autodocs/README.md Represents a Telegram user. Includes basic user information and optional fields like username and photo. ```python user = { "id": 279058397, "first_name": "John", "last_name": "Doe", "username": "johndoe", "language_code": "en", "is_premium": True, "is_bot": False, "photo_url": "https://..." } ``` -------------------------------- ### Import FastAPI Integration Components Source: https://github.com/icodecraft/telegram-init-data/blob/main/_autodocs/module-imports.md Import various components for integrating with FastAPI, including authentication dependencies and factory functions. This requires the FastAPI package to be installed. ```python from telegram_init_data.fastapi import ( TelegramInitDataAuth, TelegramInitDataBearer, create_init_data_dependency, create_optional_init_data_dependency, get_telegram_auth, ) ``` -------------------------------- ### Send Init Data from Client to Backend Source: https://github.com/icodecraft/telegram-init-data/blob/main/_autodocs/api-overview.md Example of how a Telegram Mini App's JavaScript can send init data to a backend API using POST requests with different header or body configurations. ```javascript // Client (JavaScript in Mini App) const initData = window.Telegram.WebApp.initData; // Send to backend fetch("/api/authenticate", { method: "POST", headers: {"Authorization": `tma ${initData}`}, // or headers: {"X-Telegram-Init-Data": initData}, // or include in body body: JSON.stringify({init_data: initData}) }); ``` -------------------------------- ### Project Navigation Summary Source: https://github.com/icodecraft/telegram-init-data/blob/main/_autodocs/MANIFEST.md Provides a quick reference to key documentation files within the project. ```markdown Start Here: README.md Understand Purpose: api-overview.md Learn by Example: usage-patterns.md Use Functions: core-functions.md Understand Types: types.md Handle Errors: errors.md Setup FastAPI: fastapi-integration.md Configure Options: configuration.md Import Modules: module-imports.md ``` -------------------------------- ### Get Telegram Authentication Utility Source: https://github.com/icodecraft/telegram-init-data/blob/main/_autodocs/MANIFEST.md A utility function to get Telegram authentication details, supporting different authentication types. Useful for custom authentication flows in FastAPI. ```python from fastapi import FastAPI, Request, Depends from telegram_init_data.fastapi import get_telegram_auth app = FastAPI() @app.get("/custom_auth") async def custom_auth_route( request: Request, user_data: dict = Depends(get_telegram_auth(bot_token="YOUR_BOT_TOKEN", auth_type="header")) ): # user_data contains the parsed and validated init data return {"message": "Authenticated via custom flow: " + user_data.get("user", {}).get("first_name", "User")} # Example using query parameter authentication: @app.get("/custom_auth_query") async def custom_auth_query_route( request: Request, user_data: dict = Depends(get_telegram_auth(bot_token="YOUR_BOT_TOKEN", auth_type="query")) ): return {"message": "Authenticated via query param: " + user_data.get("user", {}).get("first_name", "User")} # To run this example: # 1. Save as main.py # 2. Run: uvicorn main:app --reload ``` -------------------------------- ### Configure TelegramInitDataAuth in FastAPI Source: https://github.com/icodecraft/telegram-init-data/blob/main/_autodocs/MANIFEST.md Demonstrates how to configure the `TelegramInitDataAuth` class for use in a FastAPI application, including setting the bot token. ```python from fastapi import FastAPI, Depends from telegram_init_data.fastapi import TelegramInitDataAuth app = FastAPI() # Configure TelegramInitDataAuth with your bot token auth_handler = TelegramInitDataAuth(bot_token="YOUR_BOT_TOKEN") @app.get("/secure_resource") async def secure_resource(user_data: dict = Depends(auth_handler)): # Access user data after successful authentication return {"user_id": user_data.get("user", {}).get("id")} # To run this example: # 1. Save as main.py # 2. Run: uvicorn main:app --reload ``` -------------------------------- ### get_telegram_auth() Source: https://github.com/icodecraft/telegram-init-data/blob/main/_autodocs/configuration.md Utility function for quick setup of Telegram authentication. It returns a dependency callable for FastAPI. ```APIDOC ## get_telegram_auth() ### Description Utility function for quick setup of Telegram authentication. It returns a dependency callable for FastAPI. ### Function Signature ```python def get_telegram_auth( bot_token: str, auth_type: str = "header", validate_options: Optional[ValidateOptions] = None, **kwargs ) -> Callable ``` ### Parameters #### Path Parameters * **bot_token** (str) - Required - Bot token from @BotFather * **auth_type** (str) - Optional - Default: "header" - Type of authentication: "header", "bearer", or "custom" * **validate_options** (Optional[ValidateOptions]) - Optional - Default: None - Validation options (expires_in, etc.) * **kwargs** (Any) - Optional - Additional arguments (scheme_name, header_name, etc.) ### auth_type Options * **"header"**: Authorization header with custom scheme. Returns TelegramInitDataAuth instance. * **"bearer"**: Bearer token authentication. Returns TelegramInitDataBearer instance. * **"custom"**: Custom header name. Returns create_init_data_dependency() result. ### Example ```python from fastapi import FastAPI, Depends from telegram_init_data import get_telegram_auth, InitData app = FastAPI() # Using header authentication header_auth = get_telegram_auth( bot_token="YOUR_BOT_TOKEN", auth_type="header", scheme_name="tma" ) # Using bearer authentication bearer_auth = get_telegram_auth( bot_token="YOUR_BOT_TOKEN", auth_type="bearer" ) # Using custom header custom_auth = get_telegram_auth( bot_token="YOUR_BOT_TOKEN", auth_type="custom", header_name="X-Telegram-Data" ) @app.get("/me/header") async def get_user_header(init_data: InitData = Depends(header_auth)): return {"method": "header", "user_id": init_data["user"]["id"]} @app.get("/me/bearer") async def get_user_bearer(init_data: InitData = Depends(bearer_auth)): return {"method": "bearer", "user_id": init_data["user"]["id"]} @app.get("/me/custom") async def get_user_custom(init_data: InitData = Depends(custom_auth)): return {"method": "custom", "user_id": init_data["user"]["id"]} ``` ``` -------------------------------- ### Chat Object Example Source: https://github.com/icodecraft/telegram-init-data/blob/main/_autodocs/README.md Represents a Telegram chat, such as a group or channel. Includes chat type, title, and optional username/photo. ```python chat = { "id": -1001234567890, "type": "group", # ChatType enum "title": "Group Name", "username": "groupname", "photo_url": "https://..." } ``` -------------------------------- ### Accessing User Information from Init Data Source: https://github.com/icodecraft/telegram-init-data/blob/main/_autodocs/usage-patterns.md Demonstrates how to parse init data and access various user fields, including required and optional ones. Use `.get()` for safe access to optional fields. ```python from telegram_init_data import parse init_data = parse(init_data_string) # Get user (always present if authenticated) user = init_data["user"] # Required user fields user_id = user["id"] # int first_name = user["first_name"] # str # Optional user fields (use .get() to safely access) last_name = user.get("last_name") # str or None username = user.get("username") # str or None (without @) language_code = user.get("language_code") # str or None is_premium = user.get("is_premium", False) # bool, default False is_bot = user.get("is_bot", False) # bool, default False photo_url = user.get("photo_url") # str or None # Other init data fields query_id = init_data.get("query_id") # str or None chat = init_data.get("chat") # dict or None auth_date = init_data["auth_date"] # int (Unix timestamp) start_param = init_data.get("start_param") # str or None ``` -------------------------------- ### Importing Sign Module Source: https://github.com/icodecraft/telegram-init-data/blob/main/_autodocs/MANIFEST.md Shows how to import the sign module, potentially for signing data using different methods or keys than the sign_data module. Specific functionality depends on implementation details. ```python from telegram_init_data.sign import sign_message # Example usage: # message = "hello world" # private_key = "..." # signature = sign_message(message, private_key) ``` -------------------------------- ### Importing Hash Token Module Source: https://github.com/icodecraft/telegram-init-data/blob/main/_autodocs/MANIFEST.md Demonstrates importing the hash_token module, likely used for generating or verifying cryptographic hashes. Specific use cases would depend on the library's internal implementation. ```python from telegram_init_data.hash_token import generate_hash, verify_hash # Example usage: # payload = b'some data' # secret = 'your_secret_key' # token_hash = generate_hash(payload, secret) # is_valid = verify_hash(payload, token_hash, secret) ``` -------------------------------- ### Check FastAPI Availability at Runtime Source: https://github.com/icodecraft/telegram-init-data/blob/main/_autodocs/module-imports.md Checks if the FastAPI integration is available in the installed package. This allows for conditional logic based on the presence of the optional dependency. ```python from telegram_init_data import _fastapi_available if _fastapi_available: print("FastAPI integration is available") else: print("FastAPI integration is not available") ``` -------------------------------- ### Create Optional Init Data Dependency with create_optional_init_data_dependency Source: https://github.com/icodecraft/telegram-init-data/blob/main/_autodocs/configuration.md Use create_optional_init_data_dependency to create a dependency that may return None. This is useful for endpoints that do not require authentication. ```python from typing import Optional from fastapi import FastAPI, Depends from telegram_init_data import create_optional_init_data_dependency, InitData app = FastAPI() # Create optional dependency get_init_data = create_optional_init_data_dependency( bot_token="YOUR_BOT_TOKEN", header_name="X-Telegram-Init-Data" ) @app.get("/content") async def get_content(init_data: Optional[InitData] = Depends(get_init_data)): if init_data: return {"type": "user_content", "user_id": init_data["user"]["id"]} return {"type": "public_content"} ``` -------------------------------- ### Run Tests with Coverage Source: https://github.com/icodecraft/telegram-init-data/blob/main/README.md Run project tests and generate an HTML coverage report. This helps identify areas of the code not covered by tests. ```bash pytest --cov=telegram_init_data --cov-report=html ``` -------------------------------- ### Distinguish Between Telegram Init Data Error Types Source: https://github.com/icodecraft/telegram-init-data/blob/main/_autodocs/usage-patterns.md Handle specific errors during validation to provide tailored responses. This example shows how to catch SignatureMissingError, AuthDateInvalidError, ExpiredError, and SignatureInvalidError. ```python from telegram_init_data import validate from telegram_init_data import ( SignatureMissingError, AuthDateInvalidError, SignatureInvalidError, ExpiredError ) try: validate(init_data, bot_token) except SignatureMissingError: return {"error": "Missing signature"} except AuthDateInvalidError as e: return {"error": f"Invalid date: {e.value}"} except ExpiredError as e: return { "error": "Expired", "issued_at": e.issued_at.isoformat(), "expired_at": e.expires_at.isoformat() } except SignatureInvalidError: return {"error": "Invalid signature"} ``` -------------------------------- ### Configure FastAPI Authentication Source: https://github.com/icodecraft/telegram-init-data/blob/main/_autodocs/api-overview.md Set up TelegramInitDataAuth for FastAPI, customizing the bot token, scheme name, header name, error handling, and validation options. ```python from telegram_init_data import TelegramInitDataAuth auth = TelegramInitDataAuth( bot_token="...", scheme_name="tma", # Custom scheme header_name="Authorization", # Header to read auto_error=True, # Raise on failure validate_options={"expires_in": 1800} ) ``` -------------------------------- ### Import Everything from Main Package Source: https://github.com/icodecraft/telegram-init-data/blob/main/_autodocs/module-imports.md Imports all available components directly from the main telegram_init_data package. Use this for broad access to the library's features. ```python from telegram_init_data import ( validate, parse, sign, InitData, ChatType, TelegramInitDataError ) ``` -------------------------------- ### Testing with Signed Data Source: https://github.com/icodecraft/telegram-init-data/blob/main/_autodocs/MANIFEST.md Illustrates how to test validation logic using pre-signed Telegram Init Data. This is helpful for unit and integration testing. ```python from telegram_init_data.validate import validate_init_data async def test_validation(): # Example of signed init data (replace with actual signed data for testing) signed_init_data = "..." bot_token = 'YOUR_BOT_TOKEN' try: validated_data = await validate_init_data(signed_init_data, bot_token) print("Validation successful:", validated_data) except Exception as e: print("Validation failed:", e) ``` -------------------------------- ### Configure create_optional_init_data_dependency in FastAPI Source: https://github.com/icodecraft/telegram-init-data/blob/main/_autodocs/MANIFEST.md Demonstrates configuring `create_optional_init_data_dependency` for FastAPI, allowing routes to optionally receive validated Telegram Init Data. ```python from fastapi import FastAPI, Depends from typing import Optional from telegram_init_data.fastapi import create_optional_init_data_dependency app = FastAPI() # Configure the optional dependency factory OptionalInitDataDependency = create_optional_init_data_dependency( bot_token="YOUR_BOT_TOKEN", test=True # Optional: enable test mode for validation ) @app.get("/maybe_user") async def maybe_user_route( user_data: Optional[dict] = Depends(OptionalInitDataDependency) ): if user_data: return {"message": f"User identified: {user_data.get('user', {}).get('id')}"} else: return {"message": "No user data provided or invalid."} # To run this example: # 1. Save as main.py # 2. Run: uvicorn main:app --reload ``` -------------------------------- ### FastAPI - Multiple Authentication Methods Source: https://github.com/icodecraft/telegram-init-data/blob/main/_autodocs/usage-patterns.md Support multiple authentication schemes within the same FastAPI application. This example shows using Authorization header with 'tma' scheme, 'Bearer' token, and a custom header. ```python from fastapi import FastAPI, Depends, HTTPException from telegram_init_data import ( TelegramInitDataAuth, TelegramInitDataBearer, create_init_data_dependency, InitData ) app = FastAPI() BOT_TOKEN = "YOUR_BOT_TOKEN" # Method 1: Authorization header with tma scheme auth_header = TelegramInitDataAuth( bot_token=BOT_TOKEN, scheme_name="tma" ) # Method 2: Bearer token auth_bearer = TelegramInitDataBearer(bot_token=BOT_TOKEN) # Method 3: Custom header auth_custom = create_init_data_dependency( bot_token=BOT_TOKEN, header_name="X-Telegram-Data" ) @app.get("/me/v1") async def get_user_v1(init_data: InitData = Depends(auth_header)): """Uses: Authorization: tma """ return init_data["user"] @app.get("/me/v2") async def get_user_v2(init_data: InitData = Depends(auth_bearer)): """Uses: Authorization: Bearer """ return init_data["user"] @app.get("/me/v3") async def get_user_v3(init_data: InitData = Depends(auth_custom)): """Uses: X-Telegram-Data: """ return init_data["user"] ``` -------------------------------- ### Create Custom Init Data Dependency with create_init_data_dependency Source: https://github.com/icodecraft/telegram-init-data/blob/main/_autodocs/configuration.md Use create_init_data_dependency to generate a custom dependency for specific header names. Configure bot token, header name, and validation options. ```python from fastapi import FastAPI, Depends from telegram_init_data import create_init_data_dependency, InitData app = FastAPI() # Create dependency with custom header get_init_data = create_init_data_dependency( bot_token="YOUR_BOT_TOKEN", header_name="X-Telegram-Init-Data", validate_options={"expires_in": 3600} ) @app.get("/me") async def get_user(init_data: InitData = Depends(get_init_data)): return {"user_id": init_data["user"]["id"]} # Header format: X-Telegram-Init-Data: ``` -------------------------------- ### Configure create_init_data_dependency in FastAPI Source: https://github.com/icodecraft/telegram-init-data/blob/main/_autodocs/MANIFEST.md Shows how to configure the `create_init_data_dependency` factory function to create a FastAPI dependency that enforces Telegram Init Data authentication. ```python from fastapi import FastAPI, Depends from telegram_init_data.fastapi import create_init_data_dependency app = FastAPI() # Configure the dependency factory with the bot token InitDataDependency = create_init_data_dependency( bot_token="YOUR_BOT_TOKEN", expires_in=7200 # Optional: set custom expiration time in seconds ) @app.get("/verified_user") async def verified_user_route(user_data: dict = Depends(InitDataDependency)): # user_data is guaranteed to be valid return {"username": user_data.get("user", {}).get("username")} # To run this example: # 1. Save as main.py # 2. Run: uvicorn main:app --reload ``` -------------------------------- ### Create Optional Init Data Dependency for FastAPI Source: https://github.com/icodecraft/telegram-init-data/blob/main/_autodocs/fastapi-integration.md Use this factory function to create an optional authentication dependency for FastAPI. It returns `None` if authentication fails or is missing, instead of raising an HTTPException. Configure with your bot token and an optional custom header name. ```python from typing import Optional from fastapi import FastAPI, Depends from telegram_init_data import create_optional_init_data_dependency, InitData app = FastAPI() optional_auth = create_optional_init_data_dependency( bot_token="YOUR_BOT_TOKEN", header_name="X-Telegram-Init-Data" ) @app.get("/content") async def get_content(init_data: Optional[InitData] = Depends(optional_auth)): if init_data: user = init_data["user"] return { "type": "user_content", "user_id": user["id"], "username": user.get("username") } else: return { "type": "public_content", "message": "Login to see personalized content" } ``` -------------------------------- ### FastAPI Custom Header Authentication with Telegram Init Data Source: https://github.com/icodecraft/telegram-init-data/blob/main/_autodocs/fastapi-integration.md Configure custom header authentication for Telegram init data in FastAPI using this example. It allows you to specify a custom header name (e.g., 'X-Telegram-Data') and validation settings. ```python from fastapi import FastAPI, Depends from telegram_init_data import get_telegram_auth, InitData app = FastAPI() auth = get_telegram_auth( bot_token="YOUR_BOT_TOKEN", auth_type="custom", header_name="X-Telegram-Data", validate_options={"expires_in": 1800} ) @app.get("/me") async def get_user(init_data: InitData = Depends(auth)): return init_data["user"] ``` -------------------------------- ### Importing Parse Module Source: https://github.com/icodecraft/telegram-init-data/blob/main/_autodocs/MANIFEST.md Demonstrates importing the parse module for parsing raw Telegram Init Data into a structured format. This is often a preliminary step before validation. ```python from telegram_init_data.parse import parse_init_data # Example usage: # raw_data = "..." # parsed = parse_init_data(raw_data) # print(parsed) ``` -------------------------------- ### Importing Is Valid Module Source: https://github.com/icodecraft/telegram-init-data/blob/main/_autodocs/MANIFEST.md Shows how to import the is_valid module, likely providing a boolean check for data validity. This is useful for simple checks without detailed error handling. ```python from telegram_init_data.is_valid import is_init_data_valid # Example usage: # async def check_validity(init_data, bot_token): # is_valid = await is_init_data_valid(init_data, bot_token) # if is_valid: # print("Data is valid.") # else: # print("Data is invalid.") ``` -------------------------------- ### Importing Validate 3rd Party Module Source: https://github.com/icodecraft/telegram-init-data/blob/main/_autodocs/MANIFEST.md Demonstrates importing the validate3rd module for verifying signatures from third-party sources. This is crucial for secure external data integration. ```python from telegram_init_data.validate3rd import validate_init_data_3rd # Example usage: # async def verify_external(data, signature, bot_token): # is_valid = await validate_init_data_3rd(data, signature, bot_token) # return is_valid ``` -------------------------------- ### sign(data, token, auth_date, options=None) Source: https://github.com/icodecraft/telegram-init-data/blob/main/README.md Signs init data, typically used for testing or development purposes. It generates a signed init data string from provided data, token, and authentication date. ```APIDOC ## sign(data, token, auth_date, options=None) ### Description Signs init data, typically used for testing or development purposes. It generates a signed init data string from provided data, token, and authentication date. ### Parameters #### Path Parameters - **data** (dict): Data to sign - **token** (str): Bot token - **auth_date** (datetime): Authentication date #### Query Parameters - **options** (dict, optional): Signing options ### Returns - `str`: Signed init data as URL-encoded string ``` -------------------------------- ### sign() Source: https://github.com/icodecraft/telegram-init-data/blob/main/_autodocs/core-functions.md Creates a properly signed init data string that can be validated with `validate()`. This function is useful for creating test data, signing data for testing endpoints, and simulating Telegram Mini App init data in tests. ```APIDOC ## sign() ### Description Creates a signed init data string for testing and development. ### Function Signature ```python def sign( data: SignData, token: Text, auth_date: datetime, options: ValidateOptions = None ) -> str ``` ### Parameters #### Path Parameters - **data** (Union[dict, InitData]) - Required - Init data to sign (dictionary format) - **token** (Union[str, bytes]) - Required - Bot token from @BotFather - **auth_date** (datetime) - Required - Authentication datetime for the signature - **options** (dict) - Optional - Signing options (currently unused) ### Returns `str` - URL-encoded signed init data string ### Example: Create Test Data ```python from telegram_init_data import sign from datetime import datetime bot_token = "123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11" test_data = { "query_id": "test_query_123", "user": { "id": 279058397, "first_name": "John", "last_name": "Doe", "username": "johndoe", "language_code": "en" }, "auth_date": datetime.now() } signed_data = sign(test_data, bot_token, datetime.now()) print(f"Signed data: {signed_data}") # Returns: "auth_date=1234567890&query_id=test_query_123&user=%7B%22id%22%3A279058397%7D&hash=abc123def456..." ``` ### Example: Sign and Validate ```python from telegram_init_data import sign, validate from datetime import datetime bot_token = "123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11" test_data = { "user": { "id": 12345, "first_name": "Alice" } } # Sign the data signed = sign(test_data, bot_token, datetime.now()) # Validate the signed data (should succeed) try: validate(signed, bot_token) print("✅ Signed data validated successfully") except Exception as e: print(f"❌ Validation failed: {e}") ``` ``` -------------------------------- ### Validate Init Data with EdDSA (Production and Test) Source: https://github.com/icodecraft/telegram-init-data/blob/main/_autodocs/core-functions.md Demonstrates how to use the `validate3rd` function with a custom EdDSA verification function. The first call performs production verification with a 1-hour expiration, while the second call uses test mode, which employs a test public key. ```python # Production verification bot_id = 123456789 options = {"expires_in": 3600, "test": False} validate3rd(init_data, bot_id, verify_ed25519, options) # Test mode verification (uses test public key) options = {"expires_in": 3600, "test": True} validate3rd(init_data, bot_id, verify_ed25519, options) ``` -------------------------------- ### Importing Exceptions Module Source: https://github.com/icodecraft/telegram-init-data/blob/main/_autodocs/MANIFEST.md Demonstrates importing the exceptions module to handle specific errors raised by the library. This allows for granular error management. ```python from telegram_init_data.exceptions import InvalidDataError, ExpiredDataError, InvalidSignatureError # Example usage in a try-except block: # try: # validate_init_data(init_data, bot_token) # except InvalidDataError: # print("Invalid data provided.") # except ExpiredDataError: # print("Data has expired.") # except InvalidSignatureError: # print("Invalid signature.") ``` -------------------------------- ### FastAPI Integration with TelegramInitDataAuth Source: https://github.com/icodecraft/telegram-init-data/blob/main/_autodocs/api-overview.md Demonstrates how to use `TelegramInitDataAuth` to authenticate requests using the `Authorization: tma ` header in a FastAPI application. ```APIDOC ## GET /api/user ### Description Retrieves user information after authenticating the request using Telegram Init Data via the `tma` Authorization header. ### Method GET ### Endpoint /api/user ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example **Client sends:** ``` Authorization: tma query_id=...&user=...&auth_date=...&hash=... ``` ### Response #### Success Response (200) - **user** (User) - User information object. #### Response Example ```json { "id": 123, "first_name": "Test", "username": "test_user" } ``` ``` -------------------------------- ### Importing Sign Data Module Source: https://github.com/icodecraft/telegram-init-data/blob/main/_autodocs/MANIFEST.md Shows how to import the sign_data module, presumably for signing data payloads. This is often used in conjunction with validation. ```python from telegram_init_data.sign_data import sign_data # Example usage: # data_to_sign = {'key': 'value'} # bot_token = 'YOUR_BOT_TOKEN' # signed_payload = sign_data(data_to_sign, bot_token) ``` -------------------------------- ### Advanced Init Data Signing and Validation Source: https://github.com/icodecraft/telegram-init-data/blob/main/README.md Create signed init data for testing purposes using the `sign` function, and verify its validity with the `is_valid` function. This is useful for simulating real init data in development environments. ```python from telegram_init_data import sign, is_valid from datetime import datetime # Create test init data test_data = { "query_id": "test_query_id", "user": { "id": 123456789, "first_name": "John", "last_name": "Doe", "username": "johndoe", "language_code": "en" }, "auth_date": datetime.now() } # Sign the data signed_data = sign(test_data, bot_token, datetime.now()) print(f"Signed data: {signed_data}") # Check if data is valid (returns boolean) if is_valid(signed_data, bot_token): print("✅ Data is valid") else: print("❌ Data is invalid") ``` -------------------------------- ### Configure TelegramInitDataAuth for Authorization Header Source: https://github.com/icodecraft/telegram-init-data/blob/main/_autodocs/configuration.md Use TelegramInitDataAuth for standard Authorization header authentication. Specify bot token, scheme name, and optional validation settings. ```python from fastapi import FastAPI, Depends from telegram_init_data import TelegramInitDataAuth, InitData app = FastAPI() # Standard configuration auth = TelegramInitDataAuth( bot_token="YOUR_BOT_TOKEN", scheme_name="tma", validate_options={"expires_in": 3600} ) @app.get("/me") async def get_user(init_data: InitData = Depends(auth)): return {"user_id": init_data["user"]["id"]} # Header format: Authorization: tma ``` -------------------------------- ### Configure 3rd Party Init Data Validation Source: https://github.com/icodecraft/telegram-init-data/blob/main/_autodocs/configuration.md Configure expiration time and test mode for 3rd party init data validation. Use test=True for test environments to select the test public key. ```python from telegram_init_data import validate3rd # Production validation options = {"expires_in": 3600} validate3rd(init_data, bot_id, verify_fn, options) # Test mode validation options = {"expires_in": 3600, "test": True} validate3rd(init_data, bot_id, verify_fn, options) ``` -------------------------------- ### FastAPI Basic Usage with TelegramInitDataAuth Source: https://github.com/icodecraft/telegram-init-data/blob/main/_autodocs/fastapi-integration.md Demonstrates basic integration of Telegram init data validation in a FastAPI application using the `TelegramInitDataAuth` class with default settings. Requires a bot token. ```python from fastapi import FastAPI, Depends from telegram_init_data import TelegramInitDataAuth, InitData app = FastAPI() auth = TelegramInitDataAuth( bot_token="YOUR_BOT_TOKEN" ) @app.get("/me") async def get_user(init_data: InitData = Depends(auth)): user = init_data["user"] return { "id": user["id"], "first_name": user["first_name"] } ``` -------------------------------- ### Basic FastAPI Endpoint with TelegramInitDataBearer Source: https://github.com/icodecraft/telegram-init-data/blob/main/_autodocs/fastapi-integration.md Demonstrates a simple FastAPI endpoint secured by TelegramInitDataBearer. It requires a bot token and injects parsed init data into the endpoint function. ```python from fastapi import FastAPI, Depends from telegram_init_data import TelegramInitDataBearer, InitData app = FastAPI() auth = TelegramInitDataBearer( bot_token="YOUR_BOT_TOKEN" ) @app.get("/profile") async def get_profile(init_data: InitData = Depends(auth)): user = init_data["user"] return user ```