スキップしてメイン コンテンツに移動

PythonのワンライナーでTwitterを使う

Twitterでつぶやいたり、タイムラインを取得したりするPythonのワンライナー(1行プログラム)を作ってみた。取り敢えずWindowsで動作は確認した。Pythonさえ入っていればどこでも動くと思う。シェルやcronに組み込んだり、ウェブアプリや自作プログラムで利用したり、Python以外に必要なものがないから手軽に使えるんじゃないかな。ただ、ユーザ名とパスワードは生テキストなのでその辺は気をつけるべきかも。

まず、Twitterでつぶやくワンライナー。

python -c "import urllib,urllib2;pm=urllib2.HTTPPasswordMgrWithDefaultRealm();pm.add_password(None,'twitter.com','username','password');urllib2.install_opener(urllib2.build_opener(urllib2.HTTPBasicAuthHandler(pm)));urllib2.urlopen('http://twitter.com/statuses/update.xml',urllib.urlencode({'status':'つぶやき'.decode('cp932').encode('utf-8')}))"

次に、タイムライン取得。simplejsonを使っている。

python -c "import sys,urllib,urllib2,xml.sax.saxutils,simplejson;pm=urllib2.HTTPPasswordMgrWithDefaultRealm();pm.add_password(None,'twitter.com','username','password');urllib2.install_opener(urllib2.build_opener(urllib2.HTTPBasicAuthHandler(pm)));sys.stdout.write(''.join(['%s: %s\n'%(d['user']['screen_name'],xml.sax.saxutils.unescape(d['text']))for d in simplejson.loads(urllib2.urlopen('http://twitter.com/statuses/friends_timeline.json').read())]).encode('cp932','replace'))"

因みに文字コードはCP932、簡単に言えばShift JISなので(厳密には違うけど)、環境に合わせて修正したり、nkfをかませるなどして欲しい。それにしても、TwitterのAPIは使いやすくていいね。

追記(2009/8/29):

Twitterのつぶやきとタイムライン取得の両方を行うワンライナーも書いてみた。このコードはPython 2.5以上で動作する。

python -c "import sys,urllib,urllib2,xml.sax.saxutils,simplejson;pm=urllib2.HTTPPasswordMgrWithDefaultRealm();pm.add_password(None,'twitter.com','username','password');urllib2.install_opener(urllib2.build_opener(urllib2.HTTPBasicAuthHandler(pm)));sys.stdout.write(''.join(['%s: %s\n'%(d['user']['screen_name'],xml.sax.saxutils.unescape(d['text']))for d in simplejson.loads(urllib2.urlopen('http://twitter.com/statuses/friends_timeline.json').read())]).encode('cp932','replace'))if len(sys.argv)<2 else urllib2.urlopen('http://twitter.com/statuses/update.xml',urllib.urlencode({'status':sys.argv[1].decode('cp932').encode('utf-8')}))" つぶやき

「つぶやき」を書けばそれがTwitterに送信され、書かなければタイムライン取得となる。また、「つぶやき」にスペースなどが入る場合はダブルクォーテーション(")で括ること。

次のコードであればPython 2.4以下でもいけるかな。

python -c "import sys,urllib,urllib2,xml.sax.saxutils,simplejson;pm=urllib2.HTTPPasswordMgrWithDefaultRealm();pm.add_password(None,'twitter.com','username','password');urllib2.install_opener(urllib2.build_opener(urllib2.HTTPBasicAuthHandler(pm)));len(sys.argv)<2and[sys.stdout.write(''.join(['%s: %s\n'%(d['user']['screen_name'],xml.sax.saxutils.unescape(d['text']))for d in simplejson.loads(urllib2.urlopen('http://twitter.com/statuses/friends_timeline.json').read())]).encode('cp932','replace'))]or[urllib2.urlopen('http://twitter.com/statuses/update.xml',urllib.urlencode({'status':sys.argv[1].decode('cp932').encode('utf-8')}))]" つぶやき

コメント