agenda/update_gwr_advance_ticket_date.py

78 lines
1.8 KiB
Python
Raw Normal View History

#!/usr/bin/python3
"""Update GWR advance ticket date cache."""
import configparser
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
SMTP_HOST = "4angle.com"
EMAIL = "edward@4angle.com"
NAME = "Edward Betts"
def send_mail(subject: str, body: str) -> None:
"""Send an e-mail."""
msg = EmailMessage()
msg["Subject"] = subject
msg["To"] = f"{NAME} <{EMAIL}>"
msg["From"] = f"{NAME} <{EMAIL}>"
msg["Date"] = formatdate()
msg["Message-ID"] = make_msgid()
msg.set_content(body)
s = smtplib.SMTP(SMTP_HOST)
s.sendmail(EMAIL, [EMAIL], msg.as_string())
s.quit()
def get_data_dir() -> str:
"""Read data dir from config."""
2023-11-25 11:24:37 +00:00
config_filename = os.path.join(os.path.dirname(__file__), "config")
assert os.path.exists(config_filename)
config = configparser.ConfigParser()
config.read(config_filename)
return config.get("data", "dir")
def main() -> None:
"""Get date from web page and compare with existing."""
filename = os.path.join(get_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()