-
Notifications
You must be signed in to change notification settings - Fork 0
/
slack.go
70 lines (61 loc) · 1.71 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
package main
import (
"fmt"
"log"
"os"
"strings"
"github.com/slack-go/slack"
"github.com/slack-go/slack/slackevents"
"github.com/slack-go/slack/socketmode"
)
func handleEvents(client *socketmode.Client, lurch *LurchBot) {
for evt := range client.Events {
switch evt.Type {
case socketmode.EventTypeEventsAPI:
eventsAPIEvent, ok := evt.Data.(slackevents.EventsAPIEvent)
if !ok {
//fmt.Printf("Ignored %+v\n", evt)
continue
}
fmt.Printf("Event received: %+v\n", eventsAPIEvent)
client.Ack(*evt.Request)
switch eventsAPIEvent.Type {
case slackevents.CallbackEvent:
innerEvent := eventsAPIEvent.InnerEvent
switch ev := innerEvent.Data.(type) {
case *slackevents.AppMentionEvent:
go handleAppMentionEvent(lurch, client, ev)
}
default:
client.Debugf("unsupported Events API event received")
}
case socketmode.EventTypeHello:
//
default:
fmt.Fprintf(os.Stderr, "Unexpected event type received: %s\n", evt.Type)
}
}
}
func handleAppMentionEvent(lurch *LurchBot, client *socketmode.Client, ev *slackevents.AppMentionEvent) {
// Find all matches using the pattern
matches := IDPattern.FindAllStringSubmatch(ev.Text, -1)
message := ev.Text
// Remove userID from response
if len(matches) > 0 {
message = strings.ReplaceAll(message, matches[0][0], "")
}
message = strings.Trim(message, " ")
response, err := lurch.Chat(ev.User, message)
if err != nil {
log.Printf("failed to call chat: %v", err)
response = err.Error()
}
_, _, err = client.PostMessage(
ev.Channel,
slack.MsgOptionText(response, false),
slack.MsgOptionTS(ev.TimeStamp),
slack.MsgOptionDisableLinkUnfurl())
if err != nil {
log.Printf("failed posting message: %v", err)
}
}