-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathautocomplete.go
395 lines (346 loc) · 11.3 KB
/
autocomplete.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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
package main
import (
"context"
"fmt"
"sort"
"github.com/bwmarrin/discordgo"
"github.com/lithammer/fuzzysearch/fuzzy"
"go.uber.org/zap"
)
type Serialer interface {
Serialize() string
Deserialize(s string)
String() string
}
func fuzzyFilterSerials(partial string, recentSerials, savedSerials []string) (matchingSerials []string) {
serials := append(savedSerials, recentSerials...)
matches := fuzzy.RankFindNormalizedFold(partial, serials)
sort.Sort(matches)
matchingSerials = TargetsFromRanks(matches)
return
}
// ranked filter option choices using a partial string input
func fuzzyFilterOptionChoices(partial string, choices []*discordgo.ApplicationCommandOptionChoice) (matches []*discordgo.ApplicationCommandOptionChoice) {
choices = DistinctChoices(choices)
mchoices := make(map[string]*discordgo.ApplicationCommandOptionChoice)
schoices := make([]string, len(choices))
for i, choice := range choices {
mchoices[choice.Name] = choice
schoices[i] = choice.Name
}
rmatches := fuzzy.RankFindNormalizedFold(partial, schoices)
sort.Sort(rmatches)
smatches := TargetsFromRanks(rmatches)
matches = make([]*discordgo.ApplicationCommandOptionChoice, len(smatches))
for i, smatch := range smatches {
matches[i] = mchoices[smatch]
}
return
}
func RollSliceFromSerials(serials []string) RollSlice {
rolls := make([]*NamedRollInput, len(serials))
for i, serial := range serials {
var ri = new(NamedRollInput)
ri.Deserialize(serial)
rolls[i] = ri
}
return rolls
}
func SuggestRollsByString(ctx context.Context) {
s, i, _ := FromContext(ctx)
data := i.ApplicationCommandData()
u := UserFromInteraction(i)
recents, err := CachedSerials(u)
if err != nil {
logger.Error("cache error", zap.Error(err))
}
var choices []*discordgo.ApplicationCommandOptionChoice
saved := SavedNamedRolls(fmt.Sprintf(KeyUserGlobalExpressionsFmt, u.ID))
// fuzzy-filtered stored rolls
input := getOptionByName(data.Options, "expression").StringValue()
if input == "" {
choices = ChoicesFromRollSliceExpression(trunc(RollSliceFromSerials(recents), 5))
choices = append(choices, ChoicesFromRollSlice(saved)...)
} else {
// only sort by similarity if the user's entered something. by default
// the ranking should be by recency
choices = ChoicesFromRollSliceExpression(RollSliceFromSerials(recents))
choices = append(choices, ChoicesFromRollSlice(saved)...)
choices = fuzzyFilterOptionChoices(input, choices)
choices = append(
[]*discordgo.ApplicationCommandOptionChoice{{Name: input, Value: input}},
choices...,
)
}
choices = DistinctChoices(choices)
choices = trunc(choices, 25)
logger.Debug("choices", zap.String("input", input), zap.Any("options", choices))
if err := MeasureInteractionRespond(s.InteractionRespond, i, newChoicesResponse(choices)); err != nil {
logger.Error("autocomplete", zap.Error(err), zap.String("user", u.ID))
}
}
func SuggestExpressions(ctx context.Context) {
s, i, _ := FromContext(ctx)
data := i.ApplicationCommandData()
u := UserFromInteraction(i)
recents, err := CachedSerials(u)
if err != nil {
logger.Error("cache error", zap.Error(err))
}
var choices []*discordgo.ApplicationCommandOptionChoice
saved := SavedNamedRolls(fmt.Sprintf(KeyUserGlobalExpressionsFmt, u.ID))
// fuzzy-filtered stored rolls
input := getOptionByName(data.Options, "expression").StringValue()
choices = ChoicesFromRollSliceExpression(RollSliceFromSerials(recents))
choices = append(choices, ChoicesFromRollSliceExpression(saved)...)
if input != "" {
// only sort by similarity if the user's entered something. by default
// the ranking should be by recency
choices = fuzzyFilterOptionChoices(input, choices)
choices = append(
[]*discordgo.ApplicationCommandOptionChoice{{Name: input, Value: input}},
choices...,
)
}
choices = DistinctChoices(choices)
choices = trunc(choices, 25)
logger.Debug("choices", zap.String("input", input), zap.Any("options", choices))
if err := MeasureInteractionRespond(s.InteractionRespond, i, newChoicesResponse(choices)); err != nil {
logger.Error("autocomplete", zap.Error(err), zap.String("user", u.ID))
}
}
func SuggestNames(ctx context.Context) {
s, i, _ := FromContext(ctx)
data := i.ApplicationCommandData()
u := UserFromInteraction(i)
choices := []*discordgo.ApplicationCommandOptionChoice{}
var input string
switch {
case getOptionByName(data.Options, "name") != nil:
input = getOptionByName(data.Options, "name").StringValue()
case getOptionByName(data.Options, "expression") != nil:
input = getOptionByName(data.Options, "expression").StringValue()
default:
panic("unreachable code")
}
rolls := SavedNamedRolls(fmt.Sprintf(KeyUserGlobalExpressionsFmt, u.ID))
switch {
case data.Name == "expressions" && data.Options[0].Name == "unsave":
options := make([]string, len(rolls))
stringMap := make(map[string]*NamedRollInput)
for i, option := range rolls {
options[i] = option.String()
stringMap[option.String()] = option
}
if input != "" {
matches := fuzzy.RankFindNormalizedFold(input, options)
sort.Sort(matches)
options = TargetsFromRanks(matches)
}
// build the choices list from filtered opts
for _, option := range options {
entry := stringMap[option]
choices = append(choices, &discordgo.ApplicationCommandOptionChoice{
Name: entry.String(),
Value: entry.ID(),
})
}
case data.Name == "expressions" && data.Options[0].Name == "save":
// only suggest existing expression names to overwrite or current input
options := []string{}
nameMap := make(map[string]*NamedRollInput)
for _, option := range rolls {
if option.Name != "" {
options = append(options, option.Name)
nameMap[option.Name] = option
}
}
// if we have input, add the input as a choice, then rank filter the
// other options
if input != "" {
choices = append(choices, &discordgo.ApplicationCommandOptionChoice{
Name: input,
Value: input,
})
matches := fuzzy.RankFindNormalizedFold(input, options)
sort.Sort(matches)
options = TargetsFromRanks(matches)
}
for _, option := range options {
choices = append(choices, &discordgo.ApplicationCommandOptionChoice{
Name: nameMap[option].String(),
Value: nameMap[option].ID(),
})
}
default:
panic("unreachable code")
}
// truncate to max options count
choices = trunc(choices, 25)
logger.Debug("name choices", zap.Any("data", choices))
if err := MeasureInteractionRespond(s.InteractionRespond, i,
newChoicesResponse(choices)); err != nil {
logger.Error("autocomplete", zap.Error(err))
}
}
func SuggestLabel(ctx context.Context) {
s, i, _ := FromContext(ctx)
data := i.ApplicationCommandData()
user := UserFromInteraction(i)
rolls, err := CachedRolls(user)
if err != nil {
logger.Error("cache error", zap.Error(err))
}
logger.Debug("cached rolls", zap.Any("rolls", rolls))
options := DistinctRollLabels(rolls)
input := getOptionByName(data.Options, "label").StringValue()
if input != "" {
// only sort by similarity if the user's entered something. by default
// the ranking should be by recency
options = append([]string{input}, options...)
matches := fuzzy.RankFindNormalizedFold(input, options)
sort.Sort(matches)
options = TargetsFromRanks(matches)
}
choices := DistinctChoices(ChoicesFromStrings(options))
choices = trunc(choices, 25)
logger.Debug("choices", zap.Any("data", choices))
if err = MeasureInteractionRespond(s.InteractionRespond, i,
newChoicesResponse(choices)); err != nil {
logger.Error("autocomplete", zap.Error(err))
}
}
func ChoicesFromRollSliceExpression(rolls RollSlice) []*discordgo.ApplicationCommandOptionChoice {
if len(rolls) == 0 {
return make([]*discordgo.ApplicationCommandOptionChoice, 0)
}
choices := make([]*discordgo.ApplicationCommandOptionChoice, len(rolls))
for i, roll := range rolls {
choice := &discordgo.ApplicationCommandOptionChoice{
Name: roll.Expression,
Value: roll.Expression,
}
choices[i] = choice
}
return choices
}
func ExpressionChoicesFromRollSlice(rolls RollSlice) []*discordgo.ApplicationCommandOptionChoice {
if len(rolls) == 0 {
return make([]*discordgo.ApplicationCommandOptionChoice, 0)
}
choices := make([]*discordgo.ApplicationCommandOptionChoice, len(rolls))
for i, roll := range rolls {
choices[i] = &discordgo.ApplicationCommandOptionChoice{
Name: roll.Expression,
Value: roll.Expression,
}
}
return choices
}
func ChoicesFromRollSlice(rolls RollSlice) []*discordgo.ApplicationCommandOptionChoice {
if len(rolls) == 0 {
return make([]*discordgo.ApplicationCommandOptionChoice, 0)
}
choices := make([]*discordgo.ApplicationCommandOptionChoice, len(rolls))
for i, roll := range rolls {
choice := new(discordgo.ApplicationCommandOptionChoice)
choice.Name = roll.String()
choice.Value = roll.RollableString()
choices[i] = choice
}
return choices
}
func ChoicesFromRollSliceNames(rolls RollSlice) []*discordgo.ApplicationCommandOptionChoice {
if len(rolls) == 0 {
return make([]*discordgo.ApplicationCommandOptionChoice, 0)
}
choices := make([]*discordgo.ApplicationCommandOptionChoice, len(rolls))
for i, roll := range rolls {
choice := &discordgo.ApplicationCommandOptionChoice{
Name: roll.String(),
Value: roll.RollableString(),
}
choices[i] = choice
}
return choices
}
func ChoicesFromStrings(slice []string) []*discordgo.ApplicationCommandOptionChoice {
if len(slice) == 0 {
return make([]*discordgo.ApplicationCommandOptionChoice, 0)
}
choices := make([]*discordgo.ApplicationCommandOptionChoice, len(slice))
for i, value := range slice {
choice := &discordgo.ApplicationCommandOptionChoice{
Value: value,
Name: value,
}
choices[i] = choice
}
return choices
}
// DistinctChoices deduplicates a set of option choices by the choices' Names.
func DistinctChoices(choices []*discordgo.ApplicationCommandOptionChoice) (list []*discordgo.ApplicationCommandOptionChoice) {
if len(choices) == 0 {
return make([]*discordgo.ApplicationCommandOptionChoice, 0)
}
uniques := make(map[string]bool)
for _, choice := range choices {
if _, found := uniques[choice.Name]; !found {
uniques[choice.Name] = true
list = append(list, choice)
}
}
return list
}
func DistinctRollExpressions(rolls []NamedRollInput) (expressions []string) {
if len(rolls) == 0 {
return make([]string, 0)
}
uniques := make(map[string]bool)
for _, roll := range rolls {
if roll.Expression == "" {
continue
}
if _, found := uniques[roll.Expression]; !found {
uniques[roll.Expression] = true
expressions = append(expressions, roll.Expression)
}
}
return expressions
}
func DistinctRollLabels(rolls []NamedRollInput) (labels []string) {
uniques := make(map[string]bool)
for _, roll := range rolls {
if roll.Label == "" {
continue
}
if _, found := uniques[roll.Label]; !found {
uniques[roll.Label] = true
labels = append(labels, roll.Label)
}
}
return labels
}
func DistinctExpressionNames(rolls []*NamedRollInput) (names []string) {
if len(rolls) == 0 {
return make([]string, 0)
}
uniques := make(map[string]bool)
for _, roll := range rolls {
if roll.Name == "" {
continue
}
if _, found := uniques[roll.Name]; !found {
uniques[roll.Name] = true
names = append(names, roll.Name)
}
}
return names
}
func TargetsFromRanks(ranks fuzzy.Ranks) []string {
var targets = make([]string, len(ranks))
for i, rank := range ranks {
targets[i] = rank.Target
}
return targets
}