linebotの実装を通じてGASの魅力を見る（画像送付機能）

# はじめに
GAS（Google Apps Script）を用いて簡易的なLINEBotの構築例を示す。

# 構成
今回は簡易的なLINEBotを作成するのにサーバやDBを用意するのは面倒ということでGASを採用した。スプレッドシートをDBとして使用することで等にサーバを用意することなく爆速でLINEBotの作成ができる。

![62F12B18-4397-47E3-B0DB-218725B38499.jpg](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/1532027/c3b3e68d-3449-f139-4210-879ddff6f880.jpeg)

# コード

```js:main.gs
var url = "" 
var folderId = ""
var ACCESS_TOKEN = ''

function myFunction() {
  createGraph();
}

function doPost(e){
  var replyToken = JSON.parse(e.postData.contents).events[0].replyToken;
  var userMessage = JSON.parse(e.postData.contents).events[0].message.text;
  var url = 'https://api.line.me/v2/bot/message/reply';

  var messageList = userMessage.split(/\r\n|\n/);
  var returnText = "該当する処理は存在しませんでした"
  if(messageList[0] == "write"){
    writeData(messageList)
    returnText = "書き込み完了"
  }else if(messageList[0] == "change"){
    changeData(messageList)
    returnText = "変更完了"
  }else if(messageList[0] == "graph"){
    createGraph(replyToken)
    returnText="not_message"
  }
  if(returnText != "not_message"){
  UrlFetchApp.fetch(url, {
  'headers': {
    'Content-Type': 'application/json; charset=UTF-8',
    'Authorization': 'Bearer ' + ACCESS_TOKEN,
  },
  'method': 'post',
  'payload': JSON.stringify({
    'replyToken': replyToken,
    'messages': [{
      'type': 'text',
      'text': returnText,
    }],
  }),
  });
  }

  return ContentService.createTextOutput(JSON.stringify({'content': 'post ok'})).setMimeType(ContentService.MimeType.JSON);

}
function changeData(messageList){
  var sheet = SpreadsheetApp.openByUrl(url).getSheetByName("")
  var lastRaw = sheet.getLastRow()
  for(var i=1;i < lastRaw+1;i++){
    if(messageList[1] == sheet.getRange(i,1).getValue()){
      Logger.log(sheet.getRange(i,1).getValue())
      sheet.getRange(i,2).setValue(messageList[2])
    }    
  }
}

function writeData(messageList){
  var sheet = SpreadsheetApp.openByUrl(url).getSheetByName("")
  var lastRaw = sheet.getLastRow()
  if(messageList[1] == "今日"){
    sheet.getRange(lastRaw + 1, 1).setValue(messageList[1])

  }
  sheet.getRange(lastRaw + 1, 1).setValue(messageList[1])
  sheet.getRange(lastRaw + 1, 2).setValue(messageList[2])
}

function createGraph(replyToken){
    var sheet = SpreadsheetApp.openByUrl(url).getSheetByName("")
    var range = sheet.getDataRange()
    var chart = sheet.newChart().addRange(range).setPosition(1,3,0,0).setChartType(Charts.ChartType.LINE).build()

    var today = Utilities.formatDate(new Date(),'Asia/Tokyo', 'YYYY-MM-dd')
    var graphImage = chart.getBlob()
    var folder = DriveApp.getFolderById(folderId)
    var file = folder.createFile(graphImage)
    file.setName(today)
    file.setSharing(DriveApp.Access.ANYONE, DriveApp.Permission.EDIT)
    sendGraph(replyToken, file.getDownloadUrl(),file.getDownloadUrl())
    DriveApp.getFolderById(folderId).removeFile(file)
}

function sendGraph(replyToken,src, srcPreview){
  var url = 'https://api.line.me/v2/bot/message/reply';


  var res = UrlFetchApp.fetch(url, {
  'headers': {
    'Content-Type': 'application/json; charset=UTF-8',
    'Authorization': 'Bearer ' + ACCESS_TOKEN,
  },
  'method': 'post',
  'payload': JSON.stringify({
    'replyToken': replyToken,
    'messages': [{
      'type': 'image',
      'originalContentUrl':src,
      'previewImageUrl':srcPreview
    }],
  }),
  });
}
```
# 動作例
![116546.jpg](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/1532027/e4de531c-4e03-6034-260c-bf3e5c5fde42.jpeg)

![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/1532027/bd7a2a29-b4f2-da92-24d4-0190cb94472a.png)

![116545.jpg](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/1532027/58497082-685c-b270-6d17-c90630639983.jpeg)
![116544.jpg](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/1532027/3ec897f1-0e12-db68-131c-f2163eaf85d4.jpeg)