Skip to content

Instantly share code, notes, and snippets.

@vanpariyar
Created January 12, 2023 11:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vanpariyar/f93005461d259ed57bb252988e9789f8 to your computer and use it in GitHub Desktop.
Save vanpariyar/f93005461d259ed57bb252988e9789f8 to your computer and use it in GitHub Desktop.
Google App script for the website monitor and updates via slack or email

Google App script for the website monitor and updates via slack or email

  • Customizable as per needed
function init(){
  const urls = [
    "URL_1",
    "URL_2",
  ];

  let statusResponse = [];
  var payloadText = ":compass: Today’s status is *here* \n";
  for( let urlCounter = 0; urlCounter < urls.length ; urlCounter++ ){
    statusResponse[urlCounter] = checkWebsiteStatus(urls[urlCounter]);
    payloadText += `:computer: *Domain*: ${ statusResponse[urlCounter].url } \n :stopwatch: *Load Time*: ${statusResponse[urlCounter].loadTimeMs}Mili Seconds \n :electric_plug: *Status Code*: ${statusResponse[urlCounter].responseCode} \n \n`;
  } 
  
  var payload = {
    "channel" : "#slackbot-test",
    "username" : "Site Analysis",
    "icon_url" : "https://puu.sh/BQqA9/408cadc2b3.png",
    "text" : "Here’s an Analysis of the production Websites",
    "attachments": [{
      "text": payloadText,
      "footer": "<https://test.link|edit script>",
      "mrkdwn_in": ["text"]
    }]
  }

  const webhook = "SLACK_WEB_HOOK"; //Paste your webhook URL here
  var options = {
    "method": "post", 
    "contentType": "application/json", 
    "muteHttpExceptions": true, 
    "payload": JSON.stringify(payload) 
  };
  
  try {
    UrlFetchApp.fetch(webhook, options);
  } catch(e) {
    Logger.log(e);
  }

  // Send email notification if 
  // if(response.getResponseCode() != 200) {
  //   let email = "EMAIL_ID";
  //   let subject = "[ACTION REQUIRED] Website may be down - " + new Date();
  //   let body = `The URL ${url} may be down. Expected response code 200 but got ${responseCode} instead.`;
  //   MailApp.sendEmail(email, subject,body);
  // }
}

function checkWebsiteStatus( urlString ) {
  let url = urlString;

  // Record time so we can track how long the website
  // takes to load.
  let start = new Date();
  let response = UrlFetchApp.fetch(url, {muteHttpExceptions: true});
  let end = new Date();

  let responseCode = response.getResponseCode();
  let loadTimeMs = end - start;

  // Record a log of the website's status to the spreadsheet.
  SpreadsheetApp.getActive().getSheetByName("Data").appendRow([url, start, responseCode, loadTimeMs]);

  return {
    url,
    responseCode,
    loadTimeMs,
  }
  
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment