環境
go 1.12.5
コード
userName
/webhookUrl
/iconUrl
は適宜調整してね。
type SlackMessage struct {
Text string `json:"text"`
Channel string `json:"channel"`
Username string `json:"username"`
IconEmoji string `json:"icon_emoji"`
IconUrl string `json:"icon_url"`
Attachments *[]*SlackMessageAttachment `json:"attachments"`
}
type SlackMessageAttachment struct {
Fallback string `json:"fallback"`
Color string `json:"color"`
Pretext string `json:"pretext"`
AuthorName string `json:"author_name"`
AuthorLink string `json:"author_link"`
AuthorIcon string `json:"author_icon"`
Title string `json:"title"`
Text string `json:"text"`
Fields *[]*SlackMessageAttachmentField `json:"fields"`
ImageUrl string `json:"image_url"`
ThumbUrl string `json:"thumb_url"`
Footer string `json:"footer"`
FooterIcon string `json:"footer_icon"`
TimeStamp int64 `json:"ts"`
}
type SlackMessageAttachmentField struct {
Title string `json:"title"`
Value string `json:"value"`
Short bool `json:"short"`
}
func NotifySlack(channel string, message string, attachments *[]*SlackMessageAttachment) {
userName := "Admin Client"
webhookUrl := "https://hooks.slack.com/services/abc/def/ghi"
iconUrl := "https://example.com/icon.png"
params, _ := json.Marshal(SlackMessage{
message,
channel,
userName,
"",
iconUrl,
attachments,
})
resp, _ := http.PostForm(
webhookUrl,
url.Values{"payload": {string(params)}},
)
ioutil.ReadAll(resp.Body)
defer resp.Body.Close()
}
つかいかた
func Test() {
attachment := &SlackMessageAttachment{
"フォールバックメッセージだよ",
"#00ff00",
"プレテキストだよ",
"著者だよ",
"https://www.google.com/",
"https://img.icons8.com/metro/420/email.png",
"タイトルだよ",
"せつめーだよ",
nil,
"https://upload.wikimedia.org/wikipedia/en/thumb/e/e0/WPVG_icon_2016.svg/1024px-WPVG_icon_2016.svg.png",
"https://developer.android.com/guide/practices/ui_guidelines/images/NB_Icon_Mask_Shapes_Ext_02.gif?hl=ja",
"フッターだよ",
"https://image.flaticon.com/icons/png/512/33/33447.png",
0,
}
fields := make([]*SlackMessageAttachmentField, 0)
fields = append(fields, &SlackMessageAttachmentField{
"あいうえお",
"かきくけこ",
true,
})
fields = append(fields, &SlackMessageAttachmentField{
"さしすせそ",
"たちつてと",
true,
})
fields = append(fields, &SlackMessageAttachmentField{
"長いテキスト",
"みなみあそみずのうまれるさとはくすいこうげん",
false,
})
fields = append(fields, &SlackMessageAttachmentField{
"長いテキスト",
"Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch",
false,
})
attachment.Fields = &fields
NotifySlack("#channel_name", "", &[]*SlackMessageAttachment{attachment})
}
結果
所感
構造体作るの面倒くさい。