インストール
$ dep ensure -add github.com/nlopes/slack
構成
/infrastructure
├ Config.go
└ Slack.go
main.go
Config.go
package infrastructure
type Config struct {
Slack struct {
APIToken string
}
}
func NewConfig() *Config {
c := new(Config)
c.Slack.APIToken = "SLACK_API_TOKEN"
return c
}
infrastructure/Slack.go
package infrastructure
import (
"github.com/nlopes/slack"
)
type Slack struct {
Channels struct {
Test string
}
Connection *slack.Client
}
func NewSlack() *Slack {
c := NewConfig()
return newSlack(c)
}
func newSlack(c *Config) *Slack {
s := &Slack{
Connection: slack.New(c.Slack.APIToken),
}
s.Channels.Test = "bot_test"
return s
}
func (s *Slack) SendMessage(message string) (channel string, timestamp string, text string, err error) {
// func (api *Client) SendMessage(channel string, options ...MsgOption) (string, string, string, error)
// func MsgOptionUsername(username string) MsgOption
// func MsgOptionIconURL(iconEmoji string) MsgOption
// func MsgOptionText(text string, escape bool) MsgOption
return s.Connection.SendMessage(
s.Channels.Test,
slack.MsgOptionUsername("Mr. Bot man"),
slack.MsgOptionIconURL("https://github.githubassets.com/images/modules/site/integrators/slackhq.png"),
slack.MsgOptionText(message, true))
}
main.go
package main
import (
"fmt"
"psychedelicnekopunch/infrastructure"
)
func main() {
slack := infrastructure.NewSlack()
channel, timestamp, text, err := slack.SendMessage("test")
if err != nil {
fmt.Print(err.Error())
return
}
fmt.Print(channel + "\n")
fmt.Print(timestamp + "\n")
fmt.Print(text + "\n")
}
実行
$ go run main.go