2010-09-09

OAuth on Simple Twitter Bot




僕は直前になるまで、というか、実際に仕様変更されるまで気付かなかったわけですが、今月の頭からTwitterのBasic認証が使えなくなったそうですね。従って、Basic認証を用いてTwitterのAPIを使用しているBot達は、仕様変更の日を境に、屍と化してしまっているそうです。

僕が作ったtango! botなども同様に、Basic認証を利用していたので、屍と化してしまいました。ですが、tango! botにザオリクを唱えて欲しい(?)というご要望に応えまして、先週末にOAuth認証システムを実装しました。

で、せっかく実装したので、Simple Twitter Botを例にとって僕の実装例を次の場所に置いておきます。参考になるかどうかは甚だ疑問ではありますが、もし何かの参考になれたら幸いです。



*main.py(要約)
#!/usr/bin/env python
#! -*- coding: utf-8 -*-

from appengine_twitter import AppEngineTwitter
from basehandler import BaseHandler, h
import twitter
import sys, os, pickle
from oauthtwitter import *

# User Setting and Run Twitter Bot
#debug_flag = True
debug_flag = False
MAX_LEN = 140
SEARCH_TERM = u'"hogehoge" OR foobar'
CONSUMER_KEY    = "???"
CONSUMER_SECRET = "???"
KEY_FILE_API    = "api_key.dat"
KEY_FILE_TWITTER = "twitter_key.dat"
BOT_USERNAME = "YOUR_BOT_NAME"
BOT_PASSWORD = "???"

def oauth_twitter():
   access_token = pickle.load(file(KEY_FILE_API))
   return OAuthApi(CONSUMER_KEY, CONSUMER_SECRET, access_token)
                                                                      
# twitter.Api.__init__ method for override.
def twitter_api_init_gae(self,
                       username=None,
                       password=None,
                       input_encoding=None,
                       request_headers=None):
   import urllib2
   from twitter import Api
   self._cache = None

   self._urllib = urllib2
   self._cache_timeout = Api.DEFAULT_CACHE_TIMEOUT
   self._InitializeRequestHeaders(request_headers)
   self._InitializeUserAgent()
   self._InitializeDefaultParameters()
   self._input_encoding = input_encoding
   self.SetCredentials(username, password)

def run(name, pswd, search_term):
   acc_token = pickle.load(file(KEY_FILE_API))
   gae_twitter = AppEngineTwitter()   
   gae_twitter.set_oauth(CONSUMER_KEY,
                         CONSUMER_SECRET,
                         acc_token.key,
                         acc_token.secret)

   results = gae_twitter.search(search_term.encode('utf8'), {'rpp': 20})
   api = oauth_twitter() 
   escape_user_list = []
   escape_user_list.append(name)
   
   # Get most corrently tweeted tweet
   status = api.GetUserTimeline()
   
   for s in status:
      if s.text.startswith("RT"):
         recent_tweet = s.text
         break
      else:
         print "The following tweet would be posted by hand, so skipped it."
         print "Tweet: " + s.text.encode('utf8')
         print
      
   print "Recent Tweet: "+recent_tweet.encode('utf8')
   print

   # Search Most Recent Tweet
   results.reverse()
   flag_enable = 0
   for i,result in enumerate(results):
      rt = "RT [at]" + result['from_user']  + " " + result['text']
      rt_len = len(rt)
      
      if flag_enable:
         print "I am going to tweet the tweet above."
         """
         Retweet and exit
         """
         print "I have re-tweeted: "+rt.encode('utf8')
         print "Result of my re-tweeting: " + str(gae_twitter.update(rt.encode('utf8')))
         exit()
               
      if recent_tweet.replace("@", "[at]") == rt.replace("@", "[at]"):
         flag_enable = 1

   if flag_enable:
      print "There are no tweet found that I should tweet."
      exit()
   print
   print "There are no tweets recently tweeted, so tweet the oldest tweet."
   print

   for i,result in enumerate(results):  
      rt = "RT [at]" + result['from_user']  + " " + result['text']  
      rt_len = len(rt)

      print "I am going to tweet the tweet above."
      """
      Retweet and exit
      """
      print "I have tweeted: "+rt.encode('utf8')
      print "Result of my re-tweeting: " + str(gae_twitter.update(rt.encode('utf8')))
      exit()

# overriding API __init__
twitter.Api.__init__ = twitter_api_init_gae

# Start to run
run(BOT_USERNAME, BOT_PASSWORD, SEARCH_TERM)




*使い方(READMEから一部引用)
This bot runs in the following ways.

1. Search tweets using 'search_term' in Twitter.

2. Re-tweet the tweets.


HOW TO SETUP:
1. Register your OAuth client on Twitter
URL: http://twitter.com/oauth_clients
* you MUST choose 'client' for Simple Twitter Bot.

2. Run 'python register_pin.py' and
use CONSUMER_KEY and CONSUMER_SECRET you got from the registeration.

3. Change setting variables(e.g. CONSUMER_KEY, CONSUMER_SECRET) in main.py

4. Run Google App Engine dev_server and visit the following URL
URL: http://localhost:8080/cron/update
* If you finish all of your setting, set debug_flag in main.py off.

5. Done!

Enjoy developing your own twitter bot!

*他、ソースコード一式

*使ったもの
- App Engine Twitter
- python-twitter
- oauth-python-twitter
- Google App Engine

*参考にさせて頂いたサイト

0 件のコメント: