Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
412 views
in Technique[技术] by (71.8m points)

javascript - Cannot read properties of undefined when it shouldn't be undefined in discord.js command handler

I created a small command handler with a simple "ping" command. However, trying to access message.channel shows up undefined. Why is this?

./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!")
  }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

While Message.channel may be valid, message is not an instance of Message. It is actually an instance of Client. The order of the arguments always matter, and putting them in the wrong order can throw TypeErrors. There is 1 simple solution here

Make the arguments in the right order! You can either change the execution, or the declaration

client.commands.get(command).execute(client, message, args)

This is really common and happens for more than sending messages to channels


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...