Last active
September 16, 2021 21:41
-
-
Save agektmr/10260540 to your computer and use it in GitHub Desktop.
This script will fetch an Atom feed and insert rows on top in descending order. Make sure to replace with arbitrary URLs on 2 placeholders.
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
function main() { | |
var ss = SpreadsheetApp.openByUrl('YOUR SPREADSHEET URL COMES HERE'); | |
var sheet = ss.getSheets()[0]; | |
var property = PropertiesService.getDocumentProperties(); | |
var last_update = property.getProperty('last_update'); | |
last_update = last_update === null ? 0 : parseFloat(last_update); | |
var feed = fetch('ATOM FEED URL COMES HERE'); | |
var items = getItems(feed); | |
var i = items.length - 1; | |
while (i > -1) { | |
var item = items[i--]; | |
var date = new Date(item.getChildText('pubDate')); | |
if (date.getTime() > last_update) { | |
insertRow(item, sheet); | |
} | |
} | |
property.setProperty('last_update', date.getTime()); | |
} | |
function fetch(url) { | |
var feed = UrlFetchApp.fetch(url).getContentText(); | |
return feed; | |
} | |
function getItems(feed) { | |
var doc = XmlService.parse(feed); | |
var root = doc.getRootElement(); | |
var channel = root.getChild('channel'); | |
var items = channel.getChildren('item'); | |
return items; | |
} | |
function insertRow(item, sheet) { | |
var title = item.getChildText('title'); | |
var url = item.getChildText('link'); | |
var author = item.getChildText('author'); | |
var date = new Date(item.getChildText('pubDate')); | |
sheet.insertRowBefore(2); | |
sheet.getRange('B2:E2').setValues([[title, url, author, date.toLocaleString()]]); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
FYI - I would suggest
getScriptProperties()
rather thangetDocumentProperties()
as the latter could be null https://developers.google.com/apps-script/reference/properties/properties-service#getDocumentProperties() (I ran into this myself when trying to implement your script)