Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

180
Vistas
Add/Remove user role given username (Discord.js)

I am trying to create a function for adding and removing a role from a user given the username (not user ID).

So far I have code that works with user ID. My question is how can I modify this code to work given the username?

const addDiscord = async (discord_username) => {
    const guild = client.guilds.cache.get('<guild-id>');   // copy the id of the server your bot is in and paste it in place of guild-ID.
    const role = guild.roles.cache.get('<role-id>');  // here we are getting the role object using the id of that role.
    const member = await guild.members.fetch('user-id'); // here we are getting the member object using the id of that member. This is the member we will add the role to.
    await member.roles.add(role);   // here we just added the role to the member we got.
}

Here is my function that will handle checking for new user to add/remove

const checkNew = async () => {
    if(toUpdate.length > 0) { // Check if there are any new users to update
        toUpdate.forEach(element => {
            addDiscord(element.new)
            // Remove element.old from Discord role
            // Add element.new to Discord role
        })
        toUpdate = []
    }
}

And here I am connecting to bot and calling the checkNew() function every 10 seconds

client.once('ready', () => {
    console.log('Ready!');

    setInterval(checkNew, 10000)
});

Update: I tried using client.users.cache.find() but it returns undefined

const addDiscord = async (discord_username) => {
    const guild = client.guilds.cache.get('<guild-id>');   // copy the id of the server your bot is in and paste it in place of guild-ID.
    const role = guild.roles.cache.get('<role-id>');  // here we are getting the role object using the id of that role.
    console.log(discord_username)
    const id = client.users.cache.find(u => u.tag === discord_username)
    console.log(id)
}

Update 2: Attempted to implement the code from Miqhtie's answer

const addDiscord = async (discord_username) => {
    const guild = client.guilds.cache.get('<server-id>');   // copy the id of the server your bot is in and paste it in place of guild-ID.
    const role = guild.roles.cache.get('<role-id>');  // here we are getting the role object using the id of that role.
    const members = await guild.members.fetch()
    const member = members.find((m) => m.username === '<discord-username>')
    console.log(member)
}

Error:

const member = members.find((m) => m.username === '<discord-username>')
                           ^
TypeError: members.find is not a function
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

There is no specific method to fetch a GuildMember by username so what you would have to do is fetch all the members from a guild <guild>.members.fetch() and then filter it for a member whos username property is equal to the username you want.

An example implementation of this would be

const username = "Super Cool Username";
const members = await guild.members.fetch();
const member = members.find((m) => m.username === username);
member.roles.cache.add(role);
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda