Website Monitor with Google Docs

The following Google Apps Script monitors website domains and will send SMS text alerts when any of these sites are down or inaccessible.


/*

   Website Monitor HD by Digital Inspiration   
   =========================================  

*/

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); 
}

/*

   Published by Amit Agarwal on 09/14/2012    

*/