跳到主要内容

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 廣告