【发布时间】:2021-08-29 07:23:41
【问题描述】:
(编码新手,我只是按照教程并尝试同时理解和学习) 我最近想编写自己的 Discord 机器人,但我在事件处理程序部分遇到了问题,所以我尝试了另一种方法,但现在我遇到了另一个问题。
它没有将“pong”响应为“p!ping”,而是说:
client.commands.get('ping').execute(message, args); ^
TypeError: 无法读取未定义的属性“get”
在 Object.execute (.../events/message.js:18:23)
在客户端。
我也试过替换
client.commands.get('ping').execute(message, args); 与
client.commands.cache.get('ping').execute(message, args); 甚至 client.commands.find('ping').execute(message, args); 但它说 "TypeError: Cannot read property 'get' of undefined - Discord bot" 甚至
主文件:
const Discord = require('discord.js');
const config = require('./config.json');
const {prefix, token} = require('./config.json')
const client = new Discord.Client();
client.commands = new Discord.Collection();
const eventFiles = fs.readdirSync('./events').filter(file => file.endsWith('.js'));
for (const file of eventFiles) {
const event = require(`./events/${file}`);
if (event.once) {
client.once(event.name, (...args) => event.execute(...args));
} else {
client.on(event.name, (...args) => event.execute(...args));
}
};
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.name, command);
};
client.on('message', message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).trim().split(/ +/);
const command = args.shift().toLowerCase();
if (!client.commands.has(command)) return;
try {
client.commands.get(command).execute(message, args);
} catch (error) {
console.error(error);
message.reply('there was an error trying to execute that command!');
}
});
client.login(token);
client.on("ready", () => {
client.user.setPresence({
activity: {
name: 'p!',
type: 'WATCHING'
},status: 'idle'
});
});
Message.js:
const client = new Discord.Client();
const prefix = 'p!';
module.exports = {
name: 'message',
execute(message) {
console.log(`${message.author.tag} in #${message.channel.name} sent: ${message.content}`);
if(!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase ();
if (command === 'ping'){
client.commands.get('ping').execute(message, args);
} else if (command === 'help'){
client.commands.get('trick').execute(message, args);
}
}
};
ping.js:
module.exports = {
name: 'ping',
description: 'Ping!',
execute(message, args) {
message.channel.send('pong');
},
};
我希望我提供的信息对您有所帮助。如果这是一个小错误,例如缺少;,我很抱歉浪费您的时间。提前谢谢你
【问题讨论】:
-
我相信你只是忘了在
Message.js中创建client.commands属性。 -
现在它说
TypeError: Cannot read property 'execute' of undefined
标签: javascript node.js discord discord.js