discord 机器人 - 我在这段代码中做错了什么?

discord bots - what am I doing wrong in this code?

我正在按照 discordjs.guides 上的指南进行操作,并且在命令处理指南的末尾。我已按照提供的步骤进行操作,我的代码看起来与他们提供的代码完全一样,只是更改了一些文件名,但我收到此错误:

"Error: Cannot find module './commands/${file}'"

我很难弄清楚到底是什么导致了这个错误。我查看了有关类似问题的其他问题,但我发现的解决方案似乎对我不起作用 - 例如,一种解决方案是在表达式的开头添加一个额外的句点,但这并没有为我工作。

// Require the necessary discord.js classes
const fs = require('node:fs');
const { Client, Collection, Intents } = require('discord.js');
const { token } = require('./auth.json');

// Create a new client instance
const client = new Client({ intents: [Intents.FLAGS.GUILDS] });

client.commands = new Collection();
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));

for (const file of commandFiles) {
    const command = require('./commands/${file}');
    //Set a new item in the Collection
    //With the key as the command name and the value as the exported module
    client.commands.set(command.data.name, command);
}

// When the client is ready, run this code (only once)
client.once('ready', () => {
    console.log('Ready!');
});

client.on('interactionCreate', async interaction => {
    if (!interaction.isCommand()) return;

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

    if (!command) return;

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


// Login to Discord with your client's token
client.login(token);

你的错误是使用

require('./commands/${file}');

你应该实际使用

require(`./commands/${file}`);

请注意第二个示例中的 ${file} 变量是黑色的,而在第一个示例中它仍然是绿色的。这是因为基本引号不允许转义变量,因此,当您尝试使用基本引号要求该模块时,您的代码会查找名为 ${file}.

的模块