Getting the current Twitter-buzz with C#

My problem
I want to know what my friends on Twitter are talking about most


What’s the plan:

  1. Get the tweets from my friends
  2. Search this tweets for the #hashtags (Regex!!!)
  3. Count the hashtags
  4. Output the hashtags ordered by count

With tools like VS, .net framework and Twitter API this is EASY!!

1. How to get the tweets

a) Twitter API

Find all info here 
Currently Twitter has 2 APIs, maybe they make things easier and bring these together…

b) Tweetsharp

Tweetsharp is an awesome fluent interface for the Twitter API.
It’s toooo easy!!!! Make sure you check it out

c) Twitter "low level"

You can consume Twitter stuff via standard HTTP calls and get the response as XML or JSON, see this blog for an example
That’s tooo hard :-)


I picked Tweetsharp, because there are so many samples available, and it is fluent!  I love Intellisense!

  1. Download tweetsharp
  2. Unzip to your References Solution folder
  3. Add reference to your project
  4. Done

How easy is that!


Make sure to use a Console project, we want to focus on functionality not on UI


The code to get the list of tweets looks like this

           var twitter = FluentTwitter.CreateRequest().AuthenticateAs(MyUser, MyPass) 

           // Get response from Twitter
           var response = twitter.Request();

           // Convert response to data classes
           var tweets = response.AsStatuses();


Next step

Iterate through tweets and search for the hashtags
We use a Regex for that

private static Regex regexHashTags = new Regex(@"#\w*", RegexOptions.IgnoreCase);

No more code, because that’s up to you how to do that


Put this hashtags into dictionary

Dictionary<string, int> 

(string is the hashtag, int is the count)
Easy, so no code here


Sort the Dictionary with LINQ

var sortedDict = (from entry in hashtagCountDict orderby entry.Value descending select entry);


The final output is easy again

Iterate through the sorted dictionary and throw it to the Console

Figure: Output of current Twitter buzz. Sharepoint is big currently (13/05/2009)
because of the TechEd announcements of Sharepoint 2010


Advanced steps

  1. Get the tweet updates every couple of seconds
  2. Use a   while (abortKeyNotPressed) {   }  with a Thread.Sleep to get the buzz every 1 minute
  3. Use Console KeyAvailable to abort application
  4. Use the space key to get the current state of the iteration
  5. Serialize current dictionary to file, and load that at startup
    Continue from last time


Thanks Robert Mühsig for VERY useful input

1 comment:

Peter Gfader said...

From workmate Justin: for global hasttag trends

Post a Comment

Latest Posts

Popular Posts