2017-09-13 83 views
1

我送由PHP以这种方式电报BOT的请求:如何在请求失败时在电报机器人中检索sendmessage的结果[in php]?

<?php 
$res=file_get_contents($request); 
echo($res); 

当你发送一个有效的$请求我收到的反馈($ RES),上面写着:

{"ok":true,"result":{"message_id":***,"from":{"id":***,"is_bot":true,"first_name":"**","username":"*****"},"chat":{"id":*****,"first_name":"***","username":"***","type":"private"},"date":1505286416,"text":"test"}} 

但是当事情是错误的$请求我希望收到来自$水库是这样的:

{"ok":false,"error_code":400,"description":"Bad Request: chat not found"} 

相反,我收到一个警告,$ RES是NULL:

Warning: file_get_contents(*******): failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request in /home/test/public_html/test.php on line 2 

我应该怎么做才能获得$ res中的电报回复?

回答

1

如果您需要获取错误响应,则不能使用file_get_contents,请尝试使用cURL代替它。

$url = "https://api.telegram.org/botTOKEN/getChat?chat_id=-1"; 

$curl = curl_init(); 
curl_setopt_array($curl, [ 
    CURLOPT_URL => $url, 
    CURLOPT_RETURNTRANSFER => true 
]); 
$data = curl_exec($curl); 
curl_close($curl); 

$result = json_decode($data, true);