6

I Started programming a telegram bot and I've got a problem. when I send /start command it sends me a welcome message (as i programmed it) but it doesn't sends it once! it keeps sending it endlessly like loop! this is the source:

<?php
    define('API_KEY','<token>');
    
    function makereq($method,$datas=[])
    {
        $url = "https://api.telegram.org/bot".API_KEY."/".$method;
        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
        curl_setopt($ch,CURLOPT_POSTFIELDS,http_build_query($datas));
        $res = curl_exec($ch);
        if(curl_error($ch)){
            var_dump(curl_error($ch));
        }else{
            return json_decode($res);
        }
    }
    
    $website = "https://api.telegram.org/bot".API_KEY;
    
    $update = json_decode(file_get_contents('php://input'));
    
    $chat_id = $update->message->chat->id;
    $message_id = $update->message->message_id;
    $from_id = $update->message->from->id;
    $name = $update->message->from->first_name;
    $username = $update->message->from->username;
    $textmessage = isset($update->message->text)?$update->message->text:'';
    $reply = $update->message->reply_to_message->forward_from->id;
    $stickerid = $update->message->reply_to_message->sticker->file_id;
    $messageEntity = $update->messageentity->type;
    
    function SendMessage($ChatId, $TextMsg)
    {
     makereq('sendMessage',[
    'chat_id'=>$ChatId,
    'text'=>$TextMsg,
    'parse_mode'=>"MarkDown"]
     );
    }
    if($textmessage == '/start')
    {
      SendMessage($chat_id,'<welcome message>');
    }
    
?>
Tibebes. M
  • 6,940
  • 5
  • 15
  • 36

6 Answers6

10

You're probably using webhook.
If you don't respond with a http status 200 the telegram bot API thinks something is wrong with your server and requests again every few seconds as mentioned in the API documentation:

In case of an unsuccessful request, we will give up after a reasonable amount of attempts.

So just add header("HTTP/1.1 200 OK"); to your script and voilà!
(If your php version is greater than 5.4 you can use http_response_code(200); )

Yoily L
  • 412
  • 3
  • 8
2

If you are polling with getUpdates, you need to increment your offset.

offset = 1 + latest_update_id

IF you are using WebHooks ... https://core.telegram.org/bots/api#update update_id

The update‘s unique identifier. Update identifiers start from a certain positive number and increase sequentially. This ID becomes especially handy if you’re using Webhooks, since it allows you to ignore repeated updates or to restore the correct update sequence, should they get out of order.

Charles Okwuagwu
  • 10,538
  • 16
  • 87
  • 157
1

As Yoily L said, you gotta return 200 before telegram thinks the request has failed.

You may use fastcgi_finish_request() to flush response data to the client. http://php.net/manual/en/function.fastcgi-finish-request.php

http_response_code(200);
fastcgi_finish_request();

// continue execution, send messages and whatever

Also, notice what tuxrampage commented in the docs:

The script will still occupy a FPM process after fastcgi_finish_request(). So using it excessively for long running tasks may occupy all your FPM threads up to pm.max_children. This will lead to gateway errors on the webserver.

Another important thing is session handling. Sessions are locked as long as they're active (see the documentation for session_write_close()). This means subsequent requests will block until the session is closed.

You should therefore call session_write_close() as soon as possible (even before fastcgi_finish_request()) to allow subsequent requests and a good user experience.

This also applies for all other locking techniques as flock or database locks for example. As long as a lock is active subsequent requests might bock.

You'll probably want to check

if (is_callable('fastcgi_finish_request')) {
    ...
}

More info in related question: continue processing php after sending http response

nikans
  • 2,468
  • 1
  • 28
  • 35
1

I came upon this issue recently and stopped it by sending a blank message to the chat. you get an error from telegram, but no more messages are sent.

Toby Allen
  • 10,997
  • 11
  • 73
  • 124
0

When my Telegram-bot keeped sending messages, I created a table of recording posts in the database. When I am sending a post in my Telegram-bot, written in PHP alghorythm checks if a new post already exists in the database: * if it does, we stop the process of sending the post; * if it doesn't, we continue sending it in Telegram. The described method allows to stop cycle of sending the post again and again.

0

Telegram robot due to the structure of hooks and sending and receiving messages in specified time formats It is very sensitive to time. I had the same problem and found that using the date_default_timezone_set function This will solve the problem after deleting this function. If you have changed time templates in your code, delete them.

mamal
  • 1,791
  • 20
  • 14