Within an array of servers, I wish to sync a property of a user. I cannot be sure of the permission level of the bot in each server, or if the user is in each server.
Using timeout as a placeholder, the bot succeeds in timing me out when I am in a server I do not own, but fails to do so when I own the server. As this bot is in many servers, it is important that someone couldn’t add the bot to their server, give it no permissions, and crash the bot or at least remove the functionality of the command.
client.guilds.cache.forEach(a => {
userObject.timeout(60 * 1000, 'test of function').catch((err) => {console.log(`Invalid perms to change property in ` + a.name);});
});
The result if the command is done on a server where perms are correct, is a timeout on that server, and that server alone. If it is done on a server where perms are incorrect, the following error code follows:
Invalid perms to change property in Archive of SpeedRun //Server I own and tested the command on
Invalid perms to change property in TetrisRunner //Normally works
Invalid perms to change property in Nohtarealzrvr //Normally works
It seems that catching a single error causes the bot to catch an error in every attempt.
A solution I have tried already, putting a try{}catch(err){}
segment inside of the forEach loop:
client.guilds.cache.forEach(a => {
try {
userObject.timeout(60 * 1000, 'test of function')
}catch(err) {console.log(`Invalid perms to change property in ` + a.name);}
});
If done in a server where perms are not present, this crashes the bot (As .timeout is done async and crashes before the end of the statement?) The crash is as follows:
C:[email protected]:687
throw new DiscordAPIError(data, "code" in data ? data.code : data.error, status, method, url, requestData);
^
DiscordAPIError[50013]: Missing Permissions
at handleErrors (C:[email protected]:687:13)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async SequentialHandler.runRequest (C:[email protected]:1072:23)
at async SequentialHandler.queueRequest (C:[email protected]:913:14)
at async _REST.request (C:[email protected]:1218:22)
at async GuildMemberManager.edit (C:Protocol7Botnode_modulesdiscord.jssrcmanagersGuildMemberManager.js:381:15) {
requestBody: {
files: undefined,
json: {
communicationDisabledUntil: -,
communication_disabled_until: -
}
},
rawError: { message: 'Missing Permissions', code: 50013 },
code: 50013,
status: 403,
method: 'PATCH',
url: 'https://discord.com/api/v10/guilds/-/members/-'
}
2
Answers
I think you need to call your array of Promises with dedicated API : Promise.all() or Promise.allSettled().
When using a try/catch block, you must
await
a promise in order to catch any possible error.However, when doing async functions in a loop, it’s best to use a for-of loop.