Reputation: 13
I'm trying to add a specific role to a member on a guild and the docs for this version of discord.js says its with ".roles.add", but when I use ".roles" return undefined, so I cant work with undefined. Anyone knows how to set a role in this version of discord.js?
Code:
const member = guild.members.fetch(result.DISCORD);
if(member) {
let role = guild.roles.fetch('879811123283644490')
member.roles.add(role)
Error:
C:\Users\USER\Desktop\Thales bot\node_modules\mysql\lib\protocol\Parser.js:437
throw err; // Rethrow non-MySQL errors
^
TypeError: Cannot read property 'add' of undefined
at C:\Users\USER\Desktop\Thales bot\index.js:54:22
at Array.forEach (<anonymous>)
at Query.<anonymous> (C:\Users\USER\Desktop\Thales bot\index.js:46:13)
at Query.<anonymous> (C:\Users\USER\Desktop\Thales bot\node_modules\mysql\lib\Connection.js:526:10)
at Query._callback (C:\Users\USER\Desktop\Thales bot\node_modules\mysql\lib\Connection.js:488:16)
at Query.Sequence.end (C:\Users\USER\Desktop\Thales bot\node_modules\mysql\lib\protocol\sequences\Sequence.js:83:24)
at Query._handleFinalResultPacket (C:\Users\USER\Desktop\Thales bot\node_modules\mysql\lib\protocol\sequences\Query.js:149:8)
at Query.EofPacket (C:\Users\USER\Desktop\Thales bot\node_modules\mysql\lib\protocol\sequences\Query.js:133:8)
at Protocol._parsePacket (C:\Users\USER\Desktop\Thales bot\node_modules\mysql\lib\protocol\Protocol.js:291:23)
at Parser._parsePacket (C:\Users\USER\Desktop\Thales bot\node_modules\mysql\lib\protocol\Parser.js:433:10)
Upvotes: 1
Views: 2708
Reputation: 1802
Guild.members.fetch()
returns a Promise
which resolves with a Collection of GuildMember
s.
Thus, in your code, you are attempting to call Promise.roles.add()
, which is why you get the error.
To fix the error, you need to await
the promise (make sure the function is async
) or use .then()
:
Using async
/await
:
const member = await guild.members.fetch(result.DISCORD);
if(member) {
const role = await guild.roles.fetch('879811123283644490');
member.roles.add(role);
Using .then()
:
guild.members.fetch(result.DISCORD).then(member => {
return guild.roles.fetch('879811123283644490');
}).then(role => {
return member.roles.add(role);
}).catch((err) => {
// handle errors
});
Upvotes: 2