Twitter from IRC via node.js and RHSCL

Inspired by a couple of great posts by Ryan Jarvinen from the OpenShift team, I decided to write a nice little node.js app that would let you access Twitter from IRC.

One of the many challenges with node.js is understanding when to best use it. While I was trying to think of a good app that met the criteria of Tomislav Capan’s excellent, short article I came across Ryan’s cool quick starts about an ircbot that tells jokes and creates an irc leaderboard.

OK, so let’s get started building a node app with RHSCL on RHEL.

First and foremost, you need to add the RHSCL channel (best explained here). After that is done, then you want to install node.js. We are currently shipping node.js 0.10 which is pretty recent and pretty stable. So, as you might guess:

$ sudo yum install nodejs010

Once that is done, drop into the shell mode.

$ scl enable nodejs010 bash

Now we can move on to creating the bot. First create a directory for your project and move into it.

mkdir irc-twitter-bot && cd irc-twitter-bot

In that folder we need to create a package.json file to declare our dependencies and the other bits and pieces about our node.js app. Here is the one I used (ohh, and btw, all the code is here):

{
  "name": "irc-twitter-node",
  "description": "A bot for irc that will work with Twitter",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node ./server.js"
  }
}

Now we need to install an IRC client and a Twitter client. For this we use:

npm install irc twit -save

The “-save” flag just adds the packages to your dependency list in package.json a la:

{
  "name": "irc-twitter-node",
  "description": "A bot for irc that will work with twitter",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node ./server.js"
  },
  "dependencies": {
    "irc": "~0.3.6",
    "twit": "~1.1.11"
  }
}

Follow these links for lots more about package.json and npm.

Ok, now we can move on the meat of the conversation. We need to spin up our server.js file and let it know we need the irc and Twitter libraries:

var irc = require('irc'), util = require('util'),
    Twit = require('twit');

var my_bot_name= 'ircbot-' + process.pid;
var bot = new irc.Client('chat.freenode.net', my_bot_name, {
    channels: ['#tweetme'],
    debug: true
    });
console.log("You can talk to me on #tweetme, my name is " + my_bot_name);

//just here to test that the server is up and running for testing
bot.addListener('pm', function (from, message) {
    console.log(from + ' => ME: ' + message);
});

Ok, now fire up the server by running:

npm start

OR

node server.js

Now connect to IRC using whatever your favorite IRC client (I use irssi and xchat) is and send your bot a message (e.g. /msg ircbot-SOMEPID test , where “ircbot-SOMEPID” is the output from the console line). You should see a message on your server console with what you sent.

After that we can add in the Twitter integration. However, this is where it gets a little tricky in that you need to get some connection keys from twitter. So, go to https://dev.twitter.com/ and create a new application. Once you do that, you need to go to the “OAuth tool” tab and find the 4 different tokens you need. Once you have the tokens, you need to put them in (in order) into a file called “twitter-secrets.js”. Here is a stubbed twitter-secrets.js file so that you get the idea.

var twitter_secrets = {
    consumer_key: 'CONSUMER KEY',
    consumer_secret: 'CONSUMER SECRET',
    access_token_key: 'ACCESS TOKEN',
    access_token_secret: 'ACCESS TOKEN SECRET'
    };

Now that you have all your secrets identified and put in the right place, we can add some cool functionality to our little bot. We are going to add a “commands” object which can be extended for an arbitrary set of commands. Very simply:

var commands = {
	search: function(tweeter, bot, to, string_to_search) {},
	followers: function(tweeter, bot, to, twitter_id) {}
};
function process_message(to, message) {
	var arr = message.split(": ");
	var command = "";
	if (arr.length > 0) {
		command = arr.shift();
	}
	if (command.length > 0) {
	    var tweeter = new Twit(secrets.twitter_secrets);
	    if (commands[command]) {
			commands[command](tweeter, bot, to, arr.join());
		} else {
			bot.say(to, "Try using 'followers: ' or 'search: '");
		}
	}
}
bot.addListener('pm', function (from, message) {
    //console.log(from + ' => ME: ' + message);
    process_message(from, message);
});

You can see, we have modified the listener to call “process_message” which parses the command into “COMMAND: ” and “PARAMS”. We then flip that into calling the “commands” function array. Right now, they just hit dead air. Let’s make them do something interesting. First, let’s look at “search”:

	search: function(tweeter, bot, to, string_to_search) {
		tweeter.get('search/tweets', { q: string_to_search, count: 10 }, function(err, reply) {
			bot.say(to, "Twitter search with '" + string_to_search + "'' returned:");
			var status, statuses = reply.statuses, len = statuses.length;
			for (var i =0; i < len; i++) {
				status = statuses[i];
				bot.say(to, status.user.screen_name + ": " + status.text);
			};
		});
	}

Here we call the API using the tweeter object we created earlier. The object basically takes the Twitter REST API and wraps it up in some nice convenience functions. In this case, we are calling the search API, passing in our search string, limiting it to 10 results, and then looping over the return and printing it to IRC. Be careful here, IRC servers will rate limit if you post too fast.

Next, let’s add a “followers lookup.” Basically, this is just a way to find out who the followers are for a particular user.

	followers: function(tweeter, bot, to, twitter_id) {
		tweeter.get('followers/list', { screen_name: twitter_id, count: 10 },  function (err, reply) {
			bot.say(to, "The user " + twitter_id + " has these followers:");
			if (reply && reply.users) {
				var follower, followers = reply.users, len = followers.length;
				for (var i =0; i < len; i++) {
					follower = followers[i];
					bot.say(to, follower.screen_name + ": " + follower.description + " (" + follower.location + ")");
				};
			}
		});
	}

We just query for the list of followers (note, we are using “list” so that we don’t just get back user-ids). The list includes information for each user so we print out who they are, their description, and their location.

Well, I hope that was helpful. Please let me know what you think in the comments. You can find all the code and some new features on github here.


Join the Red Hat Developer Program (it’s free) and get access to related cheat sheets, books, and product downloads.

 

Take advantage of your Red Hat Developers membership and download RHEL today at no cost.

Share

Leave a Reply