2017-02-01 37 views
0

我正尝试使用Google Maps API来计算两个景点之间的时间和距离。我的代码是相当简单的,它工作(使用键盘和它运行流畅),但是当我部署的代码,并尝试使用机器人给了我错误的答案服务...

这是代码:
使用PHP的电报机器人 - 回声不起作用

$details = "http://maps.googleapis.com/maps/api/distancematrix/json?origins=Miami&destinations=Miami+Beach&mode=driving&sensor=false"; 
    $json = file_get_contents($details); 
    $arr = json_decode($json, TRUE); 
    $distance = $arr[rows][0][elements][0][distance][text]; 
    $time = $arr[rows][0][elements][0][duration][text]; 
    $response = "You should be there in $time. Total distance you'll cover: $distance"; 

$parameters = array('chat_id' => $chatId, "text" => $response); 
$parameters["method"] = "sendMessage"; 
echo json_encode($parameters); 


这是机器人回答我:

"You should be there in {. Total distance you'll cover: {"; 


这是实际的JSON:

{ 
    "destination_addresses" : [ "Miami Beach, Florida, Stati Uniti" ], 
    "origin_addresses" : [ "Miami, Florida, Stati Uniti" ], 
    "rows" : [ 
     { 
     "elements" : [ 
      { 
       "distance" : { 
        "text" : "15,7 km", 
        "value" : 15745 
       }, 
       "duration" : { 
        "text" : "22 min", 
        "value" : 1322 
       }, 
       "status" : "OK" 
      } 
     ] 
     } 
    ], 
    "status" : "OK" 
} 


这是怎么回事?!
更新:file_get_contents返回一个字符串。所以我把它解码成一个PHP数组,但现在这个机器人甚至都不回答!

+0

如何发送消息到telegambot?如果webhook回答500错误,您的机器人不能通过webhook发送消息。还有'$ response ='你应该在{$ time}里面。你要覆盖的总距离:{$ distance}“;'better –

回答

0
$details = "http://maps.googleapis.com/maps/api/distancematrix/json?origins=Miami&destinations=Miami+Beach&mode=driving&sensor=false"; 
$json = file_get_contents($details); 
$JsonObject = json_decode($json); 
$distance = $JsonObject->rows[0]->elements[0]->distance->text; 
$time = $JsonObject->rows[0]->elements[0]->duration->text; 
$response = "You should be there in $time. Total distance you'll cover: $distance"; 
$chatId = "your telegram id here"; 
$botToken = "your bot token here"; 
file_get_contents("https://api.telegram.org/bot$botToken/sendMessage?chat_id=$chatId&text=$response"); 

这一个与file_get_contents一起使用。