0

I'm creating a highload Telegram Bot, which means many requests come in and they take time to handle. I use webhook (Telegram sends updates to, say, handler.php) which requires to respond with correct [] answer and fully close the connection for Telegram to send the next update. Otherwise Telegram will only increase pending_update_count and won't send any new updates until the previous one is handled.

So what I'm trying to do is to respond correctly and close the connection before code is executed.

StackOverflow suggests some solutions. But none of these will work for me because they only close the connection if there was no output and I need to respond with [].

How do I close a connection early?

Send response and continue executing script - PHP

The only workaround I came up with is to call shell_exec('php sendMessage.php >/dev/null 2>/dev/null &') from handler.php. Works perfectly well but that's not what I need. Any other suggestions to respond and close the connection, so code can execute in the background?

Dei
  • 11
  • 3

1 Answers1

0

I found a simple solution that works for Telegram Bot API webhooks. It allows me to call the handling script directly within the script itself without using exec() or shell_exec().

Time-consuming code

$bool = true; // some condition in your regular code
if($bool) {
    sleep(10);
}

This will cause a huge delay for other bot users since Telegram didn't get the response and won't send you any other updates.

Solution

if(isset($_GET['action'])) {
    sleep(10);
}

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://localhost/handler.php?action');
curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
curl_setopt($ch, CURLOPT_TIMEOUT_MS, 50);
curl_exec($ch);
curl_close($ch);

This way the script will call itself (or any other script), Telegram will be provided with correct and quick response, while the heavy part is executed separately.

It is strongly recommended not to go below 50 ms on CURLOPT_TIMEOUT_MS, sometimes it just doesn't work when receiving requests from Telegram.

Dei
  • 11
  • 3