【问题标题】:Only display tweets from a single user using Twitter Streaming API仅使用 Twitter 流 API 显示来自单个用户的推文
【发布时间】:2021-11-19 15:48:48
【问题描述】:

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

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 命令根本不起作用。

感谢您的帮助!

【问题讨论】:

  • 会不会返回结果是一个列表?代码中也看不到on_status方法的任何用途。
  • 可能切换到 v4.1.0? StreamListener 自 v4.0.0 起已合并到 Stream(请参阅更新日志:docs.tweepy.org/en/latest/changelog.html)。

标签: python python-3.x twitter twitter-streaming-api twitterapi-python


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2021-11-17
    • 2014-01-18
    • 2023-03-18
    • 1970-01-01
    • 2011-04-18
    • 2021-09-20
    • 1970-01-01
    • 2013-08-19
    • 2013-06-06
    相关资源
    最近更新 更多