Skip to content

Commit cdaafea

Browse files
committed
v0.75051 - NWS in config.ini
1 parent 872e041 commit cdaafea

File tree

5 files changed

+52
-12
lines changed

5 files changed

+52
-12
lines changed

README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -236,6 +236,9 @@ If you run into any issues, consult the logs or reach out on the repository's [I
236236
---
237237

238238
# Changelog
239+
- v0.75051 - updated `config.ini` for configuring NWS weather forecasts & alerts
240+
- suggested method would be to supplement via NWS the things you need
241+
- I highly recommend leaving U.S. NWS's alerts on in `config.ini`, even if you have other fetching methods enabled (i.e. OpenWeatherMap), rather be safe than sorry
239242
- v0.7505 - U.S. NWS (National Weather Service, [weather.gov](https://weather.gov)) added as a weather data source
240243
- for additional information; **especially weather alerts**
241244
- all data will be combined from OpenWeatherMap and U.S. NWS sources by default

config/config.ini

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -168,3 +168,18 @@ Timeout = 30
168168

169169
# Chunk size for translation
170170
ChunkSize = 500
171+
172+
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
173+
# U.S. National Weather Service (NWS)
174+
# (weather.gov)
175+
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
176+
[NWS]
177+
# Fetch NWS foreacsts and/or alerts? (true/false)
178+
# Note that the service can be slow and unreliable at times.
179+
# I recommand getting the alerts to supplement i.e. OpenWeatherMap.
180+
# The alerts usually work, but sadly their open API forecasts are often broken.
181+
FetchNWSForecast = false
182+
FetchNWSAlerts = true
183+
NWSUserAgent = ChatKekeWeather/1.0 ([email protected])
184+
NWSRetries = 3
185+
NWSRetryDelay = 2

src/api_get_nws_weather.py

Lines changed: 16 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -9,17 +9,12 @@
99
import asyncio
1010
import httpx
1111
import logging
12+
from config_paths import NWS_USER_AGENT, NWS_RETRIES, NWS_RETRY_DELAY, FETCH_NWS_FORECAST, FETCH_NWS_ALERTS
1213

1314
# Base URL for NWS API
1415
NWS_BASE_URL = 'https://api.weather.gov'
1516

16-
# Custom User-Agent as per NWS API requirements
17-
USER_AGENT = 'ChatKekeWeather/1.0 ([email protected])'
18-
19-
# Default number of retries if not specified
20-
RETRIES = 0
21-
22-
async def get_nws_forecast(lat, lon, retries=RETRIES, delay=2):
17+
async def get_nws_forecast(lat, lon, retries=NWS_RETRIES, delay=NWS_RETRY_DELAY):
2318
"""
2419
Fetches the forecast from the NWS API for the given latitude and longitude.
2520
@@ -32,6 +27,11 @@ async def get_nws_forecast(lat, lon, retries=RETRIES, delay=2):
3227
Returns:
3328
dict: Combined forecast data or None if fetching fails.
3429
"""
30+
31+
if not FETCH_NWS_FORECAST:
32+
logging.info("Fetching NWS forecast is disabled in the config.")
33+
return None
34+
3535
# Round coordinates to 4 decimal places
3636
lat = round(lat, 4)
3737
lon = round(lon, 4)
@@ -41,7 +41,7 @@ async def get_nws_forecast(lat, lon, retries=RETRIES, delay=2):
4141
for attempt in range(retries + 1): # Ensure at least one attempt is made
4242
try:
4343
# Step 1: Retrieve metadata for the location
44-
response = await client.get(points_url, headers={'User-Agent': USER_AGENT})
44+
response = await client.get(points_url, headers={'User-Agent': NWS_USER_AGENT})
4545
response.raise_for_status()
4646
points_data = response.json()
4747

@@ -50,15 +50,15 @@ async def get_nws_forecast(lat, lon, retries=RETRIES, delay=2):
5050
forecast_hourly_url = points_data['properties'].get('forecastHourly')
5151

5252
# Step 2: Retrieve forecast data
53-
forecast_response = await client.get(forecast_url, headers={'User-Agent': USER_AGENT})
53+
forecast_response = await client.get(forecast_url, headers={'User-Agent': NWS_USER_AGENT})
5454
forecast_response.raise_for_status()
5555
forecast_data = forecast_response.json()
5656

5757
# Step 3: Retrieve hourly forecast data
5858
forecast_hourly_data = None
5959
if forecast_hourly_url:
6060
try:
61-
forecast_hourly_response = await client.get(forecast_hourly_url, headers={'User-Agent': USER_AGENT})
61+
forecast_hourly_response = await client.get(forecast_hourly_url, headers={'User-Agent': NWS_USER_AGENT})
6262
forecast_hourly_response.raise_for_status()
6363
forecast_hourly_data = forecast_hourly_response.json()
6464
except httpx.HTTPStatusError as e:
@@ -93,11 +93,16 @@ async def get_nws_alerts(lat, lon):
9393
Returns:
9494
list: A list of active alerts or an empty list if none are found.
9595
"""
96+
97+
if not FETCH_NWS_ALERTS:
98+
logging.info("Fetching NWS alerts is disabled in the config.")
99+
return []
100+
96101
alerts_url = f"{NWS_BASE_URL}/alerts/active?point={lat},{lon}"
97102

98103
async with httpx.AsyncClient() as client:
99104
try:
100-
response = await client.get(alerts_url, headers={'User-Agent': USER_AGENT})
105+
response = await client.get(alerts_url, headers={'User-Agent': NWS_USER_AGENT})
101106
response.raise_for_status()
102107
alerts_data = response.json()
103108

src/config_paths.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,11 @@
2929
ELASTICSEARCH_USERNAME = ''
3030
ELASTICSEARCH_PASSWORD = ''
3131

32+
# Default NWS settings
33+
NWS_USER_AGENT = 'ChatKekeWeather/1.0 ([email protected])'
34+
NWS_RETRIES = 0
35+
NWS_RETRY_DELAY = 2
36+
3237
# Attempt to read the configuration file
3338
if CONFIG_PATH.exists():
3439
try:
@@ -71,6 +76,18 @@
7176
ELASTICSEARCH_USERNAME = ''
7277
ELASTICSEARCH_PASSWORD = ''
7378
logger.warning("Elasticsearch section missing in config.ini. Using default Elasticsearch settings.")
79+
80+
# NWS Configuration
81+
if 'NWS' in config:
82+
NWS_USER_AGENT = config['NWS'].get('NWSUserAgent', fallback='ChatKekeWeather/1.0 ([email protected])')
83+
NWS_RETRIES = config['NWS'].getint('NWSRetries', fallback=0)
84+
NWS_RETRY_DELAY = config['NWS'].getint('NWSRetryDelay', fallback=2)
85+
FETCH_NWS_FORECAST = config['NWS'].getboolean('FetchNWSForecast', fallback=True)
86+
FETCH_NWS_ALERTS = config['NWS'].getboolean('FetchNWSAlerts', fallback=True)
87+
logger.info(f"NWS Config: User-Agent={NWS_USER_AGENT}, Retries={NWS_RETRIES}, Retry Delay={NWS_RETRY_DELAY}, Fetch Forecast={FETCH_NWS_FORECAST}, Fetch Alerts={FETCH_NWS_ALERTS}")
88+
else:
89+
logger.warning("NWS section not found in config.ini. Using default NWS settings.")
90+
7491
except Exception as e:
7592
# Handle exceptions during config parsing
7693
logger.error(f"Error reading configuration file: {e}")

src/main.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
# https://github.com/FlyingFathead/TelegramBot-OpenAI-API
66
#
77
# version of this program
8-
version_number = "0.7505"
8+
version_number = "0.75051"
99

1010
# Add the project root directory to Python's path
1111
import sys

0 commit comments

Comments
 (0)