TheTecno
TheTecno

Reputation: 25

How do I get my Discord Bot to ignore a TypeError and resume executing my function?

As the question states, I have a bot I am using to message a specific channel in all guilds it is invited in. At first, the function worked in my controlled experiment with 3 servers I made with the required channel the bot needed to relay all my messages in. Then as my bot went public, some members did not have this channel in their server which resulted in my Bot displaying a TypeError when executing my test/relay function.

TypeError: Cannot read property 'send' of undefined

I want the bot to be able to send my relay message to the channel name I specified, and ignore all those without the channel in their server and continue to send the message to everyone else with the channel in their server. Can someone point me in the right direction with what I need to do?

Here is my command function code. I tried using a try and catch block but it does not seem to work either.

Details:

Associations = required channel to receive bot messages from me.

test = command I made to relay the messages.

if (command === "test") {
  const Detail = args.join(" ");
  try {

    bot.guilds.cache.forEach(guild => {
      guild.channels.cache.find(t => t.name == 'associations').send(Detail)
    });

  }
  catch (err) {
    console.log(err)
  }
}

Upvotes: 0

Views: 153

Answers (1)

user13429955
user13429955

Reputation:

Like syntle said you should make the channel name more inclusive, but to answer your question you would just use the && or an if statement

if (command === "test") {
    const Detail = args.join(" ");
    bot.guilds.cache.forEach(guild => {
        const channel = guild.channels.cache.find(t => t.name.toLowerCase().startsWith('associations'));
        if (channel) { channel.send(Detail); }
    });
}

No need for an expensive try block when error handling is as easy as an if statement. Also it did work, the reason it's logging though is because you specified it to log with console.log(err)

Upvotes: 1

Related Questions