0

I'm coding a Discord js V12 bot, specifically the image command. Since I simply use the NPM package images-scraper, you can also look up NSFW images. So, what I am doing now, is adding a profanity filter. This is my code now:

    const blacklist = require("./../Other/profanity.js");

    blacklist.forEach((word) => {
      if (message.content.toLowerCase().includes(word.toLowerCase())) {
        message.delete();
        message.channel.send("Let's try to keep it family friendly!");
        console.log(
          `${message.author} used the word ${word} in an image search.`
        );

        return;
      } else {
        const image_results = await google.scrape(image_query, 1);
        await message.channel.send(image_results[0].url);
      };
    });

I left some unnecessary code out.

But, if I run this command, it gives me the SyntaxError: await is only valid in async function error. This await applies to the first await, before google. So, does anyone know where I can put in a async function? I already have async execute somewhere at the top, but it doesn't seem to work. I am sorry if this is a duplicate question, but since it's so specific, I just thougt I'd ask it anyway.

1 Answers1

0

You can't call an async function inside a forEach loop in that way, you could change it to a normal for ... of loop and put it inside a async function, you can only call a async function with await if you are already inside a async function.

I tried to write the code bellow

async function scrapeImages() {
  for(cont word of blacklist) {
    if (message.content.toLowerCase().includes(word.toLowerCase())) {
      message.delete();
      message.channel.send("Let's try to keep it family friendly!");
      console.log(
        `${message.author} used the word ${word} in an image search.`
      );

      return;
    } else {
      const image_results = await google.scrape(image_query, 1);
      await message.channel.send(image_results[0].url);
    };
  };
}

scrapeImages()

Or if you want to call scrapeImages asynchronously because of any reason you may have, you can put it inside another async function and call it this way:

await scrapeImages()
  • External links are nice as an addition but the answer itself has to contain all relevant information. In the current form, it is just a link to another question on SO with no additional information (which would make it a duplicate). If the duplicate really does not answer all problems the OP has, then it is fine to write an answer with a link to another question but only if it contains further explanations for the other problem(s). – t.niese Jan 25 '22 at 16:29
  • I have edited the answer with more informations, please take a look – Leonardo Dalcegio Feb 02 '22 at 12:12