happybot/equinox.py
2022-03-15 16:41:10 -04:00

38 lines
1.4 KiB
Python

#!/usr/bin/env python3
from datetime import datetime
from bs4 import BeautifulSoup
from urllib.request import urlopen
from subprocess import check_output
atf = '%a %b %d %H:%M:00 %Y'
with urlopen('https://en.wikipedia.org/w/index.php?title=Template:Solstice-equinox') as web:
soup = BeautifulSoup(web.read(), 'html.parser')
table = soup.find('table', attrs={'class': 'wikitable'}).find('tbody')
dates = dict()
today = datetime.now()
for tr in table.find_all('tr'):
try:
year = int(tr.find('th').text.strip())
except:
continue
times = [td.text.strip() for td in tr.find_all('td')]
for i, m, text in ((0, 3, 'March equinox'), (2, 6, 'June solstice'), (4, 9, 'September equinox'), (6, 12, 'December solstice')):
hour, minute = map(int, times[i+1].split(':'))
date = datetime(year=year, month=m, day=int(times[i]), hour=hour, minute=minute)
if date > today:
dates[date.strftime(atf)] = (date.strftime('%H:%M %B %d %Y'), text)
atd = filter(None, check_output(['atq', '-q', 's']).decode().strip().split('\n'))
atd = set(' '.join(d.split('\t')[1].split(' ')[:-2]) for d in atd)
for date, text in map(dates.get, set(dates) - atd):
text = '/home/zgrep/offtopiabday/happy ' + text
print(f'Scheduling {text} at {date}.')
try:
check_output(['at', '-q', 's', date], universal_newlines=True, input=text)
except:
print('Failed.')