open core »

Playing with Twitter Stream API and Text-to-Speech

There's a new Twitter API in town: The Twitter Stream API. But before you get all excited building a new twitter stream client, it's important for you to know that this is in alpha version for now.

Since I wanted to test this new API and didn't knew how to test it, I decided to do something silly. I wandered how it would be like to have someone read me in realtime all the tweets about a given keyword. This is the part where the Mac OS X built-in text-to-speech comes in.

The result was a PHP script that called the OS X "say" command to read the realtime Twitter stream.

The code is very simple:


$username = 'TWITTER_USER';
$password = 'TWITTER_PASSWORD';
$keyword = 'twitter';

$fp = fopen("http://$username:$$keyword", 'r');

while($data = fgets($fp))
	$res = json_decode($data, true);

	$user = $res['user']['screen_name'];
	$tweet = $res['text'];

	echo ("$user says: $tweet");
	exec (escapeshellcmd("say $user says: $tweet"));


Note the escapeshellcmd function that saves you from being owned in case someone "accidently" tweets something like ";rm -rf ~/".

You can just run this script in terminal, but first change the username and password to match your twitter account, and keyword to something you want to search.

Now you can annoy everyone at your workplace, with a voice reading out loud all your (not so) interesting tweets.