Advertisement
Guest User

Untitled

a guest
Mar 30th, 2020
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.23 KB | None | 0 0
  1. import Keys  # Import keys file which contains access tokens and API keys
  2. from tweepy.streaming import StreamListener  # From tweepy module in its streaming class import the stream Listener. This will listen for incoming tweets
  3. from tweepy import OAuthHandler  # From tweepy import the authentication handler, this will handle the authentication process
  4. from tweepy import Stream  # This will handle the incoming stream of tweets
  5. import json
  6.  
  7.  
  8. class StdOutListener(StreamListener):  # Class that Inherits from the StreamListener class
  9.  
  10.     def __init__(self, filename):
  11.         self.filename = filename
  12.  
  13.     def on_data(self,data):  # Overriding On_data method to print the data variable that is passed in from the incoming tweets
  14.         try:
  15.             print(data)  # Print tweet
  16.  
  17.             with open(self.filename, "a") as tf:
  18.                 tf.write(data)
  19.  
  20.             return True  # Return true to ensure that the method isnt executed multiple times and that we can use this method for conditional statements
  21.  
  22.         except BaseException as e:
  23.             print("ERROR AT READ %s" % str(e))
  24.  
  25.     def on_error(self,status):  # Same process as on data except for this we are using this overriden method to check for errors
  26.         print(status)
  27.         return True
  28.  
  29.  
  30. class TwitterStreamer(StdOutListener):  # This class inherits from the stdoutlistener. This class is to get the tweets
  31.  
  32.     def stream_tweets(self, filename, hashtags):
  33.        
  34.         auth = OAuthHandler(Keys.API_KEY, Keys.API_SECRET_KEY)  # AUTHORISATION
  35.         auth.set_access_token(Keys.ACCESS_TOKEN, Keys.ACCESS_TOKEN_SECRET)
  36.         listener = StdOutListener(self.filename)  # Constructor is filename
  37.         stream = Stream(auth,
  38.                         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"
  39.         stream.filter(track=hashtags, is_async=True)  # Filter tweets by search term (hashtag)
  40.  
  41.  
  42. """print(json.dumps(parsed, indent=4, sort_keys=True))
  43.  
  44.  
  45.  
  46. """
  47.  
  48. def JGAF(filename):
  49.     filename = filename
  50.  
  51.     with open(filename) as t:
  52.         data = json.load(t)
  53.         data = json.dumps(data, indent=4, sort_keys=True)
  54.     return data
  55.  
  56. """
  57.  
  58. """
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement