Python Send SMS with the rain warning Open Weather API and Twilio

Python Send SMS with the rain warning Open Weather API and Twilio

Table of contents

No heading

No headings in the article.

Today was yet another challenging task. And saying today I ment yesterday, cause I ran into some issues with setting environment variables online on a PythonEverywhere and it took me a while cause I had to refresh the state of my brain and come back to the issue next day. Also, along the way besides the challenges there were small issues from time to time so that was quite a work out for the brain and ability to search and find solutions you need. And what is the better way to learn then trying to repeat the same success, explaining what you do oneach step. the next day on your own, explaining and repeating everything. Writing this all on the next day out of my head So here we go. Ok, so the task was to create the weather program that will check the weather condition and send the message to the phone if it is going to be rainning. Firstly, let me explain my way of creating the environment variables. On the Python Everywhere I did it through the bash consol. First, I'll explain how I did it on PythonAnywhere.com: 1.Open your bash consol(and remember it should be separate bash consol that you've created and not the consol underneath that you see when you open your python file Screenshot 2022-07-22 180433.png

export SECRET_APP_KEY=here_goes_your_key_without_any_spaces_and_without_quotes

2.next step is to add those keys into your task as well (basically, to make the same thing): tasks.png

export SECRET_APP_KEY=here_goes_your_key; python3 main.py

3.Finally, to use those keys in my python I use os module. For example:

app_key = os.environ.get('SECRET_OWM_APP_KEY')

Back to the main subject of todays article: Since, I am going to use the data from the OpenWeatherMap service I need to register ther and follow their rules to work with their API (aka Automatic Programming Interface) To work with API in python I will need the requests module. import requests First i define the endpoint (aka destination, aka link, which is provided in the API documentation on the website)

endpoint = "https://api.openweathermap.org/data/2.5/onecall"

remember to put everything before the question mark(after question mark there go all the parameters that can be changed depending on the needs) Next I set the api key and make it a environmental variable:

app_key = os.environ.get('SECRET_OWM_APP_KEY')

Now, I use One Call Api, so the main parameters that are a must are:

  • longitude
  • latitude
  • app_key to find latitude and longitude you can use the latlong.net service:
    LAT = 53.5988
    LONG = 7.1967
    
    and also I created new dictionary with all the parameters:
    parameters = {
      "lat": LAT,
      "lon": LONG,
      "appid": app_key,
      "exclude": "current,minutely,daily"
    }
    
    finally, combining endpont and parameters I can request the data and to convert it to a json format: Also, to know the issue if there are going to be any regarding the connection to API I raise the Error status:
    response = requests.get(endpoint, params=parameters)
    response.raise_for_status()
    data = response.json()
    
    if you will paste all the parameters into the example link:
    https://api.openweathermap.org/data/2.5/onecall?lat=53.5988&lon=7.1967&exclude=current,minutely,daily&appid=d9d58c0b82a156f5540482dd5819abb7
    
    it is going to be the same if you will print out the 'data' in which i put the json format of the response:

Screenshot 2022-07-22 195539.png response 1.png If you will paste the printed line into the jsonviewer You will see the structure more clearly:

Screenshot 2022-07-22 200050.png

Now, if I would want to get the weather condition value:

print(data["hourly"][0]["weather"][0]["id"])

"Box inside of the box inside of the box... and ets." :) Back to the main subject. In the main task we are interested in first 12 hours of the day, so the slice comes in hand:

hourly_weather = data["hourly"]
hourly_weather_for12 = hourly_weather[:12]

Now i need to check each our the weather condition and if any of them are going to be bigger than 800 than I will need an ambrella:

for hour in hourly_weather_for12:
    weather_condition = hour["weather"][0]["id"]
    if int(weather_condition) < 700:

There might be multiple hours when it is going to rain during those 12 hours So before for loop I create boolean :

will_rain = False
for hour in ................

and inside of the if statement inside of the for loop I switch it to True:

will_rain = True

to print the message only one time I can just create boolean and check if it is true than print the message

if will_rain:
    print("bring the umbrella it is going to rain")

This is not the end yet. Finally, wecame to sending message so insted of printing the message into the consol we are going to send message to the mobile phone. To do that we are going to use yet another service Twilio.com First, we will need to register that passing all the verifications like email verification and phone verification. After, that take a look at the documentation and go to your account there you will find your account sid and token and the number from which you are going to send messages. Now if you red the documentation you will know where this code is comming from:

    client = Client(account_sid, auth_token)
    message = client.messages \
            .create(
            body="bring the umbrella it is going to rain",
            from_='+00000000000',
            to='+00000000000'
        )

put this code after print("bring the umbrella it is going to rain") and finally to know the status of the operation just print the status out inside the if statement:

    print(message.status)