from tennis import get_time_slots, get_club_address from weather import WeatherAPI from datetime import timedelta, datetime import asyncio as aio # Provided by my code monkey Lander GOOD_CODES = [1000, 1003, 1006, 1009, 1150, 1153] async def get_decent_timeslots(club_id, weather_api_key, days=1): club_address = await get_club_address(club_id) if club_address is None: return None weather_api = WeatherAPI(weather_api_key) weather_forecasts, timeslots = await aio.gather( weather_api.get_hourly_conditions(club_address, days=days), get_time_slots(club_id, days=days), ) # Filter out bad weather forecasts & sort them according to date & time weather_forecasts = sorted( filter(lambda x: x[2] in GOOD_CODES, weather_forecasts), key=lambda x: x[0] ) # Convert weather_forecasts to dict for faster lookups weather_forecasts = { date_obj: weather_str for date_obj, weather_str, _ in weather_forecasts } # Filter out non-free timeslots or timeslots in the past now = datetime.now() timeslots = list(filter(lambda x: x[1] == 0 and x[2] > now, timeslots)) output = [] for field_name, _, start_time, duration in timeslots: start_hour = start_time.replace(minute=0) weather_names = [] valid = True while start_hour < start_time + duration: if weather_name := weather_forecasts.get(start_hour): weather_names.append(weather_name) # If we can't find any information about the timeslot, we assume # it's bad else: valid = False break start_hour += timedelta(hours=1) if valid: output.append((field_name, start_time, duration, weather_names)) return output