Skip to content

Instantly share code, notes, and snippets.

@printminion
Created October 14, 2017 08:39
Show Gist options
  • Save printminion/f36ff357c633bfd7579f3f299f147494 to your computer and use it in GitHub Desktop.
Save printminion/f36ff357c633bfd7579f3f299f147494 to your computer and use it in GitHub Desktop.
Apps Script for testing site content and sending email
/** Apps Script for testing site content and sending email **/
function isSiteContainsString()
{
// Get the URL of the Website to monitor
var url = SpreadsheetApp.getActiveSheet().getRange("E2").getValue();
var stringToSearch = SpreadsheetApp.getActiveSheet().getRange("F2").getValue();
// HTTP Response Code of the last server request
if (!ScriptProperties.getProperty("status")) {
//ScriptProperties.setProperty("status", 200);
}
var response, error;
try {
// Fetch the web page using UrlFetchApp
response = UrlFetchApp.fetch(url);
} catch(error)
{
insertData(error, -1, "[dvlottery]Website down");
return;
}
var code = response.getResponseCode();
// code = 200 means the fetch request was successful
if (code == 200) {
var content = response.getContentText();
if (content.search(stringToSearch) == 0) {
insertData("Up", code, "[dvlottery]Website up! Gogogogoo!", content);
} else {
insertData("Down", code, "[dvlottery]Down", content, true);
}
} else {
insertData(response.getContent()[0], code, "[dvlottery]Website down");
}
}
function insertData(error, code, msg, content, dontSendMail) {
// Ignore if the error message is logged already
//if (ScriptProperties.getProperty("status") == code)
//return;
// Log the server error in a Google Sheet
var sheet = SpreadsheetApp.getActiveSheet();
var email = sheet.getRange("G2").getValue();
var row = sheet.getLastRow() + 1;
sheet.getRange(row,1).setValue(new Date());
sheet.getRange(row,2).setValue(error);
sheet.getRange(row,3).setValue(code);
// Send an email alert for the downtime
ScriptProperties.setProperty("status", code);
if (dontSendMail) {
return;
}
MailApp.sendEmail(
{
to: email,
subject: msg,
htmlBody: error + content
}
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment