LoginSignup
7
7

More than 3 years have passed since last update.

ゼロからSlack POST API

Last updated at Posted at 2019-11-30

別に記事にするほどのことでもないんですが。
SlackにPOStするやつを準備するとき無駄に手間取ったので、まとめておきます。

前準備

複数人がいるワークスペースだと間違えて#generalとかに流してしまう可能性があるので、
専用のワークスペースを作るのもアリだと思います
Slack ワークスペースを作成するが参考になりそうです)

アプリ作成

https://api.slack.com/ にアクセス
Screenshot_2019-12-01 Slack API(1).png
「Start Building」ボタンをクリック

Screenshot_2019-12-01 Slack API Applications Slack.png
アプリ名とアプリを使うワークスペースを選択し、「Create App」を押す

Webhook登録

Screenshot_2019-12-01 Slack API Applications Application Log Slack.png
「Incoming Webhook」を押す

Screenshot_2019-12-01 Slack API Applications Application Log Slack(1).png
「off」を「on」に変えて、

Screenshot_2019-12-01 Slack API Applications Application Log Slack(2).png
ページ下部の「Add new Webhook to Workspace」を押す

Screenshot_2019-12-01 Test Apps が Application Log Slack ワークスペースにアクセスする権限をリクエストしています Application Log Slack.png
とりあえずアプリをワークスペースにインストールします
メッセージの投稿先は#generalにしました
専用のワークスペースではない場合は自分へのDMにしても良いと思います

Screenshot_2019-12-01 Slack API Applications Application Log Slack(3).png
これで登録は完了です!
ページ下部にあるcurlコマンドを実行すると、
Screenshot_2019-12-01 Slack general Application Log.png
こんな感じのメッセージが来ます。

<補足>
僕はWindows環境なのですが、上のcurlコマンドをそのまま実行すると、

C:\Users\user>curl -X POST -H 'Content-type: application/json' --data '{"text":"Hello, World!"}' https://hooks.slack.com/services/AAAAAAAAA/AAAAAAAAA/AAAAAAAAAAAAAAAAAAAAAAAA
curl: (6) Could not resolve host: application
invalid_payload

といった感じで、エラーになります。
これは、Windowsのコマンドプロンプトがシングルクォーテーション(')をうまく処理できないために起こるエラーです。(僕は原因に気づくのに10分かかりました)
僕はWSLで実行しましたが、Windowsで実行したい場合は、上のcurlコマンドを

curl -X POST -H "Content-type: application/json" --data "{'text':'TEXT'}" https://hooks.slack.com/services/AAAAAAAAA/AAAAAAAAA/AAAAAAAAAAAAAAAAAAAAAAAA

と変えてください。

Linuxコマンド化

いちいちcurlするのがめんどいので、/usr/local/bin/slacknotifyに以下のようにしました。

#!/bin/bash

curl -X POST -H "Content-type: application/json" --data '{"text":"Message from VPS : '"$@"'"}' "https://hooks.slack.com/services/AAAAAAAAA/AAAAAAAAA/AAAAAAAAAAAAAAAAAAAAAAAA" -kLso /dev/null

これで、slacknotify Message to Slackといった感じでSlackにメッセージが送れます。
僕は処理完了時の通知やアプリのフィードバック・エラーログなどに使っています。

Pythonで使うなら以下のようになります。

import requests

def feedback(message):
    headers = {
        'Content-type': 'application/json'
    }
    data = '{"text":"{}"}'.format(message)
    response = requests.post('https://hooks.slack.com/services/AAAAAAAAA/AAAAAAAAA/AAAAAAAAAAAAAAAAAAAAAAAA', headers=headers, data=data)
7
7
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
7
7