LoginSignup
0
2

More than 3 years have passed since last update.

【2019年版】インタラクティブなボタン付きslackbotをスラッシュコマンドで起動させる

Last updated at Posted at 2019-08-18

前回

目的

前回作成したbotではURLを打ち込まないとbotが呼び出せない、という問題点があった。
これをslackのスラッシュコマンドで呼び出せるようにする。

slack上での準備

1.

スクリーンショット 2019-08-18 17.21.34.png
任意のワークスペースで画像のAppを押して

2.

スクリーンショット 2019-08-18 17.21.45.png
Appディレクトリを表示を押して

3.

スクリーンショット 2019-08-18 17.21.55.png

ビルドを押して

4.

スクリーンショット 2019-08-18 17.23.12.png
Your Appsを押して

5.

スクリーンショット 2019-08-18 17.23.19.png
対象のAppを選んで

6.

スクリーンショット 2019-08-18 17.23.48.png
Interactive Componentsを押して

7.

スクリーンショット 2019-08-18 17.26.48.png
Scopesの Add slach commands and ...を選んで、save Changesを選択

8.

スクリーンショット 2019-08-18 17.27.11.png
すると画面上部に、appを再インストールするように促されるので従って

9.

スクリーンショット 2019-08-18 17.27.34.png
画面左側のFeaturesのところにSlash Commandsが追加されるので、これを選択して

10.

スクリーンショット 2019-08-18 17.29.03.png
任意のコマンド名と、リクエストURL、その説明を打ち込む。
リクエストURLは "Herokuの自分が使っているAppのURL"/"コマンド名"
(例えばhttps://Herokuのappの名前.herokuapp.com/testcommand)

これでslack上の設定は完了です。

pythonコード


# jsonifyを新たにimport
from flask import Flask, request, make_response, Response, jsonify
# 以下は前回のコードと一緒
# ---------ここから---------
import os
import json

from slack import WebClient

# Your app's Slack bot user token

# herokuでうまく変数設定出来なかったので直接打ち込んでいます。
SLACK_BOT_TOKEN = "OAuth tokenを入力"
SLACK_VERIFICATION_TOKEN ="verify tokenを入力"

# Slack client for Web API requests
slack_client = WebClient(SLACK_BOT_TOKEN)


# Flask webserver for incoming traffic from Slack
app = Flask(__name__)

# your attachment
attachments_json = [
    {
        "fallback": "Upgrade your Slack client to use messages like these.",
        "color": "#258ab5",
        "attachment_type": "default",
        "callback_id": "the_greatest_war",
        "actions": [
            {
                "name": "choco1",
                "text": "きのこ",
                "value": "kinoko",
                "type": "button"
            },
            {
                "name": "choco2",
                "text": "たけのこ",
                "value": "takenoko",
                "type": "button"
            }
        ]
    }
]

#route
#when you access such as curl command, slackbot post interactive message
@app.route("/", methods=["GET"])
def index():
    slack_client.api_call('chat.postMessage', json={
    'channel': '#general',
    'text': 'あなたはどっち派?',
    'attachments':attachments_json
    }
)

    return make_response("", 200)

#redirect from button
@app.route("/slack/json_html", methods=["POST"])
def json_html():

    # Parse the request payload
    form_json = json.loads(request.form["payload"])

    val = form_json["actions"][0]["value"]
    if val == "kinoko":
        response_text = "よろしい、ならば戦争だ"
    else:
        response_text = "よろしい、ならば盟友だ"
    response = slack_client.api_call(
        "chat.postMessage",
        json={
        "channel":"#general",
        "text":response_text,
        "attachments":[]
        }
    )

    return make_response("", 200)
# ---------ここまで---------
# 以下が今回追加するコード
# URLはslack上で設定したURLの.com以降
@app.route('/testcommand', methods=['POST'])
def bottest():
    return jsonify(
        response_type='in_channel',
        text='あなたはどっち派?',
        attachments = attachments_json
    )

response_type='in_channel'とすれば、そのまま同じチャンネルで返してくれるので嬉しい。

これを前回と同様にデプロイして、slack上で/testcommandと打てば前回と同じものが出てくるはず。
たまに

/testcommand はエラー「operation_timeout」により失敗しました

これが出てくることもあるが、これは多分herokuのapp立ち上げに時間がかかってtimeoutしてしまうだけで、もう一度実行すれば(もう立ち上がっているので)エラーは出ないはず

参考

大体全て
https://renzo.lucioni.xyz/serverless-slash-commands-with-python/
response_type, text, attachmentsについては
https://api.slack.com/slash-commands#responding_to_commands

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