因为我想提出一个几乎完全的解决方案。以下是我的版本:#!/usr/bin/env python
import sys
import json
import datetime
from twython import TwythonStreamer
from circuits import Component, Event, Debugger, Timer
APP_KEY = 'XX'
APP_SECRET = 'XX'
OAUTH_TOKEN = 'XX'
OAUTH_TOKEN_SECRET = 'XX'
class MyStreamer(TwythonStreamer):
def on_success(self, data):
print data['text']
with open('scratch1.json', 'ab') as outfile:
json.dump(data, outfile, indent=4)
with open('scratch2.json', 'ab') as xoutfile:
json.dump(data, xoutfile, indent=4)
return
def on_error(self, status_code, data):
print status_code
return True # Don't kill the stream
def on_timeout(self):
print >> sys.stderr, 'Timeout...'
return True # Don't kill the stream
class Check(Event):
"""Check Event"""
class Terminate(Event):
"""Terminate Event"""
class App(Component):
def init(self, *args, **kwargs):
self.stream = MyStreamer(
APP_KEY, APP_SECRET,
OAUTH_TOKEN, OAUTH_TOKEN_SECRET
)
interval = datetime.datetime.now() + datetime.timedelta(hours=1)
Timer(interval, Terminate(), self.channel).register(self)
Timer(10, Check(), persist=True, channel=self.channel).register(self)
def terminate(self):
raise SystemExit(0)
def check(self):
self.stream.statuses.filter(follow=[95995660, 8820362])
app = App()
Debugger().register(app)
app.run()
这将为您的解决方案添加一个名为circuits的附加库/框架,它是功能强大的事件处理和内置Timer组件。在
注意:我没有测试过这个。我将由您决定,因为我没有特别使用twythontwiter客户机库,也没有使用它的任何API。祝你好运!在
另外请注意,我假设您不想连续检查流,因为Twitter API可能有某种trhottling限制。因此第二个计时器将每隔10秒触发一个Check事件,并在运行应用程序的生命周期内持续存在。在