前回
目的
前回作成したbotではURLを打ち込まないとbotが呼び出せない、という問題点があった。
これをslackのスラッシュコマンドで呼び出せるようにする。
slack上での準備
1.
2.
3.
ビルドを押して
4.
5.
6.
7.
Scopesの Add slach commands and ...を選んで、save Changesを選択
8.
すると画面上部に、appを再インストールするように促されるので従って
9.
画面左側のFeaturesのところにSlash Commandsが追加されるので、これを選択して
10.
任意のコマンド名と、リクエスト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