↓ Twitter is updated more often, so read it! ↓

HOWTO Write a script to update Twitter from Linux

I just signed up for Twitter as colindean. I don’t know what use I’ll have for it, as I’m not one who is much for microblogging or partying.

Anyway, the API caught my eye, and after having read Wayne’s post at Fsckin w/ Linux regarding Twitter clients for Linux, I decided to roll my own rather than use what’s out there. I wanted something simple and bashful.


#!/bin/bash
EMAIL=youremail@yourdomain.com
PASSWORD=yourpassword

WHAT="What are you doing? "
SORRY="Sorry, that was too long."
UPDATED="Tweet submitted:"

function getinput {
  if [ ${TERM} = "xterm" ]; then echo -n "${WHAT}"; read TWEET
    else TWEET=$(zenity --entry --text="${WHAT}" --entry-text="${1}")
  fi
}

function check_length {
  TWEETLENGTH=$(echo -n "${TWEET}" | wc -m)
  if [ ${TWEETLENGTH} -gt 140 ]; then
    warn_user
    getinput ${TWEET}
    check_length
  fi
}

function warn_user {
  if [ ${TERM} = "xterm" ]; then echo "${SORRY}"
    else zenity --warning --text="${SORRY}"
  fi
}
function submit_tweet {
  curl -u ${EMAIL}:${PASSWORD} \
       -d status="${TWEET}" \
       http://twitter.com/statuses/update.xml \
  > /dev/null
}

TWEET=$@ #see if it was supplied on the command line
if [ -z "${TWEET}" ]; then getinput; fi #if it wasn't, prompt for it
check_length #make sure it's less than 140 characters
submit_tweet #submit it since we got past the check

if [ ${TERM} = "xterm" ]; then echo "${UPDATED} ${TWEET}"
  else
    exec 3> >(zenity --notification --listen --window-icon=/usr/share/pixmaps/gnome-irc.png)
    echo "message: ${UPDATED}\n\n${TWEET}" >&3
    sleep 10
    exec 3>&-
fi

Just replace the EMAIL and PASSWORD variables and drop it into a directory in your $PATH. You can add it to the panel, too—it will detect if it’s been executed at a terminal or from the panel or other GUI element. It could also very easily be internationalized.

Let me know what you think of this script—it’s 4:00 am and I’m about to pass out.

Sorry, that one line might overflow the box on slim resolutions. I’ll get that fixed one of these days. Update: That was an easy fix. Added overflow: auto; to the codeblock CSS.

4 Comments

  1. Colin Dean:

    In retrospect, I should have check_length simply handle length checking instead of also handling corrections.

  2. Wayne:

    This is fantastic…

  3. Wayne:

    Ok this is more than fantastic… I dub this megatweet (at least what I named it on my box).
    This script fixed my terrible, terrible hacked up tweeting script for my cat.

    http://twitter.com/JungleCrawler

  4. Colin Dean:

    Wayne, I’ll have the improved version up by the end of the day today. It does far more error checking and I’m working on parsing the server output. I’m having trouble finding a decent xmllint tutorial, and I want to avoid using perl or python–I want to keep it as basic as possible. Make sure you’ve added the feed so you won’t miss it ;-)

Leave a comment