NodeJS 如何将超过25个选项添加到自动完成

pgky5nke  于 5个月前  发布在  Node.js
关注(0)|答案(2)|浏览(56)

我想知道是否有可能绕过自动完成选项的25个选择限制,以允许更多的选项。
去年我看到一个post,如果大于25,它会对选项列表进行切片,我试着自己做,但在使用命令时,它根本没有显示任何选项。
代码如下:

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

module.exports = {
    data: new SlashCommandBuilder()
        .setName('test')
        .setDescription('testing')
        .addStringOption(option =>
            option.setName('option')
                .setDescription('The option to select')
                .setRequired(true)
                .setAutocomplete(true)),
    async autocomplete(interaction) {
        const focusedOption = interaction.options.getFocused(true);
        let choices;
         if (focusedOption.name === 'option') {
         choices = ['Apple','Orange','Banana','Grapes','Pomegranate','Watermelon','Passionfruit','Grapefruit','Tomato','Dragonfruit','Strawberry','Blueberry','Rasberry','Blackberry','Kiwi','Lemon','Lime','Gooseberry','Guava','Tangerine','Mango','Tomato','Starfruit','Pineapple','Jackfruit','Coconut','Chilli'];
         }
        const filtered = choices.filter(choice => choice.startsWith(focusedOption.value));
         let options;
        if (filtered.length > 25) {
            options = filtered.slice(0, 25);
        } else {
            options = filtered;
        }
        await interaction.respond(
            filtered.map(choice => ({ name: choice, value: choice })),
        );
    },
    async execute(interaction){
        interaction.reply(interaction.options.getString('option'));
    }
};

字符串

91zkwejq

91zkwejq1#

filtered.map应该是options.map,如果options是最多有25个元素的过滤数组。
无论如何,你可以简化它。slice(0, 25)总是返回一个最多25个元素的新数组。如果它有10个元素,它只是复制这10个元素的数组。如果它有30个元素,它返回前25个元素。

async autocomplete(interaction) {
  const focusedOption = interaction.options.getFocused(true);
  let choices = [];
  if (focusedOption.name === 'search')
    choices = ['Apple','Orange','Banana','Grapes','Pomegranate','Watermelon','Passionfruit','Grapefruit','Tomato','Dragonfruit','Strawberry','Blueberry','Rasberry','Blackberry','Kiwi','Lemon','Lime','Gooseberry','Guava','Tangerine','Mango','Tomato','Starfruit','Pineapple','Jackfruit','Coconut','Chilli'];

  const filtered = choices
    .filter((choice) => choice.startsWith(focusedOption.value))
    .slice(0, 25);

  await interaction.respond(
    filtered.map((choice) => ({ name: choice, value: choice })),
  );
},

字符串

5uzkadbs

5uzkadbs2#

我认为你应该把选择转换成搜索结果,否则你只会看到最初的25个值,而不是搜索的值。
所以你的代码看起来像这样:

const filtered = choices
  .filter((choice) => choice.toLowerCase().startsWith(focusedOption.value))
  .slice(0, 25);

字符串

相关问题