-
Notifications
You must be signed in to change notification settings - Fork 5
/
get_input.py
executable file
·75 lines (60 loc) · 1.84 KB
/
get_input.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
#!/usr/bin/env python3
import os
import requests
from datetime import datetime
from sys import argv
BASE_DIR = os.path.dirname(__file__)
URL = "https://adventofcode.com/{year}/day/{day}/input"
HEADERS = {
"User-Agent": "https://github.com/benediktwerner/AdventOfCode/blob/master/get_input.py by [email protected]"
}
def print_usage():
print("Usage:", argv[0], "[[YEAR] DAY]")
exit(1)
def arg_to_int(i, name):
try:
return int(argv[i])
except ValueError:
print("Error:", name, "is not a number")
print_usage()
if len(argv) == 1:
now = datetime.now()
if now.month != 12 or now.day > 25:
print("Failed to deduce day: There is no new AoC puzzle today.")
print_usage()
year = now.year
day = now.day
elif "-h" in argv[1:] or "--help" in argv[1:]:
print_usage()
elif len(argv) == 2:
day = arg_to_int(1, "DAY")
now = datetime.now()
year = now.year
if now.month < 12:
year -= 1
elif len(argv) == 3:
year = arg_to_int(1, "YEAR")
day = arg_to_int(2, "DAY")
else:
print_usage()
dir_name = os.path.join(BASE_DIR, str(year), f"day{day:02}")
cookies = {}
try:
with open(os.path.join(BASE_DIR, "cookie")) as f:
cookies["session"] = f.read().strip()
except FileNotFoundError:
print("No cookie file found.")
print("Please paste the value of the 'session' cookie on the AoC website into a file named 'cookie'.")
exit(2)
os.makedirs(dir_name, exist_ok=True)
target_file = os.path.join(dir_name, "input.txt")
url = URL.format(year=year, day=day)
req = requests.get(url, cookies=cookies, headers=HEADERS)
if req.status_code != 200:
print("Error. Got status:", req.status_code)
print(req.text)
exit(3)
else:
with open(target_file, "w") as f:
f.write(req.text)
print("Input for", dir_name, "written to", target_file)