1
1

More than 1 year has passed since last update.

Bolt+CDK+PythonでSlackBotを作る

Last updated at Posted at 2021-09-27

この記事はなに?

前回こんな記事を書きました。

そして、このまえBoltのコードを読んでたらずっとシンプルに作れることがわかったので記事にしました、という話です😅

使うライブラリー

実際のコードはこんな感じ

Stack側

app.py
import os

from aws_cdk import core
from aws_cdk.aws_apigateway import LambdaIntegration, RestApi
from aws_cdk.aws_lambda import Runtime
from aws_cdk.aws_lambda_python import PythonFunction

class CdkBoltHelloWorldStack(core.Stack):
    def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)
        lambda_ = PythonFunction(
            self, f"HogeLambda", entry="lambda", handler="handler", runtime=Runtime.PYTHON_3_8,
        )
        api = RestApi(self, f"HogeApi")
        api.root.add_method("POST", LambdaIntegration(lambda_))

app = core.App()
env = core.Environment(account=os.getenv("CDK_DEFAULT_ACCOUNT"), region=os.getenv("CDK_DEFAULT_REGION"))
CdkBoltHelloWorldStack(app, APP_NAME, env=env)
app.synth()

RestAPIタイプのルート直下にPOSTで統合レスポンスのLambdaを作ります。

Lambda側

lambda/index.py
from slack_bolt import App
from slack_bolt.adapter.aws_lambda import SlackRequestHandler

app = App(
    signing_secret="** SlackのSigningSecret **", # 適宜入力  
    token="** SlackのBotUserOAuthToken **", # 適宜入力
    process_before_response=True
)

@app.message("hello")
def message_hello(message, say):
    say(f"Hey there <@{message['user']}>!")

def handler(event, context):
    return SlackRequestHandler(app).handle(event, context)

依存パッケージはBoltのみ!!

lambda/requirements.txt
slack-bolt==1.7.0

以上です!

後はデプロイして発行されたエンドポイントをSlackのEvent SubscriptionsのRequest URLに登録すれば完了です!

内容が少し違いますが、リポジトリはこの辺です!

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