From d5d8e12e2a9a99c22637597e4dd28984a31a30f9 Mon Sep 17 00:00:00 2001 From: nicholas-wu-hs Date: Thu, 2 Nov 2017 13:47:33 -0700 Subject: [PATCH] Add server/events/slack/slack_client.go --- server/events/slack/slack_client.go | 52 +++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 server/events/slack/slack_client.go diff --git a/server/events/slack/slack_client.go b/server/events/slack/slack_client.go new file mode 100644 index 00000000..6f3fbe6b --- /dev/null +++ b/server/events/slack/slack_client.go @@ -0,0 +1,52 @@ +package slack + +import ( + "errors" + + "github.com/nlopes/slack" +) + +type Client interface { + PostMessage(text string) (string, error) +} + +type ConcreteClient struct { + client *slack.Client + channel string +} + +func NewClient(slackToken string, channelName string) (*ConcreteClient, error) { + slackClient := slack.New(slackToken) + + if _, err := slackClient.AuthTest(); err != nil { + return nil, err + } + + // https://api.slack.com/faq + // 'How do I find a channel's ID if I only have its #name?' + // says need to look through all channels and match the name + channels, err := slackClient.GetChannels(true) + if err != nil { + return nil, err + } + for _, c := range channels { + if c.Name == channelName { + // channel exists, no errors + return &ConcreteClient{ + client: slackClient, + channel: channelName, + }, nil + } + } + + return nil, errors.New("channel_not_found") +} + +func (s *ConcreteClient) PostMessage(text string) (string, error) { + params := slack.NewPostMessageParameters() + params.AsUser = true + params.EscapeText = false + + _, timestamp, err := s.client.PostMessage(s.channel, text, params) + return timestamp, err +}