简体   繁体   中英

How can I add a role to user, without him sending any message first?

I've searched for answers but only found how to assign a server role to someone who either sent some message or called a command.

How can I find a specific user on a server and assign a role to them without them sending any messages or doing anything at all?

I tried some things that didn't work:

// the server bot is in
const server = client.guilds.cache.get("my server id here");

// trying to find specific user on the server
let myusr = server.members.cache.get("id", "user id here"); 

Any suggestions/solutions?

EDIT: Here's the code I have so far:

const { Client } = require('discord.js');
const client = new Client();

client.on('ready', () => {
    console.log(client.user.tag);
    
    // grabbing the server
    const guild = client.guilds.cache.get("my server's id");

    // calling a function and passing my server to it
    setUsrRole(guild);
});

function setUsrRole(server) {

  // grabbing my user
  let myusr = server.members.fetch("My user id");
  
  // finding my role by name
  let myRole = server.roles.cache.find(myRole => myRole.name === "role name");
  
  // trying to add the role to my user
  myusr.roles.add(myRole);

  // I also tried myusr.addRole(myRole);
};

// Bot login
client.login('my bot token');

There are multiple ways, but I will show you 2 ways.

client.on('guildMemberAdd', member => {
member.roles.add('someRole');
})

That way is if you want to add on member join, but you need to make sure in your discord developer portal, when you invite your bot, the "Server Members Intent" box in the "bot" section is checked. Another way, which might be based on a different event is here:

await client.guilds.fetch(); //cache guilds
const guild = client.guilds.cache.get('someGuild');
await guild.members.fetch(); //should cache users automatically
const member = guild.members.cache.get('someMember');
member.roles.add('someRole');
//MAKE SURE ITS ASYNC

If these don't work, please comment, and tell me what error you get.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM