【问题标题】:I have a problem while trying to use forEach我在尝试使用 forEach 时遇到问题
【发布时间】:2021-10-04 12:50:55
【问题描述】:

我正在尝试,当有人在公会 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)
      );

【问题讨论】:

    标签: javascript discord.js


    【解决方案1】:

    该错误表示channelundefined,你不能拥有undefined的任何属性(如'send')。

    这意味着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);
      }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-10-01
      • 2021-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多