Skip to content

Instantly share code, notes, and snippets.

@petitviolet
Created May 26, 2021 14:50
Show Gist options
  • Save petitviolet/0316d0bf02d9e856c5e5b1151807574e to your computer and use it in GitHub Desktop.
Save petitviolet/0316d0bf02d9e856c5e5b1151807574e to your computer and use it in GitHub Desktop.
Subscribe a web page by GoogleAppScript
const URL = 'https://example.com';
const CELL = 'A1'
const MAIL_TO = 'mail@example.com';
// Create a trigger to run `main` periodically
function main() {
const sheet = SpreadsheetApp.getActiveSheet();
const lastDate = readLastDate(sheet);
const today = Utilities.formatDate(new Date(), 'UTC', 'yyyy-MM-dd');
if (lastDate === null || lastDate == today) {
return; // skip
}
const html = getHtmlContent(URL);
const date = extractLatestNewsDate(html);
if (lastDate == date) {
return;
}
writeLatestDate(sheet, date);
sendMail(date);
}
const getHtmlContent = (url) => {
var html = UrlFetchApp.fetch(url).getContentText('UTF-8');
return html;
};
const extractLatestNewsDate = (html) => {
const pattern = /<small>(\d{4}-\d{2}-\d{2})</small>/;
return html.match(pattern)[0];
};
const readLastDate = (sheet) => {
return sheet.getRange(CELL).getValue();
}
const writeLatestDate = (sheet, value) => {
sheet.getRange(CELL).setValue(value);
}
const sendMail = (date) => {
var subject = `Update from ${URL}`;
var name = "GAS robot";
var body = `<a href=${URL}>${URL}</a> updated at ${date}`;
MailApp.sendEmail({
to: MAIL_TO,
subject: subject,
name: name,
htmlBody: body,
body: body
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment