I have the following code in a discord.js application.
class Bot {
// ...
activate() {
this.client.login(this.token)
this.client.on('messageCreate', this.handleMessage) // relevant
}
handleMessage(message: any) {
if (message.mentions.has(this.client.user)) // relevant
message.reply("hello")
}
}
When I run and ping the bot on discord, node raises this error
src/Bot.ts:26
if (message.mentions.has(this.client.user))
^
TypeError: Cannot read properties of undefined (reading 'user')
If I console.log(this.client.user), I see that it returns null
However, the code works if I replace the this.handleMessage callback with a lambda function containing all the executions.
activate() {
this.client.login(this.token)
this.client.on('messageCreate', (message) => {
if (message.mentions.has(this.client.user)) {
message.reply('hello')
})
}
// removed 'handleMessage()'
console logging the user shows an actual object and the bot replies.
Why does the anonymous lambda work but passing a predefined callback does not?