簡體   English   中英

如何獲取在 Discord.js 中發送消息的用戶的角色?

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

我對這個有點陌生,但我有這個

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);

但是當它 console.logs 它時,我得到undefined 如何獲取剛剛發送消息的用戶的角色。 我在網上查看了所有示例,感覺它們在使用.get方法的舊 API 上。

您無需參考在線示例。 只需閱讀文檔- 開發人員花了很多精力編寫它來有效地回答這些確切的問題。

您正在尋找“剛剛發送消息的用戶的角色”。 您可以通過msg.authormsg.member屬性獲取剛剛發送消息的用戶。 不知道更好,你可以簡單地檢查這兩個屬性的文檔,看看你能從它們中得到什么。 在這種情況下,您需要用戶的公會特定數據,因此您需要他們的GuildMember對象用於該公會 - 即msg.member

查看GuildMember文檔,您可以觀察到您可以訪問的所有屬性。 那里有一個roles屬性,它是GuildMemberRoleManager類型。 該類型具有.cache屬性,其中包含您的緩存角色集合。

把它們放在一起你會得到這個: msg.member.roles.cache 這是一個集合,因此您可以通過集合( 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