-
Notifications
You must be signed in to change notification settings - Fork 42
/
fallback.go
52 lines (40 loc) · 1.29 KB
/
fallback.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
package bot
import (
"fmt"
"math"
"strings"
"github.com/innogames/slack-bot/client"
"github.com/nlopes/slack"
"github.com/texttheater/golang-levenshtein/levenshtein"
)
const minDistance = 4
// try to find the best matching commands based on command name and examples
func (b bot) sendFallbackMessage(event slack.MessageEvent) {
bestMatching := getBestMatchingHelp(b, event.Text)
if bestMatching.Command == "" {
b.slackClient.SendMessage(event, "Oops! Command `"+event.Text+"` not found...try `help`.")
return
}
b.slackClient.SendMessage(event, "Command `"+event.Text+"` not found...do you mean *"+bestMatching.Command+"* command?")
event.Text = fmt.Sprintf("help %s", bestMatching.Command)
client.InternalMessages <- event
}
func getBestMatchingHelp(b bot, eventText string) Help {
var distance = math.MaxInt32
var bestMatching Help
eventText = strings.ToLower(eventText)
for _, commandHelp := range b.commands.GetHelp() {
for _, token := range commandHelp.GetKeywords() {
currentDistance := levenshtein.DistanceForStrings(
[]rune(strings.ToLower(token)),
[]rune(eventText),
levenshtein.DefaultOptions,
)
if currentDistance <= minDistance && currentDistance < distance {
bestMatching = commandHelp
distance = currentDistance
}
}
}
return bestMatching
}