2017-02-01 38 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一起使用。