Skip to content

IvanCampos/agents / skills/open-meteo-weather

open-meteo-weather

Verified

Get current weather using the Open-Meteo API. Use for requests like “current weather in Boston,” “get weather for Medford, MA,” or any task that needs a quick current_weather lookup via Open-Meteo (by location name or lat/lon). Use when the user wants a direct API call or a tiny CLI flow to fetch current conditions.

FileKindSize
SKILL.mdskill md1.9 KB
agents/openai.yamlconfig108 B
references/open_meteo.mdmarkdown780 B
scripts/open_meteo_current.pyexecutablescript6.0 KB

scripts/open_meteo_current.py

View on GitHub
#!/usr/bin/env python3
import argparse
import json
import sys
import urllib.parse
import urllib.request

GEO_URL = "https://geocoding-api.open-meteo.com/v1/search"
FORECAST_URL = "https://api.open-meteo.com/v1/forecast"


def http_get_json(url: str) -> dict:
    req = urllib.request.Request(url, headers={"User-Agent": "codex-open-meteo-weather/1.0"})
    with urllib.request.urlopen(req, timeout=15) as resp:
        data = resp.read()
    return json.loads(data.decode("utf-8"))


def geocode(name: str, count: int = 1) -> dict:
    params = {
        "name": name,
        "count": str(count),
        "language": "en",
        "format": "json",
    }
    url = f"{GEO_URL}?{urllib.parse.urlencode(params)}"
    return http_get_json(url)


def normalize_token(value: str | None) -> str | None:
    if value is None:
        return None
    return value.strip().lower()


def pick_best_result(results: list[dict], qualifier: str | None) -> dict | None:
    if not results:
        return None
    if not qualifier:
        return results[0]
    qual = normalize_token(qualifier)
    if not qual:
        return results[0]

    def matches(hit: dict, field: str) -> bool:
        value = normalize_token(hit.get(field))
        return value == qual

    for hit in results:
        if matches(hit, "admin1") or matches(hit, "country"):
            return hit
    for hit in results:
        admin1 = normalize_token(hit.get("admin1"))
        country = normalize_token(hit.get("country"))
        if admin1 and qual in admin1:
            return hit
        if country and qual in country:
            return hit
    return results[0]


def current_weather(lat: float, lon: float, timezone: str, temp_unit: str | None, wind_unit: str | None) -> dict:
    params = {
        "latitude": f"{lat:.6f}",
        "longitude": f"{lon:.6f}",
        "current_weather": "true",
        "timezone": timezone,
    }
    if temp_unit:
        params["temperature_unit"] = temp_unit
    if wind_unit:
        params["windspeed_unit"] = wind_unit

    url = f"{FORECAST_URL}?{urllib.parse.urlencode(params)}"
    return http_get_json(url)


def c_to_f(celsius: float) -> float:
    return (celsius * 9.0 / 5.0) + 32.0


def f_to_c(fahrenheit: float) -> float:
    return (fahrenheit - 32.0) * 5.0 / 9.0


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description="Fetch current weather from Open-Meteo.")
    parser.add_argument("--lat", type=float, help="Latitude")
    parser.add_argument("--lon", type=float, help="Longitude")
    parser.add_argument("--location", type=str, help='Location name, e.g. "Boston, MA"')
    parser.add_argument("--postal-code", type=str, help="Postal code override for location metadata")
    parser.add_argument("--timezone", type=str, default="auto", help="Timezone (default: auto)")
    parser.add_argument("--temperature-unit", type=str, choices=["celsius", "fahrenheit"], help="Temperature unit")
    parser.add_argument(
        "--windspeed-unit",
        type=str,
        choices=["kmh", "mph", "ms", "kn"],
        help="Wind speed unit",
    )
    return parser.parse_args()


def main() -> int:
    args = parse_args()

    if args.location:
        name = args.location
        qualifier = None
        if "," in args.location:
            parts = [part.strip() for part in args.location.split(",", 1)]
            name = parts[0]
            qualifier = parts[1] if len(parts) > 1 else None

        geo = geocode(name, count=10)
        results = geo.get("results") or []
        if not results and "," in args.location:
            fallback = args.location.split(",", 1)[0].strip()
            geo = geocode(fallback, count=10)
            results = geo.get("results") or []
        if not results:
            print(json.dumps({"error": "No geocoding results", "query": args.location}, indent=2))
            return 2
        hit = pick_best_result(results, qualifier)
        if not hit:
            print(json.dumps({"error": "No matching geocoding result", "query": args.location}, indent=2))
            return 2
        lat = hit["latitude"]
        lon = hit["longitude"]
        place = {
            "name": hit.get("name"),
            "admin1": hit.get("admin1"),
            "country": hit.get("country"),
            "latitude": lat,
            "longitude": lon,
        }
    elif args.lat is not None and args.lon is not None:
        lat = args.lat
        lon = args.lon
        place = {"latitude": lat, "longitude": lon}
    else:
        print("Provide either --location or both --lat and --lon", file=sys.stderr)
        return 2

    data = current_weather(
        lat,
        lon,
        args.timezone,
        args.temperature_unit,
        args.windspeed_unit,
    )

    current = data.get("current_weather") or {}
    temp_value = current.get("temperature")
    temp_unit = args.temperature_unit or "celsius"
    temp_c = None
    temp_f = None
    if isinstance(temp_value, (int, float)):
        if temp_unit == "fahrenheit":
            temp_f = float(temp_value)
            temp_c = f_to_c(temp_f)
        else:
            temp_c = float(temp_value)
            temp_f = c_to_f(temp_c)

    windspeed = current.get("windspeed")
    winddirection = current.get("winddirection")
    weathercode = current.get("weathercode")
    is_day = current.get("is_day")
    time_value = current.get("time")

    if args.postal_code:
        place = dict(place)
        place["postal_code"] = args.postal_code

    output = {
        "location": place,
        "current_weather": {
            "time": time_value,
            "interval": current.get("interval"),
            "temperature_c": round(temp_c, 2) if temp_c is not None else None,
            "temperature_f": round(temp_f, 2) if temp_f is not None else None,
            "windspeed_kmh": windspeed,
            "winddirection_deg": winddirection,
            "weathercode": weathercode,
            "is_day": bool(is_day) if is_day is not None else None,
        },
    }

    print(json.dumps(output, indent=2))
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
receiving-code-reviewobra/superpowersUse when receiving code review feedback, before implementing suggestions, especially if feedback seems unclear or technically questionable - requires technical rigor and verification, not performative agreement or blind implementationStars: 322kUpdated Claude CodeCodexVerifiedInstall
requesting-code-reviewobra/superpowersUse when completing tasks, implementing major features, or before merging to verify work meets requirementsStars: 322kUpdated Claude CodeCodexVerifiedInstall
using-git-worktreesobra/superpowersUse when starting feature work that needs isolation from current workspace or before executing implementation plans - ensures an isolated workspace exists via native tools or git worktree fallbackStars: 322kUpdated Claude CodeCodexVerifiedInstall
verification-before-completionobra/superpowersUse when about to claim work is complete, fixed, or passing, before committing or creating PRs - requires running verification commands and confirming output before making any success claims; evidence before assertions alwaysStars: 322kUpdated Claude CodeCodexVerifiedInstall