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

Discord.js V14自动补全斜杠命令报错:TypeError问题求助

解决Discord.js v14自动补全斜杠命令报错问题

问题重现

使用Node.js v16.13.2及最新版Discord.js运行自动补全斜杠命令时,触发以下错误:

TypeError: Cannot read properties of undefined (reading 'forEach')
at Object.autocomplete (/home/runner/Discordjs-v14-bot/slashCommands/fun/animal.js:21:36)

同时Discord客户端显示“加载选项失败”。

错误原因

  1. 服务器ID未配置:代码中data对象仅包含两个特定服务器ID的动物列表,当命令在未配置的服务器中运行时,data[interaction.guild.id]返回undefined,调用forEach会触发报错。
  2. 私聊场景未处理:若在私聊中使用命令,interaction.guild为null,直接访问interaction.guild.id会引发后续错误。
  3. 参数错误:Discord.js v14中autocomplete回调函数仅接收interaction参数,原代码中choices参数不存在,会导致choices.push操作失败。

修复方案

  • 先判断interaction.guild是否存在,处理私聊场景。
  • 为未配置的服务器设置默认动物列表,避免undefined调用forEach。
  • 修正autocomplete函数参数,自行创建选项数组。

修复后的完整代码

const { EmbedBuilder, ApplicationCommandType } = require('discord.js');

module.exports = {
    name: 'animal',
    description: "A test command for autocomplete slash command.",
    type: ApplicationCommandType.ChatInput,
    options: [
        {
            name: 'animal',
            description: 'Choose an animal.',
            type: 3,
            required: true,
            autocomplete: true
        }
    ],
    autocomplete: (interaction) => {
        const data = {
            '908385923673231481': ['dog', 'cat', 'rabbit'],
            '967751631695405097': ['lizard', 'horse', 'hamster']
        };

        // 处理私聊场景,返回默认选项
        if (!interaction.guild) {
            return interaction.respond([
                { name: 'dog', value: 'dog' },
                { name: 'cat', value: 'cat' }
            ]).catch(console.error);
        }

        // 获取当前服务器的动物列表,不存在则使用默认值
        const animalList = data[interaction.guild.id] || ['dog', 'cat', 'bird'];
        // 转换为Discord要求的选项格式
        const choices = animalList.map(animal => ({ name: animal, value: animal }));
        
        interaction.respond(choices).catch(console.error);
    },
    run: async (client, interaction) => {
        const animal = interaction.options.get('animal').value;
        if (animal) interaction.reply({ content: `${interaction.user}, You chose **${animal}**!` });
    }
};

额外说明

  • 可根据需求修改默认动物列表,或在服务器ID未配置时返回空数组(但建议返回默认选项提升用户体验)。
  • 若不允许在私聊中使用命令,可在autocomplete和run函数中先判断interaction.guild是否存在,不存在则回复提示并终止执行。

内容的提问来源于stack exchange,提问作者Mr Unknown

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 12:07:46