I need to get the tweets from a single user in a streaming format. However, it still displays all tweets that retweet this user or are a reply to the tweets.
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)
I don't know what I'm doing wrong but I feel like the on_status command does not work at all.
Thanks for your help!
Don't change the parameters for on_status
. Your accounts
variable is a global variable and you should use it as such. Also, status.user.id_str
is a str
but accounts
is a List[str]
. You need the not ... in ...
operators as opposed to !=
. In other words, try out the changes below:
def on_status(self, status):
if not status.user.id_str in accounts:
return
print(status.text)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.