agenda/update_gwr_advance_ticket_date.py

63 lines
1.5 KiB
Python
Raw Normal View History

#!/usr/bin/python3
"""Update GWR advance ticket date cache."""
import os.path
import smtplib
2023-11-25 11:24:37 +00:00
import sys
from email.message import EmailMessage
from email.utils import formatdate, make_msgid
import requests
from agenda import gwr
2023-12-07 19:06:48 +00:00
config = __import__("config.default", fromlist=[""])
def send_mail(subject: str, body: str) -> None:
"""Send an e-mail."""
msg = EmailMessage()
msg["Subject"] = subject
2023-12-07 19:06:48 +00:00
msg["To"] = f"{config.NAME} <{config.MAIL_TO}>"
msg["From"] = f"{config.NAME} <{config.MAIL_FROM}>"
msg["Date"] = formatdate()
msg["Message-ID"] = make_msgid()
msg.set_content(body)
2023-12-07 19:06:48 +00:00
s = smtplib.SMTP(config.SMTP_HOST)
s.sendmail(config.MAIL_TO, [config.MAIL_TO], msg.as_string())
s.quit()
def main() -> None:
"""Get date from web page and compare with existing."""
2023-12-07 19:06:48 +00:00
filename = os.path.join(config.DATA_DIR, "advance-tickets.html")
existing_html = open(filename).read()
existing_date = gwr.extract_weekday_date(existing_html)
new_html = requests.get(gwr.url).text
open(filename, "w").write(new_html)
new_date = gwr.extract_weekday_date(new_html)
if existing_date == new_date:
2023-11-25 11:24:37 +00:00
if sys.stdin.isatty():
print("date has't changed:", existing_date)
return
2023-11-30 23:17:28 +00:00
subject = f"New GWR advance ticket booking date: {new_date}"
body = f"""Old date: {existing_date}
New date: {new_date}
{gwr.url}
Agenda: https://edwardbetts.com/agenda/
"""
send_mail(subject, body)
2023-11-25 11:24:37 +00:00
if __name__ == "__main__":
main()