I'm working through the guide for discord.js but when I try and set permissions for the slash commands I keep getting the SyntaxError: await is only valid in async functions and the top level bodies of modules. not sure if I missed something or if it's something simple since I'm new to this but I couldn't find a solution for it.
here's the code from the guide that I'm trying to use
if (!client.application?.owner) await client.application?.fetch();
const command = await client.guilds.cache.get('123456789012345678')?.commands.fetch('876543210987654321');
const permissions = [
{
id: '224617799434108928',
type: 'USER',
permission: false,
},
];
await command.permissions.add({ permissions });
I realized I didn't put it in a function, I don't know how I missed that but I guess I really needed a break since I got it right after I took one.
You need to wrap await in an async-marked function, if you haven't already.
Try the code below!
// Change the name of the function to whatever name you want!
const discordFetchData = async () => {
if (!client.application?.owner) await client.application?.fetch();
const command = await client.guilds.cache.get('123456789012345678')?.commands.fetch('876543210987654321');
const permissions = [
{
id: '224617799434108928',
type: 'USER',
permission: false,
},
];
await command.permissions.add({ permissions });
};
discordFetchData();
The code above will give you a basic understanding of what to do to your code (wrap it in an async function).
You can also make the function a self-calling, anonymous, asynchronous function, like below.
(async () => {
if (!client.application?.owner) await client.application?.fetch();
const command = await client.guilds.cache.get('123456789012345678')?.commands.fetch('876543210987654321');
const permissions = [
{
id: '224617799434108928',
type: 'USER',
permission: false,
},
];
await command.permissions.add({ permissions });
})();
In the end, both of these solutions will work!
For more information, visit async function - JavaScript | MDN.
You could try this also:
(async function(){
if (!client.application?.owner) await client.application?.fetch();
//And more await calls...
})();