如何快速將服務從 Line Notify 轉換至 Line 官方帳號及 Messaging API
Line Notify 在十月初宣佈 【LINE Notify結束服務公告】,將於 2025年3月31日停止服務,還給了半年的緩衝期,不幸的,因為 Line Notify 很好用加上又是免費,不止公司,連我自己都有一堆小服務是用 Line Notify 來做告警,從上面 Line 官方連結寫的「關於發送通知的替代方法 ,建議可考慮操作Messaging API 透過LINE官方帳號來傳送訊息」,只好花點時間,把原來 Line Notify 的程式用 Messaging API 改寫,簡單寫個筆記紀錄
原 Line Notify 程式
會看這篇文章的,應該都是原 Line Notify 的用戶,對 Line Notify 就不多做介紹了,有興趣可以看舊文:【Line Notify 測試筆記】,然後同樣用 Google Apps Script 來做測試,先來看一下舊程式,詳細內容也可以參考舊文:【Google Apps Script 測試筆記,實作監控網站發送 Line Notify】
/**
* 發送 Line Notify 訊息
*/
function sendLineNotify(lineToken, message) {
let lineUrl = 'https://notify-api.line.me/api/notify';
let option = {
method: 'post',
headers: { Authorization: 'Bearer ' + lineToken },
payload: {
message: message
}
};
UrlFetchApp.fetch(lineUrl, option);
}
從這個程式來看,程式很簡單,只需要取得 line notify 的 token (權杖) 就可以了
改寫後的 Messaging API
也不難,直接貼程式碼
/**
* Messaging API 發送訊息到 Line 群組
*/
function sendLineGroupMsg(accessToken, groupId, messageText) {
const lineUrl = 'https://api.line.me/v2/bot/message/push';
const headers = {
'Content-Type': 'application/json',
'Authorization': `Bearer ${accessToken}`
};
const messageData = {
to: groupId,
messages: [
{
type: "text",
text: messageText
}
]
};
let option = {
method: 'post',
headers: headers,
payload: JSON.stringify(messageData)
};
UrlFetchApp.fetch(lineUrl, option);
}
注意一下,這支程式是傳送訊息到「群組」的,如果是要傳到個人的話,請改成 userId 即可,程式其實是一樣的
然後他和原來 Line Notify 的差別主要是它需要兩個參數:accessToken 和 groupId,所以基本上只要知道這兩個參數該怎麼找到,把 function 換掉就完工了
Channel Access Token
請參考【Line Bot Messaging API 測試筆記】這篇文章,需要先註冊 Line 官方帳號,然後到 Line Developers 就能取得該官方帳號的 channel access token 了
Group ID / User ID
這個比較麻煩一點,用過 Line 官方帳號的人應該知道官方帳號是看不到會員名單的(我還是不理解他們的理由),所以就需要從 webhook 的程式著手,同樣參考【Line Bot Messaging API 測試筆記】這篇文章,我們先把原來的程式增加一行 log
// event handler
function handleEvent(event) {
console.log(event);
}
基本上只要有什麼動作,就可以看到這一行印出訊息
將官方帳號加入好友會看到
{
type: 'follow',
webhookEventId: '',
deliveryContext: { isRedelivery: false },
timestamp: 1730174569813,
source: { type: 'user', userId: '使用者ID' },
replyToken: '',
mode: 'active'
}
將官方帳號邀請到群組會看到
{
type: 'join',
webhookEventId: '',
deliveryContext: { isRedelivery: false },
timestamp: 1730174437255,
source: { type: 'group', groupId: '群組ID' },
replyToken: '',
mode: 'active'
}
手動的記錄一下 userId 和 groupId 或寫支程式去 parser json 就可以取得資料,發送訊息給個人或群組了
其他設定
請到 Line 官方帳號,在帳號設定將加入群組或多人聊天室改成「接受邀請」,要不然是沒有辦法將官方帳號邀請到群組的
結論
Line Messaging API 要完全取代 Line Notify 看起來應該是沒有問題,轉換過程還算順利,主要的差別就只有費用,Line Notify 是免費服務,Messaging API 的免費額度則只有 200則/月,再來就要付費了,不過使用者付費其實還算合理啦,如果真的還是要找免費服務,大概就只能換 Telegram 或 Discord 了,但我沒打算試就是