|
| 1 | +{ "category": "interaction-handlers" } |
| 2 | +--- |
| 3 | +const { InteractionHandler, InteractionHandlerTypes } = require('@sapphire/framework'); |
| 4 | +const { InteractionHandler, InteractionHandlerTypes } = require('@sapphire/framework'); |
| 5 | + |
| 6 | +class AutocompleteHandler extends InteractionHandler { |
| 7 | + /** |
| 8 | + * @param {InteractionHandler.Context} context |
| 9 | + * @param {InteractionHandler.Options} options |
| 10 | + */ |
| 11 | + constructor(context, options) { |
| 12 | + super(context, { |
| 13 | + ...options, |
| 14 | + interactionHandlerType: InteractionHandlerTypes.Autocomplete |
| 15 | + }); |
| 16 | + } |
| 17 | + |
| 18 | + /** |
| 19 | + * @param {import('discord.js').AutocompleteInteraction} interaction |
| 20 | + * @param {import('discord.js').ApplicationCommandOptionChoiceData[]} result |
| 21 | + */ |
| 22 | + async run(interaction, result) { |
| 23 | + return interaction.respond(result); |
| 24 | + } |
| 25 | + |
| 26 | + /** |
| 27 | + * @param {import('discord.js').AutocompleteInteraction} interaction |
| 28 | + */ |
| 29 | + async parse(interaction) { |
| 30 | + // Only run this interaction for the command with ID '1000000000000000000' |
| 31 | + if (interaction.commandId !== '1000000000000000000') return this.none(); |
| 32 | + // Get the focussed (current) option |
| 33 | + const focusedOption = interaction.options.getFocused(true); |
| 34 | + // Ensure that the option name is one that can be autocompleted, or return none if not. |
| 35 | + switch (focusedOption.name) { |
| 36 | + case 'search': { |
| 37 | + // Search your API or similar. This is example code! |
| 38 | + const searchResult = await myApi.searchForSomething(focusedOption.value); |
| 39 | + // Map the search results to the structure required for Autocomplete |
| 40 | + return this.some(searchResult.map((match) => ({ name: match.name, value: match.key }))); |
| 41 | + } |
| 42 | + default: |
| 43 | + return this.none(); |
| 44 | + } |
| 45 | + } |
| 46 | +} |
| 47 | + |
| 48 | +module.exports = { |
| 49 | + AutocompleteHandler |
| 50 | +}; |
0 commit comments