{"id":14036775,"url":"https://github.com/xtrime-ru/TelegramApiServer","last_synced_at":"2025-07-27T04:31:58.539Z","repository":{"id":35021587,"uuid":"162985361","full_name":"xtrime-ru/TelegramApiServer","owner":"xtrime-ru","description":"Fast, simple, async php telegram api server: MadelineProto + Amp HTTP Server","archived":false,"fork":false,"pushed_at":"2024-11-05T16:28:02.000Z","size":805,"stargazers_count":575,"open_issues_count":17,"forks_count":128,"subscribers_count":19,"default_branch":"master","last_synced_at":"2024-11-21T03:35:52.642Z","etag":null,"topics":["amp","async","madelineproto","microservice","mtproto","php","telegram"],"latest_commit_sha":null,"homepage":"https://tg.i-c-a.su","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/xtrime-ru.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2018-12-24T11:48:20.000Z","updated_at":"2024-11-18T16:52:46.000Z","dependencies_parsed_at":"2023-10-02T21:22:37.270Z","dependency_job_id":"b9cb0be7-ef9e-4dc0-a506-be30b8d787eb","html_url":"https://github.com/xtrime-ru/TelegramApiServer","commit_stats":{"total_commits":394,"total_committers":6,"mean_commits":65.66666666666667,"dds":"0.10659898477157359","last_synced_commit":"2d09c548e655f218bdf4ad6eec9fe63ec1cbe8fc"},"previous_names":[],"tags_count":58,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/xtrime-ru%2FTelegramApiServer","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/xtrime-ru%2FTelegramApiServer/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/xtrime-ru%2FTelegramApiServer/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/xtrime-ru%2FTelegramApiServer/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/xtrime-ru","download_url":"https://codeload.github.com/xtrime-ru/TelegramApiServer/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":227762253,"owners_count":17815994,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["amp","async","madelineproto","microservice","mtproto","php","telegram"],"created_at":"2024-08-12T03:02:13.515Z","updated_at":"2025-07-27T04:31:58.530Z","avatar_url":"https://github.com/xtrime-ru.png","language":"PHP","funding_links":[],"categories":["PHP"],"sub_categories":[],"readme":"# TelegramApiServer\nFast, simple, async php telegram api server: \n[MadelineProto](https://github.com/danog/MadelineProto) and [Amp](https://github.com/amphp/amp) Http Server\n\n* Online demo (getHistory + Media Download): [tg.i-c-a.su](https://tg.i-c-a.su)\n* My content aggregator: [i-c-a.su](https://i-c-a.su)\n* Get telegram channels in RSS: [TelegramRSS](https://github.com/xtrime-ru/TelegramRSS) \n\n## Features\n\n* Fast async Amp Http Server\n* Full access to telegram api: bot and user\n* Multiple sessions\n* Stream media (view files in a browser)\n* Upload media\n* Websocket endpoints for events and logs\n* MadelineProto optimized settings to reduce memory consumption\n\n**Architecture Example**\n![Architecture Example](https://hsto.org/webt/j-/ob/ky/j-obkye1dv68ngsrgi12qevutra.png)\n \n## Installation\n\n```shell\ngit clone https://github.com/xtrime-ru/TelegramApiServer.git TelegramApiServer\ncd TelegramApiServer\ncp .env.docker.example .env.docker\ndocker compose pull\n```\n\n## Authorization\n\n\u003e [!CAUTION]\n\u003e Please only use old and valid accounts. All new accounts will be banned by telegram.\n\u003e If your account was banned read this: https://docs.madelineproto.xyz/docs/LOGIN.html#getting-permission-to-use-the-telegram-api\n\n1. Get app_id and app_hash at [my.telegram.org](https://my.telegram.org/). \n    Only one app_id needed for any amount of users and bots.\n1. Fill app_id and app_hash in `.env.docker`.\n1. Start TelegramApiServer in cli:\n    1. Start container interactively: `docker compose run --rm api`  \n    1. If you need to start multiple sessions, create docker-compose.override.yml. Add additional containers there. Use unique ports and session names in `command`.\n1. Authorize your session:\n    1. After promt, fill your phone number, or bot hash.\n    1. You will receive telegram code. Type it in.\n       If you're not receiving code - your server IP or hosting may be blocked by telegram. \n       Try another server or change server IP.\n    1. If you have 2fa enabled - enter 2fa passord.\n1. Wait 10-30 seconds until session is started.\n   You will see logs:\n   ```text\n   TelegramApiServer ready. \n   Number of sessions: 1.\n   ```\n1. Exit with `Ctrl + C` \n1. Run container in background `docker compose up -d`.\n\n## Change existing account/session\n1. Stop container `docker compose stop api`\n2. Remove session folder: `rm -rf /sessions/session.madeline/`\n3. Remove `session_MTProto_session` from mysql database.\n4. Log out session from app.\n5. Authorize as usual.\n\n## Update\n* `git pull` or `git fetch \u0026\u0026 git reset --hard origin/master`\n* `rm -rf vendor/`\n* Compare `.env.docker` or `.env` with corresponding `.env.example`. Update if needed.\n* Recreate containers:\n  ```shell\n  docker compose pull\n  docker compose down\n  docker compose up -d\n  ```\n\n## Security\nPlease be careful with settings, otherwise you can expose your telegram session and lose control.\nDefault settings allow to access API only from localhost/127.0.0.1.\n\n.env settings:\n- `IP_WHITELIST` - allow specific IP's to make requests without password.\n- `PASSWORDS` - protect your api with basic auth.  \n  Request with correct username and password overrides IP_WHITELIST.\n  If you specify password, then `IP_WHITELIST` is ignored\n  How to make requests with basic auth: \n  ```shell\n  curl --user username:password \"http://127.0.0.1:9503/getSelf\"\n  curl \"http://username:password@127.0.0.1:9503/getSelf\"\n  ```\n\ndocker-compose.yml:\n- `port` - port forwarding rules from host to docker container.\n  Remove 127.0.0.1 to listen all interfaces and forward all requests to container.\n  Make sure to use IP_WHITELIST and/or PASSWORDS settings to protect your account.\n\n## Usage\nAccess Telegram API with simple GET/POST requests.\nRegular and application/json POST supported.\nIt's recommended to use http_build_query, when using GET requests.\n    \n**Rules:**\n* All methods from MadelineProto supported: [Method List](https://docs.madelineproto.xyz/API_docs/methods/)\n* Url: `http://%address%:%port%/api[/%session%]/%class%.%method%/?%param%=%val%`\n* \u003cb\u003eImportant: api available only from ip in whitelist.\u003c/b\u003e \n    By default it is: `127.0.0.1`\n    You can add a client IP in .env file to `IP_WHITELIST` (separate with a comma)\n    \n    In docker version by default api available only from localhost (127.0.0.1).\n    To allow connections from the internet, need to change ports in docker-compose.yml to `9503:9503` and recreate the container: `docker compose up -d`. \n    This is very insecure, because this will open TAS port to anyone from the internet. \n    Only protection is the `IP_WHITELIST`, and there are no warranties that it will secure your accounts.\n* If method is inside class (messages, contacts and etc.) use '.' to separate class from method: \n    `http://127.0.0.1:9503/api/contacts.getContacts`\n* When passing files in POST forms, if the name of the field is `file`, it must always come **last** in the field list, and all fields after `file` will be ignored (this limit is not present for file fields named in another way, such as thumbnail fields).\n\n**Examples:**\n* get_info about channel/user: `http://127.0.0.1:9503/api/getInfo/?id=@xtrime`\n* get_info about currect account: `http://127.0.0.1:9503/api/getSelf`\n* repost: `http://127.0.0.1:9503/api/messages.forwardMessages/?from_peer=@xtrime\u0026to_peer=@xtrime\u0026id=1234`\n* get messages from channel/user: `http://127.0.0.1:9503/api/messages.getHistory/?peer=@breakingmash\u0026limit=10`\n* get messages with text in HTML: `http://127.0.0.1:9503/api/getHistoryHtml/?peer=@breakingmash\u0026limit=10`\n* search: `http://127.0.0.1:9503/api/searchGlobal/?q=Hello%20World\u0026limit=10`\n* sendMessage: `http://127.0.0.1:9503/api/messages.sendMessage/?peer=@xtrime\u0026message=Hello!`\n* copy message from one channel to another (not repost): `http://127.0.0.1:9503/api/copyMessages/?from_peer=@xtrime\u0026to_peer=@xtrime\u0026id[0]=1`\n    \n## Advanced features\n### Get events/updates\nTelegram is event driven platform. For example:  every time your account receives a message you immediately get an update.\nThere are multiple ways of [getting updates](https://docs.madelineproto.xyz/docs/UPDATES.html) in TelegramApiServer / MadelineProto:  \n1. [Websocket](#eventhandler-updates-webhooks)  \n2. Long Polling:   \nsend request to getUpdates endpoint  \n`curl \"127.0.0.1:9503/api/getUpdates?limit=3\u0026offset=0\u0026timeout=10.0\" -g`  \n3. Webhook:\nRedirect all updates to your endpoint, just like bot api!  \n`curl \"127.0.0.1:9503/api/setWebhook?url=http%3A%2F%2Fexample.com%2Fsome_webhook\" -g `  \nExample uses urlencoded url in query.\n\n### Uploading files.\n\nThere are few options to upload and send media files:\n\n- Custom method `sendDocument`/`sendVideo`/etc ([full list here](https://docs.madelineproto.xyz/docs/FILES.html)) to send document/video/audio/voice/etc by url or local path, remote url, or stream.\n  Stream upload from client:\n  ```shell script\n    curl --location --request POST 'http://127.0.0.1:9503/api/sendDocument' -g \\\n    -F peer=me \\\n    -F caption=key \\\n    -F file=@screenshot.png\n    ```\n  RemoteUrl:\n    ```shell script\n    curl --location --request POST 'http://127.0.0.1:9503/api/sendVideo' \\\n    --header 'Content-Type: application/json' \\\n    --data-raw '{\n        \"peer\": \"me\",\n        \"file\": {\n            \"_\": \"RemoteUrl\",\n            \"url\": \"https://domain.site/storage/video.mp4\"\n        },\n        \"parseMode\": \"HTML\",\n        \"caption\": \"\u003cb\u003ecaption text\u003c/b\u003e\"\n    }'\n    ```\n  Local file on server:\n   ```shell script\n    curl --location --request POST 'http://127.0.0.1:9503/api/sendDocument' \\\n    --header 'Content-Type: application/json' \\\n    --data-raw '{\n        \"peer\": \"me\",\n        \"file\": {\n            \"_\": \"LocalUrl\",\n            \"file\": \"faust.txt\"\n        },\n        \"parseMode\":  \"HTML\",\n        \"caption\": \"\u003cb\u003ecaption text\u003c/b\u003e\"\n    }'\n    ```\n- See other options: https://docs.madelineproto.xyz/docs/FILES.html#uploading-files\n\n### Downloading files\n\n```shell script\ncurl --location --request POST '127.0.0.1:9503/api/downloadToResponse' \\\n--header 'Content-Type: application/json' \\\n--data-raw '{\n    \"media\": {\n        \"_\": \"messageMediaDocument\",\n        \"document\": {\n            \"_\": \"document\",\n            \"id\": 5470079466401169993,\n            \"access_hash\": -6754208767885394084,\n            \"file_reference\": {\n                \"_\": \"bytes\",\n                \"bytes\": \"AkKdqJkAACnyXshwzMhdzeC5RkdVZeh58sAB/UU=\"\n            },\n            \"date\": 1551713685,\n            \"mime_type\": \"video/mp4\",\n            \"size\": 400967,\n            \"dc_id\": 2,\n            \"attributes\": [\n                {\n                    \"_\": \"documentAttributeFilename\",\n                    \"file_name\": \"одолдол.mp4\"\n                }\n            ]\n        }\n    }\n}'\n```\n\nAlso see: https://docs.madelineproto.xyz/docs/FILES.html#downloading-files\n\n### Multiple sessions support\nIts recommended to run every session in separate container. \n\nTo add more containers create `docker-compose.override.yml` file.\nDocker will [automatically merge](https://docs.docker.com/compose/multiple-compose-files/merge/) it with default docker-compose file.\n\nExample of `docker-compose.override.yml` with two additional containers/sessions (3 in total):\n```yaml\nservices:\n    api-2:\n        extends:\n            file: docker-compose.base.yml\n            service: base-api\n        ports:\n            - \"127.0.0.1:9512:9503\"\n        command:\n            - \"-s=session-2\"\n    api-3:\n        extends:\n            file: docker-compose.base.yml\n            service: base-api\n        ports:\n            - \"127.0.0.1:9513:9503\"\n        command:\n            - \"-s=session-3\"\n\n```\n### Multiple sessions in one container (deprecated)\n**WARNING: running multiple sessions in one instance/container is unstable.**\nCrash/error in one session will crash all of them.\n\nWhen running  multiple sessions, need to define which session to use for request.\nEach session stored in `sessions/{$session}.madeline`. Nested folders supported.\n**Examples:**\n* `php server.php --session=bot --session=users/xtrime --session=users/user1`\n* `http://127.0.0.1:9503/api/bot/getSelf`\n* `http://127.0.0.1:9503/api/users/xtrime/getSelf` \n* `http://127.0.0.1:9503/api/users/user1/getSelf`\n* sessions file paths are: `sessions/bot.madeline`, `sessions/users/xtrime.madeline` and `sessions/users/user1.madeline`\n* glob syntax for sessions:\n    * `--session=*` to use all `sessions/*.madeline` files (in subfolders too).\n    * `--session=users/* --session=bots/*`  to use all session files from `sessions/bots` and `sessions/users` folders. \n\n### Different settings for sessions\n* Use `--env` argument to define the relative path to env file.\n    Example: ```php server.php --env=.env```, ```php server.php --env=sessions/.env.session```   \n    This is helpful to define unique settings for different instances of TelegramApiServer.  \n    You can start multiple instances of TelegramApiServer with different sessions on different ports with their own settings.\n\n* Another way to manage settings - put %sessionName%.settings.json in sessions folder. \n    Example of `session.settings.json` to add proxy for the one session:\n\n    ```json\n    {\n        \"connection\": {\n            \"proxies\": {\n                \"\\\\danog\\\\MadelineProto\\\\Stream\\\\Proxy\\\\SocksProxy\": [\n                    {\n                      \"address\": \"127.0.0.1\",\n                      \"port\": 1234,\n                      \"username\": \"user\",\n                      \"password\": \"pass\"\n                    }\n                ],\n                \"\\\\danog\\\\MadelineProto\\\\Stream\\\\Proxy\\\\HttpProxy\": [\n                    {\n                      \"address\": \"127.0.0.1\",\n                      \"port\": 1234,\n                      \"username\": \"user\",\n                      \"password\": \"pass\"\n                    }\n                ]\n            }\n        }\n    }\n    ```\n    Methods to work with settings files:\n    * `http://127.0.0.1:9503/system/saveSessionSettings?session=session\u0026settings[app_info][app_id]=xxx\u0026settings[app_info][app_hash]=xxx`\n    * `http://127.0.0.1:9503/system/unlinkSessionSettings?session=session`\n* Provide settings as second argument when adding session: `http://127.0.0.1:9503/system/addSession?session=users/xtrime\u0026settings[app_info][app_id]=xxx\u0026\u0026settings[app_info][app_hash]=xxx`\n    These settings will be saved into json file and will apply after the restart. \n\n### Session management\n\n**Examples:**\n* Session list: `http://127.0.0.1:9503/system/getSessionList`\n* Adding session: `http://127.0.0.1:9503/system/addSession?session=users/xtrime`\n* ~~Removing session (session file will remain): `http://127.0.0.1:9503/system/removeSession?session=users/xtrime`\n  Due to madelineProto issue its instance still might be in memory and continue working even after the remove.~~\n* ~~Remove session file: `http://127.0.0.1:9503/system/unlinkSessionFile?session=users/xtrime`\n    Don`t forget to logout and call removeSession first!~~\n* Close TelegramApiServer (end process): `http://127.0.0.1:9503/system/exit`\n\nFull list of system methods available in [SystemApiExtensions class](https://github.com/xtrime-ru/TelegramApiServer/blob/master/src/MadelineProtoExtensions/SystemApiExtensions.php)\n\n### Authorizing session remotely\nWARNING: it is recomended to use interactive mode to authorize sessions!\nIf there is no authorization in session, or session file is blank, authorization required:\n\nUser: \n* `http://127.0.0.1:9503/api/users/xtrime/phoneLogin?phone=%2B7123...`, %2B - is urlencoded \"+\" sign\n* `http://127.0.0.1:9503/api/users/xtrime/completePhoneLogin?code=123456`\n* (optional) `http://127.0.0.1:9503/api/users/xtrime/complete2falogin?password=123456`\n* (optional) `http://127.0.0.1:9503/api/users/xtrime/completeSignup?firstName=MyExampleName`\n\nBot:\n* `http://127.0.0.1:9503/api/bot/botLogin?token=34298141894:aflknsaflknLKNFS`\n\nSave new session to file immediately: `http://127.0.0.1:9503/api/bot/serialize`\n\nAlso, session can be authorized in cli/shell on server start.\n\n### Websocket\n#### EventHandler updates (webhooks).\n \nConnect to `ws://127.0.0.1:9503/events` to get all events in json. \nThis is efficient alternative for webhooks.\nEach event is json object in [json-rpc 2.0 format](https://www.jsonrpc.org/specification#response_object). Example: \n\nWhen using multiple sessions, name of session can be added to path of websocket endpoint: \nThis endpoint will send events only from `users/xtrime` session: `ws://127.0.0.1:9503/events/users/xtrime`\n\nPHP websocket client example: [websocket-events.php](https://github.com/xtrime-ru/TelegramApiServer/blob/master/examples/websocket-events.php)\n\n`php examples/websocket-events.php --url=ws://127.0.0.1:9503/events`\n\n#### Logs.\n\nConnect to `ws://127.0.0.1:9503/log[/%level%]` to get logs in real time.\n\n`%level%` is optional parameter to filter logs. \nIf filter is specified, then only messages with equal or greater level will be send.\nThis endpoint will send only alert and emergency logs: `ws://127.0.0.1:9503/log/alert`\n\nAvailable levels: debug, info, notice, warning, error, critical, alert, emergency.\n\nPHP websocket client example: [websocket-events.php](https://github.com/xtrime-ru/TelegramApiServer/blob/master/examples/websocket-events.php)\n\n`php examples/websocket-events.php --url=ws://127.0.0.1:9503/log`\n\n\n### Custom methods\n\nTelegramApiServer extends madelineProto with some handful methods.   \nFull list of custom methods and their parameters available in [ApiExtensions class](https://github.com/xtrime-ru/TelegramApiServer/blob/master/src/MadelineProtoExtensions/ApiExtensions.php#L19)\n\n* `getHistoryHtml` - message entities converted to html\n* `formatMessage` - converts entities to html\n* `copyMessages` - copy message from one peer to onother. Like forwardMessages, but without the link to original.\n* `getMedia` - download media to stream/browser\n* `getMediaPreview` - download media preview to stream/browser\n* `uploadMediaForm` - upload document from POST request.\n\n## Contacts\n\n* Telegram:   \n    * Author: [@xtrime](https://t.me/xtrime)  \n    * [MadelineProto and Amp Support Groups](https://t.me/pwrtelegramgroup)\n    * Use madelineProto support groups to get support for TelegramApiServer.\n* Email: alexander(at)i-c-a.su\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fxtrime-ru%2FTelegramApiServer","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fxtrime-ru%2FTelegramApiServer","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fxtrime-ru%2FTelegramApiServer/lists"}