mirror of
https://github.com/danbulant/discord.js
synced 2026-07-13 07:00:44 +00:00
* internal sharding * ready event * the square deal * the new deal * the second new deal * add actual documentation * the new freedom * the great society * federal intervention * some of requested changes * i ran out of things to call these * destroy this * fix: Client#uptime went missing * fix(Client): destroy the client on login failure This may happen duo invalid sharding config / invalid token / user requested destroy * fix(Client): reject login promise when the client is destroyed before ready * fix(WebSocketManager): remove redundancy in destroy method (#2491) * typo(ErrorMessages): duo -> duo to * typo(ErrorMessages): duo -> due * fix: docs and options * docs(WebSocketManager): WebSockethard -> WebSocketShard (#2502) * fix(ClientUser): lazily load to account for extended user structure (#2501) * docs(WebSocketShard): document class to make it visible in documentation (#2504) * fix: WebSocketShard#reconnect * fix: presenceUpdate & userUpdate * presenceUpdate wasn't really being handled at all * userUpdate handled incorrectly because as of v7 in the Discord API, it comes inside presenceUpdate * re-add raw event * member is now part of message create payload * feat: Add functionality to support multiple servers with different shards (#2395) * Added functionallity to spawn multiple sharding managers due to adding start and end shards * Small fixes and limiting shard amount to max recommended * Forgot a check in spawn() * Fixed indentation * Removed optiosn object documentation for totalShards * More fixes and a check that the startShard + amount doesnt go over the recommended shard amount * fix getting max recommended * Removed async from constructor (my fault) * Changed start and end shard to a shardList or "auto" + fixed some brainfarts with isNaN * Changed the loop and totalShard count calculation * shards are actually 0 based * Fixed a problem with the gateway and handled some range errors and type errors * Changed Number.isNan to isNaN and changed a few Integer checks to use Number.isInteger * Added check if shardList contains smth greater than totalShards; made spawn use totalShards again; shardList will be ignored and rebuild if totalShards is 'auto'; fixed docs * ShardingManager#spawn now uses a for..of loop; fixed the if statement inside the new for..of loop to still work as intended; made the totalShards be set to a new amount if smth manual is put into ShardingManager#spawn just like before; Fixed some spelling * internal sharding * ready event * the square deal * the new deal * the second new deal * add actual documentation * the new freedom * the great society * federal intervention * some of requested changes * i ran out of things to call these * destroy this * fix: Client#uptime went missing * fix(Client): destroy the client on login failure This may happen duo invalid sharding config / invalid token / user requested destroy * fix(Client): reject login promise when the client is destroyed before ready * fix(WebSocketManager): remove redundancy in destroy method (#2491) * typo(ErrorMessages): duo -> duo to * typo(ErrorMessages): duo -> due * fix: docs and options * docs(WebSocketManager): WebSockethard -> WebSocketShard (#2502) * fix(ClientUser): lazily load to account for extended user structure (#2501) * docs(WebSocketShard): document class to make it visible in documentation (#2504) * fix: WebSocketShard#reconnect * fix: presenceUpdate & userUpdate * presenceUpdate wasn't really being handled at all * userUpdate handled incorrectly because as of v7 in the Discord API, it comes inside presenceUpdate * Internal Sharding adaptation Adapted to internal sharding Fixed a bug where non ready invalidated sessions wouldnt respawn * Fixed shardCount not retrieving * Fixing style removed unnecessary parenthesis * Fixing and rebasing lets hope i didnt dun hecklered it * Fixing my own retardation * Thanks git rebase * fix: assigning member in message create payload * fix: resumes * fix: IS wont give up reconnecting now * docs: add missing docs mostly * fix: found lost methods * fix: WebSocketManager#broadcast check if shard exists * fix: ShardClientUtil#id returning undefined * feat: handle new session rate limits (#2796) * feat: handle new session rate limits * i have no idea what i was doing last night * fix if statement weirdness * fix: re-add presence parsing from ClientOptions (#2893) * resolve conflicts * typings: missing typings * re-add missing linter rule * fix: replacing ClientUser wrongly * address unecessary performance waste * docs: missing disconnect event * fix(typings): Fix 2 issues with typings (#2909) * (Typings) Update typings to reflect current ClientOptions * fix(Typings) fixes a bug with Websockets and DOM Types * fix travis * feat: allow setting presence per shard * add WebSocketManager#shardX events * adjust typings, docs and performance issues * readjust shard events, now provide shardId parameter instead * fix: ready event should check shardCount, not actualShardCount * fix: re-add replayed parameter of Client#resume * fix(Sharding): fixes several things in Internal Sharding (#2914) * fix(Sharding) fixes several things in Internal Sharding * add default value for shards property * better implement checking for shards array * fix travis & some casing * split shard count into 2 words * update to latest Internal Sharding, fix requested changes * make sure totalShardCount is a number * fix comment * fix small typo * dynamically set totalShardCount if either shards or shardCount is provided * consistency: rename shardID to shardId * remove Client#shardIds * fix: typo in GuildIntegrationsUpdate handler * fix: incorrect packet data being passed in some events (#2919) * fix: edgecase of ShardingManager and totalShardCount (#2918) * fix: Client#userUpdate being passed wrong parameter and fix a potential edgecase of returning null in ClientUser#edit from this event * fix consistency and typings issues * consistency: shardId instances renamed to shardID * typings: fix typings regarding WebSocket * style(.eslintrc): remove additional whitespace * fix(Client): remove ondisconnect handler on timeout * docs(BaseClient): fix typo of Immediate * nitpick: typings, private fields and methods * typo: improve grammar a bit * fix: error assigning client in WebSocketManager * typo: actually spell milliseconds properly
222 lines
8.1 KiB
JavaScript
222 lines
8.1 KiB
JavaScript
const DataStore = require('./DataStore');
|
|
const GuildMember = require('../structures/GuildMember');
|
|
const { Events, OPCodes } = require('../util/Constants');
|
|
const Collection = require('../util/Collection');
|
|
const { Error, TypeError } = require('../errors');
|
|
|
|
/**
|
|
* Stores guild members.
|
|
* @extends {DataStore}
|
|
*/
|
|
class GuildMemberStore extends DataStore {
|
|
constructor(guild, iterable) {
|
|
super(guild.client, iterable, GuildMember);
|
|
this.guild = guild;
|
|
}
|
|
|
|
add(data, cache = true) {
|
|
return super.add(data, cache, { id: data.user.id, extras: [this.guild] });
|
|
}
|
|
|
|
/**
|
|
* Data that resolves to give a GuildMember object. This can be:
|
|
* * A GuildMember object
|
|
* * A User resolvable
|
|
* @typedef {GuildMember|UserResolvable} GuildMemberResolvable
|
|
*/
|
|
|
|
/**
|
|
* Resolves a GuildMemberResolvable to a GuildMember object.
|
|
* @param {GuildMemberResolvable} member The user that is part of the guild
|
|
* @returns {?GuildMember}
|
|
*/
|
|
resolve(member) {
|
|
const memberResolvable = super.resolve(member);
|
|
if (memberResolvable) return memberResolvable;
|
|
const userResolvable = this.client.users.resolveID(member);
|
|
if (userResolvable) return super.resolve(userResolvable);
|
|
return null;
|
|
}
|
|
|
|
/**
|
|
* Resolves a GuildMemberResolvable to an member ID string.
|
|
* @param {GuildMemberResolvable} member The user that is part of the guild
|
|
* @returns {?Snowflake}
|
|
*/
|
|
resolveID(member) {
|
|
const memberResolvable = super.resolveID(member);
|
|
if (memberResolvable) return memberResolvable;
|
|
const userResolvable = this.client.users.resolveID(member);
|
|
return this.has(userResolvable) ? userResolvable : null;
|
|
}
|
|
|
|
/**
|
|
* Options used to fetch a single member from a guild.
|
|
* @typedef {Object} FetchMemberOptions
|
|
* @property {UserResolvable} user The user to fetch
|
|
* @property {boolean} [cache=true] Whether or not to cache the fetched member
|
|
*/
|
|
|
|
/**
|
|
* Options used to fetch multiple members from a guild.
|
|
* @typedef {Object} FetchMembersOptions
|
|
* @property {string} [query=''] Limit fetch to members with similar usernames
|
|
* @property {number} [limit=0] Maximum number of members to request
|
|
*/
|
|
|
|
/**
|
|
* Fetches member(s) from Discord, even if they're offline.
|
|
* @param {UserResolvable|FetchMemberOptions|FetchMembersOptions} [options] If a UserResolvable, the user to fetch.
|
|
* If undefined, fetches all members.
|
|
* If a query, it limits the results to users with similar usernames.
|
|
* @returns {Promise<GuildMember>|Promise<Collection<Snowflake, GuildMember>>}
|
|
* @example
|
|
* // Fetch all members from a guild
|
|
* guild.members.fetch()
|
|
* .then(console.log)
|
|
* .catch(console.error);
|
|
* @example
|
|
* // Fetch a single member
|
|
* guild.members.fetch('66564597481480192')
|
|
* .then(console.log)
|
|
* .catch(console.error);
|
|
* @example
|
|
* // Fetch a single member without caching
|
|
* guild.members.fetch({ user, cache: false })
|
|
* .then(console.log)
|
|
* .catch(console.error);
|
|
* @example
|
|
* // Fetch by query
|
|
* guild.members.fetch({ query: 'hydra', limit: 1 })
|
|
* .then(console.log)
|
|
* .catch(console.error);
|
|
*/
|
|
fetch(options) {
|
|
if (!options) return this._fetchMany();
|
|
const user = this.client.users.resolveID(options);
|
|
if (user) return this._fetchSingle({ user, cache: true });
|
|
if (options.user) {
|
|
options.user = this.client.users.resolveID(options.user);
|
|
if (options.user) return this._fetchSingle(options);
|
|
}
|
|
return this._fetchMany(options);
|
|
}
|
|
|
|
/**
|
|
* Prunes members from the guild based on how long they have been inactive.
|
|
* @param {Object} [options] Prune options
|
|
* @param {number} [options.days=7] Number of days of inactivity required to kick
|
|
* @param {boolean} [options.dry=false] Get number of users that will be kicked, without actually kicking them
|
|
* @param {string} [options.reason] Reason for this prune
|
|
* @returns {Promise<number>} The number of members that were/will be kicked
|
|
* @example
|
|
* // See how many members will be pruned
|
|
* guild.members.prune({ dry: true })
|
|
* .then(pruned => console.log(`This will prune ${pruned} people!`))
|
|
* .catch(console.error);
|
|
* @example
|
|
* // Actually prune the members
|
|
* guild.members.prune({ days: 1, reason: 'too many people!' })
|
|
* .then(pruned => console.log(`I just pruned ${pruned} people!`))
|
|
* .catch(console.error);
|
|
*/
|
|
prune({ days = 7, dry = false, reason } = {}) {
|
|
if (typeof days !== 'number') throw new TypeError('PRUNE_DAYS_TYPE');
|
|
return this.client.api.guilds(this.guild.id).prune[dry ? 'get' : 'post']({ query: { days }, reason })
|
|
.then(data => data.pruned);
|
|
}
|
|
|
|
/**
|
|
* Bans a user from the guild.
|
|
* @param {UserResolvable} user The user to ban
|
|
* @param {Object} [options] Options for the ban
|
|
* @param {number} [options.days=0] Number of days of messages to delete
|
|
* @param {string} [options.reason] Reason for banning
|
|
* @returns {Promise<GuildMember|User|Snowflake>} Result object will be resolved as specifically as possible.
|
|
* If the GuildMember cannot be resolved, the User will instead be attempted to be resolved. If that also cannot
|
|
* be resolved, the user ID will be the result.
|
|
* @example
|
|
* // Ban a user by ID (or with a user/guild member object)
|
|
* guild.members.ban('84484653687267328')
|
|
* .then(user => console.log(`Banned ${user.username || user.id || user} from ${guild.name}`))
|
|
* .catch(console.error);
|
|
*/
|
|
ban(user, options = { days: 0 }) {
|
|
if (options.days) options['delete-message-days'] = options.days;
|
|
const id = this.client.users.resolveID(user);
|
|
if (!id) return Promise.reject(new Error('BAN_RESOLVE_ID', true));
|
|
return this.client.api.guilds(this.guild.id).bans[id].put({ query: options })
|
|
.then(() => {
|
|
if (user instanceof GuildMember) return user;
|
|
const _user = this.client.users.resolve(id);
|
|
if (_user) {
|
|
const member = this.resolve(_user);
|
|
return member || _user;
|
|
}
|
|
return id;
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Unbans a user from the guild.
|
|
* @param {UserResolvable} user The user to unban
|
|
* @param {string} [reason] Reason for unbanning user
|
|
* @returns {Promise<User>}
|
|
* @example
|
|
* // Unban a user by ID (or with a user/guild member object)
|
|
* guild.members.unban('84484653687267328')
|
|
* .then(user => console.log(`Unbanned ${user.username} from ${guild.name}`))
|
|
* .catch(console.error);
|
|
*/
|
|
unban(user, reason) {
|
|
const id = this.client.users.resolveID(user);
|
|
if (!id) throw new Error('BAN_RESOLVE_ID');
|
|
return this.client.api.guilds(this.guild.id).bans[id].delete({ reason })
|
|
.then(() => this.client.users.resolve(user));
|
|
}
|
|
|
|
|
|
_fetchSingle({ user, cache }) {
|
|
const existing = this.get(user);
|
|
if (existing && existing.joinedTimestamp) return Promise.resolve(existing);
|
|
return this.client.api.guilds(this.guild.id).members(user).get()
|
|
.then(data => this.add(data, cache));
|
|
}
|
|
|
|
_fetchMany({ query = '', limit = 0 } = {}) {
|
|
return new Promise((resolve, reject) => {
|
|
if (this.guild.memberCount === this.size) {
|
|
resolve(query || limit ? new Collection() : this);
|
|
return;
|
|
}
|
|
this.guild.shard.send({
|
|
op: OPCodes.REQUEST_GUILD_MEMBERS,
|
|
d: {
|
|
guild_id: this.guild.id,
|
|
query,
|
|
limit,
|
|
},
|
|
});
|
|
const fetchedMembers = new Collection();
|
|
const handler = (members, guild) => {
|
|
if (guild.id !== this.guild.id) return;
|
|
for (const member of members.values()) {
|
|
if (query || limit) fetchedMembers.set(member.id, member);
|
|
}
|
|
if (this.guild.memberCount <= this.size ||
|
|
((query || limit) && members.size < 1000) ||
|
|
(limit && fetchedMembers.size >= limit)) {
|
|
this.guild.client.removeListener(Events.GUILD_MEMBERS_CHUNK, handler);
|
|
resolve(query || limit ? fetchedMembers : this);
|
|
}
|
|
};
|
|
this.guild.client.on(Events.GUILD_MEMBERS_CHUNK, handler);
|
|
this.guild.client.setTimeout(() => {
|
|
this.guild.client.removeListener(Events.GUILD_MEMBERS_CHUNK, handler);
|
|
reject(new Error('GUILD_MEMBERS_TIMEOUT'));
|
|
}, 120e3);
|
|
});
|
|
}
|
|
}
|
|
|
|
module.exports = GuildMemberStore;
|