Saturday, May 15, 2010

New Twitter Code

I know I just posted a twitter code, but since then I decided to have twitterfeed blast my blog posts to my twitter and my Facebook. However, this posed a problem when the twitter feed on the blog was being filled with tweets about blog posts :)

To combat this problem we had to change how the feed worked. Originally we pulled from the user_timeline stream found at however we had no control over this. Switching to the search API, we lose the ability to see the post of the person whom I was replying to. Although we do not much care since this new code also removes @reply's from the list. After all, we only want 'broadcast' tweets, not individual replies.

Now, there is a drawback because the filtering of @replies is done in javascript, so if we got a whole page of @replies, nothing will show in the feed. I am still looking into this. For now, to combat this, we will load 15 tweets from twitter, and stop when we have parsed 5 that are not @replies.

First off, instead of calling the user_timeline feed noted above, we are calling a custom search pattern:

To explain:
  • from=zefie (We only want tweets zefie sent)
  • nots=New Blog Entry (We do not want any tweets containing all 3 of these words, since this is how twitterfeed prefixes a new post
  • rpp=15 (15 tweets)
  • callback=twitterCallback (run our callback instead of Twitter's twitterCallback2 in blogger.js
  • result_type=recent (Sort by date, not popularity)

function removeEntities(string) {
   return string.replace(/</g,'<').replace(/>/g,'>').replace(/"/g,'"').replace(/&/,'&');
function twitterCallback(results) {
  var statusHTML = [];
  var max = 5;
  var j = 0;
  var tweets = results.results;
  for (var i=0; i<tweets.length; i++){
    if (j == max) {
    var username = tweets[i].from_user;
    var source = tweets[i].source;
    var status = tweets[i].text.replace(/((https?|s?ftp|ssh)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g, function(url) {
      return ''+url+'';
    }).replace(/\B@([_a-z0-9]+)/ig, function(reply) {
      return  reply.charAt(0)+''+reply.substring(1)+'';
    }).replace(/\B#([_a-z0-9]+)/ig, function(hashtag) {
      return ''+hashtag+'';

    if (tweets[i].to_user == null) {
  • '+username+' '+status+'
    '+relative_time(tweets[i].created_at)+' via '+removeEntities(source)+'
  • '); } } document.getElementById('twitter_update_list').innerHTML = statusHTML.join(''); }

    No comments:

    Post a Comment