[Python] Build a today’s weather bot

Vicky’s Notes
Javarevisited
Published in
3 min readApr 25, 2022

--

LINE Notify API

LINE is the most popular messaging app in Taiwan. Among the features, LINE Notify API with an authorized token allows web applications to pass notifications manually or automatically to a personal account or group account.

Line token: https://notify-bot.line.me/my/

Step 1. Invite LINE Notify to The Group

If you’d like to send messages to LINE groups instead of your personal account, remember to invite LINE Notify to the group before messaging so the group can receive the message first.

Step 2. Generate Token

Generate the token on this page. When you click “Generate token” and then see the token, copy it to a secure place because of the notice “If you leave this page, you will not be able to view your newly generated token again. Please copy the token before leaving this page.”

LINE API token
Note:
Line Notify allow you to generate a token as the key to authorization. You can apply more than one token for variant purposes. Moreover, you can remove not used tokens.

Step 3. Get Weather API credentials

There are a lot of free open-sourced weather APIs. I’ll be using OpenWeather, one of the most popular weather APIs, in this tutorial. The doc of the current weather can be seen here.

To get what your API key is, you should click “API keys” and copy your API key from here.

Step 4. Code

  1. Check if the API works or not. I’m more used to seeing a temperature in Celsius so I replace the parameter of the API call tounit=metric as below.
import requestsimport jsonapiKey = "Your API key from step 3"
lineToken = "Your token got from step 2"
# id = city IDurl = "https://api.openweathermap.org/data/2.5/weather?id=1668338&units=metric&appid=" + keyr = requests.get(url)
data = json.loads(r.text)
print(data)

The result will be similar to the below and status=200 means getting data successfully:

{'coord': {'lon': 121.6503, 'lat': 25.0486}, 'weather': [{'id': 803, 'main': 'Clouds', 'description': 'broken clouds', 'icon': '04n'}], 'base': 'stations', 'main': {'temp': 25.9, 'feels_like': 26.37, 'temp_min': 25.33, 'temp_max': 27.26, 'pressure': 1011, 'humidity': 70}, 'visibility': 9000, 'wind': {'speed': 3.09, 'deg': 100}, 'clouds': {'all': 75}, 'dt': 1650885341, 'sys': {'type': 2, 'id': 2032887, 'country': 'TW', 'sunrise': 1650835355, 'sunset': 1650881998}, 'timezone': 28800, 'id': 1668338, 'name': 'Taipei City', 'cod': 200}
{"status":200,"message":"ok"}

2. Cuz I only need the data of city, current temperature, highest temperature, lowest temperature, and weather description as the message below, the JSON data is handled for this purpose.

"""
# if units=imperial and it should be converted to metric additionally:
def tempToC(fTemp):
return round((fTemp - 32) * 5 / 9, 1)
temp = data["main"]["temp"])
temp_max = tempToC(data["main"]["temp_max"])
temp_min = tempToC(data["main"]["temp_min"])
"""
temp = data["main"]["temp"]
temp_max = data["main"]["temp_max"]
temp_min = data["main"]["temp_min"]
weather = data["weather"][0]["description"].capitalize()

3. The message I’m going to send via the weather bot is composed of this string:

msg = "%s\n 🌡Current temperature: %s°C\n 💌Highest temperature: %s\n 💌Lowest temperature: %s\n 💧%s" %(data['name'],temp,temp_max,temp_min,weather)

4. Now, we can use LINE notify API to send the HTTP request to send the message:

url = "https://notify-api.line.me/api/notify"
payload = {"message": {msg}}
headers = {"Authorization": "Bearer " + lineToken}
response = requests.request("POST", url, headers=headers, data=payload)
print(response.text)

5. To make the code run routinely at 7:30AM every day by using schedule the module:

import schedule
import time
schedule.every().day.at("07:30").do(sendToLine(lineToken,msg))
schedule.every(10).seconds.do(sendToLine, (lineToken))
while True:
schedule.run_pending()
time.sleep(1)

Voila!! Done!!🎉

--

--

Vicky’s Notes
Javarevisited

An IT enthusiast driven by the belief that success is not just about personal achievement but inspiring others to excel.