This repository was archived by the owner on Dec 11, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathworker.py
More file actions
87 lines (71 loc) · 2.67 KB
/
worker.py
File metadata and controls
87 lines (71 loc) · 2.67 KB
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
import traceback
import os
import time
import re
from collections import defaultdict
from datetime import datetime, timedelta
#this package seems outdated, but it was super simple to set up
import tweepy
CONSUMER_KEY = os.environ.get('CONSUMER_KEY')
CONSUMER_SECRET = os.environ.get('CONSUMER_SECRET')
ACCESS_KEY = os.environ.get('ACCESS_KEY')
ACCESS_SECRET = os.environ.get('ACCESS_SECRET')
FOOTERS = ["#PULAKYELLING"]
ACCOUNTS = ["pulakm"]
#how often to check for new tweets (careful of twitter rate limiting)
DELAY = 12
#how long until we don't consider a tweet new?
#this is to deal with tweets bizarrely repeating
EXPIRED_TIME = timedelta(minutes=2)
URL_RE = ".+\..+" # crude, but should handle most of what Pulak tweets
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)
api = tweepy.API(auth)
def send_tweet(message):
final_message = message
#add in footers (hashtags and users)
for footer in FOOTERS:
if len(final_message + " " + footer) <= 140:
final_message += " " + footer
try:
api.update_status(final_message)
print "Tweeted:"
print final_message.encode('utf-8')
except:
#this will print to heroku logs
print "Error sending tweet:"
print final_message.encode('utf-8')
traceback.print_exc()
def to_upper(message):
upper_message = []
for token in message.split(" "):
if is_link(token):
print "%s is a link" % token
upper_message.append(token)
else:
upper_message.append(token.upper())
return " ".join(upper_message)
def is_link(token):
return True if re.match(URL_RE, token) else False
if __name__ == "__main__":
last_tweets = defaultdict(str) # keep track of last tweet from the stream
while True:
for user in ACCOUNTS:
try:
#get most recent tweet
tweet = api.user_timeline(user)[0]
if tweet.text != last_tweets[user]:
last_tweets[user] = tweet.text
if(datetime.now() - tweet.created_at < EXPIRED_TIME):
send_tweet(to_upper(tweet.text)) # Tweet! Tweet!
else:
print "Got tweet but it was too old for", user
print tweet.text.encode('utf-8')
else:
print "Got same tweet for", user
except IndexError:
#no tweeets found for this user
print "Error getting tweet for", user
traceback.print_exc()
finally:
time.sleep(DELAY) # Avoid Twitter rate limiting