Home > database >  I have a problem while trying to use forEach
I have a problem while trying to use forEach

Time:10-04

I am trying, when someone writes a message in guild A/B/C, the bot who is in for example 3 servers, to send me the message in the 4th server, sending them in different text channels named "guild A", "guild B" and " guild C ", not in the same ones...

I get the following error:

channel.send(msgLog)

TypeError: Cannot read property 'send' of undefined

And this is my code:

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

CodePudding user response:

The error means that channel is undefined, and you cannot any property (such as 'send') of undefined.

This means that server does not have a channel with the name guild.name for some guilds.

You could use filter to only include channels that are defined:

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

This is roughly equivalent to

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