### Single Account Example Configuration Source: https://github.com/chigwell/telegram-mcp/blob/main/_autodocs/configuration.md An example `.env` file for a single-account setup, including API credentials and a session string. ```env TELEGRAM_API_ID=123456 TELEGRAM_API_HASH=abcdef1234567890abcdef1234567890 TELEGRAM_SESSION_STRING=1BAADC0DEADBEEF... ``` -------------------------------- ### Multi-Account Example Configuration Source: https://github.com/chigwell/telegram-mcp/blob/main/_autodocs/configuration.md An example `.env` file for a multi-account setup, demonstrating multiple session strings and tool exposure mode. ```env TELEGRAM_API_ID=123456 TELEGRAM_API_HASH=abcdef1234567890abcdef1234567890 TELEGRAM_SESSION_STRING_WORK=1BAADC0DEADBEEF... TELEGRAM_SESSION_STRING_PERSONAL=1DEADBEEF1234567... TELEGRAM_EXPOSED_TOOLS=all ``` -------------------------------- ### Copy Example Environment File Source: https://github.com/chigwell/telegram-mcp/blob/main/README.md Copy the example .env file to your project directory to begin configuration. ```bash cp .env.example .env ``` -------------------------------- ### Install Dependencies and Git Hooks Source: https://github.com/chigwell/telegram-mcp/blob/main/README.md Installs project dependencies and sets up git hooks for pre-commit and pre-push actions. Ensure you have 'uv' installed. ```bash uv sync ``` ```bash uv run pre-commit install --hook-type pre-commit --hook-type pre-push ``` -------------------------------- ### Clone and Install Telegram MCP Server Source: https://github.com/chigwell/telegram-mcp/blob/main/README.md Clone the repository and install the necessary dependencies using uv. Ensure you do not install from PyPI as it is a different project. ```bash git clone https://github.com/chigwell/telegram-mcp.git cd telegram-mcp uv sync ``` -------------------------------- ### Install Proxy Support Package Source: https://github.com/chigwell/telegram-mcp/blob/main/README.md Install the 'python-socks' package required for SOCKS and HTTP proxy support. ```bash uv sync --extra proxy ``` ```bash pip install python-socks ``` -------------------------------- ### Install from GitHub (Virtual Environment) Source: https://github.com/chigwell/telegram-mcp/blob/main/README.md Install the Telegram MCP repository directly from GitHub into a virtual environment using a specific release tag or commit. ```bash python -m venv .venv . .venv/bin/activate pip install "git+https://github.com/chigwell/telegram-mcp.git@" ``` -------------------------------- ### MCP Client Configuration (Installed from GitHub) Source: https://github.com/chigwell/telegram-mcp/blob/main/README.md Configure your MCP client to run the console script installed from GitHub. ```json { "mcpServers": { "telegram-mcp": { "command": "/full/path/to/.venv/bin/telegram-mcp", "env": { "TELEGRAM_API_ID": "your_api_id_here", "TELEGRAM_API_HASH": "your_api_hash_here", "TELEGRAM_SESSION_STRING": "your_session_string_here" } } } } ``` -------------------------------- ### Run Telegram MCP Server Source: https://github.com/chigwell/telegram-mcp/blob/main/README.md Start the Telegram MCP server locally using the 'uv' command. ```bash uv run main.py ``` -------------------------------- ### Single-Account Environment Variables Source: https://github.com/chigwell/telegram-mcp/blob/main/README.md Set your Telegram API credentials and session string for a single-account setup. ```env TELEGRAM_API_ID=your_api_id_here TELEGRAM_API_HASH=your_api_hash_here TELEGRAM_SESSION_STRING=your_session_string_here ``` -------------------------------- ### Example Full Error Message Source: https://github.com/chigwell/telegram-mcp/blob/main/_autodocs/errors.md Shows a complete error message format that includes the error code and a suggestion to check logs for details. ```plaintext An error occurred (code: MSG-ERR-521). Check mcp_errors.log for details. ``` -------------------------------- ### Check Linting with Flake8 Source: https://github.com/chigwell/telegram-mcp/blob/main/README.md Run Flake8 to check for style guide violations and potential errors in the codebase. ```bash uv run flake8 . ``` -------------------------------- ### Run Telegram MCP Server Source: https://github.com/chigwell/telegram-mcp/blob/main/_autodocs/README.md Start the Telegram MCP server using the 'uv run main.py' command. Optionally, specify allowed file roots for file operations. ```bash uv run main.py # or with allowed roots: uv run main.py /data/telegram /tmp/telegram-mcp ``` -------------------------------- ### Run Telegram MCP with Docker Compose Source: https://github.com/chigwell/telegram-mcp/blob/main/README.md Start the Telegram MCP service using Docker Compose, rebuilding the image if necessary. ```bash docker compose up --build ``` -------------------------------- ### Configure Allowed File Roots via CLI Arguments Source: https://github.com/chigwell/telegram-mcp/blob/main/_autodocs/configuration.md Specify allowed root directories for file operations when starting the Telegram MCP server using command-line arguments. ```bash uv run main.py /data/telegram /tmp/telegram-mcp ``` -------------------------------- ### Get TelegramClient Instance Source: https://github.com/chigwell/telegram-mcp/blob/main/_autodocs/runtime-helpers.md Resolves an account label to a TelegramClient instance. Use when you need to interact with a specific Telegram account. ```python from telegram_mcp.runtime import get_client cl = get_client("work") me = await cl.get_me() ``` -------------------------------- ### Per-Account Proxy Overrides Source: https://github.com/chigwell/telegram-mcp/blob/main/_autodocs/configuration.md Suffixed proxy variables override global settings for specific accounts. Example shows overrides for 'work' and 'personal' accounts. ```bash TELEGRAM_PROXY_TYPE=socks5 TELEGRAM_PROXY_HOST=global-proxy.example.com TELEGRAM_PROXY_PORT=1080 TELEGRAM_PROXY_TYPE_WORK=http TELEGRAM_PROXY_HOST_WORK=work-proxy.example.com TELEGRAM_PROXY_PORT_WORK=3128 TELEGRAM_PROXY_TYPE_PERSONAL=mtproxy TELEGRAM_PROXY_HOST_PERSONAL=mtproxy.example.com TELEGRAM_PROXY_PORT_PERSONAL=443 TELEGRAM_PROXY_SECRET_PERSONAL=ee0123456789abcdef... ``` -------------------------------- ### Example Error Code Format Source: https://github.com/chigwell/telegram-mcp/blob/main/_autodocs/errors.md Illustrates the structure of error codes returned by the system, comprising a category, 'ERR', and a number. ```plaintext {CATEGORY}-ERR-{NUMBER} ``` -------------------------------- ### Get Sticker Sets Source: https://github.com/chigwell/telegram-mcp/blob/main/_autodocs/api-reference/media.md Lists all available sticker sets for your account, returning a JSON-formatted array with details like short name, title, and sticker count. Useful for identifying sticker sets before sending them. ```python async def get_sticker_sets( account: str = None ) -> str: ``` ```python from main import get_sticker_sets import json result = await get_sticker_sets() sets = json.loads(result) for s in sets['results']: print(f"{s['title']} ({s['short_name']})") ``` -------------------------------- ### Error Code Format Example Source: https://github.com/chigwell/telegram-mcp/blob/main/_autodocs/INDEX.md Telegram MCP uses a specific format for its error codes. This example shows a typical error code structure. ```text Format: {PREFIX}-ERR-{NUMBER} Example: MSG-ERR-521 ``` -------------------------------- ### Multi-Account Session Strings Source: https://github.com/chigwell/telegram-mcp/blob/main/_autodocs/configuration.md Environment variables for managing multiple accounts via session strings. Suffixed variables define account labels. ```bash TELEGRAM_SESSION_STRING_WORK= TELEGRAM_SESSION_STRING_PERSONAL= TELEGRAM_SESSION_STRING_CUSTOM= ``` -------------------------------- ### Initialize StringSession Source: https://github.com/chigwell/telegram-mcp/blob/main/_autodocs/runtime-helpers.md Creates a TelegramClient session using a serialized string, suitable for environments without database management. This session is non-persistent and rebuilt on startup. ```python from telethon.sessions import StringSession session = StringSession(session_string) ``` -------------------------------- ### Multi-Account Session Files Source: https://github.com/chigwell/telegram-mcp/blob/main/_autodocs/configuration.md Environment variables for managing multiple accounts via session files. Each account uses a separate file path. ```bash TELEGRAM_SESSION_NAME_WORK= TELEGRAM_SESSION_NAME_PERSONAL= ``` -------------------------------- ### Promote User to Admin (Full Rights) Source: https://github.com/chigwell/telegram-mcp/blob/main/_autodocs/api-reference/groups.md Promote a user to an administrator with all available permissions in a group or channel. Requires admin privileges. ```python from main import promote_admin # Full admin rights await promote_admin( chat_id="@mygroup", user_id=123456789 ) ``` -------------------------------- ### Access and Modify Folders Source: https://github.com/chigwell/telegram-mcp/blob/main/_autodocs/api-reference/folders.md Demonstrates how to retrieve all folders, find a specific folder by its title, and then add a chat to that identified folder. ```python # Get all folders folders = await list_folders() # Find folder by name for folder in folders['results']: if folder['title'] == "Important": # Add chat to that folder await add_chat_to_folder( folder_id=folder['id'], chat_id="@channel" ) ``` -------------------------------- ### Get Contact IDs Source: https://github.com/chigwell/telegram-mcp/blob/main/_autodocs/api-reference/contacts.md Retrieves a comma-separated string of all contact IDs associated with the account. This is useful for filtering or batch operations. ```python from main import get_contact_ids result = await get_contact_ids() ids = result.replace("Contact IDs: ", "").split(", ") ``` -------------------------------- ### Check Multi-Account Mode Source: https://github.com/chigwell/telegram-mcp/blob/main/_autodocs/runtime-helpers.md Checks if multiple Telegram accounts are configured in the system. Useful for conditional logic based on account setup. ```python from telegram_mcp.runtime import is_multi_mode if is_multi_mode(): print("Multiple accounts configured") else: print("Single account") ``` -------------------------------- ### Get Scheduled Messages Source: https://github.com/chigwell/telegram-mcp/blob/main/_autodocs/api-reference/messages.md Retrieve a list of all pending scheduled messages in a specified chat. Requires admin rights to view messages. ```python from main import get_scheduled_messages result = await get_scheduled_messages(chat_id="@mychannel") print(result) # Output: # Scheduled messages in chat @mychannel (2): # ID: 12345 | Scheduled: 2026-05-01T09:00:00+00:00 | Text: Good morning! # ID: 12346 | Scheduled: 2026-05-02T10:00:00+00:00 | Text: See you tomorrow! ``` -------------------------------- ### Environment Variables for Multi-Account with Per-Account Proxies Source: https://github.com/chigwell/telegram-mcp/blob/main/_autodocs/configuration.md Set up multiple Telegram accounts with distinct session strings and configure unique proxy settings for each account. ```env TELEGRAM_API_ID=123456 TELEGRAM_API_HASH=abcdef1234567890abcdef1234567890 TELEGRAM_SESSION_STRING_WORK=1BAADC0DEADBEEF... TELEGRAM_SESSION_STRING_PERSONAL=1DEADBEEF1234567... TELEGRAM_PROXY_TYPE=http TELEGRAM_PROXY_HOST=default-proxy.example.com TELEGRAM_PROXY_PORT=3128 TELEGRAM_PROXY_TYPE_WORK=socks5 TELEGRAM_PROXY_HOST_WORK=work-proxy.example.com TELEGRAM_PROXY_PORT_WORK=1080 TELEGRAM_PROXY_TYPE_PERSONAL=mtproxy TELEGRAM_PROXY_HOST_PERSONAL=mtproxy.example.com TELEGRAM_PROXY_PORT_PERSONAL=443 TELEGRAM_PROXY_SECRET_PERSONAL=ee0123456789abcdef... ``` -------------------------------- ### Handle Chat Not Found Error Source: https://github.com/chigwell/telegram-mcp/blob/main/_autodocs/errors.md Demonstrates how to catch a 'Chat not found' error when attempting to get a chat with an invalid ID or username. ```python try: await get_chat("@invalid_channel") except: # Chat not found error pass ``` -------------------------------- ### Run All Pre-Commit Checks Locally Source: https://github.com/chigwell/telegram-mcp/blob/main/README.md Executes all configured pre-commit hooks across all files in the repository to ensure code quality and consistency before committing. ```bash uv run pre-commit run --all-files ``` -------------------------------- ### Get Banned Users from Telegram Group Source: https://github.com/chigwell/telegram-mcp/blob/main/_autodocs/api-reference/groups.md List all users who have been banned or kicked from a group or channel. This read-only tool is useful for moderation reviews. ```python from main import get_banned_users result = await get_banned_users(chat_id=123456789) ``` -------------------------------- ### Single Account Session String Source: https://github.com/chigwell/telegram-mcp/blob/main/_autodocs/configuration.md Required environment variable for single-account authentication using a session string. Store this securely. ```bash TELEGRAM_SESSION_STRING= ``` -------------------------------- ### Get Contact Chats Source: https://github.com/chigwell/telegram-mcp/blob/main/_autodocs/api-reference/contacts.md Lists all chats involving a specific contact, identified by their ID or username. This includes direct messages and shared groups/channels. ```python from main import get_contact_chats import json result = await get_contact_chats(contact_id=123456789) chats = json.loads(result) for chat in chats['results']: print(f"{chat['type']}: {chat['title']} ({chat['chat_id']})") ``` -------------------------------- ### Media Module Source: https://github.com/chigwell/telegram-mcp/blob/main/_autodocs/SUMMARY.txt Functions for sending and downloading files and media. ```APIDOC ## upload file ### Description Uploads a file to be sent as a message attachment. ### Method POST ### Endpoint /media/upload ### Parameters #### Request Body - **file_path** (string) - Required - The local path to the file to upload. - **caption** (string) - Optional - A caption for the file. ### Request Example { "file_path": "/path/to/your/document.pdf", "caption": "Important document" } ### Response #### Success Response (200) - **file_id** (string) - The unique identifier for the uploaded file. - **file_reference** (string) - A reference to the uploaded file for sending. #### Response Example { "file_id": "file_abc", "file_reference": "ref_xyz" } ``` ```APIDOC ## download file ### Description Downloads a file associated with a message. ### Method GET ### Endpoint /media/download/{file_id} ### Parameters #### Path Parameters - **file_id** (string) - Required - The ID of the file to download. #### Query Parameters - **output_path** (string) - Required - The local path where the file should be saved. ### Response #### Success Response (200) - **status** (string) - The status of the download operation (e.g., 'downloaded'). - **file_path** (string) - The full path to the downloaded file. #### Response Example { "status": "downloaded", "file_path": "/path/to/saved/document.pdf" } ``` -------------------------------- ### Handle MEDIA Errors in Python Source: https://github.com/chigwell/telegram-mcp/blob/main/_autodocs/errors.md Illustrates handling 'Invalid file extension' errors when sending voice messages, 'Path traversal rejected' errors when accessing files, and 'No allowed roots configured' or 'File path rejected' errors during media downloads. Ensure correct file formats and configure allowed roots for file operations. ```python try: await send_voice(chat_id, file_path="/data/voice.mp3") except: # "Invalid file extension" - must be .ogg or .opus pass try: await send_file(chat_id, file_path="../../etc/passwd") except: # "Path traversal rejected" pass try: await download_media(chat_id, message_id) except: # "No allowed roots configured" or "File path rejected" # Configure allowed roots in server startup pass ``` -------------------------------- ### Get Specific Chat Details Source: https://github.com/chigwell/telegram-mcp/blob/main/_autodocs/api-reference/chats.md Retrieves detailed information for a specific chat using its ID, username, or link. Supports multi-account mode. ```python async def get_chat( chat_id: Union[int, str], account: str = None ) -> str: # ... function body ... pass ``` ```python from main import get_chat # Get by ID result = await get_chat(chat_id=123456789) # Get by username result = await get_chat(chat_id="@mychannel") ``` -------------------------------- ### Run Pytest Suite Source: https://github.com/chigwell/telegram-mcp/blob/main/README.md Execute the project's test suite using the 'uv' command. ```bash uv run pytest ``` -------------------------------- ### Get Own User Account Information Source: https://github.com/chigwell/telegram-mcp/blob/main/_autodocs/api-reference/profile.md Retrieves the logged-in user's account information. This is a read-only tool and returns information only about the current account. ```python async def get_me( account: str = None ) -> str ``` ```python from main import get_me import json result = await get_me() user_info = json.loads(result) print(f"Logged in as: {user_info['name']}") ``` -------------------------------- ### JSON Log Entry Format Source: https://github.com/chigwell/telegram-mcp/blob/main/_autodocs/errors.md An example of a JSON-formatted log entry for errors, including timestamp, logger name, level, message, and exception information. ```json { "asctime": "2026-04-01T12:30:45.123456+0000", "name": "telegram_mcp", "levelname": "ERROR", "message": "Error in get_chat (chat_id=123456789) - Code: CHAT-ERR-042", "exc_info": "Traceback..." } ``` -------------------------------- ### Enable File Operations with Allowed Roots Source: https://github.com/chigwell/telegram-mcp/blob/main/_autodocs/README.md Configure allowed root directories for file operations by passing them as arguments when running the server. This enhances security by restricting file access. ```bash uv run main.py /home/user/downloads /tmp/uploads ``` -------------------------------- ### list_folders Source: https://github.com/chigwell/telegram-mcp/blob/main/_autodocs/api-reference/folders.md Lists all folders in your account. This is a read-only tool that can fan out to all accounts in multi-account mode if no account is specified. ```APIDOC ## list_folders ### Description List all folders in your account. This is a read-only tool. ### Method GET (implied) ### Endpoint /folders ### Parameters #### Query Parameters - **account** (str) - Optional - Account label in multi-account mode ### Returns JSON-formatted array of folder objects with: - `id` (int): Folder ID - `title` (str): Folder name (sanitized) - `emoji` (str, optional): Folder emoji icon - `color` (int, optional): Color ID (Telegram color scheme) - `chat_count` (int, optional): Number of chats in folder - `pinned` (list, optional): IDs of pinned chats ### Raises - Connection errors ### Example ```python from main import list_folders import json result = await list_folders() folders = json.loads(result) for folder in folders['results']: print(f"{folder['emoji']} {folder['title']} ({folder.get('chat_count', 0)} chats)") ``` ``` -------------------------------- ### get_messages Source: https://github.com/chigwell/telegram-mcp/blob/main/_autodocs/api-reference/messages.md Retrieves paginated messages from a specified Telegram chat. Supports filtering by page and page size, and can be used with specific accounts in multi-account setups. ```APIDOC ## get_messages ### Description Get paginated messages from a specific chat. ### Method GET (conceptual, as this is an SDK method) ### Endpoint (Not applicable for SDK method) ### Parameters #### Path Parameters (Not applicable for SDK method) #### Query Parameters - **chat_id** (Union[int, str]) - Required - The ID (int), username (@username), or chat link of the target chat - **page** (int) - Optional - Page number (1-indexed) - **page_size** (int) - Optional - Number of messages per page (max 100) - **account** (str) - Optional - Account label in multi-account mode; if omitted and single account, uses that account ### Request Example ```python from main import get_messages # Get first 10 messages from a chat result = await get_messages(chat_id="@mychannel", page_size=10) print(result) # Get second page result = await get_messages(chat_id=123456789, page=2, page_size=20) ``` ### Response #### Success Response Human-readable text representation of messages. Each message includes: - Message ID - Sender name - Date/time - Media type (if attached) - Message text (sanitized) - Engagement metrics (reactions, replies count) - Flags (pinned, edited, forwarded, etc.) #### Response Example (Not explicitly provided in source, but described above) ### Errors - `ValueError`: Chat not found or ID invalid - Connection errors if unable to reach Telegram - Permission errors if not a member of the chat ``` -------------------------------- ### Build Telegram MCP Docker Image Source: https://github.com/chigwell/telegram-mcp/blob/main/README.md Create a Docker image for the Telegram MCP project tagged as 'telegram-mcp:latest'. ```bash docker build -t telegram-mcp:latest . ``` -------------------------------- ### Get Admins of a Telegram Group Source: https://github.com/chigwell/telegram-mcp/blob/main/_autodocs/api-reference/groups.md Retrieve a list of all administrators in a group or channel. This read-only tool includes the creator and promoted admins, along with their permissions. ```python from main import get_admins import json result = await get_admins(chat_id="@mygroup") admins = json.loads(result) for admin in admins['results']: print(f"{admin['name']} (ID: {admin['id']})") ``` -------------------------------- ### Get Exposed Tools Mode Source: https://github.com/chigwell/telegram-mcp/blob/main/_autodocs/runtime-helpers.md Retrieves the configured MCP tool exposure mode, which can be 'all' or 'read-only'. This setting respects the TELEGRAM_EXPOSED_TOOLS environment variable. ```python def _get_exposed_tools_mode(value: Optional[str] = None) -> str ``` -------------------------------- ### create_channel Source: https://github.com/chigwell/telegram-mcp/blob/main/_autodocs/api-reference/groups.md Creates a new broadcast channel with a specified title and an optional description. The caller automatically becomes an admin. ```APIDOC ## create_channel ### Description Create a new broadcast channel. ### Method `POST` (Assumed based on 'write-only tool' and creation action) ### Endpoint `/channels/create` (Assumed based on module and function name) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **title** (str) - Required - Channel name - **description** (str) - Optional - Channel description - **account** (str) - Optional - Account label ### Request Example ```json { "title": "My Blog", "description": "Updates and announcements", "account": null } ``` ### Response #### Success Response (200) - **message** (str) - Success message: "Channel {title} created." #### Response Example ```json { "message": "Channel My Blog created." } ``` ### Raises - Connection errors - Invalid title format - Channel quota exceeded ``` -------------------------------- ### Get Media Label Source: https://github.com/chigwell/telegram-mcp/blob/main/_autodocs/api-reference/messages.md Returns a human-readable label for media attached to a message. This function is useful for identifying the type of media content within a message. ```python def get_media_label(msg) -> str Returns a human-readable label for media attached to a message, or empty string if none. Detected types: - "photo" - "video" - "audio" - "voice" - "video_note" - "gif" - "document: {filename}" - "sticker {emoji}" - "contact" - "geo" - "poll" - "media" (unknown type) ``` -------------------------------- ### Configure MCP Client Roots via JSON Source: https://github.com/chigwell/telegram-mcp/blob/main/README.md Set up allowed roots and environment variables for the Telegram MCP server within an MCP client configuration file. ```json { "mcpServers": { "telegram-mcp": { "command": "uv", "args": [ "--directory", "/full/path/to/telegram-mcp", "run", "main.py", "/data/telegram", "/tmp/telegram-mcp" ], "env": { "TELEGRAM_API_ID": "your_api_id_here", "TELEGRAM_API_HASH": "your_api_hash_here", "TELEGRAM_SESSION_STRING": "your_session_string_here" } } } } ``` -------------------------------- ### Get Paginated List of Chats Source: https://github.com/chigwell/telegram-mcp/blob/main/_autodocs/api-reference/chats.md Retrieves a paginated list of all chats, including DMs, groups, channels, and archived chats. Supports multi-account mode. ```python async def get_chats( account: str = None, page: int = 1, page_size: int = 20 ) -> str: # ... function body ... pass ``` ```python from main import get_chats result = await get_chats(page=1, page_size=10) print(result) ``` -------------------------------- ### MCP Client Configuration (Local Checkout) Source: https://github.com/chigwell/telegram-mcp/blob/main/README.md Configure MCP clients like Claude Desktop or Cursor to connect to a local checkout of the Telegram MCP project. ```json { "mcpServers": { "telegram-mcp": { "command": "uv", "args": [ "--directory", "/full/path/to/telegram-mcp", "run", "main.py" ], "env": { "TELEGRAM_API_ID": "your_api_id_here", "TELEGRAM_API_HASH": "your_api_hash_here", "TELEGRAM_SESSION_STRING": "your_session_string_here" } } } } ``` -------------------------------- ### Get Direct Chat by Contact Source: https://github.com/chigwell/telegram-mcp/blob/main/_autodocs/api-reference/contacts.md Finds direct chats with a specific contact by name, username, or phone. Returns a JSON-formatted array of matching direct chats. ```python from main import get_direct_chat_by_contact import json result = await get_direct_chat_by_contact(contact_query="john") chats = json.loads(result) for chat in chats['results']: print(f"Chat {chat['chat_id']} with {chat['contact']}") ``` -------------------------------- ### Get Paginated Messages from a Chat Source: https://github.com/chigwell/telegram-mcp/blob/main/_autodocs/api-reference/messages.md Retrieves messages from a specified chat, supporting pagination and custom page sizes. User-controlled fields are sanitized to prevent injection. ```python async def get_messages( chat_id: Union[int, str], page: int = 1, page_size: int = 20, account: str = None ) -> str ``` ```python from main import get_messages # Get first 10 messages from a chat result = await get_messages(chat_id="@mychannel", page_size=10) print(result) # Get second page result = await get_messages(chat_id=123456789, page=2, page_size=20) ``` -------------------------------- ### promote_admin Source: https://github.com/chigwell/telegram-mcp/blob/main/_autodocs/api-reference/groups.md Makes a user an administrator in a group or channel, with configurable permissions. Requires admin privileges and cannot promote users above your own rank. ```APIDOC ## promote_admin ### Description Makes a user an administrator in a group or channel, with configurable permissions. Requires admin privileges and cannot promote users above your own rank. ### Method POST ### Endpoint `/promote_admin` ### Parameters #### Path Parameters - **chat_id** (Union[int, str]) - Required - Group/channel ID - **user_id** (Union[int, str]) - Required - User ID or username to promote - **account** (str) - Optional - Account label #### Query Parameters - **change_info** (bool) - Optional - Can edit chat title/description/photo (default: True) - **post_messages** (bool) - Optional - Can post messages (default: True) - **edit_messages** (bool) - Optional - Can edit messages (default: True) - **delete_messages** (bool) - Optional - Can delete messages (default: True) - **ban_users** (bool) - Optional - Can ban/remove users (default: True) - **invite_users** (bool) - Optional - Can add members (default: True) - **pin_messages** (bool) - Optional - Can pin messages (default: True) - **manage_topics** (bool) - Optional - Can manage forum topics (default: False) - **manage_video_chats** (bool) - Optional - Can start video/voice chats (default: False) ### Returns Success message: "User promoted to admin in {chat_title}." ### Raises - `ChatAdminRequiredError`: Caller not admin - `ValueError`: User not found or already admin - Connection errors ### Request Example ```json { "chat_id": "@mygroup", "user_id": 123456789, "change_info": true, "post_messages": true, "edit_messages": true, "delete_messages": true, "ban_users": true, "invite_users": true, "pin_messages": true, "manage_topics": false, "manage_video_chats": false, "account": null } ``` ### Response #### Success Response (200) - **message** (str) - Success message #### Response Example ```json { "message": "User promoted to admin in MyGroup." } ``` ``` -------------------------------- ### Run Pre-Push Checks Locally Source: https://github.com/chigwell/telegram-mcp/blob/main/README.md Executes pre-push hooks to perform checks before allowing a push to the remote repository. This helps catch issues before they reach the main branch. ```bash uv run pre-commit run --hook-stage pre-push --all-files ``` -------------------------------- ### Get Normalized Entity Type Source: https://github.com/chigwell/telegram-mcp/blob/main/_autodocs/runtime-helpers.md Returns a human-readable string representing the entity type (User, Group, Channel). Useful for conditional logic based on entity classification. ```python from telegram_mcp.runtime import get_entity_type entity_type = get_entity_type(entity) if entity_type == "Channel": print("This is a broadcast channel") ``` -------------------------------- ### Handle PROFILE Errors in Python Source: https://github.com/chigwell/telegram-mcp/blob/main/_autodocs/errors.md Shows how to handle 'Name too long' errors when updating a profile, 'Unsupported privacy key' errors when setting privacy settings, and 'Target is not a bot' errors when retrieving bot information. Validate input lengths and use supported privacy keys for profile updates. ```python try: await update_profile(first_name="A" * 100) except: # Name too long, limit typically 64 chars pass try: await set_privacy_settings(key="unknown_key") except: # "Unsupported privacy key 'unknown_key'" # Use: "status", "phone", or "profile_photo" pass try: await get_bot_info(bot_username="regular_user") except: # "Target is not a bot" pass ``` -------------------------------- ### Get Bot Information Source: https://github.com/chigwell/telegram-mcp/blob/main/_autodocs/api-reference/profile.md Retrieves publicly available information about a Telegram bot, including its ID, name, description, and commands. This read-only tool sanitizes user-generated fields. ```python from main import get_bot_info import json result = await get_bot_info(bot_username="mybot") info = json.loads(result) print(f"Description: {info.get('description')}") for cmd in info.get('commands', []): print(f" /{cmd['command']} - {cmd['description']}") ``` -------------------------------- ### create_folder Source: https://github.com/chigwell/telegram-mcp/blob/main/_autodocs/api-reference/folders.md Creates a new chat folder with specified title, included/excluded chats, and optional emoji/color. This is a write-only tool and is idempotent. ```APIDOC ## create_folder ### Description Create a new chat folder. This is a write-only tool and is idempotent. ### Method POST (implied) ### Endpoint /folders ### Parameters #### Request Body - **title** (str) - Required - Folder name (max 128 characters) - **included** (list) - Optional - Chat IDs to include in folder - **excluded** (list) - Optional - Chat IDs to explicitly exclude - **emoji** (str) - Optional - Optional emoji icon - **color** (int) - Optional - Optional color ID (0-7 for Telegram colors) - **account** (str) - Optional - Account label ### Returns Success message: "Folder {title} created with ID {folder_id}." ### Raises - `ValueError`: Invalid chat IDs or folder already exists - Title too long or invalid - Connection errors ### Example ```python from main import create_folder # Create folder with included chats await create_folder( title="Important", included=[123456789, 987654321], emoji="⭐", color=1 ) # Create folder excluding specific chats await create_folder( title="Everything Else", excluded=[111111111] ) ``` ### Color Values Telegram folder colors (0-7): - `0`: Default (varies by client) - `1`: Red - `2`: Orange - `3`: Yellow - `4`: Green - `5`: Cyan/Blue - `6`: Purple/Violet - `7`: Pink ``` -------------------------------- ### Advanced Runtime Helpers Source: https://github.com/chigwell/telegram-mcp/blob/main/_autodocs/SUMMARY.txt This section covers advanced usage patterns for the Telegram MCP Server, including multi-account support, entity resolution, custom error handling, and connection management. ```APIDOC ## Advanced Runtime Helpers This section covers advanced usage patterns for the Telegram MCP Server. ### Multi-account support with decorators Details on how to implement multi-account support using decorators. ### Entity resolution with auto-cache-warming Information on resolving entities and utilizing auto-cache-warming. ### Custom error handling Guidance on implementing custom error handling mechanisms. ### Connection management Documentation for managing server connections. ``` -------------------------------- ### Get Entity Filter Type Source: https://github.com/chigwell/telegram-mcp/blob/main/_autodocs/runtime-helpers.md Determines the filter type (user, group, channel) for a given entity, compatible with list_chats functions. Returns None if the entity type is not recognized. ```python def get_entity_filter_type(entity: Any) -> Optional[str]: ``` -------------------------------- ### SOCKS5/SOCKS4/HTTP Proxy Configuration Source: https://github.com/chigwell/telegram-mcp/blob/main/_autodocs/configuration.md Optional environment variables for routing traffic through SOCKS5, SOCKS4, or HTTP proxies. Requires the 'python-socks' package. ```bash TELEGRAM_PROXY_TYPE=socks5|socks4|http TELEGRAM_PROXY_HOST=proxy.example.com TELEGRAM_PROXY_PORT=1080 TELEGRAM_PROXY_USERNAME=optional_user TELEGRAM_PROXY_PASSWORD=optional_pass TELEGRAM_PROXY_RDNS=true|false ``` -------------------------------- ### Get Marked Entity ID Source: https://github.com/chigwell/telegram-mcp/blob/main/_autodocs/runtime-helpers.md Converts a Telegram entity to a Telethon-compatible marked ID. Handles users, groups, and channels with specific negative ID conventions for groups and channels. ```python def get_marked_id(entity: Any) -> int: ``` -------------------------------- ### Get Privacy Settings Source: https://github.com/chigwell/telegram-mcp/blob/main/_autodocs/api-reference/profile.md Retrieves the current privacy settings for the account. This is a read-only tool focused on last seen status privacy and may return errors on certain API versions. ```python from main import get_privacy_settings result = await get_privacy_settings() print(result) ``` -------------------------------- ### Promote User to Admin (Limited Rights) Source: https://github.com/chigwell/telegram-mcp/blob/main/_autodocs/api-reference/groups.md Promote a user to an administrator with specific, limited permissions, such as only the ability to delete messages. Requires admin privileges. ```python from main import promote_admin # Limited admin (only delete messages) await promote_admin( chat_id="@mygroup", user_id=123456789, change_info=False, post_messages=False, edit_messages=False, ban_users=False, invite_users=False, pin_messages=False, delete_messages=True ) ``` -------------------------------- ### Get Media Information Source: https://github.com/chigwell/telegram-mcp/blob/main/_autodocs/api-reference/media.md Retrieves detailed information about media content within a specific message. Useful for inspecting media before download and obtaining file IDs for programmatic use. This is a read-only tool. ```python async def get_media_info( chat_id: Union[int, str], message_id: int, account: str = None ) -> str ``` ```python from main import get_media_info import json result = await get_media_info( chat_id="@mychannel", message_id=12345 ) info = json.loads(result) print(f"File size: {info.get('file_size')} bytes") ``` -------------------------------- ### Invite Users to a Group or Channel Source: https://github.com/chigwell/telegram-mcp/blob/main/_autodocs/api-reference/groups.md Add users to an existing group or channel. This function requires the chat ID and a list of user IDs to invite. Admin permission is necessary, and up to 200 users can be invited per call. Users who are already members are silently skipped. ```python async def invite_to_group( chat_id: Union[int, str], user_ids: List[Union[int, str]], account: str = None ) -> str ``` ```python from main import invite_to_group await invite_to_group( chat_id="@mychannel", user_ids=[123456789, "@bob", "@charlie"] ) ``` -------------------------------- ### Get User Photos Source: https://github.com/chigwell/telegram-mcp/blob/main/_autodocs/api-reference/profile.md Retrieve profile photos for a given user. This is a read-only tool that returns metadata for publicly visible photos. The limit parameter controls the maximum number of photos to retrieve. ```python async def get_user_photos( user_id: Union[int, str], limit: int = 10, account: str = None ) -> str ``` ```python from main import get_user_photos import json result = await get_user_photos(user_id="username", limit=20) photos = json.loads(result) print(f"Found {len(photos['results'])} photos") ``` -------------------------------- ### MTProxy Configuration Source: https://github.com/chigwell/telegram-mcp/blob/main/_autodocs/configuration.md Optional environment variables for routing traffic through an MTProxy. Requires a secret key for authentication. ```bash TELEGRAM_PROXY_TYPE=mtproxy TELEGRAM_PROXY_HOST=mtproxy.example.com TELEGRAM_PROXY_PORT=443 TELEGRAM_PROXY_SECRET=ee0123456789abcdef0123456789abcdef ``` -------------------------------- ### Get Participants of a Group or Channel Source: https://github.com/chigwell/telegram-mcp/blob/main/_autodocs/api-reference/groups.md Retrieve a list of members from a group or channel. You can filter participants by type (e.g., 'admins') and use offset and limit for pagination. The result is a JSON-formatted array of member objects. ```python async def get_participants( chat_id: Union[int, str], filter_type: str = None, offset: int = 0, limit: int = 100, account: str = None ) -> str ``` ```python from main import get_participants import json # Get all members result = await get_participants(chat_id="@mychannel", limit=50) members = json.loads(result) # Get admins only result = await get_participants( chat_id=123456789, filter_type="admins" ) ``` -------------------------------- ### Generate Session String from GitHub Source: https://github.com/chigwell/telegram-mcp/blob/main/README.md Generate a session string without cloning the repository by sourcing it directly from GitHub. ```bash uvx --from "git+https://github.com/chigwell/telegram-mcp.git@" telegram-mcp-generate-session ``` -------------------------------- ### Environment Variables for Proxy and Read-Only Mode Source: https://github.com/chigwell/telegram-mcp/blob/main/_autodocs/configuration.md Configure API credentials, proxy server details, and set the tool exposure mode to 'read-only' using environment variables. ```env TELEGRAM_API_ID=123456 TELEGRAM_API_HASH=abcdef1234567890abcdef1234567890 TELEGRAM_SESSION_STRING=1BAADC0DEADBEEF... TELEGRAM_PROXY_TYPE=socks5 TELEGRAM_PROXY_HOST=proxy.example.com TELEGRAM_PROXY_PORT=1080 TELEGRAM_PROXY_USERNAME=proxyuser TELEGRAM_PROXY_PASSWORD=proxypass TELEGRAM_EXPOSED_TOOLS=read-only ``` -------------------------------- ### get_client Source: https://github.com/chigwell/telegram-mcp/blob/main/_autodocs/runtime-helpers.md Resolves an account label to a TelegramClient instance. It handles both single and multi-account configurations, returning the appropriate client or raising an error if the account is not found or required but omitted. ```APIDOC ## get_client ### Description Resolves an account label to a TelegramClient instance. If `account` is omitted in multi-account mode, it defaults to the sole account if single-account mode is enabled. ### Function Signature ```python def get_client(account: str = None) -> TelegramClient ``` ### Parameters #### Query Parameters - **account** (str, optional): The label of the account to resolve. If omitted and in single-account mode, the sole account is used. ### Returns - `TelegramClient`: An instance of `TelegramClient` for the specified account. ### Raises - `ValueError`: If the account is not found or if it's required in multi-account mode but omitted. ### Example ```python from telegram_mcp.runtime import get_client cl = get_client("work") me = await cl.get_me() ``` ``` -------------------------------- ### Get Privacy Settings for Last Seen Status Source: https://github.com/chigwell/telegram-mcp/blob/main/_autodocs/api-reference/profile.md Retrieves the current privacy settings related to the visibility of your last seen status. This function may raise a TypeError due to version compatibility issues with Telethon. ```python async def get_privacy_settings( account: str = None ) -> str ``` -------------------------------- ### Single Account Session File Source: https://github.com/chigwell/telegram-mcp/blob/main/_autodocs/configuration.md Required environment variable for single-account session storage using a file path. Less secure than session strings. ```bash TELEGRAM_SESSION_NAME= ```