Using the Twitter API
December 11, 2012 1 Comment
As part of my alerting project, I wanted to implement a Twitter push. I first googled on Bing and got this post. I made a quick implementation of my IAlert Interface like so:
public void Send() { HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(_twitterUri); request.Credentials = new NetworkCredential(_twitterUserId, _twitterPassword); request.Timeout = 5000; request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; using (Stream requestStream = request.GetRequestStream()) { using (StreamWriter streamWriter = new StreamWriter(requestStream)) { streamWriter.Write(_message); } } WebResponse response = request.GetResponse(); }
However, I get a 401
it looks like it is an old implementation of the Twitter API. I then went to this page and it looks like I can’t do basic HTTP authentication with Twitter – I have to use OAuth. Twitter’s help page recommended using the C# Twitterizer library. I went ahead and and installed it from NuGet
I then re-wrote the send method to use the Twitterizer:
public void Send() { OAuthTokens tokens = new OAuthTokens(); tokens.ConsumerKey = _consumerKey; tokens.ConsumerSecret = _consumerSecret; tokens.AccessToken = _accessToken; tokens.AccessTokenSecret = _accessTokenSecret; TwitterResponse<TwitterStatus> tweetResponse = TwitterStatus.Update(tokens, _message); }
Alas, when I re-ran my unit tests
Ugh – I guess I need to add a reference to my test project. Sure enough, that did the trick:
Now I am getting this message back from Twitter
I then when to my account settings for the app on Twitter and changed it from Read only to full control:
Hit save, regenerated the keys, and still got the same message
I then stumbled onto this. I then restarted, changed the text of my integration test and voila (that’s French for “Whoop-de-do")
Spot on with this write-up, I actually think this
website needs a lot more attention. I’ll probably be back again to see more, thanks for the advice!