1

I want to use the await keyword in an if statement but it says:

await message.guild.channels.create("tickets", {
^^^^^
SyntaxError: await is only valid in async functions and the top level bodies of modules
if (message.content.startsWith("n!ticket setup")) {
  let channel = message.mentions.channels.first()
  let kate;
  let modrole = message.mentions.roles;

  message.guild.channels.cache.forEach(chn => {
    if (chn.type == "GUILD_CATEGORY" && !kate && chn.name.toLowerCase() == "tickets ") {
      kate = chn;
    }
  })

  if (!channel) return message.channel.send({
    content: "Du musst einen Kanal angeben wo die Nachricht reingesendet werden soll."
  });

  if (!kate) {
    await message.guild.channels.create("tickets", {
      type: "GUILD_CATEGORY",
      permissionOverwrites: [{
          id: message.guild.id,
          deny: ["VIEW_CHANNEL"]
        },
        {
          id: bot.user.id,
          allow: ["VIEW_CHANNEL"]
        }
      ]
    }).then(l => kate = l);
  }
}
Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
NoxitMC
  • 11
  • 1
  • 3
  • 1
    So you’re not in global scope or you’re not in a module. Please [edit] your post and provide a [mre]: this has nothing to do with `if` statements, so remove everything unrelated to the issue. Which scope is this in? Does `package.json` say that this should be executed as a module (i.e. `"type": "module"`)? Have you tried a `.mjs` file extension instead of a `.js` file extension? – Sebastian Simon Jan 05 '22 at 07:47

1 Answers1

1

Change your code to something like below ,wrap everything in an async function.You have to wrap your if code in some async function to make it work

async function foo(){
  let channels=message.guild.channels.cache
    for(let i=0;i<channels.length;i++){
            if(channels[i].type == "GUILD_CATEGORY" && !kate && channels[i].name.toLowerCase() == "tickets "){
                kate = channels[i];
            }
        })
        
        if(!channel) return message.channel.send({content: "Du musst einen Kanal angeben wo die Nachricht reingesendet werden soll."});
       
        if(!kate){
            await message.guild.channels.create("tickets", {
                type:"GUILD_CATEGORY",
                permissionOverwrites:[
                    {id:message.guild.id, deny:["VIEW_CHANNEL"]},
                    {id:bot.user.id,allow:["VIEW_CHANNEL"]}
                ]
            }).then(l=>kate=l);
        }```


}

Or May be you can create async version of forEach from example See this

Shubham Dixit
  • 9,242
  • 4
  • 27
  • 46