TypeError: bot.commands.get(…).run不是一个函数



我刚刚试图在discord.js上创建一个命令处理程序,每当我运行bot时,它都会抛出

TypeError: bot.commands.get(…).run不是一个函数

下面的代码显示了错误发生的位置。

bot.on("message", async message => {
if(message.author.bot) return;   
if(message.channel.type === 'dm') return;
if(message.content.startsWith(prefix)) {
const args = message.content.slice(prefix.length).trim().split(/ +/);
const command = args.shift().toLowerCase();
if(!bot.commands.has(command)) return;

try {
bot.commands.get(command).run(bot, message, args);
} catch (error){
console.error(error);
}
}
})
bot.login(token);

看起来您的命令处理程序有点不完整。这是我如何设置的,你可以尝试一下,告诉我它是否有效(我用评论解释了一切:

// your bot.js or main.js file
const bot = new Discord.Client(); // I setup the bot client
bot.commands = new Discord.Collection(); // I create a collection with all the commands
const commandsFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js')); 
// In my project tree, I define all the files with the .js extension in this folder as command files. I will add a file (.js) to this folder for each command I want to create. For example, there will be './commands/ping.js' inside.
for(const file of commandsFiles){
const command = require(`./commands/${file}`);
client.commands.set(command.name, command);
}
// For each command file detected, I add it's name and it's path to my client.commands collection

client.on('message', message => {
if(message.author.bot) return;   
if(message.channel.type === 'dm') return;
if(message.content.startsWith(prefix)) {
const args = message.content.slice(prefix.length).trim().split(/ +/); 
const command = args.shift().toLowerCase();
if(!bot.commands.has(command)) return;
// if the collection doesn't have a command with this name, return
try {
bot.commands.get(command).run(bot, message, args);
// I get the command object defined previously in the 'for' loop, and I execute the run function with bot, message and args as arguments
} catch (error){
console.error(error);
}
}
}

现在您已经设置了命令句柄,对于您想要创建的每个命令,在./commands/文件夹中添加一个文件(例如,./commands/ping.js,不要忘记.js部分)。在这个新创建的文件中,写入:

module.exports = {
name : 'ping',
description : 'Ping command',
run(bot, message, args) {
// the code to be executed
}

在这里你可以看到我们定义了一个对象,它将被命令处理程序使用。

当我们执行client.commands.set(command.name, command)时(在bot.js或main.js中),我们使用这里定义的名称。

当我们执行client.commands.get(command).run(bot, message, args)时,我们运行在目标命令文件的module.export对象内部定义的run函数。

如果有什么不明白的,请尽管告诉我。

最新更新