slackのbotをAWS Lambda(Python)+API Gatewayで構築
slackで投稿した内容に応じて返信したり調べ物したりしてくれるbotですが、これをAWSのLambda(Python)+API Gatewayで構築しましたメモです。
目次
AWS Lambdaで実装する
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
def lambda_handler(event, context): try: user_name = event['user_name'] text = event['text'] msg = user_name + 'さん ' if text == '': msg += 'はい!' elif text.find('おはよ') >-1: msg += 'おはようございます!' elif text.find('こんにちは') > -1: msg += 'こんにちは' elif text.find('疲') > -1 or text.find('お先') > -1: msg += 'お疲れさまでした!' else: msg += 'その言葉は分かりません。' payload={'text':msg} return payload except Exception as e: print(e) raise e |
eventに辞書型でslackからusername,text,channel_nameなどがPOSTされるのでそれを受け取って、json形式で返します。
API Gatewayの設定
lambdaのAPI endpointsから設定します。
MethoはPOSTにします。
出来たAPI Gatewayの設定画面に行って、[統合リクエスト]の設定を展開します。
[マッピングテンプレートの追加]でContent-Type 「application/x-www-form-urlencoded」を追加します。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
## convert HTML POST data or HTTP GET query string to JSON ## get the raw post data from the AWS built-in variable and give it a nicer name #if ($context.httpMethod == "POST") #set($rawAPIData = $input.path('$')) #elseif ($context.httpMethod == "GET") #set($rawAPIData = $input.params().querystring) #set($rawAPIData = $rawAPIData.toString()) #set($rawAPIDataLength = $rawAPIData.length() - 1) #set($rawAPIData = $rawAPIData.substring(1, $rawAPIDataLength)) #set($rawAPIData = $rawAPIData.replace(", ", "&")) #else #set($rawAPIData = "") #end ## first we get the number of "&" in the string, this tells us if there is more than one key value pair #set($countAmpersands = $rawAPIData.length() - $rawAPIData.replace("&", "").length()) ## if there are no "&" at all then we have only one key value pair. ## we append an ampersand to the string so that we can tokenise it the same way as multiple kv pairs. ## the "empty" kv pair to the right of the ampersand will be ignored anyway. #if ($countAmpersands == 0) #set($rawPostData = $rawAPIData + "&") #end ## now we tokenise using the ampersand(s) #set($tokenisedAmpersand = $rawAPIData.split("&")) ## we set up a variable to hold the valid key value pairs #set($tokenisedEquals = []) ## now we set up a loop to find the valid key value pairs, which must contain only one "=" #foreach( $kvPair in $tokenisedAmpersand ) #set($countEquals = $kvPair.length() - $kvPair.replace("=", "").length()) #if ($countEquals == 1) #set($kvTokenised = $kvPair.split("=")) #if ($kvTokenised[0].length() > 0) ## we found a valid key value pair. add it to the list. #set($devNull = $tokenisedEquals.add($kvPair)) #end #end #end ## next we set up our loop inside the output structure "{" and "}" { #foreach( $kvPair in $tokenisedEquals ) ## finally we output the JSON for this pair and append a comma if this isn't the last pair #set($kvTokenised = $kvPair.split("=")) "$util.urlDecode($kvTokenised[0])" : #if($kvTokenised[1].length() > 0)"$util.urlDecode($kvTokenised[1])"#{else}""#end#if( $foreach.hasNext ),#end #end } |
保存します。
slackでOutgoing Webhooksを設定する
slackのログインしている状態でCustom IntegrarionsでOutgoing Webhooksを追加して設定します。
※Team Settingsで画面上部の検索窓(Search app directory)で「Outgoing Webhooks」を検索するとわりとたどりつきやすいです。
[Add Configuration]で設定します。
- Channel トリガーとするチャンネルを指定します。全チャンネルにしたいので「Any」を設定しました。
- Trigger Word(s) チャンネルを指定している時はブランクでもOKですが、「Any」にしている時は設定が必要です。今回はbotの名前をトリガーワードにしました。
- URL(s) Lambda(API Gateway)で設定したAPI endpoint URLを設定します。
- Customize Name botの名前を設定します。
- Customize Icon botのアイコンを設定します。
これで準備完了です。
例えば、Trigger Word(s)を「test-bot」とかにしていれば、「test-bot おはよう」のように投稿すれば返事が帰ってきます。
最後までお読みいただきましてありがとうございました!
【PR】 「AWS認定試験対策 AWS クラウドプラクティショナー」という本を書きました。
【PR】 「AWSではじめるLinux入門ガイド」という本を書きました。
【PR】 「ポケットスタディ AWS認定 デベロッパーアソシエイト」という本を書きました。
【PR】 「AWS認定資格試験テキスト&問題集 AWS認定ソリューションアーキテクト - プロフェッショナル」という本を書きました。

開発ベンダー5年、ユーザ企業システム部門通算9年、ITインストラクター5年目でプロトタイプビルダーもやりだしたSoftware Engineerです。
質問はコメントかSNSなどからお気軽にどうぞ。
出来る限りなるべく答えます。
このブログの内容/発言の一切は個人の見解であり、所属する組織とは関係ありません。
このブログは経験したことなどの共有を目的としており、手順や結果などを保証するものではありません。
ご参考にされる際は、読者様自身のご判断にてご対応をお願いいたします。
また、勉強会やイベントのレポートは自分が気になったことをメモしたり、聞いて思ったことを書いていますので、登壇者の意見や発表内容ではありません。
ad
ad
関連記事
-
-
Lambda関数からAWS Systems Managerパラメータストアの値を取得して更新する
Lambda関数で自分自身の環境変数を更新する だと、Lambdaのエイリアスと …
-
-
S3インベントリ設定でインベントリファイルの作成を設定
インベントリレポートファイルはオブジェクトの一覧情報です。 日次、週次で定期作成 …
-
-
特定AWSアカウント特定リージョンのSNSトピックを削除するLambda(Python)
やりたいこと 特定アカウント内特定リージョン内のSNSトピックを全部削除したいで …
-
-
CloudWatch LogsメトリクスフィルタでNginxのaccess_logから転送バイト数をモニタリングする
ユーザーガイドのApache ログからのフィールドの抽出を見てて、これ、Ngin …
-
-
AWS Summit 2016 Tokyoに参加してきました (Day3)
飛天3日目です。 JAWS-UGブースのすぐ前にあったこのお水がめちゃめちゃおい …
-
-
AWS Toolkit for EclipseからLambda関数を直接作成できずにMavenでパッケージ化して作成
AWS Toolkit for EclipseからLambda関数を直接作成 チ …
-
-
Going Serverless with AWS(AWS Summit Tokyo 2017)を聞いてきました
AWS Summit Tokyo 2017でセッション「Going Server …
-
-
S3バケットにWebフォントをアップロードしてCORSを設定する
Webフォントファイルは、モジワク研究さんのマメロンを使用させていただきました。 …
-
-
Amazon Elasticsearch ServiceにMySQLのデータを投入してkibanaで可視化してみる
MySQLのデータの可視化にAmazon Elasticsearch Servi …
-
-
AWS WAFの個別ルールを設定する
Web ACLを選択して、[Add my own rules and rule …