以下是用 Discord.js 编写的 Discord 机器人的代码片段:
client.channels.fetch('channelID here').then(function (channel) {
channel.messages.fetch('messageID here').then(function (message) {
console.log(message.reactions.cache.get('EmojiID here').users);
});
});
控制台输出如下:
ReactionUserManager {
cacheType: [class Collection extends Collection],
cache: Collection [Map] {},
reaction: MessageReaction {
message: Message {
channel: [TextChannel],
deleted: false,
id: 'MessageID here',
type: 'DEFAULT',
system: false,
content: 'What role do you want?\n' +
'React with:\n' +
'<:Red:870224025811558450> for <@&870162738561814578> \n' +
'<:Blue:870224213976444959> for <@&870162842983206922> \n' +
'<:Yellow:870224106061172776> for <@&870162885412810773>\n' +
'You will be assigned the role corresponding to your most recent reaction.\n' +
'Unreact to remove the role.',
author: [User],
pinned: false,
tts: false,
nonce: null,
embeds: [],
attachments: Collection [Map] {},
createdTimestamp: 1627548937713,
editedTimestamp: 1627617831107,
reactions: [ReactionManager],
mentions: [MessageMentions],
webhookID: null,
application: null,
activity: null,
_edits: [],
flags: [MessageFlags],
reference: null
},
me: true,
users: [Circular],
_emoji: ReactionEmoji {
animated: undefined,
name: 'Red',
id: 'EmojiID here',
deleted: false,
reaction: [Circular]
},
count: 2
}
}
我可以在输出中看到 count: 2
。我想获取这两个用户的对象列表。如何实现这一目标?
答案 0 :(得分:2)
你们离得很近。 ReactionUserManager
是经理;这意味着它有一个 cache
属性,该属性返回 User
个对象的 collection。
您也可以获取用户:
client.channels.fetch('channelID').then(function (channel) {
channel.messages.fetch('messageID').then(function (message) {
const reaction = message.reactions.cache.get('EmojiID')
reaction.users.fetch().then(function (users) {
console.log(users)
})
})
})
如果您可以使用 async-await(即您在 async 函数中),您可以使其更具可读性:
const channel = await client.channels.fetch('channelID')
const message = await channel.messages.fetch('messageID')
const reaction = message.reactions.cache.get('EmojiID')
const users = await reaction.users.fetch()
console.log(users)
// e.g. add a role to each user
users.each(async (user) => {
// get the member object as users don't have roles
const member = await message.guild.members.fetch(user.id)
member.roles.add('ROLE ID')
})