-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtwStream.py
296 lines (259 loc) · 10.3 KB
/
twStream.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'user'
import os
import json
import HTMLParser
import logging
import re
from threading import Timer
import time
# encoding=utf8
import sys
reload(sys)
sys.setdefaultencoding('utf8')
from sys import exit
from datetime import datetime
# Import the necessary methods from tweepy library
from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream
#import polyglot
from polyglot.text import Text, Word
import urlparse
import psycopg2
from psycopg2.extras import Json
if "NJSAGENT_APPROOT" in os.environ:
approot = os.getenv('NJSAGENT_APPROOT', "") + "/logs"
else:
approot = os.path.dirname(os.path.realpath(__file__))
logfile = approot + "/" + os.path.basename(__file__) + ".log"
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
datefmt='%m-%d %H:%M',
filename=logfile)
# define a Handler which writes INFO messages or higher to the sys.stderr
console = logging.StreamHandler()
console.setLevel(logging.ERROR)
# set a format which is simpler for console use
formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
# tell the handler to use this format
console.setFormatter(formatter)
# add the handler to the root logger
logging.getLogger('').addHandler(console)
log = logging.getLogger('')
if not "NJSAGENT_APPROOT" in os.environ:
log.warning("Missing NJSAGENT_APPROOT environment variable")
exit(1)
conn = ''
cur = ''
countries = {}
sources = {}
terms = {}
recieved = 0
found = 0
lastdata = datetime.now()
inserted = []
class RepeatedTimer(object):
def __init__(self, interval, function, *args, **kwargs):
self._timer = None
self.interval = interval
self.function = function
self.args = args
self.kwargs = kwargs
self.is_running = False
self.start()
def _run(self):
self.is_running = False
self.start()
self.function(*self.args, **self.kwargs)
def start(self):
if not self.is_running:
self._timer = Timer(self.interval, self._run)
self._timer.start()
self.is_running = True
def stop(self):
self._timer.cancel()
self.is_running = False
def report():
log.info("Recieved " + str(recieved) + " found " + str(found))
def check_inactive():
diff = datetime.now() - lastdata
total_seconds = diff.seconds
if total_seconds > (60 * 15):
log.warn("Stream idle: Lastdata recieved " + lastdata.strftime("%Y-%m-%d %H:%M:%S.%f") + " now " + datetime.now() + " diff" + str(total_seconds))
exit(1)
# This is a basic listener that just prints received tweets to stdout.
class StdOutListener(StreamListener):
def on_data(self, data):
global recieved, found, lastdata, inserted
recieved += 1
lastdata = datetime.now()
try:
tweet = json.loads(data)
try:
userid = tweet['user']['id_str']
if userid in sources:
print self.is_valid_content(tweet)
if self.is_valid_content(tweet):
if not tweet['id_str'] in inserted:
found += 1
self.save_tweet(tweet)
except KeyError, AssertionError:
pass
except Exception, e:
log.exception(str(e))
log.warning('Bad tweet json' + data)
return True
def on_error(self, status):
log.error(status)
return False
def is_valid_content(self, tweet):
if sources[tweet['user']['id_str']]["filter"] == "false":
return True
try:
h = HTMLParser.HTMLParser()
t = h.unescape(tweet["text"])
tokens = Text(t).words
country = sources[tweet['user']['id_str']]["country"]
country_terms = countries[country]
except Exception, e:
log.warning("Problem tokenizing " + tweet["text"] + " " + str(e))
return False
for token in tokens:
for country_term in country_terms:
if token.strip().lower() == country_term.strip().lower():
return True
return False
def save_tweet(self, tweet):
global inserted
today = datetime.utcnow().strftime('%Y-%m-%d')
country = sources[tweet['user']['id_str']]["country"]
try:
sql = "INSERT INTO countrydata (date) SELECT %s WHERE NOT EXISTS (SELECT 1 FROM countrydata WHERE date::date = %s)"
cur.execute(sql, [today, today])
try:
sql = "SELECT " + country + " FROM countrydata WHERE date::date = %s FOR UPDATE"
cur.execute(sql, [today])
dbdata = cur.fetchone()[0]
if not "tweets" in dbdata:
dbdata["tweets"] = []
if not self.isindb(dbdata, tweet):
try:
newdbdata = dbdata
newdbdata["tweets"].append(tweet)
sql = "UPDATE countrydata SET " + country + " = (%s) WHERE date::date = %s"
cur.execute(sql, [Json(newdbdata), today])
inserted.append(tweet['id_str'])
log.debug("Added tweet from " + tweet["user"]["name"] + " to " + country)
except psycopg2.Error as e:
log.warning("Cannot update because " + e.pgerror)
except Exception as e:
print(e)
except psycopg2.Error as e:
log.warning("Cannot select date because " + e.pgerror)
except psycopg2.Error as e:
log.warning("Cannot insert date because " + e.pgerror)
def isindb(self, dbdata, tweet):
for dbtweet in dbdata['tweets']:
if dbtweet['id_str'] == tweet['id_str']:
return True
return False
def main():
global conn, cur
if not "TWCOLLECTOR_PGSQL" in os.environ:
log.warning("Missing TWCOLLECTOR_PGSQL environment variable")
exit(1)
if not "TWCOLLECTOR_TWITTER_ACCESS_TOKEN_KEY" in os.environ:
log.warning("Missing TWCOLLECTOR_TWITTER_ACCESS_TOKEN_KEY environment variable")
exit(1)
if not "TWCOLLECTOR_TWITTER_ACCESS_TOKEN_SECRET" in os.environ:
log.warning("Missing TWCOLLECTOR_TWITTER_ACCESS_TOKEN_SECRET environment variable")
exit(1)
if not "TWCOLLECTOR_TWITTER_CONSUMER_KEY" in os.environ:
log.warning("Missing TWCOLLECTOR_TWITTER_CONSUMER_KEY environment variable")
exit(1)
if not "TWCOLLECTOR_TWITTER_CONSUMER_SECRET" in os.environ:
log.warning("Missing TWCOLLECTOR_TWITTER_CONSUMER_SECRET environment variable")
exit(1)
if not "TWCOLLECTOR_SOURCE" in os.environ:
log.warning("Missing TWCOLLECTOR_SOURCE environment variable")
exit(1)
if not "TWCOLLECTOR_MODE" in os.environ:
log.warning("Missing TWCOLLECTOR_MODE environment variable")
exit(1)
pgsql = os.getenv('TWCOLLECTOR_PGSQL', '')
# Variables that contains the user credentials to access Twitter API
access_token = os.getenv('TWCOLLECTOR_TWITTER_ACCESS_TOKEN_KEY', '')
access_token_secret = os.getenv('TWCOLLECTOR_TWITTER_ACCESS_TOKEN_SECRET', '')
consumer_key = os.getenv('TWCOLLECTOR_TWITTER_CONSUMER_KEY', '')
consumer_secret = os.getenv('TWCOLLECTOR_TWITTER_CONSUMER_SECRET', '')
target = os.getenv('TWCOLLECTOR_SOURCE', '')
mode = os.getenv('TWCOLLECTOR_MODE', '')
with open(os.path.dirname(os.path.realpath(__file__)) + "/" + target) as json_file:
json_data = json.load(json_file)
for country in json_data["tracks"]:
countries[country["country"]] = [x.strip() for x in country["track"].split(',')]
trm = [x.strip() for x in country["track"].split(',')]
for term in trm:
if term != '':
terms[term] = term
for general in json_data["general"]:
countries[country["country"]].append(general.strip())
terms[general.strip()] = general.strip()
for source in country["sources"]:
sourcedata = {}
sourcedata["country"] = country["country"].strip()
if "filter" in source:
sourcedata["filter"] = source["filter"]
else:
print "Invalid filter for source id: " + source["data-user-id"]
sourcedata["filter"] = "true"
sources[source["data-user-id"].strip()] = sourcedata
if mode == "track":
termslist = terms.keys()
termslist.sort()
parameters = ','.join(termslist)
else:
accountslist = sources.keys()
accountslist.sort()
parameters = ','.join(accountslist)
log.info("Started in mode {0} target {1} parameters {2}".format(mode, target, parameters))
try:
urlparse.uses_netloc.append('postgres')
url = urlparse.urlparse(pgsql)
conn = psycopg2.connect(
"dbname=%s user=%s password=%s host=%s " % (url.path[1:], url.username, url.password, url.hostname))
conn.autocommit = True
cur = conn.cursor()
except psycopg2.Error as e:
log.error("I am unable to connect to the database because " + e.pgerror)
exit(1)
# This handles Twitter authetification and the connection to Twitter Streaming API
l = StdOutListener()
auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
stream = Stream(auth, l)
# This line filter Twitter Streams to capture data by the keywords
if mode == "track":
stream.filter(track=[x.strip() for x in parameters.split(',')])
else:
stream.filter(follow=[x.strip() for x in parameters.split(',')])
if __name__ == '__main__':
try:
rt = RepeatedTimer(60 * 10, report) # it auto-starts, no need of rt.start()
ia = RepeatedTimer(60, check_inactive)
main()
except KeyboardInterrupt:
logging.shutdown()
print '\nGoodbye!'
exit()
except Exception, e:
log.exception(str(e))
logging.shutdown()
finally:
rt.stop() # better in a try/finally block to make sure the program ends!
ia.stop()
time.sleep(60)
log.warn("Exiting")
exit(1)