こんにちは、Mashです。
以前、Linux bashスクリプトでLINEアプリへメッセージを通知してみる という記事を書きました。
今回はこれ↑のPythonバージョンになります。
環境
環境はAWS Lambdaを利用します。
環境
・AWS Lambda
・Python 3.8
実装
それではさっそくコードをご紹介。こんな感じです。
# -*- coding: utf-8 -*- import os import json import urllib.parse import urllib.request # 環境変数 line_notify_api = os.environ.get('line_notify_api') line_notify_token = os.environ.get('line_notify_token') def lambda_handler(event, context): message = "\nLambdaからのメッセージだよー" return notify_to_line(message) def notify_to_line(message): method = "POST" headers = {"Authorization": "Bearer " + line_notify_token} payload = {"message": message} try: payload = urllib.parse.urlencode(payload).encode("utf-8") req = urllib.request.Request(line_notify_api, data=payload, method=method, headers=headers) urllib.request.urlopen(req) return message except Exception as e: return e
コード内で使用するパラメータのLINE NofityのAPI URLとTOKENは、Lambdaの環境変数に定義しておきます。

それではテスト実行してみます。

うまく動きましたねー。
ちなみにLINE Notifyの公式ドキュメントはこちら。
今回は以上です。
それじゃあまたね。