Software engineering notes

Messaging API

Slack

  1. Create a workplace
  2. Create a channel
  3. Set up an app https://api.slack.com/apps (even you have alrady created a workplace)
    1. Click on “Your Apps” in the top right corne
    2. Click on “Create New App” and finish the flow
    3. Click on “OAuth & Permissions” on left menu
      • Section ‘Scopes’: chat:write
      • Section ‘OAuth Tokens for Your Workspace’
        • click ‘Install to Workplace’
        • You will get a token which can be used by your app
        • You will see your bot app is on the left menu of your slack app
    4. Invite bot app into the channel by tagging @botName and inviting it into the channel

Other docs

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)