我用一个简单的"ping"命令。然而,试图访问message.channel
显示未定义。为什么会这样?
./index.js
//Discord, fs, prefix, client etc. declarations
client.commands = new Collection()
const files = fs.readdirSync("./commands").filter(file => file.endsWith(".js")
for (const file of files) {
const command = require(`./commands/${file}`)
client.commands.set(command.name, command)
}
client.on("messageCreate", message => {
const [command, ...args] = message.content.slice(prefix.length).split(/ +/g)
if (client.commands.has(command) {
client.commands.get(command).execute(message, client, args)
}
})
client.login(/*token*/)
./commands/ping.js
module.exports = {
name: "ping",
description: "Make me say pong",
async execute(client, message, args) {
message.channel.send("Pong!")
}
}
虽然Message.channel
可能有效,但message
不是Message
的实例。它实际上是Client
的一个实例。参数的顺序总是很重要的,把它们放在错误的顺序会引发typeerror。这里有一个简单的解决方案
让参数按正确的顺序排列!您既可以更改执行,也可以更改
声明client.commands.get(command).execute(client, message, args)
这是非常常见的,并且不止在向通道
发送消息时发生。