1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

pythonのlambdaでslack通知をするサンプル

Posted at

設定

  • ハンドラはファイル名.関数名で指定する
    image.png

SlackでImcomingWebHookを追加する

image.png

コード

  • ググってでてくるrequestsというモジュールは、urllibの中に吸収されたみたい
  • jsonをslackのWEBHOOK用のアドレスにPOSTで投げる
  • def lambda_handler(event, context):eventはLambda実行時に関数へ引き渡されるJSONデータ
    • 実行元のリソースによってもちろん中身は違うが、JSONデータなのでテンプレート的に扱うことができる

import json
import urllib.request

def post_slack():
    send_data = {
        "username": "notify_slack",
        "icon_emoji": ":vampire:",
        "text": "test",
    }
    send_text = "payload=" + json.dumps(send_data)
    
    method = 'POST'
    headers = {'Content-Type': 'application/json'}
    WEB_HOOK_URL = "https://hooks.slack.com/services/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"

    # オブジェクトを組み立てる
    request = urllib.request.Request(
        WEB_HOOK_URL, 
        data=send_text.encode('utf-8'), 
        method=method
    )

    # ここで実際にPOSTが実行される
    with urllib.request.urlopen(request) as response:
        response_body = response.read().decode('utf-8')

# 最初にLambdaから呼ばれる   
def lambda_handler(event, context):
    response = post_slack()
    return response

動作確認

  • lambdaからテストを実行
    • この際にテストするJSON文字列は適当で良い(コードの中で利用していないから)
      image.png
1
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?