【发布时间】: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