Skip to content
Advertisement

Please fix the error: “TypeError: Cannot read property ‘id’ of undefined.”

I am trying to code a discord bot for a friend’s server. It’s supposed to be a fun bot so I thought it would be funny to add a spam command. But I keep getting Errors when I do. Can someone help me out with the error? The code and the error are both given below.

It works fine when I do the command -spam @[user]. But the moment someone mistypes it and does maybe -spam [random characters], it shows me the error

CODE:

client.on("message", msg => {
  if(msg.content.startsWith(prefix+'spam ')){
    let mentions = msg.mentions.members.first().id;
    if(!mentions) return msg.reply("I'm sorry! That user does not exist.")
    for(var i=1;i<=5;i++) {
      msg.channel.send('<@'+mentions+'>')
    }
  }
})

And the error is

TypeError: Cannot read property 'id' of undefined
    at Client.<anonymous> (/home/runner/VADER-Bot/index.js:44:44)
    at Client.emit (events.js:326:22)
    at Client.EventEmitter.emit (domain.js:483:12)
    at MessageCreateAction.handle (/home/runner/VADER-Bot/node_modules/discord.js/src/client/actions/MessageCreate.js:31:14)
    at Object.module.exports [as MESSAGE_CREATE] (/home/runner/VADER-Bot/node_modules/discord.js/src/client/websocket/handlers/MESSAGE_CREATE.js:4:32)
    at WebSocketManager.handlePacket (/home/runner/VADER-Bot/node_modules/discord.js/src/client/websocket/WebSocketManager.js:384:31)
    at WebSocketShard.onPacket (/home/runner/VADER-Bot/node_modules/discord.js/src/client/websocket/WebSocketShard.js:444:22)
    at WebSocketShard.onMessage (/home/runner/VADER-Bot/node_modules/discord.js/src/client/websocket/WebSocketShard.js:301:10)
    at WebSocket.onMessage (/home/runner/VADER-Bot/node_modules/ws/lib/event-target.js:132:16)
    at WebSocket.emit (events.js:314:20)
repl process died unexpectedly: exit status 1

Advertisement

Answer

You can use optional chaining (?.). It will return undefined or null if the value before is nullish. If it isn’t, it goes to the next property (id in this case)

let mentions = msg.mentions.members.first()?.id //notice the '?.'
if(!mentions) return msg.reply("I'm sorry! That user does not exist.")

This will not throw an error if no one is mentioned, and will go to the “I’m sorry…” message.

Edit: due to your comment, it seems that you are using an old version of node.js. This is a bit longer but should do the trick.

const check = msg.mentions.members.first()
if(check) let mentions = check.id
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement