Node.js on RHEL

I was inspired by a couple of great posts by Ryan Jarvinen from the OpenShift team to write a nice little node.js app to access Twitter from IRC.

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

Building a node app with RHSCL on RHEL

1. First and foremost, you need to add the RHSCL channel (best explained here).

2. 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. Enter the following:

$ sudo yum install nodejs010

3. Once that is done, drop into the shell mode as follows:

$ scl enable nodejs010 bash

4. Now we can move on to creating the bot by creating a directory for your project and moving into it.

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

5. 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. You can find the code here. Here is the code I used:

{
  "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"
  }
}

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

npm install irc twit -save

The "-save" flag adds the packages to your dependency list in package.json as you can see 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"
  },
  "dependencies": {
    "irc": "~0.3.6",
    "twit": "~1.1.11"
  }
}

Follow these links to learn more about package.json and npm.

7. Now we move on to the spin up our server.js file and letting 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);
});

8. Fire up the server by running:

npm start

Or:

node server.js

9. Now connect to IRC using your favorite IRC client (I use irssi and xchat). Then 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.

10. After that, we add the Twitter integration. However, this is where it gets a little tricky because you need to obtain connection keys from Twitter. So, go to https://developer.twitter.com/en and create a new application.

11. Once you have done that, go to the OAuth tool tab and find the 4 tokens you need. Once you have the tokens, you need to put them (in order) into a file called "twitter-secrets.js". For example, this is a stubbed twitter-secrets.js file:

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

12. 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 as follows:

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.

13. Let's make them do something interesting. Let's look at the 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.

14. Next, 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.

Last updated: November 2, 2023