Tweepy. Make stream run forever

烈酒焚心 提交于 2019-12-05 20:29:50

Here's how I do mine and it's been running for almost a year, on two computers to handle the errors that stop the stream here and there.

#They don't need to be in the loop.
auth = OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)

while True:
    listener = TweetStreamListener()
    stream = Stream(auth, listener, timeout=60)

    try:
        stream.userstream()

    except Exception, e:
        print "Error. Restarting Stream.... Error: "
        print e.__doc__
        print e.message

To make sure that it runs forever, you should redefine the on_error method to handle the time between reconnection attempts. Your 5 seconds sleeping will hinder your chances to a successful reconnect because Twitter will see that you tried to do it too frequently. But that's another question.

Just my two cents.

I received lots of Error 420, which was weird because I didn't ask for too much keywords to the stream API.

So I figured out that the on_data() method of the stream listener class must always return True.

Mine returned False sometimes, so tweepy cut the connection, and recreate it directly as it was in a loop, twitter didn't like it much...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!