I tried to make line chatbot that can setting up an event and notify the user at the setting date with the code down below:
function doPost(e) {
const data = JSON.parse(e.postData.contents).events[0];
const lineUserId = data.source.userId;
const replyToken= data.replyToken;
const postMsg = data.message.text;
if(typeof replyToken === 'undefined') {
return;
}
const cache = CacheService.getScriptCache();
let type = cache.get("type");
if(type === null) {
if(postMsg === 'add event') {
cache.put('type', 1);
reply(replyToken, 'Please add an event description');
} else if(postMsg === 'delete event'){
cache.put('type', 3);
reply(replyToken, 'Please select an event to delete')
} else if(postMsg === 'event list'){
reply(replyToken, showEventsList());
} else {
reply(replyToken, 'โปรดเลือกพิมพ์คำสั่งที่คุณต้องการ \n[add event]\n[delete event]\n[event list]');
}
} else {
if(postMsg === 'cancel') {
cache.remove('type');
reply(replyToken, 'cancel event adding');
return;
}
switch(type) {
case '1':
cache.put('type', 2);
cache.put('name', postMsg);
reply(replyToken, 'ตัวอย่างการเพิ่มวันเกิด ให้พิมพ์รูปแบบนี้ [1996/12/20] \n ถ้าไม่ต้องการแสดงปีเกิด ให้กรอกแค่ เดือน และ วันที่');
break;
case '2':
if(postMsg.match(dateExp || dateExpYear)) {
cache.put('date', postMsg);
addBirthday(cache.get('name'), cache.get('date'), lineUserId);
reply(replyToken, `${cache.get('name')} วันเกิด ${cache.get('date')} บันทึกวันเกิดแล้ว`);
cache.remove('type');
cache.remove('name');
cache.remove('date');
break;
} else {
reply(replyToken, 'ป้อนข้อมูลให้ถูกต้อง ทำการพิมพ์ "ยกเลิก" เพื่อดำเนินการเข้าข้อมูลใหม่');
break;
}
case '3':
if(checkName(postMsg) !== -1) {
deleteBirthday(checkName(postMsg));
reply(replyToken, `${postMsg} ได้ทำการลบวันเกิดของเขาแล้ว`);
cache.remove('type');
break;
} else {
reply(replyToken, `${postMsg} ไม่มีวันเกิดคนนี้ในระบบ`);
cache.remove('type');
break;
}
}
}
}
function addBirthday(name, date, lineUserId) {
const sheet = SpreadsheetApp.openById(SHEET_ID).getSheetByName(SHEET_NAME);
const splitedDate = date.split('/');
let year, month, day;
if(splitedDate.length === 3) {
year = splitedDate[0];
month = splitedDate[1];
day = splitedDate[2];
sheet.appendRow([name, year, month, day, lineUserId]);
} else {
year = '';
month = splitedDate[0];
day = splitedDate[1];
sheet.appendRow([name, year, month, day, lineUserId]);
}
};
function checkName(name) {
const sheet = SpreadsheetApp.openById(SHEET_ID).getSheetByName(SHEET_NAME);
const values = sheet.getDataRange().getValues();
const nameList = [];
let nameIndex = -1;
for(let i = 0; i < values.length; i++) {
nameList.push(values[i][0]);
}
nameList.forEach((e, i )=> {
if(e == name) {
nameIndex = i;
return;
}
return;
});
return nameIndex;
}
function deleteBirthday(rowNumber) {
const sheet = SpreadsheetApp.openById(SHEET_ID).getSheetByName(SHEET_NAME);
sheet.deleteRows(rowNumber + 1);
}
function showBirthdaysList() {
const sheet = SpreadsheetApp.openById(SHEET_ID).getSheetByName(SHEET_NAME);
const values = sheet.getDataRange().getValues();
const ranges = sheet.getRange(2, 1, values.length - 1, 4).getValues();
const dataList = ranges.reduce((list, item) => {
if(item[1] === '') {
return `${list}\n${item[0]} : ${item[2]}/${item[3]}`;
} else {
return `${list}\n${item[0]} : ${item[1]}/${item[2]}/${item[3]}`;
}
}, 'รายชื่อ : วันเกิด');
return dataList;
}
function reply(replyToken, message) {
UrlFetchApp.fetch(URL, {
'headers': {
'Content-Type': 'application/json; charset=UTF-8',
'Authorization': 'Bearer ' + CHANNEL_ACCESS_TOKEN,
},
'method': 'post',
'payload': JSON.stringify({
'replyToken': replyToken,
'messages': [{
'type': 'text',
'text': message,
}],
}),
});
return ContentService.createTextOutput(JSON.stringify({'content': 'post ok'})).setMimeType(ContentService.MimeType.JSON);
}
function pushMessage() {
const sheet = SpreadsheetApp.openById(SHEET_ID).getSheetByName(SHEET_NAME);
const index = findUser();
if(index === -1) {
return;
}
const person = sheet.getRange(index + 1, 1).getValue();
const to = sheet.getRange(index + 1, 5).getValue();
const year = new Date().getFullYear();
let theYear = sheet.getRange(index + 1, 2).getValue();
let message = "วันนี้คุณ ";
let age;
if(theYear) {
age = year - theYear;
message += `${person} อายุ ${age} เป็นวันเกิดวันนี้!`;
} else {
message += `${person} เป็นวันเกิดวันนี้!`;
}
return push(message, to);
}
function findUser() {
const sheet = SpreadsheetApp.openById(SHEET_ID).getSheetByName(SHEET_NAME);
const values = sheet.getDataRange().getValues();
const birthdaysList = values.map( row => {
return `${row[2]}/${row[3]}`;
});
const today = new Date();
const hour = today.getHours();
const month = today.getMonth();
const date = today.getDate();
const theDay = `${month + 1}/${date}`;
const BirthdayIndex = birthdaysList.findIndex((el) => el == theDay );
return BirthdayIndex;
}
function push(message, to) {
var url = "https://api.line.me/v2/bot/message/push";
var headers = {
"Content-Type" : "application/json; charset=UTF-8",
'Authorization': 'Bearer ' + CHANNEL_ACCESS_TOKEN,
};
var postData = {
"to" : to,
"messages" : [{
"type": "flex",
"altText": "HBD",
"contents":{
"type": "bubble",
"hero": {
"type": "image",
"url": "https://i.pinimg.com/564x/6b/04/fe/6b04fe0cb4e70165f24a94c9dfb146f6.jpg",
"size": "full",
"aspectRatio": "20:13",
"aspectMode": "cover"
},
"body": {
"type": "box",
"layout": "vertical",
"contents": [
{
"type": "text",
"text": message,
"weight": "bold",
"size": "xl",
"wrap": true
}
]
}
}
}],
};
var options = {
"method" : "post",
"headers" : headers,
"payload" : JSON.stringify(postData)
};
return UrlFetchApp.fetch(url, options);
}
However, there are some information that cannot be provided here.
And when I tried to add webhook to line message api, it response like a picture down below: appeared error message
I coded that script in google script.
Is there any way to fix it?
I expected that the script is able to connect with line message api.