Last active
August 19, 2020 22:30
-
-
Save samgrover/d06723e113ecd8140efff1d6773aaf70 to your computer and use it in GitHub Desktop.
Fetch kittens available for adoption and notify if there are new ones.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# Fetch current kittens available for adoption and notify if there are new ones. | |
import sys | |
import requests | |
import logging | |
import re | |
import json | |
from datetime import datetime | |
from datetime import date | |
KITTENS_QUERY = "https://www.oregonhumane.org/adopt/?type=cats&mode=adv&age=kitten" | |
PUSHCUT_NOTIFICATION_URL = "https://api.pushcut.io/YOURTOKEN/notifications/YOURACTION" | |
# File that will be read and written to in the working directory. | |
# Before first run this should contain an empty array, or you will get an error. | |
JSON_FILENAME = 'kittens.json' | |
def save(new_kittens): | |
with open(JSON_FILENAME, 'w', encoding='utf-8') as f: | |
json.dump(new_kittens, f, ensure_ascii=False, indent=2) | |
r = requests.get(KITTENS_QUERY) | |
if r.status_code == 200: | |
m = re.findall(r'class="result-item"', r.text) | |
total_kittens = len(m) | |
m = re.findall(r'data-ohssb-name="(.+?)"', r.text) | |
names = m | |
m = re.findall(r'<strong>Date Available:</strong> (.+?) </div>', r.text) | |
dates = m | |
m = re.findall(r'<span class="id">(.+?)</span>', r.text) | |
ids = m | |
# Load existing JSON and ids to compare. | |
current_kittens = [] | |
with open(JSON_FILENAME) as f: | |
current_kittens = json.load(f) | |
current_ids = [] | |
for a_current_kitten in current_kittens: | |
current_ids.append(a_current_kitten['id']) | |
new_kittens = [] | |
has_new_id = False | |
new_ids = 0 | |
for idx, a_name in enumerate(names): | |
a_kitten = {} | |
a_kitten['name'] = names[idx] | |
a_kitten['date'] = dates[idx] | |
an_id = ids[idx] | |
a_kitten['id'] = an_id | |
if current_ids.count(an_id) == 0: | |
has_new_id = True | |
new_ids += 1 | |
new_kittens.append(a_kitten) | |
# If there's a new ID, send a notification | |
if has_new_id: | |
notification = {} | |
notification['title'] = "Kittens!" | |
notification['text'] = f"{new_ids} new kittens!" | |
r = requests.post(PUSHCUT_NOTIFICATION_URL, json=notification) | |
print(r.status_code) | |
if r.status_code == 200: | |
# Save new JSON only if notification was successful | |
save(new_kittens) | |
else: | |
save(new_kittens) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment