-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathslack.go
99 lines (79 loc) · 2.08 KB
/
slack.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package slackbot
import (
"log"
"github.com/nlopes/slack"
)
// SlackBotBackend is a Slack bot backend
type SlackBotBackend struct { //nolint
api *slack.Client
rtm *slack.RTM
channelIDs map[string]string
}
// NewSlackBotBackend constructs a bot backend from a Slack token
func NewSlackBotBackend(token string) (BotBackend, error) {
api := slack.New(token)
// api.SetDebug(true)
channelIDs, err := LoadChannelIDs(*api)
if err != nil {
return nil, err
}
bot := &SlackBotBackend{}
bot.api = api
bot.rtm = api.NewRTM()
bot.channelIDs = channelIDs
return bot, nil
}
// SendMessage sends a message to a channel
func (b *SlackBotBackend) SendMessage(text string, channel string) {
cid := b.channelIDs[channel]
if cid == "" {
cid = channel
}
if channel == "" {
log.Printf("No channel to send message: %s", text)
return
}
if b.rtm != nil {
b.rtm.SendMessage(b.rtm.NewOutgoingMessage(text, cid))
} else {
log.Printf("Unable to send message: %s", text)
}
}
// Listen starts listening on the connection
func (b *SlackBotBackend) Listen(runner BotCommandRunner) {
go b.rtm.ManageConnection()
auth, err := b.api.AuthTest()
if err != nil {
panic(err)
}
// The Slack bot "tuxbot" should expect commands to start with "!tuxbot".
log.Printf("Connected to Slack as %q", auth.User)
commandPrefix := "!" + auth.User
Loop:
for {
msg := <-b.rtm.IncomingEvents
switch ev := msg.Data.(type) {
case *slack.HelloEvent:
case *slack.ConnectedEvent:
case *slack.MessageEvent:
args := parseInput(ev.Text)
if len(args) > 0 && args[0] == commandPrefix {
cmd := args[1:]
if err := runner.RunCommand(cmd, ev.Channel); err != nil {
log.Printf("failed to run command: %s\n", err)
}
}
case *slack.PresenceChangeEvent:
// log.Printf("Presence Change: %v\n", ev)
case *slack.LatencyReport:
// log.Printf("Current latency: %v\n", ev.Value)
case *slack.RTMError:
log.Printf("Error: %s\n", ev.Error())
case *slack.InvalidAuthEvent:
log.Printf("Invalid credentials\n")
break Loop
default:
// log.Printf("Unexpected: %v\n", msg.Data)
}
}
}