Saturday, March 31, 2007

XML and Twitter and Weather, Oh My!

So with the advent of Twitter-mania I've been playing with it. However Twitter has become a victim of its own success, with the site being slow at the best of times and unresponsive at worst. So I've found a couple of alternatives to using the Twitter web site to post my status/thoughts. Since I'm a Widget fan I've discovered the Twidget which allows you to post text to Twitter with just a couple of clicks.

I wanted to post my local weather conditions to Twitter just to see if I could get a Linux command line poster working. Turns out you can! Although I first looked at the Twitter API it needed/used some stuff I'm not familiar with. So I asked the great and all-knowing Google and found a post over at Tech@Sakana which gives a script-based solution to push text onto your Twitter page using cURL.

The command line built using cURL looks like this:
curl --basic --user username:password --data status="Having fun with cURL"

Not to bad. Works great even when the twitter site is unresponsive.

Now for the Weather. Turns out that the National Weather Service (NWS) offers an XML-formatted file of the current weather conditions updated hourly. But... Having tried to use the native Linux tools to extract data from XML files I know how kludgy or even impossible it can be. I once again petitioned Google and found Xmlstarlet. Xmlstarlet is a command line utility from Sourceforge that can read and write XML files. In my case, I can use Xmlstarlet to extract the weather conditions I want from the XML file I download from the NWS.

Now I could build a script that collects the current observation file from the NWS, parses out the weather conditions I want to report. Builds a string of those conditions and sends them off to Twitter. Here's what it looks like:

cd ~/weather

mv -f KLOU.xml KLOU.XML

wget -q

# At $now it is $temperature in $location with winds $wind

now=`xml select -T -t -v //observation_time KLOU.xml|cut -d" " -f6-8;echo ""`
location=`xml select -T -t -v //location KLOU.xml|cut -d" " -f1,5;echo ""`
temperature=`xml select -T -t -v //temperature_string KLOU.xml;echo ""`
# Winds
## wind=`xml select -T -t -v //wind_string KLOU.xml|cut -d" " -f2-10;echo ""`
wind=`xml select -T -t -v //wind_string KLOU.xml;echo ""`

conditions=`echo At $now it is $temperature in $location. Winds: $wind.`

echo $conditions

curl --connect-timeout 5 --user johniac:******* --data status="$conditions"

If I'm going stick this into cron and have it run regularly, I need to add some locking code so that it won't run over the top of itself if Twitter or the NWS starts hanging connections. And of course that leads to the obligatory SMS messaging if a second instance trys to run. Maybe in version 2 ;-)

Technorati Tags: , , , ,

Labels: , , , ,


Post a Comment

<< Home

Support The Commons

RSS Atom Feed

follow johniac at

Join Johniac's Frappr Map

johniac's Rapleaf Score