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

如何在discord.js v14中为自动补全选项添加超25个选择项

Discord.js v14 自动补全超过25个选项的处理方案

问题说明

使用discord.js v14实现命令自动补全时,添加超过25个选择项后仅前25个生效,无法展示全部选项。

核心原因

Discord API对自动补全的响应结果有最多25个选项的硬性限制,直接返回超过25个结果会被平台自动截断,仅保留前25个。

解决方法

  1. 清理重复选项:先确保选择项数组无重复值,避免无效选项占用名额
  2. 过滤后截断结果:对过滤后的匹配结果进行截取,仅返回前25个,符合API限制
  3. 优化匹配逻辑(可选):将startsWith改为includes,让用户输入任意字符都能匹配相关选项,提升全量选项的可检索性

修改后的代码示例

if (interaction.options.getSubcommand() === "botanical") { 
    const focusedOption = interaction.options.getFocused(true);
    let choices;

    if (focusedOption.name === 'search') {
        // 去重处理,移除重复选项
        choices = [...new Set(['agrimony', 'allspice', 'almond', 'aloe', 'anise', 'apple', 'avocado', 'basil', 'bayLaurel', 'bergamot', 'birch', 'calendula', 'cardamom', 'chamomile', 'cinnamon', 'comfrey', 'hemp', 'lavender', 'mint', 'motherwort', 'mugwort', 'rose', 'rosemary', 'sage', 'thyme', 'valerian', 'vervain', 'yarrow'])];
    }
    // 保留原开头匹配逻辑,也可改为includes实现全字符匹配
    const filtered = choices.filter(choice => choice.startsWith(focusedOption.value.toLowerCase()));
    // 截取前25个结果,适配API限制
    const limitedResults = filtered.slice(0, 25);
    await interaction.respond(
        limitedResults.map(choice => ({ name: choice, value: choice })),
    );
}

补充说明

虽然单次响应最多返回25个选项,但通过优化匹配逻辑,用户可输入不同关键词检索到所有选项。比如输入"val"可匹配到valerian,输入"yer"可匹配到yarrow,确保全量选项都能被用户触发检索。

内容的提问来源于stack exchange,提问作者WJS.Development

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 13:27:17