-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathslack.go
90 lines (79 loc) · 2.33 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
package main
import (
"context"
"fmt"
"log"
"strings"
"github.com/ikasamah/homecast"
"github.com/nlopes/slack"
"golang.org/x/sync/errgroup"
)
type SlackBot struct {
client *slack.Client
lang string
connectedUser *slack.UserDetails
devices []*homecast.CastDevice
}
func NewSlackBot(client *slack.Client, lang string) *SlackBot {
return &SlackBot{
client: client,
lang: lang,
}
}
func (s *SlackBot) Run(ctx context.Context) {
rtm := s.client.NewRTM()
go rtm.ManageConnection()
// Handle slack events
for msg := range rtm.IncomingEvents {
switch ev := msg.Data.(type) {
case *slack.ConnectedEvent:
s.connectedUser = ev.Info.User
s.devices = homecast.LookupAndConnect(ctx)
log.Printf("[INFO] Connected: user_id=%s", s.connectedUser.ID)
case *slack.MessageEvent:
if err := s.handleMessageEvent(ctx, ev); err != nil {
if err := s.addReaction(ev, "no_entry_sign"); err != nil {
log.Printf("[ERROR] Failed to add error reaction: %s", err)
}
log.Printf("[ERROR] Failed to handle message: %s", err)
}
case *slack.InvalidAuthEvent:
log.Print("[ERROR] Failed to auth")
return
}
}
}
func (s *SlackBot) handleMessageEvent(ctx context.Context, ev *slack.MessageEvent) error {
mention := fmt.Sprintf("<@%s> ", s.connectedUser.ID)
if !strings.HasPrefix(ev.Msg.Text, mention) {
return nil
}
body := strings.TrimPrefix(ev.Msg.Text, mention)
if err := s.speak(ctx, body); err != nil {
// Reload device, because address may have changed according to DHCP.
log.Printf("[WARN] An error occurred in speak. Attempt to reload devices just now. err: %s", err)
if err := s.addReaction(ev, "warning"); err != nil {
return err
}
s.devices = homecast.LookupAndConnect(ctx)
if err := s.speak(ctx, body); err != nil {
return err
}
}
return s.addReaction(ev, "sound")
}
func (s *SlackBot) speak(ctx context.Context, body string) error {
var eg errgroup.Group
for i := range s.devices {
device := s.devices[i]
eg.Go(func() error {
log.Printf("[INFO] Attempting to make device speak: [%s]%s", device.AddrV4, device.Name)
return device.Speak(ctx, body, s.lang)
})
}
return eg.Wait()
}
func (s *SlackBot) addReaction(ev *slack.MessageEvent, emojiName string) error {
msgRef := slack.NewRefToMessage(ev.Channel, ev.Timestamp)
return s.client.AddReaction(emojiName, msgRef)
}