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

More than 5 years have passed since last update.

Slackに通知を飛ばすスクリプト

Posted at

要約: SlackのIncoming-Webhookを用いて通知を投稿するコマンドをシェルスクリプトで書いて、brewでインストールできるようにしました。(N番煎じ)

はじめに

~~全てのログや通知をSlackに集約したい。~~皆さんはSlackのIncomming-Webhook、活用していますか?URLに対してJSONパラメータを含んだHTTPリクエストを投げてやると、代わりに投稿してくれるすごいやつです。

しかし、OSインストールしたてのサーバにから通知を送信したいとか、一度URL設定したはずなのにどこにスクリプトを用意したか忘れてしまったということが多くて、毎回Incoming-Webhookの設定を追加しまくってしまいます。

INSTALL

Mac(OS X), HomeBrewを想定しています。

  1. Slackでアプリの追加よりIncoming-Webhookを追加し、URLを取得(方法)
  2. slack-notifyコマンドをインストール
  3. 環境変数SLACK_WEBHOOKを設定
$ brew tap ymmtr6/slack-notify && brew install slack-notify
$ echo "export SLACK_WEBHOOK=https://hooks.slack.com/services/[hogehoge]" >> ~/.bashrc

SLACK_WEBHOOKは取得したURLを設定してください。
zshの人は、~/.bashrc~/.zshrcに読み替えてください。

RUN

パイプでつなげる使い方と、引数を与える使い方の二つがあります。

$ echo "test" | slack-notify
$ slack-notify "これはテストです。"

例えば、コマンド出力をSlackに押し付けておく。

$ ls -lah | slack-notify

コマンド実行が終わったら、Slackに通知する。

$ python train.py && slack-notify "学習終了"

みたいな使い方ができます。

slack-notifyの実装

シェルでガリガリ書いています。

slack-notify
# !/bin/bash
SLACK_NOTIFY_VERSION="0.0.3"
# env check
if [ -z "$SLACK_WEBHOOK" ]; then
  echo "環境変数SLACK_WEBHOOKを設定してください"
  exit
fi
# stdin check
if [ -p /dev/stdin ]; then
  echo -n -e $(cat -)
  message="\`\`\`$(cat -)\`\`\`"
else
  # args check
  message=""
  for x in "$@"
  do
    message="${message}${x}\n"
  done
    # default
  if [ -z "${message}" ]; then
    message="$(hostname):${PWD##*/} ${USER}\$ 
    slack-notify\n"
  fi
  echo -n -e "${message}"
fi

# JSON DATA
data=`cat << EOF
{
  "text": "${message}",
  "blocks": [
    {
      "type": "section",
      "text": {
        "type": "mrkdwn",
        "text": "${message}"
      }
    }
  ]
}
EOF`

curl -H "Content-type: application/json" -s -S -X POST -d "${data}" "${SLACK_WEBHOOK}" > /dev/null

HomeBrewでインストールできるようにするには

参考文献参照。GitHubに homebrew-hogehoge という名前のレポジトリを作って、Rubyのファイルを作ってpushする。別ページでtarファイルを公開する必要があるが、GitHubのReleaseでも大丈夫。

参考文献

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