NOV
12
Connecting to the twitter API with C#
5
Using the Hammock library for restful API calls, from a clienside point of view, for idiots. Full OAuth stuff.
I recently had the dubious pleasure of having an idea. That idea was to code a twitter bot using C#. At the start of this project (about 5 days prior to writing this) I had no real experience of C#. I have used JAVA before and a smattering of C# for very simple ASP.net sites, with PHP and javascript being my home turf. However I like C# so away I went, I decided to write it as a console app because it wouldn’t really have any user interaction and was just going to be a scheduled task.
I’m basically writing this because I had trouble understanding a lot of the things written about how to go about creating such an app. The first problem was that 99% of material was written for web applications. There’s a subtle but important difference between the 2 and it made finding the relevant information difficult. The two resources that helped me most were:
byatool.com
And.. I can’t remember the other one but it had a reddish favicon.
Anyway, if you read the first one you can see the writer decided to use the hammock library for connection to RESTful web services, the hammock library is cool so I used it too.
Hammock library
I’m writing this as a complete noob for complete noobs, so whilst it may be a case of blind leading the blind, at least you have some semblance of direction to follow.
I’m using visual studio 2010, I guess this is the same in older versions but to create project variables that are stored for use whenever the program starts you go to Project>Properties>Settings. I set up the tokens I was going to be using for Open Authentication thing that that the twitter API uses.
You access and set these variables in the code with Properties.Settings.Default.{variablename}. When you create your new twitter app as defined in the first link you’re given 2 tokens, a public and private token for your application to identify itself to the API, you can store both of these keys in this way.
Now to actually start interacting with twitter. First of all you will want to create the credentials with which you are going to contact the API with.
var credentials = new OAuthCredentials
{
Type = OAuthType.RequestToken,
SignatureMethod = OAuthSignatureMethod.HmacSha1,
ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader,
ConsumerKey = consumerKey,
ConsumerSecret = consumerSecret,
};
I’m no expert but this seems pretty simple, creating an OAuthCredentials object from the hammock library you define its type, etc. And most importantly send over your app’s keys. Once you’ve set the credentials you need to open a connection to the service that you’re then going to make a request from.
var client = new RestClient
{
Authority = "http://twitter.com/oauth",
Credentials = credentials
};
var request = new RestRequest
{
Path = "/request_token"
};
RestResponse response = client.Request(request);
Again, this is pretty self explanatory, the response is the callback now from whatever the response to your request was. Using var collection = HttpUtility.ParseQueryString(response.Content); you can access the variables sent back in the callback, using collection[0] you will get the first variable returned to you (in this case the temporary token you receive from twitter that you give to the user to connect your app to their account in the next step).
string aURL = String.Format("http://twitter.com/oauth/authorize?oauth_token={0}", collection[0]);
Process.Start(aURL);
This part opens the users default browser and sends them to twitters open authentication log in, so users can log in and give the app access to their account. String.Format takes that first string and puts the data from collection[0] into where it has {0}.
If the user accepts etc. And your app is set as a client rather than a website twitter will respond with a code, the user has to stick this code back into your program so you can do the final step. I simply read their input like so:
var verifier = Console.ReadLine();
Once the code has been submitted you use the code as verification of the users agreement to let you access their account, using this code you request an access code from twitter that you will be able to use to access their account without them having to go through this code process every time.
var acredentials = new OAuthCredentials
{
Type = OAuthType.AccessToken,
SignatureMethod = OAuthSignatureMethod.HmacSha1,
ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader,
ConsumerKey = consumerKey,
ConsumerSecret = consumerSecret,
Verifier = verifier.ToString(),
Token = collection[0],
TokenSecret = collection[1]
};
So we need a new set of credentials, this time setting the type to “AccessToken” as was probably defined in the OAuth spec. You send over your app keys, the two keys returned from the first token request and the code the user input (as Verifier).
Set up a client and request again, this time asking for the access_token path. Using the same technique earlier to get the variables returned we set our access tokens.
var aclient = new RestClient
{
Authority = "http://twitter.com/oauth",
Credentials = acredentials
};
var arequest = new RestRequest
{
Path = "/access_token"
};
RestResponse aresponse = aclient.Request(arequest);
collection = HttpUtility.ParseQueryString(aresponse.Content);
accessToken = collection["oauth_token"];
accessSecret = collection["oauth_token_secret"];
I stored them as such for future use:
Properties.Settings.Default.AccessToken = accessToken;
Properties.Settings.Default.AccessSecret = accessSecret;
Remember to save these settings with Properties.Settings.Default.Save();
Finally to connect to the API and do stuff, which wasn’t really covered in the first link. I spent ages on this part so it might be a bit odd. Important reminder though, you’re now using http://api.twitter.com as the authority for the client!:
var zcredentials = new OAuthCredentials
{
Type = OAuthType.ProtectedResource,
SignatureMethod = OAuthSignatureMethod.HmacSha1,
ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader,
ConsumerKey = consumerKey,
ConsumerSecret = consumerSecret,
Token = accessToken,
TokenSecret = accessSecret
};
var tclient = new RestClient
{
Authority = "http://api.twitter.com",
VersionPath = "1"
};
var trequest = new RestRequest
{
Credentials = zcredentials,
Path = "/statuses/update.xml",
Method = WebMethod.Post
};
trequest.AddParameter("status", tweetResponse);
RestResponse tresp = tclient.Request(trequest);
Console.WriteLine("Response: " + tresp.Content);
This will connect to the api and add a tweet, just change the path for other things. I’m using xml here, json is pretty much the same thing but with .json instead of .xml for status updates. The AddParameter thing is all that is really important. Check the twitter api for what parameters are needed for each request. The final line just printed out the response from the api for debugging purposes.
Thats it! That should work, it worked for me eventually. Obviously there is more validation and precondition stuff in the actual code but here is the bones. There is one major factor though, if you’re getting an error about not meeting expectations you have to use this at some point in your code:
System.Net.ServicePointManager.Expect100Continue = false;
There is reasons for this on the internet somewhere probably.
Cool Comments!
5 good post
4 Very nice. Can now post to twitter from C#. Thanks!
3 lol
2 BORING WHERE DA WOMAN AT LOLMAO
1 You pretend to be stupid but it's all a giant façade.
NEW

