-
Notifications
You must be signed in to change notification settings - Fork 0
/
harvester.py
226 lines (182 loc) · 7.34 KB
/
harvester.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
import tweepy
import json
import time
import os
import sys
import commands
import datetime
from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
# This is if we're running on none debian systems
try:
import apt
cache = apt.Cache()
if cache['zip'].is_installed == False:
print "\nERROR: zip pacakge not installed on this system, please install before proceeding."
exit(1)
except ImportError:
print "\nWARNING: apt module not available to python, this script will be unable to determine if zip is available.\nPlease be sure the zip package is installed on this system, otherwise archiving will fail."
# Give the user a moment to read this message
time.sleep(3)
class TweetHarvester(StreamListener):
strConsumerKey = ""
strConsumerSecret = ""
strAccessTokenKey = ""
strAccessTokenSecret = ""
bUseGzip = True
bPaused = False
iIncrementalCount = 0
def __init__(self):
self.loadConfiguration()
self.readCommandLineArgs()
def on_data(self, strData):
# TODO: threading
# import threading
# threading.Thread(self.storeTweets, (strData,)).start()
self.storeTweets(strData)
# Lets see if theres anything to archive
self.archiveFiles()
# TODO: At the top of every hour report how many tweets have been harvested
self.iIncrementalCount += 1
self.storeCounts()
return True
def on_error(self, strError):
# Log this to the error file
oToday = datetime.date.today()
strTodaysDate = oToday.strftime("%Y-%m-%d")
strFile = strTodaysDate + ".error"
oErrorFile = open(strFile, "a")
oErrorFile.write(time.strftime("%H:%M:%S") + ": " + str(strError) + "\n")
oErrorFile.close()
# Too many connections to the streaming API, returning false disconnects the stream
if strError == 420:
return False
def storeCounts(self):
# TODO: Create count file, this is dirty implementation
if os.path.exists('count') == False:
countFile = open('count', 'w')
iCurrentCount = 0
else:
countFile = open('count', 'r+')
iCurrentCount = countFile.read()
iNewCount = int(iCurrentCount) + self.iIncrementalCount
countFile.seek(0)
countFile.write(str(iNewCount))
countFile.truncate()
countFile.close()
self.iIncrementalCount = 0
# Read in command line parameters for things like output directory
def readCommandLineArgs(self):
foo = "bar"
def storeTweets(self, strTweets):
bReturn = "true"
oToday = datetime.date.today()
strTodaysDate = oToday.strftime("%Y-%m-%d")
# does a directory for today date exist yet?
# if not create one
if (os.path.exists("./" + strTodaysDate)) is False:
os.makedirs(strTodaysDate)
strFile = strTodaysDate + "/" + time.strftime("%H") + ".txt"
oTweetFile = open(strFile, "a")
# We're converting strTweets to a string to avoid exceptions, but but we should make sure whats passed in is an actual string
oTweetFile.write(str(strTweets))
oTweetFile.close()
def archiveFiles(self, strFileName=''):
# If no filename is passed in, lets set one
if strFileName == '':
# Lets determine the name of the last directory we created
oYesterday = datetime.date.today() - datetime.timedelta(days=1)
strFileToArchive = str(oYesterday.strftime("%Y-%m-%d"))
strFileName = strFileToArchive
strZipFileName = strFileName + '.zip'
strZipCommand = "zip -r " + strZipFileName + " " + strFileName
iZipCommandStatus, strZipCommandOutput = commands.getstatusoutput(strZipCommand)
# Check if the file exists first
strFileExistsCommand = "ls " + strFileName
iFileExistsCommandStatus, strExistsCommandOutput = commands.getstatusoutput(strFileExistsCommand)
# If the file exists, lets continue, otherwise, lets exit
if iFileExistsCommandStatus == 0:
# Run the zip command
if iZipCommandStatus != 0:
print "Something went wrong while compressing the " + strFileName + " directory"
print "\tThe following command was issued: `" + strZipCommand + "`"
print "\tThe following output was recieved: '" + strZipCommandOutput + "'"
else:
# If that succeeds lets remove the uncompressed version
print "Successfully archived '" + strFileName + "' to '" + strZipFileName + "'"
strDeleteOldFileCommand = "rm -rf " + strFileName
iRmCommandStatus, strRmCommandOutput = commands.getstatusoutput(strDeleteOldFileCommand)
if iRmCommandStatus != 0:
print "Something went wrong while deleting the " + strFileName + " directory"
print "\tThe following command was issued: `" + strDeleteOldFileCommand + "`"
print "\tThe following output was recieved: '" + strRmCommandOutput + "'"
else:
print "Successfully deleted uncompressed file '" + strFileName + "'"
# Put a sleep command in here to sleep this thread for 24 hours
# print "Archiver sleeping for 24 hours"
# time.sleep(86400)
def str2bool(self, bValue):
return bValue.lower() in ("yes", "true", "t", "1")
def loadConfiguration(self, strConfigurationFile=""):
# If no filename is passed in, lets default to defaultConfig.conf
if strConfigurationFile == "":
strConfigurationFile = 'defaultConfig.conf'
oConfigFile = open(strConfigurationFile)
oConfigData = json.load(oConfigFile)
self.strConsumerKey = oConfigData["consumer_key"]
self.strConsumerSecret = oConfigData["consumer_secret"]
self.strAccessTokenKey = oConfigData["access_token_key"]
self.strAccessTokenSecret = oConfigData["access_token_secret"]
self.bUseGzip = self.str2bool(oConfigData["use_gzip_compression"])
oConfigFile.close()
def getConsumerKey(self):
return self.strConsumerKey
def getConsumerSecret(self):
return self.strConsumerSecret
def getAccessTokenKey(self):
return self.strAccessTokenKey
def getAccessTokenSecret(self):
return self.strAccessTokenSecret
def getGZip(self):
return self.bUseGzip
oHarvester = TweetHarvester()
oAuth = tweepy.OAuthHandler(oHarvester.getConsumerKey(), oHarvester.getConsumerSecret())
oAuth.set_access_token(oHarvester.getAccessTokenKey(), oHarvester.getAccessTokenSecret())
oApi = tweepy.API(oAuth, compression=oHarvester.getGZip())
oStream = tweepy.Stream(oAuth, oHarvester)
oStream.filter(track=[
'nfl',
'broncos',
'patriots',
'seahawks',
'ravens',
'bengals',
'browns',
'steelers',
'bears',
'lions',
'packers',
'vikings',
'texans',
'colts',
'jaguars',
'titans',
'falcons',
'panthers',
'saints',
'buccaneers',
'bills',
'dolphins',
'jets',
'cowboys',
'giants',
'eagles',
'redskins',
'chiefs',
'raiders',
'chargers',
'cardinals',
'49ers',
'rams',
'superbowl'
], async=True)