首页 > 解决方案 > TypeError:无法读取null的属性'awaitMessages'当它与其他相同时

问题描述

代码:

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

我真的不知道这有什么问题,因为在我添加那一点之前我完全没问题。不知道为什么。有人有什么想法吗?

标签: javascriptnode.jsdiscorddiscord.js

解决方案


您定义personmessage.author.send函数。然后你调用了send()函数 on person。这就像写:

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

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

你应该怎么做:

// 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(...);

回过头来,你得到错误的原因是,如上所述,正确的函数实际上并没有触发。这意味着 DM 从未发送过,dmChannel从未打开过,因此等于null

此外,由于person被定义为函数,因此它首先没有dmChannel属性。


如果您仍然收到相同的错误,这可能意味着在您请求dmChannel. 有两种方法可以对抗这种情况。

首先,您可以使用async/await消息await的发送,也可以使用承诺Channel.send()返回。

// 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 })
});

推荐阅读