LineBot第七堂課
4/20 2022
類別:程式教學
LineBot更多元的回覆功能
1、回覆文字
{
"type": "text",
"text": "輸入回覆文字"
}
2、回覆圖片
{
"type": "image",
"originalContentUrl": "圖片網址",
"previewImageUrl": "預覽圖片網址"
}
3、回覆影片
{
"type": "video",
"originalContentUrl": "影片網址",
"previewImageUrl": "預覽圖片網址"
}
4、回覆貼圖
{
"type": "sticker",
"packageId": "貼圖的packageId",
"stickerId": "貼圖的stickerId"
}
貼圖的packageId和stickerId可參考右方的網址: 貼圖Id查詢
5、回覆確認按鈕
{
"type": "template",
"altText": "this is a confirm template",
"template": {
"type": "confirm,
"actions": [
{
"type": "message",
"label": "是",
"text": "是"
},
{
"type": "message",
"label": "否",
"text": "否"
}
],
"text": "您確定嗎?"
}
}
6、回覆選擇按鈕
{
"type": "template",
"altText": "this is a buttons template",
"template": {
"type": "buttons",
"title": "按鈕標題",
"text": "按鈕敘述文字",
"actions": [
{
"type": "message",
"label": "動作一",
"text": "動作 1"
},
{
"type": "message",
"label": "動作二",
"text": "動作 2"
}]
}
}
撰寫Google apps script
我們由六堂課的程式碼作範本進行講解及修改
var channel_access_token = "你的LineBot的token"
var ss = SpreadsheetApp.openById("你的試算表ID"); //試算表ID
var sheet = ss.getSheetByName("工作表1"); //要讀取工作列的名稱
var data = sheet.getRange(2,2); //存對話資料的儲存格 (2,1)表示為試算表的A2
function doPost(e) {
var posted_json = JSON.parse(e.postData.contents);
var events = posted_json.events;
events.forEach(function(event) {
ME=event.source.userId; //使用者的userId
if(event.message.type == "text"){
data.setValue(event.message.text);
Utilities.sleep(1000);
//延遲1秒後再執行之後的程式,為的是讓試算表來的及翻譯
var reply = sheet.getRange(2,4).getValue();
push_message(ME,reply);
}
});
};
//下面是po訊息的函數
function push_message(to,msg) {
var postData = {
"to": to,
"messages": [{
"type": "text",
"text": msg,
}]
};
var url = "https://api.line.me/v2/bot/message/push";
var headers = {
"Content-Type": "application/json",
'Authorization': 'Bearer ' + channel_access_token,
};
var options = {
"method": "post",
"headers": headers,
"payload": JSON.stringify(postData)
};
var response = UrlFetchApp.fetch(url, options);
}