Pythonで簡易コマンドラインTwitterクライアント

pythonの勉強がてら、python twitterライブラリを使って、Twitterクライアント作ってみました。ちょっと中途半端ですが、オプション付き。

ソース

#!/usr/bin/python
# -*- coding: utf8 -*-

import twitter,random,sys
from optparse import OptionParser

id = "shiroma"
password = "XXXXXXXX"

parser = OptionParser()
parser.add_option('-p', '--post',
                    action='store', type='string', dest='message',
                    help=u'post a message',
                    )
options, args = parser.parse_args()

try:
    api = twitter.Api(id,password)
    if options.message != None:
        api.PostUpdate(options.message)
        print u"posted: %s" % (options.message.decode('utf8'))
        sys.exit()

    if len(args) == 0:
        statuses = api.GetFriendsTimeline(id)
    else:
        statuses = api.GetUserTimeline(args[0])
except twitter.TwitterError,e:
    print e
else:
    for status in statuses:
        print u"%s: %s" % (status.user.screen_name, status.text)

使い方

スクリプトは、twitterclient.pyとします。

タイムライン取得
% python twitterclient.py
あるユーザのタイムライン取得
% python twitterclient.py shiroma
ポスト

マルチバイトな文字列はターミナルとzshの設定がうまくいってないので未対応orz

% python twitterclient.py -p 'hogehoge'

感想

zshのマルチバイト設定がうまくいってなかったことにへこみました。

追記(2008/10/29)

ポストのところでoptions.message.decode('utf8')とすることで、unicode(日本語も)対応。unicode以外の入力からdecodeするとどうなるんだろう。