from __future__ import absolute_import, print_function from tweepy.streaming import StreamListener from tweepy import OAuthHandler from tweepy import Stream import json import sys class RetweetListener(StreamListener): """ Handles tweets that are received from the stream. Prints json to stdout Adapted from: https://github.com/tweepy/tweepy/blob/master/examples/streaming.py """ def __init__(self, user): self._id_str = user super().__init__() @property def source_id(self): """Not used currently""" return self._id_str def on_data(self, data): """Print retweets""" try: tweet, rt = self._process_data(data) json.dump(tweet, sys.stdout) print('\n', file=sys.stdout) return True except: return True def on_error(self, status): print(status) def _process_data(self, data): tweet = json.loads(data) retweet_of = tweet.pop('retweeted_status') return tweet, retweet_of['id_str'] if __name__ == '__main__': """Follow a user via the streaming API the follow parameter gets a lot of info: https://dev.twitter.com/streaming/overview/request-parameters#follow run like: python stream_listener.py USER_ID > data.txt """ user = sys.argv[1] with open('.creds.json', 'r') as f: # Go to http://apps.twitter.com and create an app. # The consumer key and secret will be generated for you then you will be # redirected to your app's page. Create an access token under the the # "Your access token" section. # Store these, in a file named .creds.json with the format below # { # "consumer_key": "xxxxxxxxxxxxxxxxxxxxxx", # "consumer_secret": "yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy", # "access_token": "yyyyyy-zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz", # "access_token_secret": "kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk" # } creds = json.load(f) auth = OAuthHandler(creds['consumer_key'], creds['consumer_secret']) auth.set_access_token(creds['access_token'], creds['access_token_secret']) l = RetweetListener(user) stream = Stream(auth, l) stream.filter(follow=[user])