のほほん停留所

びぼうろく

Go beginner builds Slack Bot

From Go Installation

Target of this article

  • Go beginner
  • Would like to make a Slack Bot with Go.

My Achivement

f:id:nonchalant0303:20211027174217p:plain

Slack Bot displays information on connected iOS devices. Once connected, information of the device holds locally, so it can also display information on unconnected devices.


Preparation

Go

Go can be installed by homebrew. You should set a path to handle Go libraries.

$ brew install go
$ export PATH=${HOME}/go/bin:${PATH} or export PATH=${GOPATH}/bin:${PATH}

Go Command Line Tools (CLI) and Libraries

$ go get -u github.com/spf13/cobra
$ go get -u github.com/nlopes/slack

spf13/cobra

  • Create a template of Go Command Line Tools
  • Used by develop of Docker (distribution) and Kubernetes
  • Supports arguments and subcommand.

github.com

nlopes/slack

  • Handles Slack API with Go
  • Supports to watch message event and Interactive message

github.com

Slack Bot

You should create Slack Bot and note API Token. Bot enables to respond messages on Slack by this token.


Builds Slack Bot

Create project

Project is created by installed cobra. Firstly, prepare the cobra configuration file.

$ cat 'author: <YOUR_NAME>' > ~/.cobra.yaml
$ cat 'license: MIT' > ~/.cobra.yaml

Next, creates project.

$ cobra init <YOUR_APPLICATION_NAME>
$ cobra add run // Add subcommand

Let's run it to a trial!

$ cd ~/go/src/github.com/<YOUR_NAME>/<YOUR_APPLICATION_NAME>
$ <YOUR_APPLICATION_NAME> run
run called

If you got run called, you created project successfully!🎉

Watch messages on Slack

Edit implements of run. Let's open cmd/run.go

var runCmd = &cobra.Command{
        Use:   "hoge",
        Short: "...",
        Long: `...`,
        Run: func(cmd *cobra.Command, args []string) {
                fmt.Println("run called")
        },
}

Inside of Run function is called when calls run. You will write it here.

import (
 "github.com/nlopes/slack"
 "github.com/spf13/cobra"
)

var runCmd = &cobra.Command{
        Use:   "hoge",
        Short: "...",
        Long: `...`,
        Run: func(cmd *cobra.Command, args []string) {
                api := slack.New(<YOUR_SLACK_API_TOKEN>)
                os.Exit(run(api))
        },
}

func run(api *slack.Client) int {
    rtm := api.NewRTM()
    go rtm.ManageConnection()
    
    for {
        fmt.Println(rtm.IncomingEvents)
        
        select {
            case msg := <-rtm.IncomingEvents:
            switch ev := msg.Data.(type) {
            case *slack.MessageEvent:
                fmt.Printf("Message: %v\n", ev)
            }
        }
    }
}

You should replace <YOUR_SLACK_API_TOKEN> with the noted API Token.

Real Time Messaging API (RTM API) watchs messages on Slack. When post messages to joined channels, slack.MessageEvent is called and outputs info of the messages on console.

Change fmt.Printf("Message: %v\n", ev) and let Bot posts messages to Slack.

func run(api *slack.Client) int {
    rtm := api.NewRTM()
    go rtm.ManageConnection()
    
    for {
        fmt.Println(rtm.IncomingEvents)
        
        select {
            case msg := <-rtm.IncomingEvents:
            switch ev := msg.Data.(type) {
            case *slack.MessageEvent:
                rtm.SendMessage(rtm.NewOutgoingMessage(ev.text, ev.Channel))
            }
        }
    }
}

fmt.Message is changed to rtm.SendMessage. This change enable bot to post same messages posted to Slack.

You can easily make a Slack Bot with Go. Please, try it!

Nonchalant/kikanbo

Code of Introduced Slack Bot is open source. Please also refer to this as well.

github.com


Notes

You can make easy to manage Slack API Token by using joho/godotenv.

Reference

http://blog.kaneshin.co/entry/2016/12/03/162653