Search code examples
javascriptnode.jsdiscorddiscord.js

Mention users with specific role in bot status


Sooo, hello to everyone who sees this, it's my first time posting anything on StackOverflow. Anyway, recently I started learning discord.js and I managed to create a small bot in v12 with automatically changing status. Here is the code:

setInterval(() => {
    const statuses = [
      `user 1`,
      `user 2`,
      `user 3...`
    ]

    const status = statuses[Math.floor(Math.random() * statuses.length)]
    client.user.setActivity(status, { type: "WATCHING" })
  }, 5000)

The point is to have certain members usernames appear in bot status and this is really nice if the server has like just a few of these "special" members but now my server became larger and I would like for bot to target ONE specific role and list all the members with that "special" role :) Please help me, thank you in advance

So after Elitezen tried to help me I did this:

I added async in client on ready:

client.on("ready", async () => {
  const guild = client.guilds.cache.get("SERVER_ID");

I added your code:

const role = guild.roles.cache.get('SERVER_ID');

  await guild.members.fetch();

setInterval(() => {
    const statuses = Array
       .from(role.members.cache.values())
       .map(member => member.displayName);

    const status = statuses[Math.floor(Math.random() * statuses.length)]
    client.user.setActivity(status, { type: "WATCHING" })
  }, 5000)

And now Im stuck with this error: TypeError: Cannot read property 'values' of undefined


Solution

  • An example to target your desired role using RoleManager#get() or RoleManager#find()

    const role = <Guild>.roles.cache.find(r => r.name == 'role name');
    // Or
    const role = <Guild>.roles.cache.get('role id');
    

    To get all the members that hold this role fetch all members of the guild first, then construct an array from the Collection's values.

    Then map the array of members to their display name (or user's username)

    Ensure you have the guild member's intent enabled if you want to fetch all members.

    await <Guild>.members.fetch();
    
    setInterval(() => {
        const statuses = Array
           .from(role.members.values());
           .map(member => member.displayName);
    
        const status = statuses[Math.floor(Math.random() * statuses.length)]
        client.user.setActivity(status, { type: "WATCHING" })
      }, 5000)