下期第16堂[雲端服務機器人] Line機器人-讀取資料
提供資料的機器人應用很常見,是應用的最大宗。
但查詢資料比插入資料要多一些心思,今天我們就練習建立一個情報機器人,
下面影片是提供快篩診所的查詢,同學可以換成其他有興趣的資料。
程式
var CHANNEL_ACCESS_TOKEN = "";
var spreadSheetUrl = ""; //試算表網址
var sheetName = "data"; //工作表名稱
var searchColumn = 2; //搜尋第幾欄的資料
var spreadSheet = SpreadsheetApp.openByUrl(spreadSheetUrl);
var sheet = spreadSheet.getSheetByName(sheetName);
var lastRow = sheet.getLastRow(); //最後一筆
var lastColumn = sheet.getLastColumn(); //最後一欄
var sheetData = sheet.getSheetValues(1, 1, lastRow, lastColumn);
function doPost(e) {
var userData = JSON.parse(e.postData.contents);
var searchResult = [];
var replyMessage = [];
var replyContent;
var replyToken = userData.events[0].replyToken;
var searchContent = userData.events[0].message.text; //搜尋內容
if (userData.events[0].type != "message") {
return;
}
if (userData.events[0].message.type != "text") {
return;
}
searchResult = sheetData.filter(function(item, index, array){
return item[searchColumn - 1].toString() == searchContent; //搜尋嚴格度
});
for (var i = 0; i < searchResult.length; i++) {
replyContent = sheetData[0][0] + ":" + searchResult[i][0];
for (var j = 1; j < lastColumn; j++) {
replyContent += "\n\n" + sheetData[0][j] + ":" + searchResult[i][j];
}
replyMessage.push({type:"text", text:replyContent}); //加進陣列裡面
if (replyMessage.length == 3) { //最多三筆資料
break;
}
}
if (replyMessage.length == 0) {
replyMessage.push({type:"text", text:"查詢不到「" + searchContent + "」的資料"});
}
sendReplyMessage(CHANNEL_ACCESS_TOKEN, replyToken, replyMessage);
}
//傳送訊息
function sendReplyMessage(CHANNEL_ACCESS_TOKEN, replyToken, replyMessage) {
var url = "https://api.line.me/v2/bot/message/reply";
UrlFetchApp.fetch(url, {
"headers": {
"Content-Type": "application/json; charset=UTF-8",
"Authorization": "Bearer " + CHANNEL_ACCESS_TOKEN,
},
"method": "post",
"payload": JSON.stringify({
"replyToken": replyToken,
"messages": replyMessage,
}),
});
}
今天沒有小挑戰,直接做期末成品
有問題直接開麥克風問