首页 > 解决方案 > 我在尝试使用 forEach 时遇到问题

问题描述

我正在尝试,当有人在公会 A/B/C(例如 3 个服务器中的机器人)中写入消息时,在第 4 个服务器中向我发送消息,并在名为“公会 A”的不同文本通道中发送它们,“公会B”和“公会C”,不在同一个...

我收到以下错误:

channel.send(msgLog)

TypeError: Cannot read property 'send' of undefined

这是我的代码:

const msgLog = `[#${message.channel.name}]=[${message.author.username}#${message.author.discriminator}]=> ${message.content}` ```

client.guilds.cache.map(guild => server.channels.cache.find(channel => channel.name == guild.name)).forEach(channel => 
      channel.send(msgLog)
      );

标签: javascriptdiscord.js

解决方案


错误意味着channelundefined,并且您不能拥有 的任何属性(例如'send'undefined

这意味着server没有guild.name一些公会名称的频道。

您可以使用filter仅包含定义的通道:

client.guilds.cache
  .map(guild => server.channels.cache.find(channel => channel.name == guild.name))
  .filter(channel => channel) // returns false if channel === undefined
  .forEach(channel => channel.send(msgLog));

这大致相当于

client.guilds.cache.forEach(guild => {
  const channel = server.channels.cache.find(channel => channel.name == guild.name));
  if (channel) {
    channel.send(msgLog);
  }
});

推荐阅读