專題:試算表問答機器人
試算表問答機器人用 Google 試算表當資料庫:問答內容寫在試算表裡,店員或助教改表格就能更新 Bot 的回覆,不用碰程式。Bot 也會把每則訊息記錄到試算表,並讓使用者訂閱「每日提醒」,每天早上自動推播。這是 Apps Script 最擅長的應用,完成後就是一個可以實際給店家或社團使用的客服 Bot。
完整程式:examples/gas/sheets-bot/Code.gs
功能規劃
| 功能 | 說明 | 用到的技術 |
|---|---|---|
| 關鍵字問答 | 訊息包含「營業時間」就回覆營業時間 | 讀取「問答」工作表 |
| 訊息紀錄 | 每則訊息寫入時間、使用者、內容 | appendRow、取得使用者名稱 |
| 每日提醒 | 輸入「訂閱」後,每天 8 點推播 | Push API、時間驅動觸發條件 |
| Quick Reply | 回覆下方列出所有可問的關鍵字 | Quick Reply |
建立試算表與專案
- 建立一份新的 Google 試算表,命名為
LINE Bot 資料庫。 - 點 擴充功能 > Apps Script,會開啟一個和這份試算表綁在一起的專案。
- 依照 Echo Bot 的步驟 2,在專案設定加入指令碼屬性
CHANNEL_ACCESS_TOKEN。 - 把
程式碼.gs換成下方完整程式並儲存。
完整 程式碼.gs(點開)
/**
* 用 Google 試算表當資料庫的 LINE Bot:
* 1. 關鍵字問答:回覆內容寫在「問答」工作表,非工程師也能維護
* 2. 訊息紀錄:每則訊息寫進「紀錄」工作表
* 3. 每日提醒:輸入「訂閱」後,每天早上 push 一則訊息
*
* 這份程式要從試算表的「擴充功能 > Apps Script」建立(容器繫結指令碼)。
*/
const TOKEN = PropertiesService.getScriptProperties().getProperty('CHANNEL_ACCESS_TOKEN');
const SS = SpreadsheetApp.getActiveSpreadsheet();
/** 第一次使用時手動執行一次:建立三張工作表與範例資料 */
function setup() {
const sheets = {
'問答': [['關鍵字', '回覆'], ['營業時間', '週一至週五 09:00–18:00'], ['地址', '台北市信義區信義路五段 7 號'], ['電話', '02-1234-5678']],
'紀錄': [['時間', 'userId', '名稱', '訊息']],
'訂閱': [['userId', '名稱', '訂閱時間']],
};
Object.keys(sheets).forEach(function (name) {
const sheet = SS.getSheetByName(name) || SS.insertSheet(name);
if (sheet.getLastRow() === 0) {
const rows = sheets[name];
sheet.getRange(1, 1, rows.length, rows[0].length).setValues(rows);
sheet.setFrozenRows(1);
}
});
}
function doPost(e) {
const body = JSON.parse(e.postData.contents);
body.events.forEach(function (event) {
try {
handleEvent(event);
} catch (err) {
console.error(err); // 錯誤訊息可在 Apps Script「執行作業」頁面查看
}
});
return ContentService.createTextOutput('OK');
}
function handleEvent(event) {
if (event.type === 'follow') {
reply(event.replyToken, [textWithMenu('歡迎!可以問我:' + keywords().join('、'))]);
return;
}
if (event.type !== 'message' || event.message.type !== 'text') return;
const userId = event.source.userId;
const text = event.message.text.trim();
const name = getDisplayName(userId);
SS.getSheetByName('紀錄').appendRow([new Date(), userId, name, text]);
if (text === '訂閱') {
subscribe(userId, name);
reply(event.replyToken, [textWithMenu(name + ',已訂閱每日提醒 ⏰')]);
} else if (text === '取消訂閱') {
unsubscribe(userId);
reply(event.replyToken, [textWithMenu('已取消訂閱')]);
} else {
const answer = findAnswer(text);
reply(event.replyToken, [textWithMenu(answer || '找不到「' + text + '」的答案,可以問:' + keywords().join('、'))]);
}
}
/** 在「問答」工作表找關鍵字:訊息中包含關鍵字就回覆對應內容 */
function findAnswer(text) {
const rows = SS.getSheetByName('問答').getDataRange().getValues().slice(1);
const hit = rows.find(function (row) { return row[0] && text.indexOf(row[0]) !== -1; });
return hit ? String(hit[1]) : null;
}
function keywords() {
return SS.getSheetByName('問答').getDataRange().getValues().slice(1)
.map(function (row) { return row[0]; }).filter(String);
}
function subscribe(userId, name) {
const sheet = SS.getSheetByName('訂閱');
const ids = sheet.getDataRange().getValues().map(function (row) { return row[0]; });
if (ids.indexOf(userId) === -1) sheet.appendRow([userId, name, new Date()]);
}
function unsubscribe(userId) {
const sheet = SS.getSheetByName('訂閱');
const values = sheet.getDataRange().getValues();
for (let i = values.length - 1; i >= 1; i--) {
if (values[i][0] === userId) sheet.deleteRow(i + 1);
}
}
/** 由「時間驅動」觸發條件每天執行:push 訊息給所有訂閱者 */
function dailyReminder() {
const rows = SS.getSheetByName('訂閱').getDataRange().getValues().slice(1);
const today = Utilities.formatDate(new Date(), 'Asia/Taipei', 'M 月 d 日');
rows.forEach(function (row) {
push(row[0], [{ type: 'text', text: '早安 ' + row[1] + '!今天是 ' + today + ',記得喝水 💧' }]);
});
}
/** 執行一次即可建立每天早上 8 點的觸發條件(也可以在「觸發條件」頁面手動建立) */
function createDailyTrigger() {
ScriptApp.newTrigger('dailyReminder').timeBased().everyDays(1).atHour(8).inTimezone('Asia/Taipei').create();
}
/** ---------- LINE Messaging API ---------- */
function callLine(path, payload, method) {
const options = {
method: method || 'post',
headers: { Authorization: 'Bearer ' + TOKEN },
muteHttpExceptions: true, // 失敗時不丟例外,改由下面印出錯誤內容
};
if (payload) {
options.contentType = 'application/json';
options.payload = JSON.stringify(payload);
}
const res = UrlFetchApp.fetch('https://api.line.me/v2/bot' + path, options);
if (res.getResponseCode() >= 300) console.error(path, res.getResponseCode(), res.getContentText());
return res;
}
function reply(replyToken, messages) {
callLine('/message/reply', { replyToken: replyToken, messages: messages });
}
function push(to, messages) {
callLine('/message/push', { to: to, messages: messages });
}
function getDisplayName(userId) {
const res = callLine('/profile/' + userId, null, 'get');
return res.getResponseCode() === 200 ? JSON.parse(res.getContentText()).displayName : '朋友';
}
/** 文字訊息加上 Quick Reply 按鈕 */
function textWithMenu(text) {
const items = keywords().slice(0, 10).concat(['訂閱', '取消訂閱']).map(function (k) {
return { type: 'action', action: { type: 'message', label: String(k).slice(0, 20), text: String(k) } };
});
return { type: 'text', text: text, quickReply: { items: items } };
}
初始化工作表
setup() 會建立「問答」「紀錄」「訂閱」三張工作表並放入範例資料。在編輯器上方的函式選單選 setup,按 執行(第一次會要求授權,流程同 Echo Bot):
/** 第一次使用時手動執行一次:建立三張工作表與範例資料 */
function setup() {
const sheets = {
'問答': [['關鍵字', '回覆'], ['營業時間', '週一至週五 09:00–18:00'], ['地址', '台北市信義區信義路五段 7 號'], ['電話', '02-1234-5678']],
'紀錄': [['時間', 'userId', '名稱', '訊息']],
'訂閱': [['userId', '名稱', '訂閱時間']],
};
Object.keys(sheets).forEach(function (name) {
const sheet = SS.getSheetByName(name) || SS.insertSheet(name);
if (sheet.getLastRow() === 0) {
const rows = sheets[name];
sheet.getRange(1, 1, rows.length, rows[0].length).setValues(rows);
sheet.setFrozenRows(1);
}
});
}
回到試算表,會看到三張新工作表。之後要新增問答,直接在「問答」工作表加一列即可:
| 關鍵字 | 回覆 |
|---|---|
| 營業時間 | 週一至週五 09:00–18:00 |
| 地址 | 台北市信義區信義路五段 7 號 |
| 電話 | 02-1234-5678 |
| 停車 | 附近有信義廣場停車場(自行新增的範例) |
處理事件
doPost 把每個事件交給 handleEvent,並用 try...catch 包起來,確保某個事件出錯時不影響其他事件,也一定會回應 LINE:
function doPost(e) {
const body = JSON.parse(e.postData.contents);
body.events.forEach(function (event) {
try {
handleEvent(event);
} catch (err) {
console.error(err); // 錯誤訊息可在 Apps Script「執行作業」頁面查看
}
});
return ContentService.createTextOutput('OK');
}
function handleEvent(event) {
if (event.type === 'follow') {
reply(event.replyToken, [textWithMenu('歡迎!可以問我:' + keywords().join('、'))]);
return;
}
if (event.type !== 'message' || event.message.type !== 'text') return;
const userId = event.source.userId;
const text = event.message.text.trim();
const name = getDisplayName(userId);
SS.getSheetByName('紀錄').appendRow([new Date(), userId, name, text]);
if (text === '訂閱') {
subscribe(userId, name);
reply(event.replyToken, [textWithMenu(name + ',已訂閱每日提醒 ⏰')]);
} else if (text === '取消訂閱') {
unsubscribe(userId);
reply(event.replyToken, [textWithMenu('已取消訂閱')]);
} else {
const answer = findAnswer(text);
reply(event.replyToken, [textWithMenu(answer || '找不到「' + text + '」的答案,可以問:' + keywords().join('、'))]);
}
}
讀寫試算表
getDataRange().getValues() 一次把整張表讀成二維陣列,slice(1) 去掉標題列。問答比對用「訊息中包含關鍵字」,所以「請問營業時間?」也能對到「營業時間」:
/** 在「問答」工作表找關鍵字:訊息中包含關鍵字就回覆對應內容 */
function findAnswer(text) {
const rows = SS.getSheetByName('問答').getDataRange().getValues().slice(1);
const hit = rows.find(function (row) { return row[0] && text.indexOf(row[0]) !== -1; });
return hit ? String(hit[1]) : null;
}
function keywords() {
return SS.getSheetByName('問答').getDataRange().getValues().slice(1)
.map(function (row) { return row[0]; }).filter(String);
}
function subscribe(userId, name) {
const sheet = SS.getSheetByName('訂閱');
const ids = sheet.getDataRange().getValues().map(function (row) { return row[0]; });
if (ids.indexOf(userId) === -1) sheet.appendRow([userId, name, new Date()]);
}
function unsubscribe(userId) {
const sheet = SS.getSheetByName('訂閱');
const values = sheet.getDataRange().getValues();
for (let i = values.length - 1; i >= 1; i--) {
if (values[i][0] === userId) sheet.deleteRow(i + 1);
}
}
呼叫 LINE API
Apps Script 沒有 LINE SDK,直接用 UrlFetchApp 呼叫 REST API。callLine() 統一加上授權 header,並在失敗時把錯誤印到「執行作業」紀錄:
/** ---------- LINE Messaging API ---------- */
function callLine(path, payload, method) {
const options = {
method: method || 'post',
headers: { Authorization: 'Bearer ' + TOKEN },
muteHttpExceptions: true, // 失敗時不丟例外,改由下面印出錯誤內容
};
if (payload) {
options.contentType = 'application/json';
options.payload = JSON.stringify(payload);
}
const res = UrlFetchApp.fetch('https://api.line.me/v2/bot' + path, options);
if (res.getResponseCode() >= 300) console.error(path, res.getResponseCode(), res.getContentText());
return res;
}
function reply(replyToken, messages) {
callLine('/message/reply', { replyToken: replyToken, messages: messages });
}
function push(to, messages) {
callLine('/message/push', { to: to, messages: messages });
}
function getDisplayName(userId) {
const res = callLine('/profile/' + userId, null, 'get');
return res.getResponseCode() === 200 ? JSON.parse(res.getContentText()).displayName : '朋友';
}
/** 文字訊息加上 Quick Reply 按鈕 */
function textWithMenu(text) {
const items = keywords().slice(0, 10).concat(['訂閱', '取消訂閱']).map(function (k) {
return { type: 'action', action: { type: 'message', label: String(k).slice(0, 20), text: String(k) } };
});
return { type: 'text', text: text, quickReply: { items: items } };
}
Quick Reply 最多 13 個按鈕,按鈕文字(label)最多 20 個字,所以程式取前 10 個關鍵字並截斷文字。
定時推播提醒
dailyReminder() 讀取「訂閱」工作表,對每位訂閱者呼叫 Push API。用時間驅動觸發條件讓它每天自動執行:
/** 由「時間驅動」觸發條件每天執行:push 訊息給所有訂閱者 */
function dailyReminder() {
const rows = SS.getSheetByName('訂閱').getDataRange().getValues().slice(1);
const today = Utilities.formatDate(new Date(), 'Asia/Taipei', 'M 月 d 日');
rows.forEach(function (row) {
push(row[0], [{ type: 'text', text: '早安 ' + row[1] + '!今天是 ' + today + ',記得喝水 💧' }]);
});
}
/** 執行一次即可建立每天早上 8 點的觸發條件(也可以在「觸發條件」頁面手動建立) */
function createDailyTrigger() {
ScriptApp.newTrigger('dailyReminder').timeBased().everyDays(1).atHour(8).inTimezone('Asia/Taipei').create();
}
建立觸發條件(二擇一):
- 在函式選單選 createDailyTrigger 執行一次。
- 或點左側鬧鐘圖示 觸發條件 > 新增觸發條件:函式選
dailyReminder、活動來源選「時間驅動」、類型選「日計時器」、時段選「上午 8 點到 9 點」。
Push 會計入訊息則數
每推播給一位訂閱者就算一則訊息。訂閱人數多時要注意官方帳號方案的每月則數上限,見 Reply 與 Push。
部署與測試
- 部署 > 新增部署作業 > 網頁應用程式,執行身分「我」、存取權「所有人」。
- 把網址貼到 LINE Developers Console 的 Webhook URL。
- 用手機測試:
- 傳「營業時間」「請問地址」→ 回覆試算表裡的內容
- 傳「訂閱」→ 「訂閱」工作表多一列
- 在編輯器手動執行
dailyReminder→ 手機收到推播 - 回到試算表看「紀錄」工作表,每則訊息都被記下來
之後修改程式記得用 管理部署作業 > 編輯 > 新版本 更新(見 Echo Bot);只改試算表內容則不用重新部署。
延伸挑戰
- 回覆圖片或 Flex:在「問答」工作表加一欄「類型」,依類型回覆文字、圖片或 Flex Message(Flex 寫法見 Flex Message)。
- 活動報名:搭配 LIFF 表單,把報名資料寫進新的工作表。
- 群組公告:把 Bot 加進群組,用
event.source.groupId推播到群組。