Search code examples
javascriptdiscord.jsroles

Discord.js create a role and get its id immediatly after


I want my bot to check every guild that it is in and create some roles when it sees that a guild doesn't have them.

My code looks like this:

let newRoles = {
  'guildId': '',
  'rank1': '', // the role id
  'rank2': ''
}

client.guilds.forEach(guild => {
  checkHasRoles(guild.id) // returns a Boolean
  if (hasRoles === false) {
    newRoles.guildId = guild.id
    guild.roles.create({
      data: {
        name: 'rank1',
        color: '992d22'
      }
    })
    role = guild.roles.cache.find(role => role.name === 'rank1')
    newRoles['rank1'] = role.id
    // The same for the other roles
    rolesArray.push(newRoles)
    save(rolesArray, file)
    rolesArray = load(file)
  } 
})

The error I get is: (node:11833) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'id' of undefined. I guess that there is a problem with calling the create() and find() function together but I can't think of a way to do this differently.

I'd be grateful if you could give me a detailed explaination. I'm new to this.


Solution

  • You have to use a promise for this instead of trying to find a new role because this will not work.

      message.guild.roles.create({
          data: {
            name: 'rank1',
            color: '992d22'
          }
        }).then(role => {
           let roleId = role.id;
      });