Created
October 27, 2011 16:25
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Prerequisites:
Usage:
Optionally, pass in the name of a specific SEPTA account you want to watch (default is SEPTA_WIL).
Optionally, pass in a different interval to check for new tweets (default is 30 seconds).