-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbot.go
232 lines (206 loc) · 7.29 KB
/
bot.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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
package main
import (
"capture-sre/bart/usecases"
"context"
"fmt"
"log"
"os"
"strings"
"time"
"github.com/joho/godotenv"
"github.com/slack-go/slack"
"github.com/slack-go/slack/socketmode"
)
func main() {
// Load Env variables from .dot file
godotenv.Load(".env")
token := os.Getenv("SLACK_AUTH_TOKEN")
appToken := os.Getenv("SLACK_APP_TOKEN")
// Create a new client to slack by giving token
// Set debug to true while developing
// Also add a ApplicationToken option to the client
client := slack.New(token, slack.OptionDebug(true), slack.OptionAppLevelToken(appToken))
// go-slack comes with a SocketMode package that we need to use that accepts a Slack client and outputs a Socket mode client instead
socketClient := socketmode.New(
client,
socketmode.OptionDebug(true),
// Option to set a custom logger
socketmode.OptionLog(log.New(os.Stdout, "socketmode: ", log.Lshortfile|log.LstdFlags)),
)
// Create a context that can be used to cancel goroutine
ctx, cancel := context.WithCancel(context.Background())
// Make this cancel called properly in a real program , graceful shutdown etc
defer cancel()
go func(ctx context.Context, client *slack.Client, socketClient *socketmode.Client) {
// Create a for loop that selects either the context cancellation or the events incomming
for {
select {
// inscase context cancel is called exit the goroutine
case <-ctx.Done():
log.Println("Shutting down socketmode listener")
return
case event := <-socketClient.Events:
// We have a new Events, let's type switch the event
// Add more use cases here if you want to listen to other events.
switch event.Type {
// handle EventAPI events
// case socketmode.EventTypeEventsAPI:
// // The Event sent on the channel is not the same as the EventAPI events so we need to type cast it
// eventsAPIEvent, ok := event.Data.(slackevents.EventsAPIEvent)
// if !ok {
// log.Printf("Could not type cast the event to the EventsAPIEvent: %v\n", event)
// continue
// }
// // We need to send an Acknowledge to the slack server
// socketClient.Ack(*event.Request)
// // Now we have an Events API event, but this event type can in turn be many types, so we actually need another type switch
// log.Println(eventsAPIEvent)
// err := handleEventMessage(eventsAPIEvent, client)
// if err != nil {
// // Replace with actual err handeling
// log.Fatal(err)
// }
// handle Slash commands
case socketmode.EventTypeSlashCommand:
command, ok := event.Data.(slack.SlashCommand)
if !ok {
log.Printf("Could not type case the message to a SlashCommand: %v\n", command)
continue
}
socketClient.Ack(*event.Request)
err := handleSlashCommand(command, client)
if err != nil {
log.Fatal(err)
}
}
}
}
}(ctx, client, socketClient)
socketClient.Run()
}
// handleEventMessage will take an event and handle it properly based on the type of event
// func handleEventMessage(event slackevents.EventsAPIEvent, client *slack.Client) error {
// switch event.Type {
// // First we check if this is an CallbackEvent
// case slackevents.CallbackEvent:
// innerEvent := event.InnerEvent
// // Yet Another Type switch on the actual Data to see if its an AppMentionEvent
// switch ev := innerEvent.Data.(type) {
// case *slackevents.AppMentionEvent:
// // The application has been mentioned since this Event is a Mention event
// log.Println(ev)
// err := handleAppMentionEvent(ev, client)
// if err != nil {
// return err
// }
// }
// default:
// return errors.New("unsupported event type")
// }
// return nil
// }
// handleAppMentionEvent is used to take care of the AppMentionEvent when the bot is mentioned
// func handleAppMentionEvent(event *slackevents.AppMentionEvent, client *slack.Client) error {
// // Grab the user name based on the ID of the one who mentioned the bot
// user, err := client.GetUserInfo(event.User)
// if err != nil {
// return err
// }
// // Check if the user said Hello to the bot
// text := strings.ToLower(event.Text)
// // Create the attachment and assigned based on the message
// attachment := slack.Attachment{}
// // Add Some default context like user who mentioned the bot
// attachment.Fields = []slack.AttachmentField{
// {
// Title: "Date",
// Value: time.Now().String(),
// }, {
// Title: "Initializer",
// Value: user.Name,
// },
// }
// if strings.Contains(text, "hello") {
// // Greet the user
// attachment.Text = fmt.Sprintf("Hello %s", user.Name)
// attachment.Pretext = "Greetings"
// attachment.Color = "#4af030"
// } else {
// // Send a message to the user
// attachment.Text = fmt.Sprintf("How can I help you %s?", user.Name)
// attachment.Pretext = "How can I be of service"
// attachment.Color = "#3d3d3d"
// }
// // Send the message to the channel
// // The Channel is available in the event message
// _, _, err = client.PostMessage(event.Channel, slack.MsgOptionAttachments(attachment))
// if err != nil {
// return fmt.Errorf("failed to post message: %w", err)
// }
// return nil
// }
// handleSlashCommand will take a slash command and route to the appropriate function
func handleSlashCommand(command slack.SlashCommand, client *slack.Client) error {
// We need to switch depending on the command
fmt.Printf("slash cmd received: %s\n", command.Text)
c := strings.Fields(command.Text)
switch c[0] {
case "help":
// This was a hello command, so pass it along to the proper function
return handleHelpRequest(command, client)
case "get-job":
i := usecases.GetJobInfoAsSlackFormattedString(c[1], c[2], c[3])
_, _, err := client.PostMessage(command.ChannelID, slack.MsgOptionText(i, false))
if err != nil {
return fmt.Errorf("failed to post message: %w", err)
}
}
return nil
}
// handleHelloCommand will take care of /hello submissions
func handleHelloCommand(command slack.SlashCommand, client *slack.Client) error {
// The Input is found in the text field so
// Create the attachment and assigned based on the message
attachment := slack.Attachment{}
// Add Some default context like user who mentioned the bot
attachment.Fields = []slack.AttachmentField{
{
Title: "Date",
Value: time.Now().String(),
}, {
Title: "Initializer",
Value: command.UserName,
},
}
// Greet the user
attachment.Text = fmt.Sprintf("Hello %s", command.Text)
attachment.Color = "#4af030"
// Send the message to the channel
// The Channel is available in the command.ChannelID
_, _, err := client.PostMessage(command.ChannelID, slack.MsgOptionAttachments(attachment))
if err != nil {
return fmt.Errorf("failed to post message: %w", err)
}
return nil
}
func handleHelpRequest(command slack.SlashCommand, client *slack.Client) error {
attachment := slack.Attachment{}
// Add Some default context like user who mentioned the bot
attachment.Fields = []slack.AttachmentField{
{
Title: "Date",
Value: time.Now().String(),
}, {
Title: "Initializer",
Value: command.UserName,
},
}
// Greet the user
attachment.Text = fmt.Sprintf("Help is on the way! %s", command.Text)
attachment.Color = "#4af030"
_, _, err := client.PostMessage(command.ChannelID, slack.MsgOptionAttachments(attachment))
if err != nil {
return fmt.Errorf("failed to post message: %w", err)
}
return nil
}