Wednesday, July 3, 2013

List tweets on you site with Linq2Twitter

Now that Twitter API 1 has been closed I found Linq2Twitter and used it in a small project that needed to list tweets from an account with a custom design and it worked great and was easy to setup.

  1. Add a reference to the linq2twitter dll in your project
  2. Create an application at Twitter
  3. Copy the ConsumerKey and ConsumerSecret and inset it into the code example below
  4. Replace the SCREEN_NAME_TO_FILTER_ON with the screen name you want to list tweets from (or do another type of search)
  5. Run the code to see all the tweets
var auth = new ApplicationOnlyAuthorizer
{
  Credentials = new InMemoryCredentials
  {
    ConsumerKey = YOUR_CONSUMER_KEY,
    ConsumerSecret = YOUR_CONSUMER_SECRET
  }
};
auth.Authorize();
var context = new TwitterContext(auth);
var tweets = context.Status.Where(tweet => tweet.ScreenName == SCREEN_NAME_TO_FILTER_ON && tweet.Type == StatusType.User).Take(4);
The tweet text is just plain text with no links for hash tags or other stuff but you can use this code to format the tweet,
protected string FormatTweet(Status status)
{
  var entities = new List<EntityBase>();
  entities.AddRange(status.Entities.HashTagEntities);
  entities.AddRange(status.Entities.UrlEntities);
  entities.AddRange(status.Entities.UserMentionEntities);
  entities = entities.OrderByDescending(item => item.Start).ToList();
  var linkedText = status.Text;
  foreach (var entity in entities)
  {
    if (entity is HashTagEntity)
    {
      var tagEntity = (HashTagEntity)entity;
      linkedText = string.Format(
          "{0}<a href=\"http://twitter.com/search?q=%23{1}\">{1}</a>{2}",
          linkedText.Substring(0, entity.Start),
          tagEntity.Tag,
          linkedText.Substring(entity.End));
    }
    else if (entity is UserMentionEntity)
    {
      var mentionEntity = (UserMentionEntity)entity;

      linkedText = string.Format(
          "{0}<a href=\"http://twitter.com/{1}\">@{1}</a>{2}",
          linkedText.Substring(0, entity.Start),
          mentionEntity.ScreenName,
          linkedText.Substring(entity.End));
    }
    else if (entity is UrlEntity)
    {
      var urlEntity = (UrlEntity)entity;
      linkedText = string.Format(
          "{0}<a href=\"{1}\">{1}</a>{2}",
          linkedText.Substring(0, entity.Start),
          urlEntity.Url,
          linkedText.Substring(entity.End));
    }
  }
  return linkedText;
}