はじめに
GAS(Google Apps Script)を用いて簡易的なLINEBotの構築例を示す。
構成
今回は簡易的なLINEBotを作成するのにサーバやDBを用意するのは面倒ということでGASを採用した。スプレッドシートをDBとして使用することで等にサーバを用意することなく爆速でLINEBotの作成ができる。
コード
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
}],
}),
});
}