/
slackbot.go
100 lines (83 loc) · 2.34 KB
/
slackbot.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
package slackbot
import (
"errors"
"fmt"
"log"
"github.com/nlopes/slack"
"github.com/kyokomi/slackbot/plugins"
"github.com/kyokomi/slackbot/plugins/sysstd"
)
type BotContext struct {
Plugins plugins.PluginManager
Client *slack.Client
RTM *slack.RTM
}
func NewBotContext(token string) (*BotContext, error) {
ctx, err := NewBotContextNotSysstd(token)
if err != nil {
return nil, err
}
ctx.AddPlugin("sysstd", sysstd.NewPlugin(ctx.Plugins))
return ctx, nil
}
func NewBotContextNotSysstd(token string) (*BotContext, error) {
if token == "" {
return nil, errors.New("ERROR: slack token not found")
}
ctx := &BotContext{}
ctx.Client = slack.New(token)
ctx.Client.SetDebug(true) // TODO: あとで
ctx.Plugins = plugins.NewPluginManager(ctx)
return ctx, nil
}
func (ctx *BotContext) AddPlugin(key interface{}, val plugins.BotMessagePlugin) {
fmt.Println("insert plugin ", key)
ctx.Plugins.AddPlugin(key, val)
}
func (ctx *BotContext) WebSocketRTM() {
if ctx.RTM != nil {
ctx.RTM.Disconnect()
}
ctx.RTM = ctx.Client.NewRTM()
go ctx.RTM.ManageConnection()
go func() {
for {
select {
case msg := <-ctx.RTM.IncomingEvents:
fmt.Print("Event Received: ")
switch ev := msg.Data.(type) {
case *slack.ConnectedEvent:
fmt.Println("Infos:", ev.Info)
fmt.Println("Connection counter:", ev.ConnectionCount)
// Replace #general with your Channel ID
ctx.SendMessage("Hello world", "#general")
case *slack.MessageEvent:
ctx.responseEvent(ev)
case *slack.PresenceChangeEvent:
fmt.Printf("Presence Change: %v\n", ev)
case slack.LatencyReport:
fmt.Printf("Current latency: %v\n", ev.Value)
case *slack.RTMError:
fmt.Printf("Error: %d - %s\n", ev.Code, ev.Msg)
default:
fmt.Printf("Unexpected: %+v\n", msg.Data)
}
}
}
}()
}
func (ctx *BotContext) responseEvent(ev *slack.MessageEvent) {
botUser := ctx.RTM.GetInfo().User
e := plugins.NewBotEvent(ctx, botUser.ID, botUser.Name, ev.User, ev.Username, ev.Text, ev.Channel)
ctx.Plugins.ExecPlugins(e)
}
func (ctx *BotContext) SendMessage(message, channel string) {
if !ctx.Plugins.IsReply() {
return
}
log.Println("WithSendChannelMessageFunc", channel, message)
if message != "" && channel != "" {
ctx.RTM.SendMessage(ctx.RTM.NewOutgoingMessage(message, channel))
}
}
var _ plugins.MessageSender = (*BotContext)(nil)