Embed Twitter with RSS Feeds

E
Published in: Google Apps Script - RSS - Twitter

You use widgets in Twitter for embedding Twitter timelines into your website and this Google Script will convert those widgets into RSS format. Thus you will be able to subscribe to Twitter RSS Feeds in IFTTT, Feedly, or another RSS Reader.

function getTweets(id) {

  try {

    var widget, json, tweets, regex, tweet, list, time, url, when, rss, heading, title, link;

    title = "Twitter RSS Feed :: " + id;
    link  = "http://www.labnol.org/#" + id;

    // This the ID of your Twitter widget
    url   = "http://cdn.syndication.twimg.com/widgets/timelines/" + id;

    widget  = UrlFetchApp.fetch(url);
    json    = Utilities.jsonParse(widget);

    // If the Twitter widget doesn't exist, do nothing
    if ( ! json.body ) {
      return;
    }

    // Remove all whitespaces from the Twitter's JSON response
    tweets  = json.body.replace(/\s+/g, ' ');

    // Get the Feed Title and URL from the response heading (H1)
    regex = new RegExp(/<h1[^>]*>(.*?)<\/h1>/ig);

    if ((heading = regex.exec(tweets)) !== null) {

      regex = RegExp(/href="(.*?)"/ig);
      link = regex.exec(heading[1])[1];

      regex = RegExp(/title="(.*?)"/ig);
      if ((title = regex.exec(heading[1])) !== null) {
        title = title[1];
      }
    }

    rss  = '<?xml version="1.0"?><rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">';
    rss += ' <channel><title>' + title + '</title>';
    rss += ' <link>' + link + '</link>';
    rss += ' <atom:link href="http://www.labnol.org/#' + id + '" rel="self" type="application/rss+xml" />';
    rss += ' <description>' + title + ' :: RSS Feed for Twitter widget #' + id + ' generated by Google Scripts.</description>';

    regex = RegExp(/<ol[^>]*>(.*?)<\/ol>/ig);

    if ((list = regex.exec(tweets)) !== null) {

      // Remove all the extra classes, DIV tags, SPAN tags from the tweets.
      list = list[1].replace(/<div class=\"(header|footer|detail-expander|retweet-credit)[^>]*>(.*?)<\/div>/gi, "")
      .replace(/<time[^>]*>(.*?)<\/time>/gi, "")
      .replace(/data-tweet-id=".*?"|class=".*?"|rel=".*?"|title=".*?"|target=".*?"|data-expanded-url=".*?"|data-query-source=".*?"|dir=".*?"|data-pre-embedded=".*?"/gi, "");

      regex = RegExp(/<li[^>]*>(.*?)<\/li>/ig);

      while ((tweets = regex.exec(list)) !== null) {

        tweet = tweets[1].replace(/&nbsp;/g, ' ').replace(/\s+/g, ' ')
        .replace(/<\s*(div|span|b|p)[^>]*>/gi, "")
        .replace(/<\s*\/\s*(div|span|b|p)[^>]*>/gi, "");

        // Extract the Date and Time of the tweet
        time = RegExp(/<a\s+href="(.*)"\s+data-datetime="(.*)"\s*><\/a>/gi);

        if ((time = time.exec(tweet)) !== null) {

          url = time[1];
          when = time[2];
          tweet = tweet.replace(/<a[^>]*>\s*<\/a>/gi, "");

          rss += "<item>";
          rss += " <title>" + url.split("/")[3] + ": " + tweet + "</title>";
          rss += " <pubDate>" + when.replace('T', ' ') + "</pubDate>";
          rss += " <guid>" + url + "</guid>";
          rss += " <link>" + url + "</link>";
          rss += " <description>" + tweet + "</description>";
          rss += "</item>";
        }
      }
    }

    rss += "</channel></rss>";
    return rss;

  } catch (e) {
    Logger.log(e.toString());
  }
}

function doGet(e) {

  var cache = CacheService.getPublicCache();
  var id = "twitter" + e.queryString;
  var rss = cache.get(id);

  if ( ! rss ) {
    rss = getTweets(e.queryString);
    cache.put(id, rss, 120); // Expire RSS Feed in 2 minutes
  }

  // Use the HTML Service in Google Apps Script to serve Twitter RSS Feeds
  return ContentService.createTextOutput(rss)
    .setMimeType(ContentService.MimeType.RSS);
}
Published in: Google Apps Script - RSS - Twitter

Looking for something? Find here!

Meet the Author

Web Geek, Tech Columnist
A
Amit Agarwal

Amit Agarwal is a Google Developer Expert in GSuite and Google Apps Script. He holds an engineering degree in Computer Science (I.I.T.) and is the first professional blogger in India. Read more on Lifehacker and YourStory

Get in touch