06 September 2010

Show eBay Auctions in Google Apps Calendar

This is a great demonstration of how Google Apps Script makes some really useful things quite trivial to implement.

The following script uses the provided UrlFetchApp and XML parsing API to fetch and interpret an eBay sellers listings. It then uses the Calendar service to mark the events. The script is designed to run as a time-driven event. To avoid creating duplicate events, we make use of the CalendarEvent tagging feature.

So, here is the code:

function getFeedDoc() {
  var url = ScriptProperties.getProperty("feed_url");
  var feed_txt = UrlFetchApp.fetch(url).getContentText();
  var doc = Xml.parse(feed_txt, false);
  var items = doc.rss.channel.getElements("item");
  for (var i in items) {
    var endDateMs = items[i].getElement("urn:ebay:apis:eBLBaseComponents",
        "EndTime").getText();
    var endDate = new Date(parseInt(endDateMs));
    var guid = items[i].getElement("guid").getText();
    createEvent(endDate, items[i].getElement("title").getText(), guid);
  }
}
function createEvent(endDate, title, guid) {
  var cal_id = ScriptProperties.getProperty("cal_id");
  var cal = CalendarApp.getCalendarById(cal_id);
  var events = cal.getEventsForDay(endDate);
  for (var e in events) {
    if (events[e].getTag("guid") == guid) {
      return;
    }
  }
  cal.createEvent(title, endDate, endDate).setTag("guid", guid);
}

Create a new spreadsheet and open up the script editor. Copy and paste the code above. Make sure you set the following Script Properties

feed_url
URL of the RSS feed of the seller's items
cal_id
ID of the calendar that you wish to update

You will then need to set the trigger. Go to Triggers, Current script's triggers and add a new Time-driven trigger to run getFeedDoc() every hour or so.

Run the function getFeedDoc() to confirm that it works.