-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaoc.py
More file actions
112 lines (89 loc) · 3.97 KB
/
aoc.py
File metadata and controls
112 lines (89 loc) · 3.97 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
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
import requests
import os
from bs4 import BeautifulSoup
def fetch_webpage_content_with_cookies(url, session_cookie):
"""
Fetch content from a given URL using a session cookie for authentication.
:param url: The URL to fetch.
:param session_cookie: The session cookie for authentication.
:return: Content of the webpage or an error message.
"""
if not url.startswith('https://'):
return "Error: URL must start with 'https://'"
# Add a User-Agent and include the session cookie in headers.
headers = {
"Cookie": f"session={session_cookie}",
"User-Agent": "advent-of-code-fetcher/1.0 (+https://github.com)"
}
try:
response = requests.get(url, headers=headers)
# If the server returned a non-200, return a descriptive error including a small
# snippet of the response body to help debugging (don't dump huge pages).
if response.status_code != 200:
snippet = response.text[:1000].strip()
return f"Error: Unable to fetch the webpage. Status: {response.status_code}. Response snippet: {snippet}"
return response.text
except requests.exceptions.RequestException as e:
return f"Error: Unable to fetch the webpage. Details: {str(e)}"
def inputing(year=2024, day=1):
url = f'https://adventofcode.com/{year}/day/{day}/input'
with open('session_cookie.txt', 'r') as file:
session_cookie = file.read().strip()
# Fetch webpage content
content = fetch_webpage_content_with_cookies(url, session_cookie)
# Strip whitespace
content = content.strip()
# If the fetch returned an error message, print it and don't write the file(s).
if content.startswith("Error:"):
print(f"Skipping write for {year}/{day}/input.txt — {content}")
return content
# Create directory if it doesn't exist and write the fetched input.
os.makedirs(f'{year}/{day}', exist_ok=True)
# Write content to the file, replacing it if it already exists
with open(f'{year}/{day}/input.txt', 'w') as file:
file.write(content)
# Ensure helper files exist
with open(f'{year}/{day}/ss.py', 'w') as f:
f.close()
with open(f'{year}/{day}/gs.py', 'w') as f:
f.close()
return content
def outputing(year=2024, day=1, part=1, answer=None):
"""
Submit an answer to the Advent of Code website.
:param year: The year of the challenge.
:param day: The day of the challenge.
:param part: The part of the challenge (1 or 2).
:param answer: The answer to submit.
:return: The response text or an error message.
"""
if answer is None:
return "Error: You must provide an answer."
# Adjust the URL to include "day/answer" as the form action specifies
url = f'https://adventofcode.com/{year}/day/{day}/answer'
# Read session cookie from file
try:
with open('session_cookie.txt', 'r') as file:
session_cookie = file.read().strip()
except FileNotFoundError:
return "Error: session_cookie.txt not found. Make sure it exists and contains your session cookie."
# Prepare the payload and headers
data = {'level': part, 'answer': answer}
headers = {"Cookie": f"session={session_cookie}"}
try:
# Submit the form via POST
response = requests.post(url, data=data, headers=headers)
response.raise_for_status() # Raise an exception for HTTP errors
# Parse the response text to extract the <article> tag
soup = BeautifulSoup(response.text, 'html.parser')
article = soup.find('article')
if article:
return article.prettify()
else:
return "Error: <article> tag not found in the response."
except requests.exceptions.RequestException as e:
return f"Error: Unable to submit the answer. Details: {str(e)}"
for day in range(2, 13):
print(f"Fetching input for day {day}...")
inputing(year=2025, day=day)
#print(outputing(year=2015, day=13, part=1, answer=822))