twitterd in Python
So a while ago I decided that twitter is the new finger albeit more palitable for the masses and wrote twitterd in perl. I’ve been using this to update my twitter and facebook status ever since. A couple of months ago I decided to rewrite it in Python. Next stop C?
#!/usr/bin/python
"""
twitterd
Author: Nathan Charles <ncharles at gmail dot com>
Version: 0.1
This program twits the contents of a file when it's time stamp is updated.
The functionality is similar to that of finger/.plan in days of yore.
Requires:
pytwitter
configobj
This program has no warranty to the full extent of the law
"""
import pytwitter
from sys import exit, argv
from os import path
from time import sleep
POLLINT = 60
READLEN = 140
def setEnv():
from configobj import ConfigObj
from os import environ
import getopt
env = {}
HOME = environ.get("HOME")
config = ConfigObj(HOME + '/.twitrc')
env["watchfile"] = HOME + '/.plan'
try:
env["username"] = config['username']
env["password"] = config['password']
except:
#.twitrc doesn't exist not nessarily a problem
pass
try:
env["optlist"], args = getopt.getopt(argv[1:], 'dfh',["username=","password="])
except getopt.GetoptError:
usage()
print "called exception"
exit(1)
for o,a in env["optlist"]:
if o == "--username":
env["username"]=a
if o == "--password":
env["password"]=a
if not "username" in env:
print "username is not set"
exit(1)
if not "password" in env:
print "password is not set"
exit(1)
return env
def watch(username, password, watchfile):
"""Updates a twitter feed with the contents of a file when the timestamp is updated.
"""
try:
timeStampInitial = path.getmtime(watchfile)
except:
#file doesn't exist setting to 0 because it might exist in the future
timeStampInitial = 0
while 1:
try:
timeStampIncrimented = path.getmtime(watchfile)
except:
#file still doesn't exist
timeStampIncrimented = 0
if (timeStampInitial==timeStampIncrimented):
sleep(POLLINT)
else:
timeStampInitial = timeStampIncrimented
#update status
statusTxt = file(watchfile).read(READLEN)
client = pytwitter.pytwitter(username=username, password=password)
rc = client.statuses_update(status=statusTxt)
print rc
def usage():
"""Prints when called with no arguments or with invalid arguments
"""
print """usage: twitterd [options]
-d daemonize
-f run in forground
-h help
twitterd must have twitter username/password set. this can be set via .twitrc
--password set username
--username set password
"""
if __name__ == "__main__":
g = setEnv()
if g["optlist"]:
for o,a in g["optlist"]:
if o == '-h':
usage()
exit(1)
if o == '-d':
#run in background
import daemon
daemon.daemonize()
if o == '-f':
#run in forground
print "Running in Foreground"
else:
usage()
exit(1)
watch(g["username"], g["password"], g["watchfile"])


