Discord.js Autocomplete ‘加载选项失败’

huangapple go评论70阅读模式
英文:

Discord.js Autocomplete 'Loading Options Failed'

问题

我正在使用 discord.js v14 创建一个 Discord 机器人,遇到了自动补全功能的问题。我完全按照 discord.js 的 [文档](https://discordjs.guide/slash-commands/autocomplete.html) 中的说明操作,没有出现任何错误,但当我尝试使用命令时,它显示 '加载选项失败':

以下是我的代码:

const { SlashCommandBuilder } = require('discord.js');

module.exports = {
    data: new SlashCommandBuilder()
        .setName('test')
        .setDescription('测试')
        .addStringOption(option =>
            option.setName('option')
                .setDescription('要选择的选项')
                .setRequired(true)
                .setAutocomplete(true)),
    async autocomplete(interaction) {
        const focusedValue = interaction.options.getFocused();
        const choices = ['苹果', '橙子', '香蕉', '葡萄', '西瓜'];
        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('准备就绪!');
    
    client.user.setPresence({
  activities: [{ name: `守护一切...`, type: ActivityType.Watching }],
  status: '闲置',
});
});

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

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

    if (!command) return console.log("未找到命令");

    try {
        await command.execute(interaction);
    } catch (error) {
        console.error(error);
        await interaction.reply({ content: '执行此命令时出现错误!', ephemeral: true });
    }

});

client.login(token);
英文:

I am in the process of creating a discord bot using discord.js v14 and have encountered a problem with the autocomplete feature. I followed the discord.js documentation on the command exactly, and no error shows up, but when I try to use the command, it shows 'Loading Options Failed':

Discord.js Autocomplete ‘加载选项失败’

Here is my code:

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 })),
        );
    },
};

Here is my index.js file if it is needed:

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);

I saw a similar post that said to remove if (!interaction.isChatInputCommand()) return; and so I did, but the error still persisted.

答案1

得分: 0

以下是您要翻译的内容:

问题在于您没有在InteractionCreate处理程序中处理自动完成。您当前的代码只适用于命令。

您可以使用isAutocomplete()检查interaction是否是自动完成交互。如果是的话,您可以运行导出对象的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,
      });
    }
  }
});
英文:

The problem is that you don't handle autocomplete inside your InteractionCreate handler. Your current code only works with commands.

You can check if the interaction is an autocomplete interaction with isAutcocomplete(). If it is, you can run the autocomplete() method of your exported object.

Now that you handle autocomplete, you can add another if statement that checks if the interaction is a command. You can use isChatInputCommand() for this.

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,
      });
    }
  }
});

huangapple
  • 本文由 发表于 2023年7月3日 10:46:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/76601583.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定