#!/usr/bin/env python # encoding: utf-8 import socket, urllib2, urllib, os, sys, getopt, re env_name = 'POSTTWITTERRC' def usage(): print "%s [-h] [-v] -u username -p password [-f post file] [-t timeout] STATUS" % sys.argv[0] def version(): print "%s version 0.1" % sys.argv[0] def postTwitter (username, password, status, timeout = 30): url = 'http://twitter.com/statuses/update.xml' query = [ ('source','twittertalk'), ('status', status.decode('euc-jp').encode('utf-8')), ] socket.setdefaulttimeout (timeout) auth_handler = urllib2.HTTPBasicAuthHandler () auth_handler.add_password ('Twitter API', 'http://twitter.com/', username, password) req = urllib2.Request (url + '?' + urllib.urlencode (query), "") req.add_header ('Accept-Language', 'ja') opener = urllib2.build_opener(auth_handler) fd = opener.open (req) fd.close() def main(): try: opts, args = getopt.getopt (sys.argv[1:], 'hvu:p:f:t:') except getopt.GetoptError: usage() sys.exit(2) username = None password = None postfile = None timeout = 30 if os.environ.has_key (env_name): try: rc = open (os.environ[env_name], 'r') re_username = re.compile ('username\s*:\s*(\w+)', re.IGNORECASE) re_password = re.compile ('password\s*:\s*(\w+)', re.IGNORECASE) for line in rc: ma_username = re_username.match (line) ma_password = re_password.match (line) if ma_username: username = ma_username.group(1) if ma_password: password = ma_password.group(1) rc.close() except: pass for o,a in opts: if o == '-h': usage() sys.exit(2) if o == '-v': version() sys.exit(2) if o == '-u': username = a if o == '-p': password = a if o == '-f': postfile = a if o == '-t': timeout = int (a,0) if username == None or password == None or (len (args) == 0 and postfile == None): usage() sys.exit(1) if postfile != None: fd = open (postfile, 'r') for status in fd: postTwitter (username, password, status.strip(), timeout) fd.close() if len(args) > 0: postTwitter (username, password, ' '.join(args), timeout) if __name__ == '__main__': main()