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

Discord.js V14输入时自动补全无过滤效果问题求助

排查Discord.js自动补全功能失效问题

核心问题定位

从你描述的输入后仅显示[]的情况来看,大概率是过滤逻辑未匹配到任何结果,或是自动补全的基础配置存在疏漏。

具体排查步骤

  • 确认命令参数配置:注册Slash命令时,必须将目标参数的autocomplete字段设为true,否则不会触发自动补全交互。示例配置如下:

    // 命令注册时的参数配置片段
    {
      name: 'language',
      type: ApplicationCommandOptionType.String,
      description: '选择编程语言',
      autocomplete: true, // 必须开启此配置
    }
    
  • 修复大小写敏感问题:默认的startsWith方法区分大小写,若用户输入的大小写与选项名称不匹配,会导致过滤结果为空。可统一转为小写后再匹配:

    const focusedValue = interaction.options.getFocused().toLowerCase();
    const filtered = data.filter(choice => choice.name.toLowerCase().startsWith(focusedValue));
    
  • 验证聚焦值获取正确性:在过滤前打印focusedValue,确认是否正确拿到用户输入内容:

    const focusedValue = interaction.options.getFocused();
    console.log('用户输入的聚焦值:', focusedValue); // 查看控制台输出是否与输入一致
    const filtered = data.filter(choice => choice.name.startsWith(focusedValue));
    
  • 检查异步处理逻辑:确保interaction.respond在异步函数中调用并使用await,避免异步时序问题导致响应失败:

    client.on('interactionCreate', async interaction => { // 必须添加async关键字
      if (!interaction.isAutocomplete()) return;
    
      const focusedValue = interaction.options.getFocused().toLowerCase();
      const data = [
        { name: 'JavaScript', value: 'javascript' },
        { name: 'TypeScript', value: 'typescript' },
        { name: 'Python', value: 'python' },
      ];
      const filtered = data.filter(choice => choice.name.toLowerCase().startsWith(focusedValue));
      await interaction.respond(filtered.map(choice => ({ name: choice.name, value: choice.value })));
    });
    
  • 捕获异常排查问题:添加错误捕获,查看是否有异常导致响应未发送:

    client.on('interactionCreate', async interaction => {
      if (!interaction.isAutocomplete()) return;
      try {
        const focusedValue = interaction.options.getFocused().toLowerCase();
        const data = [/* 你的选项数组 */];
        const filtered = data.filter(choice => choice.name.toLowerCase().startsWith(focusedValue));
        await interaction.respond(filtered.map(choice => ({ name: choice.name, value: choice.value })));
      } catch (error) {
        console.error('自动补全出错:', error);
      }
    });
    

额外注意事项

  • 版本匹配:确保使用的Discord.js版本与官方指南版本一致,不同版本的API细节可能存在差异(如v14与v13的自动补全实现逻辑不同)。
  • 选项数量限制:自动补全最多返回25个选项,若过滤结果超过25个,需截断后再返回。

内容的提问来源于stack exchange,提问作者Skippy The Canadian Kangaroo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 06:00:11