After spending some time(and failing!) to create a script to switch on my storage heaters at a certain time based on the highest temperature forecast that day I thought I’d try using OpenAI (ChatGPT) to create the script for me. Well it did it in no time whatsoever! The code it generated is below! I’ve not tested it yet but it looks pretty comprehensive to me and much better than I could do!
# Import required modules
import requests
import datetime
# Define API key and location for weather forecast
api_key = 'your_api_key'
location = 'your_location'
# Make API request to get forecast data
response = requests.get(f'https://api.openweathermap.org/data/2.5/forecast?q={location}&appid={api_key}')
forecast_data = response.json()
# Get the temperature forecast for today
today = datetime.datetime.now().strftime("%Y-%m-%d")
temperatures = []
for forecast in forecast_data['list']:
if forecast['dt_txt'].startswith(today):
temperatures.append(forecast['main']['temp'])
# Get the highest forecast temperature for today
highest_temperature = max(temperatures)
# Switch on device at different time based on temperature
if highest_temperature > 30:
switch_on_time = '12:00'
elif highest_temperature > 20:
switch_on_time = '14:00'
else:
switch_on_time = '16:00'
# Define switch on action
switch_on_action = {'service': 'switch.turn_on', 'entity_id': 'switch.your_switch'}
# Schedule switch on
schedule.run_at(switch_on_time, switch_on_action)
Not using AppDaemon. Just asked it to re-write the script without using Python imports! Hoping this one will work!
# Define API key and location for weather forecast
api_key = 'your_api_key'
location = 'your_location'
# Make API request to get forecast data
response = http.get(f'https://api.openweathermap.org/data/2.5/forecast?q={location}&appid={api_key}')
forecast_data = response.json()
# Get the temperature forecast for today
today = now().strftime("%Y-%m-%d")
temperatures = []
for forecast in forecast_data['list']:
if forecast['dt_txt'].startswith(today):
temperatures.append(forecast['main']['temp'])
# Get the highest forecast temperature for today
highest_temperature = max(temperatures)
# Switch on device at different time based on temperature
if highest_temperature > 30:
switch_on_time = '12:00'
elif highest_temperature > 20:
switch_on_time = '14:00'
else:
switch_on_time = '16:00'
# Define switch on action
switch_on_action = {'service': 'switch.turn_on', 'entity_id': 'switch.your_switch'}
# Schedule switch on
run_at(switch_on_time, switch_on_action)