我正在使用discord.js v14创建一个不一致机器人,并且遇到了自动完成功能的问题.我完全按照命令中的discord.js documentation执行,没有出现错误,但当我try 使用该命令时,它显示‘加载选项失败’:

enter image description here

以下是我的代码:

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 focusedValue = interaction.options.getFocused();
        const choices = ['Apples' , 'Oranges' , 'Bananas' , 'Grapes' , 'Watermelons'];
        const filtered = choices.filter(choice => choice.startsWith(focusedValue));
        await interaction.respond(
            filtered.map(choice => ({ name: choice, value: choice })),
        );
    },
};

如果需要,下面是我的index.js文件:

const fs = require('node:fs');
const path = require('node:path');
const { Client, Collection, Events, GatewayIntentBits, ActivityType } = require('discord.js');
const { token, clientId, guildId } = require('./config.json');
let slashcmdExec = require("./deploy-slashcmds.js")
slashcmdExec.deployCommands()

const client = new Client({ intents: [GatewayIntentBits.Guilds] });

client.commands = new Collection();
const commandsPath = path.join(__dirname, 'commands');
const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js'));

for (const file of commandFiles) {
    const filePath = path.join(commandsPath, file);
    const command = require(filePath);
    client.commands.set(command.data.name, command);
}

client.once("ready", () => {
    console.log('Ready!');
    
   client.user.setPresence({
  activities: [{ name: `over Everything...`, type: ActivityType.Watching }],
  status: 'idle',
});
});

client.on(Events.InteractionCreate, async interaction => {

    const command = client.commands.get(interaction.commandName);

    if (!command) return console.log("Command was not found");

    try {
        await command.execute(interaction);
    } catch (error) {
        console.error(error);
        await interaction.reply({ content: 'There was an error while executing this command!', ephemeral: true });
    }

});

client.login(token);

我看到一个类似的帖子,说要删除if (!interaction.isChatInputCommand()) return;,我照做了,但错误仍然存在.

推荐答案

问题是您不能在InteractionCreate处理程序中处理自动完成功能.您当前的代码只能与命令一起使用.

您可以判断interaction是否是与isAutcocomplete()的自动完成交互.如果是,则可以运行导出对象的autocomplete()方法.

现在您已经处理了自动完成,您可以添加另一个if语句来判断交互是否是命令.你可以用isChatInputCommand()来做这个.

client.on(Events.InteractionCreate, async (interaction) => {
  if (interaction.isAutocomplete()) {
    const command = client.commands.get(interaction.commandName);

    if (!command) return console.log('Command was not found');

    if (!command.autocomplete)
      return console.error(
        `No autocomplete handler was found for the ${interaction.commandName} command.`,
      );

    try {
      await command.autocomplete(interaction);
    } catch (error) {
      console.error(error);
    }
  }

  if (interaction.isChatInputCommand()) {
    const command = client.commands.get(interaction.commandName);

    if (!command) return console.log('Command was not found');

    try {
      await command.execute(interaction);
    } catch (error) {
      console.error(error);
      await interaction.reply({
        content: 'There was an error while executing this command!',
        ephemeral: true,
      });
    }
  }
});

Javascript相关问答推荐

Angular:ng-contract未显示

为什么在集内和集外会产生不同的promise 状态(使用Promise.race)?

reaction useEffect KeyDown for each 条目配音输出

使用redux-toolet DelivercThunks刷新访问令牌

如何解决这个未能在响应上执行json:body stream已读问题?

每次子路由重定向都会调用父加载器函数

使用复选框在d3.js多折线图中添加或删除线条

如何从隐藏/显示中删除其中一个点击?

如何使onPaste事件与可拖动的HTML元素一起工作?

如何强制Sphinx中的自定义js/css文件始终加载更改而不缓存?

如何在Node.js中排除导出的JS文件

同一类的所有div';S的模式窗口

Reaction Redux&Quot;在派单错误中检测到状态Mutations

将数组扩展到对象中

变量在导入到Vite中的另一个js文件时成为常量.

在FAQ Accodion应用程序中使用React useState时出现问题

将多个文本框中的输出合并到一个文本框中

如何修复使用axios运行TSC index.ts时出现的错误?

Jexl to LowerCase()和Replace()

使用python,我如何判断一个html复选框是否被隐藏,以及它是否被S选中?