Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save agektmr/10260540 to your computer and use it in GitHub Desktop.
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.
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()]]);
}
@derekantrican
Copy link

derekantrican commented Sep 16, 2021

FYI - I would suggest getScriptProperties() rather than getDocumentProperties() 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)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment