happybot/holi.py

62 lines
1.6 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=Holi') as web:
soup = BeautifulSoup(web.read(), 'html.parser')
table = soup.find('table', attrs={'class': 'infobox'}).find('tbody')
dates = dict()
today = datetime.now()
months = '''
January
February
March
April
May
June
July
August
September
October
November
December
'''.strip().split()
for tr in table.find_all('tr'):
try:
year = tr.find('th').text.strip()
if not year.endswith('date'):
continue
year = int(year[:-4].strip())
daymonth = tr.find('td')
for e in daymonth.find_all('sup'):
e.extract()
daymonth = daymonth.text.strip().split()
day = int(daymonth[0])
month = months.index(daymonth[1]) + 1
except:
continue
date = datetime(year=year, month=month, day=day, hour=0, minute=0)
if date > today:
dates[date.strftime(atf)] = date.strftime('%H:%M %B %d %Y')
at_letter = 'i'
atd = filter(None, check_output(['atq', '-q', at_letter]).decode().strip().split('\n'))
atd = set(' '.join(d.split('\t')[1].split(' ')[:-2]) for d in atd)
for date in map(dates.get, set(dates) - atd):
text = '/home/zgrep/offtopiabday/exclaimheart Holi mubārāk'
print(f'Scheduling {text} at {date}.')
try:
check_output(['at', '-q', at_letter, date], universal_newlines=True, input=text)
except:
print('Failed.')