Thursday, October 15, 2009

Tweet using command line

simple script that will allow you to send tweets from the command line:

The script you will see takes exactly one argument: your tweet. You use it like this:

$ ~/bin/tweet "Writing my TechMails"
Successful tweet!

Once you run the script and look on Twitter, your post is there for all to see. The script itself uses nothing fancier than cURL to post the text provided to the script.

The text must observe shell constraints: it must be properly escaped for special characters (such as "!" and "?"). The script doesn't require the tweet to be in quotes; you could use:

$ ~/bin/tweet Does my tweeter need quotes\?
Successful tweet!

and it would work just as well.

The script itself:

#!/bin/sh
tweet="${@}"
user="username"
pass="sekret"
if [ $(echo "${tweet}" | wc -c) -gt 140 ]; then
    echo "FATAL: The tweet is longer than 140 characters!"
    exit 1
fi
curl -k -u ${user}:${pass} -d status="${tweet}" 

https://twitter.com/statuses/update.xml >/dev/null 2>&1

if [ "$?" == "0" ]; then
    echo "Successful tweet!"
fi

Output of the cURL command is directed to /dev/null because it returns some XML that we don't need to care about. The script also makes sure that the tweet is 140 characters or less, and exits with an error if it is longer.

No comments: