-
-
Save zeddee/c7e550e4c1bc83a31e88b7836d17c629 to your computer and use it in GitHub Desktop.
Here I define a Tweet listener that creates a file called 'tweets.txt', collects streaming tweets as .jsons and writes them to the file 'tweets.txt'; once 100 tweets have been streamed, the listener closes the file and stops listening.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# forked from hugobowne/tweet_listener.py | |
class MyStreamListener(tweepy.StreamListener): | |
""" | |
Inheriting tweepy.StreamListener object class | |
Appears like we're doing this to add the | |
self.num_tweets and self.file attributes | |
to the initialization operator. | |
"""" | |
def __init__(self, api=None): | |
# super() allows us to access the superclass | |
# This is the Python 2 syntax for accessing super | |
# super(this_class,self).__init__() | |
# Python 3 syntax allows you to | |
super(MyStreamListener, self).__init__() | |
self.num_tweets = 0 | |
self.file = open("tweets.txt", "w") | |
# Modify SteamListener.on_status method | |
# | |
def on_status(self, status): | |
"""Called when a new status arrives""" | |
tweet = status._json | |
self.file.write( json.dumps(tweet) + '\n' ) | |
self.num_tweets += 1 | |
if self.num_tweets < 100: | |
return True | |
else: | |
return False | |
self.file.close() | |
def on_error(self, status): | |
"""Called when a non-200 status code is returned""" | |
print(status) | |
""" | |
methods from tweepy.StreamListener object class: | |
on_connect(self) | |
on_data(self, raw_data) | |
keep_alive(self): Called when a keep-alive arrived | |
on_status(self, status): Called when a new status arrives | |
on_exception(self, exception): Called when an unhandled exception occurs. | |
on_delete(self, status_id, user_id): Called when a delete notice arrives for a status | |
on_event(self, status): Called when a new event arrives | |
on_direct_message(self, status): Called when a new direct message arrives | |
on_friends(self, friends): Called when a friends list arrives. friends is a list that contains user_id | |
on_limit(self, track): Called when a limitation notice arrives | |
on_error(self, status_code): Called when a non-200 status code is returned | |
on_timeout(self): Called when stream connection times out | |
on_disconnect(self, notice): Called when twitter sends a disconnect notice. Disconnect codes are listed here: https://dev.twitter.com/docs/streaming-apis/messages Disconnect_messages_disconnect | |
on_warning(self, notice): Called when a disconnection warning message arrives | |
""" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment