I’ve been having a lot of fun writing a little ‘re-tweeter’ this morning. We basically want to monitor our user stream and then re-tweet any status with a particular hash tag. I thought this would be an excellent little project for node, and indeed it proved to be extremely easy to do. I used the node-twitter library which worked fine for what I wanted to do.
If you want to use this code, you’ll need to do the following:
First you’ll need to go to https://dev.twitter.com/apps and register a new app. You can then copy and paste your consumer key, consumer secret, access token and access token secret into the ‘xxx’ fields.
Next install node-twitter with npm:
npm install twitter
Then just run the code with node (I’m a poet and I didn’t know it):
node twitter-retweeter.js
Here’s the code in the twitter-retweeter.js file:
var util = require('util');
var twitter = require('twitter');
var twit = new twitter({
consumer_key: 'xxx',
consumer_secret: 'xxx',
access_token_key: 'xxx',
access_token_secret: 'xxx'
});
var hashtag = '#iloveprog'
function write(data) {
if ( typeof data === 'string') {
console.log(data);
}
elseif (data.text && data.user && data.user.screen_name) {
console.log(data.user.screen_name + ": " + data.text);
testForHashtag(data);
}
elseif (data.delete) {
console.log('DELETE');
}
elseif (data.message) {
console.log('ERROR' + data.message);
}
else {
console.log(util.inspect(data));
}
}
function testForHashtag(data) {
if(data.retweeted) return;
if(data.text.indexOf(hashtag) != -1) {
twit.retweetStatus(data.id_str, function(){
console.log('retweet callback');
});
}
}
function reconnect() {
setTimeout(startStreaming, 1000);
}
function startStreaming() {
twit.stream('user', function(stream) {
console.log('starting stream');
stream.on('data', write);
stream.on('end', reconnect)
});
}
startStreaming();
console.log('lisening for tweets');
It’s all really straight forward. The startStreaming function kicks of the callback on the twitter user stream. Each time an event occurs it calls the write function which checks for the given hashtag and then retweets the status if there’s a match.
Lovely!