2010年8月6日金曜日

ブラウザアプリでOauth認証

twitterのOauth認証できるようになったので
ブラウザアプリケーションでもやってみるかと思ったら
認証の仕方が微妙に違う(汗)
仕方ないのでこっちは別にやりました


callbackして同じページに戻ってきて、
認証するようにしています

access_tokenは保存しておきたいので、cPickleを使って保存しておく。

以下access_tokenを取得して認証する関数

#!/usr/bin/python
#!-*- coding: utf-8 -*-

import os, cPickle, cgi
from oauthtwitter import *

CONSUMER_KEY = "your consumer_key"
CONSUMER_SECRET = "your consumer_secret"
KEYFILE = "./keyfile/key.dat"
ACCESS_TOKEN = "./access_file/access_token.dat"

def twitter():
  form = cgi.FieldStorage()
#access_tokenをすでに取得している場合
  if os.path.isfile(ACCESS_TOKEN):
    f = file(ACCESS_TOKEN,"rb")
    access_token = cPickle.load(f)
    f.close()
    return OAuthApi(CONSUMER_KEY, CONSUMER_SECRET, access_token)
#access_tokenを取得していない場合
  else:
#ユーザに許可をもらう前。request_tokenからurlを作成し、ユーザに許可をもらう画面にアクセスする。
    if "oauth_token" not in form:
      tw = OAuthApi(CONSUMER_KEY, CONSUMER_SECRET)
      request_token = tw.getRequestToken()
      f = file(KEY_FILE,"wb")
      cPickle.dump(request_token,f)
      f.close()
      authorization_url = tw.getAuthorizationURL(request_token)
      print 'アクセス'%authorization_url
      return None
#ユーザに許可をもらった後。access_tokenを作成し保存する。
    else:
      f = file(KEY_FILE,"rb")
      request_token = cPickle.load(f)
      f.close()
      tw = OAuthApi(CONSUMER_KEY, CONSUMER_SECRET,request_token)
      access_token = tw.getAccessToken()
      f = file(ACCESS_TOKEN,"wb")
      cPickle.dump(access_token,f)
      f.close()
      return OAuthApi(CONSUMER_KEY, CONSUMER_SECRET, access_token)

def print_coment(api)
  statuses = api.GetFriendsTimeline(count=10)
  for status in statuses:
    print "%s:%s
"%(status.user.name,status.created_at)
    print "%s
"%status.text

if __name__=="__main__":
  print "Content-Type: text/html"
  print
  api = twitter()
  if(api != None):
    print_coment(api)

2010年8月2日月曜日

twitterAPIコマンドライン投稿

実際にコマンドライン投稿できるようなものを
pythonで書いてみた。

細かいところがいろいろ必要だった。

まず、python-twitterから
/usr/lib/python2.5/site-packages/のなかの
twitter.pyの中で関数PostUpdate中の

if len(status) > CHARACTER_LIMIT:
          ↓
if len(status.decode("utf-8")) > CHARACTER_LIMIT:
変更した。日本語の場合、statusの文字数が三倍くらいになるので、140文字投稿できないため

前回インストールしたものに加え、以下のものインストール。
oauth-python-twitteroauthが必要になる。
インストールするにあたって
参照サイトを参考にしており、
def getAccessTokenWithPin(self, pin, url=ACCESS_TOKEN_URL):
  token = self._FetchUrl(url, parameters={"oauth_verifier": pin}, no_cache=True)
  return oauth.OAuthToken.from_string(token)
をoauth-python-twitterのtwitter.pyに追記してインストールしている。


さらに、twitterにアプリケーション登録を行い、
Consumer_keyとConsumer_secretをもらっておく必要がある。

#!/usr/bin/python
#!-*- coding: utf-8 -*-

import sys, os, pickle
from optparse import OptionParser
from oauthtwitter import *

CONSUMER_KEY = "CONSUMER_KEY" #実際のCONSUMER KEYを入力
CONSUMER_SECRET = "CONSUMER_SECRET" #実際のCONSUMER SECRETを入力
KEY_FILE = "KEY_FILES/twitter_key.dat"

#access_tokenを取得する。ない場合は取得し、前回のものが保存してある場合はそれを使う。
def Get_Access_Token():
  if os.path.isfile(KEY_FILE):
    access_token = pickle.load(file(KEY_FILE))
  else:
    tw = OAuthApi(CONSUMER_KEY, CONSUMER_SECRET)
    request_token = tw.getRequestToken()
    authorization_url = tw.getAuthorizationURL(request_token)
    print authorization_url
    tw = OAuthApi(CONSUMER_KEY, CONSUMER_SECRET, request_token)
    oauth_verifier = raw_input("PINを入力:\n")
    access_token = tw.getAccessTokenWithPin(oauth_verifier)
    pickle.dump(access_token, file(KEY_FILE,"w"))
  return OAuthApi(CONSUMER_KEY, CONSUMER_SECRET, access_token)


#フォローしている人物のコメントを表示する。
def print_coment(option, opt_str, value, parser, *args, **kwargs):
  api = Get_Access_Token()
  statuses = api.GetFriendsTimeline(count=10)
  for s in statuses:
    print s.user.name + ":"
    print s.text


#フォローしている人物の名前を表示する。
def print_friends(option, opt_str, value, parser):
  api = Get_Access_Token()
  users = api.GetFriends()
  for user in users:
    print user.name

def main():
  tw = twitter()

  parser = OptionParser()

  parser.add_option("-t","--tweet",dest="coment",type="string",action="store",help="write coment")

  parser.add_option("-w","--watch",dest="tweet",action="callback",callback=print_coment,help="watch your friend's coment")

  parser.add_option("-f","--friend",dest="friend",action="callback",callback=print_friends,help="watch your friends")

  (options, args) = parser.parse_args()

#コメントを投稿する。
  if(options.coment != None):
    post = options.coment
    status = tw.PostUpdate(post)

if __name__=="__main__" :
  main()

コマンドラインtwitterできるようになった!
このプログラムでツイートとフォローしている人物のコメント閲覧とフォローしている人物の名前の表示ができる。

前回の認証にはBASICを使用していたが、
今回はOAuthを使用してプログラムを書いてみた。