-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathonthisday.py
executable file
·244 lines (194 loc) · 6.57 KB
/
onthisday.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
#!/usr/bin/env python
"""
Tweet your old Flickr photos from this day in history.
"""
import argparse
import datetime
import random
import sys
import webbrowser
# http://www.stuvel.eu/flickrapi
import flickrapi # pip install flickrapi
import flickrapi.shorturl
# https://github.com/sixohsix/twitter
import twitter # pip install twitter
import yaml # pip install PyYAML
import flickr_utils
def load_yaml(filename):
with open(filename) as f:
data = yaml.safe_load(f)
if not data.keys() >= {
"oauth_token",
"oauth_token_secret",
"consumer_key",
"consumer_secret",
}:
sys.exit("Twitter credentials missing from YAML: " + filename)
if not data.keys() >= {"flickr_api_key", "flickr_api_secret"}:
sys.exit("Flickr credentials missing from YAML: " + filename)
return data
def tweet_it(string, credentials):
if len(string) <= 0:
return
# Create and authorise an app with (read and) write access at:
# https://dev.twitter.com/apps/new
# Store credentials in YAML file. See data/onthisday_example.yaml
t = twitter.Twitter(
auth=twitter.OAuth(
credentials["oauth_token"],
credentials["oauth_token_secret"],
credentials["consumer_key"],
credentials["consumer_secret"],
)
)
print("TWEETING THIS:\n", string)
if args.test:
print("(Test mode, not actually tweeting)")
else:
result = t.statuses.update(status=string)
url = (
"http://twitter.com/"
+ result["user"]["screen_name"]
+ "/status/"
+ result["id_str"]
)
print("Tweeted:\n" + url)
if not args.no_web:
webbrowser.open(url, new=2) # 2 = open in a new tab, if possible
def six_months_ago(now):
import calendar
new_day = now.day
new_year = now.year
if now.month > 6:
new_month = now.month - 6
else:
new_month = now.month + 6
new_year = now.year - 1
days_in_new_month = calendar.monthrange(new_year, new_month)[1]
if new_day > days_in_new_month:
new_day = days_in_new_month
then = now.replace(year=new_year, month=new_month, day=new_day)
return then
def six_months_from(now):
import calendar
new_day = now.day
new_year = now.year
if now.month > 6:
new_month = now.month - 6
new_year = now.year + 1
else:
new_month = now.month + 6
days_in_new_month = calendar.monthrange(new_year, new_month)[1]
if new_day > days_in_new_month:
# new_day = days_in_new_month
return None
then = now.replace(year=new_year, month=new_month, day=new_day)
return then
def find_photos(flickr, my_nsid, tweet, now, earliest_year):
found = 0
# These look like "2012: http://flic.kr/p/bqhhhb":
tweetlets = []
for year in range(now.year - 1, earliest_year - 1, -1):
print("Checking", year)
photo = flickr_utils.most_interesting_today_in(flickr, my_nsid, year, now=now)
if photo is not None:
print("Found a photo for", year)
found += 1
# ET.dump(photo)
photo_id = int(photo.attrib["id"])
url = flickrapi.shorturl.url(photo_id).replace("http:", "https:")
tweetlet = str(year) + ": " + url
tweetlets.append(tweetlet)
else:
print("No photo for", year)
print("Found", found, "photos")
# There's room for eight tweetlets in a tweet
if len(tweetlets) > 8:
tweetlets = random.sample(tweetlets, 8)
# In random order
# tweet += " " + " ".join(sorted(tweetlets, reverse=True))
tweet += " " + " ".join(tweetlets)
return found, tweet
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Tweet your old Flickr photos on this day in history.",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
parser.add_argument(
"-u", "--username", default="hugovk", help="Your Twitter username"
)
parser.add_argument(
"-y",
"--yaml",
default="/Users/hugo/Dropbox/bin/data/onthisday.yaml",
help="YAML file location containing Twitter keys and secrets",
)
parser.add_argument(
"-e",
"--earliest-year",
default=2004,
type=int,
help="Earliest year to check for photos. "
"If 'None', uses the year of your oldest uploaded photo.",
)
parser.add_argument(
"-6",
"--six-months",
action="store_true",
help="Show photos from six months ago instead of on this day",
)
parser.add_argument(
"-x",
"--test",
action="store_true",
help="Test mode: go through the motions but don't tweet",
)
parser.add_argument(
"-nw",
"--no-web",
action="store_true",
help="Don't open a web browser to show the tweeted tweet",
)
args = parser.parse_args()
try:
import timing # optional
assert timing # silence warnings
except ImportError:
pass
credentials = load_yaml(args.yaml)
flickr = flickrapi.FlickrAPI(
credentials["flickr_api_key"], credentials["flickr_api_secret"]
)
# flickr.authenticate_via_browser(perms="write")
if args.test:
print("(Test mode, not actually tweeting)")
my_nsid = flickr.people_findByUsername(username=args.username)
my_nsid = my_nsid.getchildren()[0].attrib["nsid"]
print("My NSID:", my_nsid)
if args.earliest_year:
earliest_year = args.earliest_year
else:
person_info = flickr.people_getInfo(user_id=my_nsid)
firstdatetaken = (
person_info.getchildren()[0].find("photos").find("firstdatetaken").text
)
# User may have posted (for example, like me) an 19th century photo,
# but it doesn't matter, this is just an upper limit which may not be
# reached before the max tweet length is reached.
earliest_year = int(firstdatetaken[:4])
print("Earliest year:", earliest_year)
now = datetime.datetime.now()
found = 0
if not args.six_months:
tweet = "#OnThisDay"
found, tweet = find_photos(flickr, my_nsid, tweet, now, earliest_year)
if not found or args.six_months:
tweet = "#6MonthsAgo"
now = six_months_from(now)
if now:
found, tweet = find_photos(flickr, my_nsid, tweet, now, earliest_year)
if not found:
sys.exit("No photos found, try again tomorrow")
print("Tweet this:\n", tweet)
tweet_it(tweet, credentials)
# End of file