Giter Club home page Giter Club logo

telegramapiserver's Introduction

TelegramApiServer

Fast, simple, async php telegram api server: MadelineProto and Amp Http Server

Features

  • Fast async Amp Http Server
  • Full access to telegram api: bot and user
  • Multiple sessions
  • Stream media (view files in a browser)
  • Upload media
  • Websocket endpoints for events and logs
  • MadelineProto optimized settings to reduce memory consumption

Architecture Example Architecture Example

Installation

git clone https://github.com/xtrime-ru/TelegramApiServer.git TelegramApiServer
cd TelegramApiServer
cp .env.docker.example .env.docker
docker compose pull

Authorization

  1. Get app_id and app_hash at my.telegram.org. Only one app_id needed for any amount of users and bots.
  2. Fill app_id and app_hash in .env.docker.
  3. Start TelegramApiServer in cli: 1. Start container interactively: docker compose run --rm api 2. If you need to start multiple sessions, create docker-compose.override.yml. Add additional containers there. Use unique ports and session names in command.
  4. Authorize your session:
    1. After promt fill your phone number, or bot hash.
    2. Follow instructions
  5. Wait 10-30 seconds until session is started. You will see logs:
    TelegramApiServer ready. 
    Number of sessions: 1.
    
  6. Exit with Ctrl + C
  7. Run container in background docker compose up -d.

Update

  • git pull or git fetch && git reset --hard origin/master
  • rm -rf vendor/
  • Compare .env.docker or .env with corresponding .env.example. Update if needed.
  • Recreate containers:
    docker compose pull
    docker compose down
    docker compose up -d

Security

Please be careful with settings, otherwise you can expose your telegram session and lose control. Default settings allow to access API only from localhost/127.0.0.1.

.env settings:

  • IP_WHITELIST - allow specific IP's to make requests without password.
  • PASSWORDS - protect your api with basic auth.
    Request with correct username and password overrides IP_WHITELIST. If you specify password, then IP_WHITELIST is ignored How to make requests with basic auth:
    curl --user 'username:password' "http://127.0.0.1:9503/getSelf"
    curl "http://username:[email protected]:9503/getSelf"

docker-compose.yml:

  • port - port forwarding rules from host to docker container. Remove 127.0.0.1 to listen all interfaces and forward all requests to container. Make sure to use IP_WHITELIST and/or PASSWORDS settings to protect your account.

Usage

Access Telegram API with simple GET/POST requests. Regular and application/json POST supported. It's recommended to use http_build_query, when using GET requests.

Rules:

  • All methods from MadelineProto supported: Methods List

  • Url: http://%address%:%port%/api[/%session%]/%class%.%method%/?%param%=%val%

  • Important: api available only from ip in whitelist. By default it is: 127.0.0.1 You can add a client IP in .env file to IP_WHITELIST (separate with a comma)

    In docker version by default api available only from localhost (127.0.0.1). 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. This is very insecure, because this will open TAS port to anyone from the internet. Only protection is the IP_WHITELIST, and there are no warranties that it will secure your accounts.

  • If method is inside class (messages, contacts and etc.) use '.' to separate class from method: http://127.0.0.1:9503/api/contacts.getContacts

  • If method requires array of values, use any name of array, for example 'data': ?data[peer]=@xtrime&data[message]=Hello!. Order of parameters does't matter in this case.

  • If method requires one or multiple separate parameters (not inside array) then pass parameters with any names but in strict order: http://127.0.0.1:9503/api/getInfo/?id=@xtrime or http://127.0.0.1:9503/api/getInfo/?abcd=@xtrime works the same

Examples:

  • get_info about channel/user: http://127.0.0.1:9503/api/getInfo/?id=@xtrime
  • get_info about currect account: http://127.0.0.1:9503/api/getSelf
  • repost: http://127.0.0.1:9503/api/messages.forwardMessages/?data[from_peer]=@xtrime&data[to_peer]=@xtrime&data[id]=1234
  • get messages from channel/user: http://127.0.0.1:9503/api/messages.getHistory/?data[peer]=@breakingmash&data[limit]=10
  • get messages with text in HTML: http://127.0.0.1:9503/api/getHistoryHtml/?data[peer]=@breakingmash&data[limit]=10
  • search: http://127.0.0.1:9503/api/searchGlobal/?data[q]=Hello%20World&data[limit]=10
  • sendMessage: http://127.0.0.1:9503/api/messages.sendMessage/?data[peer]=@xtrime&data[message]=Hello!
  • copy message from one channel to another (not repost): http://127.0.0.1:9503/api/copyMessages/?data[from_peer]=@xtrime&data[to_peer]=@xtrime&data[id][0]=1

Advanced features

Get events/updates

Telegram is event driven platform. For example: every time your account receives a message you immediately get an update. There are multiple ways of getting updates in TelegramApiServer / MadelineProto:

  1. Websocket
  2. Long Polling:
    send request to getUpdates endpoint
    curl "127.0.0.1:9503/api/getUpdates?data[limit]=3&data[offset]=0&data[timeout]=10.0" -g
  3. Webhook: Redirect all updates to your endpoint, just like bot api!
    curl "127.0.0.1:9503/api/setWebhook?url=http%3A%2F%2Fexample.com%2Fsome_webhook" -g
    Example uses urlencoded url in query.

Uploading files.

There are few options to upload and send media files:

  • Custom method sendMedia supports upload from form:
    curl "http://127.0.0.1:9503/api/messages.sendMedia?data[peer]=xtrime&data[message]=Hello" -g \
    -F "file=@/Users/xtrime/Downloads/test.txt"
  • use custom uploadMediaForm method and then pass result to messages.sendMedia:
    1. curl "http://127.0.0.1:9503/api/uploadMediaForm" -g -F "file=@/Users/xtrime/Downloads/test.txt" Method supports application/x-www-form-urlencoded and multipart/form-data.

    2. Send result from uploadMediaForm to messages.sendMedia or sendMedia:

    curl --location --request POST 'http://127.0.0.1:9503/api/sendMedia' \
    --header 'Content-Type: application/json' \
    --data-raw '{
        "data":{
            "peer": "@xtrime",
            "media": {
                "_": "inputMediaUploadedDocument",
                "file": {
                    "_": "inputFile",
                    "id": 1164670976363200575,
                    "parts": 1,
                    "name": "test.txt",
                    "mime_type": "text/plain",
                    "md5_checksum": ""
                },
                "attributes": [
                    {
                        "_": "documentAttributeFilename",
                        "file_name": "test.txt"
                    }
                ]
            }
        }
    }'
  • See other options: https://docs.madelineproto.xyz/docs/FILES.html#uploading-files

Downloading files

curl --location --request POST '127.0.0.1:9503/api/downloadToResponse' \
--header 'Content-Type: application/json' \
--data-raw '{
    "media": {
        "_": "messageMediaDocument",
        "document": {
            "_": "document",
            "id": 5470079466401169993,
            "access_hash": -6754208767885394084,
            "file_reference": {
                "_": "bytes",
                "bytes": "AkKdqJkAACnyXshwzMhdzeC5RkdVZeh58sAB/UU="
            },
            "date": 1551713685,
            "mime_type": "video/mp4",
            "size": 400967,
            "dc_id": 2,
            "attributes": [
                {
                    "_": "documentAttributeFilename",
                    "file_name": "одолдол.mp4"
                }
            ]
        }
    }
}'

Also see: https://docs.madelineproto.xyz/docs/FILES.html#downloading-files

Multiple sessions support

Its recommended to run every session in separate container.

To add more containers create docker-compose.override.yml file. Docker will automatically merge it with default docker-compose file.

Example of docker-compose.override.yml with two additional containers/sessions (3 in total):

services:
    api-2:
        extends:
            file: docker-compose.base.yml
            service: base-api
        ports:
            - "127.0.0.1:9512:9503"
        command:
            - "-s=session-2"
    api-3:
        extends:
            file: docker-compose.base.yml
            service: base-api
        ports:
            - "127.0.0.1:9513:9503"
        command:
            - "-s=session-3"

Multiple sessions in one container (deprecated)

WARNING: running multiple sessions in one instance/container is unstable. Crash/error in one session will crash all of them.

When running multiple sessions, need to define which session to use for request. Each session stored in sessions/{$session}.madeline. Nested folders supported. Examples:

  • php server.php --session=bot --session=users/xtrime --session=users/user1
  • http://127.0.0.1:9503/api/bot/getSelf
  • http://127.0.0.1:9503/api/users/xtrime/getSelf
  • http://127.0.0.1:9503/api/users/user1/getSelf
  • sessions file paths are: sessions/bot.madeline, sessions/users/xtrime.madeline and sessions/users/user1.madeline
  • glob syntax for sessions:
    • --session=* to use all sessions/*.madeline files (in subfolders too).
    • --session=users/* --session=bots/* to use all session files from sessions/bots and sessions/users folders.

Different settings for sessions

  • Use --env argument to define the relative path to env file. Example: php server.php --env=.env, php server.php --env=sessions/.env.session
    This is helpful to define unique settings for different instances of TelegramApiServer.
    You can start multiple instances of TelegramApiServer with different sessions on different ports with their own settings.

  • Another way to manage settings - put %sessionName%.settings.json in sessions folder. Example of session.settings.json to add proxy for the one session:

    {
        "connection": {
            "proxies": {
                "\\danog\\MadelineProto\\Stream\\Proxy\\SocksProxy": [
                    {
                      "address": "127.0.0.1",
                      "port": 1234,
                      "username": "user",
                      "password": "pass"
                    }
                ],
                "\\danog\\MadelineProto\\Stream\\Proxy\\HttpProxy": [
                    {
                      "address": "127.0.0.1",
                      "port": 1234,
                      "username": "user",
                      "password": "pass"
                    }
                ]
            }
        }
    }

    Methods to work with settings files:

    • http://127.0.0.1:9503/system/saveSessionSettings?session=session&settings[app_info][app_id]=xxx&settings[app_info][app_hash]=xxx
    • http://127.0.0.1:9503/system/unlinkSessionSettings?session=session
  • Provide settings as second argument when adding session: http://127.0.0.1:9503/system/addSession?session=users/xtrime&settings[app_info][app_id]=xxx&&settings[app_info][app_hash]=xxx These settings will be saved into json file and will apply after the restart.

Session management

Examples:

  • Session list: http://127.0.0.1:9503/system/getSessionList
  • Adding session: http://127.0.0.1:9503/system/addSession?session=users/xtrime
  • Removing session (session file will remain): http://127.0.0.1:9503/system/removeSession?session=users/xtrime Due to madelineProto issue its instance still might be in memory and continue working even after the remove.
  • Remove session file: http://127.0.0.1:9503/system/unlinkSessionFile?session=users/xtrime Don`t forget to logout and call removeSession first!
  • Close TelegramApiServer (end process): http://127.0.0.1:9503/system/exit

Full list of system methods available in SystemApiExtensions class

Authorizing session remotely

WARNING: it is recomended to use interactive mode to authorize sessions! If there is no authorization in session, or session file is blank, authorization required:

User:

  • http://127.0.0.1:9503/api/users/xtrime/phoneLogin?phone=%2B7123..., %2B - is urlencoded "+" sign
  • http://127.0.0.1:9503/api/users/xtrime/completePhoneLogin?code=123456
  • (optional) http://127.0.0.1:9503/api/users/xtrime/complete2falogin?password=123456
  • (optional) http://127.0.0.1:9503/api/users/xtrime/completeSignup?firstName=MyExampleName

Bot:

  • http://127.0.0.1:9503/api/bot/botLogin?token=34298141894:aflknsaflknLKNFS

Save new session to file immediately: http://127.0.0.1:9503/api/bot/serialize

Also, session can be authorized in cli/shell on server start.

Websocket

EventHandler updates (webhooks).

Connect to ws://127.0.0.1:9503/events to get all events in json. This is efficient alternative for webhooks. Each event is json object in json-rpc 2.0 format. Example:

When using multiple sessions, name of session can be added to path of websocket endpoint: This endpoint will send events only from users/xtrime session: ws://127.0.0.1:9503/events/users/xtrime

PHP websocket client example: websocket-events.php

php examples/websocket-events.php --url=ws://127.0.0.1:9503/events

Logs.

Connect to ws://127.0.0.1:9503/log[/%level%] to get logs in real time.

%level% is optional parameter to filter logs. If filter is specified, then only messages with equal or greater level will be send. This endpoint will send only alert and emergency logs: ws://127.0.0.1:9503/log/alert

Available levels: debug, info, notice, warning, error, critical, alert, emergency.

PHP websocket client example: websocket-events.php

php examples/websocket-events.php --url=ws://127.0.0.1:9503/log

Custom methods

TelegramApiServer extends madelineProto with some handful methods.
Full list of custom methods and their parameters available in ApiExtensions class

  • getHistoryHtml - message entities converted to html
  • formatMessage - converts entities to html
  • copyMessages - copy message from one peer to onother. Like forwardMessages, but without the link to original.
  • getMedia - download media to stream/browser
  • getMediaPreview - download media preview to stream/browser
  • uploadMediaForm - upload document from POST request.

Contacts

telegramapiserver's People

Contributors

danog avatar mirmuxsin avatar surzhikov avatar xtrime-ru avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

telegramapiserver's Issues

why didn't generate autoload.php automatically?

hi,
I did:
1- composer install
2- create .env
3-fill .env (with address, port, app id and hash) and test with blank app id and hash
but autoload.php didn't generate! why ?
I'm using windows 7.

Error: connect ECONNREFUSED 45.82.**.214:9503

Привет, благодарю за крутую разработку, но у меня вопрос, если я к телеграмм серверу пытаюсь обратиться с другого сервера получаю такую ошибку. не можешь подсказать что я должен сделать что бы обращаться к нему с другой машины?
IP_WHITELIST я оставил пустым
SERVER_ADDRESS=0.0.0.0
curl http://45.82.**.214:9503/system/getSessionList возвращает ошибку, но если на сервере на котором развернут контейнер с телеграмм сервером выполить curl http://0.0.0.0:9503/system/getSessionList все работает штатно.

Как мне обратиться к Телеграм серверу со стороннего сервера ?

Hello, thank you for the cool development, but I have a question, if I try to access the telegram server from another server, I get this error. can you tell me what I should do to access it from another machine?
I left IP_WHITELIST blank
SERVER_ADDRESS = 0.0.0.0
curl http: //45.82.**.214: 9503 / system / getSessionList returns an error, but if curl http://0.0.0.0:9503/system/getSessionList is deployed on the server on which the container with telegrams is deployed, everything works normally.

How can I access the Telegram server from a third-party server?

Upgrade Report : Converting from Memory to DB Mode

Hello !

Today I had time to upgrade package to latest version .. and I also enabled DB mode ...

I have 5 Telegram Session ...

Converting to DB mode took about 2 hours ! and it created about 750/000 records !

I had to disable Health check .. as it was killing the TelegramApiServer and preventing the DB Converting process ...

Before using the DB mode .. It was using about 2 GB for 5 sessions
And After using the DB mode .. now it is using only 38MB !!!

Great mode and Great Upgrade!
Merry Christmas and Happy New year 💯
Thanks !
Artin

Две сессии - и маделина просто ловит глюк

[2021-03-24 12:03:31] [warning] Received bad_msg_notification: incorrect server salt (in this case, the bad_server_salt response is received with the correct salt, and the message is to be re-sent with it)
[2021-03-24 12:57:55] [warning] Received bad_msg_notification: incorrect server salt (in this case, the bad_server_salt response is received with the correct salt, and the message is to be re-sent with it)
[2021-03-24 14:27:34] [warning] Received bad_msg_notification: incorrect server salt (in this case, the bad_server_salt response is received with the correct salt, and the message is to be re-sent with it)
[2021-03-24 15:27:52] [warning] Received bad_msg_notification: incorrect server salt (in this case, the bad_server_salt response is received with the correct salt, and the message is to be re-sent with it)
[2021-03-24 15:32:49] [critical] {
    "tlTrace": "While serializing:  \tphone.discardCall['reason']\nConnection.php(469):\tserializeMethod(\"phone.discardCall\",{\"peer\":{\"_\":\"inputPhoneCall\",\"id\":4080593250616251705,\"access_hash\":-8604821817551491721},\"duration\":1616599969,\"connection_id\":0,\"reason\":[]})\nCallHandler.php(190):\tsendMessage({},true)\nCallHandler.php(100):\tmethodCallAsyncWrite(\"phone.discardCall\",{\"peer\":{\"_\":\"inputPhoneCall\",\"id\":4080593250616251705,\"access_hash\":-8604821817551491721},\"duration\":1616599969,\"connection_id\":0,\"reason\":[]},{\"msg_id\":null,\"postpone\":false})\nCallHandler.php(61):\tmethodCallAsyncRead(\"phone.discardCall\",{\"peer\":{\"_\":\"inputPhoneCall\",\"id\":4080593250616251705,\"access_hash\":-8604821817551491721},\"duration\":1616599969,\"connection_id\":0,\"reason\":[]},{\"msg_id\":null})\nAuthKeyHandler.php(296):\tmethodCallAsyncRead(\"phone.discardCall\",{\"peer\":{\"_\":\"inputPhoneCall\",\"id\":4080593250616251705,\"access_hash\":-8604821817551491721},\"duration\":1616599969,\"connection_id\":0,\"reason\":[]})\ndiscardCall({\"_\":\"inputPhoneCall\",\"id\":4080593250616251705,\"access_hash\":-8604821817551491721},[],[],false)\nCoroutine.php(71):  \tcurrent()\nTools.php(500):     \t__construct({})\nVoIP.php(303):      \tcallFork({})\nUpdateHandler.php(347):\tdiscard([],[],false)\nFeedLoop.php(109):  \tsaveUpdate({\"_\":\"updatePhoneCall\",\"phone_call\":{\"_\":\"phoneCallDiscarded\",\"need_rating\":false,\"need_debug\":false,\"video\":false,\"id\":4080593250616251705}})\nLoggerLoop.php(59): \tloop()\ndanog\\MadelineProto\\Loop\\{closure}()\nCoroutine.php(117): \tsend(null)\nPlaceholder.php(46):\tdanog\\MadelineProto\\{closure}(null,null)\nPrivatePromise.php(23):\tonResolve({})\nPlaceholder.php(143):\tonResolve({})\nDeferred.php(52):   \tresolve({})\nSignalLoop.php(75): \tresolve({})\nPlaceholder.php(149):\tdanog\\Loop\\Traits\\{closure}(null,null)\nDeferred.php(52):   \tresolve(null)\nResumableLoop.php(121):\tresolve()\nResumableLoop.php(90):\tresumeInternal()\nSeqLoop.php(85):    \tresume()\nLoggerLoop.php(59): \tloop()\ndanog\\MadelineProto\\Loop\\{closure}()\nCoroutine.php(117): \tsend(null)\nPlaceholder.php(46):\tdanog\\MadelineProto\\{closure}(null,null)\nPrivatePromise.php(23):\tonResolve({})\nPlaceholder.php(143):\tonResolve({})\nDeferred.php(52):   \tresolve({})\nSignalLoop.php(75): \tresolve({})\nPlaceholder.php(149):\tdanog\\Loop\\Traits\\{closure}(null,null)\nDeferred.php(52):   \tresolve(null)\nResumableLoop.php(121):\tresolve()\nResumableLoop.php(90):\tresumeInternal()\nUpdateHandler.php(242):\tresume()\nhandleUpdates({\"_\":\"updates\",\"updates\":[{\"_\":\"updatePhoneCall\",\"phone_call\":{\"_\":\"phoneCallDiscarded\",\"need_rating\":false,\"need_debug\":false,\"video\":false,\"id\":4080593250616251705}}],\"users\":[],\"chats\":[],\"date\":1616599968,\"seq\":206,\"options\":{\"seq_start\":206,\"seq_end\":206,\"date\":1616599968}})\nCoroutine.php(71):  \tcurrent()\nTools.php(500):     \t__construct({})\nTools.php(524):     \tcallFork({})\nDriver.php(119):    \tdanog\\MadelineProto\\{closure}(\"annf\",null)\nDriver.php(72):     \ttick()\nEvDriver.php(186):  \trun()\nLoop.php(95):       \trun()\nServer.php(39):     \trun()\nserver.php(100):    \t__construct({\"address\":\"\",\"port\":\"\",\"session\":[\"*\"],\"env\":\".env.docker\",\"docker\":true,\"help\":false},[\"sessions\\\/bot_sip.madeline\"])"

[Question] How to construct getInfo query.

Cannot redeclare Amp\Sync\synchronized()

I have this error on start server.php. Before madeline was update, all works fine.

Cannot redeclare Amp\Sync\synchronized() (previously declared in /root/TelegramApiServer/vendor/amphp/sync/lib/functions.php:19) in phar:///root/TelegramApiServer/madeline.phar/vendor/amphp/sync/src/functions.php on line 29

Using multiple sessions causing <<PHP Fatal error: Allowed memory size>>

When running the server with single session there is no any issue ...
But When Running with multiple sessions I am getting Memory Limit Error :

php server.php --address=127.0.0.1 --session=*

Starting MadelineProto...
 
PHP Fatal error:  Allowed memory size of 268435456 bytes exhausted (tried to allocate 10485760 bytes) in /home/test/TelegramApiServer/vendor/danog/madelineproto/src/danog/MadelineProto/Serialization.php on line 71

Memory limit for php cli is -1 .. I even tried following command but I got same result.

php -d memory_limit=4G server.php --address=127.0.0.1 --session=*

Buttons parsing

Exception:      	Undefined property: danog\MadelineProto\TL\TL::$authorization in Button.php:32
Exception:      	\danog\MadelineProto\Exception: Undefined property: danog\MadelineProto\TL\TL::$authorization in \TelegramApiServer/vendor/danog/madelineproto/src/danog/MadelineProto/TL/Types/Button.php:32
Revision: bb9804290b531b95f79c3e9501a298391d0f0acb (AN UPDATE IS REQUIRED)
TL Trace (YOU ABSOLUTELY MUST READ THE TEXT BELOW):

Не работает добавление сессии

Доброго дня.
После добавления сессии без app_id и app_hash, docker зависает на конфликнутой сессии.

Лог docker:

[2021-03-24 04:55:58] [warning]
TelegramApiServer ready.
Number of sessions: 0.
file_get_contents(http://ipv6.google.com/): Failed to open stream: Cannot assign requested address in Magic.php:307
Do you want to enter the API id and the API hash manually or automatically? (m/a)
Note that you can also provide them directly in the code using the settings: https://docs.madelineproto.xyz/docs/SETTINGS.html#settingsapp_infoapi_id

Надо как то продумать либо проверку на наличие app_id && app_hash, либо вовсе удалять сессию, которая зависает

Feature Request : Server Status

If We sent getSessionList request to the TelegramApiServer .. We can see active sessions and memory usage , which is nice ...

But If you could able to add something like Apache (web server) Http Server Status .. to show :

1-Current Version
2- Uptime
3-Number of requests
4- Number of Errors ?
5-Number of Sessions
6-Memory usage
7- number of mysql queries ?
and something more that you can access it ..

Could be very nice and handy Tools for checking and monitoring TelegramApiServer

Thanks

Session not confirmed cause restart docker container

I test add session without confirm with Telegram's code.

Docker container crash and restarted always. This is the error

`Number of sessions: 2.
Authorizing session: users/rob
Do you want to login as user or bot (u/b)? Enter your phone number:
Fatal error: Uncaught Error: Resource has already been freed in /app-host-link/vendor/amphp/byte-stream/lib/ResourceInputStream.php:250
Stack trace:
#0 /app-host-link/vendor/danog/madelineproto/src/danog/MadelineProto/Magic.php(420): Amp\ByteStream\ResourceInputStream->unreference()
#1 /app-host-link/vendor/danog/madelineproto/src/danog/MadelineProto/Exception.php(102): danog\MadelineProto\Magic::shutdown(1)
#2 [internal function]: danog\MadelineProto\Exception::exceptionHandler(Object(danog\MadelineProto\RPCErrorException))
#3 {main}
thrown in /app-host-link/vendor/amphp/byte-stream/lib/ResourceInputStream.php on line 250

Fatal error: Uncaught Error: Resource has already been freed in /app-host-link/vendor/amphp/byte-stream/lib/ResourceInputStream.php:250
Stack trace:
#0 /app-host-link/vendor/danog/madelineproto/src/danog/MadelineProto/Magic.php(420): Amp\ByteStream\ResourceInputStream->unreference()
#1 /app-host-link/vendor/danog/madelineproto/src/danog/MadelineProto/Shutdown.php(55): danog\MadelineProto\Magic::shutdown(0)
#2 [internal function]: danog\MadelineProto\Shutdown::shutdown()
#3 {main}
thrown in /app-host-link/vendor/amphp/byte-stream/lib/ResourceInputStream.php on line 250`

Add sessions

I have this error, when I call curl http://127.0.0.1:9503/system/addInstance?session=users/cloud

{ "success": false, "errors": [ { "code": 0, "message": "Call to undefined method TelegramApiServer\\MadelineProtoExtensions\\SystemApiExtensions::addInstance()" } ], "response": null }

handle received message

hi
how can i handle receive message ?
i run this command but onlye say Waiting for events...

php examples/websocket-events.php --url=ws://127.0.0.1:9503/events

whene i run this code i see some jsonp but not my received message

php examples/websocket-events.php --url=ws://127.0.0.1:9503/log

how can i receive messages as they arrived ?

Invalid URI specified at Amp\Uri\Uri::__construct

I update all, when I start server.php with php server.php --session=* I have this error:

PHP Fatal error:  Uncaught Amp\Uri\InvalidUriException: Invalid URI specified at Amp\Uri\Uri::__construct Argument 1: tcp://: in /root/TelegramApiServer/vendor/amphp/uri/src/Uri.php:33

Stack trace:
#0 /root/TelegramApiServer/vendor/danog/madelineproto/src/danog/MadelineProto/Stream/ConnectionContext.php(151): Amp\Uri\Uri->__construct()
#1 /root/TelegramApiServer/vendor/danog/madelineproto/src/danog/MadelineProto/Stream/Proxy/SocksProxy.php(69): danog\MadelineProto\Stream\ConnectionContext->setUri()
#2 [internal function]: danog\MadelineProto\Stream\Proxy\SocksProxy->connectGenerator()
#3 /root/TelegramApiServer/vendor/danog/madelineproto/src/danog/MadelineProto/Coroutine.php(77): Generator->current()
#4 /root/TelegramApiServer/vendor/danog/madelineproto/src/danog/MadelineProto/Tools.php(429): danog\MadelineProto\Coroutine->__construct()
#5 /root/TelegramApiServer/vendor/danog/madelineproto/src/danog/MadelineProto/Stream/Async/Stream.php(35): danog\MadelineProto\Tools::call()
#6 /root/TelegramApiServer/vendor/danog/madelineprot in /root/TelegramApiServer/vendor/danog/madelineproto/src/danog/MadelineProto/Tools.php on line 329

I use madeline direct and I see this:

Trying shared connection via tcp://[2001:0b28:f23f:f005:0000:0000:0000:000a]:443 main DC 5, via ipv6 using AbridgedStream => BufferedRawStream => DefaultStream (-1)

With your code, I see this:

Trying shared connection via tcp://[2001:0b28:f23d:f001:0000:0000:0000:000a]:443 main DC 1, via ipv6 using AbridgedStream => SocksProxy ({"address":false,"port":false,"username":false,"password":false}) => BufferedRawStream => DefaultStream (-1)

ws://127.0.0.1:9503/events ничего не возвращает

php examples/websocket-events.php --url=ws://127.0.0.1:9503/events
Connecting to: ws://127.0.0.1:9503/events
Waiting for events...

В то же время php examples/websocket-events.php --url=ws://127.0.0.1:9503/log
нормально так спамит
Received event: {"jsonrpc":"2.0","result":{"level":"notice","message":"Resumed update feed loop channel 1117628569","context":[]},"id":null}
Received event: {"jsonrpc":"2.0","result":{"level":"notice","message":"Given message id (6945747327531073537) is bigger than or equal to the current limit (6945747327531063297). Consider syncing your date.","context":[]},"id":null}
Received event: {"jsonrpc":"2.0","result":{"level":"notice","message":"Resumed update feed loop generic","context":[]},"id":null}

Как вообще должен events работать и что должен возвращать?

Upgrade Report : Converting from Memory to DB Mode

Hello !

Today I had time to upgrade package to latest version .. and I also enabled DB mode ...

I have 5 Telegram Session ...

Converting to DB mode took about 2 hours ! and it created about 750/000 record !

I had to disable Health check .. as it was killing the TelegramApiServer and preventing the DB Converting process ...

Before using the DB mode .. It was using about 2 GB for 5 sessions
And After using the DB mode .. now it is using only 38MB !!!

Great mode and Great Upgrade!
Merry Christmas and Happy New year 💯
Thanks !
Artin

handling exceptions ?

How do you handle exceptions ?

for example an invalid channel

url = 'http://127.0.0.1:9503/api/get_full_info/?data=@breakingmash11111111111111111111111111'

response :
failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request

server.php output :
[2020-05-22 07:31:46] [error] Username resolution failed with error USERNAME_INVALID
[2020-05-22 07:31:46] [error] USERNAME_INVALID
{
"exception": "danog\MadelineProto\RPCErrorException",
"message": "USERNAME_INVALID",
"file": "/home/test/TelegramApiServer/vendor/danog/madelineproto/src/danog/MadelineProto/MTProtoSession/ResponseHandler.php",
"line": 462,
"code": 400
}

Downloading Video Thumbs

Every video message on Telegram has 'thumbs' like this :

array:6 [▼
  "_" => "photoSize"
  "type" => "m"
  "location" => array:3 [▼
    "_" => "fileLocationToBeDeprecated"
    "volume_id" => 400032600322
    "local_id" => 4558
  ]
  "w" => 320
  "h" => 300
  "size" => 19721
]

I am trying to download them but not working and I am getting following error :

{
    "exception": "TypeError",
    "message": "Argument 1 passed to TelegramApiServer\\MadelineProtoExtensions\\ApiExtensions::downloadToResponse() must be of the type array, string given, called in \/home\/telegram\/TelegramApiServer\/src\/Controllers\/AbstractApiController.php on line 169",
    "file": "\/home\/telegram\/TelegramApiServer\/src\/MadelineProtoExtensions\/ApiExtensions.php",
    "line": 461,
    "code": 0,
    "backtrace": [
        {
            "file": "\/home\/telegram\/TelegramApiServer\/src\/Controllers\/AbstractApiController.php",
            "line": 169,
            "function": "downloadToResponse",
            "class": "TelegramApiServer\\MadelineProtoExtensions\\ApiExtensions",
            "type": "->"
        },
        {
            "file": "\/home\/telegram\/TelegramApiServer\/src\/Controllers\/ApiController.php",
            "line": 32,
            "function": "callApiCommon",
            "class": "TelegramApiServer\\Controllers\\AbstractApiController",
            "type": "->"
        },
        {
            "file": "\/home\/telegram\/TelegramApiServer\/src\/Controllers\/AbstractApiController.php",
            "line": 145,
            "function": "callApi",
            "class": "TelegramApiServer\\Controllers\\ApiController",
            "type": "->"
        }
    ]
}

I even tried to put it in "Media" array but not success

array:1 [▼
  "media" => array:6 [▼
    "_" => "photoSize"
    "type" => "m"
    "location" => array:3 [▼
      "_" => "fileLocationToBeDeprecated"
      "volume_id" => 400032600322
      "local_id" => 4558
    ]
    "w" => 320
    "h" => 300
    "size" => 19721
  ]
]

Curl Connection is giving following error ( without any error on the TelegramApiServer)
Empty reply from server

Did you ever tried to download Video Thumbnail ?

[error] Got nothing in the socket in DC 4.0, reconnecting...

Hello ,
Every few days I am restarting TelegramApiServer to free up memory usage caused by memory leak,
But it didn't start like always
It keep showing Following error in infinite loop
upgrading TelegramApiServer didn't help ...
Do you have any Idea ?
Thanks

.....
[2021-03-13 18:03:51] [error] Got nothing in the socket in DC 4.0, reconnecting...
[2021-03-13 18:03:51] [warning] Reconnecting to DC 4 (0) from existing
[2021-03-13 18:03:51] [warning] Connecting to DC 4.0
[2021-03-13 18:03:51] [warning] Connected to DC 4.0!
[2021-03-13 18:03:51] [error] Still missing help.getTermsOfServiceUpdate, users.getUsers, on DC 4.0, sending state request
[2021-03-13 18:03:51] [warning] OK!
[2021-03-13 18:03:51] [error] Got nothing in the socket in DC 4.0, reconnecting...
[2021-03-13 18:03:51] [warning] Reconnecting to DC 4 (0) from existing
[2021-03-13 18:03:51] [warning] Connecting to DC 4.0
[2021-03-13 18:03:51] [warning] Connected to DC 4.0!
[2021-03-13 18:03:51] [error] Still missing help.getTermsOfServiceUpdate, users.getUsers, on DC 4.0, sending state request
[2021-03-13 18:03:51] [warning] OK!
[2021-03-13 18:03:51] [warning] Connected to DC 4.0!
[2021-03-13 18:03:51] [error] Still missing help.getTermsOfServiceUpdate, users.getUsers, on DC 4.0, sending state request
[2021-03-13 18:03:51] [warning] OK!
[2021-03-13 18:03:51] [error] Got nothing in the socket in DC 4.0, reconnecting...
[2021-03-13 18:03:51] [warning] Reconnecting to DC 4 (0) from existing
[2021-03-13 18:03:51] [warning] Connecting to DC 4.0
[2021-03-13 18:03:51] [error] Got nothing in the socket in DC 4.0, reconnecting...
[2021-03-13 18:03:51] [warning] Reconnecting to DC 4 (0) from existing
[2021-03-13 18:03:51] [warning] Connecting to DC 4.0
[2021-03-13 18:03:51] [error] Got nothing in the socket in DC 4.0, reconnecting...
[2021-03-13 18:03:51] [warning] Reconnecting to DC 4 (0) from existing
[2021-03-13 18:03:51] [warning] Connecting to DC 4.0
[2021-03-13 18:03:51] [error] Got nothing in the socket in DC 4.0, reconnecting...
[2021-03-13 18:03:51] [warning] Reconnecting to DC 4 (0) from existing
[2021-03-13 18:03:51] [warning] Connecting to DC 4.0
[2021-03-13 18:03:51] [warning] Connected to DC 4.0!
[2021-03-13 18:03:51] [error] Still missing help.getTermsOfServiceUpdate, users.getUsers, on DC 4.0, sending state request
[2021-03-13 18:03:51] [warning] OK!
[2021-03-13 18:03:51] [warning] Connected to DC 4.0!
[2021-03-13 18:03:51] [error] Still missing help.getTermsOfServiceUpdate, users.getUsers, on DC 4.0, sending state request
[2021-03-13 18:03:51] [warning] OK!
[2021-03-13 18:03:51] [warning] Connected to DC 4.0!
[2021-03-13 18:03:51] [error] Still missing help.getTermsOfServiceUpdate, users.getUsers, on DC 4.0, sending state request
[2021-03-13 18:03:51] [warning] OK!
[2021-03-13 18:03:51] [warning] Connected to DC 4.0!
[2021-03-13 18:03:51] [error] Still missing help.getTermsOfServiceUpdate, users.getUsers, on DC 4.0, sending state request
[2021-03-13 18:03:51] [warning] OK!
[2021-03-13 18:03:51] [error] Got nothing in the socket in DC 4.0, reconnecting...
[2021-03-13 18:03:51] [warning] Reconnecting to DC 4 (0) from existing
[2021-03-13 18:03:51] [warning] Connecting to DC 4.0
[2021-03-13 18:03:51] [warning] Connected to DC 4.0!
......

Unable to Install : fatal: clone of '[email protected]:danog/MadelineProtoDocs' into submodule path 'docs' failed

I am getting following Error while installing :
fatal: clone of '[email protected]:danog/MadelineProtoDocs' into submodule path 'docs' failed

Full output :

git clone https://github.com/xtrime-ru/TelegramApiServer.git

Cloning into 'TelegramApiServer'...
remote: Enumerating objects: 54, done.
remote: Counting objects: 100% (54/54), done.
remote: Compressing objects: 100% (33/33), done.
remote: Total 1215 (delta 23), reused 41 (delta 21), pack-reused 1161
Receiving objects: 100% (1215/1215), 342.48 KiB | 0 bytes/s, done.
Resolving deltas: 100% (814/814), done.
Checking connectivity... done.

cd TelegramApiServer/
~/TelegramApiServer$ composer install -o --no-dev

Loading composer repositories with package information
Installing dependencies from lock file
Package operations: 46 installs, 0 updates, 0 removals

  • Installing amphp/amp (v2.4.4): Downloading (100%)
  • Installing amphp/sync (v1.4.0): Downloading (100%)
  • Installing amphp/cache (v1.3.0): Downloading (100%)
  • Installing amphp/hpack (v3.1.0): Downloading (100%)
  • Installing psr/log (1.1.3): Downloading (100%)
  • Installing psr/http-message (1.0.1): Downloading (100%)
  • Installing league/uri-interfaces (2.1.0): Downloading (100%)
  • Installing league/uri (6.2.1): Downloading (100%)
  • Installing cash/lrucache (1.0.0): Downloading (100%)
  • Installing league/uri-parser (1.4.1): Downloading (100%)
  • Installing kelunik/certificate (v1.1.2): Downloading (100%)
  • Installing daverandom/libdns (v2.0.2): Downloading (100%)
  • Installing amphp/byte-stream (v1.7.3): Downloading (100%)
  • Installing amphp/process (v1.1.0): Downloading (100%)
  • Installing amphp/windows-registry (v0.3.2): Downloading (100%)
  • Installing amphp/parser (v1.0.0): Downloading (100%)
  • Installing amphp/dns (v1.2.1): Downloading (100%)
  • Installing amphp/socket (v1.1.1): Downloading (100%)
  • Installing amphp/http (v1.6.0): Downloading (100%)
  • Installing amphp/http-server (v2.0.1): Downloading (100%)
  • Installing amphp/http-server-form-parser (v1.1.4): Downloading (100%)
  • Installing nikic/fast-route (v1.3.0): Downloading (100%)
  • Installing amphp/http-server-router (v1.0.2): Downloading (100%)
  • Installing amphp/serialization (v1.0.0): Downloading (100%)
  • Installing amphp/parallel (v1.4.0): Downloading (100%)
  • Installing amphp/websocket (v1.0.0-rc2): Downloading (100%)
  • Installing amphp/http-client (v4.3.0): Downloading (100%)
  • Installing amphp/websocket-client (dev-master 619e2b5): Cloning 619e2b550e from cache
  • Installing amphp/websocket-server (v2.0.0-rc3): Downloading (100%)
  • Installing danog/libdns-json (0.1.1): Downloading (100%)
  • Installing tivie/htaccess-parser (0.2.3): Downloading (100%)
  • Installing erusev/parsedown (1.7.4): Downloading (100%)
  • Installing paragonie/random_compat (v2.0.18): Downloading (100%)
  • Installing paragonie/constant_time_encoding (v1.0.4): Downloading (100%)
  • Installing danog/tgseclib (3): Downloading (100%)
  • Installing danog/tg-file-decoder (0.1.2): Downloading (100%)
  • Installing danog/primemodule (1.0.3): Downloading (100%)
  • Installing danog/magicalserializer (1.0): Downloading (100%)
  • Installing danog/ipc (0.1.1): Downloading (100%)
  • Installing danog/dns-over-https (0.2.6): Downloading (100%)
  • Installing amphp/http-client-cookies (v1.0.0): Downloading (100%)
  • Installing amphp/file (v1.0.0): Downloading (100%)
  • Installing danog/madelineproto (dev-master 68ab47d): Cloning 68ab47de32 from cache
  • Installing symfony/polyfill-ctype (v1.15.0): Downloading (100%)
  • Installing phpoption/phpoption (1.7.3): Downloading (100%)
  • Installing vlucas/phpdotenv (v4.1.5): Downloading (100%)
    Generating optimized autoload files

cd vendor/danog/madelineproto/ && git submodule init && git submodule update
Submodule 'docs' ([email protected]:danog/MadelineProtoDocs) registered for path 'docs'
Submodule 'examples/magnaluna' ([email protected]:danog/magnaluna) registered for path 'examples/magnaluna'
Submodule 'examples/pipesbot' ([email protected]:danog/pipesbot) registered for path 'examples/pipesbot'
Submodule 'schemas' ([email protected]:danog/schemas) registered for path 'schemas'
Cloning into 'docs'...
Warning: Permanently added the RSA host key for IP address '140.82.114.3' to the list of known hosts.
Permission denied (publickey).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.
fatal: clone of '[email protected]:danog/MadelineProtoDocs' into submodule path 'docs' failed
Script cd vendor/danog/madelineproto/ && git submodule init && git submodule update handling the post-autoload-dump event returned with error code 128

[error] Undefined index: location

Hello, I have this issue with supergroup:

[2020-09-26 13:13:05] [critical] Undefined index: location in PeerHandler.php:884
[2020-09-26 13:13:05] [error] Undefined index: location
{
"exception": "danog\MadelineProto\Exception",
"message": "Undefined index: location",
"file": "/root/TelegramApiServer/vendor/danog/madelineproto/src/danog/MadelineProto/MTProtoTools/PeerHandler.php",
"line": 884,
"code": 8,
"backtrace": [
{
"file": "/root/TelegramApiServer/vendor/danog/madelineproto/src/danog/MadelineProto/MTProtoTools/PeerHandler.php",
"line": 884,
"function": "exceptionErrorHandler",
"class": "danog\MadelineProto\Exception",
"type": "::"
},
{
"file": "/root/TelegramApiServer/vendor/danog/madelineproto/src/danog/MadelineProto/AbstractAPIFactory.php",
"line": 175,
"function": "getPwrChat",
"class": "danog\MadelineProto\MTProto",
"type": "->"
},
{
"function": "__call_async",
"class": "danog\MadelineProto\AbstractAPIFactory",
"type": "->"
}
]
}

If I set no supergroup picture I have no error

AN UPDATE IS REQUIRED

hi
i receive this.

Revision: 838cf11ff61a975121e11e50caa4e67c6819f192 (AN UPDATE IS REQUIRED)

how can i update ?
i install your code today

change mysql password !

hi
whene a session created i can not change my mysql password in config file!
it used the old password store in session file!
why?
how can i change it?

Question : Converting sessions from DB_TYPE=memory to DB_TYPE=mysql

Hi,
I am currently running TelegramApiServer on Memory DB Type which is working geat 👍 with a little memory leak ...
I just saw you have moved the Mysql DB Branch to the current branch ... and I am very interested to test it ...

As I have have multiple sessions .. if I upgrade to the latest version and use Mysql DB_Type .. Do I have to recreate session or it will be converted automaticity ?

or Nothing specials are stored in the sessions and I can switch between DB_Types when ever I want ?

Thanks

Call to undefined function TelegramApiServer\Server\pcntl_fork()

Hello,
thank you so much for developing this amazing tool!

I was trying to start it on Windows 10 with PHP 7.4.15 but I am getting this error:

Fatal error: Uncaught Error: Call to undefined function TelegramApiServer\Server\pcntl_fork() in C:\Users\user\Desktop\TelegramApiServer-1.10.5\src\Server\Fork.php:9
Stack trace:
#0 C:\Users\user\Desktop\TelegramApiServer-1.10.5\server.php(77): TelegramApiServer\Server\Fork::run(Object(Closure))
#1 {main}
  thrown in C:\Users\user\Desktop\TelegramApiServer-1.10.5\src\Server\Fork.php on line 9

How could I solve?

Is amphp-http-server production ready?

Is amphp-http-server production ready? or should I use nginx and proxy from it?

And I am getting some errors in the log :

MsgIdHandler, dominosys_bot: WARNING: Given message id (6781298634271932417) is bigger than or equal to the current limit (6781298634271924225). Consider syncing your date.

DataCenter: Connection failed: Invalid URI specified at Amp\Uri\Uri::__construct Argument

And on exception : Exception: Trying to access array offset on value of type bool in PKCS8.php:87

And just got this one :

Tools:                  Got the following exception within a forked strand started @ Loop:57, trying to rethrow
Tools:                  Telegram returned an RPC error: The authorization key has expired (401) (AUTH_KEY_UNREGISTERED), caused by /home/mofadmin/TelegramApiServer/vendor/danog/madelineproto/src/danog/MadelineProto/MTProtoSession/ResponseHandler.php:460


TL trace:
['updates.getState']
danog\MadelineProto\MTProtoSession\{closure}()
Coroutine.php(139):     send(null)
Placeholder.php(43):    danog\MadelineProto\{closure}(null,null)
Coroutine.php(178):     onResolve({})
Tools.php(461):         __construct({})
ResponseHandler.php(461):       callFork({})
ResponseHandler.php(93):        handleResponse()
Driver.php(116):        handleMessages("alm",null)
Driver.php(72):         tick()
Loop.php(84):           run()
Tools.php(327):         run({})
CombinedAPI.php(260):   wait({})
Client.php(81):         loop()
Driver.php(116):        TelegramApiServer\{closure}("dy",null)
Driver.php(72):         tick()
Loop.php(84):           run()
Server.php(35):         run({})
server.php(61):         __construct()

Exception:              danog\MadelineProto\RPCErrorException: AUTH_KEY_UNREGISTERED in /home/mofadmin/TelegramApiServer/vendor/danog/madelineproto/src/danog/MadelineProto/MTProtoSession/ResponseHandler.php:460
Stack trace:
#0 [internal function]: danog\MadelineProto\MTProtoSession\Session->danog\MadelineProto\MTProtoSession\{closure}()
#1 /home/mofadmin/TelegramApiServer/vendor/danog/madelineproto/src/danog/MadelineProto/Coroutine.php(139): Generator->send(NULL)
#2 /home/mofadmin/TelegramApiServer/vendor/amphp/amp/lib/Internal/Placeholder.php(43): danog\MadelineProto\Coroutine->danog\MadelineProto\{closure}(NULL, NULL)
#3 /home/mofadmin/TelegramApiServer/vendor/danog/madelineproto/src/danog/MadelineProto/Coroutine.php(178): danog\MadelineProto\Coroutine->onResolve(Object(Closure))
#4 /home/mofadmin/TelegramApiServer/vendor/danog/madelineproto/src/danog/MadelineProto/Tools.php(461): danog\MadelineProto\Coroutine->__construct(Object(Generator))
#5 /home/mofadmin/TelegramApiServer/vendor/danog/madelineproto/src/danog/MadelineProto/MTProtoSession/ResponseHandler.php(461): danog\MadelineProto\Tools::callFork(Object(Generator))
#6 /home/mofadmin/TelegramApiServer/vendor/danog/madelineproto/src/danog/MadelineProto/MTProtoSession/ResponseHandler.php(93): danog\MadelineProto\MTProtoSession\Session->handleResponse('\x18\x00\x00\x00\xA2\x05\x1C^', '\x01x*$\xA2\x05\x1C^')
#7 /home/mofadmin/TelegramApiServer/vendor/amphp/amp/lib/Loop/Driver.php(116): danog\MadelineProto\MTProtoSession\Session->handleMessages('alm', NULL)
#8 /home/mofadmin/TelegramApiServer/vendor/amphp/amp/lib/Loop/Driver.php(72): Amp\Loop\Driver->tick()
#9 /home/mofadmin/TelegramApiServer/vendor/amphp/amp/lib/Loop.php(84): Amp\Loop\Driver->run()
#10 /home/mofadmin/TelegramApiServer/vendor/danog/madelineproto/src/danog/MadelineProto/Tools.php(327): Amp\Loop::run(Object(Closure))
#11 /home/mofadmin/TelegramApiServer/vendor/danog/madelineproto/src/danog/MadelineProto/CombinedAPI.php(260): danog\MadelineProto\Tools::wait(Object(Amp\Internal\PrivatePromise))
#12 /home/mofadmin/TelegramApiServer/src/Client.php(81): danog\MadelineProto\CombinedAPI->loop()
#13 /home/mofadmin/TelegramApiServer/vendor/amphp/amp/lib/Loop/Driver.php(116): TelegramApiServer\Client->TelegramApiServer\{closure}('dy', NULL)
#14 /home/mofadmin/TelegramApiServer/vendor/amphp/amp/lib/Loop/Driver.php(72): Amp\Loop\Driver->tick()
#15 /home/mofadmin/TelegramApiServer/vendor/amphp/amp/lib/Loop.php(84): Amp\Loop\Driver->run()
#16 /home/mofadmin/TelegramApiServer/src/Server.php(35): Amp\Loop::run(Object(Closure))
#17 /home/mofadmin/TelegramApiServer/server.php(61): TelegramApiServer\Server->__construct(Object(TelegramApiServer\Client), Array)
#18 {main}

Next Error: Loop exceptionally stopped without resolving the promise in /home/mofadmin/TelegramApiServer/vendor/danog/madelineproto/src/danog/MadelineProto/Tools.php:329
Stack trace:
#0 /home/mofadmin/TelegramApiServer/vendor/danog/madelineproto/src/danog/MadelineProto/CombinedAPI.php(260): danog\MadelineProto\Tools::wait(Object(Amp\Internal\PrivatePromise))
#1 /home/mofadmin/TelegramApiServer/src/Client.php(81): danog\MadelineProto\CombinedAPI->loop()
#2 /home/mofadmin/TelegramApiServer/vendor/amphp/amp/lib/Loop/Driver.php(116): TelegramApiServer\Client->TelegramApiServer\{closure}('dy', NULL)
#3 /home/mofadmin/TelegramApiServer/vendor/amphp/amp/lib/Loop/Driver.php(72): Amp\Loop\Driver->tick()
#4 /home/mofadmin/TelegramApiServer/vendor/amphp/amp/lib/Loop.php(84): Amp\Loop\Driver->run()
#5 /home/mofadmin/TelegramApiServer/src/Server.php(35): Amp\Loop::run(Object(Closure))
#6 /home/mofadmin/TelegramApiServer/server.php(61): TelegramApiServer\Server->__construct(Object(TelegramApiServer\Client), Array)
#7 {main}
Tools:                  Got the following exception within a forked strand started @ Loop:57, trying to rethrow
Tools:                  Telegram returned an RPC error: The authorization key has expired (401) (AUTH_KEY_UNREGISTERED), caused by /home/mofadmin/TelegramApiServer/vendor/danog/madelineproto/src/danog/MadelineProto/MTProtoSession/ResponseHandler.php:460


TL trace:
['updates.getDifference']
danog\MadelineProto\MTProtoSession\{closure}()
Coroutine.php(139):     send(null)
Placeholder.php(43):    danog\MadelineProto\{closure}(null,null)
Coroutine.php(178):     onResolve({})
Tools.php(461):         __construct({})
ResponseHandler.php(461):       callFork({})
ResponseHandler.php(93):        handleResponse()
Driver.php(116):        handleMessages("alo",null)
Driver.php(72):         tick()
Loop.php(84):           run()
Tools.php(327):         run({})
CombinedAPI.php(260):   wait({})
Client.php(81):         loop()
Driver.php(116):        TelegramApiServer\{closure}("dy",null)
Driver.php(72):         tick()
Loop.php(84):           run()
Server.php(35):         run({})
server.php(61):         __construct()

PHP Fatal error:  Uncaught danog\MadelineProto\RPCErrorException: AUTH_KEY_UNREGISTERED in /home/mofadmin/TelegramApiServer/vendor/danog/madelineproto/src/danog/MadelineProto/MTProtoSession/ResponseHandler.php:460
Stack trace:
#0 [internal function]: danog\MadelineProto\MTProtoSession\Session->danog\MadelineProto\MTProtoSession\{closure}()
#1 /home/mofadmin/TelegramApiServer/vendor/danog/madelineproto/src/danog/MadelineProto/Coroutine.php(139): Generator->send(NULL)
#2 /home/mofadmin/TelegramApiServer/vendor/amphp/amp/lib/Internal/Placeholder.php(43): danog\MadelineProto\Coroutine->danog\MadelineProto\{closure}(NULL, NULL)
#3 /home/mofadmin/TelegramApiServer/vendor/danog/madelineproto/src/danog/MadelineProto/Coroutine.php(178): danog\MadelineProto\Coroutine->onResolve(Object(Closure))
#4 /home/mofadmin/TelegramApiServer/vendor/danog/madelineproto/src/danog/MadelineProto/Tools.php(461): danog\MadelineProto\Coroutine->__construct(Object(Generator))
#5 /home/mofadmin/TelegramApiServer/vendor/danog/madelineproto/src/danog/Madeline in /home/mofadmin/TelegramApiServer/vendor/danog/madelineproto/src/danog/MadelineProto/Tools.php on line 329

And now I can't kill the server with ctrl+c, it keeps printing CombinedAPI: Serializing combined event handler!!! Had to use kill -9 <pid>

Docker container don't start anymore : Allowed memory size exhausted

Hello,

I used TAS in Docker version since last week without any problem, but today I can't use it anymore.

2020-06-29T17:14:08.353209071Z ---------------------------
2020-06-29T17:14:08.353236081Z Starting with configuration:
2020-06-29T17:14:08.353243295Z  - Hosts to be waiting for: [mysql:3306]
2020-06-29T17:14:08.353248324Z  - Timeout before failure: 30 seconds
2020-06-29T17:14:08.353252973Z  - TCP connection timeout before retry: 5 seconds
2020-06-29T17:14:08.353257471Z  - Sleeping time before checking for hosts availability: 0 seconds
2020-06-29T17:14:08.353263493Z  - Sleeping time once all hosts are available: 0 seconds
2020-06-29T17:14:08.353267870Z  - Sleeping time between retries: 1 seconds
2020-06-29T17:14:08.353272289Z --------------------------------------------------------
2020-06-29T17:14:08.353276707Z Checking availability of mysql:3306
2020-06-29T17:14:08.353281126Z Host mysql:3306 is now available!
2020-06-29T17:14:08.353326681Z --------------------------------------------------------
2020-06-29T17:14:08.353334025Z docker-compose-wait - Everything's fine, the application can now start!
2020-06-29T17:14:08.353339075Z --------------------------------------------------------
2020-06-29T17:14:08.488714695Z [2020-06-29 17:14:08] [warning]
2020-06-29T17:14:08.488767625Z Starting MadelineProto...
2020-06-29T17:14:08.488774006Z
2020-06-29T17:14:09.372340270Z [2020-06-29 17:14:09] [warning] Serialization is out of date, reconstructing object!
2020-06-29T17:14:09.409051593Z
2020-06-29T17:14:09.409094794Z Fatal error: Allowed memory size of 268435456 bytes exhausted (tried to allocate 42508288 bytes) in /app-host-link/vendor/danog/madelineproto/src/danog/MadelineProto/TL/PrettyException.php on line 101

I've increased memory size up to 2048M in .env.docker, and even restarted server, but still nothing.

I can't go further, as any command ends with this response :

me@myserver:/var/www/TelegramApiServer# docker exec -it telegram-api-server curl http://127.0.0.1:9503/api/getPwrChat/?id=@AnyTelegramGroup
Error response from daemon: Container 6345704be585d470a9fce2310fbf96548d990ec699440a8f01320772eb677856 is restarting, wait until the container is running

So I can't go inside the container to update php.ini settings :(
Of course, I didnt changed anything since it's broken, I wasnt even at home.

Thanks for any suggestion !

Sessions memory usage

1-What are the reasons that some sessions (accounts) using less and some huge memory usage ?

2-I have multiple sessions ..
First time I started the Server with sessions=* and memory usage was 3.8G !
Second time I tried to add them manually using addSession one by one and memory usage was 2.15G
Third time I tried sessions=* again and memory usage was 364 MB !

Feature Request : Allow customizations

HI,
It would be nice if you could convert the hole thing to be like a module and users can customize the usage without torching the source code ...

Like adding some async events maybe!!

I really need auto bot login from my PR but currently there is no way to achive this without touching the source code which makes the updating the fork a nightmare

$botLoginPromise = $this->client->tryBotLogin($this->session);
        if ($botLoginPromise)
          yield $botLoginPromise;

Allow adding some custom routes in server.php maybe!!

Allow customizing configs

Custom Sessions Path and Auto Adding Sessions

Hi,

It could be good idea to being able to define custom Session(s) path and also adding an option to Add all available sessions to the server.

I have few sessions and every time on starting the TelegramApiServer I have to add(register) all of them to the server..

Thanks

Unexpected behavior when using the ChatId by using the Method /api/getHistory

Hi,

first of all love your ApiServer awesome way to pull information from a Telegram Account.

Now to the issue..... according to MadelineProto is it possible to pull chatHistory by using the ChannelID instead of the Username/UserID

https://docs.madelineproto.xyz/API_docs/methods/messages.getHistory.html

but when i try to use the ChannelID as peer like this for example:

http://xxx.xxx.xx.x:9503/api/getHistory/?data[peer]=ChannelID&data[limit]=1

same goes for example

http://xxx.xxx.xx.x:9503/api/getInfo?id=ChannelID

it throws an error like

 "success": false,
    "errors": [
        {
            "exception": "danog\\MadelineProto\\Exception",
            "message": "This peer is not present in the internal peer database",
            "file": "/app-host-link/vendor/danog/madelineproto/src/danog/MadelineProto/MTProtoTools/PeerHandler.php",
            "line": 545,
            "code": 0
        }
    ],
    "response": null
}

I assume that the error lies by me not using the API correctly but i have tried different variations shown in the MadelineProto documentation like channel#ChannelID but in that case the api returns the chathistory of the Channel literally called Channel and ignores everything after the Hashtag. If i url encode the Hashtag it just throws the same error again.

Thanks for any advice you can give

Downloading files (profile pic)

Hi
I am trying to download file (profile pic) and I am getting errors ..

With direct Madelineproto I was doing this :
$profile_pic = $MadelineProto->getPropicInfo($peer);
$MadelineProto->downloadToFile($profile_pic, $storing_path);

Following your example .. First I tried to get Profile Pic and using json_encode() with JSON_PRETTY_PRINT Parameter I got following :
https://paste.ubuntu.com/p/xbRzJ8Wyc3/

Then I used Curl command like this :
https://paste.ubuntu.com/p/sFWCc9fXXv/

But it is showing following Error :
https://paste.ubuntu.com/p/tSdPY26C6B/

I even tried to run your Downloading example curl command and it showed another error :

command :
https://paste.ubuntu.com/p/4R82GFMF6p/

error :
https://paste.ubuntu.com/p/Ptp8vZpHWm/

could not find method

{
"success": 0,
"errors": [
{
"code": 0,
"message": "Could not find method: users"
}
],
"response": null
}

Question: contacts.importContacts method not working

Hi, I think I am doing something incorrectly. I send get request as follow: - I use http_build_query()

http://127.0.0.1:9503/api/sname/contacts.importContacts/contacts%5B_%5D=inputPhoneContact&contacts%5Bclient_id%5D=0&contacts%5Bphone%5D=%2B00000000&contacts%5Bfirst_name%5D=xxxx&contacts%5Blast_name%5D=xxxx

the response:

{ "success": true, "errors": [], "response": { "_": "contacts.importedContacts", "imported": [], "popular_invites": [], "retry_contacts": [], "users": [] } }

The response is same if I use post method using terminal:

curl --location --request POST 'http://127.0.0.1:9503/api/contacts.importContacts'
--header 'Content-Type: application/json'
--data '{
[
contacts [
[
"_": "inputPhoneContact",
"client_id": "0",
"phone": "+00000000",
"first_name": "xxxxx",
"last_name": "xxxxx"
]
]
]
}'

I appreciate your help, thanks.

EventHandler optimization

Need to rework eventHandler, because current aproach may be unsuitable for bots, when madelineProto is used along with bot api.

  • EventHandler must be set only on client connection to websocket.
  • setNoop must be set when no clients left on websocket.

Newly created session doesn't work with TelegramApiServer But Works with direct Madelineproto

Hi..
I have tried tens of times before asking this question ...

for creating madeline sessions in CLI I am using following simple script :

<?php
if (!file_exists('madeline.php')) {
    copy('https://phar.madelineproto.xyz/madeline.php', 'madeline.php');
}
include 'madeline.php';

$MadelineProto = new \danog\MadelineProto\API('session.madeline');
$MadelineProto->async(true);
$MadelineProto->loop(function () use ($MadelineProto) {
    yield $MadelineProto->start();

    $me = yield $MadelineProto->getSelf();

    $MadelineProto->logger($me);

    yield $MadelineProto->echo('OK, done!');
}

The first test session that I have created using the same way for testing TelegramApiServer worked and is still working with TelegramApiServer ...
But Newly created sessions are throwing following error while adding the TelegramApiServer ...
But Surprisingly they are working with direct Madelineproto without any problem !

Starting MadelineProto...
 
[2020-05-24 06:11:11] [error] TypeError: Typed property danog\MadelineProto\MyTelegramOrgWrapper::$creation_hash must be string, null used in /home/test/TelegramApiServer/vendor/danog/madelineproto/src/danog/MadelineProto/Serialization.php:71
Stack trace:
#0 /home/test/TelegramApiServer/vendor/danog/madelineproto/src/danog/MadelineProto/Serialization.php(71): unserialize()
#1 /home/test/TelegramApiServer/vendor/danog/madelineproto/src/danog/MadelineProto/API.php(130): danog\MadelineProto\Serialization::legacyUnserialize()
#2 [internal function]: danog\MadelineProto\API->__construct_async()
#3 /home/test/TelegramApiServer/vendor/danog/madelineproto/src/danog/MadelineProto/Coroutine.php(116): Generator->send()
#4 /home/test/TelegramApiServer/vendor/amphp/amp/lib/Success.php(41): danog\MadelineProto\Coroutine->danog\MadelineProto\{closure}()
#5 /home/test/TelegramApiServer/vendor/danog/madelineproto/src/danog/MadelineProto/Coroutine.php(155): Amp\Success->onResolve()
#6 /home/test/TelegramApiServer/vendor/danog/madelineproto/src/danog/MadelineProto/Tools.php(397): danog\MadelineProto\Coroutine->__construct()
#7 /home/test/TelegramApiServer/vendor/danog/madelineproto/src/danog/MadelineProto/Async/AsyncConstruct.php(93): danog\MadelineProto\Tools::call()
#8 /home/test/TelegramApiServer/vendor/danog/madelineproto/src/danog/MadelineProto/API.php(108): danog\MadelineProto\Async\AsyncConstruct->setInitPromise()
#9 /home/test/TelegramApiServer/vendor/danog/magicalserializer/src/danog/Serializable.php(35): danog\MadelineProto\API->__magic_construct()
#10 /home/test/TelegramApiServer/src/Client.php(62): danog\MadelineProto\API->__construct()
#11 /home/test/TelegramApiServer/src/Client.php(41): TelegramApiServer\Client->addSession()
#12 /home/test/TelegramApiServer/src/Server/Server.php(33): TelegramApiServer\Client->connect()
#13 /home/test/TelegramApiServer/vendor/amphp/amp/lib/Loop/Driver.php(119): TelegramApiServer\Server\Server->TelegramApiServer\Server\{closure}()
#14 /home/test/TelegramApiServer/vendor/amphp/amp/lib/Loop/Driver.php(72): Amp\Loop\Driver->tick()
#15 /home/test/TelegramApiServer/vendor/amphp/amp/lib/Loop.php(95): Amp\Loop\Driver->run()
#16 /home/test/TelegramApiServer/src/Server/Server.php(40): Amp\Loop::run()
#17 /home/test/TelegramApiServer/server.php(85): TelegramApiServer\Server\Server->__construct()
#18 {main}

I don't know ... what I am doing wrong or something is changed...

Nothing happens "Authorizing session: session"

Hi! I run in docker:

php server.php --docker --port=9500 --session=session
[2020-08-09 14:18:01] [warning]
Starting MadelineProto...

[2020-08-09 14:18:01] [notice] MadelineProto
[2020-08-09 14:18:01] [notice] Copyright (C) 2016-2020 Daniil Gentili
[2020-08-09 14:18:01] [notice] Licensed under AGPLv3
[2020-08-09 14:18:01] [notice] https://github.com/danog/MadelineProto
[2020-08-09 14:18:01] [debug] Istantiating DataCenter...
[2020-08-09 14:18:01] [debug] Translating TL schemas...
[2020-08-09 14:18:01] [info] Loading TL schemes...
[2020-08-09 14:18:01] [info] Parsing TL_mtproto_v1.tl...
[2020-08-09 14:18:01] [error] CRC32 mismatch (29c1636d, 73f1f8dc) for msg_container#73f1f8dc messages:vector<%Message> = MessageContainer;
[2020-08-09 14:18:01] [debug] Translating objects...
[2020-08-09 14:18:01] [debug] Translating methods...
[2020-08-09 14:18:01] [info] Parsing TL_telegram_v113.tl...
[2020-08-09 14:18:01] [debug] Translating objects...
[2020-08-09 14:18:01] [debug] Translating methods...
[2020-08-09 14:18:01] [info] Parsing TL_secret.tl...
[2020-08-09 14:18:01] [debug] Translating objects...
[2020-08-09 14:18:01] [debug] Translating methods...
[2020-08-09 14:18:01] [info] Parsing TL_botAPI.tl...
[2020-08-09 14:18:01] [debug] Translating objects...
[2020-08-09 14:18:01] [debug] Translating methods...
[2020-08-09 14:18:01] [warning] Creating/checking table tmp_1cb2cfdf114da16_MTProto_chats
[2020-08-09 14:18:01] [info]
[
    "\n            CREATE TABLE IF NOT EXISTS `tmp_1cb2cfdf114da16_MTProto_chats`\n            (\n                `key` VARCHAR(255) NOT NULL,\n                `value` MEDIUMBLOB NULL,\n                `ts` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,\n                PRIMARY KEY (`key`)\n            )\n            ENGINE = InnoDB\n            CHARACTER SET 'utf8mb4' \n            COLLATE 'utf8mb4_general_ci'\n        ",
    []
]
[2020-08-09 14:18:01] [warning]
TelegramApiServer ready.
Number of sessions: 1.
[2020-08-09 14:18:01] [debug] Starting
[2020-08-09 14:18:01] [warning] Running in production with assertions enabled is not recommended; it has a negative impacton performance. Disable assertions in php.ini (zend.assertions = -1) for best performance or set the debug mode option to hide this warning.
[2020-08-09 14:18:01] [debug] Started
[2020-08-09 14:18:01] [info] Listening on http://0.0.0.0:9500/
Authorizing session: session

And nothing happens even after 10 minutes.

In mysql 4 empty tables:

image

I see empty file sessions/session.madeline.ipc.

Proxy works:

curl -socks5-hostname "XXXX:XXXX@XXXXX:8000" https://api.telegram.org
<html>
<head><title>302 Found</title></head>
<body>
<center><h1>302 Found</h1></center>
<hr><center>nginx/1.16.1</center>
</body>
</html>
# ENV file version
# Check for outdated .env files
VERSION=1

SERVER_ADDRESS=0.0.0.0
SERVER_PORT=9503

MEMORY_LIMIT=256M
TIMEZONE=UTC

# List of allowed clients. Separate with comma.
# Leave blanc, to allow requests from all IP (dangerous!)
IP_WHITELIST=127.0.0.1

# TELEGRAM CLIENT
TELEGRAM_API_ID=XXX
TELEGRAM_API_HASH=XXXXXXXXXXXX
# FATAL_ERROR = 0; ERROR = 1; WARNING = 2; const NOTICE = 3; VERBOSE = 4; ULTRA_VERBOSE = 5;
LOGGER_LEVEL=5

# TELEGRAM SOCKS5 PROXY (optional)
TELEGRAM_PROXY_ADDRESS=XXXXXXXXX
TELEGRAM_PROXY_PORT=8000
TELEGRAM_PROXY_USERNAME=XXXXX
TELEGRAM_PROXY_PASSWORD=XXXXX

# DB
#   memory
#       Keep all data in memory/session file.
#       This is default behavior
#   mysql
#       Keep part of data in mysql database.
#       Reduce memory consumption and session size. Beta function.
#       MariaDb + InnoDb Preffered.
#       Tables and DB will be created if not exists.

#   Change this type to convert session:
DB_TYPE=mysql
#   MYSQL Settings. Required, when DB_TYPE=mysql
MYSQL_HOST=mysql
MYSQL_PORT=3306
MYSQL_USER=root
MYSQL_PASSWORD=
MYSQL_DATABASE=MadelineProto
MYSQL_MAX_CONNECTIONS=10
MYSQL_IDLE_TIMEOUT=60
#   Recent data will be stored in memory this amount of time:
MYSQL_CACHE_TTL="+5 minutes"

Doesn't work

Hi,
I've tryed this installing swoole, amp, madeline etc. All worked, but, the server doesn't answer my requests. It keeps loading the page and also there are no logs.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.