Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import Keys # Import keys file which contains access tokens and API keys
- from tweepy.streaming import StreamListener # From tweepy module in its streaming class import the stream Listener. This will listen for incoming tweets
- from tweepy import OAuthHandler # From tweepy import the authentication handler, this will handle the authentication process
- from tweepy import Stream # This will handle the incoming stream of tweets
- import json
- class StdOutListener(StreamListener): # Class that Inherits from the StreamListener class
- def __init__(self, filename):
- self.filename = filename
- def on_data(self,data): # Overriding On_data method to print the data variable that is passed in from the incoming tweets
- try:
- print(data) # Print tweet
- with open(self.filename, "a") as tf:
- tf.write(data)
- return True # Return true to ensure that the method isnt executed multiple times and that we can use this method for conditional statements
- except BaseException as e:
- print("ERROR AT READ %s" % str(e))
- def on_error(self,status): # Same process as on data except for this we are using this overriden method to check for errors
- print(status)
- return True
- class TwitterStreamer(StdOutListener): # This class inherits from the stdoutlistener. This class is to get the tweets
- def stream_tweets(self, filename, hashtags):
- auth = OAuthHandler(Keys.API_KEY, Keys.API_SECRET_KEY) # AUTHORISATION
- auth.set_access_token(Keys.ACCESS_TOKEN, Keys.ACCESS_TOKEN_SECRET)
- listener = StdOutListener(self.filename) # Constructor is filename
- stream = Stream(auth,
- listener) # Pass through our auth and object so we can tell the twitter API "Hello i want to access data and here is how I want to do it"
- stream.filter(track=hashtags, is_async=True) # Filter tweets by search term (hashtag)
- """print(json.dumps(parsed, indent=4, sort_keys=True))
- """
- def JGAF(filename):
- filename = filename
- with open(filename) as t:
- data = json.load(t)
- data = json.dumps(data, indent=4, sort_keys=True)
- return data
- """
- """
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement