cardiparty-discord-bot/webhook.py

62 lines
2 KiB
Python
Raw Normal View History

2024-09-15 17:20:50 +10:00
#!/home/cardigan/rss-discord-bot/venv/python/python3.11
2024-09-15 11:55:45 +10:00
from datetime import datetime
import json
import os
import sys
import feedparser
import requests
2024-09-16 09:08:29 +10:00
guild = os.getenv("DISCORD_GUILD") # the Discord server/guild id
2024-09-15 17:20:50 +10:00
token = os.getenv("DISCORD_TOKEN") # token for this bot
2024-09-15 11:55:45 +10:00
cardiparty_ping = os.getenv("DISCORD_CARDIPARTY_PING")
# get the latest cardiparty with image as enclosure
2024-09-16 09:08:29 +10:00
f = feedparser.parse("https://newcardigan.org/category/cardiparties/?feed=featured_image_feed")
2024-09-15 11:55:45 +10:00
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'}
2024-09-16 09:08:29 +10:00
url = f"https://discord.com/api/webhooks/{guild}/{token}"
2024-09-15 11:55:45 +10:00
payload = {
"thread_name": f"{first.title} | {title}",
"content": content,
"embeds": embeds,
"allowed_mentions": { "roles": [cardiparty_ping] }
}
r = requests.post(url, json=payload, headers=headers)
2024-09-16 09:08:29 +10:00
print(datetime.now().isoformat(' '), r)
r.raise_for_status() # if we got a 4xx response