Google Scripts Polling

Google Scripts polling for blog

by jessekinsman

JavaScript

var alertAddress = "[email protected]";
var pollSheetId = "1ApEnSqTVfrod_duxWWiAM4TeOyT3EodbWu3EAO3U7nI";

function pollFunction(url) {
  var resCode = 0;
  var res;
  try {
    res = UrlFetchApp.fetch(url, {muteHttpExceptions: true});
    if (res) {
      resCode = res.getResponseCode();
    }
  } catch(error) {
    resCode = 404;
    Logger.log("Error " + error);
  }
  return resCode;
}

function startPolling() {
  var urls = [
    {url: "http://flowride.kinsmancreative.com", code: 200, errorAction: "email", successAction: "log"},
    {url: "http://www.kinsmancreative.com", code: 200, errorAction: "email", successAction: "log"},
    {url: "http://www.kinsmancreative.com/states", code: 200, errorAction: "email", successAction: "log"}
  ];
  for (var i = 0; i<urls.length; i+=1) {
    if (urls[i].hasOwnProperty("url") && urls[i].url !== "") {
      var res = pollFunction(urls[i].url);
      handleResponse(res, urls[i]);
    }
  }
}

function handleResponse(res, obj) {
  var dt = Utilities.formatDate(new Date(), "PST", "yyyy-MM-dd' 'hh:mm:ss a");
  if (res == obj.code) {
    Logger.log("URL: " + obj.url + " returned 200 on " + dt);
    writeToSheet([obj.url, res, dt], "log");
  } else {
    if (obj.errorAction == "email") {
      Logger.log("Sending mail alert for: " + obj.url + " returned " + res + " on " + dt);
      sendMailAlert(obj, res, dt);
      writeToSheet([obj.url, res, dt], "errors");
    } else if (obj.errorAction == "log") {
      Logger.log("URL: " + obj.url + " returned " + res + " on " + dt);
      writeToSheet([obj.url, res, dt], "errors");
    }
  }
}

function sendMailAlert(obj, res, date){
    var message = {}, text;
      text = "<p><strong>ALERT</strong></p>";
      text += "<p>The following url <a href='" + obj.url + "'>" + obj.url + "</a> returned the following code " + res + " on " + date + "</p>";
      message = {
        to: alertAddress,
        from: "[email protected]",
        subject: "Poll server alert!",
       ...