TelegramApiServer Documentation

repository·master·Indexed 20 days ago

https://github.com/xtrime-ru/telegramapiserver

A fast, asynchronous PHP-based Telegram API server built with MadelineProto and Amp HTTP server. It enables interaction with Telegram Bot and User APIs via HTTP GET/POST requests, supporting MadelineProto methods, multi-session management, and real-time updates via Long Polling, Webhooks, or Websockets. Includes features for media uploads, remote authorization, and Docker-based deployment.

Tokens
5.9K
Snippets
21
Records
27
Agent score
70%

What's inside TelegramApiServer

  1. Get Telegram updates via Long Polling, Webhooks, or Websockets

    master

    Telegram is an event-driven platform. You can retrieve updates (like new messages) using three primary methods:

    1. Long Polling: Send a request to the getUpdates endpoint. Use limit and offset to manage the queue and timeout to hold the connection.
    2. Webhooks: Redirect all updates to your own endpoint by calling setWebhook. The URL must be URL-encoded in the query string.
    3. Websockets: Connect to the /events endpoint to receive all events as JSON-RPC 2.0 formatted objects. This is an efficient alternative to webhooks.

    When using multiple sessions, you can subscribe to a specific session's events by appending the session name to the websocket path (e.g., ws://127.0.0.1:9503/events/session_name).

    # Long Polling example
    curl "127.0.0.1:9503/api/getUpdates?limit=3&offset=0&timeout=10.0" -g
    
    # Webhook setup example
    curl "127.0.0.1:9503/api/setWebhook?url=http%3A%2F%2Fexample.com%2Fsome_webhook" -g
  2. Secure the TelegramApiServer API

    master

    By default, the API is only accessible from 127.0.0.1. If you expose the server to the internet (e.g., by changing docker-compose.yml port mappings from 127.0.0.1:9503:9503 to 9503:9503), you must use one of the following protection methods in your .env file:

    • IP_WHITELIST: A comma-separated list of IP addresses allowed to make requests without a password.
    • PASSWORDS: Protects the API with Basic Auth. If PASSWORDS is set, IP_WHITELIST is ignored.

    Basic Auth Examples:

    curl --user username:password "http://127.0.0.1:9503/api/getSelf"
    curl "http://username:password@127.0.0.1:9503/api/getSelf"
    curl --user username:password "http://127.0.0.1:9503/api/getSelf"
  3. Reset or change an existing account/session

    master

    If you need to switch accounts or clear a corrupted session, follow these steps:

    1. Stop the container: docker compose stop api.
    2. Remove the session folder: rm -rf /sessions/session.madeline/.
    3. Remove the session_MTProto_session entry from your MySQL database.
    4. Log out the session from your Telegram app.
    5. Re-run the authorization process.
    docker compose stop api
    rm -rf /sessions/session.madeline/
  4. Upload media files via custom methods

    master

    You can send documents, videos, audio, and other media using methods like sendDocument or sendVideo. The server supports three upload modes:

    • Stream upload: Send a file directly from your client using a multipart/form-data POST request.
    • Remote URL: Provide a JSON object containing a RemoteUrl type and the target URL. The server will fetch it.
    • Local file on server: Provide a JSON object containing a LocalUrl type and the file path relative to the server.

    Note: For all methods, the peer field specifies the recipient (e.g., me).

    # Stream upload from client
    curl --location --request POST 'http://127.0.0.1:9503/api/sendDocument' -g \
    -F peer=me \
    -F caption=key \
    -F file=@screenshot.png
    
    # Remote URL upload
    curl --location --request POST 'http://127.0.0.1:9503/api/sendVideo' \
    --header 'Content-Type: application/json' \
    --data-raw '{
        "peer": "me",
        "file": {
            "_": "RemoteUrl",
            "url": "https://domain.site/storage/video.mp4"
        },
        "parseMode": "HTML",
        "caption": "<b>caption text</b>"
    }'
    
    # Local file on server upload
    curl --location --request POST 'http://127.0.0.1:9503/api/sendDocument' \
    --header 'Content-Type: application/json' \
    --data-raw '{
        "peer": "me",
        "file": {
            "_": "LocalUrl",
            "file": "faust.txt"
        },
        "parseMode":  "HTML",
        "caption": "<b>caption text</b>"
    }'
  5. Authorize a Telegram session

    master

    Before running the server in the background, you must perform an interactive authorization to link your Telegram account.

    1. Get Credentials: Obtain app_id and app_hash from my.telegram.org.
    2. Configure: Add these to your .env.docker file.
    3. Interactive Login:
      • Run the container interactively: docker compose run --rm api.
      • Follow the prompts to enter your phone number (or bot hash) and the Telegram code received on your device.
      • If 2FA is enabled, enter your password.
    4. Verify: Wait for the log message: TelegramApiServer ready. Number of sessions: 1.
    5. Start Service: Once authorized, exit with Ctrl + C and run the server in the background using docker compose up -d.
    CAUTION

    Use only old and valid accounts. New accounts are likely to be banned by Telegram.

    docker compose run --rm api
  6. Authorize sessions remotely

    master

    If a session is not authorized, you can perform remote authorization via API:

    For User accounts:

    1. phoneLogin?phone={phone} (Note: + must be URL-encoded as %2B).
    2. completePhoneLogin?code={code}.
    3. (Optional) complete2falogin?password={password}.
    4. (Optional) completeSignup?firstName={name}.

    For Bots:

    • botLogin?token={token}.

    Persistence: After successful authorization, use api/bot/serialize to save the new session to a file immediately.

    # User phone login example
    curl "http://127.0.0.1:9503/api/users/xtrime/phoneLogin?phone=%2B7123..."
    
    # Bot login example
    curl "http://127.0.0.1:9503/api/bot/botLogin?token=34298141894:aflknsaflknLKNFS"
  7. Manage multiple sessions

    master

    It is highly recommended to run every session in a separate container to ensure stability. You can use a docker-compose.override.yml to add additional service instances, each with its own port mapping and -s (session) command argument.

    Deprecated: Multiple sessions in one container

    Running multiple sessions in a single instance is unstable; a crash in one session will crash all others.

    If you must use one container, you can specify multiple sessions via CLI: php server.php --session=bot --session=users/xtrime

    To target a specific session in an API call, include the session path in the URL:

    • http://127.0.0.1:9503/api/bot/getSelf
    • http://127.0.0.1:9503/api/users/xtrime/getSelf

    Sessions are stored in the sessions/ directory. You can use glob syntax like --session=* to load all sessions.

    # Example docker-compose.override.yml for multiple sessions
    services:
        api-2:
            extends:
                file: docker-compose.base.yml
                service: base-api
            ports:
                - "127.0.0.1:9512:9503"
            command:
                - "-s=session-2"
  8. Install TelegramApiServer via Docker

    master

    To install the server using Docker, clone the repository, prepare the environment file, and pull the necessary images.

    git clone https://github.com/xtrime-ru/TelegramApiServer.git TelegramApiServer
    cd TelegramApiServer
    cp .env.docker.example .env.docker
    docker compose pull
  9. Configure session-specific settings

    master

    You can apply unique settings (like proxies) to specific sessions using two methods:

    1. Environment Files: Use the --env argument when starting the server to point to a specific .env file (e.g., php server.php --env=sessions/.env.session).
    2. JSON Settings Files: Place a %sessionName%.settings.json file in the sessions/ folder. For example, session1.settings.json will apply to the session1 session.

    System API methods for settings:

    • saveSessionSettings: Save settings via query parameters.
    • unlinkSessionSettings: Remove settings for a session.
    • addSession: Provide settings as the second argument during session creation to ensure they persist after restart.
    // Example session.settings.json for adding a proxy
    {
        "connection": {
            "proxies": {
                "\\danog\\MadelineProto\\Stream\\Proxy\\SocksProxy": [
                    {
                      "address": "127.0.0.1",
                      "port": 1234,
                      "username": "user",
                      "password": "pass"
                    }
                ]
            }
        }
    }
  10. Run the TelegramApiServer via CLI

    master

    The TelegramApiServer is a fast, async PHP Telegram parser built with MadelineProto and Swoole. It must be executed via the Command Line Interface (CLI).

    To start the server with default settings, run:

    php server.php

    If you need to listen for external connections, set the --address to 0.0.0.0 and ensure you configure the IP_WHITELIST in your .env file.

    php server.php
  11. Deploy TelegramApiServer using Docker Compose

    master

    You can deploy the TelegramApiServer stack using the provided docker-compose.yml. This configuration sets up two primary services: the api service and a mysql database service.

    By default, the services are bound to 127.0.0.1 to ensure they are only accessible from the local machine. The api service is configured to run with the -s=session command flag.

    services:
      api:
        extends:
          file: docker-compose.base.yml
          service: api
        ports:
          - "127.0.0.1:9503:9503"
        command:
          - "-s=session"
        depends_on:
          - mysql
      mysql:
        extends:
          file: docker-compose.base.yml
          service: mysql
        ports:
          - "127.0.0.1:9507:3306"
    networks:
      default:
        name: telegram-api-server
  12. API Request Examples

    master

    Below are common patterns for interacting with the API:

    TaskURL Pattern
    Get info about channel/userhttp://127.0.0.1:9503/api/getInfo/?id=@xtrime
    Get info about current accounthttp://127.0.0.1:9503/api/getSelf
    Repost a messagehttp://127.0.0.1:9503/api/messages.forwardMessages/?from_peer=@xtrime&to_peer=@xtrime&id=1234
    Get message historyhttp://127.0.0.1:9503/api/messages.getHistory/?peer=@breakingmash&limit=10
    Search globallyhttp://127.0.0.1:9503/api/searchGlobal/?q=Hello%20World&limit=10
    Send a messagehttp://127.0.0.1:9503/api/messages.sendMessage/?peer=@xtrime&message=Hello!
    Copy message (non-repost)http://127.0.0.1:9503/api/copyMessages/?from_peer=@xtrime&to_peer=@xtrime&id[0]=1