improved exception & error handling #1

This commit is contained in:
Michi 2024-10-12 17:30:47 +02:00
parent 5e07460615
commit 0988256239

75
main.py
View file

@ -26,41 +26,63 @@ def sendMessage(message, notificationType):
header = { header = {
"Authorization":f"Bearer {accessToken}" "Authorization":f"Bearer {accessToken}"
} }
response = requests.post(url=endpoint, headers=header, data=message) try:
else: response = requests.post(url=endpoint, data=message) response = requests.post(url=endpoint, headers=header, data=message)
except Exception as error:
raise Exception(f"Got an error while sending the notification: {error}")
else:
try:
response = requests.post(url=endpoint, data=message)
except Exception as error:
raise Exception(f"Got an error while sending the notification: {error}")
return response return response
case "discord" | _: case "discord" | _:
endpoint = os.getenv('DISCORD_WEBHOOK') endpoint = os.getenv('DISCORD_WEBHOOK')
data = { data = {
"content": message, "content": message,
} }
response = requests.post(url=endpoint, json=data) try:
return response response = requests.post(url=endpoint, json=data)
return response
except Exception as error:
raise Exception(f"Got an error while sending the notification: {error}")
# Check for the current waiting times # Check for the current waiting times
def checkTimes(subscribedAttractions, themepark): def checkTimes(subscribedAttractions, themepark):
endpoint = "https://api.wartezeiten.app/v1/waitingtimes" try:
endpoint = "https://api.wartezeiten.app/v1/waitingtimes"
header = { header = {
"language":"de", "language":"de",
"park":themepark "park":themepark
} }
req = requests.get(url=endpoint, headers=header) req = requests.get(url=endpoint, headers=header)
result = req.json() except:
attractions = result raise Exception(f"API Request to endpoint {endpoint} failed.")
for attraction in attractions: try:
if attraction["code"] in subscribedAttractions: result = req.json()
if attraction["status"] == "opened": except:
refreshTime = 30 raise Exception("Format of API response is invalid. (JSON expected)")
if not attraction["code"] in currentTimes: currentTimes[attraction["code"]] = attraction["waitingtime"]; try:
if currentTimes[attraction["code"]] > attraction["waitingtime"]: attractions = result
sendMessage(f"Waiting time of {attraction['name']} sank to {attraction['waitingtime']} Minutes!", notificationType) for attraction in attractions:
elif currentTimes[attraction["code"]] < attraction["waitingtime"]: if isinstance(attraction, dict) and "code" in attraction:
sendMessage(f"Waiting time for {attraction['name']} increased to {attraction['waitingtime']} Minutes!", notificationType) if attraction["code"] in subscribedAttractions:
currentTimes[attraction["code"]] = attraction["waitingtime"] if attraction["status"] == "opened":
refreshTime = 30
if not attraction["code"] in currentTimes: currentTimes[attraction["code"]] = attraction["waitingtime"];
if currentTimes[attraction["code"]] > attraction["waitingtime"]:
sendMessage(f"Waiting time of {attraction['name']} sank to {attraction['waitingtime']} Minutes!", notificationType)
elif currentTimes[attraction["code"]] < attraction["waitingtime"]:
sendMessage(f"Waiting time for {attraction['name']} increased to {attraction['waitingtime']} Minutes!", notificationType)
currentTimes[attraction["code"]] = attraction["waitingtime"]
else:
refreshTime = 180
else: else:
refreshTime = 180 print(f"Info: Attraction was skipt because it has an invalid data structure. Affacted attraction: {attraction}")
except Exception as error:
raise Exception(f"Got an error while checking for differences since the last API call. Error: {error}")
# Main Loop # Main Loop
# Checks every 30 seconds for changes in the waiting times of the subscribed attractions # Checks every 30 seconds for changes in the waiting times of the subscribed attractions
@ -70,7 +92,10 @@ if __name__ == '__main__':
print("By Michi von Ah") print("By Michi von Ah")
print("Big thanks to the wartezeiten.app API!") print("Big thanks to the wartezeiten.app API!")
while True: while True:
checkTimes(subscribedAttractions, themepark) try:
print(f"Checked for updates at {time.strftime('%H:%M:%S', time.localtime())}") checkTimes(subscribedAttractions, themepark)
print(f"Checked for updates at {time.strftime('%H:%M:%S', time.localtime())}")
except Exception as error:
raise Exception(error)
time.sleep(refreshTime) time.sleep(refreshTime)