python - 几个小时后 tweepy 停止

标签 python twitter tweepy twitter-streaming-api

我使用 tweepy 来流式传输一些推文。这是我的程序:

import tweepy
import json

consumer_key = "***" 
consumer_secret = "***"
access_token_key="***"
access_token_secret="***"

auth1 = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth1.set_access_token(access_token_key, access_token_secret)
api = tweepy.API(auth1)

class StreamListener(tweepy.StreamListener):
    def on_status(self, status):
        try:
            print status.text
        except Exception, e:
            print 'Encountered Exception Tweet:', e
            pass
        return True

    def on_error(self, status_code):
        print 'Encountered error with status code:' + repr(status_code)
        return True 

    def on_data(self, data):
        if 'in_reply_to_status_id' in data:
            status = tweepy.Status.parse(self.api, json.loads(data))
            if self.on_status(status) is False:
                return True
        elif 'delete' in data:
            delete = json.loads(data)['delete']['status']
            if self.on_delete(delete['id'], delete['user_id']) is False:
                return True
        elif 'limit' in data:
            if self.on_limit(json.loads(data)['limit']['track']) is False:
                return True
        return True

    def on_timeout(self):
        print 'Timeout...'
        return True

l = StreamListener()
streamer = tweepy.Stream(auth=auth1, listener=l, timeout=36000000)

setTerms = ['enbrel']
streamer.filter(follow=None,track = setTerms)

两三个小时后,此过程停止。没有信号错误、超时等。只是没有收到更多推文。我哪里做错了?

最佳答案

尝试在您的类中添加一个on_disconnect 方法。可能是 Twitter 断开了你的连接(不是错误,也不是超时)而你没有处理这个问题。如果愿意,您可以以不同的方式处理不同的 Twitter 错误。

def on_disconnect(self, notice):
    """Called when twitter sends a disconnect notice

    Disconnect codes are listed here:
    https://dev.twitter.com/docs/streaming-apis/messages#Disconnect_messages_disconnect
    """
    return

查看 streaming module的 tweepy 了解更多信息。

您还可以尝试在您的 streamer.filter() 中启用停顿警告。以下是来自 Tweepy 源的所有选项及其默认值:

def filter(self, follow=None, track=None, async=False, locations=None,
           stall_warnings=False, languages=None, encoding='utf8'):

关于python - 几个小时后 tweepy 停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14177327/

相关文章:

Spring Social Twitter 通过推文 id 搜索?

iphone - Twitter + oAuth 噩梦

python - DtypeWarning : Columns (15, 16,18,24) 有混合类型。如果列具有混合类型,则会被删除

Python 正则表达式将列表解析为文本以进行响应

python - 在python中获取两个一维数组的乘积

ios - 在 iOS 5 模拟器中使用 TWeet Compose ViewController 时如何知道设置按钮点击?

python-2.7 - 如何使用 tweepy.Cursor 和 api.search 从 Tweepy 中提取 Hashtags?

python - tweepy.TweepError 超出速率限制

python - tweepy 如何从 id 获取用户名

python - 箱线图按 python pandas 中的列分层