Created
June 25, 2020 17:06
-
-
Save waseriin/8437267375257364cb94d35086964523 to your computer and use it in GitHub Desktop.
Example implementation of webhook on Google Apps Script for LINE Simple Beacon with LINE Messaging API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const ACCESS_TOKEN = PropertiesService.getScriptProperties().getProperty('ACCESS_TOKEN'); | |
const urlBase = 'https://api.line.me/v2/bot/'; | |
const myId = PropertiesService.getScriptProperties().getProperty('MY_ID'); | |
function doPost(e) { | |
const replyToken = JSON.parse(e.postData.contents).events[0].replyToken; | |
const beaconType = JSON.parse(e.postData.contents).events[0].beacon.type; | |
const userId = JSON.parse(e.postData.contents).events[0].source.userId; | |
const replyUrl = urlBase + 'message/reply'; | |
const displayName = getDisplayName(userId); | |
myMessage = displayName + 'さんが' + beaconType + 'しました'; | |
pushMessage(myId, myMessage); | |
UrlFetchApp.fetch(replyUrl, { | |
'headers': { | |
'Content-Type': 'application/json; charset=UTF-8', | |
'Authorization': 'Bearer ' + ACCESS_TOKEN, | |
}, | |
'method': 'post', | |
'payload': JSON.stringify({ | |
'replyToken': replyToken, | |
'messages': [{ | |
'type': 'text', | |
'text': displayName + 'さんが' + beaconType + 'しました', | |
}], | |
}), | |
}); | |
return ContentService.createTextOutput(JSON.stringify({'content': 'post ok'})).setMimeType(ContentService.MimeType.JSON); | |
} | |
function getUserProfile(userId) { | |
const profileUrl = urlBase + 'profile/' + userId; | |
let response = UrlFetchApp.fetch(profileUrl, { | |
'headers': { | |
'Authorization': 'Bearer ' + ACCESS_TOKEN, | |
}, | |
'method': 'get', | |
}); | |
return response.getContentText(); | |
} | |
function getDisplayName(userId) { | |
const userProfile = JSON.parse(getUserProfile(userId)); | |
return userProfile.displayName; | |
} | |
function pushMessage(userId, message){ | |
const pushUrl = urlBase + 'message/push'; | |
UrlFetchApp.fetch(pushUrl, { | |
'headers': { | |
'Content-Type': 'application/json; charset=UTF-8', | |
'Authorization': 'Bearer ' + ACCESS_TOKEN, | |
}, | |
'method': 'post', | |
'payload': JSON.stringify({ | |
'to': userId, | |
'messages':[{ | |
'type': 'text', | |
'text': message, | |
}] | |
}), | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment