首页 > 解决方案 > Cannot read property 'members' of undefined, while trying to execute command

问题描述

Code:

message.guild.members.cache.forEach(member => {
  if (member.id !== bot.user.id && !member.user.bot);
  member.send(message);
});

If anyone knows what is the problem, it would be helpful to know

Error:

(node:2076) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'members' of undefined

标签: botsdiscorddiscord.js

解决方案


The error is probably that it's receiving messages outside of a guild, like in a dm channel.

most people don't allow dm messages when coding bots to being with, if you want to do that just return at start

client.on("message", async message => {
  if(message.channel.type === "dm") return;
});

Otherwise wrap your code around an if statement

if(message.guild) {
  message.guild.members.cache.forEach(member => {
    if (member.id !== bot.user.id && !member.user.bot);
    member.send(message);
  });
}

Could be better ways to do this depending on your other code.


推荐阅读