EasyBot / weatherr.py
NitinBot001's picture
Upload 3 files
374cabb verified
# weatherr.py
import requests
import os
from dotenv import load_dotenv
load_dotenv()
# Replace with your API keys
OPENCAGE_API_KEY = os.getenv("OPENCAGE_API_KEY")
OPENWEATHER_API_KEY = os.getenv("OPENWEATHER_API_KEY")
def get_weather(
latitude: float = None,
longitude: float = None,
address: str = None,
district: str = None,
state: str = None,
units: str = "metric" # "metric" or "imperial"
) -> dict:
"""
Fetch current weather using coordinates or location name (address/district/state).
Returns structured weather info from OpenWeatherMap.
"""
# Step 1: Determine coordinates
if latitude is None or longitude is None:
if address:
query = address
elif district and state:
query = f"{district}, {state}"
elif district:
query = district
else:
return {"error": "Provide either coordinates or location name (address/district+state)."}
# Use OpenCageData geocoding
geocode_url = "https://api.opencagedata.com/geocode/v1/json"
params = {
"q": query,
"key": OPENCAGE_API_KEY,
"limit": 1,
"no_annotations": 1
}
try:
resp = requests.get(geocode_url, params=params, timeout=10)
resp.raise_for_status()
data = resp.json()
if data["results"]:
latitude = data["results"][0]["geometry"]["lat"]
longitude = data["results"][0]["geometry"]["lng"]
else:
return {"error": f"Location not found: {query}"}
except Exception as e:
return {"error": f"Geocoding error: {e}"}
# Step 2: Fetch weather from OpenWeatherMap
weather_url = "https://api.openweathermap.org/data/2.5/weather"
params = {
"lat": latitude,
"lon": longitude,
"appid": OPENWEATHER_API_KEY,
"units": units
}
try:
resp = requests.get(weather_url, params=params, timeout=10)
resp.raise_for_status()
return {"success": True, "data": resp.json()}
except Exception as e:
return {"error": f"Weather API error: {e}"}
# Example usage:
if __name__ == "__main__":
res = get_weather(district="Bilaspur", state="Chhattisgarh")
res2 = get_weather(latitude=22.0934, longitude=82.1564)
res3 = get_weather(address="Bilaspur, Chhattisgarh")
print(res)
print(res2)
print(res3)