不和谐.js "TypeError: Cannot read property 'execute' of undefined"命令文件中具有异步功能



我试图在命令文件下添加一个命令代码,但无法使其工作。问题出现在这一行=>if(command=="checkin"|| command=="ch"({客户端.命令.获取('chk'(.执行(消息(.

如果没有这一行,代码可以与其他2个命令配合使用。我认为这与异步函数有关,但我不确定如何解决这个问题。我也不想在主文件中包含整个代码块,因为它会变得非常长和混乱。我是编码新手,所以这可能是我还不能理解的东西——请帮帮我!

bot.js(主.js文件(

const { token, prefix } = require('./config.json');
const fs = require('fs');
const db = require('quick.db');
const ms = require('parse-ms-2')
const { Client, Intents, Message, Collection } = require("discord.js");
const client = new Client({
intents: [
Intents.FLAGS.GUILDS,
Intents.FLAGS.GUILD_MESSAGES
]
});
client.commands = new Discord.Collection();
// filter commands 
const commandFiles = fs.readdirSync('./commands/').filter(file => file.endsWith('.js'));
// fetch commands
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
client.commands.set(command.name, command);
}
client.once("ready", () => {
console.log("online.");
client.user.setPresence({ activties: [{ name: 'with commands' }] });
})

client.on('messageCreate', async message => {
// definite command components
const args = message.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase()
if (command == 'help' || command == 'h') {
client.commands.get('help').execute(message)
}
if (command == 'bal') {
client.commands.get('bal').execute(message)
}
if (command == 'checkin' || command == 'ch') {
client.commands.get('chk').execute(message)
}
})
client.login(token)

chk.js(命令所在的位置(

const db = require('quick.db')
const nm = require('parse-ms-2')
module.exports = {
name: "check in",
descrption: "daily check in rewards.",
async execute(message) {
let user = message.mentions.users.first() || message.author;
let daily = await db.fetch(`daily_${message.author.id}`);
let money = db.fetch(`money_${user.id}`);
let cooldown = 1000*60*60*20
let amount = Math.floor(Math.random() * 500) + 250
if (daily != null && cooldown - (Date.now() - daily) > 0) {
let time = ms(cooldown - (Date.now() - daily));
message.channel.send(`You have already collected the daily check in reward, please check in again in **${time.hours}h ${time.minutes}m ${time.seconds}s**`)
} else {
let embed = new Discord.MessageEmbed()
.setTitle('Daily Check In')
.setDescription(`Here is the amount collected today: ${amount}`)
.setColor('#ffc300')
message.channel.send({embeds: [embed]})
db.add(`money_${message.author.id}`, amount)
db.add(`daily_${message.author.id}`, Date.now())
}
}}

Cannot read property 'execute' of undefined"

表示client.commands.get('chk')正在返回undefined。这可能意味着找不到chk命令。

所以,让我们看看您在哪里设置命令:

// fetch commands
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
client.commands.set(command.name, command);
}

让我们检查一下正在导入的chk.js文件。

module.exports = {
name: "check in",
// ...

我看到的是,您正在导出模块并设置名称为"check in"的命令,但在脚本的后面,您会要求一个名为"chk"的命令。找不到该命令,返回undefined,并在未处理时终止代码。

这种情况下的解决方案是将name属性更改为"chk",或者改为请求client.commands.get("check in")

最新更新