You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Discord.js的Autocomplete添加超过25个选项?

解决Discord.js自动补全选项超过25个无显示的问题

问题核心

Discord API对自动补全响应有最多25个选项的硬限制,无法绕过。你的代码里虽然做了切片处理,但最后调用interaction.respond()时错误传入了未截断的filtered数组——当结果超过25个时,Discord会直接拒绝该响应,导致选项完全不显示。

修复步骤

  1. 替换响应数组:把filtered.map()改成options.map(),使用经过切片截断后的合规数组
  2. 清理冗余数据:移除choices里重复的Tomato选项,避免过滤结果出现重复项
  3. 增强代码健壮性:给choices设置默认空数组,防止逻辑分支异常

修正后的代码

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') {
            // 移除重复的Tomato选项
            choices = ['Apple','Orange','Banana','Grapes','Pomegranate','Watermelon','Passionfruit','Grapefruit','Tomato','Dragonfruit','Strawberry','Blueberry','Rasberry','Blackberry','Kiwi','Lemon','Lime','Gooseberry','Guava','Tangerine','Mango','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(
            options.map(choice => ({ name: choice, value: choice })),
        );
    },
    async execute(interaction){
        interaction.reply(interaction.options.getString('option'));
    }
};

额外说明

  • 若要覆盖更多选项,只能通过优化过滤逻辑(比如模糊匹配而非前缀匹配)让用户输入更精准,从而在25个限制内返回最相关的结果
  • 必须始终保证响应的选项数量≤25,否则Discord会静默拒绝请求,不会给出任何提示

内容的提问来源于stack exchange,提问作者Delta Knight

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 01:57:44