Monday, February 15, 2010

Future Tweeting my way

Lazy + Ability to script = Nifty scripts.

I wanted to keep my Twitter account very active but I didn't want to tweet everyday, so I wrote a script to do it for me. There are better ways to do this I'm sure (specially with security and error handling) this is a quick and dirty script so if you feel like fixing it feel free to leave it in comments.

Requirements:
1. Bash shell (Should work on Cygwin or Linux (i happen to run it on ubuntu 9.10)
2. curl
3. Some basic scripting and BASH knowledge.
4. cron job to run script daily. (Ex: 6am every day: 0 6 * * * ~/script_name > dev/null)

Write your tweet file with one tweet per day:
January, March, May, July, October, December should have 31 lines
February should be 28 or 29 days depending on leap year (2012+4+4+4, etc...)
The rest of the files would be 30 lines.

Here's the script:

#!/bin/bash
# initialize tweet variable
tweet=""
tweetpath=/path/to/tweetfile

# this is the file with the tweets for the month named YEARmonth (2010Feb)
tweetfile=`date +%Y%b`

# generate today's date, which will correspond to line number in $tweetfile
linenumber=`date +%d`

# this takes the tweet for the day based on calendar day/linenumber
tweet=`sed -n "$linenumber"p $tweetpath/$tweetfile`

# we don't want to tweet at the same time of day every day, do we?
# introduce a random 0 to 240 minute delay (4 hours)
delay=$((RANDOM%240+0))m

# run only if there's a file for this month, and only if there's a tweet for the day
if [ -f $tweetpath/$tweetfile ]; then
        if [ -n "$tweet" ]; then
                echo Sleeping $delay minutes...
                sleep $delay
                curl -s -u twitter_user_name:twitter_password -d status="$tweet" http://twitter.com/statuses/update.xml > /dev/null
        fi
fi

No comments:

Post a Comment