星期二, 9月 02, 2025

[GAS] LineBot 回覆訊息

透過 LineBot 回應使用者送出訊息,該筆記很單純把使用者輸入文字加上 From GAS 字樣回應給使用者,主要流程是把 .gs Code 部屬為網頁應用程式取得 url 後,再進入 Line Developer 去啟用和設定 LineBot webhook,.gs Code 內解析 LineBot 透過 POST 送進來的 json 資料

When an event occurs, such as when a user adds your LINE Official Account as a friend or sends a message, the LINE Platform sends an HTTPS POST request to the webhook URL (bot server).  

.gs Code

解析 LineBot 送出來的 json 資料,可以取得使用者輸入文字和 Reply Token,根據 Send reply message 說明,Reply Toekn 有下列限制
  • 只能使用一次
  • 有效時間限制,取得後要盡快使用
也可以取得 UseID 或 GroupID 等資訊,詳見 Webhook Event Objects
function doPost(e) {

  // 從 PropertiesService 取出 LineChannelAccessToken
  let scriptProperties = PropertiesService.getScriptProperties();
  let properties = scriptProperties.getProperties();
  let lineBotChannelAccessToken = properties["LineChannelAccessToken"];

  // 從 Line 聊天室取得的內容
  let contents = JSON.parse(e.postData.contents);
  // 取出 replayToken 才知道要將訊息推還給誰
  let replyToken = contents.events[0].replyToken;
  // 取出使用者發送的文字訊息
  let text = contents.events[0].message.text;

  let payload = {
    replyToken: replyToken,
    messages: [
      {
        "type": "text",
        "text": text + " ( From GAS )"
      }
    ]
  };

  let options = {
    headers: { Authorization: "Bearer " + lineBotChannelAccessToken },
    contentType: "application/json",
    method: "post",
    payload: JSON.stringify(payload)
  };

  let url = "https://api.line.me/v2/bot/message/reply";
  UrlFetchApp.fetch(url, options);
}

部屬為網頁應用程式
Line Developer 上啟用 Webhook

LineBot => Messaging API settings 內啟用 Webhook

測試結果

把 LineBot 加入好友或是群組內,傳遞訊息後就會自動回覆啦

沒有留言:

張貼留言