A twitter feed is a great way to breath a little life into an otherwise static website. Check out the bottom right corner of my portfolio site as an example.

Update: Twitter upgraded their API to version 1.1. The code in this post no longer works, but you can reference the Twitter feed module that I wrote for SuperFeed to see how to use the new API. Also, I no longer have a twitter feed on my portfolio site.

link to this subheadingThe Code

So let’s get right to it. With C#, a little LINQ, and the excellent twitter API, something like this is relatively easy to do. Here’s the code (more or less) that I use on my website:

using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;

public class TweetLoader
{
const string ATOM_NAMESPACE = "http://www.w3.org/2005/Atom";
const string SCREEN_NAME = "lonekorean"; // TODO: your twitter name goes here
const int NUM_TWEETS = 5;
const int MAX_ATTEMPTS = 3;

public static List<string> LoadTweets()
{
XNamespace xmlns = ATOM_NAMESPACE;
XDocument doc = null;

// defensively attempt to get XML document
int attempts = 0;
while (attempts < MAX_ATTEMPTS &&
(doc == null || doc.ToString().Length == 0))
{
attempts++;
string url = string.Format(
"http://api.twitter.com/1/statuses/user_timeline.atom" +
"?screen_name={0}&count={1}", SCREEN_NAME, NUM_TWEETS);
try
{
doc = XDocument.Load(url);
}
catch
{
// pause half a second before retrying
System.Threading.Thread.Sleep(500);
}
}

List<string> tweets = new List<string>(NUM_TWEETS);
if (doc != null && doc.ToString().Length > 0)
{
// use linq to translate XML document into a list of strings
tweets = (
from item in doc.Descendants(xmlns + "entry")
select item.Element(xmlns + "title").Value
.Replace(SCREEN_NAME + ": ", "")
).ToList<string>();
}

return tweets;
}
}

link to this subheadingThe Walkthrough

First things first, you’ll want to change the screen name on line 8, and maybe the values on line 9 and 10 to your liking.

Line 19 sets up a while loop with a defensive try/catch block inside to retry the API request, just because the internet isn’t perfect and you never know when a request will fail. If the max number of attempts is reached without success, the final output will be null, so make sure your code can handle that.

Lines 23-25 are where the magic is. Feel free to test that URL directly in your browser. For more options, refer to the documentation.

Lines 41-45 use LINQ to pull out the actual strings that we want and package them into a tidy list. Oddly enough, every one of these strings is prepended with "lonekorean: " (or your screen name, obviously), so line 44 takes that out for us.

And that’s it. The one thing I got stuck on while coding this was the namespacing for Atom. Notice how I apply it on lines 42 and 43 with “xmlns +”. Just don’t forget that part and you’re golden.