Created
June 1, 2012 22:26
-
-
Save Hypnopompia/2855492 to your computer and use it in GitHub Desktop.
Twitter firehose client in nodejs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Twitter firehose client. | |
// Written by TJ Hunter | |
// https://dev.twitter.com/docs/api/1/post/statuses/filter | |
var https = require('https'); | |
// Command line args | |
var username = process.argv[2]; | |
var password = process.argv[3]; | |
var keyword = process.argv[4] || "zombie"; | |
if (!username || !password) { | |
console.log("Usage: node twitterhose.js <twitter_username> <twitter_password> <keyword>"); | |
return; | |
} | |
// Authentication Headers for Twitter | |
var auth = new Buffer(username + ':' + password).toString('base64'); | |
var headers = { | |
'Authorization' : "Basic " + auth, | |
'Host' : "stream.twitter.com" | |
}; | |
// Connection to Twitter's streaming API | |
var requestOptions = { | |
host: 'stream.twitter.com', | |
port: 443, | |
path: '/1/statuses/filter.json?track=' + keyword, | |
method: 'GET', | |
headers: headers | |
}; | |
var message = ""; | |
var req = https.request(requestOptions, function(res){ | |
res.setEncoding('utf8'); | |
res.on('data', function(chunk){ | |
message += chunk; | |
var newlineIndex = message.indexOf('\r'); | |
if (newlineIndex !== -1) { | |
try { | |
var tweet = JSON.parse(message.slice(0, newlineIndex)); // more info about the tweet object can be found at https://dev.twitter.com/docs/platform-objects/tweets | |
console.log('<@' + tweet.user.screen_name + '> ' + tweet.text); | |
} catch (e) { | |
} | |
} | |
message = message.slice(newlineIndex +1); | |
}); | |
}); | |
req.end(); | |
req.on('error', function(e) { | |
console.error(e); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment