-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfetch_inputs.py
More file actions
51 lines (42 loc) · 1.29 KB
/
fetch_inputs.py
File metadata and controls
51 lines (42 loc) · 1.29 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
import urllib.request
from urllib.error import HTTPError
from pathlib import Path
api_key = ""
try:
with open("./api_key.txt", "r") as f:
api_key = f.read()
except IOError:
api_key = input(
"please insert aoc cookie containing the session key (excluding the 'session=' and ';'):"
)
with open("./api_key.txt", "w") as f:
f.write(api_key)
def write_day(year, day, data):
file = Path(f"input/{year}/day_{day:02}.txt")
if not file.exists():
with open(file, "w") as f:
f.write(data)
else:
print(f"{file} already exists")
def fetch(year, day):
file = Path(f"input/{year}/day_{day:02}.txt")
if file.exists():
return True
print(f"Fetching day {day}")
req = urllib.request.Request(f"https://adventofcode.com/{year}/day/{day}/input")
req.add_header("Cookie", f"session={api_key}")
try:
data = urllib.request.urlopen(req, timeout=10).read().decode()
write_day(year, day, data)
except HTTPError as e:
if e.code == 404:
print(f"Year {year} day {day} not available yet")
return False
raise e
return True
for day in range(1, 25 + 1):
if not fetch(2024, day):
break
for day in range(1, 12 + 1):
if not fetch(2025, day):
break