2018年4月6日 星期五

Google Apps Script 入門到進階(18) --- Google 雲端硬碟傳送圖片到 Line Notify

發送本機圖片訊息到 Line Notify 已經沒什麼技術可言了,不過如果要發送 Google 雲端硬碟的圖片就需要再花一點功夫,文章 LINE Notify 入門到進階應用(6) --- 傳送本機圖片Line Notify 提到如何發送圖片,一樣的原理套用到雲端上。
將這張家扶娃娃圖片放置 Google 雲端硬碟作為發送至 Line Notify 的操作圖片。

雲端硬碟。

輸入以下 Script 程式碼並執行。
function snedImagetoLineNotify() { 
  var image = "2018家扶娃娃.jpg";
  var imagename = "2018家扶娃娃";
  var LINE_ACCESS_TOKEN = "你的Token";
  
  //指定圖片名稱
  var image = DriveApp.getFilesByName(image).next();
  
  //取得圖片ID
  var id = image.getId();   
  
  //取得圖片所有資訊
  var blob = DriveApp.getFileById(id).getBlob();
 
  //間格字串
  var boundary = "iInfo";
 
  //組合傳送內容
  var requestBody = Utilities.newBlob(
      "--" + boundary + "\r\n"
      + "Content-Disposition: form-data; name=\"message\"; \r\n\r\n" + imagename + "\r\n"
      + "--" + boundary + "\r\n"
      + "Content-Disposition: form-data; name=\"imageFile\"; filename=\"" + blob.getName() + "\"\r\n"
      + "Content-Type: " + "image/png" +"\r\n\r\n").getBytes();

  requestBody = requestBody.concat(blob.getBytes());
  requestBody = requestBody.concat(Utilities.newBlob("\r\n--" + boundary + "--\r\n").getBytes());
  
  //發送至Line Notify
  var options = {
    method: "post",
    contentType: "multipart/form-data; boundary=" + boundary,
    payload: requestBody,    
    headers : {"Authorization" : "Bearer " + LINE_ACCESS_TOKEN},
    muteHttpExceptions: true
  };
  var response = UrlFetchApp.fetch("https://notify-api.line.me/api/notify", options);

  Logger.log(response.getContentText());
}
執行結果:
參考資料: