cardiparty-discord-bot/webhook.py

61 lines
1.9 KiB
Python
Raw Normal View History

2024-09-15 11:55:45 +10:00
#!/usr/bin/env python3
from datetime import datetime
import json
import os
import sys
import feedparser
import requests
channel = os.getenv("DISCORD_CHANNEL")
token = os.getenv("DISCORD_TOKEN")
cardiparty_ping = os.getenv("DISCORD_CARDIPARTY_PING")
# get the latest cardiparty with image as enclosure
f = feedparser.parse("https://newcardigan.org/category/cardiparties/?feed=cardipartyfeed")
first = f.entries[0]
# check whether we have already seen this entry
with open("latest_post.txt", "r+") as f:
guid = f.read().strip()
f.close()
if guid != first.guid:
# update the guid
with open("latest_post.txt", "w+") as f:
f.write(first.guid)
f.close()
api_response = sys.stdin.read() # read the API call output that was piped in
api_data = json.loads(api_response)[0]
title = api_data["title"]
city = api_data["address.city"]
start_date = api_data["start_date"]
summary = api_data["summary"]
start_date = datetime.fromisoformat(start_date).astimezone().strftime(
"%I:%M%p %a %d %b %Y"
).strip("0") # remove time zero padding if any
content = f"[<:newCardigan:1280097925149626419> **{title}**]({first.link})\n_{city}_\n_{start_date}_\n\n{summary}\n\n<@&{cardiparty_ping}>"
embeds = [{
"title": "Find out more and register!",
"url": first.link,
"color": 16741516,
"image": {
"url": first.enclosures[0].href
}
}]
headers = {'user-agent': 'cardiParty-discord-bot/1.0.0'}
url = f"https://discord.com/api/webhooks/{channel}/{token}"
payload = {
"thread_name": f"{first.title} | {title}",
"content": content,
"embeds": embeds,
"allowed_mentions": { "roles": [cardiparty_ping] }
}
r = requests.post(url, json=payload, headers=headers)
r.raise_for_status() # if we got a 4xx response this will log it out