Autocomplete

This page guides you through the autocomplete system and setup

Warning

The handling setup below has already been added to the github repository and will be imported instantly when you clone the github repository! Code can be found here: https://github.com/cptcr/nexus/blob/main/src/Event%20Handler/Other/autocomplete.js

Handling

To handle autocomplete, we create a discord event in the Event Handler folder with the following code:

const {InteractionType} = require("discord.js");

module.exports = async (client) => {
    client.on('interactionCreate', async interaction => {
        if (interaction.type === InteractionType.ApplicationCommandAutocomplete) {
            const command = client.commands.get(interaction.commandName);
            if (command && command.autocomplete) {
                await command.autocomplete(interaction, client);
            }
        }
    });
    
}

Usage of autocomplete in commands

To use autocomplete in commands, we can now add the `autocomplete` function into our command file. Here is an example of a command using autocomplete which also fetches information from a mongodb database schema:

const { SlashCommandBuilder } = require('discord.js');
const mongoose = require('mongoose');
const { Schema } = mongoose;

// Define the Item schema
const itemSchema = new Schema({
  name: String  // Field used for autocomplete suggestions
});
const Item = mongoose.model('Item', itemSchema);

module.exports = {
    data: new SlashCommandBuilder()
        .setName('autocomplete-example')
        .setDescription('This command uses autocomplete!')
        .addStringOption(option => 
            option.setName('variable')
                .setDescription('Select one of the options shown.')
                .setAutocomplete(true)
                .setRequired(true)
        ),

    async execute(interaction, client) {
        // Handle the command execution here
        const variable = interaction.options.getString('variable');
        await interaction.reply(`You selected: ${variable}`);
    },

    async autocomplete(interaction, client) {
        const focusedValue = interaction.options.getFocused(true);

        // Fetch names from the Item schema
        try {
            const data = await Item.find({
                name: { $regex: new RegExp(focusedValue.value, 'i') } // Case insensitive matching
            }).select('name -_id').exec();

            const choices = data.map(doc => doc.name);

            // Respond with up to 25 filtered entries, which is the limit for autocomplete
            await interaction.respond(
                choices.slice(0, 25).map(choice => ({ name: choice, value: choice }))
            );
        } catch (error) {
            console.error('Error accessing the database:', error);
            // Respond with an empty array if there's an error
            await interaction.respond([]);
        }
    }
};

Last updated