Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
428 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 Reply

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...