Skip to content

Instantly share code, notes, and snippets.

@JakobJingleheimer
Last active December 31, 2015 11:09
Show Gist options
  • Save JakobJingleheimer/7977631 to your computer and use it in GitHub Desktop.
Save JakobJingleheimer/7977631 to your computer and use it in GitHub Desktop.
WebSocket (socket.io) proxy for Twitter stream (Twit).
// var server …
// …
var io = require('socket.io').listen(server),
Twit = require('twit');
var twitter = new Twit({ … });
io.sockets.on('connection', function connect( socket )
{
function emitTweets( sn , tweets )
{
console.log('\n','tweets retrieved for '+sn, '\n');
var data = [];
for ( var i = tweets.length-1; i >= 0; i-- )
{
var tweet = tweets[i];
data[i] = {
"avatar": tweet.user.profile_image_url,
"created": tweet.created_at,
"id": tweet.id_str,
"screen_name": tweet.user.screen_name,
"text": tweet.text
};
}
console.log('\n','Tweets: ', data, '\n');
io.sockets.in( sn ).emit('tweets', data );
}
function verifyScreenName( sn )
{
if ( !sn )
{
socket.emit('error',
{
"statusCode": 404,
"message": "A request was received but no screen name was specified."
}
);
return false;
}
if ( (/\W/).test( sn ) )
{
socket.emit('error',
{
"statusCode": 400,
"message": "The specified twitter screen name contains illegal characters: "+screen_name.match(/\W/).join('')
}
);
return false;
}
return true;
}
// var tweetStream;
socket.on('subscribe', function subscribe( data )
{
var sn = data.screen_name;
if ( !verifyScreenName( sn ) ) return false;
socket.join( sn );
twitter.get('statuses/user_timeline', { "screen_name": sn }, function getTweets( err , tweets )
{
if ( err )
{
console.log( '\n' , 'userLookup.err: ', err, '\n' );
socket.emit('error', { "statusCode": err.statusCode, "message": err.message });
return false;
} else
{
emitTweets( sn , tweets );
var user_id = tweets[0].user.id;
try {
var tweetStream = twitter.stream('statuses/filter', { "follow": user_id });
console.log('\ntweetStream: ', tweetStream, '\n');
tweetStream.on('tweet', function onTweet(tweet)
{ // emitTweets expects more than one; since there's only 1, wrap in array.
console.log( '\ntweetStream -> new tweet: ', tweet, '\n' )
emitTweets( sn , [tweet] );
});
} catch(err)
{
console.log('\ntweetStream error: ', tweetStream, '\n');
}
}
});
});
socket.on('unsubscribe disconnect', function( data )
{
var sn = data.screen_name;
if ( !verifyScreenName( sn ) ) return false;
socket.leave( sn );
if ( ! '/'+sn in io.sockets.manager.rooms ) tweetStream.stop();
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment