Last active
July 17, 2024 23:15
-
-
Save yodaluca23/ad217b927e9561bc9bec27cf7b9cd3cd to your computer and use it in GitHub Desktop.
Get weather from the CLI! No idea why you would want to do this but now you can!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import requests | |
import re | |
from datetime import datetime | |
def extract_appid(): | |
url = "https://openweathermap.org/themes/openweathermap/assets/vendor/owm/js/weather-app.cb2cf0fb.js" | |
try: | |
response = requests.get(url) | |
response.raise_for_status() # Raise an error for bad status codes | |
content = response.text | |
# Use regex to find appid:"*" | |
match = re.search(r'appid:"(.*?)"', content) | |
if match: | |
return match.group(1) | |
else: | |
return None | |
except requests.RequestException as e: | |
print(f"Error fetching the URL: {e}") | |
return None | |
def get_location_ip(): | |
try: | |
response = requests.get('https://ipinfo.io/json') | |
data = response.json() | |
loc = data['loc'].split(',') | |
latitude = float(loc[0]) | |
longitude = float(loc[1]) | |
return latitude, longitude | |
except Exception as e: | |
print(f"Error fetching location data: {e}") | |
return None, None | |
def get_location(city, api_key): | |
url = f'https://openweathermap.org/data/2.5/find?q={city}&units=Imperial&appid={api_key}' | |
response = requests.get(url) | |
if response.status_code == 200: | |
data = response.json() | |
if data and data["count"] > 0: | |
first_city = data["list"][0] | |
lat = first_city["coord"]["lat"] | |
lon = first_city["coord"]["lon"] | |
return lat, lon | |
else: | |
print(f"Error: Unable to fetch data for {city}") | |
return None | |
def convert_unix_timestamp(timestamp, format_type): | |
if format_type == 'day': | |
return datetime.utcfromtimestamp(timestamp).strftime('%A') | |
elif format_type == 'hourOnly': | |
timehour = datetime.utcfromtimestamp(timestamp).strftime('%I %p') | |
result = timehour.replace('0', '') | |
return result | |
elif format_type == 'day_hour': | |
timeday = datetime.utcfromtimestamp(timestamp).strftime('%A: %I %p') | |
result = timeday.replace('0', '') | |
return result | |
elif format_type == 'time': | |
return datetime.utcfromtimestamp(timestamp).strftime('%H:%M:%S').replace(':00', '') | |
else: | |
return datetime.utcfromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M:%S') | |
def calculate_moon_phase(phase): | |
phases = [ | |
"New Moon", | |
"Waxing Crescent", | |
"First Quarter", | |
"Waxing Gibbous", | |
"Full Moon", | |
"Waning Gibbous", | |
"Last Quarter", | |
"Waning Crescent" | |
] | |
index = int(phase * 8) % 8 | |
return phases[index] | |
def parse_data(weather_data, units): | |
result = [] | |
# Parsing hourly data | |
if 'hourly' in weather_data: | |
result.append("Hourly data:") | |
for hour in weather_data['hourly']: | |
result.append(f" {convert_unix_timestamp(hour['dt'], 'day_hour')}") | |
result.append(f" Temperature: {hour['temp']} °{units}") | |
result.append(f" Feels like: {hour['feels_like']} °{units}") | |
result.append(f" Pressure: {hour['pressure']} hPa") | |
result.append(f" Humidity: {hour['humidity']}%") | |
result.append(f" Dew point: {hour['dew_point']} °{units}") | |
result.append(f" Clouds: {hour['clouds']}%") | |
result.append(f" Wind speed: {hour['wind_speed']} m/s") | |
result.append(f" Wind direction: {hour['wind_deg']}°") | |
result.append(f" Weather: {hour['weather'][0]['description']}") | |
result.append(f" Pop: {hour['pop']}%") | |
visibility = hour.get('visibility', 'N/A') | |
result.append(f" Visibility: {visibility} meters") | |
else: | |
result.append("Hourly data not available") | |
# Parsing daily data | |
for day in weather_data['daily']: | |
result.append(f"Date: {convert_unix_timestamp(day['dt'], 'day')}") | |
result.append(f" Sunrise: {convert_unix_timestamp(day['sunrise'], 'time')}") | |
result.append(f" Sunset: {convert_unix_timestamp(day['sunset'], 'time')}") | |
result.append(f" Moonrise: {convert_unix_timestamp(day['moonrise'], 'time')}") | |
result.append(f" Moonset: {convert_unix_timestamp(day['moonset'], 'time')}") | |
result.append(f" Moon phase: {calculate_moon_phase(day['moon_phase'])}") | |
return result | |
def get_weather_data(lat, lon, units, api_key): | |
if units == "F": | |
units = "imperial" | |
else: | |
units = "metric" | |
url = f"https://openweathermap.org/data/2.5/onecall?lat={lat}&lon={lon}&units={units}&appid={api_key}" | |
response = requests.get(url) | |
if response.status_code == 200: | |
weather_data = response.json() | |
return weather_data | |
else: | |
print("Failed to get weather data") | |
return None | |
def main(): | |
appid = extract_appid() | |
city = input("Enter the city name: ") | |
if city.lower().replace(' ', '') == "mylocation": | |
lat, lon = get_location_ip() | |
else: | |
lat, lon = get_location(city, appid) | |
if lat and lon: | |
print(f"Your location: Latitude: {lat}, Longitude: {lon}") | |
units = input("Enter 'F' for Fahrenheit or 'C' for Celsius: ").replace(' ', '') | |
if units in ["F", "C"]: | |
weather_data = get_weather_data(lat, lon, units, appid) | |
if weather_data: | |
parsed_weather_data = parse_data(weather_data, units) | |
for data in parsed_weather_data: | |
print(data) | |
else: | |
print("Could not fetch weather data.") | |
else: | |
print("Invalid unit entered. Please enter 'imperial' or 'metric'.") | |
else: | |
print("Could not fetch location data.") | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment