Weather Forecast Script

Requirements:

hamvoip tts_audio.sh
python geopy
python3.5

Example Usage: python3 weather.py 97103

extensions.conf

[zip]
exten => _xxxx.,1,System(python3 /tmp/json/zip2.py ${EXTEN})
exten => _xxx.,n,Hangup()

import os
import sys
import argparse
import requests
import json
from datetime import datetime, timedelta
from geopy.geocoders import Nominatim

def zip_to_lat_long(zipcode):
    geolocator = Nominatim(user_agent="my_app")  # initialize geolocator
    location = geolocator.geocode(zipcode, timeout=10)
    if location is None:  # if geocoding fails, return None
        return None
    else:
        return (location.latitude, location.longitude)  # return latitude and longitude as a tuple

if __name__ == "__main__":
    # Define and parse command line arguments
    parser = argparse.ArgumentParser()
    parser.add_argument("zip", help="Zip code to retrieve weather forecast")
    args = parser.parse_args()

    # Convert zip code to latitude and longitude
    lat_long = zip_to_lat_long(args.zip)

    # Get weather forecast from weather.gov
    if lat_long is None:
        print("Error: Could not convert zip code to latitude and longitude.")
    else:
        lat_long_str = "{:.3f},{:.3f}".format(lat_long[0], lat_long[1])
        url = 'https://forecast.weather.gov/MapClick.php?lat={}&lon={}&FcstType=json&TextType=2'.format(lat_long_str.split(',')[0], lat_long_str.split(',')[1])
        response = requests.get(url)

        if response.status_code == 200:
            data = json.loads(response.content.decode('utf-8'))

            tomorrow = (datetime.now() + timedelta(days=0)).strftime('%Y-%m-%d')

            with open('/tmp/json/tomorrow.txt', 'w') as f:
                for i in range(len(data['time']['startValidTime'])):
                    start_valid_time = data['time']['startValidTime'][i]
                    start_period_name = data['time']['startPeriodName'][i]
                    temperature = data['data']['temperature'][i]
                    weather = data['data']['weather'][i] #Shortened Forecast.
                    text = data['data']['text'][i] #Full forecast not added in Print.

                    if start_valid_time.startswith(tomorrow):
                        print("{}: {} degrees, {}".format(start_period_name, temperature, weather), file=f)
        else:
            print("Error retrieving data from weather.gov. Status code: {response.status_code}")

    os.system("/bin/bash /usr/local/bin/tts_audio.sh /tmp/json/tomorrow.txt")

    os.system("asterisk -rx \"rpt localplay NODE# /tmp/json/tomorrow\"")