Py-Hanabi/site_api.py

42 lines
1.1 KiB
Python
Raw Normal View History

import json
2023-06-25 10:07:11 +02:00
from typing import Optional, Dict
import requests_cache
2023-05-14 14:04:57 +02:00
from log_setup import logger
2023-05-13 23:25:15 +02:00
# Cache all requests to site to reduce traffic and latency
session = requests_cache.CachedSession('hanab.live')
2023-05-13 23:25:15 +02:00
2023-06-25 10:07:11 +02:00
def get(url, refresh=False) -> Optional[Dict]:
2023-05-13 23:25:15 +02:00
# print("sending request for " + url)
query = "https://hanab.live/" + url
logger.debug("GET {} (force_refresh={})".format(query, refresh))
2023-05-14 14:04:57 +02:00
response = session.get(query, force_refresh=refresh)
2023-05-13 23:25:15 +02:00
if not response:
2023-05-14 14:04:57 +02:00
logger.error("Failed to get request {} from hanab.live".format(query))
return None
if not response.status_code == 200:
return None
if "application/json" in response.headers['content-type']:
return json.loads(response.text)
2023-05-14 14:04:57 +02:00
def api(url, refresh=False):
link = "api/v1/" + url
if "?" in url:
link += "&"
else:
link += "?"
link += "size=100"
2023-05-14 14:04:57 +02:00
return get(link, refresh)
def replay(seed):
r = api("seed/" + str(seed))
try:
game_id = r['rows'][0]['id']
except TypeError:
return None
return get("export/" + str(game_id))