[BASH]由bash發送訊息到slack
感謝兩個網站的貢獻
https://agoop.slack.com/apps/new/A0F7XDUAZ--incoming-webhook-
https://qiita.com/tt2004d/items/50d79d1569c0ace118d6
bash
webhooks.sh
有兩組方式
方式一
#!/bin/sh
set -eu
#Incoming WebHooksのURL
WEBHOOKURL="ここにIncoming Webhooks IntegrationのURLをいれてね"
#メッセージを保存する一時ファイル
# mac os
MESSAGEFILE=$(mktemp -t webhooks)
# linux
MESSAGEFILE=$(mktemp -t webhooksXXXX)
trap "
rm ${MESSAGEFILE}
" 0
usage_exit() {
echo "Usage: $0 [-m message] [-c channel] [-i icon] [-n botname]" 1>&2
exit 0
}
while getopts c:i:n:m: opts
do
case $opts in
c)
CHANNEL=$OPTARG
;;
i)
FACEICON=$OPTARG
;;
n)
BOTNAME=$OPTARG
;;
m)
MESSAGE=$OPTARG"\n"
;;
\?)
usage_exit
;;
esac
done
#slack 送信チャンネル
CHANNEL=${CHANNEL:-"#general"}
#slack 送信名
BOTNAME=${BOTNAME:-"mybot"}
#slack アイコン
FACEICON=${FACEICON:-":ghost:"}
#見出しとなるようなメッセージ
MESSAGE=${MESSAGE:-""}
if [ -p /dev/stdin ] ; then
#改行コードをslack用に変換
cat - | tr '\n' '\\' | sed 's/\\/\\n/g' > ${MESSAGEFILE}
else
echo "nothing stdin"
exit 1
fi
WEBMESSAGE='```'`cat ${MESSAGEFILE}`'```'
#Incoming WebHooks送信
curl -s -S -X POST --data-urlencode "payload={\"channel\": \"${CHANNEL}\", \"username\": \"${BOTNAME}\", \"icon_emoji\": \"${FACEICON}\", \"text\": \"${MESSAGE}${WEBMESSAGE}\" }" ${WEBHOOKURL} >/dev/null
方式二
$ echo test1 | ./webhooks.sh
$ cat file.txt | ./webhooks.sh
#!/bin/bash
set -eu
mode=${1}
###usage
# echo -e "error mode\c" | ./webhooks.sh 0
# echo -e "normal mode\c" | ./webhooks.sh 1
WEBHOOKURL="https://hooks.slack.com/services/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"
MESSAGEFILE=$(mktemp -t webhooksXXXX)
trap "
rm ${MESSAGEFILE}
" 0
usage_exit() {
echo "Usage: $0 [-m message] [-c channel] [-i icon] [-n botname]" 1>&2
exit 0
}
while getopts c:i:n:m: opts
do
case $opts in
c)
CHANNEL=$OPTARG
;;
i)
FACEICON=$OPTARG
;;
n)
BOTNAME=$OPTARG
;;
m)
MESSAGE=$OPTARG"\n"
;;
\?)
usage_exit
;;
esac
done
#slack 送信チャンネル
CHANNEL=${CHANNEL:-"#notice-mesh-process"}
#slack 送信名
BOTNAME=${BOTNAME:-"mybot"}
#slack アイコン
FACEICON=${FACEICON:-":ghost:"}
#見出しとなるようなメッセージ
MESSAGE=${MESSAGE:-""}
if [ -p /dev/stdin ] ; then
#改行コードをslack用に変換
cat - | tr '\n' '\\' | sed 's/\\/\\n/g' > ${MESSAGEFILE}
else
echo "nothing stdin"
exit 1
fi
echo "mode:${mode}"
if [ ${mode} == 1 ];then
WEBMESSAGE=''`cat ${MESSAGEFILE}`'' #normal mode
elif [ ${mode} == 0 ];then
WEBMESSAGE='```'`cat ${MESSAGEFILE}`'```'
#WEBMESSAGE='`'`cat ${MESSAGEFILE}`'`' #error #echo -e "error\c" | ./webhooks_normal.sh
fi
#Incoming WebHooks送信
echo payload={\"channel\": \"${CHANNEL}\", \"username\": \"${BOTNAME}\", \"icon_emoji\": \"${FACEICON}\", \"text\": \"${MESSAGE}${WEBMESSAGE}\" }
curl -s -S -X POST --data-urlencode "payload={\"channel\": \"${CHANNEL}\", \"username\": \"${BOTNAME}\", \"icon_emoji\": \"${FACEICON}\", \"text\": \"${MESSAGE}${WEBMESSAGE}\" }" ${WEBHOOKURL} >/dev/null
沒有留言:
張貼留言