release-tracker-bot/main.py

101 lines
3.1 KiB
Python

from dotenv import load_dotenv
from requests import get,post,put
from datetime import datetime as dt, timezone as tz
from time import mktime
from feedparser import parse
from os import getenv
from json import loads
from time import mktime
# initialise variables
new_ts = dt.now(tz.utc)
old_ts = ''
# read in old timestamp if it exists
try:
old_ts = dt.strptime(open('last_check','r').read().split(".")[0],'%Y-%m-%d %H:%M:%S')
except:
old_ts = dt.strptime('2023-01-01 00:00:00','%Y-%m-%d %H:%M:%S')
# load in the relevant .env variables
load_dotenv()
discord_user = getenv('DISCORD_USERNAME')
discord_webhook_url = getenv('DISCORD_WEBHOOK')
github_token = getenv('GITHUB_TOKEN')
# list of repos to check
repos = [
'neovim/neovim',
'mastodon/mastodon',
'hometown-fork/hometown',
'glitch-soc/mastodon',
'superseriousbusiness/gotosocial',
'borgbackup/borg',
'atuinsh/atuin',
'fish-shell/fish-shell',
'JanDeDobbeleer/oh-my-posh',
'twpayne/chezmoi'
]
github_api = 'https://api.github.com/repos'
headers = {
'Accept': 'application/vnd.github+json',
'Authorization': f'Bearer {github_token}',
'X-GitHub-Api-Version': '2022-11-28'
}
# loop through urls for latest release
def get_latest_releases():
for repo in repos:
release_url = f'{github_api}/{repo}/releases/latest'
# debug
# print(release_url)
latest_release = get(release_url, headers=headers)
if latest_release.status_code == 200:
release_details = loads(latest_release.text)
# debugging
# print(
# release_details['name'],
# release_details['published_at'],
# old_ts,
# mktime(old_ts.timetuple()),
# mktime(dt.strptime(release_details['published_at'], "%Y-%m-%dT%H:%M:%SZ").timetuple())
# )
if mktime(dt.strptime(release_details['published_at'], '%Y-%m-%dT%H:%M:%SZ').timetuple()) > mktime(old_ts.timetuple()):
# debug
# print(
# release_details['tag_name'],
# release_details['name'],
# release_details['published_at'],
# release_details['html_url']
# )
payload = {
'username': discord_user,
'content': f"{release_details['name']}: {release_details['tag_name']}\n{release_details['html_url']}"
}
webhook_put = post(discord_webhook_url, headers=headers, json=payload)
# return if something goes wrong
if webhook_put.status_code != 204:
print(f"whoops... status_code is {webhook_put.status_code}")
# debug
# print(f"call was post({discord_webhook_url}, headers={headers}, json={payload})")
return False
# debug
# else:
# print(latest_release.status_code, latest_release.reason)
else:
print(f"whoops ... got a {latest_release.status_code} on that last one")
return False
## return true if the function didn't terminate abnormally before
# print("all good - finish clean")
return True
if __name__ == "__main__":
results_sent = get_latest_releases()
if results_sent:
with open('last_check','w') as f:
print(new_ts, file=f, end='')