2016-11-14 87 views
3

我开始编程一个电报机器人,我遇到了问题。当我发送/启动命令时,它向我发送一条欢迎消息(正如我编程的那样),但它不会发送一次!它不断循环发送它! 这是源:我的电报机器人不停地发送信息

<?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>'); 
} 

?> 

回答

4

您可能正在使用webhook。如果您没有以http状态200回应,那么电报机器人会认为您的服务器出现问题,并且每隔几秒再请求一次(正如api文档中所述:“如果请求失败,我们会放弃合理的尝试次数“)。 因此,只需将header("HTTP/1.1 200 OK");添加到您的脚本中即可! (如果你的PHP版本大于5.4,你可以使用http_response_code(200);

+0

我想它的工作。谢谢 –

1

如果你是pollinggetUpdates,你需要增加你的偏移量。

偏移= 1 + latest_update_id

如果您正在使用WebHooks ...... https://core.telegram.org/bots/api#updateupdate_id

更新的唯一标识符。更新标识符从 某个正数开始,然后依次递增。 如果你使用网络挂接,因为它可以让你 忽略重复更新或以恢复正确的更新序列, 他们应该得到无序此ID变成 特别方便。

+1

那么如何代码看起来像编辑后? –

+0

你使用webhooks还是你在投票? –

+0

我使用webhooks –

0

由于Yoily大号说,你得回到200之前电报认为请求失败。

您可以使用fastcgi_finish_request()将响应数据刷新到客户端。 http://php.net/manual/en/function.fastcgi-finish-request.php

http_response_code(200); 
fastcgi_finish_request(); 

// continue execution, send messages and whatever 

另外,还要注意什么tuxrampage在文档中评论说:

该脚本将仍占据FPM过程 fastcgi_finish_request()后。因此,长时间运行 任务可能会占用您的所有FPM线程,最多为pm.max_children。这将导致网络服务器上的网关错误 。

另一个重要的事情是会话处理。会话锁定为 ,因为它们处于活动状态(请参阅 session_write_close()的文档)。这意味着后续请求将阻止 ,直到会话关闭。

因此,应该尽快 (甚至fastcgi_finish_request()之前)调用session_write_close()允许后续请求 和良好的用户体验。

这也适用于所有其他锁定技术,例如数据库锁或数据库锁。只要锁定处于活动状态,随后的请求可能会失败。

你可能要检查

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

更多信息相关的问题:continue processing php after sending http response

相关问题