Search code examples
phptimeouttelegram-webhook

encountering "Read timeout expired" error by Webhook after 60 Sec of execution


lately Im facing a problem with telegram bot api which i haven't had before... Im using Webhook method of connection to catch bot requests and respoding with PHP script and sometimes the triggered script takes more than a minute to finish processing. about a month ago everything was working fine and telegram bot wait long enough for script to completely execute, but now my connection suspend and im getting this Webhook error through telegram api "Read timeout expired" after 60 Seconds of execution and then it attempt the same request again and these goes on and on until my server overloads with too many open entries... i already tried connection-handling although it seemed useless since my connection is not browser-end. i realize it should have something to do with Webhook's setting itself but i cant figure it out... any ideas?

Here is something that could give you the figure:

my code:

<?php

...running hundreds of thousands of multi-curl requests that take 10 min for example
...or/ sleep(61);
...or/ basically anything that takes more than 60 seconds to run

?>

Telegram's response to my Webhook's state after 60 seconds of running the above script:

{"ok":true,"result":{"url":"https://????.com/??.php","has_custom_certificate":false,"pending_update_count":1,"last_error_date":1499351442,"last_error_message":"Read timeout expired","max_connections":40}}


Solution

  • this is the code I put at the top of my scripts. it responds to telegram so they stop waiting, and the scripts continues processing.

    <?php
        set_time_limit(0);
        ignore_user_abort(true);
        $out =  json_encode([
          'method'=>'sendMessage',
          'chat_id'=>$my_chat_id,
          'text'=> "Starting process..."
          ]);   
        echo $out;
        header('Connection: close');
        header('Content-Length: '.strlen($out));
        header("Content-type:application/json");
        flush();
        if (function_exists('fastcgi_finish_request')) {
            fastcgi_finish_request();
        }