-
Notifications
You must be signed in to change notification settings - Fork 0
/
tweepy_streamer.py
45 lines (34 loc) · 1.36 KB
/
tweepy_streamer.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream
import twitter_credentials
#Streams and processes live tweets
class TwitterStreamer():
def stream_tweets(self, filename, hashtag_list):
#Twitter auth and connecting to Twitter Streaming API
listener =StdOutListener(filename)
auth = OAuthHandler(twitter_credentials.CONSUMER_KEY, twitter_credentials.CONSUMER_SECRET)
auth.set_access_token(twitter_credentials.ACCESS_TOKEN, twitter_credentials.ACCESS_TOKEN_SECRET)
stream = Stream(auth, listener)
stream.filter(track=hashtag_list)
#Basic listener that just prints received tweets
class StdOutListener(StreamListener):
def __init__(self, filename):
self.filename = filename
#takes data streamed from the StreamListener
def on_data(self, data):
try:
print(data)
with open(self.filename, 'a') as tf:
tf.write(data + ',')
return True
except BaseException as e:
print("Error on data: %s " % str(e))
return True
def on_error(self, status):
print(status)
if __name__ == "__main__":
hashtag_list = ['donald trump', 'barack obama']
filename = "tweets2.json"
twitterStreamer = TwitterStreamer()
twitterStreamer.stream_tweets(filename, hashtag_list)