How do I get users.cache from all of the shards and put them into a collection just like the collection client.user.cache returns?

Viewed 338

I had a discord bot which used:

client.users.cache

This returns a Collection[Map] with all the users cached by the bot. I added sharding and I want to do the same so I replaced it with:

client.shard.fetchClientValues('users.cache');

but this returns a array and I need a Collection[Map] that is the same as the one returned from:

client.users.cache

Does anyone know how to convert that array in a Collection[Map] the same as the one returned from:

client.users.cache

or how to get a Collection[Map] from all the shards that looks the same as the one returned from:

client.users.cache
1 Answers

I think you could create a new Collection, iterate over the array, and insert/set new elements by using the set() method. Just make sure the key is the user ID, and the data is the user object:

let results = await client.shard.fetchClientValues('users.cache');
let collection = new Discord.Collection();

results.forEach((users) => {
  users.forEach((user) => {
    collection.set(user.id, new Discord.User(client, user));
  });
});

console.log(collection);

Collection is pretty similar to Map, so there is a chance that it's also can be constructed with an iterable of two-element arrays where the first element is the key and the second is the value:

let results = await client.shard.fetchClientValues('users.cache');
let collection = new Discord.Collection();

results.forEach((users) => {
  let userCollection = new Discord.Collection(users.map((user) => [user.id, new Discord.User(client, user)]));
  collection = collection.concat(userCollection);
});

console.log(collection);
Related