pulls feed and sends new posts

This commit is contained in:
yequari 2023-09-14 18:48:30 -07:00
commit 1befc62b6c
1 changed files with 79 additions and 0 deletions

79
rss.py Normal file
View File

@ -0,0 +1,79 @@
import os
import xml.etree.ElementTree as ET
import requests
from datetime import datetime, timezone
FEED = 'https://discuss.32bit.cafe/all/new.atom'
FILENAME = os.path.basename(FEED)
WEBHOOK = 'https://discord.com/api/webhooks/1152044037017186417/igGNMxiVhLSW9y4kL8cs7y6m0AutxqXHxMTWSXWN0jbCUnsxLT_er8pqWQKoAjGpPywg'
def tag(tagname: str) -> str:
el_prefix = '{http://www.w3.org/2005/Atom}'
return el_prefix + tagname
class Entry:
def __init__(self, entry):
self.title = entry.find(tag('title')).text
self.url = entry.find(tag('id')).text
self.author = entry.find(tag('author')).find(tag('name')).text
self.date = datetime.fromisoformat(entry.find(tag('published')).text)
def __str__(self):
return f'{self.title} by {self.author} at {self.date} \n {self.url}'
def get_last_update_time():
try:
stat = os.stat(FILENAME)
return datetime.fromtimestamp(stat.st_mtime,
datetime.now().astimezone().tzinfo)
except FileNotFoundError:
return datetime.now(timezone.utc)
def update_rss_file():
r = requests.get(FEED, stream=True)
with open(FILENAME, 'w') as fd:
for chunk in r.iter_content(chunk_size=1024, decode_unicode=True):
fd.write(chunk)
def parse_rss_file():
tree = ET.parse(FILENAME)
return tree.getroot()
def get_new_posts(time, root):
posts = []
for entry in root.findall(tag('entry')):
e = Entry(entry)
print(e.date)
if e.date > time:
posts.append(e)
return posts
def send_message(entry):
obj = {
'content': str(entry)
}
r = requests.post(WEBHOOK, obj)
print(r.status_code)
# Check last mod date of current rss file
# Download new version of file
# Iterate over entries, storing ones with a newer date in an array
# send POST to discord webhook
if __name__ == "__main__":
last_updated = get_last_update_time()
print(last_updated)
update_rss_file()
root = parse_rss_file()
posts = get_new_posts(last_updated, root)
print(posts)
for post in posts:
send_message(post)