首页 > 解决方案 > 仅使用 Twitter 流 API 显示来自单个用户的推文

问题描述

我需要以流格式从单个用户那里获取推文。但是,它仍会显示所有转推此用户或回复推文的推文。

topic = "tweets"
accounts = ['user_id1', 'user_id2']

class TwitterStreamer():

    def __init__(self):
        pass

    def stream_tweets(self, topic, accounts):
        listener = StreamListener(topic)
        auth = tweepy.OAuthHandler(api_key, api_secret_key)
        auth.set_access_token(access_token, access_secret_token)
        stream = tweepy.Stream(auth, listener)
        stream.filter(follow=accounts)


class StreamListener(tweepy.StreamListener):
        
    def __init__(self, file_prefix):
        self.prefix = file_prefix
    
    @property
    def fetched_tweets_filename(self):
        topic
        date = datetime.datetime.now().strftime("%Y-%m-%d")
        return f"{self.prefix}_{date}.txt"    
    
    def on_data(self, data):
        try:
            print(data)
            
            with open(self.fetched_tweets_filename, 'a') as tf:
                tf.write(data)
            return True
        except BaseException as e:
            print("Error on_data %s" % str(e))
        return True
        
    def on_exception(self, exception):
        print('exception', exception)
        stream_tweets(topic, accounts)       

    def on_status(self, accounts, status):
        if status.user.id_str != accounts: 
            return
        print(status.text) 

def stream_tweets(topic, accounts):
    listener = StreamListener(topic)
    auth = tweepy.OAuthHandler(api_key, api_secret_key)
    auth.set_access_token(access_token, access_secret_token)
    stream = tweepy.Stream(auth, listener)
    stream.filter(track=accounts)   

if __name__ == '__main__':
    twitter_streamer = TwitterStreamer()
    twitter_streamer.stream_tweets(topic, accounts)

我不知道我做错了什么,但我觉得 on_status 命令根本不起作用。

谢谢你的帮助!

标签: pythonpython-3.xtwittertwitter-streaming-apitwitterapi-python

解决方案


不要更改 的参数on_status。你的accounts变量是一个全局变量,你应该这样使用它。此外,status.user.id_stris a strbut accountsis a List[str]。您需要not ... in ...运算符而不是!=. 换句话说,请尝试以下更改:

def on_status(self, status):
    if not status.user.id_str in accounts: 
        return
    print(status.text) 

推荐阅读