Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

my telegram bot keeps sending messages endlessly

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>');
    }
    
?>
like image 820
Hamidreza Ahmadzadeh Avatar asked Nov 14 '16 16:11

Hamidreza Ahmadzadeh


2 Answers

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); )

like image 137
Yoily L Avatar answered Sep 29 '22 09:09

Yoily L


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.

like image 45
Charles Okwuagwu Avatar answered Sep 29 '22 08:09

Charles Okwuagwu