5
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

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

Last updated at Posted at 2021-05-24

はじめに

GAS(Google Apps Script)を用いて簡易的なLINEBotの構築例を示す。

構成

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

62F12B18-4397-47E3-B0DB-218725B38499.jpg

コード

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

image.png

116545.jpg
116544.jpg

5
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?