Last active
January 19, 2017 14:14
-
-
Save doug2k1/52a925bd76fd910ef2c5 to your computer and use it in GitHub Desktop.
Google Script to check Packt free book
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
The purpose of this script is to daily check Packt's Free Book offer | |
and notify via e-mail with the title of the book and link to download page | |
-> https://www.packtpub.com/packt/offers/free-learning | |
Author: Douglas Matoso - www.dmatoso.com | |
Instructions: | |
1) Create a new Google Script at http://script.google.com | |
2) Paste the code below, putting your email in the "email" var. | |
3) Execute the checkBook function to test (the script may ask an one time permission) | |
4) Check your mailbox. | |
5) If it's working, you can schedule it to run daily. | |
Click the clock icon (Project's current triggers) and add a new trigger with options: | |
Funcion: checkBook, Time-driven, Day timer, 7am to 8am (or choose a different time to receive the daily email) | |
*/ | |
function checkBook() { | |
var url = "https://www.packtpub.com/packt/offers/free-learning"; | |
var email = "[your e-mail here]"; | |
var page = UrlFetchApp.fetch(url); | |
var doc = Xml.parse(page, true); | |
var bodyHtml = doc.html.body.toXmlString(); | |
doc = XmlService.parse(bodyHtml); | |
var html = doc.getRootElement(); | |
var title = getElementsByClassName(html, 'dotd-title')[0].getChild('h2').getText(); | |
MailApp.sendEmail({ | |
to: email, | |
subject: "Packt Free Book", | |
htmlBody: "Title: " + title + "<br><br>" + url | |
}); | |
} | |
function getElementsByClassName(element, classToFind) { | |
var data = []; | |
var descendants = element.getDescendants(); | |
descendants.push(element); | |
for(i in descendants) { | |
var elt = descendants[i].asElement(); | |
if(elt != null) { | |
var classes = elt.getAttribute('class'); | |
if(classes != null) { | |
classes = classes.getValue(); | |
if(classes == classToFind) data.push(elt); | |
else { | |
classes = classes.split(' '); | |
for(j in classes) { | |
if(classes[j] == classToFind) { | |
data.push(elt); | |
break; | |
} | |
} | |
} | |
} | |
} | |
} | |
return data; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment