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:

JavaScript

And the error is

JavaScript

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)

JavaScript

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.

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement