Skip to content

Instantly share code, notes, and snippets.

@mheadd
Created October 27, 2011 16:25
Show Gist options
  • Save mheadd/1320048 to your computer and use it in GitHub Desktop.
Save mheadd/1320048 to your computer and use it in GitHub Desktop.
A Node.js script that sends a Growl notification for SEPTA service advisory tweets.
// Include required modules.
var growl = require('growl');
var redis = require('redis');
var http = require('http');
var util = require('util');
// Twitter account name to query.
var twitter_account_name = process.argv[2] || 'SEPTA_WIL';
// Loop interval.
var interval = process.argv[3] || 30000;
// Twitter API path for latest tweet.
var path = '/1/statuses/user_timeline.json?include_entities=false&include_rts=false&trim_user=true&count=1&screen_name=' + twitter_account_name;
// Variable to hold JSON returned from Twitter API.
var latest_tweets = '';
// Create Redis client instance.
client = redis.createClient();
client.on('error', function(err) {
util.puts('Error: ' + err);
});
client.on('ready', function() {
setInterval(function() {
// Get the latest id for a tweet from the specified account.
client.get('latest', function(err, reply) {
if (err) {
util.puts('Error: ' + err);
} else {
// If we have the latest id queried, use it in the Twitter API call.
if (reply) {
path += '&since_id=' + reply;
}
// HTTP client to query the Twitter API.
var latestTweet = http.createClient(80, 'api.twitter.com');
var request = latestTweet.request('GET', path, {
'host' : 'api.twitter.com'
});
request.end();
request.on('response', function(response) {
response.setEncoding('utf8');
response.on('data', function(data) {
latest_tweets += data;
});
response.on('end', function() {
// Parse response from the Twitter API.
var tweets = JSON.parse(latest_tweets);
// Reset variable that holds Twitter API response chuncks.
latest_tweets = '';
// Enpty array returned.
if (!tweets.length) {
util.puts('No new tweets.');
} else {
// Repeat tweet returned.
if (tweets[0].id == reply) {
util.puts('No new tweets.');
} else {
// Send Growl notification with text of latest Tweet.
growl.notify('Tweet from @' + twitter_account_name + ': ' + tweets[0].text);
// Update the latest tweet id in redis.
client.set('latest', tweets[0].id);
}
}
});
});
}
});
}, interval);
});
@mheadd
Copy link
Author

mheadd commented Oct 27, 2011

Prerequisites:

  • Redis installed and running locally. Download here.
  • Growlnotify installed and configured with your choice of notification style.

Usage:

~$ node septa-tweet.js

Optionally, pass in the name of a specific SEPTA account you want to watch (default is SEPTA_WIL).

~$ node septa-tweet.js SEPTA_CHW

Optionally, pass in a different interval to check for new tweets (default is 30 seconds).

~$ node septa-tweet.js SEPTA_CHW 60000

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment