開發 Line 機器人最重要的就是寫 web hook
那 webhook 就必須找個 server 來存放
可以免費放 webhook 的有 MS Azure, Amazon, Google Cloud... 等服務商
這些都要另外註冊帳號、設定 server 、可能還有期限流量等限制
用 google script 不須經過這些設定
就能直接編寫接收 line 訊息並回傳的機器人
以下範例為取得聊天室 ID 或 UserID
只要取得這些 ID 就能發送 push 訊息到這些 ID 的聊天視窗了
第一次要取得當下聊天視窗的ID
可以用reply的方式回應到當下的視窗
reply不需要輸入userID或groupID就能回傳到當下聊天視窗的ID
那 webhook 就必須找個 server 來存放
可以免費放 webhook 的有 MS Azure, Amazon, Google Cloud... 等服務商
這些都要另外註冊帳號、設定 server 、可能還有期限流量等限制
用 google script 不須經過這些設定
就能直接編寫接收 line 訊息並回傳的機器人
以下範例為取得聊天室 ID 或 UserID
只要取得這些 ID 就能發送 push 訊息到這些 ID 的聊天視窗了
function doPost(e) {
var urlReply = 'https://api.line.me/v2/bot/message/reply';
var urlPush = 'https://api.line.me/v2/bot/message/push';
var myGroup = 'XXXXXXX'; // push 訊息到這個 ID
var send_message = 'doPost message';
var strSourceType = "";
var strNewRoomID = "";
var strNewGroupID = "";
var strNewUserID = "";
var recieveData= JSON.parse(e.postData.contents);
if (recieveData.events[0].type == "join")
{
if ( recieveData.events[0].source.type == "room" )
{
strSourceType = "room";
strNewRoomID = recieveData.events[0].source.roomId;
strNewUserID = recieveData.events[0].source.userId;
}
else if ( recieveData.events[0].source.type == "group" )
{
strSourceType = "group";
strNewGroupID = recieveData.events[0].source.groupId;
strNewUserID = recieveData.events[0].source.userId;
}
else if ( recieveData.events[0].source.type == "user" )
{
strSourceType = "user";
strNewUserID = recieveData.events[0].source.userId;
}
send_message = "SourceType:" + strSourceType;
send_message = send_message + " RoomID:" + strNewRoomID;
send_message = send_message + " GroupID:" + strNewGroupID;
send_message = send_message + " UserID:" + strNewUserID;
UrlFetchApp.fetch(urlPush, {
'headers': {
'Content-Type': 'application/json; charset=UTF-8',
'Authorization': 'Bearer ' + CHANNEL_ACCESS_TOKEN,
},
'method': 'post',
'payload': JSON.stringify({
'to': myGroup,
'messages': [{
'type': 'text',
'text': send_message,
}],
}),
});
}
}
第一次要取得當下聊天視窗的ID
可以用reply的方式回應到當下的視窗
reply不需要輸入userID或groupID就能回傳到當下聊天視窗的ID
UrlFetchApp.fetch(urlReply, {
'headers': {
'Content-Type': 'application/json; charset=UTF-8',
'Authorization': 'Bearer ' + CHANNEL_ACCESS_TOKEN,
},
'method': 'post',
'payload': JSON.stringify({
'messages': [{
'type': 'text',
'text': send_message,
}],
}),
});
0 意見