bots - 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
解决方案
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.
推荐阅读
- java - Java中的HashMap如何使用equals()和hashCode()来查找对象?
- javascript - 如何在单个集合(类)或字符组中包含多个 Unicode 范围?
- python - Python 2.7 多线程 DB-Connection 随机崩溃
- sql - MS Access UPDATE 查询正在添加新行
- php - codeigniter中foreach中的未定义变量
- angular - 无法读取角度未定义的属性“名称”
- javascript - 无法理解 document.getElementsByClassName('clear')[0]; 代码 javascript
- javascript - 渲染/包含 html 文件 Google Cloud Functions
- android - 未设置 MenuItem 文本和图标
- php - 在此 PHP 文档页面的上下文中,波浪号 (~) 符号的含义是什么?