Skip to content

Interacting with Twitter

SeanBannister edited this page Oct 14, 2012 · 5 revisions

There are two common ways to interact with the twitter API, streaming and non-streaming. Both are initialised in the same manner, but the methods you use to interact differ slightly.

As always construct the oauth client.

var sys= require('sys');
bc. var OAuth= require('oauth').OAuth;
oa= new OAuth("https://twitter.com/oauth/request_token",
                 "https://twitter.com/oauth/access_token", 
                 consumer_key, consumer_secret, 
                 "1.0A", "http://localhost:3000/oauth/callback", "HMAC-SHA1");

Then get hold of a valid access token + access token secret as per the normal channels, e.g.:

var access_token= '23182282-ZXEASM32sadwAMDcVMilrXcHezMF4odlDwvKNyA';
var access_token_secret= 'PnNNSN234FMSdLQdvvDLy67dpaALies';

Then the usual (non-streaming way is to pass a callback function to the relevant client method, e.g:

oa.get("http://api.twitter.com/1/statuses/retweeted_by_me.json", access_token, access_token_secret, function(error, data) {
  console.log(sys.inspect(data));
});

If you want to use the streaming API however you will need to utilise the client method a little differently. By not passing in a callback method node-oauth will assume that you want to handle the response construction yourself and will pass back a request object to which you can attach your own response (and error) handlers. Remember to call ‘end’ on the request object when you want to start receiving data.

var request= oa.get("http://stream.twitter.com/1/statuses/sample.json", access_token, access_token_secret );
request.addListener('response', function (response) {
  response.setEncoding('utf8');
  response.addListener('data', function (chunk) {
    console.log(chunk);
  });
  response.addListener('end', function () {
    console.log('--- END ---')
  });
});
request.end();