填充未填充的react.users

时间:2019-06-06 15:38:45

标签: node.js discord.js

messageReactionAdd事件中,参数之一是MessageReaction。从该反应中,我进行message.reaction以查找该反应来自的消息。我想使用该消息查找参数user对该消息作出反应的所有反应。

但是,一个障碍是,当机器人重新启动时,似乎message.reactions尚未完全填充,因此需要提取数据。我需要一个循环反应的用户,但我在这一方面很挣扎。

我尝试过:

await message.reactions.reduce((p, c) => c.fetchUsers(), 0);
// I had thought this would of cached the users of every reaction on the message, but that did not work.
// next

message.reactions.forEach((x, y) => {
  x.fetchUsers();
});
// this was also the same train of thought, but still to no avail.

我的意思是用户不在message.reaction.users对象中,我的意思是:

// the bot restarts - and a reaction is added
console.log(reaction.users);
// outputs: Collection [Map] {}
// this is supposed to be populated with many users, but it's empty
// however, if I add ANY reaction again, not doing anything else
// it outputs a Collection with many users in it, which is expected

我不知道该怎么做。

编辑:相关代码

// raw.js (the raw event)
const events = {
  MESSAGE_REACTION_ADD: 'messageReactionAdd',
};
const Discord = require('discord.js');

module.exports = async (client, event) => {
  if (!events.hasOwnProperty(event.t)) return;
  const { d: data } = event;
  const user = client.users.get(data.user_id);
  if (!user) return;
  const channel = client.channels.get(data.channel_id);
  if (!channel) return;

  if (channel.messages.has(data.message_id)) return;
  const message = await channel.fetchMessage(data.message_id);
  const emojiKey = (data.emoji.id) ? `${data.emoji.name}:${data.emoji.id}` : data.emoji.name;

  let reaction = message.reactions.get(emojiKey);
  if (!reaction) {
    const emoji = new Discord.Emoji(client.guilds.get(data.guild_id), data.emoji);
    reaction = new Discord.MessageReaction(message, emoji, 1, data.user_id === client.user.id);
  }

  client.emit(events[event.t], reaction, user);
};

// messageReactionAdd.js (the messageReactionAdd event)
module.exports = async (client, reaction, user) => {
  const message = reaction.message;
  if (!message)
    return;
  //await message.reactions.reduce((p, c) => c.fetchUsers(), 0);
  message.reactions.forEach((x,y) => {
    x.fetchUsers();
  });
  reactions = await message.reactions.filter(r => r.users.has(`${user.id}`));
  console.log(reactions);
};

1 个答案:

答案 0 :(得分:0)

此代码为我解决了此问题。

// raw.js event file
  await reaction.message.reactions.forEach(r => {
    r.fetchUsers({before: `${reaction.message.author.id}`});
  });
  // emit the messageReactionAdd event

// messageReactionAdd.js event file
  // the message.reactions.users should be populated, which I can use
  reactions = await reaction.message.reactions.filter(r => r.users.has(`${reaction.message.author.id}`));

我在错误的事件中使用了此代码,这在逻辑上是没有道理的,从而导致我认为无效的结果。