Skip to content
Advertisement

TypeError: Cannot read property ‘awaitMessages’ of null When it is the same as the others

Code:

if (msg.channel.type == "dm") return; // if dm channel return
let person = msg.author;
if (msg.content.toLowerCase() === "!apply") {
  person.send(ally);

  person.dmChannel
    .awaitMessages((m) => m.author.id === person.id, { max: 1, time: 300000 })
    .then((collected) => {
      if (collected.first().toLowerCase() == "yes") {
        // code...
      }
    })
    .catch(person.send(other)); // if dm
} // if !apply

I really have no idea what’s wrong with this as I was completely fine until I added that bit. Not sure why. Anyone got any ideas?

Advertisement

Answer

You defined person as the message.author.send function. And then you called the send() function on person. That’s like writing:

functions log(str) {
  return console.log(str);
};

const logger = log;
logger.log(); // logger is a function, and does not have any properties

What you should do instead:

// use this one, since you need the entire author object later on
const person = message.author; 
person.send(...);

// although this would theoretically work to (just for the send() function)
const person = message.author.send;
person(...);

Circling back, the reason you got the error is that, as mentioned above, the correct function didn’t actually trigger. That means a DM was never sent, the dmChannel was never opened and thus equals null.

Also, since person was defined as a function, it doesn’t have a dmChannel property in the first place.


If you’re still getting the same error, it might mean that the message has not finished sending before you request the dmChannel. There are two ways to combat this.

First of all, you could use async/await to await the message’s sending, or you could make use of the promise Channel.send() returns.

// await method; make sure the message event you're running this in is async
await person.send(ally); 
person.dmChannel
  .awaitMessages((m) => m.author.id === person.id, { max: 1, time: 300000 })

// Promise<message> method
person.send(ally).then((msg) => {
  msg.channel
    .awaitMessages((m) => m.author.id === person.id, { max: 1, time: 300000 })
});
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement