Skip to main content
Redhat Developers  Logo
  • Products

    Featured

    • Red Hat Enterprise Linux
      Red Hat Enterprise Linux Icon
    • Red Hat OpenShift AI
      Red Hat OpenShift AI
    • Red Hat Enterprise Linux AI
      Linux icon inside of a brain
    • Image mode for Red Hat Enterprise Linux
      RHEL image mode
    • Red Hat OpenShift
      Openshift icon
    • Red Hat Ansible Automation Platform
      Ansible icon
    • Red Hat Developer Hub
      Developer Hub
    • View All Red Hat Products
    • Linux

      • Red Hat Enterprise Linux
      • Image mode for Red Hat Enterprise Linux
      • Red Hat Universal Base Images (UBI)
    • Java runtimes & frameworks

      • JBoss Enterprise Application Platform
      • Red Hat build of OpenJDK
    • Kubernetes

      • Red Hat OpenShift
      • Microsoft Azure Red Hat OpenShift
      • Red Hat OpenShift Virtualization
      • Red Hat OpenShift Lightspeed
    • Integration & App Connectivity

      • Red Hat Build of Apache Camel
      • Red Hat Service Interconnect
      • Red Hat Connectivity Link
    • AI/ML

      • Red Hat OpenShift AI
      • Red Hat Enterprise Linux AI
    • Automation

      • Red Hat Ansible Automation Platform
      • Red Hat Ansible Lightspeed
    • Developer tools

      • Red Hat Trusted Software Supply Chain
      • Podman Desktop
      • Red Hat OpenShift Dev Spaces
    • Developer Sandbox

      Developer Sandbox
      Try Red Hat products and technologies without setup or configuration fees for 30 days with this shared Openshift and Kubernetes cluster.
    • Try at no cost
  • Technologies

    Featured

    • AI/ML
      AI/ML Icon
    • Linux
      Linux Icon
    • Kubernetes
      Cloud icon
    • Automation
      Automation Icon showing arrows moving in a circle around a gear
    • View All Technologies
    • Programming Languages & Frameworks

      • Java
      • Python
      • JavaScript
    • System Design & Architecture

      • Red Hat architecture and design patterns
      • Microservices
      • Event-Driven Architecture
      • Databases
    • Developer Productivity

      • Developer productivity
      • Developer Tools
      • GitOps
    • Secure Development & Architectures

      • Security
      • Secure coding
    • Platform Engineering

      • DevOps
      • DevSecOps
      • Ansible automation for applications and services
    • Automated Data Processing

      • AI/ML
      • Data Science
      • Apache Kafka on Kubernetes
      • View All Technologies
    • Start exploring in the Developer Sandbox for free

      sandbox graphic
      Try Red Hat's products and technologies without setup or configuration.
    • Try at no cost
  • Learn

    Featured

    • Kubernetes & Cloud Native
      Openshift icon
    • Linux
      Rhel icon
    • Automation
      Ansible cloud icon
    • Java
      Java icon
    • AI/ML
      AI/ML Icon
    • View All Learning Resources

    E-Books

    • GitOps Cookbook
    • Podman in Action
    • Kubernetes Operators
    • The Path to GitOps
    • View All E-books

    Cheat Sheets

    • Linux Commands
    • Bash Commands
    • Git
    • systemd Commands
    • View All Cheat Sheets

    Documentation

    • API Catalog
    • Product Documentation
    • Legacy Documentation
    • Red Hat Learning

      Learning image
      Boost your technical skills to expert-level with the help of interactive lessons offered by various Red Hat Learning programs.
    • Explore Red Hat Learning
  • Developer Sandbox

    Developer Sandbox

    • Access Red Hat’s products and technologies without setup or configuration, and start developing quicker than ever before with our new, no-cost sandbox environments.
    • Explore Developer Sandbox

    Featured Developer Sandbox activities

    • Get started with your Developer Sandbox
    • OpenShift virtualization and application modernization using the Developer Sandbox
    • Explore all Developer Sandbox activities

    Ready to start developing apps?

    • Try at no cost
  • Blog
  • Events
  • Videos

How I built a node app with RHSCL on RHEL to access Twitter

October 22, 2013
Langdon White
Related topics:
LinuxNode.js
Related products:
Red Hat Enterprise Linux

Share:

    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

    Related Posts

    • Install Node.js on Red Hat Enterprise Linux

    • Building Software Collections on top of RHSCL Part 1

    • Build your first application using Node.js with Red Hat Container Development Kit (CDK)

    Recent Posts

    • Container starting and termination order in a pod

    • More Essential AI tutorials for Node.js Developers

    • How to run a fraud detection AI model on RHEL CVMs

    • How we use software provenance at Red Hat

    • Alternatives to creating bootc images from scratch

    What’s up next?

    10 tips for nodejs cheat sheet tile card

    Run secure and efficient Node.js applications on OpenShift and other container environments. This cheat sheet rounds up 10 tips to help you learn best practices and get up to speed quickly.

    Get the cheat sheet
    Red Hat Developers logo LinkedIn YouTube Twitter Facebook

    Products

    • Red Hat Enterprise Linux
    • Red Hat OpenShift
    • Red Hat Ansible Automation Platform

    Build

    • Developer Sandbox
    • Developer Tools
    • Interactive Tutorials
    • API Catalog

    Quicklinks

    • Learning Resources
    • E-books
    • Cheat Sheets
    • Blog
    • Events
    • Newsletter

    Communicate

    • About us
    • Contact sales
    • Find a partner
    • Report a website issue
    • Site Status Dashboard
    • Report a security problem

    RED HAT DEVELOPER

    Build here. Go anywhere.

    We serve the builders. The problem solvers who create careers with code.

    Join us if you’re a developer, software engineer, web designer, front-end designer, UX designer, computer scientist, architect, tester, product manager, project manager or team lead.

    Sign me up

    Red Hat legal and privacy links

    • About Red Hat
    • Jobs
    • Events
    • Locations
    • Contact Red Hat
    • Red Hat Blog
    • Inclusion at Red Hat
    • Cool Stuff Store
    • Red Hat Summit

    Red Hat legal and privacy links

    • Privacy statement
    • Terms of use
    • All policies and guidelines
    • Digital accessibility

    Report a website issue