LoginSignup
0
2

社内SE、ラズパイ4を買う。パート5(APIから明日の天気情報を取得し、Line通知する)

Last updated at Posted at 2023-10-02

・前回

・今回やりたいこと

どっかのAPIから住んでいる地域の降水確率を取得して、ライン通知する。

・解決したい課題

家にテレビがないし、朝起きるのがギリギリなので、前日中に降水確率をチェックして傘を持っていくべきか判断したい。午前中晴れ→午後雨のパターンでいつもびしょぬれになっている。

・技術的なポイント
Line通知は前回やったので

今回はどっかのAPIを叩いて降水確率のデータを取得すればよい。

今回はこちらを使わせていただく。

また、APIの叩き方についてはこちらを参考にさせていただいた。

一時間ぐらい格闘して完成したものがこちらになります。
(生まれて初めてAPI叩いてJSONいじった)

def LinePrint(msg):

# -*- coding:utf-8 -*-
import requests
import json

jma_url = "https://weather.tsukumijima.net/api/forecast/city/(地域コード)"
jma_json = requests.get(jma_url).json()

# 明日のデータなので、forecast[1] 0は今日のデータ
jma_date = jma_json["forecasts"][1]["dateLabel"]
jma_weather = jma_json["forecasts"][1]["telop"]
jma_rainfall_1 = jma_json["forecasts"][1]["chanceOfRain"]["T00_06"]
jma_rainfall_2 = jma_json["forecasts"][1]["chanceOfRain"]["T06_12"]
jma_rainfall_3 = jma_json["forecasts"][1]["chanceOfRain"]["T12_18"]
jma_rainfall_4 = jma_json["forecasts"][1]["chanceOfRain"]["T18_24"]
jma_max = jma_json["forecasts"][1]["temperature"]["max"]["celsius"]
jma_min = jma_json["forecasts"][1]["temperature"]["min"]["celsius"]
# 全角スペースの削除
jma_weather = jma_weather.replace(' ', '')

message = "\n" + jma_date + "の天気は" + jma_weather + "\n" + "最高気温" + jma_max + "度\n" + "最低気温" + jma_min +"度\n" + "降水確率\n" +"0時-6時 " + jma_rainfall_1 + "\n6時-12時 " + jma_rainfall_2 + "\n12時-18時 " + jma_rainfall_3 + "\n18時-24時 " + jma_rainfall_4 + "\nです"

import requests
token='(Line Notifyトークン)'
headers = {'Authorization': 'Bearer %s'%token, }        
files = {'message': (None, message),}
r = requests.post('https://notify-api.line.me/api/notify', headers=headers, files=files)
print(r,r.text)

LinePrint('')

追記
出力はこんな感じ(書くの忘れてた)
image.png

なあ~んだ、APIとかJSONとか怖いものかと思ってたけど、自分で頑張っていじってみれば全然怖くないじゃんか(思い上がり)

あとはこいつをいつものcronで定時実行して、終わり!

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2