1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

PythonでBoltを利用してSlack用ボットを作る🤖

Posted at

概要

PythonSlackBoltを利用して、Slack用のボットを作る。AWSlambdaにデプロイする想定。

lambdaで実行、かつ応答に時間がかかることを考慮して、Lazy listeners1を使用する。

ここではサンプルとして、MentionDMに反応して、Hello !と返信させるようにする。
スレッド内からMentionされたら、スレッド内に返信させる。

Slack API の設定

Slack APIでアプリを作って設定する。

  • 必要なキーを取得する
    • Basic InformationSigning Secret
    • OAuth & PermissionsOAuth Tokens
  • 権限を設定する
    • OAuth & PermissionsScopes
      • app_mentions:read
      • chat:write
      • im:history
  • ボットのURLを設定する
    • Event SubscriptionsRequest URL
      • あとでDeployするURL
      • https://xxxx.execute-api.ap-northeast-1.amazonaws.com/prod/appとかになるはず
  • 通知イベントを設定
    • Event SubscriptionsSubscribe to bot events
      • app_mention
      • message.im

コード

from slack_bolt import App, Ack
from slack_bolt.adapter.aws_lambda import SlackRequestHandler

app = App(
    signing_secret=os.environ["SLACK_SIGNING_SECRET"],
    token=os.environ["SLACK_OAUTH_TOKEN"],
    process_before_response=True,
)

# Mention受信時の処理
def receive_mention(_, event, say):
    if event.get('subtype') == 'bot_message':
        # 自分からのメッセージは無視(無限ループ対策)
        return

    say(text='Hello !', thread_ts=event.get("thread_ts"))


# DM受信時の処理
def receive_message(_, event, say):
    if 'channel_type' not in event or event['channel_type'] != 'im':
        # DirectMessage以外は無視
        return

    say(text='Hello !', thread_ts=event.get("thread_ts"))


def just_ack(ack: Ack):
    ack()

app.event("app_mention")(
    ack=just_ack,
    lazy=[receive_mention]
)

app.event("message")(
    ack=just_ack,
    lazy=[receive_message]
)


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

簡単…🥹

  1. https://tools.slack.dev/bolt-python/ja-jp/concepts/lazy-listeners/

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?