Jex’s Note

Messaging API

Slack

申請

登入後到此頁產生 token

Golang example

使用 nlopes/slack 這個 package

填入 Token 並 New 它的 client

api := slack.New("xoxp-5*******************************************************************a")

Group

groups, err := api.GetGroups(false)
if err != nil {
    fmt.Printf("%s\n", err)
    return
}
for _, group := range groups {
    fmt.Printf("ID: %s, Name: %s\n", group.ID, group.Name)
}

Channel

channels, err := api.GetChannels(false)
if err != nil {
    fmt.Printf("%s\n", err)
    return
}
for _, channel := range channels {
    fmt.Printf("Name: %s, ID: %s\n", channel.Name, channel.ID)
}

Message

params := slack.PostMessageParameters{}
channelID, timestamp, err := api.PostMessage("G*******0", "Message from golang", params)
if err != nil {
    fmt.Printf("%s\n", err)
    return
}
fmt.Printf("Message successfully sent to channel %s at %s\n", channelID, timestamp)

Image

attachment := slack.Attachment{
    Title:    "Test",
    ImageURL: "https://www.google.com.tw/images/branding/googlelogo/2x/googlelogo_color_120x44dp.png",
}
params := slack.PostMessageParameters{
    Username:    "Log Reporter",
    Attachments: []slack.Attachment{attachment},
}
_, _, err = api.PostMessage("G*******0", "Message from golang", params)

Comments