私はtweepyを使用して Twitter API にアクセスし、それらが提供するパブリック ストリームをリッスンします。これは、すべてのツイートの 1% のサンプルである必要があります。これが私が自分で使用するサンプルコードです。ストリーミングには引き続き基本的な認証メカニズムを使用できますが、すぐに変更される可能性があります。それに応じて USERNAME 変数と PASSWORD 変数を変更し、Twitter が返すエラー コードを尊重するようにしてください (このサンプル コードは、場合によっては Twitter が必要とする指数バックオフ メカニズムを尊重していない可能性があります)。
import tweepy
import time
def log_error(msg):
timestamp = time.strftime('%Y%m%d:%H%M:%S')
sys.stderr.write("%s: %s\n" % (timestamp,msg))
class StreamWatcherListener(tweepy.StreamListener):
def on_status(self, status):
print status.text.encode('utf-8')
def on_error(self, status_code):
log_error("Status code: %s." % status_code)
time.sleep(3)
return True # keep stream alive
def on_timeout(self):
log_error("Timeout.")
def main():
auth = tweepy.BasicAuthHandler(USERNAME, PASSWORD)
listener = StreamWatcherListener()
stream = tweepy.Stream(auth, listener)
stream.sample()
if __name__ == '__main__':
try:
main()
except KeyboardInterrupt:
break
except Exception,e:
log_error("Exception: %s" % str(e))
time.sleep(3)
ソケット モジュールのタイムアウトも設定しました。Python のデフォルトのタイムアウト動作に問題があると思われるので、注意してください。
import socket
socket.setdefaulttimeout(timeout)