Website Monitor with Google Scripts
Use Google Apps Script to monitors website domains and send SMS text alerts when any of these sites are down or inaccessible.
function init() {
if (ScriptApp.getScriptTriggers().length == 0) {
// Set up a monitor that triggers every 5 minutes
ScriptApp.newTrigger('websiteMonitor').timeBased().everyMinutes(5).create();
}
}
function websiteMonitor() {
var response, error, code, urls;
// The script can monitor multiple website URLs (comma separated)
urls = SpreadsheetApp.getActiveSheet().getRange('B2').getValue();
urls = urls.replace(/\s/g, '').split(',');
for (var i = 0; i < urls.length; i++) {
var url = urls[i];
if (!ScriptProperties.getProperty(url)) {
ScriptProperties.setProperty(url, 200);
}
// Trying to connect to the website URL
try {
response = UrlFetchApp.fetch(url);
} catch (error) {
// If URLFetchApp fails, the site is probably down
updateLog(url, -1);
continue;
}
code = response.getResponseCode();
updateLog(url, code);
}
}
function updateLog(url, code) {
if (ScriptProperties.getProperty(url) == code) return;
ScriptProperties.setProperty(url, code);
var sheet = SpreadsheetApp.getActiveSheet();
var row = sheet.getLastRow() + 1;
var time = new Date();
var msg = 'Down';
if (code == 200) msg = 'Up';
msg = 'Website is ' + msg + ' ' + url;
sheet.getRange(row, 1).setValue(time);
sheet.getRange(row, 2).setValue(msg);
// Send an email notification when the site status changes
var email = sheet.getRange('B3').getValue();
MailApp.sendEmail(email, msg, url);
var now = new Date(time.getTime() + 10000);
// Create an event in Google Calendar with an SMS reminder
if (sheet.getRange('B4').getValue().toLowerCase() == 'yes') CalendarApp.createEvent(msg, now, now).addSmsReminder(0);
}
Amit Agarwal
Google Developer Expert, Google Cloud Champion
Amit Agarwal is a Google Developer Expert in Google Workspace and Google Apps Script. He holds an engineering degree in Computer Science (I.I.T.) and is the first professional blogger in India.
Amit has developed several popular Google add-ons including Mail Merge for Gmail and Document Studio. Read more on Lifehacker and YourStory