2008年7月2日水曜日

pythonでtwitterクライアント。コマンドプロンプト版。

作ったやつを張っとこう。
ざっくり判った。twitterのAPIは簡単で判りやすい。json便利。


Windowsならではの小細工が。
でもこれcmdで立ち上げとくと便利。メモ代わりにどんどん書き込める。

# -*- coding: utf-8 -*-

'''
twitter
friends timeline post
'''
import urllib, urllib2
import json
import calendar
import time
import sys

toplevel_url = 'twitter.com'
target_url = 'twitter.com/statuses/update.json'
protocol = 'http://'
proxy = {'http':'http://hogehoge.com:80/'}
username = 'hogehoge@gmail.com'
password = 'xxxxx'

proxy_handler = urllib2.ProxyHandler(proxy)
passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
passman.add_password(None, toplevel_url, username, password)
authhandler = urllib2.HTTPBasicAuthHandler(passman)
opener = urllib2.build_opener(proxy_handler, authhandler)
urllib2.install_opener(opener)

def twitter_post(text):
params = urllib.urlencode({'status':text.encode('utf8')})
#print params
urllib2.urlopen(protocol + target_url, params)

def twittertime2time(created_at):
unix_time = calendar.timegm(time.strptime(created_at, '%a %b %d %H:%M:%S +0000 %Y'))
return time.strftime("%a, %d %b %Y %H:%M:%S", time.localtime(unix_time))

while ( True ):
utext = raw_input('What are you doing?: ')
text = unicode(utext, 'mbcs')
twitter_post(text)



毎分チェックに行く方

# -*- coding: utf-8 -*-

'''
twitter
friends timeline loop_get
'''

import urllib2
import json
import calendar
import time
import shelve, sha

SLEEP_TIME = 1 * 60
HISTORY_FILE = 'tw.log'
toplevel_url = 'twitter.com'
target_url = 'twitter.com/statuses/friends_timeline/screen_name.json'
protocol = 'http://'
proxy = {'http':'http://hogehoge.com:80/'}
username = 'hogehoge@gmail.com'
password = 'xxxxxxx'

proxy_handler = urllib2.ProxyHandler(proxy)
passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
passman.add_password(None, toplevel_url, username, password)
authhandler = urllib2.HTTPBasicAuthHandler(passman)
opener = urllib2.build_opener(proxy_handler, authhandler)
urllib2.install_opener(opener)

def twittertime2time(created_at):
unix_time = calendar.timegm(time.strptime(created_at, '%a %b %d %H:%M:%S +0000 %Y'))
return time.strftime("%b %d %H:%M:%S", time.localtime(unix_time))
#return time.strftime("%a, %d %b %Y %H:%M:%S", time.localtime(unix_time))

def memory_log(time, text):
FLG = True
log = shelve.open( HISTORY_FILE )
s = sha.new( text.encode('utf-8') )
if ( not log.has_key( s.digest() ) ):
log[ s.digest() ] = time
FLG = False
log.close()
return FLG

def print_twitt(contents):
for content in contents:
if ( not memory_log(content['created_at'], content['text']) ):
print twittertime2time(content['created_at']), content['user']['screen_name'], content['text']

while ( True ):
pagehandle = urllib2.urlopen(protocol + target_url)
json_contents = pagehandle.read()
contents = json.read(json_contents)
print_twitt(contents)
time.sleep( SLEEP_TIME )
print '.',

0 件のコメント: