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);
}
📮  Subscribe to our Email Newsletter for Google tips and tutorials!
Published in: Google Apps Script - RSS - Twitter

Looking for something? Find here!

Meet the Author

Web Geek, Google Developer Expert
A
Amit Agarwal

Amit Agarwal is a Google Developer Expert in Google Workspace and Google Apps Script. He holds an engineering degree in Computer Science (I.I.T.) and is the first professional blogger in India. He is the developer of Mail Merge for Gmail and Document Studio. Read more on Lifehacker and YourStory

Get in touch

Google Add-ons

Do more with your Gmail and GSuite account
G

We build bespoke solutions that use the capabilities and the features of Google Workspace for automating business processes and driving work productivity.

  1. Mail Merge with Attachments
    Send personalized email to your Google Contact with a Google Sheet and Gmail
  2. Save Emails and Attachments
    Download email messages and file attachments from Gmail to your Google Drive
  3. Google Forms Email Notifications
    Send email notifications to multiple people when a new Google Form is submitted
  4. Document Studio
    Create beautiful pixel perfect documents merging data from Google Sheets and Google Forms
  5. Creator Studio for Google Slides
    Turn your Google Slides presentations into animated GIFs and videos for uploading to YouTube