Last active
December 17, 2016 05:43
-
-
Save meisheep/57c8119fedfce4ad8cef1bfd234a0359 to your computer and use it in GitHub Desktop.
Tweepy Stream
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
import json | |
import atexit | |
import tweepy | |
from tweepy import Stream | |
from tweepy import OAuthHandler | |
from tweepy.streaming import StreamListener | |
def exit_handler(): | |
with open('tweets.json') as f: | |
content = f.readlines() | |
content_comma = ','.join(content) | |
file = open('tweets.json', 'w') | |
file.write('[' + content_comma + ']') | |
file.close() | |
atexit.register(exit_handler) | |
consumer_key = 'CONSUMER-KEY' | |
consumer_secret = 'CONSUMER-SECRET' | |
access_token = 'ACCESS-TOKEN' | |
access_secret = 'ACCESS-SECRET' | |
auth = OAuthHandler(consumer_key, consumer_secret) | |
auth.set_access_token(access_token, access_secret) | |
api = tweepy.API(auth) | |
class MyListener(StreamListener): | |
def on_data(self, data): | |
try: | |
with open('tweets.json', 'a') as f: | |
f.write(data) | |
return True | |
except BaseException as e: | |
print('Error on_data: %s' % str(e)) | |
return True | |
def on_error(self, status): | |
print(status) | |
return True | |
twitter_stream = Stream(auth, MyListener()) | |
twitter_stream.filter(languages=['en'], track=['a', 'the', 'i', 'you', 'u']) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment