-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtweet.py
162 lines (112 loc) · 4.18 KB
/
tweet.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
"""
Tweet
todo; test this; write docker command
"""
import logging
from logging.handlers import RotatingFileHandler
import pdb
import time
import requests
import twitter
from config.config import BASE_URL
from config.secrets import (
CONSUMER_API_KEY,
CONSUMER_API_SECRET,
TWITTER_ACCESS_TOKEN,
TWITTER_ACCESS_TOKEN_SECRET,
ENDPOINT,
TOKEN,
)
from utils import utils
def load(data):
headers = {
"Authorization": f"Bearer {TOKEN}",
"Content-Type": "application/json",
"Prefer": "resolution=merge-duplicates",
}
return requests.post(ENDPOINT, headers=headers, json=data)
def get_tweet_data():
params = {"order": "rsn.desc", "bot_status": "eq.ready_to_tweet"}
res = requests.get(ENDPOINT, params=params)
res.raise_for_status()
return res.json()
def parse_subtype(subtype):
# e.g. etxtract subtype description from something like `R- 101 Single Family Houses`
if "R-" in subtype or "C-" in subtype:
subtype = subtype.replace("- ", "")
subtype = subtype.split(" ")
return " ".join(subtype[1:])
else:
return subtype
def format_tweet(permit):
if not permit.get("property_zip"):
return (
f"{permit['subtype']} at {permit['project_name']} {BASE_URL}{permit['rsn']}"
)
else:
return f"{permit['subtype']} at {permit['project_name']} ({permit['property_zip']}) {BASE_URL}{permit['rsn']}"
def main():
data = get_tweet_data()
if not data:
logger.info("nothing to tweet")
return
api = twitter.Api(
consumer_key=CONSUMER_API_KEY,
consumer_secret=CONSUMER_API_SECRET,
access_token_key=TWITTER_ACCESS_TOKEN,
access_token_secret=TWITTER_ACCESS_TOKEN_SECRET,
)
tweets = []
for permit in data:
subtype = permit["subtype"]
permit["subtype"] = parse_subtype(subtype)
tweet = format_tweet(permit)
if tweet in tweets:
# avoid duplicate tweets in same run. it happens with multiple units on
# on proptery. eg.:
# https://abc.austintexas.gov/web/permit/public-search-other?t_detail=1&t_selected_folderrsn=12367861
# and
# https://abc.austintexas.gov/web/permit/public-search-other?t_detail=1&t_selected_folderrsn=12367860
continue
else:
tweets.append(tweet)
logger.info(tweet)
"""
We update the record status in postgres before tweeting. If this step were to fail after
we tweeted, the bot would continue to tweet about the permit until the db was able to
be updated. So this is a failsafe. Better to miss a tweet than tweet indefinitely.
The twitter API does it's own checks to prevent duplicate tweets. But it's not always
clear how it makes that determinition
"""
update_payload = {"bot_status": "tweeted", "rsn": permit["rsn"]}
res = load(update_payload)
res.raise_for_status()
try:
res = api.PostUpdate(tweet)
except Exception as e:
# handle when twitter rejects a duplicate tweet
# this happens occasionally for duplicate permit types at the same `project_name`
# twitter api error is [{'code': 187, 'message': 'Status is a duplicate.'}]
for message in e.message:
if message.get("code") != 187:
logger.error(e.message)
# if the tweet fails, let the db know as such
update_payload = {"bot_status": "api_error", "rsn": permit["rsn"]}
res = load(update_payload)
raise e
pass
time.sleep(3)
if __name__ == "__main__":
logger = logging.getLogger("tweet_logger")
logger.setLevel(logging.DEBUG)
file_handler = RotatingFileHandler("log/tweet.log", maxBytes=2000000)
formatter = logging.Formatter(
fmt="%(asctime)s %(message)s",
datefmt="%m/%d/%Y %I:%M:%S %p",
)
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
console = logging.StreamHandler()
console.setFormatter(formatter)
logger.addHandler(console)
main()