简体   繁体   English

如何获取在 Discord.js 中发送消息的用户的角色?

[英]How to get the roles of user who messaged in Discord.js?

I'm kind of new to this, but I have this我对这个有点陌生,但我有这个

const Discord = require('discord.js');
const auth = require("./auth.json");
const client = new Discord.Client();

client.on('ready', () => {
    console.log(`Logged in as ${client.user.tag}!`);
});

client.on('message', msg => {
    console.log(msg.guild.roles.get);
    if (msg.content === 'ping') {
        msg.reply('Pong!');
    }
});

client.login(auth.token);

But when it console.logs it, I get undefined .但是当它 console.logs 它时,我得到undefined How can I get the roles of the user who just messaged.如何获取刚刚发送消息的用户的角色。 I looked at all the examples online and it feels like they are on an older API where the .get method works.我在网上查看了所有示例,感觉它们在使用.get方法的旧 API 上。

You don't need to refer to examples online.您无需参考在线示例。 Just read the documentation - the developers spent lots of effort writing it to answer these exact questions efficiently.只需阅读文档- 开发人员花了很多精力编写它来有效地回答这些确切的问题。

You're looking for "the roles of the user who just messaged".您正在寻找“刚刚发送消息的用户的角色”。 You can get the user who just messaged by the msg.author or msg.member properties.您可以通过msg.authormsg.member属性获取刚刚发送消息的用户。 Not knowing any better, you could simply check the docs on both of these properties to see what you can get out of them.不知道更好,你可以简单地检查这两个属性的文档,看看你能从它们中得到什么。 In this case, you want a user's guild-specific data, so you want their GuildMember object for this guild - that's msg.member .在这种情况下,您需要用户的公会特定数据,因此您需要他们的GuildMember对象用于该公会 - 即msg.member

Looking at the docs for GuildMember you can observe all the properties you can access. 查看GuildMember文档,您可以观察到您可以访问的所有属性。 There is a roles property right there, which is of type GuildMemberRoleManager .那里有一个roles属性,它是GuildMemberRoleManager类型。 That type has a .cache property which contains your Collection of cached roles.该类型具有.cache属性,其中包含您的缓存角色集合。

Putting it all together you get this: msg.member.roles.cache .把它们放在一起你会得到这个: msg.member.roles.cache This is a collection so you can iterate over it any way supported by collections ( for..of , .forEach() , etc).这是一个集合,因此您可以通过集合( for..of.forEach()等)支持的任何方式对其进行迭代。

const Discord = require('discord.js');
const auth = require("./auth.json");
const client = new Discord.Client();

client.on('ready', () => {
    console.log(`Logged in as ${client.user.tag}!`);
});

client.on('message', msg => {
    for(var role of msg.member.roles.cache) {
        console.log("id:", role[0], "name:", role[1].name);
    }
    if (msg.content === 'ping') {
        msg.reply('Pong!');
    }
});

client.login(auth.token);

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

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