简体   繁体   English

如何向用户添加角色,而无需他先发送任何消息?

[英]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.如果这些不起作用,请发表评论,并告诉我您遇到了什么错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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