Weather Forecast Script


python geopy

Example Usage: python3 97103


exten => _xxxx.,1,System(python3 /tmp/json/ ${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
        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(

    # Get weather forecast from
    if lat_long is None:
        print("Error: Could not convert zip code to latitude and longitude.")
        lat_long_str = "{:.3f},{:.3f}".format(lat_long[0], lat_long[1])
        url = '{}&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 = ( + 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)
            print("Error retrieving data from Status code: {response.status_code}")

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

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