forked from seandolinar/Twitter-Tutorial
-
Notifications
You must be signed in to change notification settings - Fork 0
/
twitter_streamListener.py
executable file
·80 lines (49 loc) · 1.54 KB
/
twitter_streamListener.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
'''
Twitter Stream Listener
'''
# tweepy setup
import time
from tweepy import Stream
from tweepy import OAuthHandler
from tweepy.streaming import StreamListener
import io
import os
import json
# twitter OAuth
ckey = '*CONSUMER KEY*'
consumer_secret = '*CONSUMER SECRET*'
access_token_key = '*ACCESS TOKEN*'
access_token_secret = '*ACCESS SECRET*'
#Listener Class Override
class listener(StreamListener):
def __init__(self, start_time, time_limit=60):
self.time = start_time
self.limit = time_limit
self.tweet_data = []
def on_data(self, data):
saveFile = io.open('raw_tweets.json', 'a', encoding='utf-8')
while (time.time() - self.time) < self.limit:
try:
self.tweet_data.append(data)
return True
except BaseException, e:
print 'failed ondata,', str(e)
time.sleep(5)
pass
saveFile = io.open('raw_tweets.json', 'w', encoding='utf-8')
saveFile.write(u'[\n')
saveFile.write(','.join(self.tweet_data))
saveFile.write(u'\n]')
saveFile.close()
exit()
def on_error(self, status):
print status
def on_disconnect(self, notice):
print 'bye'
#Beginning of the specific code
start_time = time.time() #grabs the system time
keyword_list = ['emoji'] #track list
auth = OAuthHandler(ckey, consumer_secret) #OAuth object
auth.set_access_token(access_token_key, access_token_secret)
twitterStream = Stream(auth, listener(start_time, time_limit=200)) #initialize Stream object with a time out limit
twitterStream.filter(track=keyword_list, languages=['en']) #call the filter method to run the Stream Listener