2021年9月14日 星期二

【LINE聊天機器人】串接GoogleMap,帶我出去玩杯

Line@聊天機器人串接googlemap

之前有跟大家聊過如何用google script做一個客製化的Line@聊天機器人,今天來延伸一下,把googlemap的功能也導入,讓我們的聊天機器人開始做更多事情吧~

廢話不多說先上code,下面有影片教學

function doPost(e) {
  //認證身份,重新輸入line@ access_token
  var CHANNEL_ACCESS_TOKEN = 'LlKDiyNkeqsDezntSQ8QI2xh04jKBIWXDm4qiZap7qCHx3o9PW5hS2hmScm3HYZOkINADjvaFA92FJ8S28ylCUPUI/4/i8bqbUtQWovcysOlWAb5DlNRAI9w8Sn2yfgp6ZP328Vnw86yoZvXrDeEyQdB04t89/1O/w1cDnyilFU=';//這邊要改成你的 CHANNEL_ACCESS_TOKEN
  var msg= JSON.parse(e.postData.contents);

  //除錯用
  //Logger.log(msg);
  console.log(msg);

  //從接收到的訊息中取出 replayToken 和發送的訊息文字
  var replyToken = msg.events[0].replyToken;
  var userMessage = msg.events[0].message.text;
  var userid = msg.events[0].source.userId;

  if (typeof replyToken === 'undefined') {
     return;
  };

  //定義回傳訊息


  var userMessageNum = parseInt(userMessage); //parseInt 是可將字串轉換成整數的方式
  if (isNaN(parseInt(userMessage))) {//測試是不是數字
     if(userMessage.match("帶我去")){//測試是不是要開地圖
        var posotion = userMessage.replace("帶我去","");

        var mapResponse = Maps.newGeocoder().geocode(posotion);
        console.log(mapResponse);
        var returnmessage=[{
           "type": "location",
           "title": posotion,
           "address": mapResponse.results[0].formatted_address,
           "latitude": mapResponse.results[0].geometry.location.lat,
           "longitude": mapResponse.results[0].geometry.location.lng
         }]
     }else{

        var returnmessage=[{
           'type': 'text',
           'text': "我是中邊Bot"
        }];

     };

  }else{
     var returnmessage=[{
        'type': 'text',
         'text': parseInt(userMessageNum)*2
      }];
  };


  //回傳訊息給line 並傳送給使用者
  var url = 'https://api.line.me/v2/bot/message/reply';
  UrlFetchApp.fetch(url, {
        'headers': {
        'Content-Type': 'application/json; charset=UTF-8',
        'Authorization': 'Bearer ' + CHANNEL_ACCESS_TOKEN,
     },
      'method': 'post',
      'payload': JSON.stringify({
         'replyToken': replyToken,
         'messages': returnmessage,
     }),
  });
}

第一步驟_去line@後台找你的Channel access token,把上面程式碼中的access token 換掉

第二步驟_先開google script開新的專案,把code貼進去,然後發布

第三步驟_把webhook的網址設定指向發布後的網址,這樣就大功告成了

聽起來好像很簡單,但是這中間一定有很多問題跟不懂的地方,就請參考下面影片,有真實操作的畫面。在不懂就留言吧~

沒有留言:

張貼留言