Skip to content

Instantly share code, notes, and snippets.

@nullifye
Last active March 20, 2023 00:24
Show Gist options
  • Save nullifye/2f1c50fe186eb14df5236dc4faccdccb to your computer and use it in GitHub Desktop.
Save nullifye/2f1c50fe186eb14df5236dc4faccdccb to your computer and use it in GitHub Desktop.
Google App Script / Telegram bot / Notify if web is inaccessible / Run every 4 hours
const TOKEN = "YOUR-BOT-TOKEN";
let telegramUrl = "https://api.telegram.org/bot" + TOKEN;
// Telegram send message
function tgNotify(txt, to) {
let url = telegramUrl + "/sendMessage?parse_mode=Markdown&disable_web_page_preview=true&chat_id=" + to + "&text=" + txt;
let response = UrlFetchApp.fetch(url);
//Logger.log(response.getContentText());
}
// Add custom menu
function onOpen() {
let ui = SpreadsheetApp.getUi();
ui.createMenu('Extras')
.addItem('Check website(s)', 'checkWebsite')
.addToUi();
}
// This will run the script every 4 hours
function setCheckWebsiteAvailability() {
ScriptApp.newTrigger('checkWebsite').timeBased().everyHours(4).create();
}
// Check if the website is available
function checkWebsite() {
// Get the active spreadsheet
let sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
// Get the range of website URLs and response status
let dataRange = sheet.getDataRange();
let values = dataRange.getValues();
// Loop through each row in the range
for (var i = 1; i < values.length; i++) {
let row = values[i];
let websiteUrl = row[0];
try {
// Use the UrlFetchApp service to fetch the website
let response = UrlFetchApp.fetch(websiteUrl,{ muteHttpExceptions: true });
var responseCode = response.getResponseCode();
}
catch (e) {
//Logger.log(e);
responseCode = 504;
}
// If the response code is greater than or equals to 400, the website is down
if (responseCode >= 400) {
// Notify
let txt = "⚠️ " + row[0] + " is *inaccessible*!";
tgNotify(txt, row[3]);
}
// Update the response status in the spreadsheet
sheet.getRange(i+1, 2).setValue(responseCode);
const now = new Date();
sheet.getRange(i+1, 3).setValue(now);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment