-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
107 lines (98 loc) · 2.59 KB
/
main.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
100
101
102
103
104
105
106
107
package main
import (
"github.com/nlopes/slack"
"log"
"os"
"strings"
)
var api *slack.Client
func main() {
token := os.Getenv("SLACK_TOKEN")
if token == "" {
log.Println("SLACK_TOKEN not found")
os.Exit(1)
}
api = slack.New(os.Getenv("SLACK_TOKEN"))
//api.SetDebug(true)
log.Println("Slack Bot Starting")
rtm := api.NewRTM()
standupCron.Start()
go rtm.ManageConnection()
for msg := range rtm.IncomingEvents {
switch ev := msg.Data.(type) {
case *slack.MessageEvent:
info := rtm.GetInfo()
if ev.User != info.User.ID { //verifies the message is not from the bot
if verifyChannelisIM(rtm, ev.Channel) {
log.Printf("Direct message: %s", ev.Text)
go respond(rtm, ev)
}
}
case *slack.RTMError:
log.Printf("Error: %s\n", ev.Error())
case *slack.InvalidAuthEvent:
log.Printf("Invalid credentials")
os.Exit(1)
default:
// ignore other events
}
}
}
//function to handle direct messages to bot
func respond(rtm *slack.RTM, msg *slack.MessageEvent) {
var response string
trimmedCmd := strings.TrimSpace(msg.Text)
args := strings.Split(trimmedCmd, " ")
switch args[0] {
case "help":
helpResp(rtm, msg.Channel)
case "add_standup":
err := addStandup(rtm, args)
if err != nil {
response = err.Error()
} else {
response = "Standup Added"
}
case "add_user":
response = args[0] + ": Command not implemented"
case "standup_info":
response = args[0] + ": Command not implemented"
}
if response != "" {
rtm.SendMessage(rtm.NewOutgoingMessage(response, msg.Channel))
}
}
//handles the help block
func helpResp(rtm *slack.RTM, channel string) {
commands := map[string]string{
"add_standup <name> <hour or cron> <channel> <user1> <userN>": "Creates a standup that will message all given users based on cron schedule",
"add_user <name> <user>": "Adds a user to the given standup",
"list_standups": "Lists all standups with schedule and users",
}
fields := make([]slack.AttachmentField, 0)
for k, v := range commands {
fields = append(fields, slack.AttachmentField{
Title: k,
Value: v,
})
}
attachment := slack.Attachment{
Pretext: "Supported Commands:",
Color: "#B733FF",
Fields: fields,
}
params := slack.PostMessageParameters{}
params.AsUser = true
params.Attachments = []slack.Attachment{attachment}
rtm.PostMessage(channel, "", params)
}
//checks that a channel is an IM
func verifyChannelisIM(rtm *slack.RTM, id string) bool {
info := rtm.GetInfo()
for _, im := range info.IMs {
if im.ID == id {
return true
}
}
return false
}