LoginSignup
3
2

More than 3 years have passed since last update.

Lambda(Python)からChatworkに通知を送る

Last updated at Posted at 2020-11-27

はじめに

特に真新しい内容ではないですが、備忘録として記載しておきます。

この記事の続編です。

・AWS MediaLiveチャンネルの停止忘れを防ぐための自動通知設定
https://qiita.com/ktsuchi/items/fe74125df4ee79c97d5d

以前作成したLambdaの通知先としてChatworkを追加しました。
SNSは使わずにLambdaから直接メッセージをチャットワークに飛ばします。

構成図

ScreenShot 2020-11-26 21.35.25.png

手順

Chatworkに通知する手軽な方法を探していたところ、
requestsモジュールのPOSTメソッドを利用する方法に行き着いたので、その方法を採用することにしました。

Lambdaの設定箇所のみ記載します。

requestsモジュールのインストール

まずは下記のドキュメントに従って、requestsモジュールをインストールします。
https://docs.aws.amazon.com/ja_jp/lambda/latest/dg/python-package.html#python-package-dependencies

Chatwork API

Chatworkにメッセージを送るには下記2つの情報が必要になります。
取得方法のリンク先を貼っておきます。

・ルームID
https://help.chatwork.com/hc/ja/articles/360000142942

・APIトークン
https://help.chatwork.com/hc/ja/articles/115000172402

Lambdaコード

今回追記した内容は、後半部分になります。

lambda_function.py
import boto3
import requests

medialive = boto3.client('medialive')
sns = boto3.client('sns')

def lambda_handler(event, context):
    channels = medialive.list_channels()
    channel_list = []

    for Channels in channels['Channels'] :
        if Channels['State'] == 'RUNNING':
            name = Channels['Name']
            id = Channels['Id']
            state = Channels['State']
            channel_list.append("| " + name + " | " + id + " | " + state + " |")

    print('\n'.join(channel_list))

    if channel_list == []:
        pass

    else:

        #to_SNS
        request = {
            'TopicArn': "<SNSトピックのARN>",
            'Message': ('\n'.join(channel_list)),
            'Subject': "Running MediaLive Channels"
            }
        sns.publish(**request)

        #to_Chatwork
        apiurl = 'https://api.chatwork.com/v2'
        roomid   = 'xxxxxxxx'
        message  =  ('\n'.join(channel_list))
        apikey   = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'

        post_message_url = '{}/rooms/{}/messages'.format(apiurl, roomid)

        headers = { 'X-ChatWorkToken': apikey }
        params = { 'body': message }
        r = requests.post(post_message_url,headers=headers,params=params)
        print(r)

実行結果

ScreenShot 2020-11-27 10.09.45.png

参考

https://tonari-it.com/python-chatwork/
https://hacknote.jp/archives/48083/

3
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
3
2