-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathSimulatorGeneratorTwitter.py
executable file
·657 lines (558 loc) · 23 KB
/
SimulatorGeneratorTwitter.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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
#!/usr/bin/env python
# built-ins
import sys
import os
import ConfigParser
from xml.dom import minidom
import json
import random
import time
import datetime
import re
import traceback
import pickle
import sqlite3
import tempfile
import urllib
# site-packages
import requests
import prettytable
import inflection
# global constants
BASE_PATH = os.path.dirname(os.path.abspath( __file__ ))
CONFIG_PATH = os.path.join("config", "config.ini")
CREDENTIALS_PATH = os.path.join("config", "credentials.ini")
TWITTERGC_PATH = os.path.join("config", "twitter_global_config.json")
PERSIST_PATH = os.path.join("data", "persistence.sqlite3")
TWITTER_RESOURCES = "statuses,help,application,account,trends"
INNOCENCE_PATH = "http://bot-innocence.herokuapp.com/muted"
# local
sys.path.insert(0, os.path.join(BASE_PATH, "lib"))
import twitter
import titlecase
# package
import SimulatorGeneratorImage
# globals
config = None
creds = None
twitterApi = None
twitterGlobalConfig = None
persistenceConnection = None
persistence = None
def setup():
global creds
global config
global twitterApi
global twitterGlobalConfig
global persistenceConnection
global persistence
os.chdir(BASE_PATH)
random.seed()
for crucial in (CONFIG_PATH, CREDENTIALS_PATH):
if not os.path.exists(crucial):
sys.stderr.write("Couldn't load %s; exiting.\n" % (crucial))
config = ConfigParser.ConfigParser()
creds = ConfigParser.ConfigParser()
config.read(CONFIG_PATH)
creds.read(CREDENTIALS_PATH)
creatingDB = not os.path.exists(PERSIST_PATH)
persistenceConnection = sqlite3.connect(PERSIST_PATH)
persistence = persistenceConnection.cursor()
if (creatingDB):
persistence.execute("CREATE TABLE rateLimits (resource text unique, reset int, max int, remaining int)")
persistence.execute("CREATE TABLE intPrefs (name text unique, value int)")
persistence.execute("CREATE TABLE queuedRequests (tweet int unique, job text, user text)")
persistence.execute("CREATE TABLE failedRequests (tweet int unique, job text, user text)")
persistenceConnection.commit()
if (config.getint("services", "twitter_live") == 1):
consumer_key = creds.get("twitter", "consumer_key")
consumer_secret = creds.get("twitter", "consumer_secret")
access_token = creds.get("twitter", "access_token")
access_token_secret = creds.get("twitter", "access_token_secret")
twitterApi = twitter.Api(consumer_key, consumer_secret, access_token, access_token_secret)
# global config data
oneDayAgo = time.time() - 60*60*24
if (not os.path.exists(TWITTERGC_PATH) or os.path.getmtime(TWITTERGC_PATH) < oneDayAgo):
print("Getting configuration data from Twitter.")
# not checking twitter rate limits here since it will only get called once per day
twitterGlobalConfig = twitterApi.GetHelpConfiguration()
with open(TWITTERGC_PATH, "w") as tgcFile:
json.dump(twitterGlobalConfig, tgcFile)
else:
with open(TWITTERGC_PATH, "r") as tgcFile:
twitterGlobalConfig = json.load(tgcFile)
# install the rate limits
if creatingDB:
getTwitterRateLimits()
else:
# cached values will do in a pinch
with open(TWITTERGC_PATH, "r") as tgcFile:
twitterGlobalConfig = json.load(tgcFile)
def getTwitterRateLimits():
persistence.execute("SELECT resource FROM rateLimits")
existingResources = map(lambda x: x[0], persistence.fetchall())
# not checking twitter rate limits here since it will only gets called when
# one of the limits is ready to reset
limits = twitterApi.GetRateLimitStatus(TWITTER_RESOURCES)
for resourceGroup, resources in limits["resources"].items():
for resource, rateValues in resources.items():
if resource not in existingResources:
persistence.execute(
"INSERT INTO rateLimits VALUES (?, ?, ?, ?)",
[
resource,
int(rateValues["reset"]),
int(rateValues["limit"]),
int(rateValues["remaining"]),
]
)
else:
persistence.execute(
"UPDATE rateLimits SET reset=?, max=?, remaining=? WHERE resource=?",
[
int(rateValues["reset"]),
int(rateValues["limit"]),
int(rateValues["remaining"]),
resource,
]
)
persistenceConnection.commit()
defaults = [
("tweetHourlyReset", int(time.time()) + 60*60),
("tweetDailyReset", int(time.time()) + 60*60*24),
("tweetHourlyRemaining", config.getint("services", "twitter_hourly_limit")),
("tweetDailyRemaining", config.getint("services", "twitter_daily_limit")),
]
for default in defaults:
if getIntPref(default[0]) == -1:
setIntPref(default[0], default[1])
def getIntPref(name):
persistence.execute("SELECT value FROM intPrefs WHERE name=?", [name])
pref = persistence.fetchone()
if (pref == None):
return -1
return pref[0]
def setIntPref(name, value):
if getIntPref(name) == -1:
persistence.execute("INSERT INTO intPrefs VALUES (?, ?)", [name, value])
else:
persistence.execute("UPDATE intPrefs SET value=? WHERE name=?", [value, name])
persistenceConnection.commit()
def checkTwitterPostLimit():
currentTime = int(time.time())
hourlyReset = getIntPref("tweetHourlyReset")
if currentTime - hourlyReset > 0:
setIntPref("tweetHourlyReset", currentTime + 60*60)
setIntPref("tweetHourlyRemaining", config.getint("services", "twitter_hourly_limit"))
hourly = config.getint("services", "twitter_hourly_limit")
dailyReset = getIntPref("tweetDailyReset")
if currentTime - dailyReset > 0:
setIntPref("tweetDailyReset", currentTime + 60*60*24)
setIntPref("tweetDailyRemaining", config.getint("services", "twitter_daily_limit"))
hourly = getIntPref("tweetHourlyRemaining")
daily = getIntPref("tweetDailyRemaining")
if hourly > 0 and daily > 0:
return True
else:
return False
def useTweet():
for resource in ["tweetDailyRemaining", "tweetHourlyRemaining"]:
setIntPref(resource, getIntPref(resource) - 1)
def checkTwitterResource(resourceKey, proposedUsage=1):
persistence.execute("SELECT * FROM rateLimits WHERE resource=?", [resourceKey])
resourceData = persistence.fetchone()
if resourceData == None or int(time.time()) - resourceData[1] > 0:
getTwitterRateLimits()
persistence.execute("SELECT * FROM rateLimits WHERE resource=?", [resourceKey])
resourceData = persistence.fetchone()
if (resourceData == None):
sys.stderr.write("Invalid Twitter resource: %s\n" % (resourceKey))
return False
if (resourceData[3] - proposedUsage > 0):
return True
else:
return False
def useTwitterResource(resourceKey, usage=1):
persistence.execute("SELECT * FROM rateLimits WHERE resource=?", [resourceKey])
resourceData = persistence.fetchone()
if (resourceData == None):
sys.stderr.write("Invalid Twitter resource: %s\n" % (resourceKey))
return
newVal = resourceData[3] - usage
persistence.execute("UPDATE rateLimits SET reset=?, max=?, remaining=? WHERE resource=?",
[
resourceData[1],
resourceData[2],
newVal,
resourceKey,
]
)
persistenceConnection.commit()
return newVal
def getTrends():
location = config.getint("services", "twitter_trends_woeid")
trends = []
if (checkTwitterResource("/trends/place")):
trendsRaw = twitterApi.GetTrendsWoeid(location)
useTwitterResource("/trends/place")
for t in trendsRaw:
trends.append(t.name)
response = urllib.urlopen(INNOCENCE_PATH)
if response.getcode() == 200:
mutedTopics = json.loads(response.read())
trends = filter(lambda x: x not in mutedTopics, trends)
return trends
def shutdown():
if (persistence != None):
persistence.close()
def getRandomCBJobTitle():
# TODO: store off the category, don't repeat job titles, rotate categories
# http://api.careerbuilder.com/CategoryCodes.aspx
cb_apiKey = creds.get("careerbuilder", "apikey")
js_params = {
"DeveloperKey" : cb_apiKey,
"HostSite" : "US",
"OrderBy" : "Date",
}
cb_URL = "http://api.careerbuilder.com/v1/jobsearch?"
if (config.getint("services", "careerbuilder_live") == 1):
response = requests.get(cb_URL, params=js_params)
dom = minidom.parseString(response.content)
else:
with open(os.path.join("offline-samples", "careerbuilder-jobsearch.xml")) as jobFile:
dom = minidom.parse(jobFile)
jobs = []
for node in dom.getElementsByTagName("JobTitle"):
jobs.append(node.firstChild.nodeValue)
# NOTE: in the year 10,000 AD, this will need to be updated
maxLength = twitter.CHARACTER_LIMIT - (len(" Simulator ") + 4 + twitterGlobalConfig["characters_reserved_per_media"])
job = ""
count = 0
while (len(job) == 0 or len(job) > maxLength):
if (count >= 25):
# buncha really long job titles up in here
job = job[:maxLength-1] # (not great, but there are worse things)
break
job = random.choice(jobs)
count += 1
job = job.replace("'", "\\'").replace('"', '\\"')
print("%i iteration(s) found random job title: %s" % (count, job))
return job
def getRandomBLSJobTitle():
with open(os.path.join("data", "bls", "bls_normalized.txt")) as jobList:
jobs = map(str.rstrip, jobList.readlines())
job = ""
# NOTE: in the year 10,000 AD, this will need to be updated
maxLength = twitter.CHARACTER_LIMIT - (len(" Simulator ") + 4 + twitterGlobalConfig["characters_reserved_per_media"])
while (len(job) == 0 or len(job) > maxLength):
job = random.choice(jobs)
job = job.replace("'", "\\'").replace('"', '\\"')
return job
def tweet(job, year, artFile, respondingTo=None):
timestamp = datetime.datetime.now().strftime("%Y-%m-%d-%H%M.%f")
title = "%s Simulator %i" % (job, year)
userName = None
requestId = None
if (respondingTo != None):
userName = respondingTo[0]
requestId = respondingTo[1]
if not os.path.exists("archive"):
os.makedirs("archive")
if (artFile != None and os.path.exists(artFile)):
if (userName != None):
title = "@%s %s" % (userName, title)
posting = True
if config.getint("services", "twitter_live") == 0:
print("Twitter support is disabled; not posting.")
posting = False
elif config.getint("services", "actively_tweet") == 0:
print("Tweeting is turned off; not posting.")
posting = False
elif not checkTwitterPostLimit():
print("Over rate limit; not posting.")
posting = False
if posting:
useTweet()
print("Tweeting '%s' to Twitter with image: %s" % (title.encode("utf8"), artFile))
twitterApi.PostMedia(title, artFile, in_reply_to_status_id=requestId)
else:
print("Would have posted '%s' to Twitter with image: %s" % (title.encode("utf8"), artFile))
os.rename(artFile, os.path.join("archive", "output-%s.png" % timestamp))
with open(os.path.join("archive", "text-%s.txt" % timestamp), "w") as archFile:
archFile.write(title.encode('utf8'))
else:
# don't tweet; something's wrong.
sys.stderr.write("FAILURE: %s\n" % title.encode("utf8"))
with open(os.path.join("archive", "failed-%s.txt" % timestamp), "w") as archFile:
archFile.write(title.encode('utf8'))
def manualJobTweet(job, year=None):
image = SimulatorGeneratorImage.getImageFor(
job,
safeSearchLevel=config.get("services", "google_safesearch"),
referer="http://twitter.com/SimGenerator"
)
if (year == None):
year = random.randint(config.getint("settings", "minyear"), datetime.date.today().year)
artFile = "output-%s.png" % datetime.datetime.now().strftime("%Y-%m-%d-%H%M.%f")
artFile = os.path.join(tempfile.gettempdir(), artFile)
SimulatorGeneratorImage.createBoxArt(
job,
year,
image,
artFile,
maxSize=(
str(twitterGlobalConfig["photo_sizes"]["large"]["w"] - 1),
str(twitterGlobalConfig["photo_sizes"]["large"]["h"] - 1),
),
deleteInputFile=True
)
tweet(titlecase.titlecase(job), year, artFile)
def randomJobTweet(source="BLS"):
if source == "BLS":
job = getRandomBLSJobTitle()
elif source == "CB":
job = getRandomCBJobTitle()
image = SimulatorGeneratorImage.getImageFor(
job,
safeSearchLevel=config.get("services", "google_safesearch"),
referer="http://twitter.com/SimGenerator"
)
year = random.randint(config.getint("settings", "minyear"), datetime.date.today().year)
artFile = "output-%s.png" % datetime.datetime.now().strftime("%Y-%m-%d-%H%M.%f")
artFile = os.path.join(tempfile.gettempdir(), artFile)
SimulatorGeneratorImage.createBoxArt(
job,
year,
image,
artFile,
maxSize=(
str(twitterGlobalConfig["photo_sizes"]["large"]["w"] - 1),
str(twitterGlobalConfig["photo_sizes"]["large"]["h"] - 1),
),
deleteInputFile=True
)
tweet(titlecase.titlecase(job), year, artFile)
def queueMentions():
if (config.getint("settings", "taking_requests") == 0):
print("Not taking requests.")
else:
filterPath = os.path.join("data", "filters")
badWords = []
for filterFile in os.listdir(filterPath):
if filterFile[0] == ".":
continue
fp = os.path.join(filterPath, filterFile)
with open(fp, "r") as f:
loaded = json.load(f)
badWords += loaded['badwords']
print badWords
requestRegex = re.compile('make one about ([^,\.\n@]*)', re.IGNORECASE)
lastReply = getIntPref("lastReply")
if (lastReply == -1):
lastReply = 0
if (config.getint("services", "twitter_live") == 1):
if checkTwitterResource("/statuses/mentions_timeline"):
mentions = twitterApi.GetMentions(count=100, since_id=lastReply)
useTwitterResource("/statuses/mentions_timeline")
else:
print("Hit the mentions rate limit. Empty mentions.")
mentions = []
else:
with open(os.path.join("offline-samples", "twitter-mentions.pickle"), "rb") as mentionArchive:
mentions = pickle.load(mentionArchive)
print("Processing %i mentions..." % (len(mentions)))
mentions.reverse() # look at the newest one last and hold our place there
for status in mentions:
result = requestRegex.search(status.text)
if (result):
job = result.groups()[0]
# because regex is annoying
if (job.lower().startswith("a ")):
job = job[2:]
elif (job.lower().startswith("an ")):
job = job[3:]
job = titlecase.titlecase(job)
earlyOut = False
jobCheck = job.lower()
# don't accept links
# (fine with it, but Twitter's aggressive URL parsing means it's
# unexpected behavior in many instances)
if "http://" in jobCheck:
earlyOut = True
# check for derogatory speech, shock sites, etc.
for phrase in badWords:
if phrase in jobCheck:
earlyOut = True
break
# see if we'll even be able to post back at them
if len("@%s %s Simulator %i" %
(status.user.screen_name,
job,
datetime.date.today().year)
) + twitterGlobalConfig["characters_reserved_per_media"] > twitter.CHARACTER_LIMIT:
earlyOut = True
# don't let people crowd the queue
persistence.execute("SELECT user FROM queuedRequests")
existingUsers = map(lambda x: x[0], persistence.fetchall())
if status.user.screen_name in existingUsers:
earlyOut = True
if earlyOut:
# TODO: consider tweeting back "no" at them?
continue
# put them in the queue
try:
persistence.execute("INSERT INTO queuedRequests VALUES (?, ?, ?)", [status.id, job, status.user.screen_name])
persistenceConnection.commit()
except sqlite3.IntegrityError:
# already queued this tweet
pass
# even if we don't store it off, still mark the place here
setIntPref("lastReply", status.id)
def fulfillQueue():
# cycle through the queue
if (config.getint("settings", "making_requests") == 0):
print("Not automatically fulfilling requests.")
else:
print("Dequeueing %i request(s) from the backlog." % (config.getint("settings", "requests_per_run")))
persistence.execute("SELECT * FROM queuedRequests LIMIT ?", [config.getint("settings", "requests_per_run")])
artRequests = persistence.fetchall()
for req in artRequests:
takeSpecificRequest(data=req)
def printQueue():
persistence.execute("SELECT * FROM queuedRequests")
tab = prettytable.from_db_cursor(persistence)
print(tab)
def deleteRequest(tweetID=None):
if tweetID == None:
sys.stderr.write("No tweet ID provided. :-/\n")
return
persistence.execute("DELETE FROM queuedRequests WHERE tweet=?", [tweetID])
persistenceConnection.commit()
printQueue()
def takeSpecificRequest(tweetID=None, data=None):
if (tweetID != None and type(tweetID) == int):
persistence.execute("SELECT * FROM queuedRequests WHERE tweet=?", [tweetID])
req = persistence.fetchone()
if req == None:
print "Tweet not queued."
return
elif (data != None and type(data) == tuple and len(data) >= 3):
req = data
else:
print type(data)
sys.stderr.write("Need to pass either tweet ID or data to this function.\n")
return
tweetID = req[0]
job = req[1]
user = req[2]
try:
image = SimulatorGeneratorImage.getImageFor(
job,
safeSearchLevel=config.get("services", "google_safesearch"),
referer="http://twitter.com/SimGenerator"
)
year = random.randint(config.getint("settings", "minyear"), datetime.date.today().year)
artFile = "output-%s.png" % datetime.datetime.now().strftime("%Y-%m-%d-%H%M.%f")
artFile = os.path.join(tempfile.gettempdir(), artFile)
SimulatorGeneratorImage.createBoxArt(
job,
year,
image,
artFile,
maxSize=(
str(twitterGlobalConfig["photo_sizes"]["large"]["w"] - 1),
str(twitterGlobalConfig["photo_sizes"]["large"]["h"] - 1),
),
deleteInputFile=True
)
tweet( titlecase.titlecase(job), year, artFile, (user, str(tweetID)) )
except Exception, e:
sys.stderr.write("Couldn't respond to request: '%s' from %s in %i\n" %
(
job.encode("utf8"),
user.encode("utf8"),
tweetID
)
)
traceback.print_exc(file=sys.stderr)
persistence.execute("INSERT INTO failedRequests VALUES (?, ?, ?)",
[
tweetID, job, user
]
)
persistenceConnection.commit()
finally:
persistence.execute("DELETE FROM queuedRequests WHERE tweet=?", [tweetID])
persistenceConnection.commit()
printQueue()
def updateQueue():
# twitter documentation says this is rate-limited, doesn't appear
# to actually count against any resources. hmmmmm.
# resource should be "/account/update_profile", but that's not
# in the resource list at all.
persistence.execute("SELECT COUNT(*) FROM queuedRequests")
queueCount = persistence.fetchone()[0]
setIntPref("queueCount", queueCount)
print("Backlog is currently %i items." % (queueCount))
locString = "Request queue: %i" % queueCount
if len(locString) > 30:
locString = "Request queue: very, very long"
if queueCount == 0:
locString = "Request queue: EMPTY!"
twitterApi.UpdateProfile(location=locString)
def randomTrendTweet():
trends = getTrends()
if len(trends) == 0:
sys.stderr.write("Couldn't get any trending topics. :-/\n")
return
trend = random.choice(trends)
if trend[0] == "#":
text = trend[1:]
text = inflection.titleize(text)
text = titlecase.titlecase(text)
else:
text = trend
image = SimulatorGeneratorImage.getImageFor(
text,
safeSearchLevel=config.get("services", "google_safesearch"),
referer="http://twitter.com/SimGenerator"
)
year = random.randint(config.getint("settings", "minyear"), datetime.date.today().year)
artFile = "output-%s.png" % datetime.datetime.now().strftime("%Y-%m-%d-%H%M.%f")
artFile = os.path.join(tempfile.gettempdir(), artFile)
SimulatorGeneratorImage.createBoxArt(
text,
year,
image,
artFile,
maxSize=(
str(twitterGlobalConfig["photo_sizes"]["large"]["w"] - 1),
str(twitterGlobalConfig["photo_sizes"]["large"]["h"] - 1),
),
deleteInputFile=True
)
tweetString = text
if trend[0] == "#":
tweetString = trend + " " + tweetString
tweet(tweetString, year, artFile)
if __name__ == '__main__':
setup()
if (config.getint("settings", "faking_requests") == 1 or (len(sys.argv) > 1 and sys.argv[1] == "check")):
queueMentions()
elif (len(sys.argv) > 1 and sys.argv[1] == "fulfill"):
fulfillQueue()
elif (len(sys.argv) > 1 and sys.argv[1] == "updateQueue"):
updateQueue()
elif (len(sys.argv) > 2 and sys.argv[1] == "take"):
takeSpecificRequest(tweetID=int(sys.argv[2]))
elif (len(sys.argv) > 2 and sys.argv[1] == "del"):
deleteRequest(tweetID=int(sys.argv[2]))
elif (len(sys.argv) > 1 and sys.argv[1] == "pq"):
printQueue()
elif (len(sys.argv) > 1 and sys.argv[1] == "trend"):
randomTrendTweet()
elif (len(sys.argv) > 1 and sys.argv[1] == "cb"):
randomJobTweet(source="CB")
else:
randomJobTweet(source="BLS")
shutdown()