跳至主要内容

Google Apps Script 測試筆記,實作監控網站發送 Line Notify

· 5 分鐘閱讀
Eric Cheng

之前測試了一下 Line Notify,見前文【Line Notify 測試筆記】,思考了一下有什麼能夠實際運用的地方,於是想到拿來做為發送網站如果不小心掛點後的告警通知,原來想用 AWS Lambda 來寫,後來不小心看 Google 也有類似的免費服務 Google Apps Script,測試了一下,簡單做個筆記

什麼是 Google Apps Script

Google Apps Script是一種基於雲的腳本語言,允許你自動化和擴展Google Workspace(包括Gmail、Calendar、Drive、Sheets、Docs等)以及其他Google服務的功能。它提供了一種簡單的方式來進行自動化處理、集成外部API和創建自定義函數、菜單和擴展功能,無需安裝任何軟體。

以上是 ChatGPT4 說的,不過這篇文章沒那麼複雜,也沒要連動 Google 的其他服務,只要是用 Line Notify 發個告警而已

測試執行 Google Apps Script

首先先連到網址:Google Apps Script

如果之前沒使用過的話,可以先開個新專案,之後會看到像這樣的畫面

google-app-script 1

在 Google Apps Script 程式碼用的是 gs,但體感上和 javascript 很像,在 javascript 能跑的語法大致上都能用

簡單寫了兩個 function ,會發現下拉式選單可選擇要執行哪一個

google-app-script 2

點選執行後,可以看到執行結果

google-app-script 3

監控網站發送 Line Notify 程式碼

簡單寫了支程式如下

/**
* 排程
*/
function doMonitorCrontab() {
let lineToken = '您的 line token';
let monitors = [
'https://havocfuture.tw',
'https://tech.havocfuture.tw'
]
doMonitor(monitors,lineToken);
}

/**
* 執行監控網站
*/
function doMonitor(monitors, lineToken) {
for(var i = 0, len = monitors.length; i < len; i++) {
let monitorRes = monitorUrl(monitors[i]);
if (monitorRes.status !== 'success') {
sendLineNotify(lineToken, monitorRes.msg);
}
}
}

/**
* 監控網站 URL
*/
function monitorUrl(url) {
let res = {status: 'none', msg: ''};
try {
let fetchUrlCode = UrlFetchApp.fetch(url).getResponseCode();
if (fetchUrlCode !== 200) {
res = {status: 'fail', msg: url + '\n回應碼異常:' + fetchUrlCode};
} else {
res = {status: 'success', msg: ''};
}
} catch (e) {
res = {status: 'fail', msg: url + '\n異常:' + e};
}
console.log('[' + res.status + ']', url, res.msg);
return res;
}

/**
* 發送 Line Notify 訊息
*/
function sendLineNotify(lineToken, message) {
let option = {
method: 'post',
headers: { Authorization: 'Bearer ' + lineToken },
payload: {
message: message
}
};
UrlFetchApp.fetch('https://notify-api.line.me/api/notify', option);
}

程式很簡單,大致說明如下

  • function sendLineNotify 負責放送 Line Notify,當然首先需要有 Line Token,如何取得 Line Token 可以參考之前的文章:【Line Notify 測試筆記
  • UrlFetchApp.fetch 在 GAS 上直接就可以使用,不用再 import 其他的 library
  • 在 function doMonitorCrontab 填入 lineToken 和要監控的網站 URL Array 後,點選執行就可以看到結果,如果網站有 exception 或回傳碼不是 200,就可以在 Line 的群組收到告警通知

在 Google Apps Script 設立排程

在左側 menu 的「觸發條件」,點選「新增觸發條件」

google-app-script 4

填寫排程內容,以下設定為每小時執行一次 doMonitorCrontab 這個 function

google-app-script 5

執行後就可以看到結果了

google-app-script 6

結論是 Google Apps Script 是好東西,相當簡單也相當實用,至於如何連動處理 Google 其他服務的資料就改天再研究了



版權聲明


這是 google 廣告