LoginSignup
40
32

More than 5 years have passed since last update.

【Slack】Custom slash commandsを使う

Last updated at Posted at 2016-09-23

最初に

Slackそんなに使ってないけど社内でSlackに移行しようって流れになったのでSlack開発始めました。
→流れでCustom slash commandsを登録しそこから作成したプログラムを叩かせることをやったのでまとめました。 

背景

社内Slackからお知らせを投稿してDBに保存、そのお知らせを自社ポータルに表示したい。

問題

Publicのchannelだと全員見れてしまうし(インターンも)それはどうなんだろう?
Outgoing webhooksだとprivate channelでつかえない。
*Outgoing webhook...特定チャネルへのpostをフックにしてURLを叩いてくれる、楽

調べる

The outgoing webhook integration is only available in public channels. If you would like to get data out of private groups and DMs in real-time, try a slash command.

by Slackさん公式

Slash Commandsというものを使えばいいらしい。

Slash Commandsとは

"/command hogehoge"で特定の動きをしてくれる。
→Custom Slash Commandsが登録できる
このSlash Commandsにひも付けて既存のサービスをフックするようにすればいい

やることアウトライン

  1. Slackからフックさせる先のプログラムを作る
  2. Custom slash commandsの登録
  3. テスト

Custom slash commandsの登録

私は今回の場合もうプログラムは作ってあったので、説明は省略します。
1. Custom slash commandsから"Add configuration"をクリック
2. "Choose commands"で自分の登録したいコマンドを登録する->次へ
例: /addinfo
3. "URL"のフォームに叩きたいURLを貼る,その他随意に登録
4. OK

叩くプログラムの作り方

基本的にresponseをjson形式でechoで返せばok

test.php
$res = array(
    "text" => "response by bot"
);
header('Content-Type: application/json');
echo json_encode($res);

slash commandsでPOSTされるデータにはトークンやチャネルidも入っているので、プログラム側でそういうの考慮してあげることができます。

token=***
team_id=T0001
team_domain=example
channel_id=C2147483705
channel_name=test
user_id=U2147483697
user_name=Steve
command=/weather
text=94070
response_url=https://hooks.slack.com/commands/1234/5678

こういう感じらしいです。(https://api.slack.com/slash-commands#how_do_commands_work)
今回はPOSTが良かったのでPOSTにしましたが、GETでリクエストさせることもできます。

テスト

スクリーンショット 2016-09-23 21.22.23.png

つまったとこ

投稿した内容がタイムラインに表示されない

response_typeをin_channelにして返す。(参考→https://api.slack.com/slash-commands#responding_to_a_command)
これを指定しないと"only visible to you"にできる。

test.php
$res = array(
    "text" => "response by bot",
    "response_type" => "in_channel"
);
header('Content-Type: application/json');
echo json_encode($res);

json_encodeしても上手くいかない

headerを登録してあげる

test.php
header('Content-Type: application/json');
echo json_encode($res);

これ忘れててなんで表示されないんだろう〜?てちょっと詰まってました。

Botのレスポンスなしにしたい

$res = array(
        "text" => "",
        "response_type" => "in_channel"
        );
    header('Content-Type: application/json');
    echo json_encode($res);

こうやると、ユーザのポストは全員に見れるようになって、botのレスポンスはされないようにできました。

参考文献

https://api.slack.com/slash-commands
http://www.programmableweb.com/news/how-to-use-slack-api-to-build-slash-commands-powered-google-app-engine-and-go/how-to/2015/09/16

40
32
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
40
32