0
0

AWS LambdaとEventbridgeを使って毎朝7時に気象庁天気予報をLINEに通知

Posted at

概要

気象庁から天気予報データを取得、必要情報を抽出してLINEに通知するLambdaを作成して、Eventbridgeで毎朝7時に起動するよう設定しました。

準備

作成

  • Lambda作成
    Lambda作成方法は他の有志の方の記事または公式を参照ください。
    なお、PythonのRequestsモジュールをLambdaで使用するためにはLayerの追加の必要があります。
    • エリアコードは東京地方の天気を対象としています
    • 抽出データは、時間、天気、6時間ごとの降水確率と最高気温です
    • 【LINE Notifyアクセストークン】を取得したアクセストークンに置き換えてください
python.py
import requests
import json
import io

def lambda_handler(event, context):
    try:
        # import data from jma
        jma_url = "https://www.jma.go.jp/bosai/forecast/data/forecast/130000.json"
        jma_json = requests.get(jma_url).json()

        jma_timeDefines0 = jma_json[0]["timeSeries"][0]["timeDefines"][0]
        jma_weathers0 = jma_json[0]["timeSeries"][0]["areas"][0]["weathers"][0]
        jma_pops0 = jma_json[0]["timeSeries"][1]["areas"][0]["pops"][0]
        jma_pops1 = jma_json[0]["timeSeries"][1]["areas"][0]["pops"][1]
        jma_pops2 = jma_json[0]["timeSeries"][1]["areas"][0]["pops"][2]
        jma_temps1 = jma_json[0]["timeSeries"][2]["areas"][0]["temps"][1]

        # replace
        jma_timeDefines0 = jma_timeDefines0.replace('T',' ')
        jma_weathers0 = jma_weathers0.replace(' ','')
        
        headers = {
           'Authorization': 'Bearer 【LINE Notifyアクセストークン】',
        }

        # Post to LINE
        files = {
            'message': (None, '東京の天気\n' + jma_timeDefines0[:16] + '発表\n'\
             + '天気: ' + jma_weathers0 + '\n'\
             + '降水確率6H毎: ' + jma_pops0 + '% ' + jma_pops1 + '% ' + jma_pops2 + '%\n'\
             + '日中最高気温: ' + jma_temps1 + '°C'),
        }

        requests.post('https://notify-api.line.me/api/notify', headers=headers, files=files)

    except Exception as e:
        print('ERROR: bad Event!', flush=True)
        raise
  • Eventbridge
    他の有志の方の記事や公式を参照いただき、上記Lambdaを毎朝7時に起動するようスケジュールします。

実行結果

以下のように表示されれば成功です。

出典

以下の気象庁ホームページを利用して作成
https://www.jma.go.jp/bosai/common/const/area.json
https://www.jma.go.jp/bosai/forecast/data/forecast/130000.json

気象庁ホームページについて 利用規約
https://www.jma.go.jp/jma/kishou/info/coment.html

0
0
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
0