Skip to content
sern

Autocomplete

Autocomplete is a special interaction which can happen on multiple options can be suggested for a single command. We’ve implemented this functionality using a simple tree search algorithm within a nested options tree.

Example

In this example, the option list will autocomplete with the cheeses gouda, parmesan, and harvarti.

src/commands/cheese.ts
1
export default commandModule({
2
type: CommandType.Slash,
3
description: "show me cheese",
4
options: [
5
{
6
name: "list",
7
type: ApplicationCommandOptionType.String,
8
description: "pick a cheese to show",
9
required: true,
10
autocomplete: true,
11
command: {
12
execute: (ctx) => {
13
// focus can be used to refine the options
14
const focus = ctx.options.getFocused();
15
ctx.respond(
16
["gouda", "parmesan", "harvarti"].map((cheese) => ({
17
name: cheese,
18
value: cheese,
19
})),
20
);
21
},
22
},
23
},
24
],
25
execute: (ctx, [, args]) => {
26
const cheese = args.getString("list", true);
27
ctx.reply("selected cheese " + cheese);
28
},
29
});

Using Focus

The focus object refines the options. For example, if the user types g, the focus object will be g. We can filter cheeses based on the focus object, and return only the cheeses that start with the focus object. You can do a lot more with the focus object, such as performing API calls, or implementing a fuzzy search.

src/commands/cheese.ts
1
export default commandModule({
2
type: CommandType.Slash,
3
description: "show me cheese",
4
options: [
5
{
6
name: "list",
7
type: ApplicationCommandOptionType.String,
8
description: "pick a cheese to show",
9
required: true,
10
autocomplete: true,
11
command: {
12
onEvent: [],
13
execute: (ctx) => {
14
const focus = ctx.options.getFocused();
15
ctx.respond ["gouda", "parmesan", "harvarti"]
16
.filter((cheese) => cheese.startsWith(focus))
17
.map((cheese) => ({ name: cheese, value: cheese })));
18
},
19
},
20
},
21
],
22
execute: (ctx) => {
23
const cheese = ctx.options.getString("list", true);
24
ctx.reply("selected cheese");
25
},
26
});