-
Notifications
You must be signed in to change notification settings - Fork 39
/
wit.go
82 lines (69 loc) · 2.34 KB
/
wit.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
package main
import (
"fmt"
"os"
"golang.org/x/net/context"
slackbot "github.com/BeepBoopHQ/go-slackbot"
"github.com/chris-skud/go-wit"
"github.com/nlopes/slack"
)
func main() {
bot := slackbot.New(os.Getenv("SLACK_TOKEN"))
toMe := bot.Messages(slackbot.DirectMessage, slackbot.DirectMention).Preprocess(WitPreprocess).Subrouter()
toMe.AddMatcher(&IntentMatcher{intent: "hello"}).MessageHandler(HelloHandler)
toMe.AddMatcher(&IntentMatcher{intent: "how_are_you"}).MessageHandler(HowAreYouHandler)
toMe.MessageHandler(ConfusedHandler)
bot.Run()
}
func HelloHandler(ctx context.Context, bot *slackbot.Bot, msg *slack.MessageEvent) {
bot.Reply(msg, "Oh hello!", slackbot.WithTyping)
}
func HowAreYouHandler(ctx context.Context, bot *slackbot.Bot, msg *slack.MessageEvent) {
bot.Reply(msg, "A bit tired. You get it? A bit?", slackbot.WithTyping)
}
func ConfusedHandler(ctx context.Context, bot *slackbot.Bot, msg *slack.MessageEvent) {
bot.Reply(msg, "I don't understand 😰", slackbot.WithTyping)
}
func WitPreprocess(ctx context.Context) context.Context {
msg := slackbot.MessageFromContext(ctx)
text := slackbot.StripDirectMention(msg.Text)
req := &wit.MessageRequest{Query: text}
witMessage, err := wit.NewClient(os.Getenv("WIT_TOKEN")).Message(req)
if err != nil {
bot := slackbot.BotFromContext(ctx)
bot.Reply(msg, "Uh oh, I seem to be out of sorts :dizzy_face", slackbot.WithTyping)
return ctx
}
fmt.Printf("WIT: %#v\n", witMessage)
ctx = AddWitToContext(ctx, witMessage)
return ctx
}
type IntentMatcher struct {
slackbot.RegexpMatcher
intent string
confidence float32
}
func (it *IntentMatcher) Match(ctx context.Context) (bool, context.Context) {
// default confidence to 50%
if it.confidence == 0 {
it.confidence = 0.5
}
witMessage := WitFromContext(ctx)
if witMessage != nil && len(witMessage.Outcomes) > 0 {
outcome := witMessage.Outcomes[0]
if outcome.Intent == it.intent && outcome.Confidence >= it.confidence {
return true, ctx
}
}
return false, ctx
}
func WitFromContext(ctx context.Context) *wit.Message {
if result, ok := ctx.Value("__WIT__").(*wit.Message); ok {
return result
}
return nil
}
// AddLoggerToContext sets the logger and returns the newly derived context
func AddWitToContext(ctx context.Context, witMessage *wit.Message) context.Context {
return context.WithValue(ctx, "__WIT__", witMessage)
}